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
package com.freezingwind.animereleasenotifier.updater; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.freezingwind.animereleasenotifier.data.Anime; import com.freezingwind.animereleasenotifier.helpers.NetworkManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class AnimeUpdater { protected ArrayList<Anime> animeList; protected boolean completedOnly; public AnimeUpdater(boolean fetchCompletedOnly) { animeList = new ArrayList<Anime>(); completedOnly = fetchCompletedOnly; } // GetAnimeList public ArrayList<Anime> getAnimeList() { return animeList; } public void update(String response, final Context context, final AnimeListUpdateCallBack callBack) { try { JSONObject responseObject = new JSONObject(response); update(responseObject, context, callBack); } catch(JSONException e) { Log.d("AnimeUpdater", e.toString()); } } public void update(JSONObject response, final Context context, final AnimeListUpdateCallBack callBack) { try { animeList.clear(); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = sharedPrefs.edit(); JSONArray watchingList = response.getJSONArray("watching"); for (int i = 0; i < watchingList.length(); i++) { JSONObject animeJSON = watchingList.getJSONObject(i); JSONObject episodes = animeJSON.getJSONObject("episodes"); JSONObject airingDate = animeJSON.getJSONObject("airingDate"); JSONObject animeProvider = null; try { animeProvider = animeJSON.getJSONObject("animeProvider"); } catch(JSONException e) { //Log.d("AnimeUpdater", "No anime provider available"); } Anime anime = new Anime( animeJSON.getString("title"), animeJSON.getString("image"), animeJSON.getString("url"), animeProvider != null ? animeProvider.getString("url") : "", animeProvider != null ? animeProvider.getString("nextEpisodeUrl") : "", animeProvider != null ? animeProvider.getString("videoUrl") : "", episodes.getInt("watched"), episodes.getInt("available"), episodes.getInt("max"), episodes.getInt("offset"), airingDate.getString("remainingString"), completedOnly ? "completed" : "watching" ); // Load cached episode count String key = anime.title + ":episodes-available"; int availableCached = sharedPrefs.getInt(key, -1); anime.notify = anime.available > availableCached && availableCached != -1; // Save data in preferences editor.putInt(anime.title + ":episodes-available", anime.available); // Add to list animeList.add(anime); } // Write preferences editor.apply(); } catch (JSONException e) { Log.d("AnimeUpdater", "Error parsing JSON: " + e.toString()); } finally { callBack.execute(); } } // Update public void updateByUser(String userName, final Context context, final AnimeListUpdateCallBack callBack) { String apiUrl = "https://animereleasenotifier.com/api/animelist/" + userName; if(completedOnly) apiUrl += "&completed=1"; final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); apiUrl += "&animeProvider=" + sharedPrefs.getString("animeProvider", "KissAnime"); //Toast.makeText(activity, "Loading anime list of " + userName, Toast.LENGTH_SHORT).show(); final JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, apiUrl, (String)null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { update(response, context, callBack); // Cache it SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("cachedAnimeListJSON" + (completedOnly ? "Completed" : ""), response.toString()); editor.apply(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { System.out.println("Error: " + error.toString()); } }); NetworkManager.getRequestQueue().add(jsObjRequest); } }
animenotifier/anime-release-notifier-android
app/src/main/java/com/freezingwind/animereleasenotifier/updater/AnimeUpdater.java
Java
gpl-2.0
4,366
sap.ui.define([ "sap/ui/core/UIComponent", "sap/ui/Device", "opensap/manageproducts/model/models", "opensap/manageproducts/controller/ErrorHandler" ], function (UIComponent, Device, models, ErrorHandler) { "use strict"; return UIComponent.extend("opensap.manageproducts.Component", { metadata : { manifest: "json" }, /** * The component is initialized by UI5 automatically during the startup of the app and calls the init method once. * In this function, the device models are set and the router is initialized. * @public * @override */ init : function () { // call the base component's init function UIComponent.prototype.init.apply(this, arguments); // initialize the error handler with the component this._oErrorHandler = new ErrorHandler(this); // set the device model this.setModel(models.createDeviceModel(), "device"); // create the views based on the url/hash this.getRouter().initialize(); }, /** * The component is destroyed by UI5 automatically. * In this method, the ErrorHandler is destroyed. * @public * @override */ destroy : function () { this._oErrorHandler.destroy(); // call the base component's destroy function UIComponent.prototype.destroy.apply(this, arguments); }, /** * This method can be called to determine whether the sapUiSizeCompact or sapUiSizeCozy * design mode class should be set, which influences the size appearance of some controls. * @public * @return {string} css class, either 'sapUiSizeCompact' or 'sapUiSizeCozy' - or an empty string if no css class should be set */ getContentDensityClass : function() { if (this._sContentDensityClass === undefined) { // check whether FLP has already set the content density class; do nothing in this case if (jQuery(document.body).hasClass("sapUiSizeCozy") || jQuery(document.body).hasClass("sapUiSizeCompact")) { this._sContentDensityClass = ""; } else if (!Device.support.touch) { // apply "compact" mode if touch is not supported this._sContentDensityClass = "sapUiSizeCompact"; } else { // "cozy" in case of touch support; default for most sap.m controls, but needed for desktop-first controls like sap.ui.table.Table this._sContentDensityClass = "sapUiSizeCozy"; } } return this._sContentDensityClass; } }); } );
carlitosalcala/openui
ManageProducts/webapp/Component.js
JavaScript
gpl-2.0
2,424
<div class="categoryMenu"> <ul> <?php foreach($root_categories as $key => $value) { if($key == 13) echo "<div class='hiddenCategories'>"; ?> <li<?php if($key == 0) { ?> class="first"<?php } ?>><a href="<?php echo zen_href_link('index', zen_get_path($value['id']));?>"><?php echo $value['text'] ?></a></li> <?php if($key == $catcount - 1) echo "</div>"; } ?> <li class="last"><a href="#">All Categories &gt;&gt;</a></li> </ul> </div> <div class="clear"></div>
joshyan/everymarket
includes/templates/everymarket_classic/common/tpl_left_categories.php
PHP
gpl-2.0
536
/* * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Common.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Battlefield.h" #include "BattlefieldMgr.h" #include "Opcodes.h" //This send to player windows for invite player to join the war //Param1:(BattleId) the BattleId of Bf //Param2:(ZoneId) the zone where the battle is (4197 for wg) //Param3:(time) Time in second that the player have for accept void WorldSession::SendBfInvitePlayerToWar(uint32 BattleId, uint32 ZoneId, uint32 p_time) { //Send packet WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTRY_INVITE, 16); data << uint32(0); data << uint32(ZoneId); data << uint64(BattleId | 0x20000); //Sending the packet to player SendPacket(&data); } //This send invitation to player to join the queue //Param1:(BattleId) the BattleId of Bf void WorldSession::SendBfInvitePlayerToQueue(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_INVITE, 5); data << uint8(0); data << uint8(1); // warmup data << uint32(0); data << uint32(0); data << uint32(0); data << uint32(0); data << uint32(0); data << uint64(BattleId); // BattleId //warmup ? used ? //Sending packet to player SendPacket(&data); } //This send packet for inform player that he join queue //Param1:(BattleId) the BattleId of Bf //Param2:(ZoneId) the zone where the battle is (4197 for wg) void WorldSession::SendBfQueueInviteResponce(uint32 BattleId, uint32 ZoneId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_REQUEST_RESPONSE, 11); data << uint8(0); // unk, Logging In??? data << uint64(BattleId); data << uint32(ZoneId); data << uint64(GetPlayer()->GetGUID()); data << uint8(1); // 1 = accepted, 0 = You cant join queue right now data << uint8(1); // 1 = queued for next battle, 0 = you are queued, please wait... SendPacket(&data); } //This is call when player accept to join war //Param1:(BattleId) the BattleId of Bf void WorldSession::SendBfEntered(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTERED, 7); data << uint32(BattleId); data << uint8(1); //unk data << uint8(1); //unk data << uint8(_player->isAFK()?1:0); //Clear AFK SendPacket(&data); } //Send when player is kick from Battlefield void WorldSession::SendBfLeaveMessage(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_EJECTED, 7); data << uint8(8); //byte Reason data << uint8(2); //byte BattleStatus data << uint64(BattleId); data << uint8(0); //bool Relocated SendPacket(&data); } //Send by client when he click on accept for queue void WorldSession::HandleBfQueueInviteResponse(WorldPacket & recv_data) { uint32 BattleId; uint8 Accepted; recv_data >> BattleId >> Accepted; sLog->outError("HandleQueueInviteResponse: BattleID:%u Accepted:%u", BattleId, Accepted); Battlefield* Bf = sBattlefieldMgr.GetBattlefieldByBattleId(BattleId); if (!Bf) return; if (Accepted) { Bf->PlayerAcceptInviteToQueue(_player); } } //Send by client on clicking in accept or refuse of invitation windows for join game void WorldSession::HandleBfEntryInviteResponse(WorldPacket & recv_data) { uint64 data; uint8 Accepted; recv_data >> Accepted >> data; uint64 BattleId = data &~ 0x20000; Battlefield* Bf= sBattlefieldMgr.GetBattlefieldByBattleId((uint32)BattleId); if(!Bf) return; //If player accept invitation if (Accepted) { Bf->PlayerAcceptInviteToWar(_player); } else { if (_player->GetZoneId() == Bf->GetZoneId()) Bf->KickPlayerFromBf(_player->GetGUID()); } } void WorldSession::HandleBfExitRequest(WorldPacket & recv_data) { uint32 BattleId; recv_data >> BattleId; sLog->outError("HandleBfExitRequest: BattleID:%u ", BattleId); Battlefield* Bf = sBattlefieldMgr.GetBattlefieldByBattleId(BattleId); if (!Bf) return; Bf->AskToLeaveQueue(_player); }
Macavity/SkyFireEMU
src/server/game/Handlers/BattlefieldHandler.cpp
C++
gpl-2.0
4,910
<?php /** * Admin functions for post types * * @author WooThemes * @category Admin * @package WooCommerce/Admin/Post Types * @version 2.1.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly if ( ! class_exists( 'WC_Admin_CPT' ) ) : /** * WC_Admin_CPT Class */ class WC_Admin_CPT { protected $type = ''; /** * Constructor */ public function __construct() { // Insert into X media browser add_filter( 'media_view_strings', array( $this, 'change_insert_into_post' ) ); } /** * Change label for insert buttons. * * @access public * @param mixed $translation * @param mixed $original * @return void */ function change_insert_into_post( $strings ) { global $post_type; if ( $post_type == $this->type ) { $obj = get_post_type_object( $this->type ); $strings['insertIntoPost'] = sprintf( __( 'Insert into %s', 'woocommerce' ), $obj->labels->singular_name ); $strings['uploadedToThisPost'] = sprintf( __( 'Uploaded to this %s', 'woocommerce' ), $obj->labels->singular_name ); } return $strings; } } endif;
Minasokoni/coasties
wp-content/plugins/woocommerce/includes/admin/post-types/class-wc-admin-cpt.php
PHP
gpl-2.0
1,091
<?php /** * Generates the normalizer data file for Malayalam. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file * @ingroup MaintenanceLanguage */ require_once __DIR__ . '/../Maintenance.php'; /** * Generates the normalizer data file for Malayalam. * For NFC see includes/compat/normal. * * @ingroup MaintenanceLanguage */ class GenerateNormalizerDataMl extends Maintenance { public function __construct() { parent::__construct(); $this->mDescription = 'Generate the normalizer data file for Malayalam'; } public function getDbType() { return Maintenance::DB_NONE; } public function execute() { $hexPairs = array( # From http://unicode.org/versions/Unicode5.1.0/#Malayalam_Chillu_Characters '0D23 0D4D 200D' => '0D7A', '0D28 0D4D 200D' => '0D7B', '0D30 0D4D 200D' => '0D7C', '0D32 0D4D 200D' => '0D7D', '0D33 0D4D 200D' => '0D7E', # From http://permalink.gmane.org/gmane.science.linguistics.wikipedia.technical/46413 '0D15 0D4D 200D' => '0D7F', ); $pairs = array(); foreach ( $hexPairs as $hexSource => $hexDest ) { $source = UtfNormal\Utils::hexSequenceToUtf8( $hexSource ); $dest = UtfNormal\Utils::hexSequenceToUtf8( $hexDest ); $pairs[$source] = $dest; } global $IP; file_put_contents( "$IP/serialized/normalize-ml.ser", serialize( $pairs ) ); echo "ml: " . count( $pairs ) . " pairs written.\n"; } } $maintClass = 'GenerateNormalizerDataMl'; require_once RUN_MAINTENANCE_IF_MAIN;
lcp0578/mediawiki
maintenance/language/generateNormalizerDataMl.php
PHP
gpl-2.0
2,183
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER * * Copyright (c) 2012-2013 Universidad Politécnica de Madrid * Copyright (c) 2012-2013 the Center for Open Middleware * * 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. */ /*global gettext, ngettext, interpolate, StyledElements, Wirecloud*/ (function () { "use strict"; /************************************************************************* * Private functions *************************************************************************/ var updateErrorInfo = function updateErrorInfo() { var label, errorCount = this.entity.logManager.getErrorCount(); this.log_button.setDisabled(errorCount === 0); label = ngettext("%(errorCount)s error", "%(errorCount)s errors", errorCount); label = interpolate(label, {errorCount: errorCount}, true); this.log_button.setTitle(label); }; /************************************************************************* * Constructor *************************************************************************/ /** * GenericInterface Class */ var GenericInterface = function GenericInterface(extending, wiringEditor, entity, title, manager, className, isGhost) { if (extending === true) { return; } var del_button, log_button, type, msg, ghostNotification; StyledElements.Container.call(this, {'class': className}, []); Object.defineProperty(this, 'entity', {value: entity}); this.editingPos = false; this.targetAnchorsByName = {}; this.sourceAnchorsByName = {}; this.targetAnchors = []; this.sourceAnchors = []; this.wiringEditor = wiringEditor; this.title = title; this.className = className; this.initPos = {'x': 0, 'y': 0}; this.draggableSources = []; this.draggableTargets = []; this.activatedTree = null; this.hollowConnections = {}; this.fullConnections = {}; this.subdataConnections = {}; this.isMinimized = false; this.minWidth = ''; this.movement = false; this.numberOfSources = 0; this.numberOfTargets = 0; this.potentialArrow = null; // Only for minimize maximize operators. this.initialPos = null; this.isGhost = isGhost; this.readOnlyEndpoints = 0; this.readOnly = false; if (manager instanceof Wirecloud.ui.WiringEditor.ArrowCreator) { this.isMiniInterface = false; this.arrowCreator = manager; } else { this.isMiniInterface = true; this.arrowCreator = null; } // Interface buttons, not for miniInterface if (!this.isMiniInterface) { if (className == 'iwidget') { type = 'widget'; this.version = this.entity.version; this.vendor = this.entity.vendor; this.name = this.entity.name; } else { type = 'operator'; this.version = this.entity.meta.version; this.vendor = this.entity.meta.vendor; this.name = this.entity.meta.name; } // header, sources and targets for the widget this.resourcesDiv = new StyledElements.BorderLayout({'class': "geContainer"}); this.sourceDiv = this.resourcesDiv.getEastContainer(); this.sourceDiv.addClassName("sources"); this.targetDiv = this.resourcesDiv.getWestContainer(); this.targetDiv.addClassName("targets"); this.header = this.resourcesDiv.getNorthContainer(); this.header.addClassName('header'); this.wrapperElement.appendChild(this.resourcesDiv.wrapperElement); // Ghost interface if (isGhost) { this.vendor = this.entity.name.split('/')[0]; this.name = this.entity.name.split('/')[1]; this.version = new Wirecloud.Version(this.entity.name.split('/')[2].trim()); this.wrapperElement.classList.add('ghost'); ghostNotification = document.createElement("span"); ghostNotification.classList.add('ghostNotification'); msg = gettext('Warning: %(type)s not found!'); msg = interpolate(msg, {type: type}, true); ghostNotification.textContent = msg; this.header.appendChild(ghostNotification); } // Version Status if (type == 'operator' && this.wiringEditor.operatorVersions[this.vendor + '/' + this.name] && this.wiringEditor.operatorVersions[this.vendor + '/' + this.name].lastVersion.compareTo(this.version) > 0) { // Old Entity Version this.versionStatus = document.createElement("span"); this.versionStatus.classList.add('status'); this.versionStatus.classList.add('icon-exclamation-sign'); this.versionStatus.setAttribute('title', 'Outdated Version (' + this.version.text + ')'); this.header.appendChild(this.versionStatus); this.wrapperElement.classList.add('old') } // Widget name this.nameElement = document.createElement("span"); this.nameElement.textContent = title; this.nameElement.title = title; this.header.appendChild(this.nameElement); // Close button del_button = new StyledElements.StyledButton({ 'title': gettext("Remove"), 'class': 'closebutton icon-remove', 'plain': true }); del_button.insertInto(this.header); del_button.addEventListener('click', function () { if (this.readOnly == true) { return; } if (className == 'iwidget') { this.wiringEditor.events.widgetremoved.dispatch(this); } else { this.wiringEditor.events.operatorremoved.dispatch(this); } }.bind(this)); // Log button this.log_button = new StyledElements.StyledButton({ 'plain': true, 'class': 'logbutton icon-warning-sign' }); if (!isGhost) { this.log_button.addEventListener("click", function () { var dialog = new Wirecloud.ui.LogWindowMenu(this.entity.logManager); dialog.show(); }.bind(this)); updateErrorInfo.call(this); this.entity.logManager.addEventListener('newentry', updateErrorInfo.bind(this)); } else { this.log_button.disable(); } this.log_button.insertInto(this.header); // special icon for minimized interface this.iconAux = document.createElement("div"); this.iconAux.classList.add("specialIcon"); this.iconAux.classList.add("icon-cogs"); this.iconAux.setAttribute('title', title); this.resourcesDiv.wrapperElement.appendChild(this.iconAux); this.iconAux.addEventListener('click', function () { if (!this.movement) { this.restore(); } }.bind(this)); // Add a menu button except on mini interfaces this.menu_button = new StyledElements.PopupButton({ 'title': gettext("Menu"), 'class': 'editPos_button icon-cog', 'plain': true }); this.menu_button.insertInto(this.header); this.menu_button.popup_menu.append(new Wirecloud.ui.WiringEditor.GenericInterfaceSettingsMenuItems(this)); } else { // MiniInterface this.header = document.createElement("div"); this.header.classList.add('header'); this.wrapperElement.appendChild(this.header); // MiniInterface name this.nameElement = document.createElement("span"); this.nameElement.textContent = title; this.header.appendChild(this.nameElement); // MiniInterface status this.miniStatus = document.createElement("span"); this.miniStatus.classList.add('status'); this.miniStatus.classList.add('icon-exclamation-sign'); this.miniStatus.setAttribute('title', gettext('Warning! this is an old version of the operator, click to change the version')); this._miniwidgetMenu_button_callback = function _miniwidgetMenu_button_callback(e) { // Context Menu e.stopPropagation(); if (this.contextmenu.isVisible()) { this.contextmenu.hide(); } else { this.contextmenu.show(this.wrapperElement.getBoundingClientRect()); } return; }.bind(this); this.miniStatus.addEventListener('mousedown', Wirecloud.Utils.stopPropagationListener, false); this.miniStatus.addEventListener('click', this._miniwidgetMenu_button_callback, false); this.miniStatus.addEventListener('contextmenu', this._miniwidgetMenu_button_callback, false); this.header.appendChild(this.miniStatus); // MiniInterface Context Menu if (className == 'ioperator') { this.contextmenu = new StyledElements.PopupMenu({'position': ['bottom-left', 'top-left']}); this._miniwidgetMenu_callback = function _miniwidgetMenu_callback(e) { // Context Menu e.stopPropagation(); if (e.button === 2) { if (this.contextmenu.isVisible()) { this.contextmenu.hide(); } else { this.contextmenu.show(this.wrapperElement.getBoundingClientRect()); } return; } }.bind(this); this.wrapperElement.addEventListener('mousedown', this._miniwidgetMenu_callback, false); this.contextmenu.append(new Wirecloud.ui.WiringEditor.MiniInterfaceSettingsMenuItems(this)); } this.wrapperElement.addEventListener('contextmenu', Wirecloud.Utils.preventDefaultListener); } // Draggable if (!this.isMiniInterface) { this.makeDraggable(); } else { //miniInterface this.draggable = new Wirecloud.ui.Draggable(this.wrapperElement, {iObject: this}, function onStart(draggable, context) { var miniwidget_clon, pos_miniwidget, headerHeight; headerHeight = context.iObject.wiringEditor.getBoundingClientRect().top; //initial position pos_miniwidget = context.iObject.getBoundingClientRect(); context.y = pos_miniwidget.top - (headerHeight); context.x = pos_miniwidget.left; //create a miniwidget clon if (context.iObject instanceof Wirecloud.ui.WiringEditor.WidgetInterface) { miniwidget_clon = new Wirecloud.ui.WiringEditor.WidgetInterface(context.iObject.wiringEditor, context.iObject.iwidget, context.iObject.wiringEditor, true); } else { miniwidget_clon = new Wirecloud.ui.WiringEditor.OperatorInterface(context.iObject.wiringEditor, context.iObject.ioperator, context.iObject.wiringEditor, true); } miniwidget_clon.addClassName('clon'); //set the clon position over the originar miniWidget miniwidget_clon.setBoundingClientRect(pos_miniwidget, {top: -headerHeight, left: 0, width: -2, height: -10}); // put the miniwidget clon in the layout context.iObject.wiringEditor.layout.wrapperElement.appendChild(miniwidget_clon.wrapperElement); //put the clon in the context.iObject context.iObjectClon = miniwidget_clon; }, function onDrag(e, draggable, context, xDelta, yDelta) { context.iObjectClon.setPosition({posX: context.x + xDelta, posY: context.y + yDelta}); context.iObjectClon.repaint(); }, this.onFinish.bind(this), function () { return this.enabled && !this.wrapperElement.classList.contains('clon'); }.bind(this) ); }//else miniInterface }; GenericInterface.prototype = new StyledElements.Container({'extending': true}); /************************************************************************* * Private methods *************************************************************************/ var getElementPos = function getElementPos(elemList, elem) { var i; for (i = 0; i < elemList.length; i++) { if (elem === elemList[i]) { return i; } } }; /** * @Private * is empty object? */ var isEmpty = function isEmpty(obj) { for(var key in obj) { return false; } return true; }; var createMulticonnector = function createMulticonnector(name, anchor) { var multiconnector; multiconnector = new Wirecloud.ui.WiringEditor.Multiconnector(this.wiringEditor.nextMulticonnectorId, this.getId(), name, this.wiringEditor.layout.getCenterContainer().wrapperElement, this.wiringEditor, anchor, null, null); this.wiringEditor.nextMulticonnectorId = parseInt(this.wiringEditor.nextMulticonnectorId, 10) + 1; this.wiringEditor.addMulticonnector(multiconnector); multiconnector.addMainArrow(); }; /** * OutputSubendpoint */ var OutputSubendpoint = function OutputSubendpoint(name, description, iwidget, type) { var nameList, subdata, i; this.iwidget = iwidget; this.name = name; this.subdata = description.subdata; this.variable = description; this.type = type; this.friendcode = description.friendcode; nameList = name.split('/'); subdata = JSON.parse(description.subdata); for (i = 1; i < nameList.length; i++) { if (nameList[0] == nameList[1]) { break; } subdata = subdata[nameList[i]]; this.friendcode = subdata.semanticType; subdata = subdata.subdata; } }; /** * Serialize OutputSubendpoint */ OutputSubendpoint.prototype.serialize = function serialize() { return { 'type': this.type, 'id': this.iwidget.id, 'endpoint': this.name }; }; /** * Set ActionLabel listeners in a endpoint */ var setlabelActionListeners = function setlabelActionListeners(labelActionLayer, checkbox) { // Emphasize listeners labelActionLayer.addEventListener('mouseover',function (thecheckbox) { this.wiringEditor.recommendations.emphasize(thecheckbox); }.bind(this, checkbox), false); labelActionLayer.addEventListener('mouseout',function (thecheckbox) { this.wiringEditor.recommendations.deemphasize(thecheckbox); }.bind(this, checkbox), false); checkbox.wrapperElement.addEventListener('mouseover',function (thecheckbox) { this.wiringEditor.recommendations.emphasize(thecheckbox); }.bind(this, checkbox), false); checkbox.wrapperElement.addEventListener('mouseout',function (thecheckbox) { this.wiringEditor.recommendations.deemphasize(thecheckbox); }.bind(this, checkbox), false); // Sticky effect labelActionLayer.addEventListener('mouseover', checkbox._mouseover_callback, false); labelActionLayer.addEventListener('mouseout', checkbox._mouseout_callback, false); // Connect anchor whith mouseup on the label labelActionLayer.addEventListener('mouseup', checkbox._mouseup_callback, false); }; /** * format Tree */ var formatTree = function(treeDiv, entityWidth) { var heightPerLeaf, branchList, i, j, nleafsAux, desp, checkbox, label, height, firstFrame, firstTree, width, diff, treeWidth, actionLayer, bounding, treeBounding, leafs, lastTop, subtrees; firstFrame = treeDiv.getElementsByClassName("labelsFrame")[0]; firstTree = treeDiv.getElementsByClassName("tree")[0]; diff = (firstTree.getBoundingClientRect().top - firstFrame.getBoundingClientRect().top); if (diff == -10) { return; } firstFrame.style.top = diff + 10 + 'px'; height = firstFrame.getBoundingClientRect().height + 10; width = firstFrame.getBoundingClientRect().width; firstTree.style.height = height + 10 + 'px'; treeWidth = treeDiv.getBoundingClientRect().width; if (treeWidth < entityWidth - 14) { treeDiv.style.width = entityWidth - 14 + 'px'; treeDiv.style.left = 7 + 'px'; } treeDiv.style.height = height + 'px'; // Vertical Alignment leafs = treeDiv.getElementsByClassName('leaf'); heightPerLeaf = height/leafs.length; branchList = treeDiv.getElementsByClassName("dataTree branch"); for (i = 0; i < branchList.length; i++) { // Set Label position nleafsAux = branchList[i].getElementsByClassName('leaf').length; desp = -(((nleafsAux / 2) * heightPerLeaf) - (heightPerLeaf / 2)); label = branchList[i].getElementsByClassName('labelTree')[branchList[i].getElementsByClassName('labelTree').length - 1]; // Set label and anchor position checkbox = branchList[i].getElementsByClassName('subAnchor')[branchList[i].getElementsByClassName('subAnchor').length - 1]; label.style.top = desp + 'px'; checkbox.style.top = desp + 'px'; // Set action layer bounding for the label treeBounding = branchList[i].getBoundingClientRect(); if (i == 0) { lastTop = treeBounding.top; } actionLayer = branchList[i].nextElementSibling; bounding = label.getBoundingClientRect(); actionLayer.style.height = bounding.height + 'px'; actionLayer.style.width = bounding.width + 'px'; actionLayer.style.left = (bounding.left - treeBounding.left) + 'px'; actionLayer.style.top = Math.abs(lastTop - bounding.top) + 'px'; lastTop = treeBounding.top + 1; // Set leaf action layers setLeafActionLayers(branchList[i].parentNode.children); // Set leaf action layers in only-leafs subtree if (branchList[i].getElementsByClassName("dataTree branch").length == 0) { subtrees = branchList[i].getElementsByClassName('subTree'); for (j = 0; j < subtrees.length; j++) { // All leafs subtree found setLeafActionLayers(subtrees[j].getElementsByClassName('labelsFrame')[0].children); } } } }; var setLeafActionLayers = function setLeafActionLayers (brothers) { var acumulatedTop, j, treeBounding, bounding, actionLayer; acumulatedTop = 5; for (j = 0; j < brothers.length; j += 2) { treeBounding = brothers[j].getBoundingClientRect(); if (brothers[j].hasClassName('dataTree leaf')) { bounding = brothers[j].getElementsByClassName('labelTree')[0].getBoundingClientRect(); actionLayer = brothers[j].nextElementSibling; actionLayer.style.height = bounding.height + 'px'; actionLayer.style.width = bounding.width + 'px'; actionLayer.style.left = (bounding.left - treeBounding.left) + 'px'; actionLayer.style.top = acumulatedTop + 'px'; } acumulatedTop += treeBounding.height; } }; /************************************************************************* * Public methods *************************************************************************/ /** * Making Interface Draggable. */ GenericInterface.prototype.makeDraggable = function makeDraggable() { this.draggable = new Wirecloud.ui.Draggable(this.wrapperElement, {iObject: this}, function onStart(draggable, context) { context.y = context.iObject.wrapperElement.style.top === "" ? 0 : parseInt(context.iObject.wrapperElement.style.top, 10); context.x = context.iObject.wrapperElement.style.left === "" ? 0 : parseInt(context.iObject.wrapperElement.style.left, 10); context.preselected = context.iObject.selected; context.iObject.select(true); context.iObject.wiringEditor.onStarDragSelected(); }, function onDrag(e, draggable, context, xDelta, yDelta) { context.iObject.setPosition({posX: context.x + xDelta, posY: context.y + yDelta}); context.iObject.repaint(); context.iObject.wiringEditor.onDragSelectedObjects(xDelta, yDelta); }, function onFinish(draggable, context) { context.iObject.wiringEditor.onFinishSelectedObjects(); var position = context.iObject.getStylePosition(); if (position.posX < 0) { position.posX = 8; } if (position.posY < 0) { position.posY = 8; } context.iObject.setPosition(position); context.iObject.repaint(); //pseudoClick if ((Math.abs(context.x - position.posX) < 2) && (Math.abs(context.y - position.posY) < 2)) { if (context.preselected) { context.iObject.unselect(true); } context.iObject.movement = false; } else { if (!context.preselected) { context.iObject.unselect(true); } context.iObject.movement = true; } }, function () {return true; } ); }; /** * Make draggable all sources and targets for sorting */ GenericInterface.prototype.makeSlotsDraggable = function makeSlotsDraggable() { var i; for (i = 0; i < this.draggableSources.length; i++) { this.makeSlotDraggable(this.draggableSources[i], this.wiringEditor.layout.center, 'source_clon'); } for (i = 0; i < this.draggableTargets.length; i++) { this.makeSlotDraggable(this.draggableTargets[i], this.wiringEditor.layout.center, 'target_clon'); } }; /** * Make draggable a specific sources or targets for sorting */ GenericInterface.prototype.makeSlotDraggable = function makeSlotDraggable(element, place, className) { element.draggable = new Wirecloud.ui.Draggable(element.wrapperElement, {iObject: element, genInterface: this, wiringEditor: this.wiringEditor}, function onStart(draggable, context) { var clon, pos_miniwidget, gridbounds, childsN, childPos; //initial position pos_miniwidget = context.iObject.wrapperElement.getBoundingClientRect(); gridbounds = context.wiringEditor.getGridElement().getBoundingClientRect(); context.y = pos_miniwidget.top - gridbounds.top; context.x = pos_miniwidget.left - gridbounds.left; //create clon context.iObject.wrapperElement.classList.add('moving'); clon = context.iObject.wrapperElement.cloneNode(true); clon.classList.add(className); // put the clon in place place.wrapperElement.appendChild(clon); //set the clon position over the originar miniWidget clon.style.height = (pos_miniwidget.height) + 'px'; clon.style.left = (context.x) + 'px'; clon.style.top = (context.y) + 'px'; clon.style.width = (pos_miniwidget.width) + 'px'; //put the clon in the context.iObjectClon context.iObjectClon = clon; //put the reference height for change position context.refHeigth = context.iObject.wrapperElement.getBoundingClientRect().height + 2; context.refHeigthUp = context.refHeigth; context.refHeigthDown = context.refHeigth; childsN = context.iObject.wrapperElement.parentNode.childElementCount; childPos = getElementPos(context.iObject.wrapperElement.parentNode.children, context.iObject.wrapperElement); context.maxUps = childPos; context.maxDowns = childsN - (childPos + 1); }, function onDrag(e, draggable, context, xDelta, yDelta) { var top; context.iObjectClon.style.left = (context.x + xDelta) + 'px'; context.iObjectClon.style.top = (context.y + yDelta) + 'px'; top = parseInt(context.iObjectClon.style.top, 10); if (((context.y - top) > context.refHeigthUp) && (context.maxUps > 0)) { context.maxDowns += 1; context.maxUps -= 1; context.refHeigthUp += context.refHeigth; context.refHeigthDown -= context.refHeigth; context.genInterface.up(context.iObject); } else if (((top - context.y) > context.refHeigthDown) && (context.maxDowns > 0)) { context.maxUps += 1; context.maxDowns -= 1; context.refHeigthDown += context.refHeigth; context.refHeigthUp -= context.refHeigth; context.genInterface.down(context.iObject); } }, function onFinish(draggable, context) { context.iObject.wrapperElement.classList.remove('moving'); if (context.iObjectClon.parentNode) { context.iObjectClon.parentNode.removeChild(context.iObjectClon); } context.iObjectClon = null; }, function () {return true; } ); }; /** * Get the GenericInterface position. */ GenericInterface.prototype.getPosition = function getPosition() { var coordinates = {posX: this.wrapperElement.offsetLeft, posY: this.wrapperElement.offsetTop}; return coordinates; }; /** * Get the GenericInterface style position. */ GenericInterface.prototype.getStylePosition = function getStylePosition() { var coordinates; coordinates = {posX: parseInt(this.wrapperElement.style.left, 10), posY: parseInt(this.wrapperElement.style.top, 10)}; return coordinates; }; /** * Gets an anchor given a name */ GenericInterface.prototype.getAnchor = function getAnchor(name) { if (name in this.sourceAnchorsByName) { return this.sourceAnchorsByName[name]; } else if (name in this.targetAnchorsByName) { return this.targetAnchorsByName[name]; } else { return null; } }; /** * Add Ghost Endpoint */ GenericInterface.prototype.addGhostEndpoint = function addGhostEndpoint(theEndpoint, isSource) { var context; if (isSource) { context = {'data': new Wirecloud.wiring.GhostSourceEndpoint(theEndpoint, this.entity), 'iObject': this}; this.addSource(theEndpoint.endpoint, '', theEndpoint.endpoint, context, true); return this.sourceAnchorsByName[theEndpoint.endpoint]; } else { context = {'data': new Wirecloud.wiring.GhostTargetEndpoint(theEndpoint, this.entity), 'iObject': this}; this.addTarget(theEndpoint.endpoint, '', theEndpoint.endpoint, context, true); return this.targetAnchorsByName[theEndpoint.endpoint]; } }; /** * Set the GenericInterface position. */ GenericInterface.prototype.setPosition = function setPosition(coordinates) { this.wrapperElement.style.left = coordinates.posX + 'px'; this.wrapperElement.style.top = coordinates.posY + 'px'; }; /** * Set the BoundingClientRect parameters */ GenericInterface.prototype.setBoundingClientRect = function setBoundingClientRect(BoundingClientRect, move) { this.wrapperElement.style.height = (BoundingClientRect.height + move.height) + 'px'; this.wrapperElement.style.left = (BoundingClientRect.left + move.left) + 'px'; this.wrapperElement.style.top = (BoundingClientRect.top + move.top) + 'px'; this.wrapperElement.style.width = (BoundingClientRect.width + move.width) + 'px'; }; /** * Set the initial position in the menubar, miniobjects. */ GenericInterface.prototype.setMenubarPosition = function setMenubarPosition(menubarPosition) { this.menubarPosition = menubarPosition; }; /** * Set the initial position in the menubar, miniobjects. */ GenericInterface.prototype.getMenubarPosition = function getMenubarPosition() { return this.menubarPosition; }; /** * Increasing the number of read only connections */ GenericInterface.prototype.incReadOnlyConnectionsCount = function incReadOnlyConnectionsCount() { this.readOnlyEndpoints += 1; this.readOnly = true; }; /** * Reduce the number of read only connections */ GenericInterface.prototype.reduceReadOnlyConnectionsCount = function reduceReadOnlyConnectionsCount() { this.readOnlyEndpoints -= 1; if (this.readOnlyEndpoints == 0) { this.readOnly = false; } }; /** * Generic repaint */ GenericInterface.prototype.repaint = function repaint(temporal) { var key; StyledElements.Container.prototype.repaint.apply(this, arguments); for (key in this.sourceAnchorsByName) { this.sourceAnchorsByName[key].repaint(temporal); } for (key in this.targetAnchorsByName) { this.targetAnchorsByName[key].repaint(temporal); } }; /** * Generate SubTree */ GenericInterface.prototype.generateSubTree = function generateSubTree(anchorContext, subAnchors) { var treeFrame, key, lab, checkbox, subdata, subTree, labelsFrame, context, name, labelActionLayer, entity, type; treeFrame = document.createElement("div"); treeFrame.classList.add('subTree'); labelsFrame = document.createElement("div"); labelsFrame.classList.add('labelsFrame'); treeFrame.appendChild(labelsFrame); if (!isEmpty(subAnchors.subdata)) { for (key in subAnchors.subdata) { lab = document.createElement("span"); lab.classList.add("labelTree"); lab.textContent = subAnchors.subdata[key].label; name = anchorContext.data.name + "/" + key; if (anchorContext.data.iwidget != null) { entity = anchorContext.data.iwidget; type = 'iwidget'; } else { entity = anchorContext.data.operator; type = 'ioperator'; } context = {'data': new OutputSubendpoint(name, anchorContext.data, entity, type), 'iObject': this}; checkbox = new Wirecloud.ui.WiringEditor.SourceAnchor(context, anchorContext.iObject.arrowCreator, subAnchors.subdata[key]); checkbox.wrapperElement.classList.add("subAnchor"); checkbox.wrapperElement.classList.add("icon-circle"); this.sourceAnchorsByName[name] = checkbox; this.sourceAnchors.push(checkbox); subdata = document.createElement("div"); subdata.classList.add("dataTree"); labelActionLayer = document.createElement("div"); labelActionLayer.classList.add("labelActionLayer"); setlabelActionListeners.call(this, labelActionLayer, checkbox); subTree = this.generateSubTree(context, subAnchors.subdata[key], checkbox); if (subTree !== null) { subdata.appendChild(subTree); subdata.classList.add("branch"); } else{ subdata.classList.add("leaf"); } subdata.appendChild(lab); subdata.appendChild(checkbox.wrapperElement); labelsFrame.appendChild(subdata); labelsFrame.appendChild(labelActionLayer); } return treeFrame; } else { return null; } }; /** * Generate Tree */ GenericInterface.prototype.generateTree = function generateTree(anchor, name, anchorContext, subtree, label, closeHandler) { var subAnchors, treeFrame, lab, checkbox, subdata, key, subTree, subTreeFrame, type, labelsFrame, labelMain, close_button, context, name, labelActionLayer, entity, treeDiv; // Generate tree treeDiv = document.createElement("div"); treeDiv.classList.add('anchorTree'); treeDiv.addEventListener('click', function (e) { e.stopPropagation(); }.bind(this), false); treeDiv.addEventListener('mousedown', function (e) { e.stopPropagation(); }.bind(this), false); treeFrame = document.createElement("div"); treeFrame.classList.add('tree'); treeFrame.classList.add('sources'); // Close button close_button = new StyledElements.StyledButton({ 'title': gettext("Hide"), 'class': 'hideTreeButton icon-off', 'plain': true }); close_button.insertInto(treeFrame); close_button.addEventListener('click', function () {closeHandler();}, false); subAnchors = JSON.parse(subtree); subTreeFrame = null; labelsFrame = document.createElement("div"); labelsFrame.classList.add('labelsFrame'); if (subAnchors !== null) { subTreeFrame = document.createElement("div"); subTreeFrame.classList.add('subTree'); for (key in subAnchors) { lab = document.createElement("span"); lab.classList.add("labelTree"); lab.textContent = subAnchors[key].label; name = anchorContext.data.name + "/" + key; if (anchorContext.data.iwidget != null) { entity = anchorContext.data.iwidget; type = 'iwidget'; } else { entity = anchorContext.data.operator; type = 'ioperator'; } context = {'data': new OutputSubendpoint(name, anchorContext.data, entity, type), 'iObject': this}; checkbox = new Wirecloud.ui.WiringEditor.SourceAnchor(context, anchorContext.iObject.arrowCreator, subAnchors[key]); checkbox.wrapperElement.classList.add("subAnchor"); checkbox.wrapperElement.classList.add("icon-circle"); this.sourceAnchorsByName[name] = checkbox; this.sourceAnchors.push(checkbox); subdata = document.createElement("div"); subdata.classList.add("dataTree"); labelActionLayer = document.createElement("div"); labelActionLayer.classList.add("labelActionLayer"); setlabelActionListeners.call(this, labelActionLayer, checkbox); subTree = this.generateSubTree(context, subAnchors[key], checkbox); if (subTree !== null) { subdata.appendChild(subTree); subdata.classList.add("branch"); } else{ subdata.classList.add("leaf"); } subdata.appendChild(lab); subdata.appendChild(checkbox.wrapperElement); labelsFrame.appendChild(subdata); labelsFrame.appendChild(labelActionLayer); subTreeFrame.appendChild(labelsFrame); } } lab = document.createElement("span"); lab.classList.add("labelTree"); lab.textContent = label; name = anchorContext.data.name + "/" + anchorContext.data.name; if (anchorContext.data.iwidget != null) { entity = anchorContext.data.iwidget; type = 'iwidget'; } else { entity = anchorContext.data.operator; type = 'ioperator'; } context = {'data': new OutputSubendpoint(name, anchorContext.data, entity, type), 'iObject': this}; checkbox = new Wirecloud.ui.WiringEditor.SourceAnchor(context, anchorContext.iObject.arrowCreator, subAnchors); checkbox.wrapperElement.classList.add("subAnchor"); checkbox.wrapperElement.classList.add("icon-circle"); this.sourceAnchorsByName[name] = checkbox; this.sourceAnchors.push(checkbox); subdata = document.createElement("div"); subdata.classList.add("dataTree"); labelActionLayer = document.createElement("div"); labelActionLayer.classList.add("labelActionLayer"); setlabelActionListeners.call(this, labelActionLayer, checkbox); if (subTreeFrame !== null) { subdata.appendChild(subTreeFrame); subdata.classList.add("branch"); } else { subdata.classList.add("leaf"); } subdata.appendChild(lab); subdata.appendChild(checkbox.wrapperElement); labelMain = document.createElement("div"); labelMain.classList.add('labelsFrame'); labelMain.appendChild(subdata); labelMain.appendChild(labelActionLayer); treeFrame.appendChild(labelMain); treeDiv.appendChild(treeFrame); this.wrapperElement.appendChild(treeDiv); // Handler for subdata tree menu anchor.menu.append(new StyledElements.MenuItem(gettext("Unfold data structure"), this.subdataHandler.bind(this, treeDiv, name))); }; /** * handler for show/hide anchorTrees */ GenericInterface.prototype.subdataHandler = function subdataHandler(treeDiv, name) { var initialHeiht, initialWidth, key, i, externalRep, layer, subDataArrow, firstIndex, mainEndpoint, mainSubEndPoint, theArrow, mainEndpointArrows; if (treeDiv == null) { // Descend canvas this.wiringEditor.canvas.canvasElement.classList.remove("elevated"); // Hide tree this.activatedTree.classList.remove('activated'); this.activatedTree = null; // Deactivate subdataMode this.wrapperElement.classList.remove('subdataMode'); // Hide subdata connections, and show hollow and full connections if (!isEmpty(this.subdataConnections[name])) { for (key in this.subdataConnections[name]) { firstIndex = this.subdataConnections[name][key].length - 1; for (i = firstIndex; i >= 0 ; i -= 1) { externalRep = this.subdataConnections[name][key][i].externalRep; subDataArrow = this.subdataConnections[name][key][i].subDataArrow; externalRep.show(); if (externalRep.hasClassName('hollow')) { subDataArrow.hide(); } else { // Remove all subconnections that represent full connections subDataArrow.destroy(); this.subdataConnections[name][key].splice(i, 1); this.fullConnections[name][key].splice(this.fullConnections[name][key].indexOf(externalRep), 1); } } } } } else { // Elevate canvas this.wiringEditor.canvas.canvasElement.classList.add("elevated"); // Show tree initialWidth = this.wrapperElement.getBoundingClientRect().width; treeDiv.classList.add('activated'); this.activatedTree = treeDiv; formatTree(treeDiv, initialWidth); // Activate subdataMode this.wrapperElement.classList.add('subdataMode'); // Add a subconnection for each main connexion in the main endpoint layer = this.wiringEditor.arrowCreator.layer; mainEndpoint = this.sourceAnchorsByName[name]; mainSubEndPoint = this.sourceAnchorsByName[name + "/" + name]; mainEndpointArrows = mainEndpoint.getArrows(); for (i = 0; i < mainEndpointArrows.length ; i += 1) { if (!mainEndpointArrows[i].hasClassName('hollow')) { // New full subConnection theArrow = this.wiringEditor.canvas.drawArrow(mainSubEndPoint.getCoordinates(layer), mainEndpointArrows[i].endAnchor.getCoordinates(layer), "arrow subdataConnection full"); theArrow.setEndAnchor(mainEndpointArrows[i].endAnchor); theArrow.setStartAnchor(mainSubEndPoint); mainSubEndPoint.addArrow(theArrow); mainEndpointArrows[i].endAnchor.addArrow(theArrow); // Add this connections to subdataConnections if (this.subdataConnections[name] == null) { this.subdataConnections[name] = {}; } if (this.subdataConnections[name][name + "/" + name] == null) { this.subdataConnections[name][name + "/" + name] = []; } this.subdataConnections[name][name + "/" + name].push({'subDataArrow' : theArrow, 'externalRep': mainEndpointArrows[i]}); // Add this connections to fullConnections if (this.fullConnections[name] == null) { this.fullConnections[name] = {}; } if (this.fullConnections[name][name + "/" + name] == null) { this.fullConnections[name][name + "/" + name] = []; } this.fullConnections[name][name + "/" + name].push(mainEndpointArrows[i]); } } // Show subdata connections, and hide hollow connections for (key in this.subdataConnections[name]) { for (i = 0; i < this.subdataConnections[name][key].length ; i += 1) { this.subdataConnections[name][key][i].externalRep.hide(); this.subdataConnections[name][key][i].subDataArrow.show(); } } } this.repaint(); this.wiringEditor.activatedTree = this.activatedTree; }; /** * Add subdata connection. */ GenericInterface.prototype.addSubdataConnection = function addSubdataConnection(endpoint, subdatakey, connection, sourceAnchor, targetAnchor, isLoadingWiring) { var theArrow, mainEndpoint, layer; if (this.subdataConnections[endpoint] == null) { this.subdataConnections[endpoint] = {}; } if (this.subdataConnections[endpoint][subdatakey] == null) { this.subdataConnections[endpoint][subdatakey] = []; } layer = this.wiringEditor.arrowCreator.layer; mainEndpoint = this.sourceAnchorsByName[endpoint]; if ((endpoint + "/" + endpoint) == subdatakey) { // Add full connection if (this.fullConnections[endpoint] == null) { this.fullConnections[endpoint] = {}; } if (this.fullConnections[endpoint][subdatakey] == null) { this.fullConnections[endpoint][subdatakey] = []; } connection.addClassName('full'); theArrow = this.wiringEditor.canvas.drawArrow(mainEndpoint.getCoordinates(layer), targetAnchor.getCoordinates(layer), "arrow"); this.fullConnections[endpoint][subdatakey].push(theArrow); } else { // Add a hollow connection if (this.hollowConnections[endpoint] == null) { this.hollowConnections[endpoint] = {}; } if (this.hollowConnections[endpoint][subdatakey] == null) { this.hollowConnections[endpoint][subdatakey] = []; } theArrow = this.wiringEditor.canvas.drawArrow(mainEndpoint.getCoordinates(layer), targetAnchor.getCoordinates(layer), "arrow hollow"); this.hollowConnections[endpoint][subdatakey].push(theArrow); } theArrow.setEndAnchor(targetAnchor); theArrow.setStartAnchor(mainEndpoint); mainEndpoint.addArrow(theArrow); targetAnchor.addArrow(theArrow); if (isLoadingWiring) { connection.hide(); } else { theArrow.hide(); } this.subdataConnections[endpoint][subdatakey].push({'subDataArrow' : connection, 'externalRep': theArrow}); }; /** * Remove subdata connection. */ GenericInterface.prototype.removeSubdataConnection = function removeSubdataConnection(endpoint, subdatakey, connection) { var i, externalRep; if ((endpoint + "/" + endpoint) == subdatakey) { // Remove full connection if (this.fullConnections[endpoint] != null && this.fullConnections[endpoint][subdatakey] != null) { for (i = 0; i < this.subdataConnections[endpoint][subdatakey].length ; i += 1) { if (this.subdataConnections[endpoint][subdatakey][i].subDataArrow == connection) { externalRep = this.subdataConnections[endpoint][subdatakey][i].externalRep; this.fullConnections[endpoint][subdatakey].splice(this.fullConnections[endpoint][subdatakey].indexOf(externalRep), 1); externalRep.destroy(); connection.destroy(); this.subdataConnections[endpoint][subdatakey].splice(i, 1); break; } } } else { // Error } } else { // Remove a hollow connection if (this.hollowConnections[endpoint] != null && this.hollowConnections[endpoint][subdatakey] != null) { for (i = 0; i < this.subdataConnections[endpoint][subdatakey].length ; i += 1) { if (this.subdataConnections[endpoint][subdatakey][i].subDataArrow == connection) { externalRep = this.subdataConnections[endpoint][subdatakey][i].externalRep; this.hollowConnections[endpoint][subdatakey].splice(this.hollowConnections[endpoint][subdatakey].indexOf(externalRep), 1); externalRep.destroy(); connection.destroy(); this.subdataConnections[endpoint][subdatakey].splice(i, 1); break; } } } else { // Error } } }; /** * Add Source. */ GenericInterface.prototype.addSource = function addSource(label, desc, name, anchorContext, isGhost) { var anchor, anchorDiv, labelDiv, anchorLabel, treeDiv, subAnchors; // Sources counter this.numberOfSources += 1; // AnchorDiv anchorDiv = document.createElement("div"); // If the output have not description, take the label if (desc === '') { desc = label; } if (isGhost) { anchorDiv.setAttribute('title', gettext("Mismatch endpoint! ") + label); } else { anchorDiv.setAttribute('title', label + ': ' + desc); } anchorDiv.classList.add('anchorDiv'); if (isGhost) { anchorDiv.classList.add('ghost'); } // Anchor visible label anchorLabel = document.createElement("span"); anchorLabel.textContent = label; labelDiv = document.createElement("div"); anchorDiv.appendChild(labelDiv); labelDiv.setAttribute('class', 'labelDiv'); labelDiv.appendChild(anchorLabel); if (!this.isMiniInterface) { anchor = new Wirecloud.ui.WiringEditor.SourceAnchor(anchorContext, this.arrowCreator, null, isGhost); labelDiv.appendChild(anchor.wrapperElement); anchor.menu.append(new StyledElements.MenuItem(gettext('Add multiconnector'), createMulticonnector.bind(this, name, anchor))); subAnchors = anchorContext.data.subdata; if (subAnchors != null) { // Generate the tree this.generateTree(anchor, name, anchorContext, subAnchors, label, this.subdataHandler.bind(this, null, name)); } labelDiv.addEventListener('mouseover', function () { this.wiringEditor.recommendations.emphasize(anchor); }.bind(this)); labelDiv.addEventListener('mouseout', function () { this.wiringEditor.recommendations.deemphasize(anchor); }.bind(this)); // Sticky effect anchorDiv.addEventListener('mouseover', function (e) { anchor._mouseover_callback(e); }.bind(this)); anchorDiv.addEventListener('mouseout', function (e) { anchor._mouseout_callback(e); }.bind(this)); // Connect anchor whith mouseup on the label anchorDiv.addEventListener('mouseup', function (e) { anchor._mouseup_callback(e); }.bind(this)); this.sourceAnchorsByName[name] = anchor; this.sourceAnchors.push(anchor); } this.sourceDiv.appendChild(anchorDiv); this.draggableSources.push({'wrapperElement': anchorDiv, 'context': anchorContext}); }; /** * Add Target. */ GenericInterface.prototype.addTarget = function addTarget(label, desc, name, anchorContext, isGhost) { var anchor, anchorDiv, labelDiv, anchorLabel; // Targets counter this.numberOfTargets += 1; // AnchorDiv anchorDiv = document.createElement("div"); // If the output have not description, take the label if (desc === '') { desc = label; } if (isGhost) { anchorDiv.setAttribute('title', gettext('Mismatch endpoint! ') + label); } else { anchorDiv.setAttribute('title', label + ': ' + desc); } anchorDiv.classList.add('anchorDiv'); if (isGhost) { anchorDiv.classList.add('ghost'); } // Anchor visible label anchorLabel = document.createElement("span"); anchorLabel.textContent = label; labelDiv = document.createElement("div"); anchorDiv.appendChild(labelDiv); labelDiv.setAttribute('class', 'labelDiv'); labelDiv.appendChild(anchorLabel); if (!this.isMiniInterface) { anchor = new Wirecloud.ui.WiringEditor.TargetAnchor(anchorContext, this.arrowCreator, isGhost); labelDiv.appendChild(anchor.wrapperElement); anchor.menu.append(new StyledElements.MenuItem(gettext('Add multiconnector'), createMulticonnector.bind(this, name, anchor))); labelDiv.addEventListener('mouseover', function () { if (!this.wiringEditor.recommendationsActivated) { this.wiringEditor.recommendations.emphasize(anchor); } }.bind(this)); labelDiv.addEventListener('mouseout', function () { if (!this.wiringEditor.recommendationsActivated) { this.wiringEditor.recommendations.deemphasize(anchor); } }.bind(this)); // Sticky effect anchorDiv.addEventListener('mouseover', function (e) { anchor._mouseover_callback(e); }.bind(this)); anchorDiv.addEventListener('mouseout', function (e) { anchor._mouseout_callback(e); }.bind(this)); // Connect anchor whith mouseup on the label anchorDiv.addEventListener('mouseup', function (e) { anchor._mouseup_callback(e); }.bind(this)); this.targetAnchorsByName[name] = anchor; this.targetAnchors.push(anchor); } this.targetDiv.appendChild(anchorDiv); this.draggableTargets.push({'wrapperElement': anchorDiv, 'context': anchorContext}); }; /** * Add new class in to the genericInterface */ GenericInterface.prototype.addClassName = function addClassName(className) { var atr; if (className == null) { return; } atr = this.wrapperElement.getAttribute('class'); if (atr == null) { atr = ''; } this.wrapperElement.setAttribute('class', Wirecloud.Utils.appendWord(atr, className)); }; /** * Remove a genericInterface Class name */ GenericInterface.prototype.removeClassName = function removeClassName(className) { var atr; if (className == null) { return; } atr = this.wrapperElement.getAttribute('class'); if (atr == null) { atr = ''; } this.wrapperElement.setAttribute('class', Wirecloud.Utils.removeWord(atr, className)); }; /** * Select this genericInterface */ GenericInterface.prototype.select = function select(withCtrl) { var i, j, arrows; if (this.hasClassName('disabled')) { return; } if (this.hasClassName('selected')) { return; } if (!(this.wiringEditor.ctrlPushed) && (this.wiringEditor.selectedCount > 0) && (withCtrl)) { this.wiringEditor.resetSelection(); } this.selected = true; this.addClassName('selected'); // Arrows for (i = 0; i < this.targetAnchors.length; i += 1) { arrows = this.targetAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].emphasize(); } } for (i = 0; i < this.sourceAnchors.length; i += 1) { arrows = this.sourceAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].emphasize(); } } this.wiringEditor.addSelectedObject(this); }; /** * Unselect this genericInterface */ GenericInterface.prototype.unselect = function unselect(withCtrl) { var i, j, arrows; this.selected = false; this.removeClassName('selected'); //arrows for (i = 0; i < this.targetAnchors.length; i += 1) { arrows = this.targetAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].deemphasize(); } } for (i = 0; i < this.sourceAnchors.length; i += 1) { arrows = this.sourceAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].deemphasize(); } } this.wiringEditor.removeSelectedObject(this); if (!(this.wiringEditor.ctrlPushed) && (this.wiringEditor.selectedCount > 0) && (withCtrl)) { this.wiringEditor.resetSelection(); } }; /** * Destroy */ GenericInterface.prototype.destroy = function destroy() { var i, j, arrows; this.unselect(); if (this.editingPos === true) { this.disableEdit(); } StyledElements.Container.prototype.destroy.call(this); for (i = 0; i < this.sourceAnchors.length; i += 1) { arrows = this.sourceAnchors[i].arrows.slice(0); for (j = 0; j < arrows.length; j += 1) { if (!arrows[j].controlledDestruction()) { arrows[j].destroy(); } } this.sourceAnchors[i].destroy(); } for (i = 0; i < this.targetAnchors.length; i += 1) { arrows = this.targetAnchors[i].arrows.slice(0); for (j = 0; j < arrows.length; j += 1) { if (!arrows[j].controlledDestruction()) { arrows[j].destroy(); } } this.targetAnchors[i].destroy(); } this.draggable.destroy(); this.draggable = null; this.draggableSources = null; this.draggableTargets = null; this.wrapperElement = null; this.hollowConnections = null; this.subdataConnections = null; }; /** * Edit source and targets positions */ GenericInterface.prototype.editPos = function editPos() { var obj; obj = null; if ((this.targetAnchors.length <= 1) && (this.sourceAnchors.length <= 1)) { return; } if (this.editingPos === true) { this.disableEdit(); } else { this.enableEdit(); obj = this; } this.repaint(); return obj; }; /** * Enable poditions editor */ GenericInterface.prototype.enableEdit = function enableEdit() { this.draggable.destroy(); this.editingPos = true; this.sourceDiv.wrapperElement.classList.add("editing"); this.targetDiv.wrapperElement.classList.add("editing"); this.addClassName("editing"); this.makeSlotsDraggable(); }; /** * Disable poditions editor */ GenericInterface.prototype.disableEdit = function disableEdit() { var i; this.makeDraggable(); this.editingPos = false; this.sourceDiv.wrapperElement.classList.remove("editing"); this.targetDiv.wrapperElement.classList.remove("editing"); this.removeClassName("editing"); for (i = 0; i < this.draggableSources.length; i++) { this.draggableSources[i].draggable.destroy(); } for (i = 0; i < this.draggableTargets.length; i++) { this.draggableTargets[i].draggable.destroy(); } }; /** * Move an endpoint up 1 position. */ GenericInterface.prototype.up = function up(element) { element.wrapperElement.parentNode.insertBefore(element.wrapperElement, element.wrapperElement.previousElementSibling); this.repaint(); }; /** * Move an endpoint down 1 position. */ GenericInterface.prototype.down = function down(element) { if (element.wrapperElement.nextElementSibling !== null) { element.wrapperElement.parentNode.insertBefore(element.wrapperElement, element.wrapperElement.nextElementSibling.nextElementSibling); this.repaint(); } }; /** * Get sources and targets titles lists in order to save positions */ GenericInterface.prototype.getInOutPositions = function getInOutPositions() { var i, sources, targets; sources = []; targets = []; for (i = 0; i < this.sourceDiv.wrapperElement.childNodes.length; i++) { sources[i] = this.getNameForSort(this.sourceDiv.wrapperElement.childNodes[i], 'source'); } for (i = 0; i < this.targetDiv.wrapperElement.childNodes.length; i++) { targets[i] = this.getNameForSort(this.targetDiv.wrapperElement.childNodes[i], 'target'); } return {'sources': sources, 'targets': targets}; }; /** * Get the source or target name for the especific node */ GenericInterface.prototype.getNameForSort = function getNameForSort(node, type) { var i, collection; if (type === 'source') { collection = this.draggableSources; } else { collection = this.draggableTargets; } for (i = 0; collection.length; i++) { if (collection[i].wrapperElement === node) { return collection[i].context.data.name; } } }; /** * Change to minimized view for operators */ GenericInterface.prototype.minimize = function minimize(omitEffects) { var position, oc, scrollX, scrollY; if (!omitEffects) { this.resizeTransitStart(); } this.initialPos = this.wrapperElement.getBoundingClientRect(); this.minWidth = this.wrapperElement.style.minWidth; this.wrapperElement.classList.add('reducedInt'); this.wrapperElement.style.minWidth = '55px'; // Scroll correction oc = this.wiringEditor.layout.getCenterContainer(); scrollX = parseInt(oc.wrapperElement.scrollLeft, 10); scrollY = parseInt(oc.wrapperElement.scrollTop, 10); this.wrapperElement.style.top = (this.initialPos.top + scrollY - this.wiringEditor.headerHeight) + ((this.initialPos.height - 8) / 2) - 12 + 'px'; this.wrapperElement.style.left = (this.initialPos.left + scrollX - this.wiringEditor.menubarWidth) + (this.initialPos.width / 2) - 32 + 'px'; // correct it pos if is out of grid position = this.getStylePosition(); if (position.posX < 0) { position.posX = 8; } if (position.posY < 0) { position.posY = 8; } this.setPosition(position); this.isMinimized = true; this.repaint(); }; /** * Change to normal view for operators */ GenericInterface.prototype.restore = function restore(omitEffects) { var currentPos, position, oc, scrollX, scrollY; if (!omitEffects) { this.resizeTransitStart(); } // Scroll correction oc = this.wiringEditor.layout.getCenterContainer(); scrollX = parseInt(oc.wrapperElement.scrollLeft, 10) + 1; scrollY = parseInt(oc.wrapperElement.scrollTop, 10); currentPos = this.wrapperElement.getBoundingClientRect(); this.wrapperElement.style.top = (currentPos.top + scrollY - this.wiringEditor.headerHeight) - ((this.initialPos.height + 8) / 2) + 'px'; this.wrapperElement.style.left = (currentPos.left + scrollX - this.wiringEditor.menubarWidth) - (this.initialPos.width / 2) + 32 + 'px'; // correct it position if is out of grid position = this.getStylePosition(); if (position.posX < 0) { position.posX = 8; } if (position.posY < 0) { position.posY = 8; } this.setPosition(position); this.wrapperElement.style.minWidth = this.minWidth; this.wrapperElement.classList.remove('reducedInt'); this.isMinimized = false; this.repaint(); }; /** * Resize Transit Start */ GenericInterface.prototype.resizeTransitStart = function resizeTransitStart() { var interval; // transition events this.wrapperElement.classList.add('flex'); /*this.wrapperElement.addEventListener('webkitTransitionEnd', this.resizeTransitEnd.bind(this), false); this.wrapperElement.addEventListener('transitionend', this.resizeTransitEnd.bind(this), false); this.wrapperElement.addEventListener('oTransitionEnd', this.resizeTransitEnd.bind(this), false);*/ interval = setInterval(this.animateArrows.bind(this), 20); setTimeout(function () { clearInterval(interval); }, 400); setTimeout(function () { this.resizeTransitEnd(); }.bind(this), 450); }; /** * Resize Transit End */ GenericInterface.prototype.resizeTransitEnd = function resizeTransitEnd() { // transition events this.wrapperElement.classList.remove('flex'); /*this.wrapperElement.removeEventListener('webkitTransitionEnd', this.resizeTransitEnd.bind(this), false); this.wrapperElement.removeEventListener('transitionend', this.resizeTransitEnd.bind(this), false); this.wrapperElement.removeEventListener('oTransitionEnd', this.resizeTransitEnd.bind(this), false);*/ this.repaint(); }; /** * Animated arrows for the transitions betwen minimized an normal shape */ GenericInterface.prototype.animateArrows = function animateArrows() { var key, layer; for (key in this.sourceAnchorsByName) { this.sourceAnchorsByName[key].repaint(); } for (key in this.targetAnchorsByName) { this.targetAnchorsByName[key].repaint(); } if (this.potentialArrow != null) { layer = this.wiringEditor.canvas.getHTMLElement().parentNode; if (this.potentialArrow.startAnchor != null) { // from source to target this.potentialArrow.setStart(this.potentialArrow.startAnchor.getCoordinates(layer)); } else { // from target to source this.potentialArrow.setEnd(this.potentialArrow.endAnchor.getCoordinates(layer)); } } }; /************************************************************************* * Make GenericInterface public *************************************************************************/ Wirecloud.ui.WiringEditor.GenericInterface = GenericInterface; })();
sixuanwang/SAMSaaS
wirecloud-develop/src/wirecloud/platform/static/js/wirecloud/ui/WiringEditor/GenericInterface.js
JavaScript
gpl-2.0
67,661
module.exports = { browserSync: { hostname: "localhost", port: 8080, openAutomatically: false, reloadDelay: 50 }, drush: { enabled: false, alias: 'drush @SITE-ALIAS cache-rebuild' }, twig: { useCache: true } };
erdfisch/DBCD16
web/themes/custom/dbcd_theme_base/example.config.js
JavaScript
gpl-2.0
253
package anon.psd.gui.activities; import android.content.ContextWrapper; import android.content.Intent; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.view.View; import android.widget.AdapterView; import com.nhaarman.listviewanimations.itemmanipulation.DynamicListView; import java.io.File; import anon.psd.R; import anon.psd.gui.activities.global.PSDActivity; import anon.psd.gui.adapters.PassItemsAdapter; import anon.psd.gui.exchange.ActivitiesExchange; import anon.psd.models.AppearancesList; import anon.psd.models.PasswordList; import anon.psd.models.gui.PrettyPassword; import anon.psd.storage.AppearanceCfg; import static anon.psd.utils.DebugUtils.Log; public class MainActivity extends PSDActivity implements SearchView.OnQueryTextListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener { DynamicListView lvPasses; File appearanceCfgFile; AppearancesList passes; PassItemsAdapter adapter; AppearanceCfg appearanceCfg; @Override public void passItemChanged() { adapter.notifyDataSetChanged(); } @Override public void onPassesInfo(PasswordList passesInfo) { checkOrUpdateAppearanceCfg(); passes = AppearancesList.Merge(passesInfo, appearanceCfg.getPassesAppearances()); bindAdapter(); } /** * Activity events */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log(this, "[ ACTIVITY ] [ CREATE ]"); setContentView(R.layout.activity_main); initVariables(); } @Override protected void onResume() { super.onResume(); checkOrUpdateAppearanceCfg(); //if (passes != null) // bindAdapter(); } private void initVariables() { //load path to appearance.cfg file appearanceCfgFile = new File(new ContextWrapper(this).getFilesDir().getPath(), "appearance.cfg"); //init passes list element lvPasses = (DynamicListView) findViewById(R.id.lvPassesList); lvPasses.setOnItemClickListener(this); lvPasses.setOnItemLongClickListener(this); //set default pic for passes PrettyPassword.setDefaultPic(BitmapFactory.decodeResource(getResources(), R.drawable.default_key_pic)); PrettyPassword.setPicsDir(new File(new ContextWrapper(this).getFilesDir().getPath(), "pics")); } /** * Search */ @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { return false; } /** * Items */ @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { PrettyPassword item = (PrettyPassword) (lvPasses).getAdapter().getItem(position); openItem(item); } public void openItem(PrettyPassword item) { ActivitiesExchange.addObject("PASSES", passes); ActivitiesExchange.addObject("ACTIVITIES_SERVICE_WORKER", serviceWorker); Intent intent = new Intent(getApplicationContext(), PassActivity.class); intent.putExtra("ID", item.getPassItem().getPsdId()); startActivity(intent); } @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { PrettyPassword selectedPassWrapper = (PrettyPassword) adapterView.getItemAtPosition(position); serviceWorker.sendPrettyPass(selectedPassWrapper); return true; } private void bindAdapter() { adapter = new PassItemsAdapter<>(this, android.R.layout.simple_list_item_1, passes); lvPasses.setAdapter(adapter); } private void checkOrUpdateAppearanceCfg() { //loading appearanceCfg appearanceCfg = new AppearanceCfg(appearanceCfgFile); AppearancesList prevPasses = ActivitiesExchange.getObject("PASSES"); if (prevPasses != null) appearanceCfg.setPassesAppearances(prevPasses); else appearanceCfg.update(); } @Override public void killService() { serviceWorker.killService(); } }
dc914337/PSD
PSD/app/src/main/java/anon/psd/gui/activities/MainActivity.java
Java
gpl-2.0
4,342
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe 'ValidatesTimeliness::ActionView::InstanceTag' do include ActionView::Helpers::DateHelper include ActionController::Assertions::SelectorAssertions before do @person = Person.new end def params @params ||= {} end describe "datetime_select" do it "should use param values when attribute is nil" do params["person"] = { "birth_date_and_time(1i)" => 2009, "birth_date_and_time(2i)" => 2, "birth_date_and_time(3i)" => 29, "birth_date_and_time(4i)" => 12, "birth_date_and_time(5i)" => 13, "birth_date_and_time(6i)" => 14, } @person.birth_date_and_time = nil output = datetime_select(:person, :birth_date_and_time, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_and_time_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_and_time_2i] option[selected=selected]', 'February') output.should have_tag('select[id=person_birth_date_and_time_3i] option[selected=selected]', '29') output.should have_tag('select[id=person_birth_date_and_time_4i] option[selected=selected]', '12') output.should have_tag('select[id=person_birth_date_and_time_5i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_date_and_time_6i] option[selected=selected]', '14') end it "should override object values and use params if present" do params["person"] = { "birth_date_and_time(1i)" => 2009, "birth_date_and_time(2i)" => 2, "birth_date_and_time(3i)" => 29, "birth_date_and_time(4i)" => 13, "birth_date_and_time(5i)" => 14, "birth_date_and_time(6i)" => 15, } @person.birth_date_and_time = "2009-03-01 13:14:15" output = datetime_select(:person, :birth_date_and_time, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_and_time_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_and_time_2i] option[selected=selected]', 'February') output.should have_tag('select[id=person_birth_date_and_time_3i] option[selected=selected]', '29') output.should have_tag('select[id=person_birth_date_and_time_4i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_date_and_time_5i] option[selected=selected]', '14') output.should have_tag('select[id=person_birth_date_and_time_6i] option[selected=selected]', '15') end it "should select attribute values from object if no params" do @person.birth_date_and_time = "2009-01-02 13:14:15" output = datetime_select(:person, :birth_date_and_time, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_and_time_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_and_time_2i] option[selected=selected]', 'January') output.should have_tag('select[id=person_birth_date_and_time_3i] option[selected=selected]', '2') output.should have_tag('select[id=person_birth_date_and_time_4i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_date_and_time_5i] option[selected=selected]', '14') output.should have_tag('select[id=person_birth_date_and_time_6i] option[selected=selected]', '15') end it "should select attribute values if params does not contain attribute params" do @person.birth_date_and_time = "2009-01-02 13:14:15" params["person"] = { } output = datetime_select(:person, :birth_date_and_time, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_and_time_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_and_time_2i] option[selected=selected]', 'January') output.should have_tag('select[id=person_birth_date_and_time_3i] option[selected=selected]', '2') output.should have_tag('select[id=person_birth_date_and_time_4i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_date_and_time_5i] option[selected=selected]', '14') output.should have_tag('select[id=person_birth_date_and_time_6i] option[selected=selected]', '15') end it "should not select values when attribute value is nil and has no param values" do @person.birth_date_and_time = nil output = datetime_select(:person, :birth_date_and_time, :include_blank => true, :include_seconds => true) output.should_not have_tag('select[id=person_birth_date_and_time_1i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_and_time_2i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_and_time_3i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_and_time_4i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_and_time_5i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_and_time_6i] option[selected=selected]') end end describe "date_select" do it "should use param values when attribute is nil" do params["person"] = { "birth_date(1i)" => 2009, "birth_date(2i)" => 2, "birth_date(3i)" => 29, } @person.birth_date = nil output = date_select(:person, :birth_date, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_2i] option[selected=selected]', 'February') output.should have_tag('select[id=person_birth_date_3i] option[selected=selected]', '29') end it "should override object values and use params if present" do params["person"] = { "birth_date(1i)" => 2009, "birth_date(2i)" => 2, "birth_date(3i)" => 29, } @person.birth_date = "2009-03-01" output = date_select(:person, :birth_date, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_2i] option[selected=selected]', 'February') output.should have_tag('select[id=person_birth_date_3i] option[selected=selected]', '29') end it "should select attribute values from object if no params" do @person.birth_date = "2009-01-02" output = date_select(:person, :birth_date, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_2i] option[selected=selected]', 'January') output.should have_tag('select[id=person_birth_date_3i] option[selected=selected]', '2') end it "should select attribute values if params does not contain attribute params" do @person.birth_date = "2009-01-02" params["person"] = { } output = date_select(:person, :birth_date, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_2i] option[selected=selected]', 'January') output.should have_tag('select[id=person_birth_date_3i] option[selected=selected]', '2') end it "should not select values when attribute value is nil and has no param values" do @person.birth_date = nil output = date_select(:person, :birth_date, :include_blank => true, :include_seconds => true) output.should_not have_tag('select[id=person_birth_date_1i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_2i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_3i] option[selected=selected]') end end describe "time_select" do before :all do Time.now = Time.mktime(2009,1,1) end it "should use param values when attribute is nil" do params["person"] = { "birth_time(1i)" => 2000, "birth_time(2i)" => 1, "birth_time(3i)" => 1, "birth_time(4i)" => 12, "birth_time(5i)" => 13, "birth_time(6i)" => 14, } @person.birth_time = nil output = time_select(:person, :birth_time, :include_blank => true, :include_seconds => true) output.should have_tag('input[id=person_birth_time_1i][value=2000]') output.should have_tag('input[id=person_birth_time_2i][value=1]') output.should have_tag('input[id=person_birth_time_3i][value=1]') output.should have_tag('select[id=person_birth_time_4i] option[selected=selected]', '12') output.should have_tag('select[id=person_birth_time_5i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_time_6i] option[selected=selected]', '14') end it "should select attribute values from object if no params" do @person.birth_time = "13:14:15" output = time_select(:person, :birth_time, :include_blank => true, :include_seconds => true) output.should have_tag('input[id=person_birth_time_1i][value=2000]') output.should have_tag('input[id=person_birth_time_2i][value=1]') output.should have_tag('input[id=person_birth_time_3i][value=1]') output.should have_tag('select[id=person_birth_time_4i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_time_5i] option[selected=selected]', '14') output.should have_tag('select[id=person_birth_time_6i] option[selected=selected]', '15') end it "should not select values when attribute value is nil and has no param values" do @person.birth_time = nil output = time_select(:person, :birth_time, :include_blank => true, :include_seconds => true) output.should have_tag('input[id=person_birth_time_1i][value=""]') # Annoyingly these may or not have value attribute depending on rails version. # output.should have_tag('input[id=person_birth_time_2i][value=""]') # output.should have_tag('input[id=person_birth_time_3i][value=""]') output.should_not have_tag('select[id=person_birth_time_4i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_time_5i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_time_6i] option[selected=selected]') end after :all do Time.now = nil end end end
valdas-s/sandelys2
vendor/plugins/validates_timeliness/spec/action_view/instance_tag_spec.rb
Ruby
gpl-2.0
10,844
/* * Copyright (C) 2012 Samsung Electronics * * 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 "config.h" #include "NavigatorVibration.h" #if ENABLE(VIBRATION) #include "Frame.h" #include "Navigator.h" #include "Page.h" #include "Vibration.h" #include <runtime/Uint32Array.h> namespace WebCore { NavigatorVibration::NavigatorVibration() { } NavigatorVibration::~NavigatorVibration() { } bool NavigatorVibration::vibrate(Navigator& navigator, unsigned time) { return NavigatorVibration::vibrate(navigator, VibrationPattern(1, time)); } bool NavigatorVibration::vibrate(Navigator& navigator, const VibrationPattern& pattern) { if (!navigator.frame()->page()) return false; if (navigator.frame()->page()->visibilityState() == PageVisibilityState::Hidden) return false; return Vibration::from(navigator.frame()->page())->vibrate(pattern); } } // namespace WebCore #endif // ENABLE(VIBRATION)
Debian/openjfx
modules/web/src/main/native/Source/WebCore/Modules/vibration/NavigatorVibration.cpp
C++
gpl-2.0
1,684
<?php /** * Theme Customizer */ function presentation_lite_customize_register( $wp_customize ) { /** =============== * Extends CONTROLS class to add textarea */ class presentation_lite_customize_textarea_control extends WP_Customize_Control { public $type = 'textarea'; public function render_content() { ?> <label> <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span> <textarea rows="5" style="width:98%;" <?php $this->link(); ?>><?php echo esc_textarea( $this->value() ); ?></textarea> </label> <?php } } /** =============== * Site Title (Logo) & Tagline */ // section adjustments $wp_customize->get_section( 'title_tagline' )->title = __( 'Site Title (Logo) & Tagline', 'presentation_lite' ); $wp_customize->get_section( 'title_tagline' )->priority = 10; //site title $wp_customize->get_control( 'blogname' )->priority = 10; $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; // tagline $wp_customize->get_control( 'blogdescription' )->priority = 30; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; // logo uploader $wp_customize->add_setting( 'presentation_lite_logo', array( 'default' => null ) ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'presentation_lite_logo', array( 'label' => __( 'Custom Site Logo (replaces title)', 'presentation_lite' ), 'section' => 'title_tagline', 'settings' => 'presentation_lite_logo', 'priority' => 20 ) ) ); /** =============== * Presentation Lite Design Options */ $wp_customize->add_section( 'presentation_lite_style_section', array( 'title' => __( 'Design Options', 'presentation_lite' ), 'description' => __( 'Choose a color scheme for Presentation Lite. Individual styles can be overwritten in your child theme stylesheet.', 'presentation_lite' ), 'priority' => 25, ) ); $wp_customize->add_setting( 'presentation_lite_stylesheet', array( 'default' => 'blue', 'sanitize_callback' => 'presentation_lite_sanitize_stylesheet' ) ); $wp_customize->add_control( 'presentation_lite_stylesheet', array( 'type' => 'select', 'label' => __( 'Choose a color scheme:', 'presentation_lite' ), 'section' => 'presentation_lite_style_section', 'choices' => array( 'blue' => 'Blue', 'purple' => 'Purple', 'red' => 'Red', 'gray' => 'Gray' ) ) ); /** =============== * Content Options */ $wp_customize->add_section( 'presentation_lite_content_section', array( 'title' => __( 'Content Options', 'presentation_lite' ), 'description' => __( 'Adjust the display of content on your website. All options have a default value that can be left as-is but you are free to customize.', 'presentation_lite' ), 'priority' => 20, ) ); // post content $wp_customize->add_setting( 'presentation_lite_post_content', array( 'default' => 'full_content', 'sanitize_callback' => 'presentation_lite_sanitize_radio' ) ); $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'presentation_lite_post_content', array( 'label' => __( 'Post Feed Content', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'settings' => 'presentation_lite_post_content', 'priority' => 10, 'type' => 'radio', 'choices' => array( 'excerpt' => 'Excerpt', 'full_content' => 'Full Content' ), ) ) ); // show single post footer? $wp_customize->add_setting( 'presentation_lite_post_footer', array( 'default' => 1, 'sanitize_callback' => 'presentation_lite_sanitize_checkbox' ) ); $wp_customize->add_control( 'presentation_lite_post_footer', array( 'label' => __( 'Show Post Footer on Single Posts?', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'priority' => 50, 'type' => 'checkbox', ) ); // twitter url $wp_customize->add_setting( 'presentation_lite_twitter', array( 'default' => null, 'sanitize_callback' => 'presentation_lite_sanitize_text' ) ); $wp_customize->add_control( 'presentation_lite_twitter', array( 'label' => __( 'Twitter Profile URL', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'settings' => 'presentation_lite_twitter', 'priority' => 80, ) ); // facebook url $wp_customize->add_setting( 'presentation_lite_facebook', array( 'default' => null, 'sanitize_callback' => 'presentation_lite_sanitize_text' ) ); $wp_customize->add_control( 'presentation_lite_facebook', array( 'label' => __( 'Facebook Profile URL', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'settings' => 'presentation_lite_facebook', 'priority' => 90, ) ); // google plus url $wp_customize->add_setting( 'presentation_lite_gplus', array( 'default' => null, 'sanitize_callback' => 'presentation_lite_sanitize_text' ) ); $wp_customize->add_control( 'presentation_lite_gplus', array( 'label' => __( 'Google Plus Profile URL', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'settings' => 'presentation_lite_gplus', 'priority' => 100, ) ); // linkedin url $wp_customize->add_setting( 'presentation_lite_linkedin', array( 'default' => null, 'sanitize_callback' => 'presentation_lite_sanitize_text' ) ); $wp_customize->add_control( 'presentation_lite_linkedin', array( 'label' => __( 'LinkedIn Profile URL', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'settings' => 'presentation_lite_linkedin', 'priority' => 110, ) ); /** =============== * Navigation Menu(s) */ // section adjustments $wp_customize->get_section( 'nav' )->title = __( 'Navigation Menu(s)', 'presentation_lite' ); $wp_customize->get_section( 'nav' )->priority = 40; /** =============== * Static Front Page */ // section adjustments $wp_customize->get_section( 'static_front_page' )->priority = 50; } add_action( 'customize_register', 'presentation_lite_customize_register' ); /** =============== * Sanitize the theme design select option */ function presentation_lite_sanitize_stylesheet( $input ) { $valid = array( 'blue' => 'Blue', 'purple' => 'Purple', 'red' => 'Red', 'gray' => 'Gray' ); if ( array_key_exists( $input, $valid ) ) { return $input; } else { return ''; } } /** =============== * Sanitize checkbox options */ function presentation_lite_sanitize_checkbox( $input ) { if ( $input == 1 ) { return 1; } else { return 0; } } /** =============== * Sanitize radio options */ function presentation_lite_sanitize_radio( $input ) { $valid = array( 'excerpt' => 'Excerpt', 'full_content' => 'Full Content' ); if ( array_key_exists( $input, $valid ) ) { return $input; } else { return ''; } } /** =============== * Sanitize text input */ function presentation_lite_sanitize_text( $input ) { return strip_tags( stripslashes( $input ) ); } /** =============== * Add Customizer UI styles to the <head> only on Customizer page */ function presentation_lite_customizer_styles() { ?> <style type="text/css"> body { background: #fff; } #customize-controls #customize-theme-controls .description { display: block; color: #999; margin: 2px 0 15px; font-style: italic; } textarea, input, select, .customize-description { font-size: 12px !important; } .customize-control-title { font-size: 13px !important; margin: 10px 0 3px !important; } .customize-control label { font-size: 12px !important; } </style> <?php } add_action('customize_controls_print_styles', 'presentation_lite_customizer_styles'); /** * Binds JS handlers to make Theme Customizer preview reload changes asynchronously. */ function presentation_lite_customize_preview_js() { wp_enqueue_script( 'presentation_lite_customizer', get_template_directory_uri() . '/inc/js/customizer.js', array( 'customize-preview' ), '20130508', true ); } add_action( 'customize_preview_init', 'presentation_lite_customize_preview_js' );
mihaienescu1/wp_wmihu
wp-content/themes/presentation-lite/inc/customizer.php
PHP
gpl-2.0
8,069
<?php /** * @version $Id$ * @package Joomla.Administrator * @subpackage JoomDOC * @author ARTIO s.r.o., info@artio.net, http:://www.artio.net * @copyright Copyright (C) 2011 Artio s.r.o.. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die(); include_once(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_joomdoc' . DS . 'defines.php'); class JElementIcons extends JElement { var $_name = 'Icons'; function fetchElement ($name, $value, &$node, $control_name) { $field = JText::_('JOOMDOC_ICON_THEME_NOT_AVAILABLE'); if (JFolder::exists(JOOMDOC_PATH_ICONS)) { $themes = JFolder::folders(JOOMDOC_PATH_ICONS, '.', false, false); foreach ($themes as $theme) $options[] = JHtml::_('select.option', $theme, $theme, 'id', 'title'); if (isset($options)) { $fieldName = $control_name ? $control_name . '[' . $name . ']' : $name; $field = JHtml::_('select.genericlist', $options, $fieldName, '', 'id', 'title', $value); } } return $field; } } ?>
berkeley-amsa/past-site
administrator/tmp/install_4e65459e58fe3/admin/elements/icons.php
PHP
gpl-2.0
1,170
/* Adept MobileRobots Robotics Interface for Applications (ARIA) Copyright (C) 2004-2005 ActivMedia Robotics LLC Copyright (C) 2006-2010 MobileRobots Inc. Copyright (C) 2011-2014 Adept Technology 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 If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at robots@mobilerobots.com or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960 */ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.40 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.mobilerobots.Aria; public class ArJoyVec3f { /* (begin code from javabody typemap) */ private long swigCPtr; protected boolean swigCMemOwn; /* for internal use by swig only */ public ArJoyVec3f(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } /* for internal use by swig only */ public static long getCPtr(ArJoyVec3f obj) { return (obj == null) ? 0 : obj.swigCPtr; } /* (end code from javabody typemap) */ protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; AriaJavaJNI.delete_ArJoyVec3f(swigCPtr); } swigCPtr = 0; } } public void setX(double value) { AriaJavaJNI.ArJoyVec3f_x_set(swigCPtr, this, value); } public double getX() { return AriaJavaJNI.ArJoyVec3f_x_get(swigCPtr, this); } public void setY(double value) { AriaJavaJNI.ArJoyVec3f_y_set(swigCPtr, this, value); } public double getY() { return AriaJavaJNI.ArJoyVec3f_y_get(swigCPtr, this); } public void setZ(double value) { AriaJavaJNI.ArJoyVec3f_z_set(swigCPtr, this, value); } public double getZ() { return AriaJavaJNI.ArJoyVec3f_z_get(swigCPtr, this); } public ArJoyVec3f() { this(AriaJavaJNI.new_ArJoyVec3f(), true); } }
lakid/libaria
java/com/mobilerobots/Aria/ArJoyVec3f.java
Java
gpl-2.0
2,914
/* Copyright (c) 2002-2011 by XMLVM.org * * Project Info: http://www.xmlvm.org * * This program 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 Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ package org.xmlvm.iphone; import org.xmlvm.XMLVMSkeletonOnly; @XMLVMSkeletonOnly public abstract class SKRequest extends NSObject { private SKRequestDelegate delegate; public void start() { } public void cancel() { } public SKRequestDelegate getDelegate() { return delegate; } public void setDelegate(SKRequestDelegate delegate) { this.delegate = delegate; } }
skyHALud/codenameone
Ports/iOSPort/xmlvm/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/SKRequest.java
Java
gpl-2.0
1,255
<?php /** * @copyright Ilch 2.0 * @package ilch */ namespace Modules\Sample\Models; class Sample extends \Ilch\Model { }
Saarlonz/Ilch-2.0
application/modules/sample/models/Sample.php
PHP
gpl-2.0
126
<?php /* +---------------------------------------------------------------------------+ | OpenX v2.8 | | ========== | | | | Copyright (c) 2003-2009 OpenX Limited | | For contact details, see: http://www.openx.org/ | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by | | the Free Software Foundation; either version 2 of the License, or | | (at your option) any later version. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | | | | You should have received a copy of the GNU General Public License | | along with this program; if not, write to the Free Software | | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | +---------------------------------------------------------------------------+ $Id: template.php 79311 2011-11-03 21:18:14Z chris.nutting $ */ /** * * This is autogenerated merged delivery file which contains all files * from delivery merged into one output file. * * !!!Warning!!! * * Do not edit this file. If you need to do any changes to any delivery PHP file * checkout sourcecode from the svn repository, do a necessary changes inside * "delivery_dev" folder and regenerate delivery files using command: * # php rebuild.php * * For more information on ant generator or if you want to check why we do this * check out the documentation wiki page: * https://developer.openx.org/wiki/display/COMM/Using+Ant#UsingAnt-Generatingoptimizeddelivery * */ function parseDeliveryIniFile($configPath = null, $configFile = null, $sections = true) { if (!$configPath) { $configPath = MAX_PATH . '/var'; } if ($configFile) { $configFile = '.' . $configFile; } $host = OX_getHostName(); $configFileName = $configPath . '/' . $host . $configFile . '.conf.php'; $conf = @parse_ini_file($configFileName, $sections); if (isset($conf['realConfig'])) { $realconf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections); $conf = mergeConfigFiles($realconf, $conf); } if (!empty($conf)) { return $conf; } elseif ($configFile === '.plugin') { $pluginType = basename($configPath); $defaultConfig = MAX_PATH . '/plugins/' . $pluginType . '/default.plugin.conf.php'; $conf = @parse_ini_file($defaultConfig, $sections); if ($conf !== false) { return $conf; } echo "OpenX could not read the default configuration file for the {$pluginType} plugin"; exit(1); } $configFileName = $configPath . '/default' . $configFile . '.conf.php'; $conf = @parse_ini_file($configFileName, $sections); if (isset($conf['realConfig'])) { $conf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections); } if (!empty($conf)) { return $conf; } if (file_exists(MAX_PATH . '/var/INSTALLED')) { echo "OpenX has been installed, but no configuration file was found.\n"; exit(1); } echo "OpenX has not been installed yet -- please read the INSTALL.txt file.\n"; exit(1); } if (!function_exists('mergeConfigFiles')) { function mergeConfigFiles($realConfig, $fakeConfig) { foreach ($fakeConfig as $key => $value) { if (is_array($value)) { if (!isset($realConfig[$key])) { $realConfig[$key] = array(); } $realConfig[$key] = mergeConfigFiles($realConfig[$key], $value); } else { if (isset($realConfig[$key]) && is_array($realConfig[$key])) { $realConfig[$key][0] = $value; } else { if (isset($realConfig) && !is_array($realConfig)) { $temp = $realConfig; $realConfig = array(); $realConfig[0] = $temp; } $realConfig[$key] = $value; } } } unset($realConfig['realConfig']); return $realConfig; } } function OX_getMinimumRequiredMemory($limit = null) { if ($limit == 'maintenance') { return 134217728; } return 134217728; } function OX_getMemoryLimitSizeInBytes() { $phpMemoryLimit = ini_get('memory_limit'); if (empty($phpMemoryLimit) || $phpMemoryLimit == -1) { return -1; } $aSize = array( 'G' => 1073741824, 'M' => 1048576, 'K' => 1024 ); $phpMemoryLimitInBytes = $phpMemoryLimit; foreach($aSize as $type => $multiplier) { $pos = strpos($phpMemoryLimit, $type); if (!$pos) { $pos = strpos($phpMemoryLimit, strtolower($type)); } if ($pos) { $phpMemoryLimitInBytes = substr($phpMemoryLimit, 0, $pos) * $multiplier; } } return $phpMemoryLimitInBytes; } function OX_checkMemoryCanBeSet() { $phpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes(); if ($phpMemoryLimitInBytes == -1) { return true; } OX_increaseMemoryLimit($phpMemoryLimitInBytes + 1); $newPhpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes(); $memoryCanBeSet = ($phpMemoryLimitInBytes != $newPhpMemoryLimitInBytes); @ini_set('memory_limit', $phpMemoryLimitInBytes); return $memoryCanBeSet; } function OX_increaseMemoryLimit($setMemory) { $phpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes(); if ($phpMemoryLimitInBytes == -1) { return true; } if ($setMemory > $phpMemoryLimitInBytes) { if (@ini_set('memory_limit', $setMemory) === false) { return false; } } return true; } function setupConfigVariables() { $GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'] = '|'; $GLOBALS['_MAX']['MAX_COOKIELESS_PREFIX'] = '__'; $GLOBALS['_MAX']['thread_id'] = uniqid(); $GLOBALS['_MAX']['SSL_REQUEST'] = false; if ( (!empty($_SERVER['SERVER_PORT']) && ($_SERVER['SERVER_PORT'] == $GLOBALS['_MAX']['CONF']['openads']['sslPort'])) || (!empty($_SERVER['HTTPS']) && ((strtolower($_SERVER['HTTPS']) == 'on') || ($_SERVER['HTTPS'] == 1))) || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && (strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https')) || (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && (strtolower($_SERVER['HTTP_X_FORWARDED_SSL']) == 'on')) || (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && (strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) == 'on')) || (!empty($_SERVER['FRONT-END-HTTPS']) && (strtolower($_SERVER['FRONT-END-HTTPS']) == 'on')) ) { $GLOBALS['_MAX']['SSL_REQUEST'] = true; } $GLOBALS['_MAX']['MAX_RAND'] = isset($GLOBALS['_MAX']['CONF']['priority']['randmax']) ? $GLOBALS['_MAX']['CONF']['priority']['randmax'] : 2147483647; list($micro_seconds, $seconds) = explode(" ", microtime()); $GLOBALS['_MAX']['NOW_ms'] = round(1000 *((float)$micro_seconds + (float)$seconds)); if (substr($_SERVER['SCRIPT_NAME'], -11) != 'install.php') { $GLOBALS['serverTimezone'] = date_default_timezone_get(); OA_setTimeZoneUTC(); } } function setupServerVariables() { if (empty($_SERVER['REQUEST_URI'])) { $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME']; if (!empty($_SERVER['QUERY_STRING'])) { $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING']; } } } function setupDeliveryConfigVariables() { if (!defined('MAX_PATH')) { define('MAX_PATH', dirname(__FILE__).'/../..'); } if (!defined('OX_PATH')) { define('OX_PATH', MAX_PATH); } if (!defined('LIB_PATH')) { define('LIB_PATH', MAX_PATH. DIRECTORY_SEPARATOR. 'lib'. DIRECTORY_SEPARATOR. 'OX'); } if ( !(isset($GLOBALS['_MAX']['CONF']))) { $GLOBALS['_MAX']['CONF'] = parseDeliveryIniFile(); } setupConfigVariables(); } function OA_setTimeZone($timezone) { date_default_timezone_set($timezone); $GLOBALS['_DATE_TIMEZONE_DEFAULT'] = $timezone; } function OA_setTimeZoneUTC() { OA_setTimeZone('UTC'); } function OA_setTimeZoneLocal() { $tz = !empty($GLOBALS['_MAX']['PREF']['timezone']) ? $GLOBALS['_MAX']['PREF']['timezone'] : 'GMT'; OA_setTimeZone($tz); } function OX_getHostName() { if (!empty($_SERVER['HTTP_HOST'])) { $host = explode(':', $_SERVER['HTTP_HOST']); $host = $host[0]; } else if (!empty($_SERVER['SERVER_NAME'])) { $host = explode(':', $_SERVER['SERVER_NAME']); $host = $host[0]; } return $host; } function OX_getHostNameWithPort() { if (!empty($_SERVER['HTTP_HOST'])) { $host = $_SERVER['HTTP_HOST']; } else if (!empty($_SERVER['SERVER_NAME'])) { $host = $_SERVER['SERVER_NAME']; } return $host; } function setupIncludePath() { static $checkIfAlreadySet; if (isset($checkIfAlreadySet)) { return; } $checkIfAlreadySet = true; $oxPearPath = MAX_PATH . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'pear'; $oxZendPath = MAX_PATH . DIRECTORY_SEPARATOR . 'lib'; set_include_path($oxPearPath . PATH_SEPARATOR . $oxZendPath . PATH_SEPARATOR . get_include_path()); } OX_increaseMemoryLimit(OX_getMinimumRequiredMemory()); if (!defined('E_DEPRECATED')) { define('E_DEPRECATED', 0); } setupServerVariables(); setupDeliveryConfigVariables(); $conf = $GLOBALS['_MAX']['CONF']; $GLOBALS['_OA']['invocationType'] = array_search(basename($_SERVER['SCRIPT_FILENAME']), $conf['file']); if (!empty($conf['debug']['production'])) { error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED); } else { error_reporting(E_ALL ^ E_DEPRECATED); } $file = '/lib/max/Delivery/common.php'; $GLOBALS['_MAX']['FILES'][$file] = true; $file = '/lib/max/Delivery/cookie.php'; $GLOBALS['_MAX']['FILES'][$file] = true; $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'] = array(); if (!is_callable('MAX_cookieSet')) { if (!empty($conf['cookie']['plugin']) && is_readable(MAX_PATH . "/plugins/cookieStorage/{$conf['cookie']['plugin']}.delivery.php")) { include MAX_PATH . "/plugins/cookieStorage/{$conf['cookie']['plugin']}.delivery.php"; } else { function MAX_cookieSet($name, $value, $expire, $path = '/', $domain = null) { return MAX_cookieClientCookieSet($name, $value, $expire, $path, $domain); } function MAX_cookieUnset($name) { return MAX_cookieClientCookieUnset($name); } function MAX_cookieFlush() { return MAX_cookieClientCookieFlush(); } function MAX_cookieLoad() { return true; } } } function MAX_cookieAdd($name, $value, $expire = 0) { if (!isset($GLOBALS['_MAX']['COOKIE']['CACHE'])) { $GLOBALS['_MAX']['COOKIE']['CACHE'] = array(); } $GLOBALS['_MAX']['COOKIE']['CACHE'][$name] = array($value, $expire); } function MAX_cookieSetViewerIdAndRedirect($viewerId) { $aConf = $GLOBALS['_MAX']['CONF']; MAX_cookieAdd($aConf['var']['viewerId'], $viewerId, _getTimeYearFromNow()); MAX_cookieFlush(); if ($GLOBALS['_MAX']['SSL_REQUEST']) { $url = MAX_commonConstructSecureDeliveryUrl(basename($_SERVER['SCRIPT_NAME'])); } else { $url = MAX_commonConstructDeliveryUrl(basename($_SERVER['SCRIPT_NAME'])); } $url .= "?{$aConf['var']['cookieTest']}=1&" . $_SERVER['QUERY_STRING']; MAX_header("Location: {$url}"); exit; } function _getTimeThirtyDaysFromNow() { return MAX_commonGetTimeNow() + 2592000; } function _getTimeYearFromNow() { return MAX_commonGetTimeNow() + 31536000; } function _getTimeYearAgo() { return MAX_commonGetTimeNow() - 31536000; } function MAX_cookieUnpackCapping() { $conf = $GLOBALS['_MAX']['CONF']; $cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames']; if (!is_array($cookieNames)) return; foreach ($cookieNames as $cookieName) { if (!empty($_COOKIE[$cookieName])) { if (!is_array($_COOKIE[$cookieName])) { $output = array(); $data = explode('_', $_COOKIE[$cookieName]); foreach ($data as $pair) { list($name, $value) = explode('.', $pair); $output[$name] = $value; } $_COOKIE[$cookieName] = $output; } } if (!empty($_COOKIE['_' . $cookieName]) && is_array($_COOKIE['_' . $cookieName])) { foreach ($_COOKIE['_' . $cookieName] as $adId => $cookie) { if (_isBlockCookie($cookieName)) { $_COOKIE[$cookieName][$adId] = $cookie; } else { if (isset($_COOKIE[$cookieName][$adId])) { $_COOKIE[$cookieName][$adId] += $cookie; } else { $_COOKIE[$cookieName][$adId] = $cookie; } } MAX_cookieUnset("_{$cookieName}[{$adId}]"); } } } } function _isBlockCookie($cookieName) { return in_array($cookieName, array( $GLOBALS['_MAX']['CONF']['var']['blockAd'], $GLOBALS['_MAX']['CONF']['var']['blockCampaign'], $GLOBALS['_MAX']['CONF']['var']['blockZone'], $GLOBALS['_MAX']['CONF']['var']['lastView'], $GLOBALS['_MAX']['CONF']['var']['lastClick'], $GLOBALS['_MAX']['CONF']['var']['blockLoggingClick'], )); } function MAX_cookieGetUniqueViewerId($create = true) { static $uniqueViewerId = null; if(!is_null($uniqueViewerId)) { return $uniqueViewerId; } $conf = $GLOBALS['_MAX']['CONF']; if (isset($_COOKIE[$conf['var']['viewerId']])) { $uniqueViewerId = $_COOKIE[$conf['var']['viewerId']]; } elseif ($create) { $uniqueViewerId = md5(uniqid('', true)); $GLOBALS['_MAX']['COOKIE']['newViewerId'] = true; } return $uniqueViewerId; } function MAX_cookieGetCookielessViewerID() { if (empty($_SERVER['REMOTE_ADDR']) || empty($_SERVER['HTTP_USER_AGENT'])) { return ''; } $cookiePrefix = $GLOBALS['_MAX']['MAX_COOKIELESS_PREFIX']; return $cookiePrefix . substr(md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']), 0, 32-(strlen($cookiePrefix))); } function MAX_Delivery_cookie_cappingOnRequest() { if (isset($GLOBALS['_OA']['invocationType']) && ($GLOBALS['_OA']['invocationType'] == 'xmlrpc' || $GLOBALS['_OA']['invocationType'] == 'view') ) { return true; } return !$GLOBALS['_MAX']['CONF']['logging']['adImpressions']; } function MAX_Delivery_cookie_setCapping($type, $id, $block = 0, $cap = 0, $sessionCap = 0) { $conf = $GLOBALS['_MAX']['CONF']; $setBlock = false; if ($cap > 0) { $expire = MAX_commonGetTimeNow() + $conf['cookie']['permCookieSeconds']; if (!isset($_COOKIE[$conf['var']['cap' . $type]][$id])) { $value = 1; $setBlock = true; } else if ($_COOKIE[$conf['var']['cap' . $type]][$id] >= $cap) { $value = -$_COOKIE[$conf['var']['cap' . $type]][$id]+1; $setBlock = true; } else { $value = 1; } MAX_cookieAdd("_{$conf['var']['cap' . $type]}[{$id}]", $value, $expire); } if ($sessionCap > 0) { if (!isset($_COOKIE[$conf['var']['sessionCap' . $type]][$id])) { $value = 1; $setBlock = true; } else if ($_COOKIE[$conf['var']['sessionCap' . $type]][$id] >= $sessionCap) { $value = -$_COOKIE[$conf['var']['sessionCap' . $type]][$id]+1; $setBlock = true; } else { $value = 1; } MAX_cookieAdd("_{$conf['var']['sessionCap' . $type]}[{$id}]", $value, 0); } if ($block > 0 || $setBlock) { MAX_cookieAdd("_{$conf['var']['block' . $type]}[{$id}]", MAX_commonGetTimeNow(), _getTimeThirtyDaysFromNow()); } } function MAX_cookieClientCookieSet($name, $value, $expire, $path = '/', $domain = null) { if (isset($GLOBALS['_OA']['invocationType']) && $GLOBALS['_OA']['invocationType'] == 'xmlrpc') { if (!isset($GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'])) { $GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'] = array(); } $GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'][$name] = array($value, $expire); } else { @setcookie($name, $value, $expire, $path, $domain); } } function MAX_cookieClientCookieUnset($name) { $conf = $GLOBALS['_MAX']['CONF']; $domain = (!empty($conf['cookie']['domain'])) ? $conf['cookie']['domain'] : null; MAX_cookieSet($name, false, _getTimeYearAgo(), '/', $domain); MAX_cookieSet(str_replace('_', '%5F', urlencode($name)), false, _getTimeYearAgo(), '/', $domain); } function MAX_cookieClientCookieFlush() { $conf = $GLOBALS['_MAX']['CONF']; MAX_cookieSendP3PHeaders(); if (!empty($GLOBALS['_MAX']['COOKIE']['CACHE'])) { reset($GLOBALS['_MAX']['COOKIE']['CACHE']); while (list($name,$v) = each ($GLOBALS['_MAX']['COOKIE']['CACHE'])) { list($value, $expire) = $v; if ($name == $conf['var']['viewerId']) { MAX_cookieClientCookieSet($name, $value, $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null)); } else { MAX_cookieSet($name, $value, $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null)); } } $GLOBALS['_MAX']['COOKIE']['CACHE'] = array(); } $cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames']; if (!is_array($cookieNames)) return; $maxCookieSize = !empty($conf['cookie']['maxCookieSize']) ? $conf['cookie']['maxCookieSize'] : 2048; foreach ($cookieNames as $cookieName) { if (empty($_COOKIE["_{$cookieName}"])) { continue; } switch ($cookieName) { case $conf['var']['blockAd'] : case $conf['var']['blockCampaign'] : case $conf['var']['blockZone'] : $expire = _getTimeThirtyDaysFromNow(); break; case $conf['var']['lastClick'] : case $conf['var']['lastView'] : case $conf['var']['capAd'] : case $conf['var']['capCampaign'] : case $conf['var']['capZone'] : $expire = _getTimeYearFromNow(); break; case $conf['var']['sessionCapCampaign'] : case $conf['var']['sessionCapAd'] : case $conf['var']['sessionCapZone'] : $expire = 0; break; } if (!empty($_COOKIE[$cookieName]) && is_array($_COOKIE[$cookieName])) { $data = array(); foreach ($_COOKIE[$cookieName] as $adId => $value) { $data[] = "{$adId}.{$value}"; } while (strlen(implode('_', $data)) > $maxCookieSize) { $data = array_slice($data, 1); } MAX_cookieSet($cookieName, implode('_', $data), $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null)); } } } function MAX_cookieSendP3PHeaders() { if ($GLOBALS['_MAX']['CONF']['p3p']['policies']) { MAX_header("P3P: ". _generateP3PHeader()); } } function _generateP3PHeader() { $conf = $GLOBALS['_MAX']['CONF']; $p3p_header = ''; if ($conf['p3p']['policies']) { if ($conf['p3p']['policyLocation'] != '') { $p3p_header .= " policyref=\"".$conf['p3p']['policyLocation']."\""; } if ($conf['p3p']['policyLocation'] != '' && $conf['p3p']['compactPolicy'] != '') { $p3p_header .= ", "; } if ($conf['p3p']['compactPolicy'] != '') { $p3p_header .= " CP=\"".$conf['p3p']['compactPolicy']."\""; } } return $p3p_header; } $file = '/lib/max/Delivery/remotehost.php'; $GLOBALS['_MAX']['FILES'][$file] = true; function MAX_remotehostSetInfo($run = false) { if (empty($GLOBALS['_OA']['invocationType']) || $run || ($GLOBALS['_OA']['invocationType'] != 'xmlrpc')) { MAX_remotehostProxyLookup(); MAX_remotehostReverseLookup(); MAX_remotehostSetGeoInfo(); } } function MAX_remotehostProxyLookup() { $conf = $GLOBALS['_MAX']['CONF']; if ($conf['logging']['proxyLookup']) { OX_Delivery_logMessage('checking remote host proxy', 7); $proxy = false; if (!empty($_SERVER['HTTP_VIA']) || !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $proxy = true; } elseif (!empty($_SERVER['REMOTE_HOST'])) { $aProxyHosts = array( 'proxy', 'cache', 'inktomi' ); foreach ($aProxyHosts as $proxyName) { if (strpos($_SERVER['REMOTE_HOST'], $proxyName) !== false) { $proxy = true; break; } } } if ($proxy) { OX_Delivery_logMessage('proxy detected', 7); $aHeaders = array( 'HTTP_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP' ); foreach ($aHeaders as $header) { if (!empty($_SERVER[$header])) { $ip = $_SERVER[$header]; break; } } if (!empty($ip)) { foreach (explode(',', $ip) as $ip) { $ip = trim($ip); if (($ip != 'unknown') && (!MAX_remotehostPrivateAddress($ip))) { $_SERVER['REMOTE_ADDR'] = $ip; $_SERVER['REMOTE_HOST'] = ''; $_SERVER['HTTP_VIA'] = ''; OX_Delivery_logMessage('real address set to '.$ip, 7); break; } } } } } } function MAX_remotehostReverseLookup() { if (empty($_SERVER['REMOTE_HOST'])) { if ($GLOBALS['_MAX']['CONF']['logging']['reverseLookup']) { $_SERVER['REMOTE_HOST'] = @gethostbyaddr($_SERVER['REMOTE_ADDR']); } else { $_SERVER['REMOTE_HOST'] = $_SERVER['REMOTE_ADDR']; } } } function MAX_remotehostSetGeoInfo() { if (!function_exists('parseDeliveryIniFile')) { } $aConf = $GLOBALS['_MAX']['CONF']; $type = (!empty($aConf['geotargeting']['type'])) ? $aConf['geotargeting']['type'] : null; if (!is_null($type) && $type != 'none') { $aComponent = explode(':', $aConf['geotargeting']['type']); if (!empty($aComponent[1]) && (!empty($aConf['pluginGroupComponents'][$aComponent[1]]))) { $GLOBALS['_MAX']['CLIENT_GEO'] = OX_Delivery_Common_hook('getGeoInfo', array(), $type); } } } function MAX_remotehostPrivateAddress($ip) { setupIncludePath(); require_once 'Net/IPv4.php'; $aPrivateNetworks = array( '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '127.0.0.0/24' ); foreach ($aPrivateNetworks as $privateNetwork) { if (Net_IPv4::ipInNetwork($ip, $privateNetwork)) { return true; } } return false; } $file = '/lib/max/Delivery/log.php'; $GLOBALS['_MAX']['FILES'][$file] = true; $file = '/lib/max/Dal/Delivery.php'; $GLOBALS['_MAX']['FILES'][$file] = true; $file = '/lib/OA/Dal/Delivery.php'; $GLOBALS['_MAX']['FILES'][$file] = true; function OA_Dal_Delivery_getAccountTZs() { $aConf = $GLOBALS['_MAX']['CONF']; $query = " SELECT value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['application_variable'])." WHERE name = 'admin_account_id' "; $res = OA_Dal_Delivery_query($query); if (is_resource($res) && OA_Dal_Delivery_numRows($res)) { $adminAccountId = (int)OA_Dal_Delivery_result($res, 0, 0); } else { $adminAccountId = false; } $query = " SELECT a.account_id AS account_id, apa.value AS timezone FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a JOIN ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa ON (apa.account_id = a.account_id) JOIN ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['preferences'])." AS p ON (p.preference_id = apa.preference_id) WHERE a.account_type IN ('ADMIN', 'MANAGER') AND p.preference_name = 'timezone' "; $res = OA_Dal_Delivery_query($query); $aResult = array( 'adminAccountId' => $adminAccountId, 'aAccounts' => array() ); if (is_resource($res)) { while ($row = OA_Dal_Delivery_fetchAssoc($res)) { $accountId = (int)$row['account_id']; if ($accountId === $adminAccountId) { $aResult['default'] = $row['timezone']; } else { $aResult['aAccounts'][$accountId] = $row['timezone']; } } } if (empty($aResult['default'])) { $aResult['default'] = 'UTC'; } return $aResult; } function OA_Dal_Delivery_getZoneInfo($zoneid) { $aConf = $GLOBALS['_MAX']['CONF']; $zoneid = (int)$zoneid; $query = " SELECT z.zoneid AS zone_id, z.zonename AS name, z.delivery AS type, z.description AS description, z.width AS width, z.height AS height, z.chain AS chain, z.prepend AS prepend, z.append AS append, z.appendtype AS appendtype, z.forceappend AS forceappend, z.inventory_forecast_type AS inventory_forecast_type, z.block AS block_zone, z.capping AS cap_zone, z.session_capping AS session_cap_zone, z.show_capped_no_cookie AS show_capped_no_cookie_zone, z.ext_adselection AS ext_adselection, z.affiliateid AS publisher_id, a.agencyid AS agency_id, a.account_id AS trafficker_account_id, m.account_id AS manager_account_id FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['zones'])." AS z, ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['affiliates'])." AS a, ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['agency'])." AS m WHERE z.zoneid = {$zoneid} AND z.affiliateid = a.affiliateid AND a.agencyid = m.agencyid"; $rZoneInfo = OA_Dal_Delivery_query($query); if (!is_resource($rZoneInfo)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false; } $aZoneInfo = OA_Dal_Delivery_fetchAssoc($rZoneInfo); $query = " SELECT p.preference_id AS preference_id, p.preference_name AS preference_name FROM {$aConf['table']['prefix']}{$aConf['table']['preferences']} AS p WHERE p.preference_name = 'default_banner_image_url' OR p.preference_name = 'default_banner_destination_url'"; $rPreferenceInfo = OA_Dal_Delivery_query($query); if (!is_resource($rPreferenceInfo)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false; } if (OA_Dal_Delivery_numRows($rPreferenceInfo) != 2) { return $aZoneInfo; } $aPreferenceInfo = OA_Dal_Delivery_fetchAssoc($rPreferenceInfo); $variableName = $aPreferenceInfo['preference_name'] . '_id'; $$variableName = $aPreferenceInfo['preference_id']; $aPreferenceInfo = OA_Dal_Delivery_fetchAssoc($rPreferenceInfo); $variableName = $aPreferenceInfo['preference_name'] . '_id'; $$variableName = $aPreferenceInfo['preference_id']; $query = " SELECT 'default_banner_destination_url_trafficker' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa WHERE apa.account_id = {$aZoneInfo['trafficker_account_id']} AND apa.preference_id = $default_banner_destination_url_id UNION SELECT 'default_banner_destination_url_manager' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa WHERE apa.account_id = {$aZoneInfo['manager_account_id']} AND apa.preference_id = $default_banner_destination_url_id UNION SELECT 'default_banner_image_url_trafficker' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa WHERE apa.account_id = {$aZoneInfo['trafficker_account_id']} AND apa.preference_id = $default_banner_image_url_id UNION SELECT 'default_banner_image_url_manager' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa WHERE apa.account_id = {$aZoneInfo['manager_account_id']} AND apa.preference_id = $default_banner_image_url_id UNION SELECT 'default_banner_image_url_admin' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa, ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a WHERE apa.account_id = a.account_id AND a.account_type = 'ADMIN' AND apa.preference_id = $default_banner_image_url_id UNION SELECT 'default_banner_destination_url_admin' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa, ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a WHERE apa.account_id = a.account_id AND a.account_type = 'ADMIN' AND apa.preference_id = $default_banner_destination_url_id"; $rDefaultBannerInfo = OA_Dal_Delivery_query($query); if (!is_resource($rDefaultBannerInfo)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false; } if (OA_Dal_Delivery_numRows($rDefaultBannerInfo) == 0) { if ($aConf['defaultBanner']['imageUrl'] != '') { $aZoneInfo['default_banner_image_url'] = $aConf['defaultBanner']['imageUrl']; } return $aZoneInfo; } $aDefaultImageURLs = array(); $aDefaultDestinationURLs = array(); while ($aRow = OA_Dal_Delivery_fetchAssoc($rDefaultBannerInfo)) { if (stristr($aRow['item'], 'default_banner_image_url')) { $aDefaultImageURLs[$aRow['item']] = $aRow['value']; } else if (stristr($aRow['item'], 'default_banner_destination_url')) { $aDefaultDestinationURLs[$aRow['item']] = $aRow['value']; } } $aTypes = array( 0 => 'admin', 1 => 'manager', 2 => 'trafficker' ); foreach ($aTypes as $type) { if (isset($aDefaultImageURLs['default_banner_image_url_' . $type])) { $aZoneInfo['default_banner_image_url'] = $aDefaultImageURLs['default_banner_image_url_' . $type]; } if (isset($aDefaultDestinationURLs['default_banner_destination_url_' . $type])) { $aZoneInfo['default_banner_destination_url'] = $aDefaultDestinationURLs['default_banner_destination_url_' . $type]; } } return $aZoneInfo; } function OA_Dal_Delivery_getPublisherZones($publisherid) { $conf = $GLOBALS['_MAX']['CONF']; $publisherid = (int)$publisherid; $rZones = OA_Dal_Delivery_query(" SELECT z.zoneid AS zone_id, z.affiliateid AS publisher_id, z.zonename AS name, z.delivery AS type FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['zones'])." AS z WHERE z.affiliateid={$publisherid} "); if (!is_resource($rZones)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false; } while ($aZone = OA_Dal_Delivery_fetchAssoc($rZones)) { $aZones[$aZone['zone_id']] = $aZone; } return ($aZones); } function OA_Dal_Delivery_getZoneLinkedAds($zoneid) { $conf = $GLOBALS['_MAX']['CONF']; $zoneid = (int)$zoneid; $aRows = OA_Dal_Delivery_getZoneInfo($zoneid); $aRows['xAds'] = array(); $aRows['ads'] = array(); $aRows['lAds'] = array(); $aRows['eAds'] = array(); $aRows['count_active'] = 0; $aRows['zone_companion'] = false; $aRows['count_active'] = 0; $totals = array( 'xAds' => 0, 'ads' => 0, 'lAds' => 0 ); $query = " SELECT d.bannerid AS ad_id, d.campaignid AS placement_id, d.status AS status, d.description AS name, d.storagetype AS type, d.contenttype AS contenttype, d.pluginversion AS pluginversion, d.filename AS filename, d.imageurl AS imageurl, d.htmltemplate AS htmltemplate, d.htmlcache AS htmlcache, d.width AS width, d.height AS height, d.weight AS weight, d.seq AS seq, d.target AS target, d.url AS url, d.alt AS alt, d.statustext AS statustext, d.bannertext AS bannertext, d.adserver AS adserver, d.block AS block_ad, d.capping AS cap_ad, d.session_capping AS session_cap_ad, d.compiledlimitation AS compiledlimitation, d.acl_plugins AS acl_plugins, d.prepend AS prepend, d.append AS append, d.bannertype AS bannertype, d.alt_filename AS alt_filename, d.alt_imageurl AS alt_imageurl, d.alt_contenttype AS alt_contenttype, d.parameters AS parameters, d.transparent AS transparent, d.ext_bannertype AS ext_bannertype, az.priority AS priority, az.priority_factor AS priority_factor, az.to_be_delivered AS to_be_delivered, c.campaignid AS campaign_id, c.priority AS campaign_priority, c.weight AS campaign_weight, c.companion AS campaign_companion, c.block AS block_campaign, c.capping AS cap_campaign, c.session_capping AS session_cap_campaign, c.show_capped_no_cookie AS show_capped_no_cookie, c.clientid AS client_id, c.expire_time AS expire_time, c.revenue_type AS revenue_type, c.ecpm_enabled AS ecpm_enabled, c.ecpm AS ecpm, c.clickwindow AS clickwindow, c.viewwindow AS viewwindow, m.advertiser_limitation AS advertiser_limitation, a.account_id AS account_id, z.affiliateid AS affiliate_id, a.agencyid as agency_id FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id) JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['zones'])." AS z ON (az.zone_id = z.zoneid) JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c ON (c.campaignid = d.campaignid) LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS m ON (m.clientid = c.clientid) LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = m.agencyid) WHERE az.zone_id = {$zoneid} AND d.status <= 0 AND c.status <= 0 "; $rAds = OA_Dal_Delivery_query($query); if (!is_resource($rAds)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } $aConversionLinkedCreatives = MAX_cacheGetTrackerLinkedCreatives(); while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) { $aAd['tracker_status'] = (!empty($aConversionLinkedCreatives[$aAd['ad_id']]['status'])) ? $aConversionLinkedCreatives[$aAd['ad_id']]['status'] : null; if ($aAd['campaign_priority'] == -1) { $aRows['xAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } elseif ($aAd['campaign_priority'] == 0) { $aRows['lAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } elseif ($aAd['campaign_priority'] == -2) { $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } else { $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } if ($aAd['campaign_companion'] == 1) { $aRows['zone_companion'][] = $aAd['placement_id']; } } if (is_array($aRows['xAds'])) { $totals['xAds'] = _setPriorityFromWeights($aRows['xAds']); } if (is_array($aRows['ads'])) { $totals['ads'] = _getTotalPrioritiesByCP($aRows['ads']); } if (is_array($aRows['eAds'])) { $totals['eAds'] = _getTotalPrioritiesByCP($aRows['eAds']); } if (is_array($aRows['lAds'])) { $totals['lAds'] = _setPriorityFromWeights($aRows['lAds']); } $aRows['priority'] = $totals; return $aRows; } function OA_Dal_Delivery_getZoneLinkedAdInfos($zoneid) { $conf = $GLOBALS['_MAX']['CONF']; $zoneid = (int)$zoneid; $aRows['xAds'] = array(); $aRows['ads'] = array(); $aRows['lAds'] = array(); $aRows['eAds'] = array(); $aRows['zone_companion'] = false; $aRows['count_active'] = 0; $query = "SELECT " ."d.bannerid AS ad_id, " ."d.campaignid AS placement_id, " ."d.status AS status, " ."d.width AS width, " ."d.ext_bannertype AS ext_bannertype, " ."d.height AS height, " ."d.storagetype AS type, " ."d.contenttype AS contenttype, " ."d.weight AS weight, " ."d.adserver AS adserver, " ."d.block AS block_ad, " ."d.capping AS cap_ad, " ."d.session_capping AS session_cap_ad, " ."d.compiledlimitation AS compiledlimitation, " ."d.acl_plugins AS acl_plugins, " ."d.alt_filename AS alt_filename, " ."az.priority AS priority, " ."az.priority_factor AS priority_factor, " ."az.to_be_delivered AS to_be_delivered, " ."c.campaignid AS campaign_id, " ."c.priority AS campaign_priority, " ."c.weight AS campaign_weight, " ."c.companion AS campaign_companion, " ."c.block AS block_campaign, " ."c.capping AS cap_campaign, " ."c.session_capping AS session_cap_campaign, " ."c.show_capped_no_cookie AS show_capped_no_cookie, " ."c.clientid AS client_id, " ."c.expire_time AS expire_time, " ."c.revenue_type AS revenue_type, " ."c.ecpm_enabled AS ecpm_enabled, " ."c.ecpm AS ecpm, " ."ct.status AS tracker_status, " .OX_Dal_Delivery_regex("d.htmlcache", "src\\s?=\\s?[\\'\"]http:")." AS html_ssl_unsafe, " .OX_Dal_Delivery_regex("d.imageurl", "^http:")." AS url_ssl_unsafe " ."FROM " .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d JOIN " .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id) JOIN " .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c ON (c.campaignid = d.campaignid) LEFT JOIN " .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns_trackers'])." AS ct ON (ct.campaignid = c.campaignid) " ."WHERE " ."az.zone_id = {$zoneid} " ."AND " ."d.status <= 0 " ."AND " ."c.status <= 0 "; $rAds = OA_Dal_Delivery_query($query); if (!is_resource($rAds)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) { if ($aAd['campaign_priority'] == -1) { $aRows['xAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } elseif ($aAd['campaign_priority'] == 0) { $aRows['lAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } elseif ($aAd['campaign_priority'] == -2) { $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } else { $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } if ($aAd['campaign_companion'] == 1) { $aRows['zone_companion'][] = $aAd['placement_id']; } } return $aRows; } function OA_Dal_Delivery_getLinkedAdInfos($search, $campaignid = '', $lastpart = true) { $conf = $GLOBALS['_MAX']['CONF']; $campaignid = (int)$campaignid; if ($campaignid > 0) { $precondition = " AND d.campaignid = '".$campaignid."' "; } else { $precondition = ''; } $aRows['xAds'] = array(); $aRows['ads'] = array(); $aRows['lAds'] = array(); $aRows['count_active'] = 0; $aRows['zone_companion'] = false; $aRows['count_active'] = 0; $totals = array( 'xAds' => 0, 'ads' => 0, 'lAds' => 0 ); $query = OA_Dal_Delivery_buildAdInfoQuery($search, $lastpart, $precondition); $rAds = OA_Dal_Delivery_query($query); if (!is_resource($rAds)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) { if ($aAd['campaign_priority'] == -1) { $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight']; $aRows['xAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; $totals['xAds'] += $aAd['priority']; } elseif ($aAd['campaign_priority'] == 0) { $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight']; $aRows['lAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; $totals['lAds'] += $aAd['priority']; } elseif ($aAd['campaign_priority'] == -2) { $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } else { $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } } return $aRows; } function OA_Dal_Delivery_getLinkedAds($search, $campaignid = '', $lastpart = true) { $conf = $GLOBALS['_MAX']['CONF']; $campaignid = (int)$campaignid; if ($campaignid > 0) { $precondition = " AND d.campaignid = '".$campaignid."' "; } else { $precondition = ''; } $aRows['xAds'] = array(); $aRows['ads'] = array(); $aRows['lAds'] = array(); $aRows['count_active'] = 0; $aRows['zone_companion'] = false; $aRows['count_active'] = 0; $totals = array( 'xAds' => 0, 'ads' => 0, 'lAds' => 0 ); $query = OA_Dal_Delivery_buildQuery($search, $lastpart, $precondition); $rAds = OA_Dal_Delivery_query($query); if (!is_resource($rAds)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } $aConversionLinkedCreatives = MAX_cacheGetTrackerLinkedCreatives(); while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) { $aAd['tracker_status'] = (!empty($aConversionLinkedCreatives[$aAd['ad_id']]['status'])) ? $aConversionLinkedCreatives[$aAd['ad_id']]['status'] : null; if ($aAd['campaign_priority'] == -1) { $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight']; $aRows['xAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; $totals['xAds'] += $aAd['priority']; } elseif ($aAd['campaign_priority'] == 0) { $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight']; $aRows['lAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; $totals['lAds'] += $aAd['priority']; } elseif ($aAd['campaign_priority'] == -2) { $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } else { $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } } if (isset($aRows['xAds']) && is_array($aRows['xAds'])) { $totals['xAds'] = _setPriorityFromWeights($aRows['xAds']); } if (isset($aRows['ads']) && is_array($aRows['ads'])) { if (isset($aRows['lAds']) && is_array($aRows['lAds']) && count($aRows['lAds']) > 0) { $totals['ads'] = _getTotalPrioritiesByCP($aRows['ads'], true); } else { $totals['ads'] = _getTotalPrioritiesByCP($aRows['ads'], false); } } if (is_array($aRows['eAds'])) { $totals['eAds'] = _getTotalPrioritiesByCP($aRows['eAds']); } if (isset($aRows['lAds']) && is_array($aRows['lAds'])) { $totals['lAds'] = _setPriorityFromWeights($aRows['lAds']); } $aRows['priority'] = $totals; return $aRows; } function OA_Dal_Delivery_getAd($ad_id) { $conf = $GLOBALS['_MAX']['CONF']; $ad_id = (int)$ad_id; $query = " SELECT d.bannerid AS ad_id, d.campaignid AS placement_id, d.status AS status, d.description AS name, d.storagetype AS type, d.contenttype AS contenttype, d.pluginversion AS pluginversion, d.filename AS filename, d.imageurl AS imageurl, d.htmltemplate AS htmltemplate, d.htmlcache AS htmlcache, d.width AS width, d.height AS height, d.weight AS weight, d.seq AS seq, d.target AS target, d.url AS url, d.alt AS alt, d.statustext AS statustext, d.bannertext AS bannertext, d.adserver AS adserver, d.block AS block_ad, d.capping AS cap_ad, d.session_capping AS session_cap_ad, d.compiledlimitation AS compiledlimitation, d.acl_plugins AS acl_plugins, d.prepend AS prepend, d.append AS append, d.bannertype AS bannertype, d.alt_filename AS alt_filename, d.alt_imageurl AS alt_imageurl, d.alt_contenttype AS alt_contenttype, d.parameters AS parameters, d.transparent AS transparent, d.ext_bannertype AS ext_bannertype, c.campaignid AS campaign_id, c.block AS block_campaign, c.capping AS cap_campaign, c.session_capping AS session_cap_campaign, c.show_capped_no_cookie AS show_capped_no_cookie, m.clientid AS client_id, c.clickwindow AS clickwindow, c.viewwindow AS viewwindow, m.advertiser_limitation AS advertiser_limitation, m.agencyid AS agency_id FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d, ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c, ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS m WHERE d.bannerid={$ad_id} AND d.campaignid = c.campaignid AND m.clientid = c.clientid "; $rAd = OA_Dal_Delivery_query($query); if (!is_resource($rAd)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { return (OA_Dal_Delivery_fetchAssoc($rAd)); } } function OA_Dal_Delivery_getChannelLimitations($channelid) { $conf = $GLOBALS['_MAX']['CONF']; $channelid = (int)$channelid; $rLimitation = OA_Dal_Delivery_query(" SELECT acl_plugins,compiledlimitation FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['channel'])." WHERE channelid={$channelid}"); if (!is_resource($rLimitation)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } $limitations = OA_Dal_Delivery_fetchAssoc($rLimitation); return $limitations; } function OA_Dal_Delivery_getCreative($filename) { $conf = $GLOBALS['_MAX']['CONF']; $rCreative = OA_Dal_Delivery_query(" SELECT contents, t_stamp FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['images'])." WHERE filename = '".OX_escapeString($filename)."' "); if (!is_resource($rCreative)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { $aResult = OA_Dal_Delivery_fetchAssoc($rCreative); $aResult['t_stamp'] = strtotime($aResult['t_stamp'] . ' GMT'); return ($aResult); } } function OA_Dal_Delivery_getTracker($trackerid) { $conf = $GLOBALS['_MAX']['CONF']; $trackerid = (int)$trackerid; $rTracker = OA_Dal_Delivery_query(" SELECT t.clientid AS advertiser_id, t.trackerid AS tracker_id, t.trackername AS name, t.variablemethod AS variablemethod, t.description AS description, t.viewwindow AS viewwindow, t.clickwindow AS clickwindow, t.blockwindow AS blockwindow, t.appendcode AS appendcode FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['trackers'])." AS t WHERE t.trackerid={$trackerid} "); if (!is_resource($rTracker)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { return (OA_Dal_Delivery_fetchAssoc($rTracker)); } } function OA_Dal_Delivery_getTrackerLinkedCreatives($trackerid = null) { $aConf = $GLOBALS['_MAX']['CONF']; $trackerid = (int)$trackerid; $rCreatives = OA_Dal_Delivery_query(" SELECT b.bannerid AS ad_id, b.campaignid AS placement_id, c.viewwindow AS view_window, c.clickwindow AS click_window, ct.status AS status, t.type AS tracker_type FROM {$aConf['table']['prefix']}{$aConf['table']['banners']} AS b, {$aConf['table']['prefix']}{$aConf['table']['campaigns_trackers']} AS ct, {$aConf['table']['prefix']}{$aConf['table']['campaigns']} AS c, {$aConf['table']['prefix']}{$aConf['table']['trackers']} AS t WHERE ct.trackerid=t.trackerid AND c.campaignid=b.campaignid AND b.campaignid = ct.campaignid " . ((!empty($trackerid)) ? ' AND t.trackerid='.$trackerid : '') . " "); if (!is_resource($rCreatives)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { $output = array(); while ($aRow = OA_Dal_Delivery_fetchAssoc($rCreatives)) { $output[$aRow['ad_id']] = $aRow; } return $output; } } function OA_Dal_Delivery_getTrackerVariables($trackerid) { $conf = $GLOBALS['_MAX']['CONF']; $trackerid = (int)$trackerid; $rVariables = OA_Dal_Delivery_query(" SELECT v.variableid AS variable_id, v.trackerid AS tracker_id, v.name AS name, v.datatype AS type, purpose AS purpose, reject_if_empty AS reject_if_empty, is_unique AS is_unique, unique_window AS unique_window, v.variablecode AS variablecode FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['variables'])." AS v WHERE v.trackerid={$trackerid} "); if (!is_resource($rVariables)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { $output = array(); while ($aRow = OA_Dal_Delivery_fetchAssoc($rVariables)) { $output[$aRow['variable_id']] = $aRow; } return $output; } } function OA_Dal_Delivery_getMaintenanceInfo() { $conf = $GLOBALS['_MAX']['CONF']; $result = OA_Dal_Delivery_query(" SELECT value AS maintenance_timestamp FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['application_variable'])." WHERE name = 'maintenance_timestamp' "); if (!is_resource($result)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { $result = OA_Dal_Delivery_fetchAssoc($result); return $result['maintenance_timestamp']; } } function OA_Dal_Delivery_buildQuery($part, $lastpart, $precondition) { $conf = $GLOBALS['_MAX']['CONF']; $aColumns = array( 'd.bannerid AS ad_id', 'd.campaignid AS placement_id', 'd.status AS status', 'd.description AS name', 'd.storagetype AS type', 'd.contenttype AS contenttype', 'd.pluginversion AS pluginversion', 'd.filename AS filename', 'd.imageurl AS imageurl', 'd.htmltemplate AS htmltemplate', 'd.htmlcache AS htmlcache', 'd.width AS width', 'd.height AS height', 'd.weight AS weight', 'd.seq AS seq', 'd.target AS target', 'd.url AS url', 'd.alt AS alt', 'd.statustext AS statustext', 'd.bannertext AS bannertext', 'd.adserver AS adserver', 'd.block AS block_ad', 'd.capping AS cap_ad', 'd.session_capping AS session_cap_ad', 'd.compiledlimitation AS compiledlimitation', 'd.acl_plugins AS acl_plugins', 'd.prepend AS prepend', 'd.append AS append', 'd.bannertype AS bannertype', 'd.alt_filename AS alt_filename', 'd.alt_imageurl AS alt_imageurl', 'd.alt_contenttype AS alt_contenttype', 'd.parameters AS parameters', 'd.transparent AS transparent', 'd.ext_bannertype AS ext_bannertype', 'az.priority AS priority', 'az.priority_factor AS priority_factor', 'az.to_be_delivered AS to_be_delivered', 'm.campaignid AS campaign_id', 'm.priority AS campaign_priority', 'm.weight AS campaign_weight', 'm.companion AS campaign_companion', 'm.block AS block_campaign', 'm.capping AS cap_campaign', 'm.session_capping AS session_cap_campaign', 'm.show_capped_no_cookie AS show_capped_no_cookie', 'm.clickwindow AS clickwindow', 'm.viewwindow AS viewwindow', 'cl.clientid AS client_id', 'm.expire_time AS expire_time', 'm.revenue_type AS revenue_type', 'm.ecpm_enabled AS ecpm_enabled', 'm.ecpm AS ecpm', 'cl.advertiser_limitation AS advertiser_limitation', 'a.account_id AS account_id', 'a.agencyid AS agency_id' ); $aTables = array( "".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d", "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS m ON (d.campaignid = m.campaignid) ", "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS cl ON (m.clientid = cl.clientid) ", "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id)" ); $select = " az.zone_id = 0 AND m.status <= 0 AND d.status <= 0"; if ($precondition != '') $select .= " $precondition "; if ($part != '') { $conditions = ''; $onlykeywords = true; $part_array = explode(',', $part); for ($k=0; $k < count($part_array); $k++) { if (substr($part_array[$k], 0, 1) == '+' || substr($part_array[$k], 0, 1) == '_') { $operator = 'AND'; $part_array[$k] = substr($part_array[$k], 1); } elseif (substr($part_array[$k], 0, 1) == '-') { $operator = 'NOT'; $part_array[$k] = substr($part_array[$k], 1); } else $operator = 'OR'; if($part_array[$k] != '' && $part_array[$k] != ' ') { if(preg_match('#^(?:size:)?([0-9]+x[0-9]+)$#', $part_array[$k], $m)) { list($width, $height) = explode('x', $m[1]); if ($operator == 'OR') $conditions .= "OR (d.width = $width AND d.height = $height) "; elseif ($operator == 'AND') $conditions .= "AND (d.width = $width AND d.height = $height) "; else $conditions .= "AND (d.width != $width OR d.height != $height) "; $onlykeywords = false; } elseif (substr($part_array[$k],0,6) == 'width:') { $part_array[$k] = substr($part_array[$k], 6); if ($part_array[$k] != '' && $part_array[$k] != ' ') { if (is_int(strpos($part_array[$k], '-'))) { list($min, $max) = explode('-', $part_array[$k]); if ($min == '') $min = 1; if ($max == '') { if ($operator == 'OR') $conditions .= "OR d.width >= '".trim($min)."' "; elseif ($operator == 'AND') $conditions .= "AND d.width >= '".trim($min)."' "; else $conditions .= "AND d.width < '".trim($min)."' "; } if ($max != '') { if ($operator == 'OR') $conditions .= "OR (d.width >= '".trim($min)."' AND d.width <= '".trim($max)."') "; elseif ($operator == 'AND') $conditions .= "AND (d.width >= '".trim($min)."' AND d.width <= '".trim($max)."') "; else $conditions .= "AND (d.width < '".trim($min)."' OR d.width > '".trim($max)."') "; } } else { if ($operator == 'OR') $conditions .= "OR d.width = '".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.width = '".trim($part_array[$k])."' "; else $conditions .= "AND d.width != '".trim($part_array[$k])."' "; } } $onlykeywords = false; } elseif (substr($part_array[$k],0,7) == 'height:') { $part_array[$k] = substr($part_array[$k], 7); if ($part_array[$k] != '' && $part_array[$k] != ' ') { if (is_int(strpos($part_array[$k], '-'))) { list($min, $max) = explode('-', $part_array[$k]); if ($min == '') $min = 1; if ($max == '') { if ($operator == 'OR') $conditions .= "OR d.height >= '".trim($min)."' "; elseif ($operator == 'AND') $conditions .= "AND d.height >= '".trim($min)."' "; else $conditions .= "AND d.height < '".trim($min)."' "; } if ($max != '') { if ($operator == 'OR') $conditions .= "OR (d.height >= '".trim($min)."' AND d.height <= '".trim($max)."') "; elseif ($operator == 'AND') $conditions .= "AND (d.height >= '".trim($min)."' AND d.height <= '".trim($max)."') "; else $conditions .= "AND (d.height < '".trim($min)."' OR d.height > '".trim($max)."') "; } } else { if ($operator == 'OR') $conditions .= "OR d.height = '".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.height = '".trim($part_array[$k])."' "; else $conditions .= "AND d.height != '".trim($part_array[$k])."' "; } } $onlykeywords = false; } elseif (preg_match('#^(?:(?:bannerid|adid|ad_id):)?([0-9]+)$#', $part_array[$k], $m)) { $part_array[$k] = $m[1]; if ($part_array[$k]) { if ($operator == 'OR') $conditions .= "OR d.bannerid='".$part_array[$k]."' "; elseif ($operator == 'AND') $conditions .= "AND d.bannerid='".$part_array[$k]."' "; else $conditions .= "AND d.bannerid!='".$part_array[$k]."' "; } $onlykeywords = false; } elseif (preg_match('#^(?:(?:clientid|campaignid|placementid|placement_id):)?([0-9]+)$#', $part_array[$k], $m)) { $part_array[$k] = $m[1]; if ($part_array[$k]) { if ($operator == 'OR') $conditions .= "OR d.campaignid='".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.campaignid='".trim($part_array[$k])."' "; else $conditions .= "AND d.campaignid!='".trim($part_array[$k])."' "; } $onlykeywords = false; } elseif (substr($part_array[$k], 0, 7) == 'format:') { $part_array[$k] = substr($part_array[$k], 7); if($part_array[$k] != '' && $part_array[$k] != ' ') { if ($operator == 'OR') $conditions .= "OR d.contenttype='".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.contenttype='".trim($part_array[$k])."' "; else $conditions .= "AND d.contenttype!='".trim($part_array[$k])."' "; } $onlykeywords = false; } elseif($part_array[$k] == 'html') { if ($operator == 'OR') $conditions .= "OR d.storagetype='html' "; elseif ($operator == 'AND') $conditions .= "AND d.storagetype='html' "; else $conditions .= "AND d.storagetype!='html' "; $onlykeywords = false; } elseif($part_array[$k] == 'textad') { if ($operator == 'OR') $conditions .= "OR d.storagetype='txt' "; elseif ($operator == 'AND') $conditions .= "AND d.storagetype='txt' "; else $conditions .= "AND d.storagetype!='txt' "; $onlykeywords = false; } else { $conditions .= OA_Dal_Delivery_getKeywordCondition($operator, $part_array[$k]); } } } $conditions = strstr($conditions, ' '); if ($lastpart == true && $onlykeywords == true) $conditions .= OA_Dal_Delivery_getKeywordCondition('OR', 'global'); if ($conditions != '') $select .= ' AND ('.$conditions.') '; } $columns = implode(",\n ", $aColumns); $tables = implode("\n ", $aTables); $leftJoin = " LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS c ON (c.clientid = m.clientid) LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = c.agencyid) "; $query = "SELECT\n " . $columns . "\nFROM\n " . $tables . $leftJoin . "\nWHERE " . $select; return $query; } function OA_Dal_Delivery_buildAdInfoQuery($part, $lastpart, $precondition) { $conf = $GLOBALS['_MAX']['CONF']; $aColumns = array( 'd.bannerid AS ad_id', 'd.campaignid AS placement_id', 'd.status AS status', 'd.storagetype AS type', 'd.contenttype AS contenttype', 'd.weight AS weight', 'd.width AS width', 'd.ext_bannertype AS ext_bannertype', 'd.height AS height', 'd.adserver AS adserver', 'd.block AS block_ad', 'd.capping AS cap_ad', 'd.session_capping AS session_cap_ad', 'd.compiledlimitation AS compiledlimitation', 'd.acl_plugins AS acl_plugins', 'd.alt_filename AS alt_filename', 'az.priority AS priority', 'az.priority_factor AS priority_factor', 'az.to_be_delivered AS to_be_delivered', 'm.campaignid AS campaign_id', 'm.priority AS campaign_priority', 'm.weight AS campaign_weight', 'm.companion AS campaign_companion', 'm.block AS block_campaign', 'm.capping AS cap_campaign', 'm.session_capping AS session_cap_campaign', 'm.show_capped_no_cookie AS show_capped_no_cookie', 'cl.clientid AS client_id', 'm.expire_time AS expire_time', 'm.revenue_type AS revenue_type', 'm.ecpm_enabled AS ecpm_enabled', 'm.ecpm AS ecpm', 'ct.status AS tracker_status', OX_Dal_Delivery_regex("d.htmlcache", "src\\s?=\\s?[\\'\"]http:")." AS html_ssl_unsafe", OX_Dal_Delivery_regex("d.imageurl", "^http:")." AS url_ssl_unsafe", ); $aTables = array( "".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d", "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id)", "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS m ON (m.campaignid = d.campaignid) ", ); $select = " az.zone_id = 0 AND m.status <= 0 AND d.status <= 0"; if ($precondition != '') $select .= " $precondition "; if ($part != '') { $conditions = ''; $onlykeywords = true; $part_array = explode(',', $part); for ($k=0; $k < count($part_array); $k++) { if (substr($part_array[$k], 0, 1) == '+' || substr($part_array[$k], 0, 1) == '_') { $operator = 'AND'; $part_array[$k] = substr($part_array[$k], 1); } elseif (substr($part_array[$k], 0, 1) == '-') { $operator = 'NOT'; $part_array[$k] = substr($part_array[$k], 1); } else $operator = 'OR'; if($part_array[$k] != '' && $part_array[$k] != ' ') { if(preg_match('#^(?:size:)?([0-9]+x[0-9]+)$#', $part_array[$k], $m)) { list($width, $height) = explode('x', $m[1]); if ($operator == 'OR') $conditions .= "OR (d.width = $width AND d.height = $height) "; elseif ($operator == 'AND') $conditions .= "AND (d.width = $width AND d.height = $height) "; else $conditions .= "AND (d.width != $width OR d.height != $height) "; $onlykeywords = false; } elseif (substr($part_array[$k],0,6) == 'width:') { $part_array[$k] = substr($part_array[$k], 6); if ($part_array[$k] != '' && $part_array[$k] != ' ') { if (is_int(strpos($part_array[$k], '-'))) { list($min, $max) = explode('-', $part_array[$k]); if ($min == '') $min = 1; if ($max == '') { if ($operator == 'OR') $conditions .= "OR d.width >= '".trim($min)."' "; elseif ($operator == 'AND') $conditions .= "AND d.width >= '".trim($min)."' "; else $conditions .= "AND d.width < '".trim($min)."' "; } if ($max != '') { if ($operator == 'OR') $conditions .= "OR (d.width >= '".trim($min)."' AND d.width <= '".trim($max)."') "; elseif ($operator == 'AND') $conditions .= "AND (d.width >= '".trim($min)."' AND d.width <= '".trim($max)."') "; else $conditions .= "AND (d.width < '".trim($min)."' OR d.width > '".trim($max)."') "; } } else { if ($operator == 'OR') $conditions .= "OR d.width = '".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.width = '".trim($part_array[$k])."' "; else $conditions .= "AND d.width != '".trim($part_array[$k])."' "; } } $onlykeywords = false; } elseif (substr($part_array[$k],0,7) == 'height:') { $part_array[$k] = substr($part_array[$k], 7); if ($part_array[$k] != '' && $part_array[$k] != ' ') { if (is_int(strpos($part_array[$k], '-'))) { list($min, $max) = explode('-', $part_array[$k]); if ($min == '') $min = 1; if ($max == '') { if ($operator == 'OR') $conditions .= "OR d.height >= '".trim($min)."' "; elseif ($operator == 'AND') $conditions .= "AND d.height >= '".trim($min)."' "; else $conditions .= "AND d.height < '".trim($min)."' "; } if ($max != '') { if ($operator == 'OR') $conditions .= "OR (d.height >= '".trim($min)."' AND d.height <= '".trim($max)."') "; elseif ($operator == 'AND') $conditions .= "AND (d.height >= '".trim($min)."' AND d.height <= '".trim($max)."') "; else $conditions .= "AND (d.height < '".trim($min)."' OR d.height > '".trim($max)."') "; } } else { if ($operator == 'OR') $conditions .= "OR d.height = '".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.height = '".trim($part_array[$k])."' "; else $conditions .= "AND d.height != '".trim($part_array[$k])."' "; } } $onlykeywords = false; } elseif (preg_match('#^(?:(?:bannerid|adid|ad_id):)?([0-9]+)$#', $part_array[$k], $m)) { $part_array[$k] = $m[1]; if ($part_array[$k]) { if ($operator == 'OR') $conditions .= "OR d.bannerid='".$part_array[$k]."' "; elseif ($operator == 'AND') $conditions .= "AND d.bannerid='".$part_array[$k]."' "; else $conditions .= "AND d.bannerid!='".$part_array[$k]."' "; } $onlykeywords = false; } elseif (preg_match('#^(?:(?:clientid|campaignid|placementid|placement_id):)?([0-9]+)$#', $part_array[$k], $m)) { $part_array[$k] = $m[1]; if ($part_array[$k]) { if ($operator == 'OR') $conditions .= "OR d.campaignid='".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.campaignid='".trim($part_array[$k])."' "; else $conditions .= "AND d.campaignid!='".trim($part_array[$k])."' "; } $onlykeywords = false; } elseif (substr($part_array[$k], 0, 7) == 'format:') { $part_array[$k] = substr($part_array[$k], 7); if($part_array[$k] != '' && $part_array[$k] != ' ') { if ($operator == 'OR') $conditions .= "OR d.contenttype='".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.contenttype='".trim($part_array[$k])."' "; else $conditions .= "AND d.contenttype!='".trim($part_array[$k])."' "; } $onlykeywords = false; } elseif($part_array[$k] == 'html') { if ($operator == 'OR') $conditions .= "OR d.storagetype='html' "; elseif ($operator == 'AND') $conditions .= "AND d.storagetype='html' "; else $conditions .= "AND d.storagetype!='html' "; $onlykeywords = false; } elseif($part_array[$k] == 'textad') { if ($operator == 'OR') $conditions .= "OR d.storagetype='txt' "; elseif ($operator == 'AND') $conditions .= "AND d.storagetype='txt' "; else $conditions .= "AND d.storagetype!='txt' "; $onlykeywords = false; } else { $conditions .= OA_Dal_Delivery_getKeywordCondition($operator, $part_array[$k]); } } } $conditions = strstr($conditions, ' '); if ($lastpart == true && $onlykeywords == true) $conditions .= OA_Dal_Delivery_getKeywordCondition('OR', 'global'); if ($conditions != '') $select .= ' AND ('.$conditions.') '; } $columns = implode(",\n ", $aColumns); $tables = implode("\n ", $aTables); $leftJoin = " LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns_trackers'])." AS ct ON (ct.campaignid = m.campaignid) LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS cl ON (cl.clientid = m.clientid) LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = cl.agencyid) "; $query = "SELECT\n " . $columns . "\nFROM\n " . $tables . $leftJoin . "\nWHERE " . $select; return $query; } function _setPriorityFromWeights(&$aAds) { if (!count($aAds)) { return 0; } $aCampaignWeights = array(); $aCampaignAdWeight = array(); foreach ($aAds as $v) { if (!isset($aCampaignWeights[$v['placement_id']])) { $aCampaignWeights[$v['placement_id']] = $v['campaign_weight']; $aCampaignAdWeight[$v['placement_id']] = 0; } $aCampaignAdWeight[$v['placement_id']] += $v['weight']; } foreach ($aCampaignWeights as $k => $v) { if ($aCampaignAdWeight[$k]) { $aCampaignWeights[$k] /= $aCampaignAdWeight[$k]; } } $totalPri = 0; foreach ($aAds as $k => $v) { $aAds[$k]['priority'] = $aCampaignWeights[$v['placement_id']] * $v['weight']; $totalPri += $aAds[$k]['priority']; } if ($totalPri) { foreach ($aAds as $k => $v) { $aAds[$k]['priority'] /= $totalPri; } return 1; } return 0; } function _getTotalPrioritiesByCP($aAdsByCP, $includeBlank = true) { $totals = array(); $total_priority_cp = array(); $blank_priority = 1; foreach ($aAdsByCP as $campaign_priority => $aAds) { $total_priority_cp[$campaign_priority] = 0; foreach ($aAds as $key => $aAd) { $blank_priority -= (double)$aAd['priority']; if ($aAd['to_be_delivered']) { $priority = $aAd['priority'] * $aAd['priority_factor']; } else { $priority = 0.00001; } $total_priority_cp[$campaign_priority] += $priority; } } $total_priority = 0; if ($includeBlank) { $total_priority = $blank_priority <= 1e-15 ? 0 : $blank_priority; } ksort($total_priority_cp); foreach($total_priority_cp as $campaign_priority => $priority) { $total_priority += $priority; if ($total_priority) { $totals[$campaign_priority] = $priority / $total_priority; } else { $totals[$campaign_priority] = 0; } } return $totals; } function MAX_Dal_Delivery_Include() { static $included; if (isset($included)) { return; } $included = true; $conf = $GLOBALS['_MAX']['CONF']; if (isset($conf['origin']['type']) && is_readable(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['origin']['type']) . '.php')) { require(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['origin']['type']) . '.php'); } else { require(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['database']['type']) . '.php'); } } function MAX_trackerbuildJSVariablesScript($trackerid, $conversionInfo, $trackerJsCode = null) { $conf = $GLOBALS['_MAX']['CONF']; $buffer = ''; $url = MAX_commonGetDeliveryUrl($conf['file']['conversionvars']); $tracker = MAX_cacheGetTracker($trackerid); $variables = MAX_cacheGetTrackerVariables($trackerid); $variableQuerystring = ''; if (empty($trackerJsCode)) { $trackerJsCode = md5(uniqid('', true)); } else { $tracker['variablemethod'] = 'default'; } if (!empty($variables)) { if ($tracker['variablemethod'] == 'dom') { $buffer .= " function MAX_extractTextDom(o) { var txt = ''; if (o.nodeType == 3) { txt = o.data; } else { for (var i = 0; i < o.childNodes.length; i++) { txt += MAX_extractTextDom(o.childNodes[i]); } } return txt; } function MAX_TrackVarDom(id, v) { if (max_trv[id][v]) { return; } var o = document.getElementById(v); if (o) { max_trv[id][v] = escape(o.tagName == 'INPUT' ? o.value : MAX_extractTextDom(o)); } }"; $funcName = 'MAX_TrackVarDom'; } elseif ($tracker['variablemethod'] == 'default') { $buffer .= " function MAX_TrackVarDefault(id, v) { if (max_trv[id][v]) { return; } if (typeof(window[v]) == undefined) { return; } max_trv[id][v] = window[v]; }"; $funcName = 'MAX_TrackVarDefault'; } else { $buffer .= " function MAX_TrackVarJs(id, v, c) { if (max_trv[id][v]) { return; } if (typeof(window[v]) == undefined) { return; } if (typeof(c) != 'undefined') { eval(c); } max_trv[id][v] = window[v]; }"; $funcName = 'MAX_TrackVarJs'; } $buffer .= " if (!max_trv) { var max_trv = new Array(); } if (!max_trv['{$trackerJsCode}']) { max_trv['{$trackerJsCode}'] = new Array(); }"; foreach($variables as $key => $variable) { $variableQuerystring .= "&{$variable['name']}=\"+max_trv['{$trackerJsCode}']['{$variable['name']}']+\""; if ($tracker['variablemethod'] == 'custom') { $buffer .= " {$funcName}('{$trackerJsCode}', '{$variable['name']}', '".addcslashes($variable['variablecode'], "'")."');"; } else { $buffer .= " {$funcName}('{$trackerJsCode}', '{$variable['name']}');"; } } if (!empty($variableQuerystring)) { $conversionInfoParams = array(); foreach ($conversionInfo as $plugin => $pluginData) { if (is_array($pluginData)) { foreach ($pluginData as $key => $value) { $conversionInfoParams[] = $key . '=' . urlencode($value); } } } $conversionInfoParams = '&' . implode('&', $conversionInfoParams); $buffer .= " document.write (\"<\" + \"script language='JavaScript' type='text/javascript' src='\"); document.write (\"$url?trackerid=$trackerid{$conversionInfoParams}{$variableQuerystring}'\");"; $buffer .= "\n\tdocument.write (\"><\\/scr\"+\"ipt>\");"; } } if(!empty($tracker['appendcode'])) { $tracker['appendcode'] = preg_replace('/("\?trackerid=\d+&amp;inherit)=1/', '$1='.$trackerJsCode, $tracker['appendcode']); $jscode = MAX_javascriptToHTML($tracker['appendcode'], "MAX_{$trackerid}_appendcode"); $jscode = preg_replace("/\{m3_trackervariable:(.+?)\}/", "\"+max_trv['{$trackerJsCode}']['$1']+\"", $jscode); $buffer .= "\n".preg_replace('/^/m', "\t", $jscode)."\n"; } if (empty($buffer)) { $buffer = "document.write(\"\");"; } return $buffer; } function MAX_trackerCheckForValidAction($trackerid) { $aTrackerLinkedAds = MAX_cacheGetTrackerLinkedCreatives($trackerid); if (empty($aTrackerLinkedAds)) { return false; } $aPossibleActions = _getActionTypes(); $now = MAX_commonGetTimeNow(); $aConf = $GLOBALS['_MAX']['CONF']; $aMatchingActions = array(); foreach ($aTrackerLinkedAds as $creativeId => $aLinkedInfo) { foreach ($aPossibleActions as $actionId => $action) { if (!empty($aLinkedInfo[$action . '_window']) && !empty($_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId])) { if (stristr($_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId], ' ')) { list($value, $extra) = explode(' ', $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId], 2); $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId] = $value; } else { $extra = ''; } list($lastAction, $zoneId) = explode('-', $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId]); $lastAction = MAX_commonUnCompressInt($lastAction); $lastSeenSecondsAgo = $now - $lastAction; if ($lastSeenSecondsAgo <= $aLinkedInfo[$action . '_window'] && $lastSeenSecondsAgo > 0) { $aMatchingActions[$lastSeenSecondsAgo] = array( 'action_type' => $actionId, 'tracker_type' => $aLinkedInfo['tracker_type'], 'status' => $aLinkedInfo['status'], 'cid' => $creativeId, 'zid' => $zoneId, 'dt' => $lastAction, 'window' => $aLinkedInfo[$action . '_window'], 'extra' => $extra, ); } } } } if (empty($aMatchingActions)) { return false; } ksort($aMatchingActions); return array_shift($aMatchingActions); } function _getActionTypes() { return array(0 => 'view', 1 => 'click'); } function _getTrackerTypes() { return array(1 => 'sale', 2 => 'lead', 3 => 'signup'); } function MAX_Delivery_log_logAdRequest($adId, $zoneId, $aAd = array()) { if (empty($GLOBALS['_MAX']['CONF']['logging']['adRequests'])) { return true; } OX_Delivery_Common_hook('logRequest', array($adId, $zoneId, $aAd, _viewersHostOkayToLog($adId, $zoneId))); } function MAX_Delivery_log_logAdImpression($adId, $zoneId) { if (empty($GLOBALS['_MAX']['CONF']['logging']['adImpressions'])) { return true; } OX_Delivery_Common_hook('logImpression', array($adId, $zoneId, _viewersHostOkayToLog($adId, $zoneId))); } function MAX_Delivery_log_logAdClick($adId, $zoneId) { if (empty($GLOBALS['_MAX']['CONF']['logging']['adClicks'])) { return true; } OX_Delivery_Common_hook('logClick', array($adId, $zoneId, _viewersHostOkayToLog($adId, $zoneId))); } function MAX_Delivery_log_logConversion($trackerId, $aConversion) { if (empty($GLOBALS['_MAX']['CONF']['logging']['trackerImpressions'])) { return true; } $aConf = $GLOBALS['_MAX']['CONF']; if (!empty($aConf['lb']['enabled'])) { $aConf['rawDatabase']['host'] = $_SERVER['SERVER_ADDR']; } else { $aConf['rawDatabase']['host'] = 'singleDB'; } if (isset($aConf['rawDatabase']['serverRawIp'])) { $serverRawIp = $aConf['rawDatabase']['serverRawIp']; } else { $serverRawIp = $aConf['rawDatabase']['host']; } $aConversionInfo = OX_Delivery_Common_hook('logConversion', array($trackerId, $serverRawIp, $aConversion, _viewersHostOkayToLog(null, null, $trackerId))); if (is_array($aConversionInfo)) { return $aConversionInfo; } return false; } function MAX_Delivery_log_logVariableValues($aVariables, $trackerId, $serverConvId, $serverRawIp) { $aConf = $GLOBALS['_MAX']['CONF']; foreach ($aVariables as $aVariable) { if (isset($_GET[$aVariable['name']])) { $value = $_GET[$aVariable['name']]; if (!strlen($value) || $value == 'undefined') { unset($aVariables[$aVariable['variable_id']]); continue; } switch ($aVariable['type']) { case 'int': case 'numeric': $value = preg_replace('/[^0-9.]/', '', $value); $value = floatval($value); break; case 'date': if (!empty($value)) { $value = date('Y-m-d H:i:s', strtotime($value)); } else { $value = ''; } break; } } else { unset($aVariables[$aVariable['variable_id']]); continue; } $aVariables[$aVariable['variable_id']]['value'] = $value; } if (count($aVariables)) { OX_Delivery_Common_hook('logConversionVariable', array($aVariables, $trackerId, $serverConvId, $serverRawIp, _viewersHostOkayToLog(null, null, $trackerId))); } } function _viewersHostOkayToLog($adId=0, $zoneId=0, $trackerId=0) { $aConf = $GLOBALS['_MAX']['CONF']; $agent = strtolower($_SERVER['HTTP_USER_AGENT']); $okToLog = true; if (!empty($aConf['logging']['enforceUserAgents'])) { $aKnownBrowsers = explode('|', strtolower($aConf['logging']['enforceUserAgents'])); $allowed = false; foreach ($aKnownBrowsers as $browser) { if (strpos($agent, $browser) !== false) { $allowed = true; break; } } OX_Delivery_logMessage('user-agent browser : '.$agent.' is '.($allowed ? '' : 'not ').'allowed', 7); if (!$allowed) { $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'enforceUserAgents'; $okToLog = false; } } if (!empty($aConf['logging']['ignoreUserAgents'])) { $aKnownBots = explode('|', strtolower($aConf['logging']['ignoreUserAgents'])); foreach ($aKnownBots as $bot) { if (strpos($agent, $bot) !== false) { OX_Delivery_logMessage('user-agent '.$agent.' is a known bot '.$bot, 7); $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreUserAgents'; $okToLog = false; } } } if (!empty($aConf['logging']['ignoreHosts'])) { $hosts = str_replace(',', '|', $aConf['logging']['ignoreHosts']); $hosts = '#^('.$hosts.')$#i'; $hosts = str_replace('.', '\.', $hosts); $hosts = str_replace('*', '[^.]+', $hosts); if (preg_match($hosts, $_SERVER['REMOTE_ADDR'])) { OX_Delivery_logMessage('viewer\'s ip is in the ignore list '.$_SERVER['REMOTE_ADDR'], 7); $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreHosts_ip'; $okToLog = false; } if (preg_match($hosts, $_SERVER['REMOTE_HOST'])) { OX_Delivery_logMessage('viewer\'s host is in the ignore list '.$_SERVER['REMOTE_HOST'], 7); $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreHosts_host'; $okToLog = false; } } if ($okToLog) OX_Delivery_logMessage('viewer\'s host is OK to log', 7); $result = OX_Delivery_Common_Hook('filterEvent', array($adId, $zoneId, $trackerId)); if (!empty($result) && is_array($result)) { foreach ($result as $pci => $value) { if ($value == true) { $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = $pci; $okToLog = false; } } } return $okToLog; } function MAX_Delivery_log_getArrGetVariable($name) { $varName = $GLOBALS['_MAX']['CONF']['var'][$name]; return isset($_GET[$varName]) ? explode($GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'], $_GET[$varName]) : array(); } function MAX_Delivery_log_ensureIntegerSet(&$aArray, $index) { if (!is_array($aArray)) { $aArray = array(); } if (empty($aArray[$index])) { $aArray[$index] = 0; } else { if (!is_integer($aArray[$index])) { $aArray[$index] = intval($aArray[$index]); } } } function MAX_Delivery_log_setAdLimitations($index, $aAds, $aCaps) { _setLimitations('Ad', $index, $aAds, $aCaps); } function MAX_Delivery_log_setCampaignLimitations($index, $aCampaigns, $aCaps) { _setLimitations('Campaign', $index, $aCampaigns, $aCaps); } function MAX_Delivery_log_setZoneLimitations($index, $aZones, $aCaps) { _setLimitations('Zone', $index, $aZones, $aCaps); } function MAX_Delivery_log_setLastAction($index, $aAdIds, $aZoneIds, $aSetLastSeen, $action = 'view') { $aConf = $GLOBALS['_MAX']['CONF']; if (!empty($aSetLastSeen[$index])) { $cookieData = MAX_commonCompressInt(MAX_commonGetTimeNow()) . "-" . $aZoneIds[$index]; $conversionParams = OX_Delivery_Common_hook('addConversionParams', array(&$index, &$aAdIds, &$aZoneIds, &$aSetLastSeen, &$action, &$cookieData)); if (!empty($conversionParams) && is_array($conversionParams)) { foreach ($conversionParams as $params) { if (!empty($params) && is_array($params)) { foreach ($params as $key => $value) { $cookieData .= " {$value}"; } } } } MAX_cookieAdd("_{$aConf['var']['last' . ucfirst($action)]}[{$aAdIds[$index]}]", $cookieData, _getTimeThirtyDaysFromNow()); } } function MAX_Delivery_log_setClickBlocked($index, $aAdIds) { $aConf = $GLOBALS['_MAX']['CONF']; MAX_cookieAdd("_{$aConf['var']['blockLoggingClick']}[{$aAdIds[$index]}]", MAX_commonCompressInt(MAX_commonGetTimeNow()), _getTimeThirtyDaysFromNow()); } function MAX_Delivery_log_isClickBlocked($adId, $aBlockLoggingClick) { if (isset($GLOBALS['conf']['logging']['blockAdClicksWindow']) && $GLOBALS['conf']['logging']['blockAdClicksWindow'] != 0) { if (isset($aBlockLoggingClick[$adId])) { $endBlock = MAX_commonUnCompressInt($aBlockLoggingClick[$adId]) + $GLOBALS['conf']['logging']['blockAdClicksWindow']; if ($endBlock >= MAX_commonGetTimeNow()) { OX_Delivery_logMessage('adID '.$adId.' click is still blocked by block logging window ', 7); return true; } } } return false; } function _setLimitations($type, $index, $aItems, $aCaps) { MAX_Delivery_log_ensureIntegerSet($aCaps['block'], $index); MAX_Delivery_log_ensureIntegerSet($aCaps['capping'], $index); MAX_Delivery_log_ensureIntegerSet($aCaps['session_capping'], $index); MAX_Delivery_cookie_setCapping( $type, $aItems[$index], $aCaps['block'][$index], $aCaps['capping'][$index], $aCaps['session_capping'][$index] ); } function MAX_commonGetDeliveryUrl($file = null) { $conf = $GLOBALS['_MAX']['CONF']; if ($GLOBALS['_MAX']['SSL_REQUEST']) { $url = MAX_commonConstructSecureDeliveryUrl($file); } else { $url = MAX_commonConstructDeliveryUrl($file); } return $url; } function MAX_commonConstructDeliveryUrl($file) { $conf = $GLOBALS['_MAX']['CONF']; return 'http://' . $conf['webpath']['delivery'] . '/' . $file; } function MAX_commonConstructSecureDeliveryUrl($file) { $conf = $GLOBALS['_MAX']['CONF']; if ($conf['openads']['sslPort'] != 443) { $path = preg_replace('#/#', ':' . $conf['openads']['sslPort'] . '/', $conf['webpath']['deliverySSL'], 1); } else { $path = $conf['webpath']['deliverySSL']; } return 'https://' . $path . '/' . $file; } function MAX_commonConstructPartialDeliveryUrl($file, $ssl = false) { $conf = $GLOBALS['_MAX']['CONF']; if ($ssl) { return '//' . $conf['webpath']['deliverySSL'] . '/' . $file; } else { return '//' . $conf['webpath']['delivery'] . '/' . $file; } } function MAX_commonRemoveSpecialChars(&$var) { static $magicQuotes; if (!isset($magicQuotes)) { $magicQuotes = get_magic_quotes_gpc(); } if (isset($var)) { if (!is_array($var)) { if ($magicQuotes) { $var = stripslashes($var); } $var = strip_tags($var); $var = str_replace(array("\n", "\r"), array('', ''), $var); $var = trim($var); } else { array_walk($var, 'MAX_commonRemoveSpecialChars'); } } } function MAX_commonConvertEncoding($content, $toEncoding, $fromEncoding = 'UTF-8', $aExtensions = null) { if (($toEncoding == $fromEncoding) || empty($toEncoding)) { return $content; } if (!isset($aExtensions) || !is_array($aExtensions)) { $aExtensions = array('iconv', 'mbstring', 'xml'); } if (is_array($content)) { foreach ($content as $key => $value) { $content[$key] = MAX_commonConvertEncoding($value, $toEncoding, $fromEncoding, $aExtensions); } return $content; } else { $toEncoding = strtoupper($toEncoding); $fromEncoding = strtoupper($fromEncoding); $aMap = array(); $aMap['mbstring']['WINDOWS-1255'] = 'ISO-8859-8'; $aMap['xml']['ISO-8859-15'] = 'ISO-8859-1'; $converted = false; foreach ($aExtensions as $extension) { $mappedFromEncoding = isset($aMap[$extension][$fromEncoding]) ? $aMap[$extension][$fromEncoding] : $fromEncoding; $mappedToEncoding = isset($aMap[$extension][$toEncoding]) ? $aMap[$extension][$toEncoding] : $toEncoding; switch ($extension) { case 'iconv': if (function_exists('iconv')) { $converted = @iconv($mappedFromEncoding, $mappedToEncoding, $content); } break; case 'mbstring': if (function_exists('mb_convert_encoding')) { $converted = @mb_convert_encoding($content, $mappedToEncoding, $mappedFromEncoding); } break; case 'xml': if (function_exists('utf8_encode')) { if ($mappedToEncoding == 'UTF-8' && $mappedFromEncoding == 'ISO-8859-1') { $converted = utf8_encode($content); } elseif ($mappedToEncoding == 'ISO-8859-1' && $mappedFromEncoding == 'UTF-8') { $converted = utf8_decode($content); } } break; } } return $converted ? $converted : $content; } } function MAX_commonSendContentTypeHeader($type = 'text/html', $charset = null) { $header = 'Content-type: ' . $type; if (!empty($charset) && preg_match('/^[a-zA-Z0-9_-]+$/D', $charset)) { $header .= '; charset=' . $charset; } MAX_header($header); } function MAX_commonSetNoCacheHeaders() { MAX_header('Pragma: no-cache'); MAX_header('Cache-Control: private, max-age=0, no-cache'); MAX_header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); } function MAX_commonAddslashesRecursive($a) { if (is_array($a)) { reset($a); while (list($k,$v) = each($a)) { $a[$k] = MAX_commonAddslashesRecursive($v); } reset ($a); return ($a); } else { return is_null($a) ? null : addslashes($a); } } function MAX_commonRegisterGlobalsArray($args = array()) { static $magic_quotes_gpc; if (!isset($magic_quotes_gpc)) { $magic_quotes_gpc = ini_get('magic_quotes_gpc'); } $found = false; foreach($args as $key) { if (isset($_GET[$key])) { $value = $_GET[$key]; $found = true; } if (isset($_POST[$key])) { $value = $_POST[$key]; $found = true; } if ($found) { if (!$magic_quotes_gpc) { if (!is_array($value)) { $value = addslashes($value); } else { $value = MAX_commonAddslashesRecursive($value); } } $GLOBALS[$key] = $value; $found = false; } } } function MAX_commonDeriveSource($source) { return MAX_commonEncrypt(trim(urldecode($source))); } function MAX_commonEncrypt($string) { $convert = ''; if (isset($string) && substr($string,1,4) != 'obfs' && $GLOBALS['_MAX']['CONF']['delivery']['obfuscate']) { $strLen = strlen($string); for ($i=0; $i < $strLen; $i++) { $dec = ord(substr($string,$i,1)); if (strlen($dec) == 2) { $dec = 0 . $dec; } $dec = 324 - $dec; $convert .= $dec; } $convert = '{obfs:' . $convert . '}'; return ($convert); } else { return $string; } } function MAX_commonDecrypt($string) { $conf = $GLOBALS['_MAX']['CONF']; $convert = ''; if (isset($string) && substr($string,1,4) == 'obfs' && $conf['delivery']['obfuscate']) { $strLen = strlen($string); for ($i=6; $i < $strLen-1; $i = $i+3) { $dec = substr($string,$i,3); $dec = 324 - $dec; $dec = chr($dec); $convert .= $dec; } return ($convert); } else { return($string); } } function MAX_commonInitVariables() { MAX_commonRegisterGlobalsArray(array('context', 'source', 'target', 'withText', 'withtext', 'ct0', 'what', 'loc', 'referer', 'zoneid', 'campaignid', 'bannerid', 'clientid', 'charset')); global $context, $source, $target, $withText, $withtext, $ct0, $what, $loc, $referer, $zoneid, $campaignid, $bannerid, $clientid, $charset; if (isset($withText) && !isset($withtext)) $withtext = $withText; $withtext = (isset($withtext) && is_numeric($withtext) ? $withtext : 0 ); $ct0 = (isset($ct0) ? $ct0 : '' ); $context = (isset($context) ? $context : array() ); $target = (isset($target) && (!empty($target)) && (!strpos($target , chr(32))) ? $target : '' ); $charset = (isset($charset) && (!empty($charset)) && (!strpos($charset, chr(32))) ? $charset : 'UTF-8' ); $bannerid = (isset($bannerid) && is_numeric($bannerid) ? $bannerid : '' ); $campaignid = (isset($campaignid) && is_numeric($campaignid) ? $campaignid : '' ); $clientid = (isset($clientid) && is_numeric($clientid) ? $clientid : '' ); $zoneid = (isset($zoneid) && is_numeric($zoneid) ? $zoneid : '' ); if (!isset($what)) { if (!empty($bannerid)) { $what = 'bannerid:'.$bannerid; } elseif (!empty($campaignid)) { $what = 'campaignid:'.$campaignid; } elseif (!empty($zoneid)) { $what = 'zone:'.$zoneid; } else { $what = ''; } } elseif (preg_match('/^([a-z]+):(\d+)$/', $what, $matches)) { switch ($matches[1]) { case 'zoneid': case 'zone': $zoneid = $matches[2]; break; case 'bannerid': $bannerid = $matches[2]; break; case 'campaignid': $campaignid = $matches[2]; break; case 'clientid': $clientid = $matches[2]; break; } } if (!isset($clientid)) $clientid = ''; if (empty($campaignid)) $campaignid = $clientid; $source = MAX_commonDeriveSource($source); if (!empty($loc)) { $loc = stripslashes($loc); } elseif (!empty($_SERVER['HTTP_REFERER'])) { $loc = $_SERVER['HTTP_REFERER']; } else { $loc = ''; } if (!empty($referer)) { $_SERVER['HTTP_REFERER'] = stripslashes($referer); } else { if (isset($_SERVER['HTTP_REFERER'])) unset($_SERVER['HTTP_REFERER']); } $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'] = array( $GLOBALS['_MAX']['CONF']['var']['blockAd'], $GLOBALS['_MAX']['CONF']['var']['capAd'], $GLOBALS['_MAX']['CONF']['var']['sessionCapAd'], $GLOBALS['_MAX']['CONF']['var']['blockCampaign'], $GLOBALS['_MAX']['CONF']['var']['capCampaign'], $GLOBALS['_MAX']['CONF']['var']['sessionCapCampaign'], $GLOBALS['_MAX']['CONF']['var']['blockZone'], $GLOBALS['_MAX']['CONF']['var']['capZone'], $GLOBALS['_MAX']['CONF']['var']['sessionCapZone'], $GLOBALS['_MAX']['CONF']['var']['lastClick'], $GLOBALS['_MAX']['CONF']['var']['lastView'], $GLOBALS['_MAX']['CONF']['var']['blockLoggingClick'], ); if (strtolower($charset) == 'unicode') { $charset = 'utf-8'; } } function MAX_commonDisplay1x1() { MAX_header('Content-Type: image/gif'); MAX_header('Content-Length: 43'); echo base64_decode('R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=='); } function MAX_commonGetTimeNow() { if (!isset($GLOBALS['_MAX']['NOW'])) { $GLOBALS['_MAX']['NOW'] = time(); } return $GLOBALS['_MAX']['NOW']; } function MAX_getRandomNumber($length = 10) { return substr(md5(uniqid(time(), true)), 0, $length); } function MAX_header($value) { header($value); } function MAX_redirect($url) { if (!preg_match('/^(?:javascript|data):/i', $url)) { header('Location: '.$url); MAX_sendStatusCode(302); } } function MAX_sendStatusCode($iStatusCode) { $aConf = $GLOBALS['_MAX']['CONF']; $arr = array( 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => '[Unused]', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported' ); if (isset($arr[$iStatusCode])) { $text = $iStatusCode . ' ' . $arr[$iStatusCode]; if (!empty($aConf['delivery']['cgiForceStatusHeader']) && strpos(php_sapi_name(), 'cgi') !== 0) { MAX_header('Status: ' . $text); } else { MAX_header($_SERVER["SERVER_PROTOCOL"] .' ' . $text); } } } function MAX_commonPackContext($context = array()) { $include = array(); $exclude = array(); foreach ($context as $idx => $value) { reset($value); list($key, $value) = each($value); list($item,$id) = explode(':', $value); switch ($item) { case 'campaignid': $value = 'c:' . $id; break; case 'clientid': $value = 'a:' . $id; break; case 'bannerid': $value = 'b:' . $id; break; case 'companionid': $value = 'p:' . $id; break; } switch ($key) { case '!=': $exclude[$value] = true; break; case '==': $include[$value] = true; break; } } $exclude = array_keys($exclude); $include = array_keys($include); return base64_encode(implode('#', $exclude) . '|' . implode('#', $include)); } function MAX_commonUnpackContext($context = '') { list($exclude,$include) = explode('|', base64_decode($context)); return array_merge(_convertContextArray('!=', explode('#', $exclude)), _convertContextArray('==', explode('#', $include))); } function MAX_commonCompressInt($int) { return base_convert($int, 10, 36); } function MAX_commonUnCompressInt($string) { return base_convert($string, 36, 10); } function _convertContextArray($key, $array) { $unpacked = array(); foreach ($array as $value) { if (empty($value)) { continue; } list($item, $id) = explode(':', $value); switch ($item) { case 'c': $unpacked[] = array($key => 'campaignid:' . $id); break; case 'a': $unpacked[] = array($key => 'clientid:' . $id); break; case 'b': $unpacked[] = array($key => 'bannerid:' . $id); break; case 'p': $unpacked[] = array($key => 'companionid:'.$id); break; } } return $unpacked; } function OX_Delivery_Common_hook($hookName, $aParams = array(), $functionName = '') { $return = null; if (!empty($functionName)) { $aParts = explode(':', $functionName); if (count($aParts) === 3) { $functionName = OX_Delivery_Common_getFunctionFromComponentIdentifier($functionName, $hookName); } if (function_exists($functionName)) { $return = call_user_func_array($functionName, $aParams); } } else { if (!empty($GLOBALS['_MAX']['CONF']['deliveryHooks'][$hookName])) { $return = array(); $hooks = explode('|', $GLOBALS['_MAX']['CONF']['deliveryHooks'][$hookName]); foreach ($hooks as $identifier) { $functionName = OX_Delivery_Common_getFunctionFromComponentIdentifier($identifier, $hookName); if (function_exists($functionName)) { OX_Delivery_logMessage('calling on '.$functionName, 7); $return[$identifier] = call_user_func_array($functionName, $aParams); } } } } return $return; } function OX_Delivery_Common_getFunctionFromComponentIdentifier($identifier, $hook = null) { $aInfo = explode(':', $identifier); $functionName = 'Plugin_' . implode('_', $aInfo) . '_Delivery' . (!empty($hook) ? '_' . $hook : ''); if (!function_exists($functionName)) { if (!empty($GLOBALS['_MAX']['CONF']['pluginSettings']['useMergedFunctions'])) _includeDeliveryPluginFile('/var/cache/' . OX_getHostName() . '_mergedDeliveryFunctions.php'); if (!function_exists($functionName)) { _includeDeliveryPluginFile($GLOBALS['_MAX']['CONF']['pluginPaths']['plugins'] . '/' . implode('/', $aInfo) . '.delivery.php'); if (!function_exists($functionName)) { _includeDeliveryPluginFile('/lib/OX/Extension/' . $aInfo[0] . '/' . $aInfo[0] . 'Delivery.php'); $functionName = 'Plugin_' . $aInfo[0] . '_delivery'; if (!empty($hook) && function_exists($functionName . '_' . $hook)) { $functionName .= '_' . $hook; } } } } return $functionName; } function _includeDeliveryPluginFile($fileName) { if (!in_array($fileName, array_keys($GLOBALS['_MAX']['FILES']))) { $GLOBALS['_MAX']['FILES'][$fileName] = true; if (file_exists(MAX_PATH . $fileName)) { include MAX_PATH . $fileName; } } } function OX_Delivery_logMessage($message, $priority = 6) { $conf = $GLOBALS['_MAX']['CONF']; if (empty($conf['deliveryLog']['enabled'])) return true; $priorityLevel = is_numeric($conf['deliveryLog']['priority']) ? $conf['deliveryLog']['priority'] : 6; if ($priority > $priorityLevel && empty($_REQUEST[$conf['var']['trace']])) { return true; } error_log('[' . date('r') . "] {$conf['log']['ident']}-delivery-{$GLOBALS['_MAX']['thread_id']}: {$message}\n", 3, MAX_PATH . '/var/' . $conf['deliveryLog']['name']); OX_Delivery_Common_hook('logMessage', array($message, $priority)); return true; } $file = '/lib/max/Delivery/cache.php'; $GLOBALS['_MAX']['FILES'][$file] = true; define ('OA_DELIVERY_CACHE_FUNCTION_ERROR', 'Function call returned an error'); $GLOBALS['OA_Delivery_Cache'] = array( 'prefix' => 'deliverycache_', 'host' => OX_getHostName(), 'expiry' => $GLOBALS['_MAX']['CONF']['delivery']['cacheExpire'] ); function OA_Delivery_Cache_fetch($name, $isHash = false, $expiryTime = null) { $filename = OA_Delivery_Cache_buildFileName($name, $isHash); $aCacheVar = OX_Delivery_Common_hook( 'cacheRetrieve', array($filename), $GLOBALS['_MAX']['CONF']['delivery']['cacheStorePlugin'] ); if ($aCacheVar !== false) { if ($aCacheVar['cache_name'] != $name) { OX_Delivery_logMessage("Cache ERROR: {$name} != {$aCacheVar['cache_name']}", 7); return false; } if ($expiryTime === null) { $expiryTime = $GLOBALS['OA_Delivery_Cache']['expiry']; } $now = MAX_commonGetTimeNow(); if ( (isset($aCacheVar['cache_time']) && $aCacheVar['cache_time'] + $expiryTime < $now) || (isset($aCacheVar['cache_expire']) && $aCacheVar['cache_expire'] < $now) ) { OA_Delivery_Cache_store($name, $aCacheVar['cache_contents'], $isHash); OX_Delivery_logMessage("Cache EXPIRED: {$name}", 7); return false; } OX_Delivery_logMessage("Cache HIT: {$name}", 7); return $aCacheVar['cache_contents']; } OX_Delivery_logMessage("Cache MISS {$name}", 7); return false; } function OA_Delivery_Cache_store($name, $cache, $isHash = false, $expireAt = null) { if ($cache === OA_DELIVERY_CACHE_FUNCTION_ERROR) { return false; } $filename = OA_Delivery_Cache_buildFileName($name, $isHash); $aCacheVar = array(); $aCacheVar['cache_contents'] = $cache; $aCacheVar['cache_name'] = $name; $aCacheVar['cache_time'] = MAX_commonGetTimeNow(); $aCacheVar['cache_expire'] = $expireAt; return OX_Delivery_Common_hook( 'cacheStore', array($filename, $aCacheVar), $GLOBALS['_MAX']['CONF']['delivery']['cacheStorePlugin'] ); } function OA_Delivery_Cache_store_return($name, $cache, $isHash = false, $expireAt = null) { OX_Delivery_Common_hook( 'preCacheStore_'.OA_Delivery_Cache_getHookName($name), array($name, &$cache) ); if (OA_Delivery_Cache_store($name, $cache, $isHash, $expireAt)) { return $cache; } $currentCache = OA_Delivery_Cache_fetch($name, $isHash); if ($currentCache === false) { return $cache; } return $currentCache; } function OA_Delivery_Cache_getHookName($name) { $pos = strpos($name, '^'); return $pos ? substr($name, 0, $pos) : substr($name, 0, strpos($name, '@')); } function OA_Delivery_Cache_buildFileName($name, $isHash = false) { if(!$isHash) { $name = md5($name); } return $GLOBALS['OA_Delivery_Cache']['prefix'].$name.'.php'; } function OA_Delivery_Cache_getName($functionName) { $args = func_get_args(); $args[0] = strtolower(str_replace('MAX_cacheGet', '', $args[0])); return join('^', $args).'@'.$GLOBALS['OA_Delivery_Cache']['host']; } function MAX_cacheGetAd($ad_id, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $ad_id); if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aRows = OA_Dal_Delivery_getAd($ad_id); $aRows = OA_Delivery_Cache_store_return($sName, $aRows); } return $aRows; } function MAX_cacheGetAccountTZs($cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__); if (!$cached || ($aResult = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aResult = OA_Dal_Delivery_getAccountTZs(); $aResult = OA_Delivery_Cache_store_return($sName, $aResult); } return $aResult; } function MAX_cacheGetZoneLinkedAds($zoneId, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId); if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aRows = OA_Dal_Delivery_getZoneLinkedAds($zoneId); $aRows = OA_Delivery_Cache_store_return($sName, $aRows); } return $aRows; } function MAX_cacheGetZoneLinkedAdInfos($zoneId, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId); if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aRows = OA_Dal_Delivery_getZoneLinkedAdInfos($zoneId); $aRows = OA_Delivery_Cache_store_return($sName, $aRows); } return $aRows; } function MAX_cacheGetZoneInfo($zoneId, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId); if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aRows = OA_Dal_Delivery_getZoneInfo($zoneId); $aRows = OA_Delivery_Cache_store_return($sName, $aRows); } return $aRows; } function MAX_cacheGetLinkedAds($search, $campaignid, $laspart, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $search, $campaignid, $laspart); if (!$cached || ($aAds = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aAds = OA_Dal_Delivery_getLinkedAds($search, $campaignid, $laspart); $aAds = OA_Delivery_Cache_store_return($sName, $aAds); } return $aAds; } function MAX_cacheGetLinkedAdInfos($search, $campaignid, $laspart, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $search, $campaignid, $laspart); if (!$cached || ($aAds = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aAds = OA_Dal_Delivery_getLinkedAdInfos($search, $campaignid, $laspart); $aAds = OA_Delivery_Cache_store_return($sName, $aAds); } return $aAds; } function MAX_cacheGetCreative($filename, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $filename); if (!$cached || ($aCreative = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aCreative = OA_Dal_Delivery_getCreative($filename); $aCreative['contents'] = addslashes(serialize($aCreative['contents'])); $aCreative = OA_Delivery_Cache_store_return($sName, $aCreative); } $aCreative['contents'] = unserialize(stripslashes($aCreative['contents'])); return $aCreative; } function MAX_cacheGetTracker($trackerid, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid); if (!$cached || ($aTracker = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aTracker = OA_Dal_Delivery_getTracker($trackerid); $aTracker = OA_Delivery_Cache_store_return($sName, $aTracker); } return $aTracker; } function MAX_cacheGetTrackerLinkedCreatives($trackerid = null, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid); if (!$cached || ($aTracker = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aTracker = OA_Dal_Delivery_getTrackerLinkedCreatives($trackerid); $aTracker = OA_Delivery_Cache_store_return($sName, $aTracker); } return $aTracker; } function MAX_cacheGetTrackerVariables($trackerid, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid); if (!$cached || ($aVariables = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aVariables = OA_Dal_Delivery_getTrackerVariables($trackerid); $aVariables = OA_Delivery_Cache_store_return($sName, $aVariables); } return $aVariables; } function MAX_cacheCheckIfMaintenanceShouldRun($cached = true) { $interval = $GLOBALS['_MAX']['CONF']['maintenance']['operationInterval'] * 60; $delay = intval(($GLOBALS['_MAX']['CONF']['maintenance']['operationInterval'] / 12) * 60); $now = MAX_commonGetTimeNow(); $today = strtotime(date('Y-m-d'), $now); $nextRunTime = $today + (floor(($now - $today) / $interval) + 1) * $interval + $delay; if ($nextRunTime - $now > $interval) { $nextRunTime -= $interval; } $cName = OA_Delivery_Cache_getName(__FUNCTION__); if (!$cached || ($lastRunTime = OA_Delivery_Cache_fetch($cName)) === false) { MAX_Dal_Delivery_Include(); $lastRunTime = OA_Dal_Delivery_getMaintenanceInfo(); if ($lastRunTime >= $nextRunTime - $delay) { $nextRunTime += $interval; } OA_Delivery_Cache_store($cName, $lastRunTime, false, $nextRunTime); } return $lastRunTime < $nextRunTime - $interval; } function MAX_cacheGetChannelLimitations($channelid, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $channelid); if (!$cached || ($limitations = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $limitations = OA_Dal_Delivery_getChannelLimitations($channelid); $limitations = OA_Delivery_Cache_store_return($sName, $limitations); } return $limitations; } function MAX_cacheGetGoogleJavaScript($cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__); if (!$cached || ($output = OA_Delivery_Cache_fetch($sName)) === false) { $file = '/lib/max/Delivery/google.php'; if(!isset($GLOBALS['_MAX']['FILES'][$file])) { include MAX_PATH . $file; } $output = MAX_googleGetJavaScript(); $output = OA_Delivery_Cache_store_return($sName, $output); } return $output; } function OA_cacheGetPublisherZones($affiliateid, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $affiliateid); if (!$cached || ($output = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $output = OA_Dal_Delivery_getPublisherZones($affiliateid); $output = OA_Delivery_Cache_store_return($sName, $output); } return $output; } OX_Delivery_logMessage('starting delivery script: ' . basename($_SERVER['REQUEST_URI']), 7); if (!empty($_REQUEST[$conf['var']['trace']])) { OX_Delivery_logMessage('trace enabled: ' . $_REQUEST[$conf['var']['trace']], 7); } MAX_remotehostSetInfo(); MAX_commonInitVariables(); MAX_cookieLoad(); MAX_cookieUnpackCapping(); if (empty($GLOBALS['_OA']['invocationType']) || $GLOBALS['_OA']['invocationType'] != 'xmlrpc') { OX_Delivery_Common_hook('postInit'); } function MAX_querystringConvertParams() { $conf = $GLOBALS['_MAX']['CONF']; $qs = $_SERVER['QUERY_STRING']; $dest = false; $destStr = $conf['var']['dest'] . '='; $pos = strpos($qs, $destStr); if ($pos === false) { $destStr = 'dest='; $pos = strpos($qs, $destStr); } if ($pos !== false) { $dest = urldecode(substr($qs, $pos + strlen($destStr))); $qs = substr($qs, 0, $pos); } $aGet = array(); $paramStr = $conf['var']['params'] . '='; $paramPos = strpos($qs, $paramStr); if (is_numeric($paramPos)) { $qs = urldecode(substr($qs, $paramPos + strlen($paramStr))); $delim = $qs{0}; if (is_numeric($delim)) { $delim = substr($qs, 1, $delim); } $qs = substr($qs, strlen($delim) + 1); MAX_querystringParseStr($qs, $aGet, $delim); $qPos = isset($aGet[$conf['var']['dest']]) ? strpos($aGet[$conf['var']['dest']], '?') : false; $aPos = isset($aGet[$conf['var']['dest']]) ? strpos($aGet[$conf['var']['dest']], '&') : false; if ($aPos && !$qPos) { $desturl = substr($aGet[$conf['var']['dest']], 0, $aPos); $destparams = substr($aGet[$conf['var']['dest']], $aPos+1); $aGet[$conf['var']['dest']] = $desturl . '?' . $destparams; } } else { parse_str($qs, $aGet); } if ($dest !== false) { $aGet[$conf['var']['dest']] = $dest; } $n = isset($_GET[$conf['var']['n']]) ? $_GET[$conf['var']['n']] : ''; if (empty($n)) { $n = isset($aGet[$conf['var']['n']]) ? $aGet[$conf['var']['n']] : ''; } if (!empty($n) && !empty($_COOKIE[$conf['var']['vars']][$n])) { $aVars = unserialize(stripslashes($_COOKIE[$conf['var']['vars']][$n])); foreach ($aVars as $name => $value) { if (!isset($_GET[$name])) { $aGet[$name] = $value; } } } $_GET = $aGet; $_REQUEST = $_GET + $_POST + $_COOKIE; } function MAX_querystringGetDestinationUrl($adId = null) { $conf = $GLOBALS['_MAX']['CONF']; $dest = isset($_REQUEST[$conf['var']['dest']]) ? $_REQUEST[$conf['var']['dest']] : ''; if (empty($dest) && !empty($adId)) { $aAd = MAX_cacheGetAd($adId); if (!empty($aAd)) { $dest = $aAd['url']; } } if (empty($dest)) { return; } $aVariables = array(); $aValidVariables = array_values($conf['var']); $componentParams = OX_Delivery_Common_hook('addUrlParams', array(array('bannerid' => $adId))); if (!empty($componentParams) && is_array($componentParams)) { foreach ($componentParams as $params) { if (!empty($params) && is_array($params)) { foreach ($params as $key => $value) { $aValidVariables[] = $key; } } } } $destParams = parse_url($dest); if (!empty($destParams['query'])) { $destQuery = explode('&', $destParams['query']); if (!empty($destQuery)) { foreach ($destQuery as $destPair) { list($destName, $destValue) = explode('=', $destPair); $aValidVariables[] = $destName; } } } foreach ($_GET as $name => $value) { if (!in_array($name, $aValidVariables)) { $aVariables[] = $name . '=' . $value; } } foreach ($_POST as $name => $value) { if (!in_array($name, $aValidVariables)) { $aVariables[] = $name . '=' . $value; } } if (!empty($aVariables)) { $dest .= ((strpos($dest, '?') > 0) ? '&' : '?') . implode('&', $aVariables); } return $dest; } function MAX_querystringParseStr($qs, &$aArr, $delim = '&') { $aArr = $_GET; $aElements = explode($delim, $qs); foreach($aElements as $element) { $len = strpos($element, '='); if ($len !== false) { $name = substr($element, 0, $len); $value = substr($element, $len+1); $aArr[$name] = urldecode($value); } } } MAX_commonSetNoCacheHeaders(); MAX_commonRemoveSpecialChars($_REQUEST); $viewerId = MAX_cookieGetUniqueViewerId(); MAX_cookieAdd($conf['var']['viewerId'], $viewerId, _getTimeYearFromNow()); $aAdIds = MAX_Delivery_log_getArrGetVariable('adId'); $aCampaignIds = MAX_Delivery_log_getArrGetVariable('campaignId'); $aCreativeIds = MAX_Delivery_log_getArrGetVariable('creativeId'); $aZoneIds = MAX_Delivery_log_getArrGetVariable('zoneId'); $aCapAd['block'] = MAX_Delivery_log_getArrGetVariable('blockAd'); $aCapAd['capping'] = MAX_Delivery_log_getArrGetVariable('capAd'); $aCapAd['session_capping'] = MAX_Delivery_log_getArrGetVariable('sessionCapAd'); $aCapCampaign['block'] = MAX_Delivery_log_getArrGetVariable('blockCampaign'); $aCapCampaign['capping'] = MAX_Delivery_log_getArrGetVariable('capCampaign'); $aCapCampaign['session_capping'] = MAX_Delivery_log_getArrGetVariable('sessionCapCampaign'); $aCapZone['block'] = MAX_Delivery_log_getArrGetVariable('blockZone'); $aCapZone['capping'] = MAX_Delivery_log_getArrGetVariable('capZone'); $aCapZone['session_capping'] = MAX_Delivery_log_getArrGetVariable('sessionCapZone'); $aSetLastSeen = MAX_Delivery_log_getArrGetVariable('lastView'); $countAdIds = count($aAdIds); for ($index = 0; $index < $countAdIds; $index++) { MAX_Delivery_log_ensureIntegerSet($aAdIds, $index); MAX_Delivery_log_ensureIntegerSet($aCampaignIds, $index); MAX_Delivery_log_ensureIntegerSet($aCreativeIds, $index); MAX_Delivery_log_ensureIntegerSet($aZoneIds, $index); if ($aAdIds[$index] >= -1) { $adId = $aAdIds[$index]; if ($GLOBALS['_MAX']['CONF']['logging']['adImpressions']) { MAX_Delivery_log_logAdImpression($adId, $aZoneIds[$index]); } if ($aAdIds[$index] == $adId) { MAX_Delivery_log_setAdLimitations($index, $aAdIds, $aCapAd); MAX_Delivery_log_setCampaignLimitations($index, $aCampaignIds, $aCapCampaign); MAX_Delivery_log_setLastAction($index, $aAdIds, $aZoneIds, $aSetLastSeen); if ($aZoneIds[$index] != 0) { MAX_Delivery_log_setZoneLimitations($index, $aZoneIds, $aCapZone); } } } } MAX_cookieFlush(); MAX_querystringConvertParams(); if (!empty($_REQUEST[$GLOBALS['_MAX']['CONF']['var']['dest']])) { MAX_redirect($_REQUEST[$GLOBALS['_MAX']['CONF']['var']['dest']]); } else { MAX_commonDisplay1x1(); } if (!empty($GLOBALS['_MAX']['CONF']['maintenance']['autoMaintenance']) && empty($GLOBALS['_MAX']['CONF']['lb']['enabled'])) { if (MAX_cacheCheckIfMaintenanceShouldRun()) { include MAX_PATH . '/lib/OA/Maintenance/Auto.php'; OA_Maintenance_Auto::run(); } } ?>
kriwil/OpenX
www/delivery/lg.php
PHP
gpl-2.0
107,769
/* smpppdunsettled.cpp Copyright (c) 2006 by Heiko Schaefer <heiko@rangun.de> Kopete (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; version 2 of the License. * * * ************************************************************************* */ #include <cstdlib> #include <openssl/md5.h> #include <qregexp.h> #include <kdebug.h> #include <kstreamsocket.h> #include "smpppdready.h" #include "smpppdunsettled.h" using namespace SMPPPD; Unsettled * Unsettled::m_instance = NULL; Unsettled::Unsettled() {} Unsettled::~Unsettled() {} Unsettled * Unsettled::instance() { if(!m_instance) { m_instance = new Unsettled(); } return m_instance; } bool Unsettled::connect(Client * client, const QString& server, uint port) { if(!socket(client) || socket(client)->state() != KNetwork::KStreamSocket::Connected || socket(client)->state() != KNetwork::KStreamSocket::Connecting) { QString resolvedServer = server; changeState(client, Ready::instance()); disconnect(client); // since a lookup on a non-existant host can take a lot of time we // try to get the IP of server before and we do the lookup ourself KNetwork::KResolver resolver(server); resolver.start(); if(resolver.wait(500)) { KNetwork::KResolverResults results = resolver.results(); if(!results.empty()) { QString ip = results[0].address().asInet().ipAddress().toString(); kdDebug(14312) << k_funcinfo << "Found IP-Address for " << server << ": " << ip << endl; resolvedServer = ip; } else { kdWarning(14312) << k_funcinfo << "No IP-Address found for " << server << endl; return false; } } else { kdWarning(14312) << k_funcinfo << "Looking up hostname timed out, consider to use IP or correct host" << endl; return false; } setSocket(client, new KNetwork::KStreamSocket(resolvedServer, QString::number(port))); socket(client)->setBlocking(TRUE); if(!socket(client)->connect()) { kdDebug(14312) << k_funcinfo << "Socket Error: " << KNetwork::KStreamSocket::errorString(socket(client)->error()) << endl; } else { kdDebug(14312) << k_funcinfo << "Successfully connected to smpppd \"" << server << ":" << port << "\"" << endl; static QString verRex = "^SuSE Meta pppd \\(smpppd\\), Version (.*)$"; static QString clgRex = "^challenge = (.*)$"; QRegExp ver(verRex); QRegExp clg(clgRex); QString response = read(client)[0]; if(response != QString::null && ver.exactMatch(response)) { setServerID(client, response); setServerVersion(client, ver.cap(1)); changeState(client, Ready::instance()); return true; } else if(response != QString::null && clg.exactMatch(response)) { if(password(client) != QString::null) { // we are challenged, ok, respond write(client, QString("response = %1\n").arg(make_response(clg.cap(1).stripWhiteSpace(), password(client))).latin1()); response = read(client)[0]; if(ver.exactMatch(response)) { setServerID(client, response); setServerVersion(client, ver.cap(1)); return true; } else { kdWarning(14312) << k_funcinfo << "SMPPPD responded: " << response << endl; changeState(client, Ready::instance()); disconnect(client); } } else { kdWarning(14312) << k_funcinfo << "SMPPPD requested a challenge, but no password was supplied!" << endl; changeState(client, Ready::instance()); disconnect(client); } } } } return false; } QString Unsettled::make_response(const QString& chex, const QString& password) const { int size = chex.length (); if (size & 1) return "error"; size >>= 1; // convert challenge from hex to bin QString cbin; for (int i = 0; i < size; i++) { QString tmp = chex.mid (2 * i, 2); cbin.append ((char) strtol (tmp.ascii (), 0, 16)); } // calculate response unsigned char rbin[MD5_DIGEST_LENGTH]; MD5state_st md5; MD5_Init (&md5); MD5_Update (&md5, cbin.ascii (), size); MD5_Update (&md5, password.ascii(), password.length ()); MD5_Final (rbin, &md5); // convert response from bin to hex QString rhex; for (int i = 0; i < MD5_DIGEST_LENGTH; i++) { char buffer[3]; snprintf (buffer, 3, "%02x", rbin[i]); rhex.append (buffer); } return rhex; }
iegor/kdenetwork
kopete/plugins/smpppdcs/libsmpppdclient/smpppdunsettled.cpp
C++
gpl-2.0
5,200
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2011 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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 "Navigation/GeoPoint.hpp" #include "Navigation/Geometry/GeoVector.hpp" #include "Math/Earth.hpp" GeoPoint GeoPoint::parametric(const GeoPoint &delta, const fixed t) const { return (*this) + delta * t; } GeoPoint GeoPoint::interpolate(const GeoPoint &end, const fixed t) const { return (*this) + (end - (*this)) * t; } fixed GeoPoint::distance(const GeoPoint &other) const { return ::Distance(*this, other); } Angle GeoPoint::bearing(const GeoPoint &other) const { return ::Bearing(*this, other); } GeoVector GeoPoint::distance_bearing(const GeoPoint &other) const { GeoVector gv; ::DistanceBearing(*this, other, &gv.Distance, &gv.Bearing); return gv; } fixed GeoPoint::projected_distance(const GeoPoint &from, const GeoPoint &to) const { return ::ProjectedDistance(from, to, *this); } bool GeoPoint::equals(const GeoPoint &other) const { return (Longitude == other.Longitude) && (Latitude == other.Latitude); } bool GeoPoint::sort(const GeoPoint &sp) const { if (Longitude < sp.Longitude) return false; else if (Longitude == sp.Longitude) return Latitude > sp.Latitude; else return true; } GeoPoint GeoPoint::intermediate_point(const GeoPoint &destination, const fixed distance) const { return ::IntermediatePoint(*this, destination, distance); }
joachimwieland/xcsoar-jwieland
src/Engine/Navigation/GeoPoint.cpp
C++
gpl-2.0
2,269
package net.minecraft.world.gen.structure; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Map.Entry; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; public class MapGenVillage extends MapGenStructure { /** A list of all the biomes villages can spawn in. */ public static final List villageSpawnBiomes = Arrays.asList(new BiomeGenBase[] {BiomeGenBase.plains, BiomeGenBase.desert, BiomeGenBase.field_150588_X}); /** World terrain type, 0 for normal, 1 for flat map */ private int terrainType; private int field_82665_g; private int field_82666_h; private static final String __OBFID = "CL_00000514"; public MapGenVillage() { this.field_82665_g = 32; this.field_82666_h = 8; } public MapGenVillage(Map p_i2093_1_) { this(); Iterator var2 = p_i2093_1_.entrySet().iterator(); while (var2.hasNext()) { Entry var3 = (Entry)var2.next(); if (((String)var3.getKey()).equals("size")) { this.terrainType = MathHelper.parseIntWithDefaultAndMax((String)var3.getValue(), this.terrainType, 0); } else if (((String)var3.getKey()).equals("distance")) { this.field_82665_g = MathHelper.parseIntWithDefaultAndMax((String)var3.getValue(), this.field_82665_g, this.field_82666_h + 1); } } } public String func_143025_a() { return "Village"; } protected boolean canSpawnStructureAtCoords(int p_75047_1_, int p_75047_2_) { int var3 = p_75047_1_; int var4 = p_75047_2_; if (p_75047_1_ < 0) { p_75047_1_ -= this.field_82665_g - 1; } if (p_75047_2_ < 0) { p_75047_2_ -= this.field_82665_g - 1; } int var5 = p_75047_1_ / this.field_82665_g; int var6 = p_75047_2_ / this.field_82665_g; Random var7 = this.worldObj.setRandomSeed(var5, var6, 10387312); var5 *= this.field_82665_g; var6 *= this.field_82665_g; var5 += var7.nextInt(this.field_82665_g - this.field_82666_h); var6 += var7.nextInt(this.field_82665_g - this.field_82666_h); if (var3 == var5 && var4 == var6) { boolean var8 = this.worldObj.getWorldChunkManager().areBiomesViable(var3 * 16 + 8, var4 * 16 + 8, 0, villageSpawnBiomes); if (var8) { return true; } } return false; } protected StructureStart getStructureStart(int p_75049_1_, int p_75049_2_) { return new MapGenVillage.Start(this.worldObj, this.rand, p_75049_1_, p_75049_2_, this.terrainType); } public static class Start extends StructureStart { private boolean hasMoreThanTwoComponents; private static final String __OBFID = "CL_00000515"; public Start() {} public Start(World p_i2092_1_, Random p_i2092_2_, int p_i2092_3_, int p_i2092_4_, int p_i2092_5_) { super(p_i2092_3_, p_i2092_4_); List var6 = StructureVillagePieces.getStructureVillageWeightedPieceList(p_i2092_2_, p_i2092_5_); StructureVillagePieces.Start var7 = new StructureVillagePieces.Start(p_i2092_1_.getWorldChunkManager(), 0, p_i2092_2_, (p_i2092_3_ << 4) + 2, (p_i2092_4_ << 4) + 2, var6, p_i2092_5_); this.components.add(var7); var7.buildComponent(var7, this.components, p_i2092_2_); List var8 = var7.field_74930_j; List var9 = var7.field_74932_i; int var10; while (!var8.isEmpty() || !var9.isEmpty()) { StructureComponent var11; if (var8.isEmpty()) { var10 = p_i2092_2_.nextInt(var9.size()); var11 = (StructureComponent)var9.remove(var10); var11.buildComponent(var7, this.components, p_i2092_2_); } else { var10 = p_i2092_2_.nextInt(var8.size()); var11 = (StructureComponent)var8.remove(var10); var11.buildComponent(var7, this.components, p_i2092_2_); } } this.updateBoundingBox(); var10 = 0; Iterator var13 = this.components.iterator(); while (var13.hasNext()) { StructureComponent var12 = (StructureComponent)var13.next(); if (!(var12 instanceof StructureVillagePieces.Road)) { ++var10; } } this.hasMoreThanTwoComponents = var10 > 2; } public boolean isSizeableStructure() { return this.hasMoreThanTwoComponents; } public void func_143022_a(NBTTagCompound p_143022_1_) { super.func_143022_a(p_143022_1_); p_143022_1_.setBoolean("Valid", this.hasMoreThanTwoComponents); } public void func_143017_b(NBTTagCompound p_143017_1_) { super.func_143017_b(p_143017_1_); this.hasMoreThanTwoComponents = p_143017_1_.getBoolean("Valid"); } } }
mviitanen/marsmod
mcp/src/minecraft_server/net/minecraft/world/gen/structure/MapGenVillage.java
Java
gpl-2.0
5,468
// Copyright 2008 Dolphin Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "VideoCommon/CommandProcessor.h" #include <atomic> #include <cstring> #include <fmt/format.h> #include "Common/Assert.h" #include "Common/ChunkFile.h" #include "Common/CommonTypes.h" #include "Common/Flag.h" #include "Common/Logging/Log.h" #include "Core/ConfigManager.h" #include "Core/CoreTiming.h" #include "Core/HW/GPFifo.h" #include "Core/HW/MMIO.h" #include "Core/HW/ProcessorInterface.h" #include "Core/System.h" #include "VideoCommon/Fifo.h" namespace CommandProcessor { static CoreTiming::EventType* et_UpdateInterrupts; // TODO(ector): Warn on bbox read/write // STATE_TO_SAVE SCPFifoStruct fifo; static UCPStatusReg m_CPStatusReg; static UCPCtrlReg m_CPCtrlReg; static UCPClearReg m_CPClearReg; static u16 m_bboxleft; static u16 m_bboxtop; static u16 m_bboxright; static u16 m_bboxbottom; static u16 m_tokenReg; static Common::Flag s_interrupt_set; static Common::Flag s_interrupt_waiting; static bool s_is_fifo_error_seen = false; static bool IsOnThread() { return Core::System::GetInstance().IsDualCoreMode(); } static void UpdateInterrupts_Wrapper(u64 userdata, s64 cyclesLate) { UpdateInterrupts(userdata); } void SCPFifoStruct::Init() { CPBase = 0; CPEnd = 0; CPHiWatermark = 0; CPLoWatermark = 0; CPReadWriteDistance = 0; CPWritePointer = 0; CPReadPointer = 0; CPBreakpoint = 0; SafeCPReadPointer = 0; bFF_GPLinkEnable = 0; bFF_GPReadEnable = 0; bFF_BPEnable = 0; bFF_BPInt = 0; bFF_Breakpoint.store(0, std::memory_order_relaxed); bFF_HiWatermark.store(0, std::memory_order_relaxed); bFF_HiWatermarkInt.store(0, std::memory_order_relaxed); bFF_LoWatermark.store(0, std::memory_order_relaxed); bFF_LoWatermarkInt.store(0, std::memory_order_relaxed); s_is_fifo_error_seen = false; } void SCPFifoStruct::DoState(PointerWrap& p) { p.Do(CPBase); p.Do(CPEnd); p.Do(CPHiWatermark); p.Do(CPLoWatermark); p.Do(CPReadWriteDistance); p.Do(CPWritePointer); p.Do(CPReadPointer); p.Do(CPBreakpoint); p.Do(SafeCPReadPointer); p.Do(bFF_GPLinkEnable); p.Do(bFF_GPReadEnable); p.Do(bFF_BPEnable); p.Do(bFF_BPInt); p.Do(bFF_Breakpoint); p.Do(bFF_LoWatermarkInt); p.Do(bFF_HiWatermarkInt); p.Do(bFF_LoWatermark); p.Do(bFF_HiWatermark); } void DoState(PointerWrap& p) { p.DoPOD(m_CPStatusReg); p.DoPOD(m_CPCtrlReg); p.DoPOD(m_CPClearReg); p.Do(m_bboxleft); p.Do(m_bboxtop); p.Do(m_bboxright); p.Do(m_bboxbottom); p.Do(m_tokenReg); fifo.DoState(p); p.Do(s_interrupt_set); p.Do(s_interrupt_waiting); } static inline void WriteLow(std::atomic<u32>& reg, u16 lowbits) { reg.store((reg.load(std::memory_order_relaxed) & 0xFFFF0000) | lowbits, std::memory_order_relaxed); } static inline void WriteHigh(std::atomic<u32>& reg, u16 highbits) { reg.store((reg.load(std::memory_order_relaxed) & 0x0000FFFF) | (static_cast<u32>(highbits) << 16), std::memory_order_relaxed); } void Init() { m_CPStatusReg.Hex = 0; m_CPStatusReg.CommandIdle = 1; m_CPStatusReg.ReadIdle = 1; m_CPCtrlReg.Hex = 0; m_CPClearReg.Hex = 0; m_bboxleft = 0; m_bboxtop = 0; m_bboxright = 640; m_bboxbottom = 480; m_tokenReg = 0; fifo.Init(); s_interrupt_set.Clear(); s_interrupt_waiting.Clear(); et_UpdateInterrupts = CoreTiming::RegisterEvent("CPInterrupt", UpdateInterrupts_Wrapper); } u32 GetPhysicalAddressMask() { // Physical addresses in CP seem to ignore some of the upper bits (depending on platform) // This can be observed in CP MMIO registers by setting to 0xffffffff and then reading back. return SConfig::GetInstance().bWii ? 0x1fffffff : 0x03ffffff; } void RegisterMMIO(MMIO::Mapping* mmio, u32 base) { constexpr u16 WMASK_NONE = 0x0000; constexpr u16 WMASK_ALL = 0xffff; constexpr u16 WMASK_LO_ALIGN_32BIT = 0xffe0; const u16 WMASK_HI_RESTRICT = GetPhysicalAddressMask() >> 16; struct { u32 addr; u16* ptr; bool readonly; // FIFO mmio regs in the range [cc000020-cc00003e] have certain bits that always read as 0 // For _LO registers in this range, only bits 0xffe0 can be set // For _HI registers in this range, only bits 0x03ff can be set on GCN and 0x1fff on Wii u16 wmask; } directly_mapped_vars[] = { {FIFO_TOKEN_REGISTER, &m_tokenReg, false, WMASK_ALL}, // Bounding box registers are read only. {FIFO_BOUNDING_BOX_LEFT, &m_bboxleft, true, WMASK_NONE}, {FIFO_BOUNDING_BOX_RIGHT, &m_bboxright, true, WMASK_NONE}, {FIFO_BOUNDING_BOX_TOP, &m_bboxtop, true, WMASK_NONE}, {FIFO_BOUNDING_BOX_BOTTOM, &m_bboxbottom, true, WMASK_NONE}, {FIFO_BASE_LO, MMIO::Utils::LowPart(&fifo.CPBase), false, WMASK_LO_ALIGN_32BIT}, {FIFO_BASE_HI, MMIO::Utils::HighPart(&fifo.CPBase), false, WMASK_HI_RESTRICT}, {FIFO_END_LO, MMIO::Utils::LowPart(&fifo.CPEnd), false, WMASK_LO_ALIGN_32BIT}, {FIFO_END_HI, MMIO::Utils::HighPart(&fifo.CPEnd), false, WMASK_HI_RESTRICT}, {FIFO_HI_WATERMARK_LO, MMIO::Utils::LowPart(&fifo.CPHiWatermark), false, WMASK_LO_ALIGN_32BIT}, {FIFO_HI_WATERMARK_HI, MMIO::Utils::HighPart(&fifo.CPHiWatermark), false, WMASK_HI_RESTRICT}, {FIFO_LO_WATERMARK_LO, MMIO::Utils::LowPart(&fifo.CPLoWatermark), false, WMASK_LO_ALIGN_32BIT}, {FIFO_LO_WATERMARK_HI, MMIO::Utils::HighPart(&fifo.CPLoWatermark), false, WMASK_HI_RESTRICT}, // FIFO_RW_DISTANCE has some complex read code different for // single/dual core. {FIFO_WRITE_POINTER_LO, MMIO::Utils::LowPart(&fifo.CPWritePointer), false, WMASK_LO_ALIGN_32BIT}, {FIFO_WRITE_POINTER_HI, MMIO::Utils::HighPart(&fifo.CPWritePointer), false, WMASK_HI_RESTRICT}, // FIFO_READ_POINTER has different code for single/dual core. }; for (auto& mapped_var : directly_mapped_vars) { mmio->Register(base | mapped_var.addr, MMIO::DirectRead<u16>(mapped_var.ptr), mapped_var.readonly ? MMIO::InvalidWrite<u16>() : MMIO::DirectWrite<u16>(mapped_var.ptr, mapped_var.wmask)); } mmio->Register(base | FIFO_BP_LO, MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.CPBreakpoint)), MMIO::ComplexWrite<u16>([](u32, u16 val) { WriteLow(fifo.CPBreakpoint, val & WMASK_LO_ALIGN_32BIT); })); mmio->Register(base | FIFO_BP_HI, MMIO::DirectRead<u16>(MMIO::Utils::HighPart(&fifo.CPBreakpoint)), MMIO::ComplexWrite<u16>([WMASK_HI_RESTRICT](u32, u16 val) { WriteHigh(fifo.CPBreakpoint, val & WMASK_HI_RESTRICT); })); // Timing and metrics MMIOs are stubbed with fixed values. struct { u32 addr; u16 value; } metrics_mmios[] = { {XF_RASBUSY_L, 0}, {XF_RASBUSY_H, 0}, {XF_CLKS_L, 0}, {XF_CLKS_H, 0}, {XF_WAIT_IN_L, 0}, {XF_WAIT_IN_H, 0}, {XF_WAIT_OUT_L, 0}, {XF_WAIT_OUT_H, 0}, {VCACHE_METRIC_CHECK_L, 0}, {VCACHE_METRIC_CHECK_H, 0}, {VCACHE_METRIC_MISS_L, 0}, {VCACHE_METRIC_MISS_H, 0}, {VCACHE_METRIC_STALL_L, 0}, {VCACHE_METRIC_STALL_H, 0}, {CLKS_PER_VTX_OUT, 4}, }; for (auto& metrics_mmio : metrics_mmios) { mmio->Register(base | metrics_mmio.addr, MMIO::Constant<u16>(metrics_mmio.value), MMIO::InvalidWrite<u16>()); } mmio->Register(base | STATUS_REGISTER, MMIO::ComplexRead<u16>([](u32) { Fifo::SyncGPUForRegisterAccess(); SetCpStatusRegister(); return m_CPStatusReg.Hex; }), MMIO::InvalidWrite<u16>()); mmio->Register(base | CTRL_REGISTER, MMIO::DirectRead<u16>(&m_CPCtrlReg.Hex), MMIO::ComplexWrite<u16>([](u32, u16 val) { UCPCtrlReg tmp(val); m_CPCtrlReg.Hex = tmp.Hex; SetCpControlRegister(); Fifo::RunGpu(); })); mmio->Register(base | CLEAR_REGISTER, MMIO::DirectRead<u16>(&m_CPClearReg.Hex), MMIO::ComplexWrite<u16>([](u32, u16 val) { UCPClearReg tmp(val); m_CPClearReg.Hex = tmp.Hex; SetCpClearRegister(); Fifo::RunGpu(); })); mmio->Register(base | PERF_SELECT, MMIO::InvalidRead<u16>(), MMIO::Nop<u16>()); // Some MMIOs have different handlers for single core vs. dual core mode. mmio->Register( base | FIFO_RW_DISTANCE_LO, IsOnThread() ? MMIO::ComplexRead<u16>([](u32) { if (fifo.CPWritePointer.load(std::memory_order_relaxed) >= fifo.SafeCPReadPointer.load(std::memory_order_relaxed)) { return static_cast<u16>(fifo.CPWritePointer.load(std::memory_order_relaxed) - fifo.SafeCPReadPointer.load(std::memory_order_relaxed)); } else { return static_cast<u16>(fifo.CPEnd.load(std::memory_order_relaxed) - fifo.SafeCPReadPointer.load(std::memory_order_relaxed) + fifo.CPWritePointer.load(std::memory_order_relaxed) - fifo.CPBase.load(std::memory_order_relaxed) + 32); } }) : MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.CPReadWriteDistance)), MMIO::DirectWrite<u16>(MMIO::Utils::LowPart(&fifo.CPReadWriteDistance), WMASK_LO_ALIGN_32BIT)); mmio->Register(base | FIFO_RW_DISTANCE_HI, IsOnThread() ? MMIO::ComplexRead<u16>([](u32) { Fifo::SyncGPUForRegisterAccess(); if (fifo.CPWritePointer.load(std::memory_order_relaxed) >= fifo.SafeCPReadPointer.load(std::memory_order_relaxed)) { return (fifo.CPWritePointer.load(std::memory_order_relaxed) - fifo.SafeCPReadPointer.load(std::memory_order_relaxed)) >> 16; } else { return (fifo.CPEnd.load(std::memory_order_relaxed) - fifo.SafeCPReadPointer.load(std::memory_order_relaxed) + fifo.CPWritePointer.load(std::memory_order_relaxed) - fifo.CPBase.load(std::memory_order_relaxed) + 32) >> 16; } }) : MMIO::ComplexRead<u16>([](u32) { Fifo::SyncGPUForRegisterAccess(); return fifo.CPReadWriteDistance.load(std::memory_order_relaxed) >> 16; }), MMIO::ComplexWrite<u16>([WMASK_HI_RESTRICT](u32, u16 val) { Fifo::SyncGPUForRegisterAccess(); WriteHigh(fifo.CPReadWriteDistance, val & WMASK_HI_RESTRICT); Fifo::RunGpu(); })); mmio->Register( base | FIFO_READ_POINTER_LO, IsOnThread() ? MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.SafeCPReadPointer)) : MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.CPReadPointer)), MMIO::DirectWrite<u16>(MMIO::Utils::LowPart(&fifo.CPReadPointer), WMASK_LO_ALIGN_32BIT)); mmio->Register(base | FIFO_READ_POINTER_HI, IsOnThread() ? MMIO::ComplexRead<u16>([](u32) { Fifo::SyncGPUForRegisterAccess(); return fifo.SafeCPReadPointer.load(std::memory_order_relaxed) >> 16; }) : MMIO::ComplexRead<u16>([](u32) { Fifo::SyncGPUForRegisterAccess(); return fifo.CPReadPointer.load(std::memory_order_relaxed) >> 16; }), IsOnThread() ? MMIO::ComplexWrite<u16>([WMASK_HI_RESTRICT](u32, u16 val) { Fifo::SyncGPUForRegisterAccess(); WriteHigh(fifo.CPReadPointer, val & WMASK_HI_RESTRICT); fifo.SafeCPReadPointer.store(fifo.CPReadPointer.load(std::memory_order_relaxed), std::memory_order_relaxed); }) : MMIO::ComplexWrite<u16>([WMASK_HI_RESTRICT](u32, u16 val) { Fifo::SyncGPUForRegisterAccess(); WriteHigh(fifo.CPReadPointer, val & WMASK_HI_RESTRICT); })); } void GatherPipeBursted() { SetCPStatusFromCPU(); // if we aren't linked, we don't care about gather pipe data if (!m_CPCtrlReg.GPLinkEnable) { if (IsOnThread() && !Fifo::UseDeterministicGPUThread()) { // In multibuffer mode is not allowed write in the same FIFO attached to the GPU. // Fix Pokemon XD in DC mode. if ((ProcessorInterface::Fifo_CPUEnd == fifo.CPEnd.load(std::memory_order_relaxed)) && (ProcessorInterface::Fifo_CPUBase == fifo.CPBase.load(std::memory_order_relaxed)) && fifo.CPReadWriteDistance.load(std::memory_order_relaxed) > 0) { Fifo::FlushGpu(); } } Fifo::RunGpu(); return; } // update the fifo pointer if (fifo.CPWritePointer.load(std::memory_order_relaxed) == fifo.CPEnd.load(std::memory_order_relaxed)) { fifo.CPWritePointer.store(fifo.CPBase, std::memory_order_relaxed); } else { fifo.CPWritePointer.fetch_add(GATHER_PIPE_SIZE, std::memory_order_relaxed); } if (m_CPCtrlReg.GPReadEnable && m_CPCtrlReg.GPLinkEnable) { ProcessorInterface::Fifo_CPUWritePointer = fifo.CPWritePointer.load(std::memory_order_relaxed); ProcessorInterface::Fifo_CPUBase = fifo.CPBase.load(std::memory_order_relaxed); ProcessorInterface::Fifo_CPUEnd = fifo.CPEnd.load(std::memory_order_relaxed); } // If the game is running close to overflowing, make the exception checking more frequent. if (fifo.bFF_HiWatermark.load(std::memory_order_relaxed) != 0) CoreTiming::ForceExceptionCheck(0); fifo.CPReadWriteDistance.fetch_add(GATHER_PIPE_SIZE, std::memory_order_seq_cst); Fifo::RunGpu(); ASSERT_MSG(COMMANDPROCESSOR, fifo.CPReadWriteDistance.load(std::memory_order_relaxed) <= fifo.CPEnd.load(std::memory_order_relaxed) - fifo.CPBase.load(std::memory_order_relaxed), "FIFO is overflowed by GatherPipe !\nCPU thread is too fast!"); // check if we are in sync ASSERT_MSG(COMMANDPROCESSOR, fifo.CPWritePointer.load(std::memory_order_relaxed) == ProcessorInterface::Fifo_CPUWritePointer, "FIFOs linked but out of sync"); ASSERT_MSG(COMMANDPROCESSOR, fifo.CPBase.load(std::memory_order_relaxed) == ProcessorInterface::Fifo_CPUBase, "FIFOs linked but out of sync"); ASSERT_MSG(COMMANDPROCESSOR, fifo.CPEnd.load(std::memory_order_relaxed) == ProcessorInterface::Fifo_CPUEnd, "FIFOs linked but out of sync"); } void UpdateInterrupts(u64 userdata) { if (userdata) { s_interrupt_set.Set(); DEBUG_LOG_FMT(COMMANDPROCESSOR, "Interrupt set"); ProcessorInterface::SetInterrupt(INT_CAUSE_CP, true); } else { s_interrupt_set.Clear(); DEBUG_LOG_FMT(COMMANDPROCESSOR, "Interrupt cleared"); ProcessorInterface::SetInterrupt(INT_CAUSE_CP, false); } CoreTiming::ForceExceptionCheck(0); s_interrupt_waiting.Clear(); Fifo::RunGpu(); } void UpdateInterruptsFromVideoBackend(u64 userdata) { if (!Fifo::UseDeterministicGPUThread()) CoreTiming::ScheduleEvent(0, et_UpdateInterrupts, userdata, CoreTiming::FromThread::NON_CPU); } bool IsInterruptWaiting() { return s_interrupt_waiting.IsSet(); } void SetCPStatusFromGPU() { // breakpoint const bool breakpoint = fifo.bFF_Breakpoint.load(std::memory_order_relaxed); if (fifo.bFF_BPEnable.load(std::memory_order_relaxed) != 0) { if (fifo.CPBreakpoint.load(std::memory_order_relaxed) == fifo.CPReadPointer.load(std::memory_order_relaxed)) { if (!breakpoint) { DEBUG_LOG_FMT(COMMANDPROCESSOR, "Hit breakpoint at {}", fifo.CPReadPointer.load(std::memory_order_relaxed)); fifo.bFF_Breakpoint.store(1, std::memory_order_relaxed); } } else { if (breakpoint) { DEBUG_LOG_FMT(COMMANDPROCESSOR, "Cleared breakpoint at {}", fifo.CPReadPointer.load(std::memory_order_relaxed)); fifo.bFF_Breakpoint.store(0, std::memory_order_relaxed); } } } else { if (breakpoint) { DEBUG_LOG_FMT(COMMANDPROCESSOR, "Cleared breakpoint at {}", fifo.CPReadPointer.load(std::memory_order_relaxed)); fifo.bFF_Breakpoint = false; } } // overflow & underflow check fifo.bFF_HiWatermark.store( (fifo.CPReadWriteDistance.load(std::memory_order_relaxed) > fifo.CPHiWatermark), std::memory_order_relaxed); fifo.bFF_LoWatermark.store( (fifo.CPReadWriteDistance.load(std::memory_order_relaxed) < fifo.CPLoWatermark), std::memory_order_relaxed); bool bpInt = fifo.bFF_Breakpoint.load(std::memory_order_relaxed) && fifo.bFF_BPInt.load(std::memory_order_relaxed); bool ovfInt = fifo.bFF_HiWatermark.load(std::memory_order_relaxed) && fifo.bFF_HiWatermarkInt.load(std::memory_order_relaxed); bool undfInt = fifo.bFF_LoWatermark.load(std::memory_order_relaxed) && fifo.bFF_LoWatermarkInt.load(std::memory_order_relaxed); bool interrupt = (bpInt || ovfInt || undfInt) && m_CPCtrlReg.GPReadEnable; if (interrupt != s_interrupt_set.IsSet() && !s_interrupt_waiting.IsSet()) { u64 userdata = interrupt ? 1 : 0; if (IsOnThread()) { if (!interrupt || bpInt || undfInt || ovfInt) { // Schedule the interrupt asynchronously s_interrupt_waiting.Set(); CommandProcessor::UpdateInterruptsFromVideoBackend(userdata); } } else { CommandProcessor::UpdateInterrupts(userdata); } } } void SetCPStatusFromCPU() { // overflow & underflow check fifo.bFF_HiWatermark.store( (fifo.CPReadWriteDistance.load(std::memory_order_relaxed) > fifo.CPHiWatermark), std::memory_order_relaxed); fifo.bFF_LoWatermark.store( (fifo.CPReadWriteDistance.load(std::memory_order_relaxed) < fifo.CPLoWatermark), std::memory_order_relaxed); bool bpInt = fifo.bFF_Breakpoint.load(std::memory_order_relaxed) && fifo.bFF_BPInt.load(std::memory_order_relaxed); bool ovfInt = fifo.bFF_HiWatermark.load(std::memory_order_relaxed) && fifo.bFF_HiWatermarkInt.load(std::memory_order_relaxed); bool undfInt = fifo.bFF_LoWatermark.load(std::memory_order_relaxed) && fifo.bFF_LoWatermarkInt.load(std::memory_order_relaxed); bool interrupt = (bpInt || ovfInt || undfInt) && m_CPCtrlReg.GPReadEnable; if (interrupt != s_interrupt_set.IsSet() && !s_interrupt_waiting.IsSet()) { u64 userdata = interrupt ? 1 : 0; if (IsOnThread()) { if (!interrupt || bpInt || undfInt || ovfInt) { s_interrupt_set.Set(interrupt); DEBUG_LOG_FMT(COMMANDPROCESSOR, "Interrupt set"); ProcessorInterface::SetInterrupt(INT_CAUSE_CP, interrupt); } } else { CommandProcessor::UpdateInterrupts(userdata); } } } void SetCpStatusRegister() { // Here always there is one fifo attached to the GPU m_CPStatusReg.Breakpoint = fifo.bFF_Breakpoint.load(std::memory_order_relaxed); m_CPStatusReg.ReadIdle = !fifo.CPReadWriteDistance.load(std::memory_order_relaxed) || (fifo.CPReadPointer.load(std::memory_order_relaxed) == fifo.CPWritePointer.load(std::memory_order_relaxed)); m_CPStatusReg.CommandIdle = !fifo.CPReadWriteDistance.load(std::memory_order_relaxed) || Fifo::AtBreakpoint() || !fifo.bFF_GPReadEnable.load(std::memory_order_relaxed); m_CPStatusReg.UnderflowLoWatermark = fifo.bFF_LoWatermark.load(std::memory_order_relaxed); m_CPStatusReg.OverflowHiWatermark = fifo.bFF_HiWatermark.load(std::memory_order_relaxed); DEBUG_LOG_FMT(COMMANDPROCESSOR, "\t Read from STATUS_REGISTER : {:04x}", m_CPStatusReg.Hex); DEBUG_LOG_FMT( COMMANDPROCESSOR, "(r) status: iBP {} | fReadIdle {} | fCmdIdle {} | iOvF {} | iUndF {}", m_CPStatusReg.Breakpoint ? "ON" : "OFF", m_CPStatusReg.ReadIdle ? "ON" : "OFF", m_CPStatusReg.CommandIdle ? "ON" : "OFF", m_CPStatusReg.OverflowHiWatermark ? "ON" : "OFF", m_CPStatusReg.UnderflowLoWatermark ? "ON" : "OFF"); } void SetCpControlRegister() { fifo.bFF_BPInt.store(m_CPCtrlReg.BPInt, std::memory_order_relaxed); fifo.bFF_BPEnable.store(m_CPCtrlReg.BPEnable, std::memory_order_relaxed); fifo.bFF_HiWatermarkInt.store(m_CPCtrlReg.FifoOverflowIntEnable, std::memory_order_relaxed); fifo.bFF_LoWatermarkInt.store(m_CPCtrlReg.FifoUnderflowIntEnable, std::memory_order_relaxed); fifo.bFF_GPLinkEnable.store(m_CPCtrlReg.GPLinkEnable, std::memory_order_relaxed); if (fifo.bFF_GPReadEnable.load(std::memory_order_relaxed) && !m_CPCtrlReg.GPReadEnable) { fifo.bFF_GPReadEnable.store(m_CPCtrlReg.GPReadEnable, std::memory_order_relaxed); Fifo::FlushGpu(); } else { fifo.bFF_GPReadEnable = m_CPCtrlReg.GPReadEnable; } DEBUG_LOG_FMT(COMMANDPROCESSOR, "\t GPREAD {} | BP {} | Int {} | OvF {} | UndF {} | LINK {}", fifo.bFF_GPReadEnable.load(std::memory_order_relaxed) ? "ON" : "OFF", fifo.bFF_BPEnable.load(std::memory_order_relaxed) ? "ON" : "OFF", fifo.bFF_BPInt.load(std::memory_order_relaxed) ? "ON" : "OFF", m_CPCtrlReg.FifoOverflowIntEnable ? "ON" : "OFF", m_CPCtrlReg.FifoUnderflowIntEnable ? "ON" : "OFF", m_CPCtrlReg.GPLinkEnable ? "ON" : "OFF"); } // NOTE: We intentionally don't emulate this function at the moment. // We don't emulate proper GP timing anyway at the moment, so it would just slow down emulation. void SetCpClearRegister() { } void HandleUnknownOpcode(u8 cmd_byte, const u8* buffer, bool preprocess) { // Datel software uses 0x01 during startup, and Mario Party 5's Wiggler capsule // accidentally uses 0x01-0x03 due to sending 4 more vertices than intended. // Hardware testing indicates that 0x01-0x07 do nothing, so to avoid annoying the user with // spurious popups, we don't create a panic alert in those cases. Other unknown opcodes // (such as 0x18) seem to result in hangs. if (!s_is_fifo_error_seen && cmd_byte > 0x07) { s_is_fifo_error_seen = true; // TODO(Omega): Maybe dump FIFO to file on this error PanicAlertFmtT("GFX FIFO: Unknown Opcode ({0:#04x} @ {1}, preprocess={2}).\n" "This means one of the following:\n" "* The emulated GPU got desynced, disabling dual core can help\n" "* Command stream corrupted by some spurious memory bug\n" "* This really is an unknown opcode (unlikely)\n" "* Some other sort of bug\n\n" "Further errors will be sent to the Video Backend log and\n" "Dolphin will now likely crash or hang. Enjoy.", cmd_byte, fmt::ptr(buffer), preprocess); PanicAlertFmt("Illegal command {:02x}\n" "CPBase: {:#010x}\n" "CPEnd: {:#010x}\n" "CPHiWatermark: {:#010x}\n" "CPLoWatermark: {:#010x}\n" "CPReadWriteDistance: {:#010x}\n" "CPWritePointer: {:#010x}\n" "CPReadPointer: {:#010x}\n" "CPBreakpoint: {:#010x}\n" "bFF_GPReadEnable: {}\n" "bFF_BPEnable: {}\n" "bFF_BPInt: {}\n" "bFF_Breakpoint: {}\n" "bFF_GPLinkEnable: {}\n" "bFF_HiWatermarkInt: {}\n" "bFF_LoWatermarkInt: {}\n", cmd_byte, fifo.CPBase.load(std::memory_order_relaxed), fifo.CPEnd.load(std::memory_order_relaxed), fifo.CPHiWatermark, fifo.CPLoWatermark, fifo.CPReadWriteDistance.load(std::memory_order_relaxed), fifo.CPWritePointer.load(std::memory_order_relaxed), fifo.CPReadPointer.load(std::memory_order_relaxed), fifo.CPBreakpoint.load(std::memory_order_relaxed), fifo.bFF_GPReadEnable.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_BPEnable.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_BPInt.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_Breakpoint.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_GPLinkEnable.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_HiWatermarkInt.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_LoWatermarkInt.load(std::memory_order_relaxed) ? "true" : "false"); } // We always generate this log message, though we only generate the panic alerts once. ERROR_LOG_FMT(VIDEO, "FIFO: Unknown Opcode ({:#04x} @ {}, preprocessing = {})", cmd_byte, fmt::ptr(buffer), preprocess ? "yes" : "no"); } } // namespace CommandProcessor
ZephyrSurfer/dolphin
Source/Core/VideoCommon/CommandProcessor.cpp
C++
gpl-2.0
25,741
/* * synergy -- mouse and keyboard sharing utility * Copyright (C) 2004 Chris Schoeneman * * This package is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * found in the file COPYING that should have accompanied this file. * * This package is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include "CXWindowsClipboardAnyBitmapConverter.h" // BMP info header structure struct CBMPInfoHeader { public: UInt32 biSize; SInt32 biWidth; SInt32 biHeight; UInt16 biPlanes; UInt16 biBitCount; UInt32 biCompression; UInt32 biSizeImage; SInt32 biXPelsPerMeter; SInt32 biYPelsPerMeter; UInt32 biClrUsed; UInt32 biClrImportant; }; // BMP is little-endian static void toLE(UInt8*& dst, UInt16 src) { dst[0] = static_cast<UInt8>(src & 0xffu); dst[1] = static_cast<UInt8>((src >> 8) & 0xffu); dst += 2; } static void toLE(UInt8*& dst, SInt32 src) { dst[0] = static_cast<UInt8>(src & 0xffu); dst[1] = static_cast<UInt8>((src >> 8) & 0xffu); dst[2] = static_cast<UInt8>((src >> 16) & 0xffu); dst[3] = static_cast<UInt8>((src >> 24) & 0xffu); dst += 4; } static void toLE(UInt8*& dst, UInt32 src) { dst[0] = static_cast<UInt8>(src & 0xffu); dst[1] = static_cast<UInt8>((src >> 8) & 0xffu); dst[2] = static_cast<UInt8>((src >> 16) & 0xffu); dst[3] = static_cast<UInt8>((src >> 24) & 0xffu); dst += 4; } static inline UInt16 fromLEU16(const UInt8* data) { return static_cast<UInt16>(data[0]) | (static_cast<UInt16>(data[1]) << 8); } static inline SInt32 fromLES32(const UInt8* data) { return static_cast<SInt32>(static_cast<UInt32>(data[0]) | (static_cast<UInt32>(data[1]) << 8) | (static_cast<UInt32>(data[2]) << 16) | (static_cast<UInt32>(data[3]) << 24)); } static inline UInt32 fromLEU32(const UInt8* data) { return static_cast<UInt32>(data[0]) | (static_cast<UInt32>(data[1]) << 8) | (static_cast<UInt32>(data[2]) << 16) | (static_cast<UInt32>(data[3]) << 24); } // // CXWindowsClipboardAnyBitmapConverter // CXWindowsClipboardAnyBitmapConverter::CXWindowsClipboardAnyBitmapConverter() { // do nothing } CXWindowsClipboardAnyBitmapConverter::~CXWindowsClipboardAnyBitmapConverter() { // do nothing } IClipboard::EFormat CXWindowsClipboardAnyBitmapConverter::getFormat() const { return IClipboard::kBitmap; } int CXWindowsClipboardAnyBitmapConverter::getDataSize() const { return 8; } CString CXWindowsClipboardAnyBitmapConverter::fromIClipboard(const CString& bmp) const { // fill BMP info header with native-endian data CBMPInfoHeader infoHeader; const UInt8* rawBMPInfoHeader = reinterpret_cast<const UInt8*>(bmp.data()); infoHeader.biSize = fromLEU32(rawBMPInfoHeader + 0); infoHeader.biWidth = fromLES32(rawBMPInfoHeader + 4); infoHeader.biHeight = fromLES32(rawBMPInfoHeader + 8); infoHeader.biPlanes = fromLEU16(rawBMPInfoHeader + 12); infoHeader.biBitCount = fromLEU16(rawBMPInfoHeader + 14); infoHeader.biCompression = fromLEU32(rawBMPInfoHeader + 16); infoHeader.biSizeImage = fromLEU32(rawBMPInfoHeader + 20); infoHeader.biXPelsPerMeter = fromLES32(rawBMPInfoHeader + 24); infoHeader.biYPelsPerMeter = fromLES32(rawBMPInfoHeader + 28); infoHeader.biClrUsed = fromLEU32(rawBMPInfoHeader + 32); infoHeader.biClrImportant = fromLEU32(rawBMPInfoHeader + 36); // check that format is acceptable if (infoHeader.biSize != 40 || infoHeader.biWidth == 0 || infoHeader.biHeight == 0 || infoHeader.biPlanes != 0 || infoHeader.biCompression != 0 || (infoHeader.biBitCount != 24 && infoHeader.biBitCount != 32)) { return CString(); } // convert to image format const UInt8* rawBMPPixels = rawBMPInfoHeader + 40; if (infoHeader.biBitCount == 24) { return doBGRFromIClipboard(rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight); } else { return doBGRAFromIClipboard(rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight); } } CString CXWindowsClipboardAnyBitmapConverter::toIClipboard(const CString& image) const { // convert to raw BMP data UInt32 w, h, depth; CString rawBMP = doToIClipboard(image, w, h, depth); if (rawBMP.empty() || w == 0 || h == 0 || (depth != 24 && depth != 32)) { return CString(); } // fill BMP info header with little-endian data UInt8 infoHeader[40]; UInt8* dst = infoHeader; toLE(dst, static_cast<UInt32>(40)); toLE(dst, static_cast<SInt32>(w)); toLE(dst, static_cast<SInt32>(h)); toLE(dst, static_cast<UInt16>(1)); toLE(dst, static_cast<UInt16>(depth)); toLE(dst, static_cast<UInt32>(0)); // BI_RGB toLE(dst, static_cast<UInt32>(image.size())); toLE(dst, static_cast<SInt32>(2834)); // 72 dpi toLE(dst, static_cast<SInt32>(2834)); // 72 dpi toLE(dst, static_cast<UInt32>(0)); toLE(dst, static_cast<UInt32>(0)); // construct image return CString(reinterpret_cast<const char*>(infoHeader), sizeof(infoHeader)) + rawBMP; }
undecided/synergy
lib/platform/CXWindowsClipboardAnyBitmapConverter.cpp
C++
gpl-2.0
5,164
package org.openyu.mix.sasang.vo; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.openyu.mix.app.vo.Prize; import org.openyu.commons.bean.IdBean; import org.openyu.commons.bean.ProbabilityBean; import org.openyu.commons.enumz.IntEnum; import com.sun.xml.bind.AnyTypeAdapter; /** * 開出的結果 */ @XmlJavaTypeAdapter(AnyTypeAdapter.class) public interface Outcome extends IdBean, ProbabilityBean { String KEY = Outcome.class.getName(); /** * 結果類別 * */ public enum OutcomeType implements IntEnum { /** * 都不相同 */ STAND_ALONE(1), /** * 兩個相同 */ SAME_TWO(2), /** * 三個相同 */ SAME_THREE(3), // ; private final int value; private OutcomeType(int value) { this.value = value; } public int getValue() { return value; } } /** * 開出的獎 * * @return */ Prize getPrize(); void setPrize(Prize prize); /** * 結果類別 * * @return */ OutcomeType getOutcomeType(); void setOutcomeType(OutcomeType outcomeType); /** * 機率 * * @return */ double getProbability(); void setProbability(double probability); }
mixaceh/openyu-mix.j
openyu-mix-core/src/main/java/org/openyu/mix/sasang/vo/Outcome.java
Java
gpl-2.0
1,183
/* * thd_cdev_order_parser.cpp: Specify cdev order * * Copyright (C) 2012 Intel Corporation. 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 version * 2 or later as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * Author Name <Srinivas.Pandruvada@linux.intel.com> * */ #include "thd_cdev_order_parser.h" #include "thd_sys_fs.h" cthd_cdev_order_parse::cthd_cdev_order_parse() :doc(NULL), root_element(NULL) { std::string name = TDCONFDIR; filename=name+"/""thermal-cdev-order.xml"; } int cthd_cdev_order_parse::parser_init() { doc = xmlReadFile(filename.c_str(), NULL, 0); if (doc == NULL) { thd_log_warn("error: could not parse file %s\n", filename.c_str()); return THD_ERROR; } root_element = xmlDocGetRootElement(doc); if (root_element == NULL) { thd_log_warn("error: could not get root element \n"); return THD_ERROR; } return THD_SUCCESS; } int cthd_cdev_order_parse::start_parse() { parse(root_element, doc); return THD_SUCCESS; } void cthd_cdev_order_parse::parser_deinit() { xmlFreeDoc(doc); xmlCleanupParser(); } int cthd_cdev_order_parse::parse_new_cdev(xmlNode * a_node, xmlDoc *doc) { xmlNode *cur_node = NULL; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { thd_log_info("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); cdev_order_list.push_back(xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); } } return THD_SUCCESS; } int cthd_cdev_order_parse::parse(xmlNode * a_node, xmlDoc *doc) { xmlNode *cur_node = NULL; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { if (!strcmp((const char*)cur_node->name, "CoolingDeviceOrder")) { parse_new_cdev(cur_node->children, doc); } } } return THD_SUCCESS; } int cthd_cdev_order_parse::get_order_list(std::vector <std::string> &list) { list = cdev_order_list; return 0; }
RAOF/thermal_daemon
src/thd_cdev_order_parser.cpp
C++
gpl-2.0
2,571
<?php /* * (c) 2017 Siveo, http://www.siveo.net * * $Id$ * * This file is part of MMC, http://www.siveo.net * * MMC 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. * * MMC 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 MMC; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * File xmppmaster/machine_xmpp_detail.php */ // recupere information machine //print_r($_GET); extract($_GET); ?> <?php //print_r($_GET); $cn = explode ( "/", $machine)[1]; $machinexmpp = xmlrpc_getMachinefromjid($machine); header('Location: main.php?module=base&submod=computers&action=glpitabs&cn='.urlencode($cn).'&objectUUID='.urlencode($machinexmpp['uuid_inventorymachine'])); exit(); /* echo "<pre>"; print_r($machinexmpp); echo "</pre>";*/ ?>
pulse-project/mmc-core
web/modules/xmppmaster/xmppmaster/machine_xmpp_detail.php
PHP
gpl-2.0
1,270
/** \file * Base class for visual SVG elements */ /* * Authors: * Lauris Kaplinski <lauris@kaplinski.com> * bulia byak <buliabyak@users.sf.net> * Johan Engelen <j.b.c.engelen@ewi.utwente.nl> * Abhishek Sharma * Jon A. Cruz <jon@joncruz.org> * * Copyright (C) 2001-2006 authors * Copyright (C) 2001 Ximian, Inc. * * Released under GNU GPL, read the file 'COPYING' for more information */ /** \class SPItem * * SPItem is an abstract base class for all graphic (visible) SVG nodes. It * is a subclass of SPObject, with great deal of specific functionality. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "sp-item.h" #include "svg/svg.h" #include "print.h" #include "display/drawing-item.h" #include "attributes.h" #include "document.h" #include "uri.h" #include "inkscape.h" #include "desktop.h" #include "desktop-handles.h" #include "style.h" #include <glibmm/i18n.h> #include "sp-root.h" #include "sp-clippath.h" #include "sp-mask.h" #include "sp-rect.h" #include "sp-use.h" #include "sp-text.h" #include "sp-textpath.h" #include "sp-item-rm-unsatisfied-cns.h" #include "sp-pattern.h" #include "sp-paint-server.h" #include "sp-switch.h" #include "sp-guide-constraint.h" #include "gradient-chemistry.h" #include "preferences.h" #include "conn-avoid-ref.h" #include "conditions.h" #include "sp-filter-reference.h" #include "filter-chemistry.h" #include "sp-guide.h" #include "sp-title.h" #include "sp-desc.h" #include "util/find-last-if.h" #include "util/reverse-list.h" #include <2geom/rect.h> #include <2geom/affine.h> #include <2geom/transforms.h> #include "xml/repr.h" #include "extract-uri.h" #include "helper/geom.h" #include "live_effects/lpeobject.h" #include "live_effects/effect.h" #include "live_effects/lpeobject-reference.h" #include "util/units.h" #define noSP_ITEM_DEBUG_IDLE static SPItemView* sp_item_view_list_remove(SPItemView *list, SPItemView *view); SPItem::SPItem() : SPObject() { this->sensitive = 0; this->clip_ref = NULL; this->avoidRef = NULL; this->_is_evaluated = false; this->stop_paint = 0; this->_evaluated_status = StatusUnknown; this->bbox_valid = 0; this->freeze_stroke_width = false; this->transform_center_x = 0; this->transform_center_y = 0; this->display = NULL; this->mask_ref = NULL; sensitive = TRUE; bbox_valid = FALSE; transform_center_x = 0; transform_center_y = 0; _is_evaluated = true; _evaluated_status = StatusUnknown; transform = Geom::identity(); doc_bbox = Geom::OptRect(); freeze_stroke_width = false; display = NULL; clip_ref = new SPClipPathReference(this); clip_ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(clip_ref_changed), this)); mask_ref = new SPMaskReference(this); mask_ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(mask_ref_changed), this)); style->signal_fill_ps_changed.connect(sigc::bind(sigc::ptr_fun(fill_ps_ref_changed), this)); style->signal_stroke_ps_changed.connect(sigc::bind(sigc::ptr_fun(stroke_ps_ref_changed), this)); avoidRef = new SPAvoidRef(this); } SPItem::~SPItem() { } bool SPItem::isVisibleAndUnlocked() const { return (!isHidden() && !isLocked()); } bool SPItem::isVisibleAndUnlocked(unsigned display_key) const { return (!isHidden(display_key) && !isLocked()); } bool SPItem::isLocked() const { for (SPObject const *o = this; o != NULL; o = o->parent) { if (SP_IS_ITEM(o) && !(SP_ITEM(o)->sensitive)) { return true; } } return false; } void SPItem::setLocked(bool locked) { setAttribute("sodipodi:insensitive", ( locked ? "1" : NULL )); updateRepr(); } bool SPItem::isHidden() const { if (!isEvaluated()) return true; return style->display.computed == SP_CSS_DISPLAY_NONE; } void SPItem::setHidden(bool hide) { style->display.set = TRUE; style->display.value = ( hide ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE ); style->display.computed = style->display.value; style->display.inherit = FALSE; updateRepr(); } bool SPItem::isHidden(unsigned display_key) const { if (!isEvaluated()) return true; for ( SPItemView *view(display) ; view ; view = view->next ) { if ( view->key == display_key ) { g_assert(view->arenaitem != NULL); for ( Inkscape::DrawingItem *arenaitem = view->arenaitem ; arenaitem ; arenaitem = arenaitem->parent() ) { if (!arenaitem->visible()) { return true; } } return false; } } return true; } void SPItem::setEvaluated(bool evaluated) { _is_evaluated = evaluated; _evaluated_status = StatusSet; } void SPItem::resetEvaluated() { if ( StatusCalculated == _evaluated_status ) { _evaluated_status = StatusUnknown; bool oldValue = _is_evaluated; if ( oldValue != isEvaluated() ) { requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); } } if ( StatusSet == _evaluated_status ) { if (SP_IS_SWITCH(parent)) { SP_SWITCH(parent)->resetChildEvaluated(); } } } bool SPItem::isEvaluated() const { if ( StatusUnknown == _evaluated_status ) { _is_evaluated = sp_item_evaluate(this); _evaluated_status = StatusCalculated; } return _is_evaluated; } /** * Returns something suitable for the `Hide' checkbox in the Object Properties dialog box. * Corresponds to setExplicitlyHidden. */ bool SPItem::isExplicitlyHidden() const { return (style->display.set && style->display.value == SP_CSS_DISPLAY_NONE); } /** * Sets the display CSS property to `hidden' if \a val is true, * otherwise makes it unset */ void SPItem::setExplicitlyHidden(bool val) { style->display.set = val; style->display.value = ( val ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE ); style->display.computed = style->display.value; updateRepr(); } /** * Sets the transform_center_x and transform_center_y properties to retain the rotation center */ void SPItem::setCenter(Geom::Point const &object_centre) { document->ensureUpToDate(); // Copied from DocumentProperties::onDocUnitChange() gdouble viewscale = 1.0; Geom::Rect vb = this->document->getRoot()->viewBox; if ( !vb.hasZeroArea() ) { gdouble viewscale_w = this->document->getWidth().value("px") / vb.width(); gdouble viewscale_h = this->document->getHeight().value("px")/ vb.height(); viewscale = std::min(viewscale_h, viewscale_w); } // FIXME this is seriously wrong Geom::OptRect bbox = desktopGeometricBounds(); if (bbox) { // object centre is document coordinates (i.e. in pixels), so we need to consider the viewbox // to translate to user units; transform_center_x/y is in user units transform_center_x = (object_centre[Geom::X] - bbox->midpoint()[Geom::X])/viewscale; if (Geom::are_near(transform_center_x, 0)) // rounding error transform_center_x = 0; transform_center_y = (object_centre[Geom::Y] - bbox->midpoint()[Geom::Y])/viewscale; if (Geom::are_near(transform_center_y, 0)) // rounding error transform_center_y = 0; } } void SPItem::unsetCenter() { transform_center_x = 0; transform_center_y = 0; } bool SPItem::isCenterSet() const { return (transform_center_x != 0 || transform_center_y != 0); } // Get the item's transformation center in document coordinates (i.e. in pixels) Geom::Point SPItem::getCenter() const { document->ensureUpToDate(); // Copied from DocumentProperties::onDocUnitChange() gdouble viewscale = 1.0; Geom::Rect vb = this->document->getRoot()->viewBox; if ( !vb.hasZeroArea() ) { gdouble viewscale_w = this->document->getWidth().value("px") / vb.width(); gdouble viewscale_h = this->document->getHeight().value("px")/ vb.height(); viewscale = std::min(viewscale_h, viewscale_w); } // FIXME this is seriously wrong Geom::OptRect bbox = desktopGeometricBounds(); if (bbox) { // transform_center_x/y are stored in user units, so we have to take the viewbox into account to translate to document coordinates return bbox->midpoint() + Geom::Point (transform_center_x*viewscale, transform_center_y*viewscale); } else { return Geom::Point(0, 0); // something's wrong! } } void SPItem::scaleCenter(Geom::Scale const &sc) { transform_center_x *= sc[Geom::X]; transform_center_y *= sc[Geom::Y]; } namespace { bool is_item(SPObject const &object) { return SP_IS_ITEM(&object); } } void SPItem::raiseToTop() { using Inkscape::Algorithms::find_last_if; SPObject *topmost=find_last_if<SPObject::SiblingIterator>( next, NULL, &is_item ); if (topmost) { getRepr()->parent()->changeOrder( getRepr(), topmost->getRepr() ); } } void SPItem::raiseOne() { SPObject *next_higher=std::find_if<SPObject::SiblingIterator>( next, NULL, &is_item ); if (next_higher) { Inkscape::XML::Node *ref = next_higher->getRepr(); getRepr()->parent()->changeOrder(getRepr(), ref); } } void SPItem::lowerOne() { using Inkscape::Util::MutableList; using Inkscape::Util::reverse_list; MutableList<SPObject &> next_lower=std::find_if( reverse_list<SPObject::SiblingIterator>( parent->firstChild(), this ), MutableList<SPObject &>(), &is_item ); if (next_lower) { ++next_lower; Inkscape::XML::Node *ref = ( next_lower ? next_lower->getRepr() : NULL ); getRepr()->parent()->changeOrder(getRepr(), ref); } } void SPItem::lowerToBottom() { using Inkscape::Algorithms::find_last_if; using Inkscape::Util::MutableList; using Inkscape::Util::reverse_list; MutableList<SPObject &> bottom=find_last_if( reverse_list<SPObject::SiblingIterator>( parent->firstChild(), this ), MutableList<SPObject &>(), &is_item ); if (bottom) { ++bottom; Inkscape::XML::Node *ref = ( bottom ? bottom->getRepr() : NULL ); getRepr()->parent()->changeOrder(getRepr(), ref); } } /* * Move this SPItem into or after another SPItem in the doc * \param target - the SPItem to move into or after * \param intoafter - move to after the target (false), move inside (sublayer) of the target (true) */ void SPItem::moveTo(SPItem *target, gboolean intoafter) { Inkscape::XML::Node *target_ref = ( target ? target->getRepr() : NULL ); Inkscape::XML::Node *our_ref = getRepr(); gboolean first = FALSE; if (target_ref == our_ref) { // Move to ourself ignore return; } if (!target_ref) { // Assume move to the "first" in the top node, find the top node target_ref = our_ref; while (target_ref->parent() != target_ref->root()) { target_ref = target_ref->parent(); } first = TRUE; } if (intoafter) { // Move this inside of the target at the end our_ref->parent()->removeChild(our_ref); target_ref->addChild(our_ref, NULL); } else if (target_ref->parent() != our_ref->parent()) { // Change in parent, need to remove and add our_ref->parent()->removeChild(our_ref); target_ref->parent()->addChild(our_ref, target_ref); } else if (!first) { // Same parent, just move our_ref->parent()->changeOrder(our_ref, target_ref); } if (first && parent) { // If "first" ensure it appears after the defs etc lowerToBottom(); return; } } void SPItem::build(SPDocument *document, Inkscape::XML::Node *repr) { SPItem* object = this; object->readAttr( "style" ); object->readAttr( "transform" ); object->readAttr( "clip-path" ); object->readAttr( "mask" ); object->readAttr( "sodipodi:insensitive" ); object->readAttr( "sodipodi:nonprintable" ); object->readAttr( "inkscape:transform-center-x" ); object->readAttr( "inkscape:transform-center-y" ); object->readAttr( "inkscape:connector-avoid" ); object->readAttr( "inkscape:connection-points" ); SPObject::build(document, repr); } void SPItem::release() { SPItem* item = this; // Note: do this here before the clip_ref is deleted, since calling // ensureUpToDate() for triggered routing may reference // the deleted clip_ref. delete item->avoidRef; // we do NOT disconnect from the changed signal of those before deletion. // The destructor will call *_ref_changed with NULL as the new value, // which will cause the hide() function to be called. delete item->clip_ref; delete item->mask_ref; SPObject::release(); SPPaintServer *fill_ps = style->getFillPaintServer(); SPPaintServer *stroke_ps = style->getStrokePaintServer(); while (item->display) { if (fill_ps) { fill_ps->hide(item->display->arenaitem->key()); } if (stroke_ps) { stroke_ps->hide(item->display->arenaitem->key()); } item->display = sp_item_view_list_remove(item->display, item->display); } //item->_transformed_signal.~signal(); } void SPItem::set(unsigned int key, gchar const* value) { SPItem *item = this; SPItem* object = item; switch (key) { case SP_ATTR_TRANSFORM: { Geom::Affine t; if (value && sp_svg_transform_read(value, &t)) { item->set_item_transform(t); } else { item->set_item_transform(Geom::identity()); } break; } case SP_PROP_CLIP_PATH: { gchar *uri = extract_uri(value); if (uri) { try { item->clip_ref->attach(Inkscape::URI(uri)); } catch (Inkscape::BadURIException &e) { g_warning("%s", e.what()); item->clip_ref->detach(); } g_free(uri); } else { item->clip_ref->detach(); } break; } case SP_PROP_MASK: { gchar *uri = extract_uri(value); if (uri) { try { item->mask_ref->attach(Inkscape::URI(uri)); } catch (Inkscape::BadURIException &e) { g_warning("%s", e.what()); item->mask_ref->detach(); } g_free(uri); } else { item->mask_ref->detach(); } break; } case SP_ATTR_SODIPODI_INSENSITIVE: item->sensitive = !value; for (SPItemView *v = item->display; v != NULL; v = v->next) { v->arenaitem->setSensitive(item->sensitive); } break; case SP_ATTR_CONNECTOR_AVOID: item->avoidRef->setAvoid(value); break; case SP_ATTR_TRANSFORM_CENTER_X: if (value) { item->transform_center_x = g_strtod(value, NULL); } else { item->transform_center_x = 0; } object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; case SP_ATTR_TRANSFORM_CENTER_Y: if (value) { item->transform_center_y = g_strtod(value, NULL); } else { item->transform_center_y = 0; } object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; case SP_PROP_SYSTEM_LANGUAGE: case SP_PROP_REQUIRED_FEATURES: case SP_PROP_REQUIRED_EXTENSIONS: { item->resetEvaluated(); // pass to default handler } default: if (SP_ATTRIBUTE_IS_CSS(key)) { sp_style_read_from_object(object->style, object); object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); } else { SPObject::set(key, value); } break; } } void SPItem::clip_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item) { item->bbox_valid = FALSE; // force a re-evaluation if (old_clip) { SPItemView *v; /* Hide clippath */ for (v = item->display; v != NULL; v = v->next) { SP_CLIPPATH(old_clip)->hide(v->arenaitem->key()); } } if (SP_IS_CLIPPATH(clip)) { Geom::OptRect bbox = item->geometricBounds(); for (SPItemView *v = item->display; v != NULL; v = v->next) { if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } Inkscape::DrawingItem *ai = SP_CLIPPATH(clip)->show( v->arenaitem->drawing(), v->arenaitem->key()); v->arenaitem->setClip(ai); SP_CLIPPATH(clip)->setBBox(v->arenaitem->key(), bbox); clip->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } } void SPItem::mask_ref_changed(SPObject *old_mask, SPObject *mask, SPItem *item) { if (old_mask) { /* Hide mask */ for (SPItemView *v = item->display; v != NULL; v = v->next) { SP_MASK(old_mask)->sp_mask_hide(v->arenaitem->key()); } } if (SP_IS_MASK(mask)) { Geom::OptRect bbox = item->geometricBounds(); for (SPItemView *v = item->display; v != NULL; v = v->next) { if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } Inkscape::DrawingItem *ai = SP_MASK(mask)->sp_mask_show( v->arenaitem->drawing(), v->arenaitem->key()); v->arenaitem->setMask(ai); SP_MASK(mask)->sp_mask_set_bbox(v->arenaitem->key(), bbox); mask->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } } void SPItem::fill_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) { SPPaintServer *old_fill_ps = SP_PAINT_SERVER(old_ps); if (old_fill_ps) { for (SPItemView *v =item->display; v != NULL; v = v->next) { old_fill_ps->hide(v->arenaitem->key()); } } SPPaintServer *new_fill_ps = SP_PAINT_SERVER(ps); if (new_fill_ps) { Geom::OptRect bbox = item->geometricBounds(); for (SPItemView *v = item->display; v != NULL; v = v->next) { if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } Inkscape::DrawingPattern *pi = new_fill_ps->show( v->arenaitem->drawing(), v->arenaitem->key(), bbox); v->arenaitem->setFillPattern(pi); if (pi) { new_fill_ps->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } } } void SPItem::stroke_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) { SPPaintServer *old_stroke_ps = SP_PAINT_SERVER(old_ps); if (old_stroke_ps) { for (SPItemView *v =item->display; v != NULL; v = v->next) { old_stroke_ps->hide(v->arenaitem->key()); } } SPPaintServer *new_stroke_ps = SP_PAINT_SERVER(ps); if (new_stroke_ps) { Geom::OptRect bbox = item->geometricBounds(); for (SPItemView *v = item->display; v != NULL; v = v->next) { if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } Inkscape::DrawingPattern *pi = new_stroke_ps->show( v->arenaitem->drawing(), v->arenaitem->key(), bbox); v->arenaitem->setStrokePattern(pi); if (pi) { new_stroke_ps->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } } } void SPItem::update(SPCtx* /*ctx*/, guint flags) { SPItem *item = this; SPItem* object = item; // SPObject::onUpdate(ctx, flags); // any of the modifications defined in sp-object.h might change bbox, // so we invalidate it unconditionally item->bbox_valid = FALSE; if (flags & (SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG)) { if (flags & SP_OBJECT_MODIFIED_FLAG) { for (SPItemView *v = item->display; v != NULL; v = v->next) { v->arenaitem->setTransform(item->transform); } } SPClipPath *clip_path = item->clip_ref ? item->clip_ref->getObject() : NULL; SPMask *mask = item->mask_ref ? item->mask_ref->getObject() : NULL; if ( clip_path || mask ) { Geom::OptRect bbox = item->geometricBounds(); if (clip_path) { for (SPItemView *v = item->display; v != NULL; v = v->next) { clip_path->setBBox(v->arenaitem->key(), bbox); } } if (mask) { for (SPItemView *v = item->display; v != NULL; v = v->next) { mask->sp_mask_set_bbox(v->arenaitem->key(), bbox); } } } if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) { for (SPItemView *v = item->display; v != NULL; v = v->next) { v->arenaitem->setOpacity(SP_SCALE24_TO_FLOAT(object->style->opacity.value)); v->arenaitem->setAntialiasing(object->style->shape_rendering.computed != SP_CSS_SHAPE_RENDERING_CRISPEDGES); v->arenaitem->setIsolation( object->style->isolation.value ); v->arenaitem->setBlendMode( object->style->mix_blend_mode.value ); v->arenaitem->setVisible(!item->isHidden()); } } } /* Update bounding box in user space, used for filter and objectBoundingBox units */ if (item->style->filter.set && item->display) { Geom::OptRect item_bbox = item->geometricBounds(); SPItemView *itemview = item->display; do { if (itemview->arenaitem) itemview->arenaitem->setItemBounds(item_bbox); } while ( (itemview = itemview->next) ); } // Update libavoid with item geometry (for connector routing). if (item->avoidRef) item->avoidRef->handleSettingChange(); } void SPItem::modified(unsigned int /*flags*/) { } Inkscape::XML::Node* SPItem::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { SPItem *item = this; SPItem* object = item; // in the case of SP_OBJECT_WRITE_BUILD, the item should always be newly created, // so we need to add any children from the underlying object to the new repr if (flags & SP_OBJECT_WRITE_BUILD) { GSList *l = NULL; for (SPObject *child = object->firstChild(); child != NULL; child = child->next ) { if (SP_IS_TITLE(child) || SP_IS_DESC(child)) { Inkscape::XML::Node *crepr = child->updateRepr(xml_doc, NULL, flags); if (crepr) { l = g_slist_prepend (l, crepr); } } } while (l) { repr->addChild((Inkscape::XML::Node *) l->data, NULL); Inkscape::GC::release((Inkscape::XML::Node *) l->data); l = g_slist_remove (l, l->data); } } else { for (SPObject *child = object->firstChild() ; child != NULL; child = child->next ) { if (SP_IS_TITLE(child) || SP_IS_DESC(child)) { child->updateRepr(flags); } } } gchar *c = sp_svg_transform_write(item->transform); repr->setAttribute("transform", c); g_free(c); if (flags & SP_OBJECT_WRITE_EXT) { repr->setAttribute("sodipodi:insensitive", ( item->sensitive ? NULL : "true" )); if (item->transform_center_x != 0) sp_repr_set_svg_double (repr, "inkscape:transform-center-x", item->transform_center_x); else repr->setAttribute ("inkscape:transform-center-x", NULL); if (item->transform_center_y != 0) sp_repr_set_svg_double (repr, "inkscape:transform-center-y", item->transform_center_y); else repr->setAttribute ("inkscape:transform-center-y", NULL); } if (item->clip_ref){ if (item->clip_ref->getObject()) { gchar *uri = item->clip_ref->getURI()->toString(); const gchar *value = g_strdup_printf ("url(%s)", uri); repr->setAttribute ("clip-path", value); g_free ((void *) value); g_free ((void *) uri); } } if (item->mask_ref){ if (item->mask_ref->getObject()) { gchar *uri = item->mask_ref->getURI()->toString(); const gchar *value = g_strdup_printf ("url(%s)", uri); repr->setAttribute ("mask", value); g_free ((void *) value); g_free ((void *) uri); } } SPObject::write(xml_doc, repr, flags); return repr; } // CPPIFY: make pure virtual Geom::OptRect SPItem::bbox(Geom::Affine const & /*transform*/, SPItem::BBoxType /*type*/) const { //throw; return Geom::OptRect(); } /** * Get item's geometric bounding box in this item's coordinate system. * * The geometric bounding box includes only the path, disregarding all style attributes. */ Geom::OptRect SPItem::geometricBounds(Geom::Affine const &transform) const { Geom::OptRect bbox; // call the subclass method // CPPIFY //bbox = this->bbox(transform, SPItem::GEOMETRIC_BBOX); bbox = const_cast<SPItem*>(this)->bbox(transform, SPItem::GEOMETRIC_BBOX); return bbox; } /** * Get item's visual bounding box in this item's coordinate system. * * The visual bounding box includes the stroke and the filter region. */ Geom::OptRect SPItem::visualBounds(Geom::Affine const &transform) const { using Geom::X; using Geom::Y; Geom::OptRect bbox; if ( style && style->filter.href && style->getFilter() && SP_IS_FILTER(style->getFilter())) { // call the subclass method // CPPIFY //bbox = this->bbox(Geom::identity(), SPItem::VISUAL_BBOX); bbox = const_cast<SPItem*>(this)->bbox(Geom::identity(), SPItem::GEOMETRIC_BBOX); // see LP Bug 1229971 SPFilter *filter = SP_FILTER(style->getFilter()); // default filer area per the SVG spec: SVGLength x, y, w, h; Geom::Point minp, maxp; x.set(SVGLength::PERCENT, -0.10, 0); y.set(SVGLength::PERCENT, -0.10, 0); w.set(SVGLength::PERCENT, 1.20, 0); h.set(SVGLength::PERCENT, 1.20, 0); // if area is explicitly set, override: if (filter->x._set) x = filter->x; if (filter->y._set) y = filter->y; if (filter->width._set) w = filter->width; if (filter->height._set) h = filter->height; double len_x = bbox ? bbox->width() : 0; double len_y = bbox ? bbox->height() : 0; x.update(12, 6, len_x); y.update(12, 6, len_y); w.update(12, 6, len_x); h.update(12, 6, len_y); if (filter->filterUnits == SP_FILTER_UNITS_OBJECTBOUNDINGBOX && bbox) { minp[X] = bbox->left() + x.computed * (x.unit == SVGLength::PERCENT ? 1.0 : len_x); maxp[X] = minp[X] + w.computed * (w.unit == SVGLength::PERCENT ? 1.0 : len_x); minp[Y] = bbox->top() + y.computed * (y.unit == SVGLength::PERCENT ? 1.0 : len_y); maxp[Y] = minp[Y] + h.computed * (h.unit == SVGLength::PERCENT ? 1.0 : len_y); } else if (filter->filterUnits == SP_FILTER_UNITS_USERSPACEONUSE) { minp[X] = x.computed; maxp[X] = minp[X] + w.computed; minp[Y] = y.computed; maxp[Y] = minp[Y] + h.computed; } bbox = Geom::OptRect(minp, maxp); *bbox *= transform; } else { // call the subclass method // CPPIFY //bbox = this->bbox(transform, SPItem::VISUAL_BBOX); bbox = const_cast<SPItem*>(this)->bbox(transform, SPItem::VISUAL_BBOX); } if (clip_ref->getObject()) { SP_ITEM(clip_ref->getOwner())->bbox_valid = FALSE; // LP Bug 1349018 bbox.intersectWith(SP_CLIPPATH(clip_ref->getObject())->geometricBounds(transform)); } return bbox; } Geom::OptRect SPItem::bounds(BBoxType type, Geom::Affine const &transform) const { if (type == GEOMETRIC_BBOX) { return geometricBounds(transform); } else { return visualBounds(transform); } } /** Get item's geometric bbox in document coordinate system. * Document coordinates are the default coordinates of the root element: * the origin is at the top left, X grows to the right and Y grows downwards. */ Geom::OptRect SPItem::documentGeometricBounds() const { return geometricBounds(i2doc_affine()); } /// Get item's visual bbox in document coordinate system. Geom::OptRect SPItem::documentVisualBounds() const { if (!bbox_valid) { doc_bbox = visualBounds(i2doc_affine()); bbox_valid = true; } return doc_bbox; } Geom::OptRect SPItem::documentBounds(BBoxType type) const { if (type == GEOMETRIC_BBOX) { return documentGeometricBounds(); } else { return documentVisualBounds(); } } /** Get item's geometric bbox in desktop coordinate system. * Desktop coordinates should be user defined. Currently they are hardcoded: * origin is at bottom left, X grows to the right and Y grows upwards. */ Geom::OptRect SPItem::desktopGeometricBounds() const { return geometricBounds(i2dt_affine()); } /// Get item's visual bbox in desktop coordinate system. Geom::OptRect SPItem::desktopVisualBounds() const { /// @fixme hardcoded desktop transform Geom::Affine m = Geom::Scale(1, -1) * Geom::Translate(0, document->getHeight().value("px")); Geom::OptRect ret = documentVisualBounds(); if (ret) *ret *= m; return ret; } Geom::OptRect SPItem::desktopPreferredBounds() const { if (Inkscape::Preferences::get()->getInt("/tools/bounding_box") == 0) { return desktopBounds(SPItem::VISUAL_BBOX); } else { return desktopBounds(SPItem::GEOMETRIC_BBOX); } } Geom::OptRect SPItem::desktopBounds(BBoxType type) const { if (type == GEOMETRIC_BBOX) { return desktopGeometricBounds(); } else { return desktopVisualBounds(); } } unsigned int SPItem::pos_in_parent() const { g_assert(parent != NULL); g_assert(SP_IS_OBJECT(parent)); unsigned int pos = 0; for ( SPObject *iter = parent->firstChild() ; iter ; iter = iter->next) { if (iter == this) { return pos; } if (SP_IS_ITEM(iter)) { pos++; } } g_assert_not_reached(); return 0; } // CPPIFY: make pure virtual, see below! void SPItem::snappoints(std::vector<Inkscape::SnapCandidatePoint> & /*p*/, Inkscape::SnapPreferences const */*snapprefs*/) const { //throw; } /* This will only be called if the derived class doesn't override this. * see for example sp_genericellipse_snappoints in sp-ellipse.cpp * We don't know what shape we could be dealing with here, so we'll just * do nothing */ void SPItem::getSnappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const { // Get the snappoints of the item // CPPIFY //this->snappoints(p, snapprefs); const_cast<SPItem*>(this)->snappoints(p, snapprefs); // Get the snappoints at the item's center if (snapprefs != NULL && snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_ROTATION_CENTER)) { p.push_back(Inkscape::SnapCandidatePoint(getCenter(), Inkscape::SNAPSOURCE_ROTATION_CENTER, Inkscape::SNAPTARGET_ROTATION_CENTER)); } // Get the snappoints of clipping paths and mask, if any std::list<SPObject const *> clips_and_masks; clips_and_masks.push_back(clip_ref->getObject()); clips_and_masks.push_back(mask_ref->getObject()); SPDesktop *desktop = inkscape_active_desktop(); for (std::list<SPObject const *>::const_iterator o = clips_and_masks.begin(); o != clips_and_masks.end(); ++o) { if (*o) { // obj is a group object, the children are the actual clippers for (SPObject *child = (*o)->children ; child ; child = child->next) { if (SP_IS_ITEM(child)) { std::vector<Inkscape::SnapCandidatePoint> p_clip_or_mask; // Please note the recursive call here! SP_ITEM(child)->getSnappoints(p_clip_or_mask, snapprefs); // Take into account the transformation of the item being clipped or masked for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator p_orig = p_clip_or_mask.begin(); p_orig != p_clip_or_mask.end(); ++p_orig) { // All snappoints are in desktop coordinates, but the item's transformation is // in document coordinates. Hence the awkward construction below Geom::Point pt = desktop->dt2doc((*p_orig).getPoint()) * i2dt_affine(); p.push_back(Inkscape::SnapCandidatePoint(pt, (*p_orig).getSourceType(), (*p_orig).getTargetType())); } } } } } } // CPPIFY: make pure virtual void SPItem::print(SPPrintContext* /*ctx*/) { //throw; } void SPItem::invoke_print(SPPrintContext *ctx) { if ( !isHidden() ) { if (!transform.isIdentity() || style->opacity.value != SP_SCALE24_MAX) { sp_print_bind(ctx, transform, SP_SCALE24_TO_FLOAT(style->opacity.value)); this->print(ctx); sp_print_release(ctx); } else { this->print(ctx); } } } const char* SPItem::displayName() const { return _("Object"); } gchar* SPItem::description() const { return g_strdup(""); } /** * Returns a string suitable for status bar, formatted in pango markup language. * * Must be freed by caller. */ gchar *SPItem::detailedDescription() const { gchar* s = g_strdup_printf("<b>%s</b> %s", this->displayName(), this->description()); if (s && clip_ref->getObject()) { gchar *snew = g_strdup_printf (_("%s; <i>clipped</i>"), s); g_free (s); s = snew; } if (s && mask_ref->getObject()) { gchar *snew = g_strdup_printf (_("%s; <i>masked</i>"), s); g_free (s); s = snew; } if ( style && style->filter.href && style->filter.href->getObject() ) { const gchar *label = style->filter.href->getObject()->label(); gchar *snew = 0; if (label) { snew = g_strdup_printf (_("%s; <i>filtered (%s)</i>"), s, _(label)); } else { snew = g_strdup_printf (_("%s; <i>filtered</i>"), s); } g_free (s); s = snew; } return s; } /** * Returns true if the item is filtered, false otherwise. Used with groups/lists to determine how many, or if any, are filtered * */ bool SPItem::isFiltered() const { return (style && style->filter.href && style->filter.href->getObject()); } /** * Allocates unique integer keys. * \param numkeys Number of keys required. * \return First allocated key; hence if the returned key is n * you can use n, n + 1, ..., n + (numkeys - 1) */ unsigned SPItem::display_key_new(unsigned numkeys) { static unsigned dkey = 0; dkey += numkeys; return dkey - numkeys; } // CPPIFY: make pure virtual Inkscape::DrawingItem* SPItem::show(Inkscape::Drawing& /*drawing*/, unsigned int /*key*/, unsigned int /*flags*/) { //throw; return 0; } Inkscape::DrawingItem *SPItem::invoke_show(Inkscape::Drawing &drawing, unsigned key, unsigned flags) { Inkscape::DrawingItem *ai = NULL; ai = this->show(drawing, key, flags); if (ai != NULL) { Geom::OptRect item_bbox = geometricBounds(); display = sp_item_view_new_prepend(display, this, flags, key, ai); ai->setTransform(transform); ai->setOpacity(SP_SCALE24_TO_FLOAT(style->opacity.value)); ai->setIsolation( style->isolation.value ); ai->setBlendMode( style->mix_blend_mode.value ); //ai->setCompositeOperator( style->composite_op.value ); ai->setVisible(!isHidden()); ai->setSensitive(sensitive); if (clip_ref->getObject()) { SPClipPath *cp = clip_ref->getObject(); if (!display->arenaitem->key()) { display->arenaitem->setKey(display_key_new(3)); } int clip_key = display->arenaitem->key(); // Show and set clip Inkscape::DrawingItem *ac = cp->show(drawing, clip_key); ai->setClip(ac); // Update bbox, in case the clip uses bbox units SP_CLIPPATH(cp)->setBBox(clip_key, item_bbox); cp->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } if (mask_ref->getObject()) { SPMask *mask = mask_ref->getObject(); if (!display->arenaitem->key()) { display->arenaitem->setKey(display_key_new(3)); } int mask_key = display->arenaitem->key(); // Show and set mask Inkscape::DrawingItem *ac = mask->sp_mask_show(drawing, mask_key); ai->setMask(ac); // Update bbox, in case the mask uses bbox units SP_MASK(mask)->sp_mask_set_bbox(mask_key, item_bbox); mask->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } SPPaintServer *fill_ps = style->getFillPaintServer(); if (fill_ps) { if (!display->arenaitem->key()) { display->arenaitem->setKey(display_key_new(3)); } int fill_key = display->arenaitem->key(); Inkscape::DrawingPattern *ap = fill_ps->show(drawing, fill_key, item_bbox); ai->setFillPattern(ap); if (ap) { fill_ps->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } SPPaintServer *stroke_ps = style->getStrokePaintServer(); if (stroke_ps) { if (!display->arenaitem->key()) { display->arenaitem->setKey(display_key_new(3)); } int stroke_key = display->arenaitem->key(); Inkscape::DrawingPattern *ap = stroke_ps->show(drawing, stroke_key, item_bbox); ai->setStrokePattern(ap); if (ap) { stroke_ps->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } ai->setData(this); ai->setItemBounds(geometricBounds()); } return ai; } // CPPIFY: make pure virtual void SPItem::hide(unsigned int /*key*/) { //throw; } void SPItem::invoke_hide(unsigned key) { this->hide(key); SPItemView *ref = NULL; SPItemView *v = display; while (v != NULL) { SPItemView *next = v->next; if (v->key == key) { if (clip_ref->getObject()) { (clip_ref->getObject())->hide(v->arenaitem->key()); v->arenaitem->setClip(NULL); } if (mask_ref->getObject()) { mask_ref->getObject()->sp_mask_hide(v->arenaitem->key()); v->arenaitem->setMask(NULL); } SPPaintServer *fill_ps = style->getFillPaintServer(); if (fill_ps) { fill_ps->hide(v->arenaitem->key()); } SPPaintServer *stroke_ps = style->getStrokePaintServer(); if (stroke_ps) { stroke_ps->hide(v->arenaitem->key()); } if (!ref) { display = v->next; } else { ref->next = v->next; } delete v->arenaitem; g_free(v); } else { ref = v; } v = next; } } // Adjusters void SPItem::adjust_pattern(Geom::Affine const &postmul, bool set, PatternTransform pt) { bool fill = (pt == TRANSFORM_FILL || pt == TRANSFORM_BOTH); if (fill && style && (style->fill.isPaintserver())) { SPObject *server = style->getFillPaintServer(); if ( SP_IS_PATTERN(server) ) { SPPattern *pattern = sp_pattern_clone_if_necessary(this, SP_PATTERN(server), "fill"); sp_pattern_transform_multiply(pattern, postmul, set); } } bool stroke = (pt == TRANSFORM_STROKE || pt == TRANSFORM_BOTH); if (stroke && style && (style->stroke.isPaintserver())) { SPObject *server = style->getStrokePaintServer(); if ( SP_IS_PATTERN(server) ) { SPPattern *pattern = sp_pattern_clone_if_necessary(this, SP_PATTERN(server), "stroke"); sp_pattern_transform_multiply(pattern, postmul, set); } } } void SPItem::adjust_gradient( Geom::Affine const &postmul, bool set ) { if ( style && style->fill.isPaintserver() ) { SPPaintServer *server = style->getFillPaintServer(); if ( SP_IS_GRADIENT(server) ) { /** * \note Bbox units for a gradient are generally a bad idea because * with them, you cannot preserve the relative position of the * object and its gradient after rotation or skew. So now we * convert them to userspace units which are easy to keep in sync * just by adding the object's transform to gradientTransform. * \todo FIXME: convert back to bbox units after transforming with * the item, so as to preserve the original units. */ SPGradient *gradient = sp_gradient_convert_to_userspace( SP_GRADIENT(server), this, "fill" ); sp_gradient_transform_multiply( gradient, postmul, set ); } } if ( style && style->stroke.isPaintserver() ) { SPPaintServer *server = style->getStrokePaintServer(); if ( SP_IS_GRADIENT(server) ) { SPGradient *gradient = sp_gradient_convert_to_userspace( SP_GRADIENT(server), this, "stroke"); sp_gradient_transform_multiply( gradient, postmul, set ); } } } void SPItem::adjust_stroke( gdouble ex ) { if (freeze_stroke_width) { return; } SPStyle *style = this->style; if (style && !style->stroke.isNone() && !Geom::are_near(ex, 1.0, Geom::EPSILON)) { style->stroke_width.computed *= ex; style->stroke_width.set = TRUE; if ( !style->stroke_dasharray.values.empty() ) { for (unsigned i = 0; i < style->stroke_dasharray.values.size(); i++) { style->stroke_dasharray.values[i] *= ex; } style->stroke_dashoffset.value *= ex; } updateRepr(); } } /** * Find out the inverse of previous transform of an item (from its repr) */ static Geom::Affine sp_item_transform_repr (SPItem *item) { Geom::Affine t_old(Geom::identity()); gchar const *t_attr = item->getRepr()->attribute("transform"); if (t_attr) { Geom::Affine t; if (sp_svg_transform_read(t_attr, &t)) { t_old = t; } } return t_old; } /** * Recursively scale stroke width in \a item and its children by \a expansion. */ void SPItem::adjust_stroke_width_recursive(double expansion) { adjust_stroke (expansion); // A clone's child is the ghost of its original - we must not touch it, skip recursion if ( !SP_IS_USE(this) ) { for ( SPObject *o = children; o; o = o->getNext() ) { if (SP_IS_ITEM(o)) { SP_ITEM(o)->adjust_stroke_width_recursive(expansion); } } } } void SPItem::freeze_stroke_width_recursive(bool freeze) { freeze_stroke_width = freeze; // A clone's child is the ghost of its original - we must not touch it, skip recursion if ( !SP_IS_USE(this) ) { for ( SPObject *o = children; o; o = o->getNext() ) { if (SP_IS_ITEM(o)) { SP_ITEM(o)->freeze_stroke_width_recursive(freeze); } } } } /** * Recursively adjust rx and ry of rects. */ static void sp_item_adjust_rects_recursive(SPItem *item, Geom::Affine advertized_transform) { if (SP_IS_RECT (item)) { SP_RECT(item)->compensateRxRy(advertized_transform); } for (SPObject *o = item->children; o != NULL; o = o->next) { if (SP_IS_ITEM(o)) sp_item_adjust_rects_recursive(SP_ITEM(o), advertized_transform); } } /** * Recursively compensate pattern or gradient transform. */ void SPItem::adjust_paint_recursive (Geom::Affine advertized_transform, Geom::Affine t_ancestors, bool is_pattern) { // _Before_ full pattern/gradient transform: t_paint * t_item * t_ancestors // _After_ full pattern/gradient transform: t_paint_new * t_item * t_ancestors * advertised_transform // By equating these two expressions we get t_paint_new = t_paint * paint_delta, where: Geom::Affine t_item = sp_item_transform_repr (this); Geom::Affine paint_delta = t_item * t_ancestors * advertized_transform * t_ancestors.inverse() * t_item.inverse(); // Within text, we do not fork gradients, and so must not recurse to avoid double compensation; // also we do not recurse into clones, because a clone's child is the ghost of its original - // we must not touch it if (!(this && (SP_IS_TEXT(this) || SP_IS_USE(this)))) { for (SPObject *o = children; o != NULL; o = o->next) { if (SP_IS_ITEM(o)) { // At the level of the transformed item, t_ancestors is identity; // below it, it is the accmmulated chain of transforms from this level to the top level SP_ITEM(o)->adjust_paint_recursive (advertized_transform, t_item * t_ancestors, is_pattern); } } } // We recursed into children first, and are now adjusting this object second; // this is so that adjustments in a tree are done from leaves up to the root, // and paintservers on leaves inheriting their values from ancestors could adjust themselves properly // before ancestors themselves are adjusted, probably differently (bug 1286535) if (is_pattern) { adjust_pattern(paint_delta); } else { adjust_gradient(paint_delta); } } void SPItem::adjust_livepatheffect (Geom::Affine const &postmul, bool set) { if ( SP_IS_LPE_ITEM(this) ) { SPLPEItem *lpeitem = SP_LPE_ITEM (this); if ( lpeitem->hasPathEffect() ) { lpeitem->forkPathEffectsIfNecessary(); // now that all LPEs are forked_if_necessary, we can apply the transform PathEffectList effect_list = lpeitem->getEffectList(); for (PathEffectList::iterator it = effect_list.begin(); it != effect_list.end(); ++it) { LivePathEffectObject *lpeobj = (*it)->lpeobject; if (lpeobj && lpeobj->get_lpe()) { Inkscape::LivePathEffect::Effect * effect = lpeobj->get_lpe(); effect->transform_multiply(postmul, set); } } } } } // CPPIFY:: make pure virtual? // Not all SPItems must necessarily have a set transform method! Geom::Affine SPItem::set_transform(Geom::Affine const &transform) { // throw; return transform; } /** * Set a new transform on an object. * * Compensate for stroke scaling and gradient/pattern fill transform, if * necessary. Call the object's set_transform method if transforms are * stored optimized. Send _transformed_signal. Invoke _write method so that * the repr is updated with the new transform. */ void SPItem::doWriteTransform(Inkscape::XML::Node *repr, Geom::Affine const &transform, Geom::Affine const *adv, bool compensate) { g_return_if_fail(repr != NULL); // calculate the relative transform, if not given by the adv attribute Geom::Affine advertized_transform; if (adv != NULL) { advertized_transform = *adv; } else { advertized_transform = sp_item_transform_repr (this).inverse() * transform; } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (compensate) { // recursively compensating for stroke scaling will not always work, because it can be scaled to zero or infinite // from which we cannot ever recover by applying an inverse scale; therefore we temporarily block any changes // to the strokewidth in such a case instead, and unblock these after the transformation // (as reported in https://bugs.launchpad.net/inkscape/+bug/825840/comments/4) if (!prefs->getBool("/options/transform/stroke", true)) { double const expansion = 1. / advertized_transform.descrim(); if (expansion < 1e-9 || expansion > 1e9) { freeze_stroke_width_recursive(true); // This will only work if the item has a set_transform method (in this method adjust_stroke() will be called) // We will still have to apply the inverse scaling to other items, not having a set_transform method // such as ellipses and stars // PS: We cannot use this freeze_stroke_width_recursive() trick in all circumstances. For example, it will // break pasting objects within their group (because in such a case the transformation of the group will affect // the strokewidth, and has to be compensated for. See https://bugs.launchpad.net/inkscape/+bug/959223/comments/10) } else { adjust_stroke_width_recursive(expansion); } } // recursively compensate rx/ry of a rect if requested if (!prefs->getBool("/options/transform/rectcorners", true)) { sp_item_adjust_rects_recursive(this, advertized_transform); } // recursively compensate pattern fill if it's not to be transformed if (!prefs->getBool("/options/transform/pattern", true)) { adjust_paint_recursive (advertized_transform.inverse(), Geom::identity(), true); } /// \todo FIXME: add the same else branch as for gradients below, to convert patterns to userSpaceOnUse as well /// recursively compensate gradient fill if it's not to be transformed if (!prefs->getBool("/options/transform/gradient", true)) { adjust_paint_recursive (advertized_transform.inverse(), Geom::identity(), false); } else { // this converts the gradient/pattern fill/stroke, if any, to userSpaceOnUse; we need to do // it here _before_ the new transform is set, so as to use the pre-transform bbox adjust_paint_recursive (Geom::identity(), Geom::identity(), false); } } // endif(compensate) gint preserve = prefs->getBool("/options/preservetransform/value", 0); Geom::Affine transform_attr (transform); // CPPIFY: check this code. // If onSetTransform is not overridden, CItem::onSetTransform will return the transform it was given as a parameter. // onSetTransform cannot be pure due to the fact that not all visible Items are transformable. if ( // run the object's set_transform (i.e. embed transform) only if: SP_IS_TEXT_TEXTPATH(this) || (!preserve && // user did not chose to preserve all transforms (!clip_ref || !clip_ref->getObject()) && // the object does not have a clippath (!mask_ref || !mask_ref->getObject()) && // the object does not have a mask !(!transform.isTranslation() && style && style->getFilter())) // the object does not have a filter, or the transform is translation (which is supposed to not affect filters) ) { transform_attr = this->set_transform(transform); if (freeze_stroke_width) { freeze_stroke_width_recursive(false); } } else { if (freeze_stroke_width) { freeze_stroke_width_recursive(false); if (compensate) { if (!prefs->getBool("/options/transform/stroke", true)) { // Recursively compensate for stroke scaling, depending on user preference // (As to why we need to do this, see the comment a few lines above near the freeze_stroke_width_recursive(true) call) double const expansion = 1. / advertized_transform.descrim(); adjust_stroke_width_recursive(expansion); } } } } set_item_transform(transform_attr); // Note: updateRepr comes before emitting the transformed signal since // it causes clone SPUse's copy of the original object to brought up to // date with the original. Otherwise, sp_use_bbox returns incorrect // values if called in code handling the transformed signal. updateRepr(); // send the relative transform with a _transformed_signal _transformed_signal.emit(&advertized_transform, this); } // CPPIFY: see below, do not make pure? gint SPItem::event(SPEvent* /*event*/) { return FALSE; } gint SPItem::emitEvent(SPEvent &event) { return this->event(&event); } /** * Sets item private transform (not propagated to repr), without compensating stroke widths, * gradients, patterns as sp_item_write_transform does. */ void SPItem::set_item_transform(Geom::Affine const &transform_matrix) { if (!Geom::are_near(transform_matrix, transform, 1e-18)) { transform = transform_matrix; /* The SP_OBJECT_USER_MODIFIED_FLAG_B is used to mark the fact that it's only a transformation. It's apparently not used anywhere else. */ requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_USER_MODIFIED_FLAG_B); sp_item_rm_unsatisfied_cns(*this); } } //void SPItem::convert_to_guides() const { // // CPPIFY: If not overridden, call SPItem::convert_to_guides() const, see below! // this->convert_to_guides(); //} /** * \pre \a ancestor really is an ancestor (\>=) of \a object, or NULL. * ("Ancestor (\>=)" here includes as far as \a object itself.) */ Geom::Affine i2anc_affine(SPObject const *object, SPObject const *const ancestor) { Geom::Affine ret(Geom::identity()); g_return_val_if_fail(object != NULL, ret); /* stop at first non-renderable ancestor */ while ( object != ancestor && SP_IS_ITEM(object) ) { if (SP_IS_ROOT(object)) { ret *= SP_ROOT(object)->c2p; } else { ret *= SP_ITEM(object)->transform; } object = object->parent; } return ret; } Geom::Affine i2i_affine(SPObject const *src, SPObject const *dest) { g_return_val_if_fail(src != NULL && dest != NULL, Geom::identity()); SPObject const *ancestor = src->nearestCommonAncestor(dest); return i2anc_affine(src, ancestor) * i2anc_affine(dest, ancestor).inverse(); } Geom::Affine SPItem::getRelativeTransform(SPObject const *dest) const { return i2i_affine(this, dest); } /** * Returns the accumulated transformation of the item and all its ancestors, including root's viewport. * \pre (item != NULL) and SP_IS_ITEM(item). */ Geom::Affine SPItem::i2doc_affine() const { return i2anc_affine(this, NULL); } /** * Returns the transformation from item to desktop coords */ Geom::Affine SPItem::i2dt_affine() const { Geom::Affine ret; SPDesktop const *desktop = inkscape_active_desktop(); if ( desktop ) { ret = i2doc_affine() * desktop->doc2dt(); } else { // TODO temp code to prevent crashing on command-line launch: ret = i2doc_affine() * Geom::Scale(1, -1) * Geom::Translate(0, document->getHeight().value("px")); } return ret; } void SPItem::set_i2d_affine(Geom::Affine const &i2dt) { Geom::Affine dt2p; /* desktop to item parent transform */ if (parent) { dt2p = static_cast<SPItem *>(parent)->i2dt_affine().inverse(); } else { SPDesktop *dt = inkscape_active_desktop(); dt2p = dt->dt2doc(); } Geom::Affine const i2p( i2dt * dt2p ); set_item_transform(i2p); } /** * should rather be named "sp_item_d2i_affine" to match "sp_item_i2d_affine" (or vice versa) */ Geom::Affine SPItem::dt2i_affine() const { /* fixme: Implement the right way (Lauris) */ return i2dt_affine().inverse(); } /* Item views */ SPItemView *SPItem::sp_item_view_new_prepend(SPItemView *list, SPItem *item, unsigned flags, unsigned key, Inkscape::DrawingItem *drawing_item) { g_assert(item != NULL); g_assert(SP_IS_ITEM(item)); g_assert(drawing_item != NULL); SPItemView *new_view = g_new(SPItemView, 1); new_view->next = list; new_view->flags = flags; new_view->key = key; new_view->arenaitem = drawing_item; return new_view; } static SPItemView* sp_item_view_list_remove(SPItemView *list, SPItemView *view) { SPItemView *ret = list; if (view == list) { ret = list->next; } else { SPItemView *prev; prev = list; while (prev->next != view) prev = prev->next; prev->next = view->next; } delete view->arenaitem; g_free(view); return ret; } /** * Return the arenaitem corresponding to the given item in the display * with the given key */ Inkscape::DrawingItem *SPItem::get_arenaitem(unsigned key) { for ( SPItemView *iv = display ; iv ; iv = iv->next ) { if ( iv->key == key ) { return iv->arenaitem; } } return NULL; } int sp_item_repr_compare_position(SPItem const *first, SPItem const *second) { return sp_repr_compare_position(first->getRepr(), second->getRepr()); } SPItem const *sp_item_first_item_child(SPObject const *obj) { return sp_item_first_item_child( const_cast<SPObject *>(obj) ); } SPItem *sp_item_first_item_child(SPObject *obj) { SPItem *child = 0; for ( SPObject *iter = obj->firstChild() ; iter ; iter = iter->next ) { if ( SP_IS_ITEM(iter) ) { child = SP_ITEM(iter); break; } } return child; } void SPItem::convert_to_guides() const { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int prefs_bbox = prefs->getInt("/tools/bounding_box", 0); Geom::OptRect bbox = (prefs_bbox == 0) ? desktopVisualBounds() : desktopGeometricBounds(); if (!bbox) { g_warning ("Cannot determine item's bounding box during conversion to guides.\n"); return; } std::list<std::pair<Geom::Point, Geom::Point> > pts; Geom::Point A((*bbox).min()); Geom::Point C((*bbox).max()); Geom::Point B(A[Geom::X], C[Geom::Y]); Geom::Point D(C[Geom::X], A[Geom::Y]); pts.push_back(std::make_pair(A, B)); pts.push_back(std::make_pair(B, C)); pts.push_back(std::make_pair(C, D)); pts.push_back(std::make_pair(D, A)); sp_guide_pt_pairs_to_guides(document, pts); } /* Local Variables: mode:c++ c-file-style:"stroustrup" c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) indent-tabs-mode:nil fill-column:99 End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :
yaii/yai
src/sp-item.cpp
C++
gpl-2.0
59,315
class CreateFeedbacks < ActiveRecord::Migration[4.2] def change create_table :feedbacks do |t| t.references :feedback_receiving, index: {name: :feedbacks_polymorphic_index}, polymorphic: true, null: false t.string :author_email t.integer :rating, null: false t.text :comment, null: false t.string :ip_address t.string :session_id, index: true t.timestamps null: false end end end
ignisf/clarion
db/migrate/20171022182011_create_feedbacks.rb
Ruby
gpl-2.0
435
/* $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 yapf_common.hpp Commonly used classes for YAPF. */ #ifndef YAPF_COMMON_HPP #define YAPF_COMMON_HPP /** YAPF origin provider base class - used when origin is one tile / multiple trackdirs */ template <class Types> class CYapfOriginTileT { public: typedef typename Types::Tpf Tpf; ///< the pathfinder class (derived from THIS class) typedef typename Types::NodeList::Titem Node; ///< this will be our node type typedef typename Node::Key Key; ///< key to hash tables protected: TileIndex m_orgTile; ///< origin tile TrackdirBits m_orgTrackdirs; ///< origin trackdir mask /** to access inherited path finder */ FORCEINLINE Tpf& Yapf() { return *static_cast<Tpf*>(this); } public: /** Set origin tile / trackdir mask */ void SetOrigin(TileIndex tile, TrackdirBits trackdirs) { m_orgTile = tile; m_orgTrackdirs = trackdirs; } /** Called when YAPF needs to place origin nodes into open list */ void PfSetStartupNodes() { bool is_choice = (KillFirstBit(m_orgTrackdirs) != TRACKDIR_BIT_NONE); for (TrackdirBits tdb = m_orgTrackdirs; tdb != TRACKDIR_BIT_NONE; tdb = KillFirstBit(tdb)) { Trackdir td = (Trackdir)FindFirstBit2x64(tdb); Node& n1 = Yapf().CreateNewNode(); n1.Set(NULL, m_orgTile, td, is_choice); Yapf().AddStartupNode(n1); } } }; /** YAPF origin provider base class - used when there are two tile/trackdir origins */ template <class Types> class CYapfOriginTileTwoWayT { public: typedef typename Types::Tpf Tpf; ///< the pathfinder class (derived from THIS class) typedef typename Types::NodeList::Titem Node; ///< this will be our node type typedef typename Node::Key Key; ///< key to hash tables protected: TileIndex m_orgTile; ///< first origin tile Trackdir m_orgTd; ///< first origin trackdir TileIndex m_revTile; ///< second (reversed) origin tile Trackdir m_revTd; ///< second (reversed) origin trackdir int m_reverse_penalty; ///< penalty to be added for using the reversed origin bool m_treat_first_red_two_way_signal_as_eol; ///< in some cases (leaving station) we need to handle first two-way signal differently /** to access inherited path finder */ FORCEINLINE Tpf& Yapf() { return *static_cast<Tpf*>(this); } public: /** set origin (tiles, trackdirs, etc.) */ void SetOrigin(TileIndex tile, Trackdir td, TileIndex tiler = INVALID_TILE, Trackdir tdr = INVALID_TRACKDIR, int reverse_penalty = 0, bool treat_first_red_two_way_signal_as_eol = true) { m_orgTile = tile; m_orgTd = td; m_revTile = tiler; m_revTd = tdr; m_reverse_penalty = reverse_penalty; m_treat_first_red_two_way_signal_as_eol = treat_first_red_two_way_signal_as_eol; } /** Called when YAPF needs to place origin nodes into open list */ void PfSetStartupNodes() { if (m_orgTile != INVALID_TILE && m_orgTd != INVALID_TRACKDIR) { Node& n1 = Yapf().CreateNewNode(); n1.Set(NULL, m_orgTile, m_orgTd, false); Yapf().AddStartupNode(n1); } if (m_revTile != INVALID_TILE && m_revTd != INVALID_TRACKDIR) { Node& n2 = Yapf().CreateNewNode(); n2.Set(NULL, m_revTile, m_revTd, false); n2.m_cost = m_reverse_penalty; Yapf().AddStartupNode(n2); } } /** return true if first two-way signal should be treated as dead end */ FORCEINLINE bool TreatFirstRedTwoWaySignalAsEOL() { return Yapf().PfGetSettings().rail_firstred_twoway_eol && m_treat_first_red_two_way_signal_as_eol; } }; /** YAPF destination provider base class - used when destination is single tile / multiple trackdirs */ template <class Types> class CYapfDestinationTileT { public: typedef typename Types::Tpf Tpf; ///< the pathfinder class (derived from THIS class) typedef typename Types::NodeList::Titem Node; ///< this will be our node type typedef typename Node::Key Key; ///< key to hash tables protected: TileIndex m_destTile; ///< destination tile TrackdirBits m_destTrackdirs; ///< destination trackdir mask public: /** set the destination tile / more trackdirs */ void SetDestination(TileIndex tile, TrackdirBits trackdirs) { m_destTile = tile; m_destTrackdirs = trackdirs; } protected: /** to access inherited path finder */ Tpf& Yapf() { return *static_cast<Tpf*>(this); } public: /** Called by YAPF to detect if node ends in the desired destination */ FORCEINLINE bool PfDetectDestination(Node& n) { bool bDest = (n.m_key.m_tile == m_destTile) && ((m_destTrackdirs & TrackdirToTrackdirBits(n.GetTrackdir())) != TRACKDIR_BIT_NONE); return bDest; } /** Called by YAPF to calculate cost estimate. Calculates distance to the destination * adds it to the actual cost from origin and stores the sum to the Node::m_estimate */ inline bool PfCalcEstimate(Node& n) { static const int dg_dir_to_x_offs[] = {-1, 0, 1, 0}; static const int dg_dir_to_y_offs[] = {0, 1, 0, -1}; if (PfDetectDestination(n)) { n.m_estimate = n.m_cost; return true; } TileIndex tile = n.GetTile(); DiagDirection exitdir = TrackdirToExitdir(n.GetTrackdir()); int x1 = 2 * TileX(tile) + dg_dir_to_x_offs[(int)exitdir]; int y1 = 2 * TileY(tile) + dg_dir_to_y_offs[(int)exitdir]; int x2 = 2 * TileX(m_destTile); int y2 = 2 * TileY(m_destTile); int dx = abs(x1 - x2); int dy = abs(y1 - y2); int dmin = min(dx, dy); int dxy = abs(dx - dy); int d = dmin * YAPF_TILE_CORNER_LENGTH + (dxy - 1) * (YAPF_TILE_LENGTH / 2); n.m_estimate = n.m_cost + d; assert(n.m_estimate >= n.m_parent->m_estimate); return true; } }; /** YAPF template that uses Ttypes template argument to determine all YAPF * components (base classes) from which the actual YAPF is composed. * For example classes consult: CYapfRail_TypesT template and its instantiations: * CYapfRail1, CYapfRail2, CYapfRail3, CYapfAnyDepotRail1, CYapfAnyDepotRail2, CYapfAnyDepotRail3 */ template <class Ttypes> class CYapfT : public Ttypes::PfBase ///< Instance of CYapfBaseT - main YAPF loop and support base class , public Ttypes::PfCost ///< Cost calculation provider base class , public Ttypes::PfCache ///< Segment cost cache provider , public Ttypes::PfOrigin ///< Origin (tile or two-tile origin) , public Ttypes::PfDestination ///< Destination detector and distance (estimate) calculation provider , public Ttypes::PfFollow ///< Node follower (stepping provider) { }; #endif /* YAPF_COMMON_HPP */
oshepherd/openttd-progsigs
src/pathfinder/yapf/yapf_common.hpp
C++
gpl-2.0
7,218
function updateLabel() { var form = $('contentForm'); var preset_ddm = form.elements['preset']; var presetIndex = preset_ddm[preset_ddm.selectedIndex].value; if ( labels[presetIndex] ) { form.newLabel.value = labels[presetIndex]; } else { form.newLabel.value = ''; } } window.addEvent('domready', updateLabel);
pliablepixels/ZoneMinder
web/skins/classic/views/js/controlpreset.js
JavaScript
gpl-2.0
332
import fill import array a = array.array('I') a.append(1) a.append(1) a.append(3) a.append(2) a.append(2) a.append(2) a.append(2) a.append(2) a.append(2) a.append(2) a.append(2) a.append(2) print "before", a b = fill.fill(a, 2, 2, 3, 3, 4278190080) print "after", b print "after 2", array.array('I', b)
samdroid-apps/paint-activity
test_fill.py
Python
gpl-2.0
304
/* Copyright_License { Top Hat Soaring Glide Computer - http://www.tophatsoaring.org/ Copyright (C) 2000-2016 The Top Hat Soaring Project A detailed list of copyright holders can be found in the file "AUTHORS". 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. } */ #ifndef XCSOAR_DEVICE_DECLARATION_HPP #define XCSOAR_DEVICE_DECLARATION_HPP #include "Geo/GeoPoint.hpp" #include "Engine/Waypoint/Waypoint.hpp" #include "Util/StaticString.hxx" #include "Compiler.h" #include <vector> #include <tchar.h> struct LoggerSettings; struct Plane; class OrderedTask; class OrderedTaskPoint; struct Declaration { struct TurnPoint { enum Shape { CYLINDER, SECTOR, LINE, DAEC_KEYHOLE }; Waypoint waypoint; Shape shape; unsigned radius; TurnPoint(const Waypoint &_waypoint) :waypoint(_waypoint), shape(CYLINDER), radius(1500) {} TurnPoint(const OrderedTaskPoint &tp); }; StaticString<64> pilot_name; StaticString<32> aircraft_type; StaticString<32> aircraft_registration; StaticString<8> competition_id; std::vector<TurnPoint> turnpoints; Declaration(const LoggerSettings &logger_settings, const Plane &plane, const OrderedTask* task); void Append(const Waypoint &waypoint) { turnpoints.push_back(waypoint); } const Waypoint &GetWaypoint(unsigned i) const { return turnpoints[i].waypoint; } const Waypoint &GetFirstWaypoint() const { return turnpoints.front().waypoint; } const Waypoint &GetLastWaypoint() const { return turnpoints.back().waypoint; } gcc_pure const TCHAR *GetName(const unsigned i) const { return turnpoints[i].waypoint.name.c_str(); } const GeoPoint &GetLocation(const unsigned i) const { return turnpoints[i].waypoint.location; } gcc_pure unsigned Size() const { return turnpoints.size(); } }; #endif
rdunning0823/tophat
src/Device/Declaration.hpp
C++
gpl-2.0
2,530
jQuery(function($) { //Get Level 2 Category $('#level1').on("change", ":checkbox", function () { $("#imageloader").show(); if (this.checked) { var parentCat=this.value; // call ajax add_action declared in functions.php $.ajax({ url: "/wp-admin/admin-ajax.php", type:'POST', data:'action=home_category_select_action&parent_cat_ID=' + parentCat, success:function(results) { $("#level2help").hide(); $("#imageloader").hide(); $(".lev1.cat-col").removeClass('dsbl'); //Append all child element in level 2 $("#level2").append(results); } }); } else { //Remove all level 2 element if unchecked $("#imageloader").hide(); $("#getallcat"+this.value).remove(); } }); //Get Level 3 Category $('#level2').on("change", ":checkbox", function () { $("#imageloader2").show(); if (this.checked) { var parentCat=this.value; var parentvalue = $('#parent_id'+parentCat).val(); // call ajax $.ajax({ url: "/wp-admin/admin-ajax.php", type:'POST', data:'action=home_category_select_action&parent_cat_ID=' + parentCat, success:function(results) { $("#level3help").hide(); $(".lev2.cat-col").removeClass('dsbl'); $("#imageloader2").hide(); //Append all child element in level 3 $("#level3").append(results); //Disable parent category $("#level1 input[value='"+parentvalue+"']").prop("disabled", true); // removeChild.push(parentCat); } }); } else { $("#imageloader2").hide(); var parentvalue = $('#parent_id'+this.value).val(); var checkcheckbox=$('#getallcat'+parentvalue+' #parent_cat2').is(':checked'); //check if any child category is checked if(checkcheckbox==false) { //Enable the parent checkbox if unchecked all child element $("#level1 input[value='"+parentvalue+"']").prop("disabled", false); } //Remove all level 3 element if unchecked $("#getallcat"+this.value).remove(); } }); //Load Profile based on tags var list = new Array(); var $container = $('#getTagProfiles'); var $checkboxes = $('#levelContainer input.cb'); $('#levelContainer').on("change", ":checkbox", function () { if (this.checked) { var filterclass=".isoShow"; list.push(this.value); $("#getAllCatId").val(list); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $.post("/wp-admin/admin-ajax.php", 'action=home_tag_select_action&All_cat_ID=' + list+'&listlength='+list.length, function(response) { $(".firstsearch").remove(); $("#contentSection").remove(); $container.html(response); if(!$container.hasClass('isotope')){ $container.isotope({ filter: filterclass }); } else { $container.isotope('reloadItems'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $container.isotope({ filter: filterclass }); } }); } else //If unchecked { var filterclass=".isoShow"; list.splice( $.inArray(this.value,list) ,1 ); $("#getAllCatId").val(list); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $.post("/wp-admin/admin-ajax.php", 'action=home_tag_select_action&All_cat_ID=' + list+'&listlength='+list.length, function(response) { $(".firstsearch").remove(); $("#contentSection").remove(); $container.html(response); if(!$container.hasClass('isotope')){ $container.isotope({ filter: filterclass }); } else { $container.isotope('reloadItems'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $container.isotope({ filter: filterclass }); } }); } }); //Load more $('.more_button').live("click",function() { //var $container2 = $('#getTagProfiles .profile-sec'); var getId = $(this).attr("id"); var getCat= $("#getAllCatId").val(); var filterclass=".isoShow"; if(getId) { $("#load_more_"+getId).html('<img src="/wp-content/themes/marsaec/img/load_img.gif" style="padding:10px 0 0 100px;"/>'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $.post("/wp-admin/admin-ajax.php", 'action=get_loadmore_profile&getLastContentId='+getId+'&getParentId='+getCat+'&listlength='+getCat.length, function(response) { $container.append(response); if(!$container.hasClass('isotope')){ $("#load_more_"+getId).remove(); $container.isotope({ filter: filterclass }); } else { $("#load_more_"+getId).remove(); $container.isotope('reloadItems'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $container.isotope({ filter: filterclass }); } }); // $.ajax({ // type: "POST", // url: "/wp-admin/admin-ajax.php", // data:'action=get_loadmore_profile&getLastContentId='+getId+'&getParentId='+getCat+'&listlength='+getCat.length, // success: function(html){ // $container2.append(html); // $("#load_more_"+getId).remove(); // } // }); } return false; }); });
moveable-dev1/rep1
wp-content/themes/marsaec/js/toggle.js
JavaScript
gpl-2.0
7,013
//===-- tsan_platform_mac.cpp ---------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer (TSan), a race detector. // // Mac-specific code. //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_MAC #include "sanitizer_common/sanitizer_atomic.h" #include "sanitizer_common/sanitizer_common.h" #include "sanitizer_common/sanitizer_libc.h" #include "sanitizer_common/sanitizer_posix.h" #include "sanitizer_common/sanitizer_procmaps.h" #include "sanitizer_common/sanitizer_ptrauth.h" #include "sanitizer_common/sanitizer_stackdepot.h" #include "tsan_platform.h" #include "tsan_rtl.h" #include "tsan_flags.h" #include <mach/mach.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <sys/mman.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/resource.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include <sched.h> namespace __tsan { #if !SANITIZER_GO static void *SignalSafeGetOrAllocate(uptr *dst, uptr size) { atomic_uintptr_t *a = (atomic_uintptr_t *)dst; void *val = (void *)atomic_load_relaxed(a); atomic_signal_fence(memory_order_acquire); // Turns the previous load into // acquire wrt signals. if (UNLIKELY(val == nullptr)) { val = (void *)internal_mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); CHECK(val); void *cmp = nullptr; if (!atomic_compare_exchange_strong(a, (uintptr_t *)&cmp, (uintptr_t)val, memory_order_acq_rel)) { internal_munmap(val, size); val = cmp; } } return val; } // On OS X, accessing TLVs via __thread or manually by using pthread_key_* is // problematic, because there are several places where interceptors are called // when TLVs are not accessible (early process startup, thread cleanup, ...). // The following provides a "poor man's TLV" implementation, where we use the // shadow memory of the pointer returned by pthread_self() to store a pointer to // the ThreadState object. The main thread's ThreadState is stored separately // in a static variable, because we need to access it even before the // shadow memory is set up. static uptr main_thread_identity = 0; ALIGNED(64) static char main_thread_state[sizeof(ThreadState)]; static ThreadState *main_thread_state_loc = (ThreadState *)main_thread_state; // We cannot use pthread_self() before libpthread has been initialized. Our // current heuristic for guarding this is checking `main_thread_identity` which // is only assigned in `__tsan::InitializePlatform`. static ThreadState **cur_thread_location() { if (main_thread_identity == 0) return &main_thread_state_loc; uptr thread_identity = (uptr)pthread_self(); if (thread_identity == main_thread_identity) return &main_thread_state_loc; return (ThreadState **)MemToShadow(thread_identity); } ThreadState *cur_thread() { return (ThreadState *)SignalSafeGetOrAllocate( (uptr *)cur_thread_location(), sizeof(ThreadState)); } void set_cur_thread(ThreadState *thr) { *cur_thread_location() = thr; } // TODO(kuba.brecka): This is not async-signal-safe. In particular, we call // munmap first and then clear `fake_tls`; if we receive a signal in between, // handler will try to access the unmapped ThreadState. void cur_thread_finalize() { ThreadState **thr_state_loc = cur_thread_location(); if (thr_state_loc == &main_thread_state_loc) { // Calling dispatch_main() or xpc_main() actually invokes pthread_exit to // exit the main thread. Let's keep the main thread's ThreadState. return; } internal_munmap(*thr_state_loc, sizeof(ThreadState)); *thr_state_loc = nullptr; } #endif void FlushShadowMemory() { } static void RegionMemUsage(uptr start, uptr end, uptr *res, uptr *dirty) { vm_address_t address = start; vm_address_t end_address = end; uptr resident_pages = 0; uptr dirty_pages = 0; while (address < end_address) { vm_size_t vm_region_size; mach_msg_type_number_t count = VM_REGION_EXTENDED_INFO_COUNT; vm_region_extended_info_data_t vm_region_info; mach_port_t object_name; kern_return_t ret = vm_region_64( mach_task_self(), &address, &vm_region_size, VM_REGION_EXTENDED_INFO, (vm_region_info_t)&vm_region_info, &count, &object_name); if (ret != KERN_SUCCESS) break; resident_pages += vm_region_info.pages_resident; dirty_pages += vm_region_info.pages_dirtied; address += vm_region_size; } *res = resident_pages * GetPageSizeCached(); *dirty = dirty_pages * GetPageSizeCached(); } void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) { uptr shadow_res, shadow_dirty; uptr meta_res, meta_dirty; uptr trace_res, trace_dirty; RegionMemUsage(ShadowBeg(), ShadowEnd(), &shadow_res, &shadow_dirty); RegionMemUsage(MetaShadowBeg(), MetaShadowEnd(), &meta_res, &meta_dirty); RegionMemUsage(TraceMemBeg(), TraceMemEnd(), &trace_res, &trace_dirty); #if !SANITIZER_GO uptr low_res, low_dirty; uptr high_res, high_dirty; uptr heap_res, heap_dirty; RegionMemUsage(LoAppMemBeg(), LoAppMemEnd(), &low_res, &low_dirty); RegionMemUsage(HiAppMemBeg(), HiAppMemEnd(), &high_res, &high_dirty); RegionMemUsage(HeapMemBeg(), HeapMemEnd(), &heap_res, &heap_dirty); #else // !SANITIZER_GO uptr app_res, app_dirty; RegionMemUsage(AppMemBeg(), AppMemEnd(), &app_res, &app_dirty); #endif StackDepotStats *stacks = StackDepotGetStats(); internal_snprintf(buf, buf_size, "shadow (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" "meta (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" "traces (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" #if !SANITIZER_GO "low app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" "high app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" "heap (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" #else // !SANITIZER_GO "app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" #endif "stacks: %zd unique IDs, %zd kB allocated\n" "threads: %zd total, %zd live\n" "------------------------------\n", ShadowBeg(), ShadowEnd(), shadow_res / 1024, shadow_dirty / 1024, MetaShadowBeg(), MetaShadowEnd(), meta_res / 1024, meta_dirty / 1024, TraceMemBeg(), TraceMemEnd(), trace_res / 1024, trace_dirty / 1024, #if !SANITIZER_GO LoAppMemBeg(), LoAppMemEnd(), low_res / 1024, low_dirty / 1024, HiAppMemBeg(), HiAppMemEnd(), high_res / 1024, high_dirty / 1024, HeapMemBeg(), HeapMemEnd(), heap_res / 1024, heap_dirty / 1024, #else // !SANITIZER_GO AppMemBeg(), AppMemEnd(), app_res / 1024, app_dirty / 1024, #endif stacks->n_uniq_ids, stacks->allocated / 1024, nthread, nlive); } #if !SANITIZER_GO void InitializeShadowMemoryPlatform() { } // On OS X, GCD worker threads are created without a call to pthread_create. We // need to properly register these threads with ThreadCreate and ThreadStart. // These threads don't have a parent thread, as they are created "spuriously". // We're using a libpthread API that notifies us about a newly created thread. // The `thread == pthread_self()` check indicates this is actually a worker // thread. If it's just a regular thread, this hook is called on the parent // thread. typedef void (*pthread_introspection_hook_t)(unsigned int event, pthread_t thread, void *addr, size_t size); extern "C" pthread_introspection_hook_t pthread_introspection_hook_install( pthread_introspection_hook_t hook); static const uptr PTHREAD_INTROSPECTION_THREAD_CREATE = 1; static const uptr PTHREAD_INTROSPECTION_THREAD_TERMINATE = 3; static pthread_introspection_hook_t prev_pthread_introspection_hook; static void my_pthread_introspection_hook(unsigned int event, pthread_t thread, void *addr, size_t size) { if (event == PTHREAD_INTROSPECTION_THREAD_CREATE) { if (thread == pthread_self()) { // The current thread is a newly created GCD worker thread. ThreadState *thr = cur_thread(); Processor *proc = ProcCreate(); ProcWire(proc, thr); ThreadState *parent_thread_state = nullptr; // No parent. int tid = ThreadCreate(parent_thread_state, 0, (uptr)thread, true); CHECK_NE(tid, 0); ThreadStart(thr, tid, GetTid(), ThreadType::Worker); } } else if (event == PTHREAD_INTROSPECTION_THREAD_TERMINATE) { if (thread == pthread_self()) { ThreadState *thr = cur_thread(); if (thr->tctx) { DestroyThreadState(); } } } if (prev_pthread_introspection_hook != nullptr) prev_pthread_introspection_hook(event, thread, addr, size); } #endif void InitializePlatformEarly() { #if !SANITIZER_GO && defined(__aarch64__) uptr max_vm = GetMaxUserVirtualAddress() + 1; if (max_vm != Mapping::kHiAppMemEnd) { Printf("ThreadSanitizer: unsupported vm address limit %p, expected %p.\n", max_vm, Mapping::kHiAppMemEnd); Die(); } #endif } static uptr longjmp_xor_key = 0; void InitializePlatform() { DisableCoreDumperIfNecessary(); #if !SANITIZER_GO CheckAndProtect(); CHECK_EQ(main_thread_identity, 0); main_thread_identity = (uptr)pthread_self(); prev_pthread_introspection_hook = pthread_introspection_hook_install(&my_pthread_introspection_hook); #endif if (GetMacosAlignedVersion() >= MacosVersion(10, 14)) { // Libsystem currently uses a process-global key; this might change. const unsigned kTLSLongjmpXorKeySlot = 0x7; longjmp_xor_key = (uptr)pthread_getspecific(kTLSLongjmpXorKeySlot); } } #ifdef __aarch64__ # define LONG_JMP_SP_ENV_SLOT \ ((GetMacosAlignedVersion() >= MacosVersion(10, 14)) ? 12 : 13) #else # define LONG_JMP_SP_ENV_SLOT 2 #endif uptr ExtractLongJmpSp(uptr *env) { uptr mangled_sp = env[LONG_JMP_SP_ENV_SLOT]; uptr sp = mangled_sp ^ longjmp_xor_key; sp = (uptr)ptrauth_auth_data((void *)sp, ptrauth_key_asdb, ptrauth_string_discriminator("sp")); return sp; } #if !SANITIZER_GO void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) { // The pointer to the ThreadState object is stored in the shadow memory // of the tls. uptr tls_end = tls_addr + tls_size; uptr thread_identity = (uptr)pthread_self(); if (thread_identity == main_thread_identity) { MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr, tls_size); } else { uptr thr_state_start = thread_identity; uptr thr_state_end = thr_state_start + sizeof(uptr); CHECK_GE(thr_state_start, tls_addr); CHECK_LE(thr_state_start, tls_addr + tls_size); CHECK_GE(thr_state_end, tls_addr); CHECK_LE(thr_state_end, tls_addr + tls_size); MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr, thr_state_start - tls_addr); MemoryRangeImitateWrite(thr, /*pc=*/2, thr_state_end, tls_end - thr_state_end); } } #endif #if !SANITIZER_GO // Note: this function runs with async signals enabled, // so it must not touch any tsan state. int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m, void *abstime), void *c, void *m, void *abstime, void(*cleanup)(void *arg), void *arg) { // pthread_cleanup_push/pop are hardcore macros mess. // We can't intercept nor call them w/o including pthread.h. int res; pthread_cleanup_push(cleanup, arg); res = fn(c, m, abstime); pthread_cleanup_pop(0); return res; } #endif } // namespace __tsan #endif // SANITIZER_MAC
Gurgel100/gcc
libsanitizer/tsan/tsan_platform_mac.cpp
C++
gpl-2.0
12,112
(function ($) { 'use strict'; function Ninja() { this.keys = { arrowDown: 40, arrowLeft: 37, arrowRight: 39, arrowUp: 38, enter: 13, escape: 27, tab: 9 }; this.version = '0.0.0development'; } Ninja.prototype.log = function (message) { if (console && 'log' in console) { console.log('Ninja: ' + message); } }; Ninja.prototype.warn = function (message) { if (console && 'warn' in console) { console.warn('Ninja: ' + message); } }; Ninja.prototype.error = function (message) { var fullMessage = 'Ninja: ' + message; if (console && 'error' in console) { console.error(fullMessage); } throw fullMessage; }; Ninja.prototype.key = function (code, names) { var keys = this.keys, codes = $.map(names, function (name) { return keys[name]; }); return $.inArray(code, codes) > -1; }; $.Ninja = function (element, options) { if ($.isPlainObject(element)) { this.$element = $('<span>'); this.options = element; } else { this.$element = $(element); this.options = options || {}; } }; $.Ninja.prototype.deselect = function () { if (this.$element.hasClass('nui-slc') && !this.$element.hasClass('nui-dsb')) { this.$element.trigger('deselect.ninja'); } }; $.Ninja.prototype.disable = function () { this.$element.addClass('nui-dsb').trigger('disable.ninja'); }; $.Ninja.prototype.enable = function () { this.$element.removeClass('nui-dsb').trigger('enable.ninja'); }; $.Ninja.prototype.select = function () { if (!this.$element.hasClass('nui-dsb')) { this.$element.trigger('select.ninja'); } }; $.ninja = new Ninja(); $.fn.ninja = function (component, options) { return this.each(function () { if (!$.data(this, 'ninja.' + component)) { $.data(this, 'ninja.' + component); $.ninja[component](this, options); } }); }; }(jQuery));
Bremaweb/streber
js/ninja.js
JavaScript
gpl-2.0
2,022
define([ 'container/BasicContainer', 'text!./CascadeContainer.html', 'core/functions/ComponentFactory', 'jquery', 'underscore' ], function (BasicContainer, template, ComponentFactory, $, _) { var CascadeContainer = BasicContainer.extend({ events: { "click .btn-prev": "clickPrev", "click .btn-next": "clickNext" }, clickPrev: function () { if (this._currentindex > 0) { this._currentindex--; var root = this._containerRoot; var li = root.find('.form-bootstrapWizard>li'); li.removeClass('active'); li.eq(this._currentindex).addClass('active'); root.find('.form-pane'); var pane = root.find('.form-pane'); pane.hide(); pane.eq(this._currentindex).show(); } }, clickNext: function (state) { if (this._currentindex <= this._renderindex - 1) { this._currentindex++; var root = this._containerRoot; var li = root.find('.form-bootstrapWizard>li'); li.removeClass('active'); li.eq(this._currentindex - 1).addClass(state || 'success'); li.eq(this._currentindex).addClass('active'); var pane = root.find('.form-pane'); pane.hide(); pane.eq(this._currentindex).show(); } }, addComponent: function (options) { this._components.push({ name: options.name, description: options.description, constructor: options.constructor, factory: options.factory || ComponentFactory, options: options.options, extend: options.extend }); }, getContainer: function (index, options) { var node = '<div id="' + index + '" class="form-pane" ' + (this._renderindex == 0 ? '' : 'style="display:none"') + ' data-value="step' + (this._renderindex + 1) + '" ></div>'; return $(node); }, addStep: function (name, index, text) { var root = this._containerRoot; root.find('.form-bootstrapWizard').append('<li ' + (index == 1 ? 'class="active"' : '') + ' data-target="step1">' + '<span class="step">' + index + '</span>' + '<span class="title">' + name + '</span>' + (text ? '<span class="text">' + text + '</span>' : '') + '</li>'); }, renderComponents: function (options) { this._currentindex = 0; this._renderindex = 0; var self = this; var containerRoot; if (this.options.root) { var tmp = this._containerRoot.find(this.options.root); containerRoot = tmp.length ? tmp : $(this._containerRoot.get(0)); } else { containerRoot = $(this._containerRoot.get(0)); } _.forEach(this._components, function (item) { var name = item.name; if (typeof self._componentStack[name] == 'undefined') { self._componentStack[name] = self.createComponent(item, options || {}); } var component = self._componentStack[name]; var el = self.getContainer(name, options || {}).appendTo(containerRoot).get(0); component.setElement(el); component.beforeShow(); component.render(options || {}); self.addStep(name, self._renderindex + 1, item.description); self._renderindex++; }); this.addStep('Complete', this._renderindex + 1); containerRoot.append('' + '<div id="Complete" class="form-pane" style="display:none" data-value="step' + (this._renderindex + 1) + '"><br/>' + '<h1 class="text-center text-success"><strong><i class="fa fa-check fa-lg"></i> Complete</strong></h1>' + '<h4 class="text-center">Click next to finish</h4>' + '<br/><br/></div>'); } }); CascadeContainer.create = function (options) { var ret = new CascadeContainer(); options.template = template; options.root = '.form-content'; if (ret.initialize(options) == false) { return false; } return ret; }; return CascadeContainer; });
MaxLeap/MyBaaS
webroot/javascript/core/container/CascadeContainer.js
JavaScript
gpl-2.0
4,532
/* -*- OpenSAF -*- * * (C) Copyright 2008 The OpenSAF 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. This file and program are licensed * under the GNU Lesser General Public License Version 2.1, February 1999. * The complete license can be accessed from the following location: * http://opensource.org/licenses/lgpl-license.php * See the Copying file included with the OpenSAF distribution for full * licensing terms. * * Author(s): Ericsson AB * */ /** * This object handles information about NTF clients. * */ #include "NtfClient.hh" #include "logtrace.h" #include "NtfAdmin.hh" /** * This is the constructor. * * Client object is created, initial variables are set. * * @param clientId Node-wide unique id of this client. * @param mds_dest MDS communication pointer to this client. * * @param locatedOnThisNode * Flag that is set if the client is located on this node. */ NtfClient::NtfClient(unsigned int clientId, MDS_DEST mds_dest):readerId_(0),mdsDest_(mds_dest) { clientId_ = clientId; mdsDest_ = mds_dest; TRACE_3("NtfClient::NtfClient NtfClient %u created mdest: %" PRIu64, clientId_, mdsDest_); } /** * This is the destructor. * * It is called when a client is removed, i.e. a client finalized its * connection. * * Subscription objects belonging to this client are deleted. */ NtfClient::~NtfClient() { // delete all subscriptions SubscriptionMap::iterator pos; for (pos = subscriptionMap.begin(); pos != subscriptionMap.end(); pos++) { NtfSubscription* subscription = pos->second; delete subscription; } // delete all readers ReaderMapT::iterator rpos; for (rpos = readerMap.begin(); rpos != readerMap.end(); rpos++) { unsigned int readerId = 0; NtfReader* reader = rpos->second; if (reader != NULL) { readerId = reader->getId(); TRACE_3("~Client delete reader Id %u ", readerId); delete reader; } } TRACE_3("NtfClient::~NtfClient NtfClient %u destroyed, mdest %" PRIu64, clientId_, mdsDest_); } /** * This method is called to get the id of this client. * * @return Node-wide unique id of this client. */ unsigned int NtfClient::getClientId() const { return clientId_; } MDS_DEST NtfClient::getMdsDest() const { return mdsDest_; } /** * This method is called when the client made a new subscription. * * The pointer to the subscription object is stored if it did not * exist. If the client is located on this node, a confirmation * for the subscription is sent. * * @param subscription * Pointer to the subscription object. */ void NtfClient::subscriptionAdded(NtfSubscription* subscription, MDS_SYNC_SND_CTXT *mdsCtxt) { // check if subscription already exists SubscriptionMap::iterator pos; pos = subscriptionMap.find(subscription->getSubscriptionId()); if (pos != subscriptionMap.end()) { // subscription found TRACE_3("NtfClient::subscriptionAdded subscription %u already exists" ", client %u", subscription->getSubscriptionId(), clientId_); delete subscription; } else { // store new subscription in subscriptionMap subscriptionMap[subscription->getSubscriptionId()] = subscription; TRACE_3("NtfClient::subscriptionAdded subscription %u added," " client %u, subscriptionMap size is %u", subscription->getSubscriptionId(), clientId_, (unsigned int)subscriptionMap.size()); if (activeController()) { sendSubscriptionUpdate(subscription->getSubscriptionInfo()); confirmNtfSubscribe(subscription->getSubscriptionId(), mdsCtxt); } } } /** * This method is called when the client received a notification. * * If the notification is send from this client, a confirmation * for the notification is sent. * * The client scans through its subscriptions and if it finds a * matching one, it stores the id of the matching subscription in * the notification object. * * @param clientId Node-wide unique id of the client who sent the notification. * @param notification * Pointer to the notification object. */ void NtfClient::notificationReceived(unsigned int clientId, NtfSmartPtr& notification, MDS_SYNC_SND_CTXT *mdsCtxt) { TRACE_ENTER2("%u %u", clientId_, clientId); // send acknowledgement if (clientId_ == clientId) { // this is the client who sent the notification if (activeController()) { confirmNtfNotification(notification->getNotificationId(), mdsCtxt, mdsDest_); if (notification->loggedOk()) { sendLoggedConfirmUpdate(notification->getNotificationId()); } else { notification->loggFromCallback_= true; } } } // scan through all subscriptions SubscriptionMap::iterator pos; for (pos = subscriptionMap.begin(); pos != subscriptionMap.end(); pos++) { NtfSubscription* subscription = pos->second; if (subscription->checkSubscription(notification)) { // notification matches the subscription TRACE_2("NtfClient::notificationReceived notification %llu matches" " subscription %d, client %u", notification->getNotificationId(), subscription->getSubscriptionId(), clientId_); // first store subscription data in notifiaction object for // tracking purposes notification->storeMatchingSubscription(clientId_, subscription->getSubscriptionId()); // if active, send out the notification if (activeController()) { subscription->sendNotification(notification, this); } } else { TRACE_2("NtfClient::notificationReceived notification %llu does not" " match subscription %u, client %u", notification->getNotificationId(), subscription->getSubscriptionId(), clientId_); } } TRACE_LEAVE(); } /** * This method is called if the client made an unsubscribe. * * The subscription object is deleted. If the client is located on * this node, a confirmation is sent. * * @param subscriptionId * Client-wide unique id of the subscription that was removed. */ void NtfClient::subscriptionRemoved(SaNtfSubscriptionIdT subscriptionId, MDS_SYNC_SND_CTXT *mdsCtxt) { // find subscription SubscriptionMap::iterator pos; pos = subscriptionMap.find(subscriptionId); if (pos != subscriptionMap.end()) { // subscription found NtfSubscription* subscription = pos->second; delete subscription; // remove subscription from subscription map subscriptionMap.erase(pos); } else { LOG_ER( "NtfClient::subscriptionRemoved subscription" " %u not found", subscriptionId); } if (activeController()) { // client is located on this node sendUnsubscribeUpdate(clientId_, subscriptionId); confirmNtfUnsubscribe(subscriptionId, mdsCtxt); } } void NtfClient::discardedAdd(SaNtfSubscriptionIdT subscriptionId, SaNtfIdentifierT notificationId) { SubscriptionMap::iterator pos; pos = subscriptionMap.find(subscriptionId); if (pos != subscriptionMap.end()) { pos->second->discardedAdd(notificationId); } else { LOG_ER( "discardedAdd subscription %u not found", subscriptionId); } } void NtfClient::discardedClear(SaNtfSubscriptionIdT subscriptionId) { SubscriptionMap::iterator pos; pos = subscriptionMap.find(subscriptionId); if (pos != subscriptionMap.end()) { pos->second->discardedClear(); } else { LOG_ER( "discardedClear subscription %u not found", subscriptionId); } } /** * This method is called when information about this client is * requested by another node. * * The client scans through its subscriptions and sends them out one by one. */ void NtfClient::syncRequest(NCS_UBAID *uba) { // scan through all subscriptions sendNoOfSubscriptions(subscriptionMap.size(), uba); SubscriptionMap::iterator pos; for (pos = subscriptionMap.begin(); pos != subscriptionMap.end(); pos++) { NtfSubscription* subscription = pos->second; TRACE_3("NtfClient::syncRequest sending info about subscription %u for " "client %u", subscription->getSubscriptionId(), clientId_); subscription->syncRequest(uba); } } void NtfClient::sendNotConfirmedNotification(NtfSmartPtr notification, SaNtfSubscriptionIdT subscriptionId) { TRACE_ENTER(); // if active, send out the notification if (activeController()) { SubscriptionMap::iterator pos; pos = subscriptionMap.find(subscriptionId); if (pos != subscriptionMap.end()) { pos->second->sendNotification(notification, this); } else { TRACE_3("subscription: %u client: %u not found", subscriptionId, getClientId()); } } TRACE_LEAVE(); } /** * This method is called when a confirmation for the subscription * should be sent to a client. * * @param subscriptionId Client-wide unique id of the subscription that should * be confirmed. */ void NtfClient::confirmNtfSubscribe(SaNtfSubscriptionIdT subscriptionId, MDS_SYNC_SND_CTXT *mds_ctxt) { TRACE_2("NtfClient::confirmNtfSubscribe subscribe_res_lib called, " "client %u, subscription %u", clientId_, subscriptionId); subscribe_res_lib( SA_AIS_OK, subscriptionId, mdsDest_, mds_ctxt); } /** * This method is called when a confirmation for the unsubscription * should be sent to a client. * * @param subscriptionId Client-wide unique id of the subscription that shoul be * confirmed. */ void NtfClient::confirmNtfUnsubscribe(SaNtfSubscriptionIdT subscriptionId, MDS_SYNC_SND_CTXT *mdsCtxt) { TRACE_2("NtfClient::confirmNtfUnsubscribe unsubscribe_res_lib called," " client %u, subscription %u", clientId_, subscriptionId); unsubscribe_res_lib(SA_AIS_OK, subscriptionId, mdsDest_, mdsCtxt); } /** * This method is called when a confirmation for the notification * should be sent to a client. * * @param notificationId * Cluster-wide unique id of the notification that should be confirmed. */ void NtfClient::confirmNtfNotification(SaNtfIdentifierT notificationId, MDS_SYNC_SND_CTXT *mdsCtxt, MDS_DEST mdsDest) { notfication_result_lib( SA_AIS_OK, notificationId, mdsCtxt, mdsDest); } void NtfClient::newReaderResponse(SaAisErrorT* error, unsigned int readerId, MDS_SYNC_SND_CTXT *mdsCtxt) { new_reader_res_lib( *error, readerId, mdsDest_, mdsCtxt); } void NtfClient::readNextResponse(SaAisErrorT* error, NtfSmartPtr& notification, MDS_SYNC_SND_CTXT *mdsCtxt) { TRACE_ENTER(); if (*error == SA_AIS_OK) { read_next_res_lib(*error, notification->sendNotInfo_, mdsDest_, mdsCtxt); } else { read_next_res_lib(*error, NULL, mdsDest_, mdsCtxt); } TRACE_ENTER(); } void NtfClient::deleteReaderResponse(SaAisErrorT* error, MDS_SYNC_SND_CTXT *mdsCtxt) { delete_reader_res_lib( *error, mdsDest_, mdsCtxt); } void NtfClient::newReader(SaNtfSearchCriteriaT searchCriteria, ntfsv_filter_ptrs_t *f_rec, MDS_SYNC_SND_CTXT *mdsCtxt) { SaAisErrorT error = SA_AIS_OK; readerId_++; NtfReader* reader; if (f_rec) { reader = new NtfReader(NtfAdmin::theNtfAdmin->logger, readerId_, searchCriteria, f_rec); } else { /*old API no filtering */ reader = new NtfReader(NtfAdmin::theNtfAdmin->logger, readerId_); } readerMap[readerId_] = reader; newReaderResponse(&error,readerId_, mdsCtxt); } void NtfClient::readNext(unsigned int readerId, SaNtfSearchDirectionT searchDirection, MDS_SYNC_SND_CTXT *mdsCtxt) { TRACE_ENTER(); TRACE_6("readerId %u", readerId); // check if reader already exists SaAisErrorT error = SA_AIS_ERR_NOT_EXIST; ReaderMapT::iterator pos; pos = readerMap.find(readerId); if (pos != readerMap.end()) { // reader found TRACE_3("NtfClient::readNext readerId %u FOUND!", readerId); NtfReader* reader = pos->second; NtfSmartPtr notif(reader->next(searchDirection, &error)); readNextResponse(&error, notif, mdsCtxt); TRACE_LEAVE(); return; } else { NtfSmartPtr notif; // reader not found TRACE_3("NtfClient::readNext readerId %u not found", readerId); error = SA_AIS_ERR_BAD_HANDLE; readNextResponse(&error, notif, mdsCtxt); TRACE_LEAVE(); } } void NtfClient::deleteReader(unsigned int readerId, MDS_SYNC_SND_CTXT *mdsCtxt) { SaAisErrorT error = SA_AIS_ERR_NOT_EXIST; ReaderMapT::iterator pos; pos = readerMap.find(readerId); if (pos != readerMap.end()) { // reader found TRACE_3("NtfClient::deleteReader readerId %u ", readerId); NtfReader* reader = pos->second; error = SA_AIS_OK; delete reader; readerMap.erase(pos); } else { // reader not found TRACE_3("NtfClient::readNext readerId %u not found", readerId); } deleteReaderResponse(&error, mdsCtxt); } void NtfClient::printInfo() { TRACE("Client information"); TRACE(" clientId: %u", clientId_); TRACE(" mdsDest %" PRIu64, mdsDest_); SubscriptionMap::iterator pos; for (pos = subscriptionMap.begin(); pos != subscriptionMap.end(); pos++) { NtfSubscription* subscription = pos->second; subscription->printInfo(); } TRACE(" readerId counter: %u", readerId_); ReaderMapT::iterator rpos; for (rpos = readerMap.begin(); rpos != readerMap.end(); rpos++) { unsigned int readerId = 0; NtfReader* reader = rpos->second; if (reader != NULL) { readerId = reader->getId(); TRACE(" Reader Id %u ", readerId); } } }
indonexia2004/opensaf-indo
osaf/services/saf/ntfsv/ntfs/NtfClient.cc
C++
gpl-2.0
15,097
package lk.score.androphsy.exceptions; /** * This exception is thrown when a property cannot be read from the property * file */ public class PropertyNotDefinedException extends Exception { private static final String MESSAGE_PREFIX = "Property not defined!! : "; public PropertyNotDefinedException(String message) { super(MESSAGE_PREFIX + message); } public PropertyNotDefinedException() { } }
swsachith/ANDROPHSY
src/main/java/lk/score/androphsy/exceptions/PropertyNotDefinedException.java
Java
gpl-2.0
409
/* * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the Classpath exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.btrace.core.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * BTrace fields with this annotation are exposed as attributes of the dynamic JMX bean that wraps * the BTrace class. * * @author A. Sundararajan */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Property { // by default, the name of the attribute is same as the name // of the field of the BTrace class. String name() default ""; // description of this attribute String description() default ""; }
jbachorik/btrace
btrace-core/src/main/java/org/openjdk/btrace/core/annotations/Property.java
Java
gpl-2.0
1,873
<?php /** * Kunena Component * @package Kunena.Template.Blue_Eagle * @subpackage User * * @copyright (C) 2008 - 2016 Kunena Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.kunena.org **/ defined ( '_JEXEC' ) or die (); JHtml::_('behavior.calendar'); JHtml::_('behavior.tooltip'); ?> <div id="kprofile-rightcoltop"> <div class="kprofile-rightcol2"> <?php $this->displayTemplateFile('user', 'default', 'social'); ?> </div> <div class="kprofile-rightcol1"> <ul> <li><span class="kicon-profile kicon-profile-location"></span><strong><?php echo JText::_('COM_KUNENA_MYPROFILE_LOCATION'); ?>:</strong> <?php echo $this->locationlink; ?></li> <!-- The gender determines the suffix on the span class- gender-male & gender-female --> <li><span class="kicon-profile kicon-profile-gender-<?php echo $this->genderclass; ?>"></span><strong><?php echo JText::_('COM_KUNENA_MYPROFILE_GENDER'); ?>:</strong> <?php echo $this->gender; ?></li> <li class="bd"><span class="kicon-profile kicon-profile-birthdate"></span><strong><?php echo JText::_('COM_KUNENA_MYPROFILE_BIRTHDATE'); ?>:</strong> <span title="<?php echo KunenaDate::getInstance($this->profile->birthdate)->toKunena('ago', 'GMT'); ?>"><?php echo KunenaDate::getInstance($this->profile->birthdate)->toKunena('date', 'GMT'); ?></span> <!-- <a href="#" title=""><span class="bday-remind"></span></a> --> </li> </ul> </div> </div> <div class="clrline"></div> <div id="kprofile-rightcolbot"> <div class="kprofile-rightcol2"> <?php if ($this->email || !empty($this->profile->websiteurl)): ?> <ul> <?php if ($this->email): ?> <li><span class="kicon-profile kicon-profile-email"></span><?php echo $this->email; ?></li> <?php endif; ?> <?php if (!empty($this->profile->websiteurl)): ?> <?php // FIXME: we need a better way to add http/https ?> <li><span class="kicon-profile kicon-profile-website"></span><a href="<?php echo $this->escape($this->websiteurl); ?>" target="_blank"><?php echo KunenaHtmlParser::parseText(trim($this->profile->websitename) ? $this->profile->websitename : $this->websiteurl); ?></a></li> <?php endif; ?> </ul> <?php endif;?> </div> <div class="kprofile-rightcol1"> <h4><?php echo JText::_('COM_KUNENA_MYPROFILE_SIGNATURE'); ?></h4> <div class="kmsgsignature"><div><?php echo $this->signatureHtml ?></div></div> </div> </div> <div class="clrline"></div> <div id="kprofile-tabs"> <dl class="tabs"> <?php if($this->showUserPosts) : ?> <dt class="open" title="<?php echo JText::_('COM_KUNENA_USERPOSTS'); ?>"><?php echo JText::_('COM_KUNENA_USERPOSTS'); ?></dt> <dd style="display: none;"> <?php $this->displayUserPosts(); ?> </dd> <?php endif; ?> <?php if ($this->showSubscriptions) :?> <dt class="closed" title="<?php echo JText::_('COM_KUNENA_SUBSCRIPTIONS'); ?>"><?php echo JText::_('COM_KUNENA_SUBSCRIPTIONS'); ?></dt> <dd style="display: none;"> <?php $this->displayCategoriesSubscriptions(); ?> <?php $this->displaySubscriptions(); ?> </dd> <?php endif; ?> <?php if ($this->showFavorites) : ?> <dt class="closed" title="<?php echo JText::_('COM_KUNENA_FAVORITES'); ?>"><?php echo JText::_('COM_KUNENA_FAVORITES'); ?></dt> <dd style="display: none;"> <?php $this->displayFavorites(); ?> </dd> <?php endif; ?> <?php if($this->showThankyou) : ?> <dt class="closed" title="<?php echo JText::_('COM_KUNENA_THANK_YOU'); ?>"><?php echo JText::_('COM_KUNENA_THANK_YOU'); ?></dt> <dd style="display: none;"> <?php $this->displayGotThankyou(); ?> <?php $this->displaySaidThankyou(); ?> </dd> <?php endif; ?> <?php if ($this->showUnapprovedPosts): ?> <dt class="open" title="<?php echo JText::_('COM_KUNENA_MESSAGE_ADMINISTRATION'); ?>"><?php echo JText::_('COM_KUNENA_MESSAGE_ADMINISTRATION'); ?></dt> <dd style="display: none;"> <?php $this->displayUnapprovedPosts(); ?> </dd> <?php endif; ?> <?php if ($this->showAttachments): ?> <dt class="closed" title="<?php echo JText::_('COM_KUNENA_MANAGE_ATTACHMENTS'); ?>"><?php echo JText::_('COM_KUNENA_MANAGE_ATTACHMENTS'); ?></dt> <dd style="display: none;"> <?php $this->displayAttachments(); ?> </dd> <?php endif;?> <?php if ($this->showBanManager): ?> <dt class="closed" title="<?php echo JText::_('COM_KUNENA_BAN_BANMANAGER'); ?>"><?php echo JText::_('COM_KUNENA_BAN_BANMANAGER'); ?></dt> <dd style="display: none;"> <?php $this->displayBanManager(); ?> </dd> <?php endif;?> <?php if ($this->showBanHistory):?> <dt class="closed" title="<?php echo JText::_('COM_KUNENA_BAN_BANHISTORY'); ?>"><?php echo JText::_('COM_KUNENA_BAN_BANHISTORY'); ?></dt> <dd style="display: none;"> <?php $this->displayBanHistory(); ?> </dd> <?php endif;?> <?php if ($this->showBanUser) : ?> <dt class="closed" title="<?php echo $this->banInfo->id ? JText::_('COM_KUNENA_BAN_EDIT') : JText::_('COM_KUNENA_BAN_NEW' ); ?>"><?php echo $this->banInfo->id ? JText::_('COM_KUNENA_BAN_EDIT') : JText::_('COM_KUNENA_BAN_NEW' ); ?></dt> <dd style="display: none;"> <?php $this->displayBanUser(); ?> </dd> <?php endif; ?> </dl> </div>
githubupttik/upttik
components/com_kunena/template/blue_eagle/html/user/default_tab.php
PHP
gpl-2.0
5,180
<?php /** * @file * Default theme implementation to display a term. * * Available variables: * - $name: (deprecated) The unsanitized name of the term. Use $term_name * instead. * - $content: An array of items for the content of the term (fields and * description). Use render($content) to print them all, or print a subset * such as render($content['field_example']). Use * hide($content['field_example']) to temporarily suppress the printing of a * given element. * - $term_url: Direct URL of the current term. * - $term_name: Name of the current term. * - $classes: String of classes that can be used to style contextually through * CSS. It can be manipulated through the variable $classes_array from * preprocess functions. The default values can be one or more of the following: * - taxonomy-term: The current template type, i.e., "theming hook". * - vocabulary-[vocabulary-name]: The vocabulary to which the term belongs to. * For example, if the term is a "Tag" it would result in "vocabulary-tag". * * Other variables: * - $term: Full term object. Contains data that may not be safe. * - $view_mode: View mode, e.g. 'full', 'teaser'... * - $page: Flag for the full page state. * - $classes_array: Array of html class attribute values. It is flattened * into a string within the variable $classes. * - $zebra: Outputs either "even" or "odd". Useful for zebra striping in * teaser listings. * - $id: Position of the term. Increments each time it's output. * - $is_front: Flags true when presented in the front page. * - $logged_in: Flags true when the current user is a logged-in member. * - $is_admin: Flags true when the current user is an administrator. * * @see template_preprocess() * @see template_preprocess_taxonomy_term() * @see template_process() * * @ingroup themeable */ ?> <?php $output = ""; //$output .= "<h1>" . $term->tid . "</h1>"; $output .= "<!-- ARTIKEL START -->"; $output .= "<section id=\"taxonomy-term-" . $term->tid . "\" class=\"" . $classes . " aktivitetsside\">"; $output .= "<div class=\"container\">"; // Brødkrummesti $output .= "<div class=\"row\">"; $output .= "<div class=\"grid-two-thirds\">"; $output .= "<p class=\"breadcrumbs\">" . theme('breadcrumb', array('breadcrumb'=>drupal_get_breadcrumb())) . " / " . $term_name . "</p>"; $output .= "</div>"; $output .= "</div>"; $output .= "<div class=\"row second\">"; $output .= "<div class=\"grid-two-thirds\">"; $output .= "<h1>Aktiviteter i kategorien \"" . $term_name . "\"</h1>"; // $output .= "<h1>" . $term_name . "</h1>"; $output .= "</div>"; $output .= "<div class=\"grid-third sociale-medier social-desktop\"></div>"; $output .= "</div>"; $output .= "<div class=\"row\">"; // $output .= "<div class=\"grid-two-thirds\">"; // $output .= "<!-- ARTIKEL TOP START -->"; // $output .= "<div class=\"artikel-top\">"; // $output .= "</div>"; // $output .= "<!-- ARTIKEL TOP SLUT -->"; // $output .= "<h1>Jaaaaaa, det virker!</h1>"; // $output .= render($content); // DEL PÅ SOCIALE MEDIER // include_once drupal_get_path('theme', 'ishoj') . '/includes/del-paa-sociale-medier.php'; // SENEST OPDATERET // $output .= "<!-- SENEST OPDATERET START -->"; // $output .= "<p class=\"last-updated\">Senest opdateret " . format_date($node->changed, 'senest_redigeret') . "</p>"; // $output .= "<!-- SENEST OPDATERET SLUT -->"; // $output .= "</div>"; $output .= "<div class=\"activities node-visning\">"; $output .= "<div class=\"swiper-container-activities-aktivitetsside\">"; $output .= "<div class=\"swiper-wrapper\">"; $output .= views_embed_view('aktiviteter','aktivitet_aktiviteter_med_kategori', $term->tid); $output .= "</div>"; $output .= "</div>"; $output .= "</div>"; // Højre kolonne // Flyt (prepend) højrekolonne ind i klassen .view-aktiviteter // $output .= "<div class=\"grid-third\">"; // $output .= "<h2>Jaaaa, man!!!</h2>"; // $output .= "</div>"; $output .= "</div>"; $output .= "</div>"; $output .= "</section>"; $output .= "<!-- ARTIKEL SLUT -->"; // DIMMER DEL SIDEN $options = array('absolute' => TRUE); // NODEVISNING // $nid = $node->nid; // $abs_url = url('node/' . $nid, $options); // ----------- // TAXONOMIVISNING $abs_url = url(substr($term_url, 1), $options); include_once drupal_get_path('theme', 'ishoj') . '/includes/dimmer-del-siden.php'; ?> <!--<div id="taxonomy-term-<?php print $term->tid; ?>" class="<?php print $classes; ?>">--> <?php// if (!$page): ?> <!-- <h2><a href="<?php //print $term_url; ?>"><?php //print $term_name; ?></a></h2>--> <?php //endif; ?> <!-- <div class="content">--> <?php// print render($content); ?> <!-- </div>--> <!--</div>--> <?php // BREAKING print views_embed_view('kriseinformation', 'pagevisning'); // OUTPUT print $output; ?>
ishoj/ishoj.dk
public_html/sites/all/themes/ishoj/templates/taxonomy-term--aktivitetstype.tpl.php
PHP
gpl-2.0
5,453
// Copyright (C) 2007, 2008, 2009 EPITA Research and Development Laboratory (LRDE) // // This file is part of Olena. // // Olena 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. // // Olena 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 Olena. If not, see <http://www.gnu.org/licenses/>. // // As a special exception, you may use this file as part of a free // software project 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. #ifndef MLN_CANVAS_ALL_HH # define MLN_CANVAS_ALL_HH /// \file /// /// File that includes all canvas-related routines. namespace mln { /// Namespace of canvas. namespace canvas { /// Implementation namespace of canvas namespace. namespace impl {} } } # include <mln/canvas/browsing/all.hh> # include <mln/canvas/chamfer.hh> # include <mln/canvas/distance_front.hh> # include <mln/canvas/distance_geodesic.hh> # include <mln/canvas/labeling/all.hh> # include <mln/canvas/morpho/all.hh> #endif // ! MLN_CANVAS_ALL_HH
glazzara/olena
milena/mln/canvas/all.hh
C++
gpl-2.0
1,796
<?php /** * pChart - a PHP class to build charts! * Copyright (C) 2008 Jean-Damien POGOLOTTI * Version 2.0 * * http://pchart.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 1,2,3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ spl_autoload_register('pChart_autoload'); function pChart_autoload($name){ $file = dirname(__FILE__).'/'.$name.'.php'; if(file_exists($file)) require_once($file); } /* Declare some script wide constants */ define ("SCALE_NORMAL", 1); define ("SCALE_ADDALL", 2); define ("SCALE_START0", 3); define ("SCALE_ADDALLSTART0", 4); define ("TARGET_GRAPHAREA", 1); define ("TARGET_BACKGROUND", 2); define ("ALIGN_TOP_LEFT", 1); define ("ALIGN_TOP_CENTER", 2); define ("ALIGN_TOP_RIGHT", 3); define ("ALIGN_LEFT", 4); define ("ALIGN_CENTER", 5); define ("ALIGN_RIGHT", 6); define ("ALIGN_BOTTOM_LEFT", 7); define ("ALIGN_BOTTOM_CENTER", 8); define ("ALIGN_BOTTOM_RIGHT", 9); /** * pChart class definition */ class pChart { protected $palette; /* Some static vars used in the class */ protected $XSize = NULL; protected $YSize = NULL; protected $Picture = NULL; protected $ImageMap = NULL; /* Error management */ protected $ErrorReporting = FALSE; protected $ErrorInterface = "CLI"; protected $Errors = NULL; protected $ErrorFontName = "Fonts/pf_arma_five.ttf"; protected $ErrorFontSize = 6; /* vars related to the graphing area */ protected $GArea_X1 = NULL; protected $GArea_Y1 = NULL; protected $GArea_X2 = NULL; protected $GArea_Y2 = NULL; protected $GAreaXOffset = NULL; protected $VMax = NULL; protected $VMin = NULL; protected $VXMax = NULL; protected $VXMin = NULL; protected $Divisions = NULL; protected $XDivisions = NULL; protected $DivisionHeight = NULL; protected $XDivisionHeight = NULL; protected $DivisionCount = NULL; protected $XDivisionCount = NULL; protected $DivisionRatio = NULL; protected $XDivisionRatio = NULL; protected $DivisionWidth = NULL; protected $DataCount = NULL; /* Text format related vars */ protected $FontName = NULL; /** @var float $FontSize */ protected $FontSize = NULL; protected $DateFormat = "d/m/Y"; /* Lines format related vars */ protected $LineWidth = 1; protected $LineDotSize = 0; /* Shadow settings */ private $shadowProperties; /* Image Map settings */ protected $BuildMap = FALSE; protected $MapFunction = NULL; protected $tmpFolder = "tmp/"; protected $MapID = NULL; /** * @brief An abstract ICanvas onto which we draw the chart * * @todo This probably shouldn't be protected, I'm still working * on how the modules are going to break down between the various * chart types. */ protected $canvas = null; /** * Initializes the Graph and Canvas object */ public function __construct($XSize, $YSize, ICanvas $canvas) { $this->palette = Palette::defaultPalette(); $this->XSize = $XSize; $this->YSize = $YSize; $this->setFontProperties("tahoma.ttf", 8); $this->shadowProperties = ShadowProperties::FromDefaults(); $this->canvas = $canvas; } /** * Set if warnings should be reported */ function reportWarnings($Interface = "CLI") { $this->ErrorReporting = TRUE; $this->ErrorInterface = $Interface; } /** * Set the font properties * * Will be used for all following text operations. * * @param string $FontFile full path to the TTF font file * @param float $FontSize */ function setFontProperties($FontFile, $FontSize) { $this->FontName = $FontFile; $this->FontSize = $FontSize; } /** * Changes the color Palette * * @param Palette $newPalette */ public function setPalette(Palette $newPalette) { $this->palette = $newPalette; } /** * Set the shadow properties */ function setShadowProperties($XDistance = 1, $YDistance = 1, Color $color = null, $Alpha = 50, $Blur = 0) { if($color == null) { $color = new Color(60, 60, 60); } $this->shadowProperties = ShadowProperties::FromSettings( $XDistance, $YDistance, $color, $Alpha, $Blur ); } /** * Remove shadow option */ function clearShadow() { $this->shadowProperties = ShadowProperties::FromDefaults(); } /** * Load Color Palette from file */ function loadColorPalette($FileName, $Delimiter = ",") { $this->palette = Palette::fromFile($FileName, $Delimiter); } /** * Set line style */ function setLineStyle($Width = 1, $DotSize = 0) { $this->LineWidth = $Width; $this->LineDotSize = $DotSize; } /** * Set the graph area location */ function setGraphArea($X1, $Y1, $X2, $Y2) { $this->GArea_X1 = $X1; $this->GArea_Y1 = $Y1; $this->GArea_X2 = $X2; $this->GArea_Y2 = $Y2; } /** * Prepare the graph area */ private function drawGraphArea(BackgroundStyle $style) { $this->canvas->drawFilledRectangle( new Point($this->GArea_X1, $this->GArea_Y1), new Point($this->GArea_X2, $this->GArea_Y2), $style->getBackgroundColor(), $this->shadowProperties, FALSE ); $this->canvas->drawRectangle( new Point($this->GArea_X1, $this->GArea_Y1), new Point($this->GArea_X2, $this->GArea_Y2), $style->getBackgroundColor()->addRGBIncrement(-40), $style->getBorderWidth(), $style->getBorderDotSize(), $this->shadowProperties ); if($style->useStripe()) { $color2 = $style->getBackgroundColor()->addRGBIncrement(-15); $SkewWidth = $this->GArea_Y2 - $this->GArea_Y1 - 1; for($i = $this->GArea_X1 - $SkewWidth; $i <= $this->GArea_X2; $i = $i + 4) { $X1 = $i; $Y1 = $this->GArea_Y2; $X2 = $i + $SkewWidth; $Y2 = $this->GArea_Y1; if($X1 < $this->GArea_X1) { $X1 = $this->GArea_X1; $Y1 = $this->GArea_Y1 + $X2 - $this->GArea_X1 + 1; } if($X2 >= $this->GArea_X2) { $Y2 = $this->GArea_Y1 + $X2 - $this->GArea_X2 + 1; $X2 = $this->GArea_X2 - 1; } $this->canvas->drawLine( new Point($X1, $Y1), new Point($X2, $Y2 + 1), $color2, 1, 0, ShadowProperties::NoShadow() ); } } } public function drawGraphBackground(BackgroundStyle $style) { $this->drawGraphArea($style); $this->drawGraphAreaGradient($style); } /** * Allow you to clear the scale : used if drawing multiple charts */ function clearScale() { $this->VMin = NULL; $this->VMax = NULL; $this->VXMin = NULL; $this->VXMax = NULL; $this->Divisions = NULL; $this->XDivisions = NULL; } /** * Allow you to fix the scale, use this to bypass the automatic scaling */ function setFixedScale($VMin, $VMax, $Divisions = 5, $VXMin = 0, $VXMax = 0, $XDivisions = 5) { $this->VMin = $VMin; $this->VMax = $VMax; $this->Divisions = $Divisions; if(!$VXMin == 0) { $this->VXMin = $VXMin; $this->VXMax = $VXMax; $this->XDivisions = $XDivisions; } } /** * Wrapper to the drawScale() function allowing a second scale to * be drawn */ function drawRightScale(pData $data, ScaleStyle $style, $Angle = 0, $Decimals = 1, $WithMargin = FALSE, $SkipLabels = 1) { $this->drawScale($data, $style, $Angle, $Decimals, $WithMargin, $SkipLabels, TRUE); } /** * Compute and draw the scale */ function drawScale(pData $Data, ScaleStyle $style, $Angle = 0, $Decimals = 1, $WithMargin = FALSE, $SkipLabels = 1, $RightScale = FALSE) { /* Validate the Data and DataDescription array */ $this->validateData("drawScale", $Data->getData()); $this->canvas->drawLine( new Point($this->GArea_X1, $this->GArea_Y1), new Point($this->GArea_X1, $this->GArea_Y2), $style->getColor(), $style->getLineWidth(), $style->getLineDotSize(), $this->shadowProperties ); $this->canvas->drawLine( new Point($this->GArea_X1, $this->GArea_Y2), new Point($this->GArea_X2, $this->GArea_Y2), $style->getColor(), $style->getLineWidth(), $style->getLineDotSize(), $this->shadowProperties ); if($this->VMin == NULL && $this->VMax == NULL) { $Divisions = $this->calculateDivisions($Data, $style); } else $Divisions = $this->Divisions; $this->DivisionCount = $Divisions; $DataRange = $this->VMax - $this->VMin; if($DataRange == 0) { $DataRange = .1; } $this->DivisionHeight = ($this->GArea_Y2 - $this->GArea_Y1) / $Divisions; $this->DivisionRatio = ($this->GArea_Y2 - $this->GArea_Y1) / $DataRange; $this->GAreaXOffset = 0; if(count($Data->getData()) > 1) { if($WithMargin == FALSE) $this->DivisionWidth = ($this->GArea_X2 - $this->GArea_X1) / (count($Data->getData()) - 1); else { $this->DivisionWidth = ($this->GArea_X2 - $this->GArea_X1) / (count($Data->getData())); $this->GAreaXOffset = $this->DivisionWidth / 2; } } else { $this->DivisionWidth = $this->GArea_X2 - $this->GArea_X1; $this->GAreaXOffset = $this->DivisionWidth / 2; } $this->DataCount = count($Data->getData()); if($style->getDrawTicks() == FALSE) return (0); $YPos = $this->GArea_Y2; $XMin = NULL; for($i = 1; $i <= $Divisions + 1; $i++) { if($RightScale) $this->canvas->drawLine( new Point($this->GArea_X2, $YPos), new Point($this->GArea_X2 + 5, $YPos), $style->getColor(), $style->getLineWidth(), $style->getLineDotSize(), $this->shadowProperties ); else $this->canvas->drawLine( new Point($this->GArea_X1, $YPos), new Point($this->GArea_X1 - 5, $YPos), $style->getColor(), $style->getLineWidth(), $style->getLineDotSize(), $this->shadowProperties ); $Value = $this->VMin + ($i - 1) * (($this->VMax - $this->VMin) / $Divisions); $Value = round($Value * pow(10, $Decimals)) / pow(10, $Decimals); $Value = $this->convertValueForDisplay( $Value, $Data->getDataDescription()->getYFormat(), $Data->getDataDescription()->getYUnit() ); $Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value); $TextWidth = $Position [2] - $Position [0]; if($RightScale) { $this->canvas->drawText( $this->FontSize, 0, new Point($this->GArea_X2 + 10, $YPos + ($this->FontSize / 2)), $style->getColor(), $this->FontName, $Value, ShadowProperties::NoShadow() ); if($XMin < $this->GArea_X2 + 15 + $TextWidth || $XMin == NULL) { $XMin = $this->GArea_X2 + 15 + $TextWidth; } } else { $this->canvas->drawText( $this->FontSize, 0, new Point($this->GArea_X1 - 10 - $TextWidth, $YPos + ($this->FontSize / 2)), $style->getColor(), $this->FontName, $Value, ShadowProperties::NoShadow() ); if($XMin > $this->GArea_X1 - 10 - $TextWidth || $XMin == NULL) { $XMin = $this->GArea_X1 - 10 - $TextWidth; } } $YPos = $YPos - $this->DivisionHeight; } /* Write the Y Axis caption if set */ if($Data->getDataDescription()->getYAxisName() != '') { $Position = imageftbbox($this->FontSize, 90, $this->FontName, $Data->getDataDescription()->getYAxisName()); $TextHeight = abs($Position [1]) + abs($Position [3]); $TextTop = (($this->GArea_Y2 - $this->GArea_Y1) / 2) + $this->GArea_Y1 + ($TextHeight / 2); if($RightScale) { $this->canvas->drawText( $this->FontSize, 90, new Point($XMin + $this->FontSize, $TextTop), $style->getColor(), $this->FontName, $Data->getDataDescription()->getYAxisName(), ShadowProperties::NoShadow() ); } else { $this->canvas->drawText( $this->FontSize, 90, new Point($XMin - $this->FontSize, $TextTop), $style->getColor(), $this->FontName, $Data->getDataDescription()->getYAxisName(), ShadowProperties::NoShadow() ); } } /* Horizontal Axis */ $XPos = $this->GArea_X1 + $this->GAreaXOffset; $ID = 1; $YMax = NULL; foreach($Data->getData() as $Values) { if($ID % $SkipLabels == 0) { $this->canvas->drawLine( new Point(floor($XPos), $this->GArea_Y2), new Point(floor($XPos), $this->GArea_Y2 + 5), $style->getColor(), $style->getLineWidth(), $style->getLineDotSize(), $this->shadowProperties ); $Value = $Values[$Data->getDataDescription()->getPosition()]; $Value = $this->convertValueForDisplay( $Value, $Data->getDataDescription()->getXFormat(), $Data->getDataDescription()->getXUnit() ); $Position = imageftbbox($this->FontSize, $Angle, $this->FontName, $Value); $TextWidth = abs($Position [2]) + abs($Position [0]); $TextHeight = abs($Position [1]) + abs($Position [3]); if($Angle == 0) { $YPos = $this->GArea_Y2 + 18; $this->canvas->drawText( $this->FontSize, $Angle, new Point(floor($XPos) - floor($TextWidth / 2), $YPos), $style->getColor(), $this->FontName, $Value, ShadowProperties::NoShadow() ); } else { $YPos = $this->GArea_Y2 + 10 + $TextHeight; if($Angle <= 90) { $this->canvas->drawText( $this->FontSize, $Angle, new Point(floor($XPos) - $TextWidth + 5, $YPos), $style->getColor(), $this->FontName, $Value, ShadowProperties::NoShadow() ); } else { $this->canvas->drawText( $this->FontSize, $Angle, new Point(floor($XPos) + $TextWidth + 5, $YPos), $style->getColor(), $this->FontName, $Value, ShadowProperties::NoShadow() ); } } if($YMax < $YPos || $YMax == NULL) { $YMax = $YPos; } } $XPos = $XPos + $this->DivisionWidth; $ID++; } /* Write the X Axis caption if set */ if($Data->getDataDescription()->getXAxisName() != '') { $Position = imageftbbox( $this->FontSize, 90, $this->FontName, $Data->getDataDescription()->getXAxisName() ); $TextWidth = abs($Position [2]) + abs($Position [0]); $TextLeft = (($this->GArea_X2 - $this->GArea_X1) / 2) + $this->GArea_X1 + ($TextWidth / 2); $this->canvas->drawText( $this->FontSize, 0, new Point($TextLeft, $YMax + $this->FontSize + 5), $style->getColor(), $this->FontName, $Data->getDataDescription()->getXAxisName(), ShadowProperties::NoShadow() ); } } /** * Calculate the number of divisions that the Y axis will be * divided into. This is a function of the range of Y values the * data covers, as well as the scale style. Divisions should have * some minimum size in screen coordinates in order that the * divisions are clearly visible, so this is also a function of * the graph size in screen coordinates. * * This method returns the number of divisions, but it also has * side-effects on some class data members. This needs to be * refactored to make it clearer what is and isn't affected. */ private function calculateDivisions(pData $Data, ScaleStyle $style) { if(isset ($Data->getDataDescription()->values[0])) { /* Pointless temporary is necessary because you can't * directly apply an array index to the return value * of a function in PHP */ $dataArray = $Data->getData(); $this->VMin = $dataArray[0] [$Data->getDataDescription()->values[0]]; $this->VMax = $dataArray[0] [$Data->getDataDescription()->values[0]]; } else { $this->VMin = 2147483647; $this->VMax = -2147483647; } /* Compute Min and Max values */ if($style->getScaleMode() == SCALE_NORMAL || $style->getScaleMode() == SCALE_START0 ) { if($style->getScaleMode() == SCALE_START0) { $this->VMin = 0; } foreach($Data->getData() as $Values) { foreach($Data->getDataDescription()->values as $ColName) { if(isset ($Values[$ColName])) { $Value = $Values[$ColName]; if(is_numeric($Value)) { if($this->VMax < $Value) { $this->VMax = $Value; } if($this->VMin > $Value) { $this->VMin = $Value; } } } } } } elseif($style->getScaleMode() == SCALE_ADDALL || $style->getScaleMode() == SCALE_ADDALLSTART0) /* Experimental */ { if($style->getScaleMode() == SCALE_ADDALLSTART0) { $this->VMin = 0; } foreach($Data->getData() as $Values) { $Sum = 0; foreach($Data->getDataDescription()->values as $ColName) { $dataArray = $Data->getData(); if(isset ($Values[$ColName])) { $Value = $Values[$ColName]; if(is_numeric($Value)) $Sum += $Value; } } if($this->VMax < $Sum) { $this->VMax = $Sum; } if($this->VMin > $Sum) { $this->VMin = $Sum; } } } $this->VMax = ceil($this->VMax); /* If all values are the same */ if($this->VMax == $this->VMin) { if($this->VMax >= 0) { $this->VMax++; } else { $this->VMin--; } } $DataRange = $this->VMax - $this->VMin; if($DataRange == 0) { $DataRange = .1; } $this->calculateScales($Scale, $Divisions); if(!isset ($Divisions)) $Divisions = 2; if($Scale == 1 && $Divisions % 2 == 1) $Divisions--; return $Divisions; } /** * Compute and draw the scale for X/Y charts */ function drawXYScale(pData $Data, ScaleStyle $style, $YSerieName, $XSerieName, $Angle = 0, $Decimals = 1) { /* Validate the Data and DataDescription array */ $this->validateData("drawScale", $Data->getData()); $this->canvas->drawLine( new Point($this->GArea_X1, $this->GArea_Y1), new Point($this->GArea_X1, $this->GArea_Y2), $style->getColor(), $style->getLineWidth(), $style->getLineDotSize(), $this->shadowProperties ); $this->canvas->drawLine( new Point($this->GArea_X1, $this->GArea_Y2), new Point($this->GArea_X2, $this->GArea_Y2), $style->getColor(), $style->getLineWidth(), $style->getLineDotSize(), $this->shadowProperties ); /* Process Y scale */ if($this->VMin == NULL && $this->VMax == NULL) { $this->VMin = $Data->getSeriesMin($YSerieName); $this->VMax = $Data->getSeriesMax($YSerieName); /** @todo The use of ceil() here is questionable if all * the values are much less than 1, AIUI */ $this->VMax = ceil($this->VMax); $DataRange = $this->VMax - $this->VMin; if($DataRange == 0) { $DataRange = .1; } self::computeAutomaticScaling( $this->GArea_Y1, $this->GArea_Y2, $this->VMin, $this->VMax, $Divisions ); } else $Divisions = $this->Divisions; $this->DivisionCount = $Divisions; $DataRange = $this->VMax - $this->VMin; if($DataRange == 0) { $DataRange = .1; } $this->DivisionHeight = ($this->GArea_Y2 - $this->GArea_Y1) / $Divisions; $this->DivisionRatio = ($this->GArea_Y2 - $this->GArea_Y1) / $DataRange; $YPos = $this->GArea_Y2; $XMin = NULL; for($i = 1; $i <= $Divisions + 1; $i++) { $this->canvas->drawLine( new Point($this->GArea_X1, $YPos), new Point($this->GArea_X1 - 5, $YPos), $style->getColor(), $style->getLineWidth(), $style->getLineDotSize(), $this->shadowProperties ); $Value = $this->VMin + ($i - 1) * (($this->VMax - $this->VMin) / $Divisions); $Value = round($Value * pow(10, $Decimals)) / pow(10, $Decimals); $Value = $this->convertValueForDisplay( $Value, $Data->getDataDescription()->getYFormat(), $Data->getDataDescription()->getYUnit() ); $Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value); $TextWidth = $Position [2] - $Position [0]; $this->canvas->drawText( $this->FontSize, 0, new Point($this->GArea_X1 - 10 - $TextWidth, $YPos + ($this->FontSize / 2)), $style->getColor(), $this->FontName, $Value, $this->shadowProperties ); if($XMin > $this->GArea_X1 - 10 - $TextWidth || $XMin == NULL) { $XMin = $this->GArea_X1 - 10 - $TextWidth; } $YPos = $YPos - $this->DivisionHeight; } /* Process X scale */ if($this->VXMin == NULL && $this->VXMax == NULL) { $this->VXMax = $Data->getSeriesMax($XSerieName); $this->VXMin = $Data->getSeriesMin($XSerieName); $this->VXMax = ceil($this->VXMax); $DataRange = $this->VMax - $this->VMin; if($DataRange == 0) { $DataRange = .1; } /* Compute automatic scaling */ self::computeAutomaticScaling( $this->GArea_X1, $this->GArea_X2, $this->VXMin, $this->VXMax, $XDivisions ); } else $XDivisions = $this->XDivisions; $this->XDivisionCount = $Divisions; $this->DataCount = $Divisions + 2; $XDataRange = $this->VXMax - $this->VXMin; if($XDataRange == 0) { $XDataRange = .1; } $this->DivisionWidth = ($this->GArea_X2 - $this->GArea_X1) / $XDivisions; $this->XDivisionRatio = ($this->GArea_X2 - $this->GArea_X1) / $XDataRange; $XPos = $this->GArea_X1; $YMax = NULL; for($i = 1; $i <= $XDivisions + 1; $i++) { $this->canvas->drawLine( new Point($XPos, $this->GArea_Y2), new Point($XPos, $this->GArea_Y2 + 5), $style->getColor(), $style->getLineWidth(), $style->getLineDotSize(), $this->shadowProperties ); $Value = $this->VXMin + ($i - 1) * (($this->VXMax - $this->VXMin) / $XDivisions); $Value = round($Value * pow(10, $Decimals)) / pow(10, $Decimals); $Value = $this->convertValueForDisplay( $Value, $Data->getDataDescription()->getYFormat(), $Data->getDataDescription()->getYUnit() ); $Position = imageftbbox($this->FontSize, $Angle, $this->FontName, $Value); $TextWidth = abs($Position [2]) + abs($Position [0]); $TextHeight = abs($Position [1]) + abs($Position [3]); if($Angle == 0) { $YPos = $this->GArea_Y2 + 18; $this->canvas->drawText( $this->FontSize, $Angle, new Point(floor($XPos) - floor($TextWidth / 2), $YPos), $style->getColor(), $this->FontName, $Value, $this->shadowProperties ); } else { $YPos = $this->GArea_Y2 + 10 + $TextHeight; if($Angle <= 90) { $this->canvas->drawText( $this->FontSize, $Angle, new Point(floor($XPos) - $TextWidth + 5, $YPos), $style->getColor(), $this->FontName, $Value, $this->shadowProperties ); } else { $this->canvas->drawText( $this->FontSize, $Angle, new Point(floor($XPos) + $TextWidth + 5, $YPos), $style->getColor(), $this->FontName, $Value, $this->shadowProperties ); } } if($YMax < $YPos || $YMax == NULL) { $YMax = $YPos; } $XPos = $XPos + $this->DivisionWidth; } /* Write the Y Axis caption if set */ if($Data->getDataDescription()->getYAxisName() != '') { $Position = imageftbbox( $this->FontSize, 90, $this->FontName, $Data->getDataDescription()->getYAxisName() ); $TextHeight = abs($Position [1]) + abs($Position [3]); $TextTop = (($this->GArea_Y2 - $this->GArea_Y1) / 2) + $this->GArea_Y1 + ($TextHeight / 2); $this->canvas->drawText( $this->FontSize, 90, new Point($XMin - $this->FontSize, $TextTop), $style->getColor(), $this->FontName, $Data->getDataDescription()->getYAxisName(), $this->shadowProperties ); } /* Write the X Axis caption if set */ $this->writeScaleXAxisCaption($Data, $style, $YMax); } private function drawGridMosaic(GridStyle $style, $divisionCount, $divisionHeight) { $LayerHeight = $this->GArea_Y2 - $this->GArea_Y1; $YPos = $LayerHeight - 1; //$this->GArea_Y2-1; $LastY = $YPos; for($i = 0; $i < $divisionCount; $i++) { $LastY = $YPos; $YPos = $YPos - $divisionHeight; if($YPos <= 0) { $YPos = 1; } if($i % 2 == 0) { $this->canvas->drawFilledRectangle( new Point($this->GArea_X1 + 1, $this->GArea_Y1 + $YPos), new Point($this->GArea_X2 - 1, $this->GArea_Y1 + $LastY), new Color(250, 250, 250), ShadowProperties::NoShadow(), false, $style->getAlpha() ); } } } /** * Write the X Axis caption on the scale, if set */ private function writeScaleXAxisCaption(pData $data, ScaleStyle $style, $YMax) { if($data->getDataDescription()->getXAxisName() != '') { $Position = imageftbbox($this->FontSize, 90, $this->FontName, $data->getDataDescription()->getXAxisName()); $TextWidth = abs($Position [2]) + abs($Position [0]); $TextLeft = (($this->GArea_X2 - $this->GArea_X1) / 2) + $this->GArea_X1 + ($TextWidth / 2); $this->canvas->drawText( $this->FontSize, 0, new Point($TextLeft, $YMax + $this->FontSize + 5), $style->getColor(), $this->FontName, $data->getDataDescription()->getXAxisName(), $this->shadowProperties ); } } /** * Compute and draw the scale */ function drawGrid(GridStyle $style) { /* Draw mosaic */ if($style->getMosaic()) { $this->drawGridMosaic($style, $this->DivisionCount, $this->DivisionHeight); } /* Horizontal lines */ $YPos = $this->GArea_Y2 - $this->DivisionHeight; for($i = 1; $i <= $this->DivisionCount; $i++) { if($YPos > $this->GArea_Y1 && $YPos < $this->GArea_Y2) $this->canvas->drawDottedLine( new Point($this->GArea_X1, $YPos), new Point($this->GArea_X2, $YPos), $style->getLineWidth(), $this->LineWidth, $style->getColor(), ShadowProperties::NoShadow() ); /** @todo There's some inconsistency here. The parameter * $lineWidth appears to be used to control the dot size, * not the line width? This is the same way it's always * been done, although now it's more obvious that there's * a problem. */ $YPos = $YPos - $this->DivisionHeight; } /* Vertical lines */ if($this->GAreaXOffset == 0) { $XPos = $this->GArea_X1 + $this->DivisionWidth + $this->GAreaXOffset; $ColCount = $this->DataCount - 2; } else { $XPos = $this->GArea_X1 + $this->GAreaXOffset; $ColCount = floor(($this->GArea_X2 - $this->GArea_X1) / $this->DivisionWidth); } for($i = 1; $i <= $ColCount; $i++) { if($XPos > $this->GArea_X1 && $XPos < $this->GArea_X2) $this->canvas->drawDottedLine( new Point(floor($XPos), $this->GArea_Y1), new Point(floor($XPos), $this->GArea_Y2), $style->getLineWidth(), $this->LineWidth, $style->getcolor(), $this->shadowProperties ); $XPos = $XPos + $this->DivisionWidth; } } /** * retrieve the legends size */ public function getLegendBoxSize($DataDescription) { if(!isset ($DataDescription->description)) return (-1); /* <-10->[8]<-4->Text<-10-> */ $MaxWidth = 0; $MaxHeight = 8; foreach($DataDescription->description as $Value) { $Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value); $TextWidth = $Position [2] - $Position [0]; $TextHeight = $Position [1] - $Position [7]; if($TextWidth > $MaxWidth) { $MaxWidth = $TextWidth; } $MaxHeight = $MaxHeight + $TextHeight + 4; } $MaxHeight = $MaxHeight - 3; $MaxWidth = $MaxWidth + 32; return (array($MaxWidth, $MaxHeight)); } /** * Draw the data legends */ public function drawLegend($XPos, $YPos, $DataDescription, Color $color, Color $color2 = null, Color $color3 = null, $Border = TRUE) { if($color2 == null) { $color2 = $color->addRGBIncrement(-30); } if($color3 == null) { $color3 = new Color(0, 0, 0); } /* Validate the Data and DataDescription array */ $this->validateDataDescription("drawLegend", $DataDescription); if(!isset ($DataDescription->description)) return (-1); /* <-10->[8]<-4->Text<-10-> */ $MaxWidth = 0; $MaxHeight = 8; foreach($DataDescription->description as $Key => $Value) { $Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value); $TextWidth = $Position [2] - $Position [0]; $TextHeight = $Position [1] - $Position [7]; if($TextWidth > $MaxWidth) { $MaxWidth = $TextWidth; } $MaxHeight = $MaxHeight + $TextHeight + 4; } $MaxHeight = $MaxHeight - 5; $MaxWidth = $MaxWidth + 32; if($Border) { $this->canvas->drawFilledRoundedRectangle( new Point($XPos + 1, $YPos + 1), new Point($XPos + $MaxWidth + 1, $YPos + $MaxHeight + 1), 5, $color2, $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $this->canvas->drawFilledRoundedRectangle( new Point($XPos, $YPos), new Point($XPos + $MaxWidth, $YPos + $MaxHeight), 5, $color, $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); } $YOffset = 4 + $this->FontSize; $ID = 0; foreach($DataDescription->description as $Key => $Value) { $this->canvas->drawFilledRoundedRectangle( new Point($XPos + 10, $YPos + $YOffset - 4), new Point($XPos + 14, $YPos + $YOffset - 4), 2, $this->palette->getColor($ID), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $this->canvas->drawText( $this->FontSize, 0, new Point($XPos + 22, $YPos + $YOffset), $color3, $this->FontName, $Value, $this->shadowProperties ); $Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value); $TextHeight = $Position [1] - $Position [7]; $YOffset = $YOffset + $TextHeight + 4; $ID++; } } /** * Draw the graph title * * @todo Should we pass in a ShadowProperties object here? Or is * this a public function? */ public function drawTitle($XPos, $YPos, $Value, Color $color, $XPos2 = -1, $YPos2 = -1, ShadowProperties $shadowProperties = null) { if($shadowProperties == null) { $shadowProperties = ShadowProperties::NoShadow(); } if($XPos2 != -1) { $Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value); $TextWidth = $Position [2] - $Position [0]; $XPos = floor(($XPos2 - $XPos - $TextWidth) / 2) + $XPos; } if($YPos2 != -1) { $Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value); $TextHeight = $Position [5] - $Position [3]; $YPos = floor(($YPos2 - $YPos - $TextHeight) / 2) + $YPos; } $this->canvas->drawText( $this->FontSize, 0, new Point($XPos, $YPos), $color, $this->FontName, $Value, $shadowProperties ); } /** * Draw a text box with text align & alpha properties * * @param $point1 Minimum corner of the box * @param $point2 Maximum corner of the box * * @todo This should probably be a method on the ICanvas * interface, since it doesn't have anything specifically to do * with graphs */ public function drawTextBox(Point $point1, Point $point2, $Text, $Angle = 0, Color $color = null, $Align = ALIGN_LEFT, ShadowProperties $shadowProperties = null, Color $backgroundColor = null, $Alpha = 100) { if($color == null) { $color = new Color(255, 255, 255); } if($shadowProperties == null) { $shadowProperties = ShadowProperties::NoShadow(); } $Position = imageftbbox($this->FontSize, $Angle, $this->FontName, $Text); $TextWidth = $Position [2] - $Position [0]; $TextHeight = $Position [5] - $Position [3]; $AreaWidth = $point2->getX() - $point1->getX(); $AreaHeight = $point2->getY() - $point1->getY(); if($backgroundColor != null) $this->canvas->drawFilledRectangle( $point1, $point2, $backgroundColor, $shadowProperties, FALSE, $Alpha ); if($Align == ALIGN_TOP_LEFT) { $newPosition = $point1->addIncrement(1, $this->FontSize + 1); } if($Align == ALIGN_TOP_CENTER) { $newPosition = $point1->addIncrement( ($AreaWidth / 2) - ($TextWidth / 2), $this->FontSize + 1 ); } if($Align == ALIGN_TOP_RIGHT) { $newPosition = new Point($point2->getX() - $TextWidth - 1, $point1->getY() + $this->FontSize + 1); } if($Align == ALIGN_LEFT) { $newPosition = $point1->addIncrement( 1, ($AreaHeight / 2) - ($TextHeight / 2) ); } if($Align == ALIGN_CENTER) { $newPosition = $point1->addIncrement( ($AreaWidth / 2) - ($TextWidth / 2), ($AreaHeight / 2) - ($TextHeight / 2) ); } if($Align == ALIGN_RIGHT) { $newPosition = new Point($point2->getX() - $TextWidth - 1, $point1->getY() + ($AreaHeight / 2) - ($TextHeight / 2)); } if($Align == ALIGN_BOTTOM_LEFT) { $newPosition = new Point($point1->getX() + 1, $point2->getY() - 1); } if($Align == ALIGN_BOTTOM_CENTER) { $newPosition = new Point($point1->getX() + ($AreaWidth / 2) - ($TextWidth / 2), $point2->getY() - 1); } if($Align == ALIGN_BOTTOM_RIGHT) { $newPosition = $point2->addIncrement( -$TextWidth - 1, -1 ); } $this->canvas->drawText($this->FontSize, $Angle, $newPosition, $color, $this->FontName, $Text, $shadowProperties); } /** * Compute and draw the scale * * @todo What is the method name a typo for? Threshold? */ function drawTreshold($Value, Color $color, $ShowLabel = FALSE, $ShowOnRight = FALSE, $TickWidth = 4, $FreeText = NULL) { $Y = $this->GArea_Y2 - ($Value - $this->VMin) * $this->DivisionRatio; if($Y <= $this->GArea_Y1 || $Y >= $this->GArea_Y2) return (-1); if($TickWidth == 0) $this->canvas->drawLine( new Point($this->GArea_X1, $Y), new Point($this->GArea_X2, $Y), $color, $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); else $this->canvas->drawDottedLine( new Point($this->GArea_X1, $Y), new Point($this->GArea_X2, $Y), $TickWidth, $this->LineWidth, $color, $this->shadowProperties ); if($ShowLabel) { if($FreeText == NULL) { $Label = $Value; } else { $Label = $FreeText; } if($ShowOnRight) { $position = new Point($this->GArea_X2 + 2, $Y + ($this->FontSize / 2)); } else { $position = new Point($this->GArea_X1 + 2, $Y - ($this->FontSize / 2)); } $this->canvas->drawText( $this->FontSize, 0, $position, $color, $this->FontName, $Label, ShadowProperties::NoShadow() ); } } /** * This function put a label on a specific point */ function setLabel($Data, $DataDescription, $SerieName, $ValueName, $Caption, Color $color = null) { if($color == null) { $color = new Color(210, 210, 210); } /* Validate the Data and DataDescription array */ $this->validateDataDescription("setLabel", $DataDescription); $this->validateData("setLabel", $Data); $ShadowFactor = 100; $Cp = 0; $Found = FALSE; foreach($Data as $Value) { if($Value[$DataDescription->getPosition()] == $ValueName) { $NumericalValue = $Value[$SerieName]; $Found = TRUE; } if(!$Found) $Cp++; } $XPos = $this->GArea_X1 + $this->GAreaXOffset + ($this->DivisionWidth * $Cp) + 2; $YPos = $this->GArea_Y2 - ($NumericalValue - $this->VMin) * $this->DivisionRatio; $Position = imageftbbox($this->FontSize, 0, $this->FontName, $Caption); $TextHeight = $Position [3] - $Position [5]; $TextWidth = $Position [2] - $Position [0] + 2; $TextOffset = floor($TextHeight / 2); // Shadow $Poly = array($XPos + 1, $YPos + 1, $XPos + 9, $YPos - $TextOffset, $XPos + 8, $YPos + $TextOffset + 2); $this->canvas->drawFilledPolygon( $Poly, 3, $color->addRGBIncrement(-$ShadowFactor) ); $this->canvas->drawLine( new Point($XPos, $YPos + 1), new Point($XPos + 9, $YPos - $TextOffset - .2), $color->addRGBIncrement(-$ShadowFactor), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $this->canvas->drawLine( new Point($XPos, $YPos + 1), new Point($XPos + 9, $YPos + $TextOffset + 2.2), $color->addRGBIncrement(-$ShadowFactor), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $this->canvas->drawFilledRectangle( new Point($XPos + 9, $YPos - $TextOffset - .2), new Point($XPos + 13 + $TextWidth, $YPos + $TextOffset + 2.2), $color->addRGBIncrement(-$ShadowFactor), $this->shadowProperties ); // Label background $Poly = array($XPos, $YPos, $XPos + 8, $YPos - $TextOffset - 1, $XPos + 8, $YPos + $TextOffset + 1); $this->canvas->drawFilledPolygon($Poly, 3, $color); /** @todo We draw exactly the same line twice, with the same settings. * Surely this is pointless? */ $this->canvas->drawLine( new Point($XPos - 1, $YPos), new Point($XPos + 8, $YPos - $TextOffset - 1.2), $color, $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $this->canvas->drawLine( new Point($XPos - 1, $YPos), new Point($XPos + 8, $YPos + $TextOffset + 1.2), $color, $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $this->canvas->drawFilledRectangle( new Point($XPos + 8, $YPos - $TextOffset - 1.2), new Point($XPos + 12 + $TextWidth, $YPos + $TextOffset + 1.2), $color, $this->shadowProperties ); $this->canvas->drawText( $this->FontSize, 0, new Point($XPos + 10, $YPos + $TextOffset), new Color(0, 0, 0), $this->FontName, $Caption, ShadowProperties::NoShadow() ); } /** * Linearly Scale a given value * * using it's own minima/maxima and the desired output minima/maxima */ function linearScale($value, $istart, $istop, $ostart, $ostop) { $div = ($istop - $istart); if($div == 0.0) $div = 1; return $ostart + ($ostop - $ostart) * (($value - $istart) / $div); } /** * This function draw a plot graph */ function drawPlotGraph($Data, $DataDescription, $BigRadius = 5, $SmallRadius = 2, Color $color2 = null, $Shadow = FALSE) { /* Validate the Data and DataDescription array */ $this->validateDataDescription("drawPlotGraph", $DataDescription); $this->validateData("drawPlotGraph", $Data); $GraphID = 0; $colorO = $color2; foreach($DataDescription->values as $ColName) { $ColorID = $DataDescription->getColumnIndex($ColName); $color = $this->palette->getColor($ColorID); $color2 = $colorO; if(isset ($DataDescription->seriesSymbols[$ColName])) { $Infos = getimagesize($DataDescription->seriesSymbols[$ColName]); $ImageWidth = $Infos [0]; $ImageHeight = $Infos [1]; $Symbol = imagecreatefromgif($DataDescription->seriesSymbols[$ColName]); } $XPos = $this->GArea_X1 + $this->GAreaXOffset; $Hsize = round($BigRadius / 2); $color3 = null; foreach($Data as $Values) { $Value = $Values[$ColName]; $YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio); /* Save point into the image map if option activated */ if($this->BuildMap) $this->addToImageMap($XPos - $Hsize, $YPos - $Hsize, $XPos + 1 + $Hsize, $YPos + $Hsize + 1, $DataDescription->description[$ColName], $Values[$ColName].$DataDescription->getYUnit(), "Plot"); if(is_numeric($Value)) { if(!isset ($DataDescription->seriesSymbols[$ColName])) { if($Shadow) { if($color3 != null) { $this->canvas->drawFilledCircle( new Point($XPos + 2, $YPos + 2), $BigRadius, $color3, $this->shadowProperties ); } else { $color3 = $this->palette->getColor($ColorID)->addRGBIncrement(-20); $this->canvas->drawFilledCircle( new Point($XPos + 2, $YPos + 2), $BigRadius, $color3, $this->shadowProperties ); } } $this->canvas->drawFilledCircle( new Point($XPos + 1, $YPos + 1), $BigRadius, $color, $this->shadowProperties ); if($SmallRadius != 0) { if($color2 != null) { $this->canvas->drawFilledCircle( new Point($XPos + 1, $YPos + 1), $SmallRadius, $color2, $this->shadowProperties ); } else { $color2 = $this->palette->getColor($ColorID)->addRGBIncrement(-15); $this->canvas->drawFilledCircle( new Point($XPos + 1, $YPos + 1), $SmallRadius, $color2, $this->shadowProperties ); } } } else { imagecopymerge($this->canvas->getPicture(), $Symbol, $XPos + 1 - $ImageWidth / 2, $YPos + 1 - $ImageHeight / 2, 0, 0, $ImageWidth, $ImageHeight, 100); } } $XPos = $XPos + $this->DivisionWidth; } $GraphID++; } } /** * @brief This function draw a plot graph in an X/Y space */ function drawXYPlotGraph(pData $DataSet, $YSerieName, $XSerieName, $PaletteID = 0, $BigRadius = 5, $SmallRadius = 2, Color $color2 = null, $Shadow = TRUE, $SizeSerieName = '') { $color = $this->palette->getColor($PaletteID); $color3 = null; $Data = $DataSet->getData(); foreach($Data as $Values) { if(isset($Values[$YSerieName]) && isset ($Values[$XSerieName])) { $X = $Values[$XSerieName]; $Y = $Values[$YSerieName]; $Y = $this->GArea_Y2 - (($Y - $this->VMin) * $this->DivisionRatio); $X = $this->GArea_X1 + (($X - $this->VXMin) * $this->XDivisionRatio); if(isset($Values[$SizeSerieName])) { $br = $this->linearScale( $Values[$SizeSerieName], $DataSet->getSeriesMin($SizeSerieName), $DataSet->getSeriesMax($SizeSerieName), $SmallRadius, $BigRadius ); $sr = $br; } else { $br = $BigRadius; $sr = $SmallRadius; } if($Shadow) { if($color3 != null) { $this->canvas->drawFilledCircle( new Point($X + 2, $Y + 2), $br, $color3, $this->shadowProperties ); } else { $color3 = $this->palette->getColor($PaletteID)->addRGBIncrement(-20); $this->canvas->drawFilledCircle( new Point($X + 2, $Y + 2), $br, $color3, $this->shadowProperties ); } } $this->canvas->drawFilledCircle( new Point($X + 1, $Y + 1), $br, $color, $this->shadowProperties ); if($color2 != null) { $this->canvas->drawFilledCircle( new Point($X + 1, $Y + 1), $sr, $color2, $this->shadowProperties ); } else { $color2 = $this->palette->getColor($PaletteID)->addRGBIncrement(20); $this->canvas->drawFilledCircle( new Point($X + 1, $Y + 1), $sr, $color2, $this->shadowProperties ); } } } } /** * This function draw an area between two series */ function drawArea($Data, $Serie1, $Serie2, Color $color, $Alpha = 50) { /* Validate the Data and DataDescription array */ $this->validateData("drawArea", $Data); $LayerHeight = $this->GArea_Y2 - $this->GArea_Y1; $XPos = $this->GAreaXOffset; $LastXPos = -1; $LastYPos1 = 0; $LastYPos2 = 0; foreach($Data as $Values) { $Value1 = $Values[$Serie1]; $Value2 = $Values[$Serie2]; $YPos1 = $LayerHeight - (($Value1 - $this->VMin) * $this->DivisionRatio); $YPos2 = $LayerHeight - (($Value2 - $this->VMin) * $this->DivisionRatio); if($LastXPos != -1) { $Points = array(); $Points [] = $LastXPos + $this->GArea_X1; $Points [] = $LastYPos1 + $this->GArea_Y1; $Points [] = $LastXPos + $this->GArea_X1; $Points [] = $LastYPos2 + $this->GArea_Y1; $Points [] = $XPos + $this->GArea_X1; $Points [] = $YPos2 + $this->GArea_Y1; $Points [] = $XPos + $this->GArea_X1; $Points [] = $YPos1 + $this->GArea_Y1; $this->canvas->drawFilledPolygon( $Points, 4, $color, $Alpha ); } $LastYPos1 = $YPos1; $LastYPos2 = $YPos2; $LastXPos = $XPos; $XPos = $XPos + $this->DivisionWidth; } } /** * This function write the values of the specified series */ function writeValues($Data, $DataDescription, $Series) { /* Validate the Data and DataDescription array */ $this->validateDataDescription("writeValues", $DataDescription); $this->validateData("writeValues", $Data); if(!is_array($Series)) { $Series = array($Series); } foreach($Series as $Serie) { $ColorID = $DataDescription->getColumnIndex($Serie); $XPos = $this->GArea_X1 + $this->GAreaXOffset; foreach($Data as $Values) { if(isset ($Values[$Serie]) && is_numeric($Values[$Serie])) { $Value = $Values[$Serie]; $YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio); $Positions = imagettfbbox($this->FontSize, 0, $this->FontName, $Value); $Width = $Positions [2] - $Positions [6]; $XOffset = $XPos - ($Width / 2); $YOffset = $YPos - 4; $this->canvas->drawText( $this->FontSize, 0, new Point($XOffset, $YOffset), $this->palette->getColor($ColorID), $this->FontName, $Value, ShadowProperties::NoShadow() ); } $XPos = $XPos + $this->DivisionWidth; } } } /** * @brief Draws a line graph where the data gives Y values for a * series of regular positions along the X axis */ function drawLineGraph($Data, $DataDescription, $SerieName = "") { /* Validate the Data and DataDescription array */ $this->validateDataDescription("drawLineGraph", $DataDescription); $this->validateData("drawLineGraph", $Data); $GraphID = 0; foreach($DataDescription->values as $ColName) { $ColorID = $DataDescription->getColumnIndex($ColName); if($SerieName == "" || $SerieName == $ColName) { $XPos = $this->GArea_X1 + $this->GAreaXOffset; $XLast = -1; $YLast = 0; foreach($Data as $Values) { if(isset ($Values[$ColName])) { $Value = $Values[$ColName]; $YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio); /* Save point into the image map if option activated */ if($this->BuildMap) $this->addToImageMap($XPos - 3, $YPos - 3, $XPos + 3, $YPos + 3, $DataDescription->description[$ColName], $Values[$ColName].$DataDescription->getYUnit(), "Line"); if(!is_numeric($Value)) { $XLast = -1; } if($XLast != -1) $this->canvas->drawLine( new Point($XLast, $YLast), new Point($XPos, $YPos), $this->palette->getColor($ColorID), $this->LineWidth, $this->LineDotSize, $this->shadowProperties, new Point($this->GArea_X1, $this->GArea_Y1), new Point($this->GArea_X2, $this->GArea_Y2) ); $XLast = $XPos; $YLast = $YPos; if(!is_numeric($Value)) { $XLast = -1; } } $XPos = $XPos + $this->DivisionWidth; } $GraphID++; } } } /** * @brief Draws a line graph where one series of data defines the * X position and another the Y position */ function drawXYGraph($Data, $YSerieName, $XSerieName, $PaletteID = 0) { $graphAreaMin = new Point($this->GArea_X1, $this->GArea_Y1); $graphAreaMax = new Point($this->GArea_X2, $this->GArea_Y2); $lastPoint = null; foreach($Data as $Values) { if(isset ($Values[$YSerieName]) && isset ($Values[$XSerieName])) { $X = $Values[$XSerieName]; $Y = $Values[$YSerieName]; $Y = $this->GArea_Y2 - (($Y - $this->VMin) * $this->DivisionRatio); $X = $this->GArea_X1 + (($X - $this->VXMin) * $this->XDivisionRatio); $currentPoint = new Point($X, $Y); if($lastPoint != null) { $this->canvas->drawLine( $lastPoint, $currentPoint, $this->palette->getColor($PaletteID), $this->LineWidth, $this->LineDotSize, $this->shadowProperties, $graphAreaMin, $graphAreaMax ); } $lastPoint = $currentPoint; } } } /** * This function draw a cubic curve */ function drawCubicCurve(pData $data, $Accuracy = .1, $SerieName = "") { /* Validate the Data and DataDescription array */ $this->validateDataDescription( "drawCubicCurve", $data->getDataDescription() ); $this->validateData("drawCubicCurve", $data->getData()); $graphAreaMin = new Point($this->GArea_X1, $this->GArea_Y1); $graphAreaMax = new Point($this->GArea_X2, $this->GArea_Y2); $GraphID = 0; foreach($data->getDataDescription()->values as $ColName) { if($SerieName == "" || $SerieName == $ColName) { /** @todo The next section of code has been duplicated by * copy & paste */ $XIn = array(); $YIn = array(); $Yt = ""; $U = ""; $ColorID = $data->getDataDescription()->getColumnIndex($ColName); $Index = 1; $XLast = -1; $YLast = 0; $Missing = array(); $data->getXYMap($ColName, $XIn, $YIn, $Missing, $Index); assert(count($XIn) == count($YIn)); assert($Index + 1 >= count($XIn)); $Yt [0] = 0; $Yt [1] = 0; $U [1] = 0; $this->calculateCubicCurve($Yt, $XIn, $YIn, $U, $Index); $Yt [$Index] = 0; for($k = $Index - 1; $k >= 1; $k--) $Yt [$k] = $Yt [$k] * $Yt [$k + 1] + $U [$k]; $XPos = $this->GArea_X1 + $this->GAreaXOffset; for($X = 1; $X <= $Index; $X = $X + $Accuracy) { /* I believe here we're searching for the integral * value k such that $X lies between $XIn[k] and * $XIn[k-1] */ $klo = 1; $khi = $Index; $k = $khi - $klo; while($k > 1) { $k = $khi - $klo; If($XIn [$k] >= $X) $khi = $k; else $klo = $k; } $klo = $khi - 1; /* These assertions are to check my understanding * of the code. If they fail, it is my fault and * not a bug */ assert($khi = $klo + 1); assert($XIn[$klo] < $X); assert($X <= $XIn[$khi]); $h = $XIn [$khi] - $XIn [$klo]; $a = ($XIn [$khi] - $X) / $h; $b = ($X - $XIn [$klo]) / $h; /** * I believe this is the actual cubic Bezier * calculation. In parametric form: * * B(t) = (1-t)^3 * B0 * + 3 (1-t)^2 * t * B1 * + 3 (1-t) * t^2 * B2 * + t^3 B3 */ $Value = $a * $YIn [$klo] + $b * $YIn [$khi] + (($a * $a * $a - $a) * $Yt [$klo] + ($b * $b * $b - $b) * $Yt [$khi]) * ($h * $h) / 6; $YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio); if($XLast != -1 && !isset ($Missing [floor($X)]) && !isset ($Missing [floor($X + 1)])) $this->canvas->drawLine( new Point($XLast, $YLast), new Point($XPos, $YPos), $this->palette->getColor($ColorID), $this->LineWidth, $this->LineDotSize, $this->shadowProperties, $graphAreaMin, $graphAreaMax ); $XLast = $XPos; $YLast = $YPos; $XPos = $XPos + $this->DivisionWidth * $Accuracy; } // Add potentialy missing values $XPos = $XPos - $this->DivisionWidth * $Accuracy; if($XPos < ($this->GArea_X2 - $this->GAreaXOffset)) { $YPos = $this->GArea_Y2 - (($YIn [$Index] - $this->VMin) * $this->DivisionRatio); $this->canvas->drawLine( new Point($XLast, $YLast), new Point($this->GArea_X2 - $this->GAreaXOffset, $YPos), $this->palette->getColor($ColorID), $this->LineWidth, $this->LineDotSize, $this->shadowProperties, $graphAreaMin, $graphAreaMax ); } $GraphID++; } } } /** * @todo I haven't figured out exactly what this bit of code does, * it's just an attempt to reduce code duplication */ private function calculateCubicCurve(array & $Yt, array $XIn, array $YIn, array & $U, $Index) { for($i = 2; $i <= $Index - 1; $i++) { /* Typically $Sig will be 0.5, since each X value will be * one unit past the last. If there is missing data then * this ratio will change */ $Sig = ($XIn [$i] - $XIn [$i - 1]) / ($XIn [$i + 1] - $XIn [$i - 1]); $p = $Sig * $Yt [$i - 1] + 2; /* This Y value will nearly always be negative, thanks to * $Sig being 0.5 */ $Yt [$i] = ($Sig - 1) / $p; /** @todo No idea what the following code is doing */ $U [$i] = ($YIn [$i + 1] - $YIn [$i]) / ($XIn [$i + 1] - $XIn [$i]) - ($YIn [$i] - $YIn [$i - 1]) / ($XIn [$i] - $XIn [$i - 1]); $U [$i] = (6 * $U [$i] / ($XIn [$i + 1] - $XIn [$i - 1]) - $Sig * $U [$i - 1]) / $p; } } /** * This function draw a filled cubic curve */ function drawFilledCubicCurve(pData $data, $Accuracy = .1, $Alpha = 100, $AroundZero = FALSE) { /* Validate the Data and DataDescription array */ $this->validateDataDescription( "drawFilledCubicCurve", $data->getDataDescription() ); $this->validateData("drawFilledCubicCurve", $data->getData()); $LayerWidth = $this->GArea_X2 - $this->GArea_X1; $LayerHeight = $this->GArea_Y2 - $this->GArea_Y1; $YZero = $LayerHeight - ((0 - $this->VMin) * $this->DivisionRatio); if($YZero > $LayerHeight) { $YZero = $LayerHeight; } $GraphID = 0; foreach($data->getDataDescription()->values as $ColName) { $XIn = array(); $YIn = array(); $Yt = array(); $U = array(); $ColorID = $data->getDataDescription()->getColumnIndex($ColName); $numElements = 1; $XLast = -1; $Missing = array(); $data->getXYMap($ColName, $XIn, $YIn, $Missing, $numElements); $Yt [0] = 0; $Yt [1] = 0; $U [1] = 0; $this->calculateCubicCurve($Yt, $XIn, $YIn, $U, $numElements); $Yt [$numElements] = 0; for($k = $numElements - 1; $k >= 1; $k--) $Yt [$k] = $Yt [$k] * $Yt [$k + 1] + $U [$k]; $Points = ""; $Points [] = $this->GAreaXOffset + $this->GArea_X1; $Points [] = $LayerHeight + $this->GArea_Y1; $YLast = NULL; $XPos = $this->GAreaXOffset; $PointsCount = 2; for($X = 1; $X <= $numElements; $X = $X + $Accuracy) { $klo = 1; $khi = $numElements; $k = $khi - $klo; while($k > 1) { $k = $khi - $klo; If($XIn [$k] >= $X) $khi = $k; else $klo = $k; } $klo = $khi - 1; $h = $XIn [$khi] - $XIn [$klo]; $a = ($XIn [$khi] - $X) / $h; $b = ($X - $XIn [$klo]) / $h; $Value = $a * $YIn [$klo] + $b * $YIn [$khi] + (($a * $a * $a - $a) * $Yt [$klo] + ($b * $b * $b - $b) * $Yt [$khi]) * ($h * $h) / 6; $YPos = $LayerHeight - (($Value - $this->VMin) * $this->DivisionRatio); if($YLast != NULL && $AroundZero && !isset ($Missing [floor($X)]) && !isset ($Missing [floor($X + 1)])) { $aPoints = ""; $aPoints [] = $XLast + $this->GArea_X1; $aPoints [] = min($YLast + $this->GArea_Y1, $this->GArea_Y2); $aPoints [] = $XPos + $this->GArea_X1; $aPoints [] = min($YPos + $this->GArea_Y1, $this->GArea_Y2); $aPoints [] = $XPos + $this->GArea_X1; $aPoints [] = $YZero + $this->GArea_Y1; $aPoints [] = $XLast + $this->GArea_X1; $aPoints [] = $YZero + $this->GArea_Y1; $this->canvas->drawFilledPolygon( $aPoints, 4, $this->palette->getColor($ColorID), $alpha ); } if(!isset ($Missing [floor($X)]) || $YLast == NULL) { $PointsCount++; $Points [] = $XPos + $this->GArea_X1; $Points [] = min($YPos + $this->GArea_Y1, $this->GArea_Y2); } else { $PointsCount++; $Points [] = $XLast + $this->GArea_X1; $Points [] = min( $LayerHeight + $this->GArea_Y1, $this->GArea_Y2 ); ; } $YLast = $YPos; $XLast = $XPos; $XPos = $XPos + $this->DivisionWidth * $Accuracy; } // Add potentialy missing values $XPos = $XPos - $this->DivisionWidth * $Accuracy; if($XPos < ($LayerWidth - $this->GAreaXOffset)) { $YPos = $LayerHeight - (($YIn [$numElements] - $this->VMin) * $this->DivisionRatio); if($YLast != NULL && $AroundZero) { $aPoints = ""; $aPoints [] = $XLast + $this->GArea_X1; $aPoints [] = max($YLast + $this->GArea_Y1, $this->GArea_Y1); $aPoints [] = $LayerWidth - $this->GAreaXOffset + $this->GArea_X1; $aPoints [] = max($YPos + $this->GArea_Y1, $this->GArea_Y1); $aPoints [] = $LayerWidth - $this->GAreaXOffset + $this->GArea_X1; $aPoints [] = max($YZero + $this->GArea_Y1, $this->GArea_Y1); $aPoints [] = $XLast + $this->GArea_X1; $aPoints [] = max($YZero + $this->GArea_Y1, $this->GArea_Y1); $this->canvas->drawFilledPolygon( $aPoints, 4, $this->palette->getColor($ColorID), $alpha ); } if($YIn [$klo] != "" && $YIn [$khi] != "" || $YLast == NULL) { $PointsCount++; $Points [] = $LayerWidth - $this->GAreaXOffset + $this->GArea_X1; $Points [] = $YPos + $this->GArea_Y1; } } $Points [] = $LayerWidth - $this->GAreaXOffset + $this->GArea_X1; $Points [] = $LayerHeight + $this->GArea_Y1; if(!$AroundZero) { $this->canvas->drawFilledPolygon( $Points, $PointsCount, $this->palette->getColor($ColorID), $Alpha ); } $this->drawCubicCurve($data, $Accuracy, $ColName); $GraphID++; } } /** * This function draw a filled line graph */ function drawFilledLineGraph($Data, $DataDescription, $Alpha = 100, $AroundZero = FALSE) { $Empty = -2147483647; /* Validate the Data and DataDescription array */ $this->validateDataDescription("drawFilledLineGraph", $DataDescription); $this->validateData("drawFilledLineGraph", $Data); $LayerWidth = $this->GArea_X2 - $this->GArea_X1; $LayerHeight = $this->GArea_Y2 - $this->GArea_Y1; $GraphID = 0; foreach($DataDescription->values as $ColName) { $ColorID = $DataDescription->getColumnIndex($ColName); $aPoints = array(); $aPoints [] = $this->GAreaXOffset + $this->GArea_X1; $aPoints [] = $LayerHeight + $this->GArea_Y1; $XPos = $this->GAreaXOffset; $XLast = -1; $PointsCount = 2; $YZero = $LayerHeight - ((0 - $this->VMin) * $this->DivisionRatio); if($YZero > $LayerHeight) { $YZero = $LayerHeight; } $YLast = $Empty; foreach(array_keys($Data) as $Key) { $Value = $Data [$Key] [$ColName]; $YPos = $LayerHeight - (($Value - $this->VMin) * $this->DivisionRatio); /* Save point into the image map if option activated */ if($this->BuildMap) $this->addToImageMap($XPos - 3, $YPos - 3, $XPos + 3, $YPos + 3, $DataDescription->description[$ColName], $Data [$Key] [$ColName].$DataDescription->getYUnit(), "FLine"); if(!is_numeric($Value)) { $PointsCount++; $aPoints [] = $XLast + $this->GArea_X1; $aPoints [] = $LayerHeight + $this->GArea_Y1; $YLast = $Empty; } else { $PointsCount++; if($YLast != $Empty) { $aPoints [] = $XPos + $this->GArea_X1; $aPoints [] = $YPos + $this->GArea_Y1; } else { $PointsCount++; $aPoints [] = $XPos + $this->GArea_X1; $aPoints [] = $LayerHeight + $this->GArea_Y1; $aPoints [] = $XPos + $this->GArea_X1; $aPoints [] = $YPos + $this->GArea_Y1; } if($YLast != $Empty && $AroundZero) { $Points = ""; $Points [] = $XLast + $this->GArea_X1; $Points [] = $YLast + $this->GArea_Y1; $Points [] = $XPos + $this->GArea_X1; $Points [] = $YPos + $this->GArea_Y1; $Points [] = $XPos + $this->GArea_X1; $Points [] = $YZero + $this->GArea_Y1; $Points [] = $XLast + $this->GArea_X1; $Points [] = $YZero + $this->GArea_Y1; $this->canvas->drawFilledPolygon( $Points, 4, $this->palette->getColor($ColorID), $Alpha ); } $YLast = $YPos; } $XLast = $XPos; $XPos = $XPos + $this->DivisionWidth; } $aPoints [] = $LayerWidth - $this->GAreaXOffset + $this->GArea_X1; $aPoints [] = $LayerHeight + $this->GArea_Y1; if($AroundZero == FALSE) { $this->canvas->drawFilledPolygon( $aPoints, $PointsCount, $this->palette->getColor($ColorID), $Alpha ); } $GraphID++; $this->drawLineGraph($Data, $DataDescription, $ColName); } } /** * This function draws a bar graph */ function drawOverlayBarGraph($Data, $DataDescription, $Alpha = 50) { /* Validate the Data and DataDescription array */ $this->validateDataDescription("drawOverlayBarGraph", $DataDescription); $this->validateData("drawOverlayBarGraph", $Data); $LayerHeight = $this->GArea_Y2 - $this->GArea_Y1; $GraphID = 0; foreach($DataDescription->values as $ColName) { $ColorID = $DataDescription->getColumnIndex($ColName); $XWidth = $this->DivisionWidth / 4; $XPos = $this->GAreaXOffset; $YZero = $LayerHeight - ((0 - $this->VMin) * $this->DivisionRatio); foreach(array_keys($Data) as $Key) { if(isset ($Data [$Key] [$ColName])) { $Value = $Data [$Key] [$ColName]; if(is_numeric($Value)) { $YPos = $LayerHeight - (($Value - $this->VMin) * $this->DivisionRatio); $this->canvas->drawFilledRectangle( new Point(floor($XPos - $XWidth + $this->GArea_X1), floor($YPos + $this->GArea_Y1)), new Point(floor($XPos + $XWidth + $this->GArea_X1), floor($YZero + $this->GArea_Y1)), $this->palette->getColor($GraphID), ShadowProperties::NoShadow(), false, $Alpha ); $X1 = floor($XPos - $XWidth + $this->GArea_X1); $Y1 = floor($YPos + $this->GArea_Y1) + .2; $X2 = floor($XPos + $XWidth + $this->GArea_X1); $Y2 = $this->GArea_Y2 - ((0 - $this->VMin) * $this->DivisionRatio); if($X1 <= $this->GArea_X1) { $X1 = $this->GArea_X1 + 1; } if($X2 >= $this->GArea_X2) { $X2 = $this->GArea_X2 - 1; } /* Save point into the image map if option activated */ if($this->BuildMap) $this->addToImageMap($X1, min($Y1, $Y2), $X2, max($Y1, $Y2), $DataDescription->description[$ColName], $Data [$Key] [$ColName].$DataDescription->getYUnit(), "oBar"); $this->canvas->drawLine( new Point($X1, $Y1), new Point($X2, $Y1), $this->palette->getColor($ColorID), $this->LineWidth, $this->LineDotSize, $this->shadowProperties, new Point($this->GArea_X1, $this->GArea_Y1), new Point($this->GArea_X2, $this->GArea_Y2) ); } } $XPos = $XPos + $this->DivisionWidth; } $GraphID++; } } /** * This function draw a bar graph */ function drawBarGraph($Data, $DataDescription, $Alpha = 100) { /* Validate the Data and DataDescription array */ $this->validateDataDescription("drawBarGraph", $DataDescription); $this->validateData("drawBarGraph", $Data); $Series = count($DataDescription->values); $SeriesWidth = $this->DivisionWidth / ($Series + 1); $SerieXOffset = $this->DivisionWidth / 2 - $SeriesWidth / 2; $YZero = $this->GArea_Y2 - ((0 - $this->VMin) * $this->DivisionRatio); if($YZero > $this->GArea_Y2) { $YZero = $this->GArea_Y2; } $SerieID = 0; foreach($DataDescription->values as $ColName) { $ColorID = $DataDescription->getColumnIndex($ColName); $XPos = $this->GArea_X1 + $this->GAreaXOffset - $SerieXOffset + $SeriesWidth * $SerieID; foreach(array_keys($Data) as $Key) { if(isset ($Data [$Key] [$ColName])) { if(is_numeric($Data [$Key] [$ColName])) { $Value = $Data [$Key] [$ColName]; $YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio); /* Save point into the image map if option activated */ if($this->BuildMap) { $this->addToImageMap($XPos + 1, min($YZero, $YPos), $XPos + $SeriesWidth - 1, max($YZero, $YPos), $DataDescription->description[$ColName], $Data [$Key] [$ColName].$DataDescription->getYUnit(), "Bar"); } if($Alpha == 100) { $this->canvas->drawRectangle( new Point($XPos + 1, $YZero), new Point($XPos + $SeriesWidth - 1, $YPos), new Color(25, 25, 25), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); } $this->canvas->drawFilledRectangle( new Point($XPos + 1, $YZero), new Point($XPos + $SeriesWidth - 1, $YPos), $this->palette->getColor($ColorID), $this->shadowProperties, TRUE, $Alpha ); } } $XPos = $XPos + $this->DivisionWidth; } $SerieID++; } } /** * This function draw a stacked bar graph */ function drawStackedBarGraph($Data, $DataDescription, $Alpha = 50, $Contiguous = FALSE) { /* Validate the Data and DataDescription array */ $this->validateDataDescription("drawBarGraph", $DataDescription); $this->validateData("drawBarGraph", $Data); if($Contiguous) $SeriesWidth = $this->DivisionWidth; else $SeriesWidth = $this->DivisionWidth * .8; $YZero = $this->GArea_Y2 - ((0 - $this->VMin) * $this->DivisionRatio); if($YZero > $this->GArea_Y2) { $YZero = $this->GArea_Y2; } $SerieID = 0; $LastValue = ""; foreach($DataDescription->values as $ColName) { $ColorID = $DataDescription->getColumnIndex($ColName); $XPos = $this->GArea_X1 + $this->GAreaXOffset - $SeriesWidth / 2; foreach(array_keys($Data) as $Key) { if(isset ($Data [$Key] [$ColName])) { if(is_numeric($Data [$Key] [$ColName])) { $Value = $Data [$Key] [$ColName]; if(isset ($LastValue [$Key])) { $YPos = $this->GArea_Y2 - ((($Value + $LastValue [$Key]) - $this->VMin) * $this->DivisionRatio); $YBottom = $this->GArea_Y2 - (($LastValue [$Key] - $this->VMin) * $this->DivisionRatio); $LastValue [$Key] += $Value; } else { $YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio); $YBottom = $YZero; $LastValue [$Key] = $Value; } /* Save point into the image map if option activated */ if($this->BuildMap) $this->addToImageMap($XPos + 1, min($YBottom, $YPos), $XPos + $SeriesWidth - 1, max($YBottom, $YPos), $DataDescription->description[$ColName], $Data [$Key] [$ColName].$DataDescription->getYUnit(), "sBar"); $this->canvas->drawFilledRectangle( new Point($XPos + 1, $YBottom), new Point($XPos + $SeriesWidth - 1, $YPos), $this->palette->getColor($ColorID), $this->shadowProperties, TRUE, $Alpha ); } } $XPos = $XPos + $this->DivisionWidth; } $SerieID++; } } /** * This function draw a limits bar graphs */ function drawLimitsGraph($Data, $DataDescription, Color $color = null) { if($color == null) { $color = new Color(0, 0, 0); } /* Validate the Data and DataDescription array */ $this->validateDataDescription("drawLimitsGraph", $DataDescription); $this->validateData("drawLimitsGraph", $Data); $XWidth = $this->DivisionWidth / 4; $XPos = $this->GArea_X1 + $this->GAreaXOffset; $graphAreaMin = new Point($this->GArea_X1, $this->GArea_Y1); $graphAreaMax = new Point($this->GArea_X2, $this->GArea_Y2); foreach(array_keys($Data) as $Key) { $Min = $Data [$Key] [$DataDescription->values[0]]; $Max = $Data [$Key] [$DataDescription->values[0]]; $GraphID = 0; $MaxID = 0; $MinID = 0; foreach($DataDescription->values as $ColName) { if(isset ($Data [$Key] [$ColName])) { if($Data [$Key] [$ColName] > $Max && is_numeric($Data [$Key] [$ColName])) { $Max = $Data [$Key] [$ColName]; $MaxID = $GraphID; } } if(isset ($Data [$Key] [$ColName]) && is_numeric($Data [$Key] [$ColName])) { if($Data [$Key] [$ColName] < $Min) { $Min = $Data [$Key] [$ColName]; $MinID = $GraphID; } $GraphID++; } } $YPos = $this->GArea_Y2 - (($Max - $this->VMin) * $this->DivisionRatio); $X1 = floor($XPos - $XWidth); $Y1 = floor($YPos) - .2; $X2 = floor($XPos + $XWidth); if($X1 <= $this->GArea_X1) { $X1 = $this->GArea_X1 + 1; } if($X2 >= $this->GArea_X2) { $X2 = $this->GArea_X2 - 1; } $YPos = $this->GArea_Y2 - (($Min - $this->VMin) * $this->DivisionRatio); $Y2 = floor($YPos) + .2; $this->canvas->drawLine( new Point(floor($XPos) - .2, $Y1 + 1), new Point(floor($XPos) - .2, $Y2 - 1), $color, $this->LineWidth, $this->LineDotSize, $this->shadowProperties, $graphAreaMin, $graphAreaMax ); $this->canvas->drawLine( new Point(floor($XPos) + .2, $Y1 + 1), new Point(floor($XPos) + .2, $Y2 - 1), $color, $this->LineWidth, $this->LineDotSize, $this->shadowProperties, $graphAreaMin, $graphAreaMax ); $this->canvas->drawLine( new Point($X1, $Y1), new Point($X2, $Y1), $this->palette->getColor($MaxID), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $this->canvas->drawLine( new Point($X1, $Y2), new Point($X2, $Y2), $this->palette->getColor($MinID), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $XPos = $XPos + $this->DivisionWidth; } } /** * This function draw radar axis centered on the graph area */ function drawRadarAxis($Data, $DataDescription, $Mosaic = TRUE, $BorderOffset = 10, Color $colorA = null, Color $colorS = null, $MaxValue = -1) { if($colorA == null) { $colorA = new Color(60, 60, 60); } if($colorS == null) { $colorS = new Color(200, 200, 200); } /* Validate the Data and DataDescription array */ $this->validateDataDescription("drawRadarAxis", $DataDescription); $this->validateData("drawRadarAxis", $Data); /* Draw radar axis */ $Points = count($Data); $Radius = ($this->GArea_Y2 - $this->GArea_Y1) / 2 - $BorderOffset; $XCenter = ($this->GArea_X2 - $this->GArea_X1) / 2 + $this->GArea_X1; $YCenter = ($this->GArea_Y2 - $this->GArea_Y1) / 2 + $this->GArea_Y1; /* Search for the max value */ if($MaxValue == -1) { foreach($DataDescription->values as $ColName) { foreach(array_keys($Data) as $Key) { if(isset ($Data [$Key] [$ColName])) if($Data [$Key] [$ColName] > $MaxValue) { $MaxValue = $Data [$Key] [$ColName]; } } } } $LastX2 = 0; $LastY1 = 0; $LastY2 = 0; /* Draw the mosaic */ if($Mosaic) { $RadiusScale = $Radius / $MaxValue; for($t = 1; $t <= $MaxValue - 1; $t++) { $TRadius = $RadiusScale * $t; $LastX1 = -1; for($i = 0; $i <= $Points; $i++) { $Angle = -90 + $i * 360 / $Points; $X1 = cos($Angle * M_PI / 180) * $TRadius + $XCenter; $Y1 = sin($Angle * M_PI / 180) * $TRadius + $YCenter; $X2 = cos($Angle * M_PI / 180) * ($TRadius + $RadiusScale) + $XCenter; $Y2 = sin($Angle * M_PI / 180) * ($TRadius + $RadiusScale) + $YCenter; if($t % 2 == 1 && $LastX1 != -1) { $Plots = ""; $Plots [] = $X1; $Plots [] = $Y1; $Plots [] = $X2; $Plots [] = $Y2; $Plots [] = $LastX2; $Plots [] = $LastY2; $Plots [] = $LastX1; $Plots [] = $LastY1; $this->canvas->drawFilledPolygon( $Plots, (count($Plots) + 1) / 2, new Color(250, 250, 250) ); } $LastX1 = $X1; $LastY1 = $Y1; $LastX2 = $X2; $LastY2 = $Y2; } } } /* Draw the spider web */ $LastY = 0; for($t = 1; $t <= $MaxValue; $t++) { $TRadius = ($Radius / $MaxValue) * $t; $LastX = -1; for($i = 0; $i <= $Points; $i++) { $Angle = -90 + $i * 360 / $Points; $X = cos($Angle * M_PI / 180) * $TRadius + $XCenter; $Y = sin($Angle * M_PI / 180) * $TRadius + $YCenter; if($LastX != -1) $this->canvas->drawDottedLine( new Point($LastX, $LastY), new Point($X, $Y), 4, 1, $colorS, $this->shadowProperties ); $LastX = $X; $LastY = $Y; } } /* Draw the axis */ for($i = 0; $i <= $Points; $i++) { $Angle = -90 + $i * 360 / $Points; $X = cos($Angle * M_PI / 180) * $Radius + $XCenter; $Y = sin($Angle * M_PI / 180) * $Radius + $YCenter; $this->canvas->drawLine( new Point($XCenter, $YCenter), new Point($X, $Y), $colorA, $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $XOffset = 0; $YOffset = 0; if(isset ($Data [$i] [$DataDescription->getPosition()])) { $Label = $Data [$i] [$DataDescription->getPosition()]; $Positions = imagettfbbox($this->FontSize, 0, $this->FontName, $Label); $Width = $Positions [2] - $Positions [6]; $Height = $Positions [3] - $Positions [7]; if($Angle >= 0 && $Angle <= 90) $YOffset = $Height; if($Angle > 90 && $Angle <= 180) { $YOffset = $Height; $XOffset = -$Width; } if($Angle > 180 && $Angle <= 270) { $XOffset = -$Width; } $this->canvas->drawText( $this->FontSize, 0, new Point($X + $XOffset, $Y + $YOffset), $colorA, $this->FontName, $Label, ShadowProperties::NoShadow() ); } } /* Write the values */ for($t = 1; $t <= $MaxValue; $t++) { $TRadius = ($Radius / $MaxValue) * $t; $Angle = -90 + 360 / $Points; $X1 = $XCenter; $Y1 = $YCenter - $TRadius; $X2 = cos($Angle * M_PI / 180) * $TRadius + $XCenter; $Y2 = sin($Angle * M_PI / 180) * $TRadius + $YCenter; $XPos = floor(($X2 - $X1) / 2) + $X1; $YPos = floor(($Y2 - $Y1) / 2) + $Y1; $Positions = imagettfbbox($this->FontSize, 0, $this->FontName, $t); $X = $XPos - ($X + $Positions [2] - $X + $Positions [6]) / 2; $Y = $YPos + $this->FontSize; $this->canvas->drawFilledRoundedRectangle( new Point($X + $Positions [6] - 2, $Y + $Positions [7] - 1), new Point($X + $Positions [2] + 4, $Y + $Positions [3] + 1), 2, new Color(240, 240, 240), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $this->canvas->drawRoundedRectangle( new Point($X + $Positions [6] - 2, $Y + $Positions [7] - 1), new Point($X + $Positions [2] + 4, $Y + $Positions [3] + 1), 2, new Color(220, 220, 220), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $this->canvas->drawText( $this->FontSize, 0, new Point($X, $Y), $colorA, $this->FontName, $t, ShadowProperties::NoShadow() ); } } private function calculateMaxValue($Data, $DataDescription) { $MaxValue = -1; foreach($DataDescription->values as $ColName) { foreach(array_keys($Data) as $Key) { if(isset ($Data [$Key] [$ColName])) if($Data [$Key] [$ColName] > $MaxValue && is_numeric($Data[$Key][$ColName])) { $MaxValue = $Data [$Key] [$ColName]; } } } return $MaxValue; } /** * This function draw a radar graph centered on the graph area */ function drawRadar($Data, $DataDescription, $BorderOffset = 10, $MaxValue = -1) { /* Validate the Data and DataDescription array */ $this->validateDataDescription("drawRadar", $DataDescription); $this->validateData("drawRadar", $Data); $Points = count($Data); $Radius = ($this->GArea_Y2 - $this->GArea_Y1) / 2 - $BorderOffset; $XCenter = ($this->GArea_X2 - $this->GArea_X1) / 2 + $this->GArea_X1; $YCenter = ($this->GArea_Y2 - $this->GArea_Y1) / 2 + $this->GArea_Y1; /* Search for the max value */ if($MaxValue == -1) { $MaxValue = $this->calculateMaxValue($Data, $DataDescription); } $GraphID = 0; $YLast = 0; foreach($DataDescription->values as $ColName) { $ColorID = $DataDescription->getColumnIndex($ColName); $Angle = -90; $XLast = -1; foreach(array_keys($Data) as $Key) { if(isset ($Data [$Key] [$ColName])) { $Value = $Data [$Key] [$ColName]; $Strength = ($Radius / $MaxValue) * $Value; $XPos = cos($Angle * M_PI / 180) * $Strength + $XCenter; $YPos = sin($Angle * M_PI / 180) * $Strength + $YCenter; if($XLast != -1) $this->canvas->drawLine( new Point($XLast, $YLast), new Point($XPos, $YPos), $this->palette->getColor($ColorID), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); if($XLast == -1) { $FirstX = $XPos; $FirstY = $YPos; } $Angle = $Angle + (360 / $Points); $XLast = $XPos; $YLast = $YPos; } } $this->canvas->drawLine( new Point($XPos, $YPos), new Point($FirstX, $FirstY), $this->palette->getColor($ColorID), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $GraphID++; } } /** * This function draw a radar graph centered on the graph area */ function drawFilledRadar($Data, $DataDescription, $Alpha = 50, $BorderOffset = 10, $MaxValue = -1) { /* Validate the Data and DataDescription array */ $this->validateDataDescription("drawFilledRadar", $DataDescription); $this->validateData("drawFilledRadar", $Data); $Points = count($Data); $Radius = ($this->GArea_Y2 - $this->GArea_Y1) / 2 - $BorderOffset; $XCenter = ($this->GArea_X2 - $this->GArea_X1) / 2; $YCenter = ($this->GArea_Y2 - $this->GArea_Y1) / 2; /* Search for the max value */ if($MaxValue == -1) { $MaxValue = $this->calculateMaxValue($Data, $DataDescription); } $GraphID = 0; foreach($DataDescription->values as $ColName) { $ColorID = $DataDescription->getColumnIndex($ColName); $Angle = -90; $XLast = -1; $Plots = array(); foreach(array_keys($Data) as $Key) { if(isset ($Data [$Key] [$ColName])) { $Value = $Data [$Key] [$ColName]; if(!is_numeric($Value)) { $Value = 0; } $Strength = ($Radius / $MaxValue) * $Value; $XPos = cos($Angle * M_PI / 180) * $Strength + $XCenter; $YPos = sin($Angle * M_PI / 180) * $Strength + $YCenter; $Plots [] = $XPos + $this->GArea_X1; $Plots [] = $YPos + $this->GArea_Y1; $Angle = $Angle + (360 / $Points); $XLast = $XPos; } } if(isset ($Plots [0])) { $Plots [] = $Plots [0]; $Plots [] = $Plots [1]; $this->canvas->drawFilledPolygon( $Plots, (count($Plots) + 1) / 2, $this->palette->getColor($ColorID), $Alpha ); for($i = 0; $i <= count($Plots) - 4; $i = $i + 2) $this->canvas->drawLine( new Point($Plots [$i], $Plots [$i + 1]), new Point($Plots [$i + 2], $Plots [$i + 3]), $this->palette->getColor($ColorID), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); } $GraphID++; } } /** * This function can be used to set the background color */ function drawBackground(Color $color) { $C_Background = $this->canvas->allocateColor($color); imagefilledrectangle($this->canvas->getPicture(), 0, 0, $this->XSize, $this->YSize, $C_Background); } private function drawGradient(Point $point1, Point $point2, Color $color, $decay) { /* Positive gradient */ if($decay > 0) { $YStep = ($point2->getY() - $point1->getY() - 2) / $decay; for($i = 0; $i <= $decay; $i++) { $color = $color->addRGBIncrement(-1); $Yi1 = $point1->getY() + ($i * $YStep); $Yi2 = ceil($Yi1 + ($i * $YStep) + $YStep); if($Yi2 >= $Yi2) { $Yi2 = $point2->getY() - 1; } $this->canvas->drawFilledRectangle( new Point($point1->getX(), $Yi1), new Point($point2->getX(), $Yi2), $color, ShadowProperties::NoShadow() ); } } /* Negative gradient */ if($decay < 0) { $YStep = ($point2->getY() - $point1->getY() - 2) / -$decay; $Yi1 = $point1->getY(); $Yi2 = $point1->getY() + $YStep; for($i = -$decay; $i >= 0; $i--) { $color = $color->addRGBIncrement(1); $this->canvas->drawFilledRectangle( new Point($point1->getX(), $Yi1), new Point($point2->getX(), $Yi2), $color, ShadowProperties::NoShadow() ); $Yi1 += $YStep; $Yi2 += $YStep; if($Yi2 >= $Yi2) { $Yi2 = $point2->getY() - 1; } } } } /** * This function can be used to set the background color */ private function drawGraphAreaGradient(BackgroundStyle $style) { if(!$style->useGradient()) { return; } $this->drawGradient( new Point($this->GArea_X1 + 1, $this->GArea_Y1 + 1), new Point($this->GArea_X2 - 1, $this->GArea_Y2), $style->getGradientStartColor(), $style->getGradientDecay() ); } public function drawBackgroundGradient(Color $color, $decay) { $this->drawGradient( new Point(0, 0), new Point($this->XSize, $this->YSize), $color, $decay ); } /** * This function will draw an ellipse */ function drawEllipse($Xc, $Yc, $Height, $Width, Color $color) { $this->canvas->drawCircle(new Point($Xc, $Yc), $Height, $color, $this->shadowProperties, $Width); } /** * This function will draw a filled ellipse */ function drawFilledEllipse($Xc, $Yc, $Height, $Width, Color $color) { $this->canvas->drawFilledCircle(new Point($Xc, $Yc), $Height, $color, $this->shadowProperties, $Width); } /** * Load a PNG file and draw it over the chart */ function drawFromPNG($FileName, $X, $Y, $Alpha = 100) { $this->drawFromPicture(1, $FileName, $X, $Y, $Alpha); } /** * Load a GIF file and draw it over the chart */ function drawFromGIF($FileName, $X, $Y, $Alpha = 100) { $this->drawFromPicture(2, $FileName, $X, $Y, $Alpha); } /** * Load a JPEG file and draw it over the chart */ function drawFromJPG($FileName, $X, $Y, $Alpha = 100) { $this->drawFromPicture(3, $FileName, $X, $Y, $Alpha); } /** * Generic loader function for external pictures */ function drawFromPicture($PicType, $FileName, $X, $Y, $Alpha = 100) { if(file_exists($FileName)) { $Infos = getimagesize($FileName); $Width = $Infos [0]; $Height = $Infos [1]; if($PicType == 1) { $Raster = imagecreatefrompng($FileName); } if($PicType == 2) { $Raster = imagecreatefromgif($FileName); } if($PicType == 3) { $Raster = imagecreatefromjpeg($FileName); } imagecopymerge($this->canvas->getPicture(), $Raster, $X, $Y, 0, 0, $Width, $Height, $Alpha); imagedestroy($Raster); } } /** * Add a border to the picture * * @todo This hasn't been updated to the new API yet */ function addBorder($Size = 3, $R = 0, $G = 0, $B = 0) { $Width = $this->XSize + 2 * $Size; $Height = $this->YSize + 2 * $Size; $Resampled = imagecreatetruecolor($Width, $Height); $C_Background = imagecolorallocate($Resampled, $R, $G, $B); imagefilledrectangle($Resampled, 0, 0, $Width, $Height, $C_Background); imagecopy($Resampled, $this->canvas->getPicture(), $Size, $Size, 0, 0, $this->XSize, $this->YSize); imagedestroy($this->canvas->getPicture()); $this->XSize = $Width; $this->YSize = $Height; $this->canvas->setPicture(imagecreatetruecolor($this->XSize, $this->YSize)); $C_White = $this->canvas->allocate(new Color(255, 255, 255)); imagefilledrectangle($this->canvas->getPicture(), 0, 0, $this->XSize, $this->YSize, $C_White); imagecolortransparent($this->canvas->getPicture(), $C_White); imagecopy($this->canvas->getPicture(), $Resampled, 0, 0, 0, 0, $this->XSize, $this->YSize); } /** * Render the current picture to a file */ function Render($FileName) { if($this->ErrorReporting) $this->printErrors($this->ErrorInterface); /* Save image map if requested */ if($this->BuildMap) $this->SaveImageMap(); if($FileName) { imagepng($this->canvas->getPicture(), $FileName); } else { imagepng($this->canvas->getPicture()); } } /** * Render the current picture to STDOUT */ function Stroke() { if($this->ErrorReporting) $this->printErrors("GD"); /* Save image map if requested */ if($this->BuildMap) $this->SaveImageMap(); header('Content-type: image/png'); imagepng($this->canvas->getPicture()); } /** * Validate data contained in the description array * * @todo Should this be a method on DataDescription? */ protected function validateDataDescription($FunctionName, DataDescription $DataDescription, $DescriptionRequired = TRUE) { if($DataDescription->getPosition() == '') { $this->Errors [] = "[Warning] ".$FunctionName." - Y Labels are not set."; $DataDescription->setPosition("Name"); } if($DescriptionRequired) { if(!isset ($DataDescription->description)) { $this->Errors [] = "[Warning] ".$FunctionName." - Series descriptions are not set."; foreach($DataDescription->values as $key => $Value) { $DataDescription->description[$Value] = $Value; } } if(count($DataDescription->description) < count($DataDescription->values)) { $this->Errors [] = "[Warning] ".$FunctionName." - Some series descriptions are not set."; foreach($DataDescription->values as $key => $Value) { if(!isset ($DataDescription->description[$Value])) $DataDescription->description[$Value] = $Value; } } } } /** * Validate data contained in the data array */ protected function validateData($FunctionName, $Data) { $DataSummary = array(); foreach($Data as $key => $Values) { foreach($Values as $key2 => $Value) { if(!isset ($DataSummary [$key2])) $DataSummary [$key2] = 1; else $DataSummary [$key2]++; } } if(empty($DataSummary)) $this->Errors [] = "[Warning] ".$FunctionName." - No data set."; foreach($DataSummary as $key => $Value) { if($Value < max($DataSummary)) { $this->Errors [] = "[Warning] ".$FunctionName." - Missing data in serie ".$key."."; } } } /** * Print all error messages on the CLI or graphically */ function printErrors($Mode = "CLI") { if(count($this->Errors) == 0) return (0); if($Mode == "CLI") { foreach($this->Errors as $key => $Value) echo $Value."\r\n"; } elseif($Mode == "GD") { $MaxWidth = 0; foreach($this->Errors as $key => $Value) { $Position = imageftbbox($this->ErrorFontSize, 0, $this->ErrorFontName, $Value); $TextWidth = $Position [2] - $Position [0]; if($TextWidth > $MaxWidth) { $MaxWidth = $TextWidth; } } $this->canvas->drawFilledRoundedRectangle( new Point($this->XSize - ($MaxWidth + 20), $this->YSize - (20 + (($this->ErrorFontSize + 4) * count($this->Errors)))), new Point($this->XSize - 10, $this->YSize - 10), 6, new Color(233, 185, 185), $this->lineWidth, $this->lineDotSize, $this->shadowProperties ); $this->canvas->drawRoundedRectangle( new Point($this->XSize - ($MaxWidth + 20), $this->YSize - (20 + (($this->ErrorFontSize + 4) * count($this->Errors)))), new Point($this->XSize - 10, $this->YSize - 10), 6, new Color(193, 145, 145), $this->LineWidth, $this->LineDotSize, $this->shadowProperties ); $YPos = $this->YSize - (18 + (count($this->Errors) - 1) * ($this->ErrorFontSize + 4)); foreach($this->Errors as $key => $Value) { $this->canvas->drawText( $this->ErrorFontSize, 0, new Point($this->XSize - ($MaxWidth + 15), $YPos), new Color(133, 85, 85), $this->ErrorFontName, $Value, ShadowProperties::NoShadow() ); $YPos = $YPos + ($this->ErrorFontSize + 4); } } } /** * Activate the image map creation process */ function setImageMap($Mode = TRUE, $GraphID = "MyGraph") { $this->BuildMap = $Mode; $this->MapID = $GraphID; } /** * Add a box into the image map */ function addToImageMap($X1, $Y1, $X2, $Y2, $SerieName, $Value, $CallerFunction) { if($this->MapFunction == NULL || $this->MapFunction == $CallerFunction) { $this->ImageMap [] = round($X1).",".round($Y1).",".round($X2).",".round($Y2).",".$SerieName.",".$Value; $this->MapFunction = $CallerFunction; } } /** * Load and cleanup the image map from disk */ function getImageMap($MapName, $Flush = TRUE) { /* Strip HTML query strings */ $Values = $this->tmpFolder.$MapName; $Value = explode("\?", $Values); $FileName = $Value [0]; if(file_exists($FileName)) { $Handle = fopen($FileName, "r"); $MapContent = fread($Handle, filesize($FileName)); fclose($Handle); echo $MapContent; if($Flush) unlink($FileName); exit (); } else { header("HTTP/1.0 404 Not Found"); exit (); } } /** * Save the image map to the disk */ function SaveImageMap() { if(!$this->BuildMap) { return (-1); } if($this->ImageMap == NULL) { $this->Errors [] = "[Warning] SaveImageMap - Image map is empty."; return (-1); } $Handle = fopen($this->tmpFolder.$this->MapID, 'w'); if(!$Handle) { $this->Errors [] = "[Warning] SaveImageMap - Cannot save the image map."; return (-1); } else { foreach($this->ImageMap as $Value) fwrite($Handle, htmlentities($Value)."\r"); } fclose($Handle); } /** * Set date format for axis labels */ function setDateFormat($Format) { $this->DateFormat = $Format; } /** * Convert TS to a date format string */ function ToDate($Value) { return (date($this->DateFormat, $Value)); } /** * Check if a number is a full integer (for scaling) */ static private function isRealInt($Value) { if($Value == floor($Value)) return (TRUE); return (FALSE); } /** * @todo I don't know what this does yet, I'm refactoring... */ public function calculateScales(& $Scale, & $Divisions) { /* Compute automatic scaling */ $ScaleOk = FALSE; $Factor = 1; $MinDivHeight = 25; $MaxDivs = ($this->GArea_Y2 - $this->GArea_Y1) / $MinDivHeight; if($this->VMax <= $this->VMin) { throw new Exception("Impossible to calculate scales when VMax <= VMin"); } if($this->VMin == 0 && $this->VMax == 0) { $this->VMin = 0; $this->VMax = 2; $Scale = 1; $Divisions = 2; } elseif($MaxDivs > 1) { while(!$ScaleOk) { $Scale1 = ($this->VMax - $this->VMin) / $Factor; $Scale2 = ($this->VMax - $this->VMin) / $Factor / 2; if($Scale1 > 1 && $Scale1 <= $MaxDivs && !$ScaleOk) { $ScaleOk = TRUE; $Divisions = floor($Scale1); $Scale = 1; } if($Scale2 > 1 && $Scale2 <= $MaxDivs && !$ScaleOk) { $ScaleOk = TRUE; $Divisions = floor($Scale2); $Scale = 2; } if(!$ScaleOk) { if($Scale2 > 1) { $Factor = $Factor * 10; } if($Scale2 < 1) { $Factor = $Factor / 10; } } } if(floor($this->VMax / $Scale / $Factor) != $this->VMax / $Scale / $Factor) { $GridID = floor($this->VMax / $Scale / $Factor) + 1; $this->VMax = $GridID * $Scale * $Factor; $Divisions++; } if(floor($this->VMin / $Scale / $Factor) != $this->VMin / $Scale / $Factor) { $GridID = floor($this->VMin / $Scale / $Factor); $this->VMin = $GridID * $Scale * $Factor; $Divisions++; } } else /* Can occur for small graphs */ $Scale = 1; } /* * Returns the resource */ public function getPicture() { return $this->canvas->getPicture(); } static private function computeAutomaticScaling($minCoord, $maxCoord, &$minVal, &$maxVal, &$Divisions) { $ScaleOk = FALSE; $Factor = 1; $Scale = 1; $MinDivHeight = 25; $MaxDivs = ($maxCoord - $minCoord) / $MinDivHeight; $minVal = (float) $minVal; $maxVal = (float) $maxVal; // when min and max are the them spread out the value if($minVal == $maxVal) { $ispos = $minVal > 0; $maxVal += $maxVal/2; $minVal -= $minVal/2; if($minVal < 0 && $ispos) $minVal = 0; } if($minVal == 0 && $maxVal == 0) { $minVal = 0; $maxVal = 2; $Divisions = 2; } elseif($MaxDivs > 1) { while(!$ScaleOk) { if($Factor == 0) throw new Exception('Division by zero whne calculating scales (should not happen)'); $Scale1 = ($maxVal - $minVal) / $Factor; $Scale2 = ($maxVal - $minVal) / $Factor / 2; if($Scale1 > 1 && $Scale1 <= $MaxDivs && !$ScaleOk) { $ScaleOk = TRUE; $Divisions = floor($Scale1); $Scale = 1; } if($Scale2 > 1 && $Scale2 <= $MaxDivs && !$ScaleOk) { $ScaleOk = TRUE; $Divisions = floor($Scale2); $Scale = 2; } if(!$ScaleOk) { if($Scale2 >= 1) { $Factor = $Factor * 10.0; } if($Scale2 < 1) { $Factor = $Factor / 10.0; } } } if(floor($maxVal / $Scale / $Factor) != $maxVal / $Scale / $Factor) { $GridID = floor($maxVal / $Scale / $Factor) + 1; $maxVal = $GridID * $Scale * $Factor; $Divisions++; } if(floor($minVal / $Scale / $Factor) != $minVal / $Scale / $Factor) { $GridID = floor($minVal / $Scale / $Factor); $minVal = $GridID * $Scale * $Factor; $Divisions++; } } if(!isset ($Divisions)) { $Divisions = 2; } if(self::isRealInt(($maxVal - $minVal) / ($Divisions - 1))) { $Divisions--; } elseif(self::isRealInt(($maxVal - $minVal) / ($Divisions + 1))) { $Divisions++; } } static private function convertValueForDisplay($value, $format, $unit) { if($format == "number") return $value.$unit; if($format == "time") return ConversionHelpers::ToTime($value); if($format == "date") return date('Y-m-d', $value); //todo: might be wrong, needs to go into converseion helper and needs a test if($format == "metric") return ConversionHelpers::ToMetric($value); if($format == "currency") return ConversionHelpers::ToCurrency($value); } } /** * * @param $Message */ function RaiseFatal($Message) { echo "[FATAL] ".$Message."\r\n"; exit (); }
Lorpotin/Dokuwiki-Gamification
lib/plugins/statistics/inc/pchart/pChart.php
PHP
gpl-2.0
122,890
<?php $french = array( 'gccollab_stats:title' => "Statistiques de GCconnex", 'gccollab_stats:unknown' => "Inconnu", 'gccollab_stats:membercount' => "Membres inscrits", 'gccollab_stats:loading' => "Chargement des données...", 'gccollab_stats:registration:title' => "Inscription des membres", 'gccollab_stats:types:title' => "Types de membres", 'gccollab_stats:federal:title' => "Gouvernement fédéral", 'gccollab_stats:provincial:title' => "Provinciaux/territoriaux", 'gccollab_stats:student:title' => "Étudiants", 'gccollab_stats:academic:title' => "Universitaires", 'gccollab_stats:other:title' => "Autres", 'gccollab_stats:membertype' => "Type de membre", 'gccollab_stats:other' => "Autre membre", 'gccollab_stats:date' => "Date :", 'gccollab_stats:signups' => "Inscriptions :", 'gccollab_stats:total' => "Total :", 'gccollab_stats:users' => "utilisateurs", 'gccollab_stats:department' => "Département", 'gccollab_stats:province' => "Province / Territoire", 'gccollab_stats:wireposts:title' => "Messages sur le fil", 'gccollab_stats:wireposts:amount' => "Nombre de messages sur le fil", 'gccollab_stats:blogposts:title' => "Billets de blogue", 'gccollab_stats:blogposts:amount' => "Nombre de billets de blogue", 'gccollab_stats:comments:title' => "Commentaires", 'gccollab_stats:comments:amount' => "Nombre de commentaires", 'gccollab_stats:groups:label' => "Groupes :", 'gccollab_stats:groups:amount' => "Nombre de groupes", 'gccollab_stats:groupscreated:title' => "Groupes créés", 'gccollab_stats:groupscreated:amount' => "Nombre de groupes créés", 'gccollab_stats:groupsjoined:title' => "Groupes rejoints", 'gccollab_stats:groupsjoined:amount' => "Nombre de groupes rejoints", 'gccollab_stats:likes:title' => "Mentions « j\'aime »", 'gccollab_stats:likes:amount' => "Nombre de mentions « j\'aime »", 'gccollab_stats:messages:title' => "Messages", 'gccollab_stats:messages:amount' => "Nombre de messages", 'gccollab_stats:ministrymessage' => "Cliquez sur les colonnes pour afficher les ministères de la province ou du territoire", 'gccollab_stats:schoolmessage' => "Cliquez sur les colonnes pour afficher les différentes écoles", 'gccollab_stats:zoommessage' => "- Cliquez et glissez pour faire un zoom avant", 'gccollab_stats:pinchmessage' => "Pincer le graphique pour le zoomer", ); add_translation("fr", $french);
pscrevs/gcconnex
mod/gccollab_stats/languages/fr.php
PHP
gpl-2.0
2,506
<?php /** * The Footer widget areas. * * @package ECVET STEP Themes * @subpackage ECVET STEP One * @since ECVET STEP One 1.0 */ ?> <?php /* The footer widget area is triggered if any of the areas * have widgets. So let's check that first. * * If none of the sidebars have widgets, then let's bail early. */ if ( ! is_active_sidebar( 'sidebar-2' ) && ! is_active_sidebar( 'sidebar-3' ) && ! is_active_sidebar( 'sidebar-4' ) && ! is_active_sidebar( 'sidebar-5' ) ) return; // If we get this far, we have widgets. Let do this. ?> <div id="footer-sidebar" class="container"> <div id="supplementary" <?php ecvetstep_footer_sidebar_class(); ?>> <?php if ( is_active_sidebar( 'sidebar-2' ) ) : ?> <div id="first" class="widget-area" role="complementary"> <?php dynamic_sidebar( 'sidebar-2' ); ?> </div><!-- #first .widget-area --> <?php endif; ?> <?php if ( is_active_sidebar( 'sidebar-3' ) ) : ?> <div id="second" class="widget-area" role="complementary"> <?php dynamic_sidebar( 'sidebar-3' ); ?> </div><!-- #second .widget-area --> <?php endif; ?> <?php if ( is_active_sidebar( 'sidebar-4' ) ) : ?> <div id="third" class="widget-area" role="complementary"> <?php dynamic_sidebar( 'sidebar-4' ); ?> </div><!-- #third .widget-area --> <?php endif; ?> <?php if ( is_active_sidebar( 'sidebar-5' ) ) : ?> <div id="fourth" class="widget-area" role="complementary"> <?php dynamic_sidebar( 'sidebar-5' ); ?> </div><!-- #third .widget-area --> <?php endif; ?> </div><!-- #supplementary --> </div><!-- #footer-sidebar -->
EcvetStep/ecvet-step.eu
wp-content/themes/ecvet-step/sidebar-footer.php
PHP
gpl-2.0
1,753
/* Copyright (C) 2008 AbiSource Corporation B.V. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ #include <boost/lexical_cast.hpp> #include "ServiceErrorCodes.h" namespace abicollab { namespace service { SOAP_ERROR error(const soa::SoapFault& fault) { if (!fault.string()) return SOAP_ERROR_GENERIC; try { return static_cast<SOAP_ERROR>(boost::lexical_cast<int>(fault.string()->value())); } catch (boost::bad_lexical_cast&) { return SOAP_ERROR_GENERIC; } } } }
hfiguiere/abiword
plugins/collab/backends/service/xp/ServiceErrorCodes.cpp
C++
gpl-2.0
1,153
<?php namespace Google\AdsApi\AdWords\v201705\cm; /** * This file was generated from WSDL. DO NOT EDIT. */ class ManualCpcBiddingScheme extends \Google\AdsApi\AdWords\v201705\cm\BiddingScheme { /** * @var boolean $enhancedCpcEnabled */ protected $enhancedCpcEnabled = null; /** * @param string $BiddingSchemeType * @param boolean $enhancedCpcEnabled */ public function __construct($BiddingSchemeType = null, $enhancedCpcEnabled = null) { parent::__construct($BiddingSchemeType); $this->enhancedCpcEnabled = $enhancedCpcEnabled; } /** * @return boolean */ public function getEnhancedCpcEnabled() { return $this->enhancedCpcEnabled; } /** * @param boolean $enhancedCpcEnabled * @return \Google\AdsApi\AdWords\v201705\cm\ManualCpcBiddingScheme */ public function setEnhancedCpcEnabled($enhancedCpcEnabled) { $this->enhancedCpcEnabled = $enhancedCpcEnabled; return $this; } }
renshuki/dfp-manager
vendor/googleads/googleads-php-lib/src/Google/AdsApi/AdWords/v201705/cm/ManualCpcBiddingScheme.php
PHP
gpl-2.0
1,018
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006-2007. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #include <boost/interprocess/detail/config_begin.hpp> #include <boost/interprocess/detail/workaround.hpp> #ifdef BOOST_WINDOWS //[doc_windows_shared_memory2 #include <boost/interprocess/windows_shared_memory.hpp> #include <boost/interprocess/mapped_region.hpp> #include <iostream> #include <cstring> int main () { using namespace boost::interprocess; try{ //Open already created shared memory object. windows_shared_memory shm(open_only, "shared_memory", read_only); //Map the whole shared memory in this process mapped_region region (shm, read_only); //Check that memory was initialized to 1 const char *mem = static_cast<char*>(region.get_address()); for(std::size_t i = 0; i < 1000; ++i){ if(*mem++ != 1){ std::cout << "Error checking memory!" << std::endl; return 1; } } std::cout << "Test successful!" << std::endl; } catch(interprocess_exception &ex){ std::cout << "Unexpected exception: " << ex.what() << std::endl; return 1; } return 0; } //] #else //#ifdef BOOST_WINDOWS int main() { return 0; } #endif//#ifdef BOOST_WINDOWS #include <boost/interprocess/detail/config_end.hpp>
scs/uclinux
lib/boost/boost_1_38_0/libs/interprocess/example/doc_windows_shared_memory2.cpp
C++
gpl-2.0
1,665
<?php /** * @package Joomla.Administrator * @subpackage com_privacy * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; /** @var PrivacyViewRequest $this */ // Include the component HTML helpers. JHtml::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_privacy/helpers/html'); JHtml::_('behavior.formvalidator'); JHtml::_('behavior.keepalive'); $js = <<< JS Joomla.submitbutton = function(task) { if (task === 'request.cancel' || document.formvalidator.isValid(document.getElementById('item-form'))) { Joomla.submitform(task, document.getElementById('item-form')); } }; JS; JFactory::getDocument()->addScriptDeclaration($js); ?> <form action="<?php echo JRoute::_('index.php?option=com_privacy&view=request&id=' . (int) $this->item->id); ?>" method="post" name="adminForm" id="item-form" class="form-validate"> <div class="row-fluid"> <div class="span6"> <h3><?php echo JText::_('COM_PRIVACY_HEADING_REQUEST_INFORMATION'); ?></h3> <dl class="dl-horizontal"> <dt><?php echo JText::_('JGLOBAL_EMAIL'); ?>:</dt> <dd><?php echo $this->item->email; ?></dd> <dt><?php echo JText::_('JSTATUS'); ?>:</dt> <dd><?php echo JHtml::_('PrivacyHtml.helper.statusLabel', $this->item->status); ?></dd> <dt><?php echo JText::_('COM_PRIVACY_FIELD_REQUEST_TYPE_LABEL'); ?>:</dt> <dd><?php echo JText::_('COM_PRIVACY_HEADING_REQUEST_TYPE_TYPE_' . $this->item->request_type); ?></dd> <dt><?php echo JText::_('COM_PRIVACY_FIELD_REQUESTED_AT_LABEL'); ?>:</dt> <dd><?php echo JHtml::_('date', $this->item->requested_at, JText::_('DATE_FORMAT_LC6')); ?></dd> </dl> </div> <div class="span6"> <h3><?php echo JText::_('COM_PRIVACY_HEADING_ACTION_LOG'); ?></h3> <?php if (empty($this->actionlogs)) : ?> <div class="alert alert-no-items"> <?php echo JText::_('JGLOBAL_NO_MATCHING_RESULTS'); ?> </div> <?php else : ?> <table class="table table-striped table-hover"> <thead> <th> <?php echo JText::_('COM_ACTIONLOGS_ACTION'); ?> </th> <th> <?php echo JText::_('COM_ACTIONLOGS_DATE'); ?> </th> <th> <?php echo JText::_('COM_ACTIONLOGS_NAME'); ?> </th> </thead> <tbody> <?php foreach ($this->actionlogs as $i => $item) : ?> <tr class="row<?php echo $i % 2; ?>"> <td> <?php echo ActionlogsHelper::getHumanReadableLogMessage($item); ?> </td> <td> <?php echo JHtml::_('date', $item->log_date, JText::_('DATE_FORMAT_LC6')); ?> </td> <td> <?php echo $item->name; ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php endif;?> </div> </div> <input type="hidden" name="task" value="" /> <?php echo JHtml::_('form.token'); ?> </form>
mvanvu/joomla-cms
administrator/components/com_privacy/views/request/tmpl/default.php
PHP
gpl-2.0
2,937
/* $Id: KeyboardImpl.cpp $ */ /** @file * VirtualBox COM class implementation */ /* * Copyright (C) 2006-2012 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 "KeyboardImpl.h" #include "ConsoleImpl.h" #include "AutoCaller.h" #include "Logging.h" #include <VBox/com/array.h> #include <VBox/vmm/pdmdrv.h> #include <iprt/asm.h> #include <iprt/cpp/utils.h> // defines //////////////////////////////////////////////////////////////////////////////// // globals //////////////////////////////////////////////////////////////////////////////// /** @name Keyboard device capabilities bitfield * @{ */ enum { /** The keyboard device does not wish to receive keystrokes. */ KEYBOARD_DEVCAP_DISABLED = 0, /** The keyboard device does wishes to receive keystrokes. */ KEYBOARD_DEVCAP_ENABLED = 1 }; /** * Keyboard driver instance data. */ typedef struct DRVMAINKEYBOARD { /** Pointer to the keyboard object. */ Keyboard *pKeyboard; /** Pointer to the driver instance structure. */ PPDMDRVINS pDrvIns; /** Pointer to the keyboard port interface of the driver/device above us. */ PPDMIKEYBOARDPORT pUpPort; /** Our keyboard connector interface. */ PDMIKEYBOARDCONNECTOR IConnector; /** The capabilities of this device. */ uint32_t u32DevCaps; } DRVMAINKEYBOARD, *PDRVMAINKEYBOARD; /** Converts PDMIVMMDEVCONNECTOR pointer to a DRVMAINVMMDEV pointer. */ #define PPDMIKEYBOARDCONNECTOR_2_MAINKEYBOARD(pInterface) ( (PDRVMAINKEYBOARD) ((uintptr_t)pInterface - RT_OFFSETOF(DRVMAINKEYBOARD, IConnector)) ) // constructor / destructor //////////////////////////////////////////////////////////////////////////////// Keyboard::Keyboard() : mParent(NULL) { } Keyboard::~Keyboard() { } HRESULT Keyboard::FinalConstruct() { RT_ZERO(mpDrv); mpVMMDev = NULL; mfVMMDevInited = false; return BaseFinalConstruct(); } void Keyboard::FinalRelease() { uninit(); BaseFinalRelease(); } // public methods //////////////////////////////////////////////////////////////////////////////// /** * Initializes the keyboard object. * * @returns COM result indicator * @param parent handle of our parent object */ HRESULT Keyboard::init(Console *aParent) { LogFlowThisFunc(("aParent=%p\n", aParent)); ComAssertRet(aParent, E_INVALIDARG); /* Enclose the state transition NotReady->InInit->Ready */ AutoInitSpan autoInitSpan(this); AssertReturn(autoInitSpan.isOk(), E_FAIL); unconst(mParent) = aParent; unconst(mEventSource).createObject(); HRESULT rc = mEventSource->init(static_cast<IKeyboard*>(this)); AssertComRCReturnRC(rc); /* Confirm a successful initialization */ autoInitSpan.setSucceeded(); return S_OK; } /** * Uninitializes the instance and sets the ready flag to FALSE. * Called either from FinalRelease() or by the parent when it gets destroyed. */ void Keyboard::uninit() { LogFlowThisFunc(("\n")); /* Enclose the state transition Ready->InUninit->NotReady */ AutoUninitSpan autoUninitSpan(this); if (autoUninitSpan.uninitDone()) return; for (unsigned i = 0; i < KEYBOARD_MAX_DEVICES; ++i) { if (mpDrv[i]) mpDrv[i]->pKeyboard = NULL; mpDrv[i] = NULL; } mpVMMDev = NULL; mfVMMDevInited = true; unconst(mParent) = NULL; unconst(mEventSource).setNull(); } /** * Sends a scancode to the keyboard. * * @returns COM status code * @param scancode The scancode to send */ STDMETHODIMP Keyboard::PutScancode(LONG scancode) { com::SafeArray<LONG> scancodes(1); scancodes[0] = scancode; return PutScancodes(ComSafeArrayAsInParam(scancodes), NULL); } /** * Sends a list of scancodes to the keyboard. * * @returns COM status code * @param scancodes Pointer to the first scancode * @param count Number of scancodes * @param codesStored Address of variable to store the number * of scancodes that were sent to the keyboard. This value can be NULL. */ STDMETHODIMP Keyboard::PutScancodes(ComSafeArrayIn(LONG, scancodes), ULONG *codesStored) { if (ComSafeArrayInIsNull(scancodes)) return E_INVALIDARG; AutoCaller autoCaller(this); if (FAILED(autoCaller.rc())) return autoCaller.rc(); com::SafeArray<LONG> keys(ComSafeArrayInArg(scancodes)); AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); CHECK_CONSOLE_DRV(mpDrv[0]); /* Send input to the last enabled device. Relies on the fact that * the USB keyboard is always initialized after the PS/2 keyboard. */ PPDMIKEYBOARDPORT pUpPort = NULL; for (int i = KEYBOARD_MAX_DEVICES - 1; i >= 0 ; --i) { if (mpDrv[i] && (mpDrv[i]->u32DevCaps & KEYBOARD_DEVCAP_ENABLED)) { pUpPort = mpDrv[i]->pUpPort; break; } } /* No enabled keyboard - throw the input away. */ if (!pUpPort) { if (codesStored) *codesStored = (uint32_t)keys.size(); return S_OK; } int vrc = VINF_SUCCESS; uint32_t sent; for (sent = 0; (sent < keys.size()) && RT_SUCCESS(vrc); sent++) vrc = pUpPort->pfnPutEvent(pUpPort, (uint8_t)keys[sent]); if (codesStored) *codesStored = sent; /* Only signal the keys in the event which have been actually sent. */ com::SafeArray<LONG> keysSent(sent); memcpy(keysSent.raw(), keys.raw(), sent*sizeof(LONG)); VBoxEventDesc evDesc; evDesc.init(mEventSource, VBoxEventType_OnGuestKeyboard, ComSafeArrayAsInParam(keys)); evDesc.fire(0); if (RT_FAILURE(vrc)) return setError(VBOX_E_IPRT_ERROR, tr("Could not send all scan codes to the virtual keyboard (%Rrc)"), vrc); return S_OK; } /** * Sends Control-Alt-Delete to the keyboard. This could be done otherwise * but it's so common that we'll be nice and supply a convenience API. * * @returns COM status code * */ STDMETHODIMP Keyboard::PutCAD() { static com::SafeArray<LONG> cadSequence(8); cadSequence[0] = 0x1d; // Ctrl down cadSequence[1] = 0x38; // Alt down cadSequence[2] = 0xe0; // Del down 1 cadSequence[3] = 0x53; // Del down 2 cadSequence[4] = 0xe0; // Del up 1 cadSequence[5] = 0xd3; // Del up 2 cadSequence[6] = 0xb8; // Alt up cadSequence[7] = 0x9d; // Ctrl up return PutScancodes(ComSafeArrayAsInParam(cadSequence), NULL); } STDMETHODIMP Keyboard::COMGETTER(EventSource)(IEventSource ** aEventSource) { CheckComArgOutPointerValid(aEventSource); AutoCaller autoCaller(this); if (FAILED(autoCaller.rc())) return autoCaller.rc(); // no need to lock - lifetime constant mEventSource.queryInterfaceTo(aEventSource); return S_OK; } // // private methods // /** * @interface_method_impl{PDMIBASE,pfnQueryInterface} */ DECLCALLBACK(void *) Keyboard::drvQueryInterface(PPDMIBASE pInterface, const char *pszIID) { PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface); PDRVMAINKEYBOARD pDrv = PDMINS_2_DATA(pDrvIns, PDRVMAINKEYBOARD); PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase); PDMIBASE_RETURN_INTERFACE(pszIID, PDMIKEYBOARDCONNECTOR, &pDrv->IConnector); return NULL; } /** * Destruct a keyboard driver instance. * * @returns VBox status. * @param pDrvIns The driver instance data. */ DECLCALLBACK(void) Keyboard::drvDestruct(PPDMDRVINS pDrvIns) { PDRVMAINKEYBOARD pData = PDMINS_2_DATA(pDrvIns, PDRVMAINKEYBOARD); LogFlow(("Keyboard::drvDestruct: iInstance=%d\n", pDrvIns->iInstance)); PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns); if (pData->pKeyboard) { AutoWriteLock kbdLock(pData->pKeyboard COMMA_LOCKVAL_SRC_POS); for (unsigned cDev = 0; cDev < KEYBOARD_MAX_DEVICES; ++cDev) if (pData->pKeyboard->mpDrv[cDev] == pData) { pData->pKeyboard->mpDrv[cDev] = NULL; break; } pData->pKeyboard->mpVMMDev = NULL; } } DECLCALLBACK(void) keyboardLedStatusChange(PPDMIKEYBOARDCONNECTOR pInterface, PDMKEYBLEDS enmLeds) { PDRVMAINKEYBOARD pDrv = PPDMIKEYBOARDCONNECTOR_2_MAINKEYBOARD(pInterface); pDrv->pKeyboard->getParent()->onKeyboardLedsChange(!!(enmLeds & PDMKEYBLEDS_NUMLOCK), !!(enmLeds & PDMKEYBLEDS_CAPSLOCK), !!(enmLeds & PDMKEYBLEDS_SCROLLLOCK)); } /** * @interface_method_impl{PDMIKEYBOARDCONNECTOR,pfnSetActive} */ DECLCALLBACK(void) Keyboard::keyboardSetActive(PPDMIKEYBOARDCONNECTOR pInterface, bool fActive) { PDRVMAINKEYBOARD pDrv = PPDMIKEYBOARDCONNECTOR_2_MAINKEYBOARD(pInterface); if (fActive) pDrv->u32DevCaps |= KEYBOARD_DEVCAP_ENABLED; else pDrv->u32DevCaps &= ~KEYBOARD_DEVCAP_ENABLED; } /** * Construct a keyboard driver instance. * * @copydoc FNPDMDRVCONSTRUCT */ DECLCALLBACK(int) Keyboard::drvConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags) { PDRVMAINKEYBOARD pData = PDMINS_2_DATA(pDrvIns, PDRVMAINKEYBOARD); LogFlow(("Keyboard::drvConstruct: iInstance=%d\n", pDrvIns->iInstance)); PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns); /* * Validate configuration. */ if (!CFGMR3AreValuesValid(pCfg, "Object\0")) return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES; AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER, ("Configuration error: Not possible to attach anything to this driver!\n"), VERR_PDM_DRVINS_NO_ATTACH); /* * IBase. */ pDrvIns->IBase.pfnQueryInterface = Keyboard::drvQueryInterface; pData->IConnector.pfnLedStatusChange = keyboardLedStatusChange; pData->IConnector.pfnSetActive = keyboardSetActive; /* * Get the IKeyboardPort interface of the above driver/device. */ pData->pUpPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIKEYBOARDPORT); if (!pData->pUpPort) { AssertMsgFailed(("Configuration error: No keyboard port interface above!\n")); return VERR_PDM_MISSING_INTERFACE_ABOVE; } /* * Get the Keyboard object pointer and update the mpDrv member. */ void *pv; int rc = CFGMR3QueryPtr(pCfg, "Object", &pv); if (RT_FAILURE(rc)) { AssertMsgFailed(("Configuration error: No/bad \"Object\" value! rc=%Rrc\n", rc)); return rc; } pData->pKeyboard = (Keyboard *)pv; /** @todo Check this cast! */ unsigned cDev; for (cDev = 0; cDev < KEYBOARD_MAX_DEVICES; ++cDev) if (!pData->pKeyboard->mpDrv[cDev]) { pData->pKeyboard->mpDrv[cDev] = pData; break; } if (cDev == KEYBOARD_MAX_DEVICES) return VERR_NO_MORE_HANDLES; return VINF_SUCCESS; } /** * Keyboard driver registration record. */ const PDMDRVREG Keyboard::DrvReg = { /* u32Version */ PDM_DRVREG_VERSION, /* szName */ "MainKeyboard", /* szRCMod */ "", /* szR0Mod */ "", /* pszDescription */ "Main keyboard driver (Main as in the API).", /* fFlags */ PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT, /* fClass. */ PDM_DRVREG_CLASS_KEYBOARD, /* cMaxInstances */ ~0U, /* cbInstance */ sizeof(DRVMAINKEYBOARD), /* pfnConstruct */ Keyboard::drvConstruct, /* pfnDestruct */ Keyboard::drvDestruct, /* pfnRelocate */ NULL, /* pfnIOCtl */ NULL, /* pfnPowerOn */ NULL, /* pfnReset */ NULL, /* pfnSuspend */ NULL, /* pfnResume */ NULL, /* pfnAttach */ NULL, /* pfnDetach */ NULL, /* pfnPowerOff */ NULL, /* pfnSoftReset */ NULL, /* u32EndVersion */ PDM_DRVREG_VERSION }; /* vi: set tabstop=4 shiftwidth=4 expandtab: */
yuyuyu101/VirtualBox-NetBSD
src/VBox/Main/src-client/KeyboardImpl.cpp
C++
gpl-2.0
12,529
/* * Firemox is a turn based strategy simulator * Copyright (C) 2003-2007 Fabrice Daugan * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.sf.firemox.clickable.ability; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import net.sf.firemox.clickable.target.card.MCard; import net.sf.firemox.event.MEventListener; import net.sf.firemox.test.And; import net.sf.firemox.test.InZone; import net.sf.firemox.test.Test; import net.sf.firemox.test.TestFactory; import net.sf.firemox.test.TestOn; import net.sf.firemox.token.TrueFalseAuto; /** * @author <a href="mailto:fabdouglas@users.sourceforge.net">Fabrice Daugan </a> * @since 0.93 */ public class TriggeredAbilitySet extends TriggeredAbility { /** * Create a new instance of this class. * <ul> * Structure of InputStream : Data[size] * <li>super [ActivatedAbility]</li> * <li>when [Test]</li> * </ul> * * @param input * file containing this ability * @param card * referenced card * @throws IOException * if error occurred during the reading process from the specified * input stream */ public TriggeredAbilitySet(InputStream input, MCard card) throws IOException { super(input, card); final Test when = TestFactory.readNextTest(input); final List<MEventListener> events = new ArrayList<MEventListener>(); when.extractTriggeredEvents(events, card, And.append(new InZone(eventComing .getIdPlace(), TestOn.THIS), when)); linkedAbilities = new ArrayList<Ability>(events.size()); for (MEventListener event : events) { linkedAbilities.add(new NestedAbility(event)); } } /** * */ private class NestedAbility extends TriggeredAbility { /** * Create a new instance of this class. * * @param event */ protected NestedAbility(MEventListener event) { super(TriggeredAbilitySet.this, event); this.playAsSpell = TrueFalseAuto.FALSE; } } @Override public Ability clone(MCard container) { final Collection<Ability> linkedAbilities = new ArrayList<Ability>( this.linkedAbilities.size()); for (Ability ability : linkedAbilities) { linkedAbilities.add(ability.clone(container)); } final TriggeredAbility clone = new TriggeredAbility(this, eventComing .clone(container)); clone.playAsSpell = TrueFalseAuto.FALSE; clone.linkedAbilities = linkedAbilities; return clone; } }
JoeyLeeuwinga/Firemox
src/main/java/net/sf/firemox/clickable/ability/TriggeredAbilitySet.java
Java
gpl-2.0
3,258
var requestQueue = new Request.Queue({ concurrent: monitorData.length, stopOnFailure: false }); function Monitor(monitorData) { this.id = monitorData.id; this.connKey = monitorData.connKey; this.url = monitorData.url; this.status = null; this.alarmState = STATE_IDLE; this.lastAlarmState = STATE_IDLE; this.streamCmdParms = 'view=request&request=stream&connkey='+this.connKey; if ( auth_hash ) { this.streamCmdParms += '&auth='+auth_hash; } this.streamCmdTimer = null; this.type = monitorData.type; this.refresh = monitorData.refresh; this.start = function(delay) { if ( this.streamCmdQuery ) { this.streamCmdTimer = this.streamCmdQuery.delay(delay, this); } else { console.log("No streamCmdQuery"); } }; this.eventHandler = function(event) { console.log(event); }; this.onclick = function(evt) { var el = evt.currentTarget; var tag = 'watch'; var id = el.getAttribute("data-monitor-id"); var width = el.getAttribute("data-width"); var height = el.getAttribute("data-height"); var url = '?view=watch&mid='+id; var name = 'zmWatch'+id; evt.preventDefault(); createPopup(url, name, tag, width, height); }; this.setup_onclick = function() { var el = document.getElementById('imageFeed'+this.id); if ( el ) el.addEventListener('click', this.onclick, false); }; this.disable_onclick = function() { document.getElementById('imageFeed'+this.id).removeEventListener('click', this.onclick ); }; this.setStateClass = function(element, stateClass) { if ( !element.hasClass( stateClass ) ) { if ( stateClass != 'alarm' ) { element.removeClass('alarm'); } if ( stateClass != 'alert' ) { element.removeClass('alert'); } if ( stateClass != 'idle' ) { element.removeClass('idle'); } element.addClass(stateClass); } }; this.onError = function(text, error) { console.log('onerror: ' + text + ' error:'+error); // Requeue, but want to wait a while. var streamCmdTimeout = 10*statusRefreshTimeout; this.streamCmdTimer = this.streamCmdQuery.delay(streamCmdTimeout, this); }; this.onFailure = function(xhr) { console.log('onFailure: ' + this.connKey); console.log(xhr); if ( ! requestQueue.hasNext("cmdReq"+this.id) ) { console.log("Not requeuing because there is one already"); requestQueue.addRequest("cmdReq"+this.id, this.streamCmdReq); } if ( 0 ) { // Requeue, but want to wait a while. if ( this.streamCmdTimer ) { this.streamCmdTimer = clearTimeout( this.streamCmdTimer ); } var streamCmdTimeout = 1000*statusRefreshTimeout; this.streamCmdTimer = this.streamCmdQuery.delay( streamCmdTimeout, this, true ); requestQueue.resume(); } console.log("done failure"); }; this.getStreamCmdResponse = function(respObj, respText) { if ( this.streamCmdTimer ) { this.streamCmdTimer = clearTimeout( this.streamCmdTimer ); } var stream = $j('#liveStream'+this.id)[0]; if ( respObj.result == 'Ok' ) { if ( respObj.status ) { this.status = respObj.status; this.alarmState = this.status.state; var stateClass = ""; if ( this.alarmState == STATE_ALARM ) { stateClass = "alarm"; } else if ( this.alarmState == STATE_ALERT ) { stateClass = "alert"; } else { stateClass = "idle"; } if ( (!COMPACT_MONTAGE) && (this.type != 'WebSite') ) { $('fpsValue'+this.id).set('text', this.status.fps); $('stateValue'+this.id).set('text', stateStrings[this.alarmState]); this.setStateClass($('monitorState'+this.id), stateClass); } this.setStateClass($('monitor'+this.id), stateClass); /*Stream could be an applet so can't use moo tools*/ stream.className = stateClass; var isAlarmed = ( this.alarmState == STATE_ALARM || this.alarmState == STATE_ALERT ); var wasAlarmed = ( this.lastAlarmState == STATE_ALARM || this.lastAlarmState == STATE_ALERT ); var newAlarm = ( isAlarmed && !wasAlarmed ); var oldAlarm = ( !isAlarmed && wasAlarmed ); if ( newAlarm ) { if ( false && SOUND_ON_ALARM ) { // Enable the alarm sound $('alarmSound').removeClass('hidden'); } if ( POPUP_ON_ALARM ) { windowToFront(); } } if ( false && SOUND_ON_ALARM ) { if ( oldAlarm ) { // Disable alarm sound $('alarmSound').addClass('hidden'); } } if ( this.status.auth ) { if ( this.status.auth != auth_hash ) { // Try to reload the image stream. if ( stream ) { stream.src = stream.src.replace(/auth=\w+/i, 'auth='+this.status.auth); } console.log("Changed auth from " + auth_hash + " to " + this.status.auth); auth_hash = this.status.auth; } } // end if have a new auth hash } // end if has state } else { console.error(respObj.message); // Try to reload the image stream. if ( stream ) { if ( stream.src ) { console.log('Reloading stream: ' + stream.src); stream.src = stream.src.replace(/rand=\d+/i, 'rand='+Math.floor((Math.random() * 1000000) )); } else { } } else { console.log('No stream to reload?'); } } // end if Ok or not var streamCmdTimeout = statusRefreshTimeout; // The idea here is if we are alarmed, do updates faster. // However, there is a timeout in the php side which isn't getting modified, // so this may cause a problem. Also the server may only be able to update so fast. //if ( this.alarmState == STATE_ALARM || this.alarmState == STATE_ALERT ) { //streamCmdTimeout = streamCmdTimeout/5; //} this.streamCmdTimer = this.streamCmdQuery.delay(streamCmdTimeout, this); this.lastAlarmState = this.alarmState; }; this.streamCmdQuery = function(resent) { if ( resent ) { console.log(this.connKey+": timeout: Resending"); this.streamCmdReq.cancel(); } //console.log("Starting CmdQuery for " + this.connKey ); if ( this.type != 'WebSite' ) { this.streamCmdReq.send(this.streamCmdParms+"&command="+CMD_QUERY); } }; if ( this.type != 'WebSite' ) { this.streamCmdReq = new Request.JSON( { url: this.url, method: 'get', timeout: AJAX_TIMEOUT, onSuccess: this.getStreamCmdResponse.bind(this), onTimeout: this.streamCmdQuery.bind(this, true), onError: this.onError.bind(this), onFailure: this.onFailure.bind(this), link: 'cancel' } ); console.log("queueing for " + this.id + " " + this.connKey + " timeout is: " + AJAX_TIMEOUT); requestQueue.addRequest("cmdReq"+this.id, this.streamCmdReq); } } // end function Monitor /** * called when the layoutControl select element is changed, or the page * is rendered * @param {*} element - the event data passed by onchange callback */ function selectLayout(element) { console.log(element); layout = $j(element).val(); if ( layout_id = parseInt(layout) ) { layout = layouts[layout]; for ( var i = 0, length = monitors.length; i < length; i++ ) { monitor = monitors[i]; // Need to clear the current positioning, and apply the new monitor_frame = $j('#monitorFrame'+monitor.id); if ( ! monitor_frame ) { console.log("Error finding frame for " + monitor.id); continue; } // Apply default layout options, like float left if ( layout.Positions['default'] ) { styles = layout.Positions['default']; for ( style in styles ) { monitor_frame.css(style, styles[style]); } } else { console.log("No default styles to apply" + layout.Positions); } // end if default styles if ( layout.Positions['mId'+monitor.id] ) { styles = layout.Positions['mId'+monitor.id]; for ( style in styles ) { monitor_frame.css(style, styles[style]); console.log("Applying " + style + ' : ' + styles[style]); } } else { console.log("No Monitor styles to apply"); } // end if specific monitor style } // end foreach monitor } // end if a stored layout if ( ! layout ) { return; } Cookie.write('zmMontageLayout', layout_id, {duration: 10*365}); if ( layouts[layout_id].Name != 'Freeform' ) { // 'montage_freeform.css' ) { Cookie.write( 'zmMontageScale', '', {duration: 10*365} ); $('scale').set('value', ''); $('width').set('value', 'auto'); for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; var streamImg = $('liveStream'+monitor.id); if ( streamImg ) { if ( streamImg.nodeName == 'IMG' ) { var src = streamImg.src; src = src.replace(/width=[\.\d]+/i, 'width=0' ); if ( src != streamImg.src ) { streamImg.src = ''; streamImg.src = src; } } else if ( streamImg.nodeName == 'APPLET' || streamImg.nodeName == 'OBJECT' ) { // APPLET's and OBJECTS need to be re-initialized } streamImg.style.width = '100%'; } } // end foreach monitor } } // end function selectLayout(element) /** * called when the widthControl|heightControl select elements are changed */ function changeSize() { var width = $('width').get('value'); var height = $('height').get('value'); for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; // Scale the frame monitor_frame = $j('#monitorFrame'+monitor.id); if ( !monitor_frame ) { console.log("Error finding frame for " + monitor.id); continue; } if ( width ) { monitor_frame.css('width', width); } if ( height ) { monitor_frame.css('height', height); } /*Stream could be an applet so can't use moo tools*/ var streamImg = $('liveStream'+monitor.id); if ( streamImg ) { if ( streamImg.nodeName == 'IMG' ) { var src = streamImg.src; streamImg.src = ''; src = src.replace(/width=[\.\d]+/i, 'width='+width); src = src.replace(/height=[\.\d]+/i, 'height='+height); src = src.replace(/rand=\d+/i, 'rand='+Math.floor((Math.random() * 1000000) )); streamImg.src = src; } streamImg.style.width = width ? width : null; streamImg.style.height = height ? height : null; //streamImg.style.height = ''; } } $('scale').set('value', ''); Cookie.write('zmMontageScale', '', {duration: 10*365}); Cookie.write('zmMontageWidth', width, {duration: 10*365}); Cookie.write('zmMontageHeight', height, {duration: 10*365}); //selectLayout('#zmMontageLayout'); } // end function changeSize() /** * called when the scaleControl select element is changed */ function changeScale() { var scale = $('scale').get('value'); $('width').set('value', 'auto'); $('height').set('value', 'auto'); Cookie.write('zmMontageScale', scale, {duration: 10*365}); Cookie.write('zmMontageWidth', '', {duration: 10*365}); Cookie.write('zmMontageHeight', '', {duration: 10*365}); if ( !scale ) { selectLayout('#zmMontageLayout'); return; } for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; var newWidth = ( monitorData[i].width * scale ) / SCALE_BASE; var newHeight = ( monitorData[i].height * scale ) / SCALE_BASE; // Scale the frame monitor_frame = $j('#monitorFrame'+monitor.id); if ( !monitor_frame ) { console.log("Error finding frame for " + monitor.id); continue; } if ( newWidth ) { monitor_frame.css('width', newWidth); } // We don't set the frame height because it has the status bar as well //if ( height ) { ////monitor_frame.css('height', height+'px'); //} /*Stream could be an applet so can't use moo tools*/ var streamImg = $j('#liveStream'+monitor.id)[0]; if ( streamImg ) { if ( streamImg.nodeName == 'IMG' ) { var src = streamImg.src; streamImg.src = ''; //src = src.replace(/rand=\d+/i,'rand='+Math.floor((Math.random() * 1000000) )); src = src.replace(/scale=[\.\d]+/i, 'scale='+scale); src = src.replace(/width=[\.\d]+/i, 'width='+newWidth); src = src.replace(/height=[\.\d]+/i, 'height='+newHeight); streamImg.src = src; } streamImg.style.width = newWidth + "px"; streamImg.style.height = newHeight + "px"; } } } function toGrid(value) { return Math.round(value / 80) * 80; } // Makes monitorFrames draggable. function edit_layout(button) { // Turn off the onclick on the image. for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; monitor.disable_onclick(); }; $j('#monitors .monitorFrame').draggable({ cursor: 'crosshair', //revert: 'invalid' }); $j('#SaveLayout').show(); $j('#EditLayout').hide(); } // end function edit_layout function save_layout(button) { var form = button.form; var name = form.elements['Name'].value; if ( !name ) { name = form.elements['zmMontageLayout'].options[form.elements['zmMontageLayout'].selectedIndex].text; } if ( name=='Freeform' || name=='2 Wide' || name=='3 Wide' || name=='4 Wide' || name=='5 Wide' ) { alert('You cannot edit the built in layouts. Please give the layout a new name.'); return; } // In fixed positioning, order doesn't matter. In floating positioning, it does. var Positions = {}; for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; monitor_frame = $j('#monitorFrame'+monitor.id); Positions['mId'+monitor.id] = { width: monitor_frame.css('width'), height: monitor_frame.css('height'), top: monitor_frame.css('top'), bottom: monitor_frame.css('bottom'), left: monitor_frame.css('left'), right: monitor_frame.css('right'), position: monitor_frame.css('position'), float: monitor_frame.css('float'), }; } // end foreach monitor form.Positions.value = JSON.stringify(Positions); form.submit(); } // end function save_layout function cancel_layout(button) { $j('#SaveLayout').hide(); $j('#EditLayout').show(); for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; monitor.setup_onclick(); //monitor_feed = $j('#imageFeed'+monitor.id); //monitor_feed.click(monitor.onclick); }; selectLayout('#zmMontageLayout'); } function reloadWebSite(ndx) { document.getElementById('imageFeed'+ndx).innerHTML = document.getElementById('imageFeed'+ndx).innerHTML; } var monitors = new Array(); function initPage() { jQuery(document).ready(function() { jQuery("#hdrbutton").click(function() { jQuery("#flipMontageHeader").slideToggle("slow"); jQuery("#hdrbutton").toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up'); Cookie.write( 'zmMontageHeaderFlip', jQuery('#hdrbutton').hasClass('glyphicon-menu-up') ? 'up' : 'down', {duration: 10*365} ); }); }); if ( Cookie.read('zmMontageHeaderFlip') == 'down' ) { // The chosen dropdowns require the selects to be visible, so once chosen has initialized, we can hide the header jQuery("#flipMontageHeader").slideToggle("fast"); jQuery("#hdrbutton").toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up'); } for ( var i = 0, length = monitorData.length; i < length; i++ ) { monitors[i] = new Monitor(monitorData[i]); // Start the fps and status updates. give a random delay so that we don't assault the server var delay = Math.round( (Math.random()+0.5)*statusRefreshTimeout ); monitors[i].start(delay); var interval = monitors[i].refresh; if ( monitors[i].type == 'WebSite' && interval > 0 ) { setInterval(reloadWebSite, interval*1000, i); } monitors[i].setup_onclick(); } selectLayout('#zmMontageLayout'); } // Kick everything off window.addEventListener('DOMContentLoaded', initPage);
Simpler1/ZoneMinder
web/skins/classic/views/js/montage.js
JavaScript
gpl-2.0
16,321
from miasm2.core.asmblock import disasmEngine from miasm2.arch.aarch64.arch import mn_aarch64 cb_aarch64_funcs = [] def cb_aarch64_disasm(*args, **kwargs): for func in cb_aarch64_funcs: func(*args, **kwargs) class dis_aarch64b(disasmEngine): attrib = "b" def __init__(self, bs=None, **kwargs): super(dis_aarch64b, self).__init__( mn_aarch64, self.attrib, bs, dis_bloc_callback = cb_aarch64_disasm, **kwargs) class dis_aarch64l(disasmEngine): attrib = "l" def __init__(self, bs=None, **kwargs): super(dis_aarch64l, self).__init__( mn_aarch64, self.attrib, bs, dis_bloc_callback = cb_aarch64_disasm, **kwargs)
stephengroat/miasm
miasm2/arch/aarch64/disasm.py
Python
gpl-2.0
731
/************************************************************************ * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. * * Use is subject to license terms. * * 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. You can also * obtain a copy of the License at http://odftoolkit.org/docs/license.txt * * 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. * ************************************************************************/ /* * This file is automatically generated. * Don't edit manually. */ package org.odftoolkit.odfdom.dom.attribute.table; import org.odftoolkit.odfdom.dom.OdfDocumentNamespace; import org.odftoolkit.odfdom.pkg.OdfAttribute; import org.odftoolkit.odfdom.pkg.OdfFileDom; import org.odftoolkit.odfdom.pkg.OdfName; /** * DOM implementation of OpenDocument attribute {@odf.attribute table:script}. * */ public class TableScriptAttribute extends OdfAttribute { public static final OdfName ATTRIBUTE_NAME = OdfName.newName(OdfDocumentNamespace.TABLE, "script"); /** * Create the instance of OpenDocument attribute {@odf.attribute table:script}. * * @param ownerDocument The type is <code>OdfFileDom</code> */ public TableScriptAttribute(OdfFileDom ownerDocument) { super(ownerDocument, ATTRIBUTE_NAME); } /** * Returns the attribute name. * * @return the <code>OdfName</code> for {@odf.attribute table:script}. */ @Override public OdfName getOdfName() { return ATTRIBUTE_NAME; } /** * @return Returns the name of this attribute. */ @Override public String getName() { return ATTRIBUTE_NAME.getLocalName(); } /** * Returns the default value of {@odf.attribute table:script}. * * @return the default value as <code>String</code> dependent of its element name * return <code>null</code> if the default value does not exist */ @Override public String getDefault() { return null; } /** * Default value indicator. As the attribute default value is dependent from its element, the attribute has only a default, when a parent element exists. * * @return <code>true</code> if {@odf.attribute table:script} has an element parent * otherwise return <code>false</code> as undefined. */ @Override public boolean hasDefault() { return false; } /** * @return Returns whether this attribute is known to be of type ID (i.e. xml:id ?) */ @Override public boolean isId() { return false; } }
jbjonesjr/geoproponis
external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/attribute/table/TableScriptAttribute.java
Java
gpl-2.0
2,957
<? /**[N]** * JIBAS Education Community * Jaringan Informasi Bersama Antar Sekolah * * @version: 3.2 (September 03, 2013) * @notes: JIBAS Education Community will be managed by Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * Copyright (C) 2009 Yayasan Indonesia Membaca (http://www.indonesiamembaca.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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License **[N]**/ ?> <? require_once('../../include/sessionchecker.php'); require_once('../../include/common.php'); require_once('../../include/sessioninfo.php'); require_once('../../include/config.php'); require_once('../../include/db_functions.php'); $op=""; if (isset($_REQUEST[op])) $op=$_REQUEST[op]; $page='t'; if (isset($_REQUEST[page])) $page = $_REQUEST[page]; OpenDb(); $sql="SELECT * FROM jbsvcr.galerifoto WHERE idguru='".SI_USER_ID()."'"; $result=QueryDb($sql); $num=@mysql_num_rows($result); $cnt=1; while ($row=@mysql_fetch_array($result)) { $ket[$cnt]=$row[keterangan]; $nama[$cnt]=$row[nama]; $fn[$cnt]=$row[filename]; $rep[$cnt]=$row[replid]; $cnt++; } CloseDb(); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <link rel="stylesheet" href="../../script/TinySlideshow/style.css" /> <link href="../../style/style.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="../../script/contentslider.css" /> <script type="text/javascript" language="javascript" src="../../style/lytebox.js"></script> <script type="text/javascript" language="javascript" src="../../script/tools.js"></script> <link rel="stylesheet" href="../../style/lytebox.css" type="text/css" media="screen" /> <script type="text/javascript" src="../../script/contentslider.js"></script> <script language="javascript" src="../../script/ajax.js"></script> <script src="SpryTabbedPanels.js" type="text/javascript"></script> <script language="javascript" > function get_fresh(){ document.location.href="galerifoto_ss.php"; } function over(id){ var actmenu = document.getElementById('actmenu').value; if (actmenu==id) return false; if (actmenu=='t') document.getElementById('tabimages').src='../../images/s_over.png'; else document.getElementById('tabimages').src='../../images/t_over.png'; } function out(id){ var actmenu = document.getElementById('actmenu').value; if (actmenu==id) return false; if (actmenu=='t') document.getElementById('tabimages').src='../../images/t.png'; else document.getElementById('tabimages').src='../../images/s.png'; } function show(id){ if (id=='t'){ document.getElementById('actmenu').value='t'; document.getElementById('tabimages').src='../../images/t.png'; document.getElementById('slice_t').style.display=''; document.getElementById('salideshow').style.display='none'; } else { document.getElementById('actmenu').value='s'; document.getElementById('tabimages').src='../../images/s.png'; document.getElementById('slice_t').style.display='none'; document.getElementById('salideshow').style.display=''; } } </script> <style type="text/css"> <!-- .style1 { font-size: 0.7px; font-family: Verdana; } .style3 {font-size: 12px} --> </style> <link href="SpryTabbedPanels.css" rel="stylesheet" type="text/css"> </head> <body> <table width="100%" border="0" cellspacing="5"> <tr> <td align="left"><font size="4" style="background-color:#ffcc66">&nbsp;</font>&nbsp;<font size="4" color="Gray">Galeri Foto</font><br /> <a href="../../home.php" target="framecenter">Home</a> > <strong>Galeri Foto</strong><br /> <br /></td> <td align="right" valign="bottom"> <a href="galerifoto.php"><img src="../../images/ico/thumbnail.gif" border="0">&nbsp;Thumbnails</a>&nbsp;&nbsp; <a href="#" onClick="newWindow('tambahfoto.php?pagesource=ss','TambahFoto','550','207','resizable=1,scrollbars=0,status=0,toolbar=0');"><img src="../../images/ico/tambah.png" border="0" />&nbsp;Tambah Foto</a><br> </td> </tr> <tr> <td align="left" colspan='2'> <table border='0' width='100%'> <tr> <td width='25%'>&nbsp;</td> <td width='*'> <? if ($num>0) { ?> <ul id="slideshow"> <? for ($i = 1; $i <= $num; $i++) { $fphoto = "$FILESHARE_ADDR/galeriguru/photos/".$fn[$i]; $fthumb = "$FILESHARE_ADDR/galeriguru/thumbnails/".$fn[$i]; ?> <li> <h3><?=$nama[$i]?></h3> <span><?=$fphoto?></span> <p><?=$ket[$i]?></p> <a href="#"><img src="<?=$fthumb?>" height="480" alt="" /></a> </li> <? } ?> </ul> <div id="wrapper" > <div id="fullsize" style="width: 800px; height: 600px;"> <div id="imgprev" class="imgnav" title="Previous Image"></div> <div id="imglink"></div> <div id="imgnext" class="imgnav" title="Next Image"></div> <div id="image"></div> <div id="information"> <h3></h3> <p></p> </div> </div> <div id="thumbnails" style="visibility: hidden;"> <div id="slideleft" title="Slide Left"></div> <div id="slidearea"> <div id="slider"></div> </div> <div id="slideright" title="Slide Right"></div> </div> </div> <script type="text/javascript" src="../../script/TinySlideshow/compressed.js"></script> <script type="text/javascript"> $('slideshow').style.display='none'; $('wrapper').style.display='block'; var slideshow=new TINY.slideshow("slideshow"); window.onload=function(){ slideshow.auto=true; slideshow.speed=5; slideshow.link="linkhover"; slideshow.info="information"; slideshow.thumbs="slider"; slideshow.left="slideleft"; slideshow.right="slideright"; slideshow.scrollSpeed=4; slideshow.height=480; slideshow.spacing=5; slideshow.active="#fff"; slideshow.init("slideshow","image","imgprev","imgnext","imglink"); } </script> <? } else { ?> <table width="100%" border="0" cellspacing="0" align="center"> <tr> <td><div align="center"><em>Tidak ada foto</em></div></td> </tr> </table> <? } ?> </td> <td width='25%'>&nbsp;</td> </tr> </table> </td> </tr> </table> </body> </html>
nurulimamnotes/sistem-informasi-sekolah
jibas/infosiswa/buletin/galerifoto/galerifoto_ss.php
PHP
gpl-2.0
7,300
/* Copyright (c) 2009, 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 */ package com.myblockchain.clusterj.tie; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.myblockchain.clusterj.ClusterJUserException; import com.myblockchain.clusterj.core.store.Blob; import com.myblockchain.clusterj.core.store.Column; import com.myblockchain.clusterj.core.store.Operation; import com.myblockchain.clusterj.core.store.ResultData; import com.myblockchain.clusterj.core.store.Table; import com.myblockchain.clusterj.core.util.I18NHelper; import com.myblockchain.clusterj.core.util.Logger; import com.myblockchain.clusterj.core.util.LoggerFactoryService; import com.myblockchain.clusterj.tie.DbImpl.BufferManager; import com.myblockchain.ndbjtie.ndbapi.NdbBlob; import com.myblockchain.ndbjtie.ndbapi.NdbOperation; /** * */ class OperationImpl implements Operation { /** My message translator */ static final I18NHelper local = I18NHelper .getInstance(OperationImpl.class); /** My logger */ static final Logger logger = LoggerFactoryService.getFactory() .getInstance(OperationImpl.class); private NdbOperation ndbOperation; protected List<Column> storeColumns = new ArrayList<Column>(); protected ClusterTransactionImpl clusterTransaction; /** The size of the receive buffer for this operation (may be zero for non-read operations) */ protected int bufferSize; /** The maximum column id for this operation (may be zero for non-read operations) */ protected int maximumColumnId; /** The offsets into the buffer for each column (may be null for non-read operations) */ protected int[] offsets; /** The lengths of fields in the buffer for each column (may be null for non-read operations) */ protected int[] lengths; /** The maximum length of any column in this operation */ protected int maximumColumnLength; protected BufferManager bufferManager; /** Constructor used for insert and delete operations that do not need to read data. * * @param operation the operation * @param transaction the transaction */ public OperationImpl(NdbOperation operation, ClusterTransactionImpl transaction) { this.ndbOperation = operation; this.clusterTransaction = transaction; this.bufferManager = clusterTransaction.getBufferManager(); } /** Constructor used for read operations. The table is used to obtain data used * to lay out memory for the result. * @param storeTable the table * @param operation the operation * @param transaction the transaction */ public OperationImpl(Table storeTable, NdbOperation operation, ClusterTransactionImpl transaction) { this(operation, transaction); TableImpl tableImpl = (TableImpl)storeTable; this.maximumColumnId = tableImpl.getMaximumColumnId(); this.bufferSize = tableImpl.getBufferSize(); this.offsets = tableImpl.getOffsets(); this.lengths = tableImpl.getLengths(); this.maximumColumnLength = tableImpl.getMaximumColumnLength(); } public void equalBigInteger(Column storeColumn, BigInteger value) { ByteBuffer buffer = Utility.convertValue(storeColumn, value); int returnCode = ndbOperation.equal(storeColumn.getName(), buffer); handleError(returnCode, ndbOperation); } public void equalBoolean(Column storeColumn, boolean booleanValue) { byte value = (booleanValue?(byte)0x01:(byte)0x00); int returnCode = ndbOperation.equal(storeColumn.getName(), value); handleError(returnCode, ndbOperation); } public void equalByte(Column storeColumn, byte value) { int storeValue = Utility.convertByteValueForStorage(storeColumn, value); int returnCode = ndbOperation.equal(storeColumn.getName(), storeValue); handleError(returnCode, ndbOperation); } public void equalBytes(Column storeColumn, byte[] value) { if (logger.isDetailEnabled()) logger.detail("Column: " + storeColumn.getName() + " columnId: " + storeColumn.getColumnId() + " data length: " + value.length); ByteBuffer buffer = Utility.convertValue(storeColumn, value); int returnCode = ndbOperation.equal(storeColumn.getName(), buffer); handleError(returnCode, ndbOperation); } public void equalDecimal(Column storeColumn, BigDecimal value) { ByteBuffer buffer = Utility.convertValue(storeColumn, value); int returnCode = ndbOperation.equal(storeColumn.getName(), buffer); handleError(returnCode, ndbOperation); } public void equalDouble(Column storeColumn, double value) { ByteBuffer buffer = Utility.convertValue(storeColumn, value); int returnCode = ndbOperation.equal(storeColumn.getName(), buffer); handleError(returnCode, ndbOperation); } public void equalFloat(Column storeColumn, float value) { ByteBuffer buffer = Utility.convertValue(storeColumn, value); int returnCode = ndbOperation.equal(storeColumn.getName(), buffer); handleError(returnCode, ndbOperation); } public void equalInt(Column storeColumn, int value) { int returnCode = ndbOperation.equal(storeColumn.getName(), value); handleError(returnCode, ndbOperation); } public void equalShort(Column storeColumn, short value) { int storeValue = Utility.convertShortValueForStorage(storeColumn, value); int returnCode = ndbOperation.equal(storeColumn.getName(), storeValue); handleError(returnCode, ndbOperation); } public void equalLong(Column storeColumn, long value) { long storeValue = Utility.convertLongValueForStorage(storeColumn, value); int returnCode = ndbOperation.equal(storeColumn.getName(), storeValue); handleError(returnCode, ndbOperation); } public void equalString(Column storeColumn, String value) { ByteBuffer stringStorageBuffer = Utility.encode(value, storeColumn, bufferManager); int returnCode = ndbOperation.equal(storeColumn.getName(), stringStorageBuffer); bufferManager.clearStringStorageBuffer(); handleError(returnCode, ndbOperation); } public void getBlob(Column storeColumn) { NdbBlob ndbBlob = ndbOperation.getBlobHandleM(storeColumn.getColumnId()); handleError(ndbBlob, ndbOperation); } public Blob getBlobHandle(Column storeColumn) { NdbBlob blobHandle = ndbOperation.getBlobHandleM(storeColumn.getColumnId()); handleError(blobHandle, ndbOperation); return new BlobImpl(blobHandle); } /** Specify the columns to be used for the operation. * For now, just save the columns. When resultData is called, pass the columns * to the ResultData constructor and then execute the operation. * */ public void getValue(Column storeColumn) { storeColumns.add(storeColumn); } public void postExecuteCallback(Runnable callback) { clusterTransaction.postExecuteCallback(callback); } /** Construct a new ResultData using the saved column data and then execute the operation. * */ public ResultData resultData() { return resultData(true); } /** Construct a new ResultData and if requested, execute the operation. * */ public ResultData resultData(boolean execute) { if (logger.isDetailEnabled()) logger.detail("storeColumns: " + Arrays.toString(storeColumns.toArray())); ResultDataImpl result; if (execute) { result = new ResultDataImpl(ndbOperation, storeColumns, maximumColumnId, bufferSize, offsets, lengths, bufferManager, false); clusterTransaction.executeNoCommit(false, true); } else { result = new ResultDataImpl(ndbOperation, storeColumns, maximumColumnId, bufferSize, offsets, lengths, bufferManager, true); } return result; } public void setBigInteger(Column storeColumn, BigInteger value) { ByteBuffer buffer = Utility.convertValue(storeColumn, value); int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), buffer); handleError(returnCode, ndbOperation); } public void setBoolean(Column storeColumn, Boolean value) { byte byteValue = (value?(byte)0x01:(byte)0x00); setByte(storeColumn, byteValue); } public void setByte(Column storeColumn, byte value) { int storeValue = Utility.convertByteValueForStorage(storeColumn, value); int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), storeValue); handleError(returnCode, ndbOperation); } public void setBytes(Column storeColumn, byte[] value) { // TODO use the string storage buffer instead of allocating a new buffer for each value int length = value.length; if (length > storeColumn.getLength()) { throw new ClusterJUserException(local.message("ERR_Data_Too_Long", storeColumn.getName(), storeColumn.getLength(), length)); } ByteBuffer buffer = Utility.convertValue(storeColumn, value); int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), buffer); handleError(returnCode, ndbOperation); } public void setDecimal(Column storeColumn, BigDecimal value) { ByteBuffer buffer = Utility.convertValue(storeColumn, value); int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), buffer); handleError(returnCode, ndbOperation); } public void setDouble(Column storeColumn, Double value) { int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), value); handleError(returnCode, ndbOperation); } public void setFloat(Column storeColumn, Float value) { int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), value); handleError(returnCode, ndbOperation); } public void setInt(Column storeColumn, Integer value) { int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), value); handleError(returnCode, ndbOperation); } public void setLong(Column storeColumn, long value) { long storeValue = Utility.convertLongValueForStorage(storeColumn, value); int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), storeValue); handleError(returnCode, ndbOperation); } public void setNull(Column storeColumn) { int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), null); handleError(returnCode, ndbOperation); } public void setShort(Column storeColumn, Short value) { int storeValue = Utility.convertShortValueForStorage(storeColumn, value); int returnCode = ndbOperation.setValue(storeColumn.getName(), storeValue); handleError(returnCode, ndbOperation); } public void setString(Column storeColumn, String value) { ByteBuffer stringStorageBuffer = Utility.encode(value, storeColumn, bufferManager); int length = stringStorageBuffer.remaining() - storeColumn.getPrefixLength(); if (length > storeColumn.getLength()) { throw new ClusterJUserException(local.message("ERR_Data_Too_Long", storeColumn.getName(), storeColumn.getLength(), length)); } int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), stringStorageBuffer); bufferManager.clearStringStorageBuffer(); handleError(returnCode, ndbOperation); } public int errorCode() { return ndbOperation.getNdbError().code(); } protected void handleError(int returnCode, NdbOperation ndbOperation) { if (returnCode == 0) { return; } else { Utility.throwError(returnCode, ndbOperation.getNdbError()); } } protected static void handleError(Object object, NdbOperation ndbOperation) { if (object != null) { return; } else { Utility.throwError(null, ndbOperation.getNdbError()); } } public void beginDefinition() { // nothing to do } public void endDefinition() { // nothing to do } public int getErrorCode() { return ndbOperation.getNdbError().code(); } public int getClassification() { return ndbOperation.getNdbError().classification(); } public int getMysqlCode() { return ndbOperation.getNdbError().myblockchain_code(); } public int getStatus() { return ndbOperation.getNdbError().status(); } public void freeResourcesAfterExecute() { } }
MrDunne/myblockchain
storage/ndb/clusterj/clusterj-tie/src/main/java/com/mysql/clusterj/tie/OperationImpl.java
Java
gpl-2.0
13,552
package mica import "fmt" // LinkToCompressed represents a link from a reference sequence to a // compressed original sequence. It serves as a bridge from a BLAST hit in // the coarse database to the corresponding original sequence that is // redundant to the specified residue range in the reference sequence. type LinkToCompressed struct { OrgSeqId uint32 CoarseStart, CoarseEnd uint16 Next *LinkToCompressed } func NewLinkToCompressed( orgSeqId uint32, coarseStart, coarseEnd uint16) *LinkToCompressed { return &LinkToCompressed{ OrgSeqId: orgSeqId, CoarseStart: coarseStart, CoarseEnd: coarseEnd, Next: nil, } } func (lk LinkToCompressed) String() string { return fmt.Sprintf("original sequence id: %d, coarse range: (%d, %d)", lk.OrgSeqId, lk.CoarseStart, lk.CoarseEnd) }
jameslz/MICA
link_to_compressed.go
GO
gpl-2.0
843
// renderimpl.cpp // this file is part of Context Free // --------------------- // Copyright (C) 2006-2008 Mark Lentczner - markl@glyphic.com // Copyright (C) 2006-2014 John Horigan - john@glyphic.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. // // John Horigan can be contacted at john@glyphic.com or at // John Horigan, 1209 Villa St., Mountain View, CA 94041-1123, USA // // Mark Lentczner can be contacted at markl@glyphic.com or at // Mark Lentczner, 1209 Villa St., Mountain View, CA 94041-1123, USA // // #include "renderimpl.h" #include <iterator> #include <string> #include <algorithm> #include <stack> #include <cassert> #include <functional> #ifdef _WIN32 #include <float.h> #include <math.h> #define isfinite _finite #else #include <math.h> #endif #include "shapeSTL.h" #include "primShape.h" #include "builder.h" #include "astreplacement.h" #include "CmdInfo.h" #include "tiledCanvas.h" using namespace std; using namespace AST; //#define DEBUG_SIZES unsigned int RendererImpl::MoveFinishedAt = 0; // when this many, move to file unsigned int RendererImpl::MoveUnfinishedAt = 0; // when this many, move to files unsigned int RendererImpl::MaxMergeFiles = 0; // maximum number of files to merge at once const double SHAPE_BORDER = 1.0; // multiplier of shape size when calculating bounding box const double FIXED_BORDER = 8.0; // fixed extra border, in pixels RendererImpl::RendererImpl(CFDGImpl* cfdg, int width, int height, double minSize, int variation, double border) : RendererAST(width, height), m_cfdg(cfdg), m_canvas(nullptr), mColorConflict(false), m_maxShapes(500000000), mVariation(variation), m_border(border), mScaleArea(0.0), mScale(0.0), m_currScale(0.0), m_currArea(0.0), m_minSize(minSize), mFrameTimeBounds(1.0, -Renderer::Infinity, Renderer::Infinity), circleCopy(primShape::circle), squareCopy(primShape::square), triangleCopy(primShape::triangle), shapeMap{} { if (MoveFinishedAt == 0) { #ifndef DEBUG_SIZES size_t mem = m_cfdg->system()->getPhysicalMemory(); if (mem == 0) { MoveFinishedAt = MoveUnfinishedAt = 2000000; } else { MoveFinishedAt = MoveUnfinishedAt = static_cast<unsigned int>(mem / (sizeof(FinishedShape) * 4)); } MaxMergeFiles = 200; // maximum number of files to merge at once #else MoveFinishedAt = 1000; // when this many, move to file MoveUnfinishedAt = 200; // when this many, move to files MaxMergeFiles = 4; // maximum number of files to merge at once #endif } mCFstack.reserve(8000); shapeMap = { { CommandInfo(&circleCopy), CommandInfo(&squareCopy), CommandInfo(&triangleCopy)} }; m_cfdg->hasParameter(CFG::FrameTime, mCurrentTime, nullptr); m_cfdg->hasParameter(CFG::Frame, mCurrentFrame, nullptr); } void RendererImpl::colorConflict(const yy::location& w) { if (mColorConflict) return; CfdgError err(w, "Conflicting color change"); system()->syntaxError(err); mColorConflict = true; } void RendererImpl::init() { // Performs RendererImpl initializations that are needed before rendering // and before each frame of an animation mCurrentSeed.seed(static_cast<unsigned long long>(mVariation)); mCurrentSeed(); Shape dummy; for (const rep_ptr& rep: m_cfdg->mCFDGcontents.mBody) { if (const ASTdefine* def = dynamic_cast<const ASTdefine*> (rep.get())) def->traverse(dummy, false, this); } mFinishedFileCount = 0; mUnfinishedFileCount = 0; mFixedBorderX = mFixedBorderY = 0.0; mShapeBorder = 1.0; mTotalArea = 0.0; m_minArea = 0.3; m_outputSoFar = m_stats.shapeCount = m_stats.toDoCount = 0; double minSize = m_minSize; m_cfdg->hasParameter(CFG::MinimumSize, minSize, this); minSize = (minSize <= 0.0) ? 0.3 : minSize; m_minArea = minSize * minSize; mFixedBorderX = FIXED_BORDER * ((m_border <= 1.0) ? m_border : 1.0); mShapeBorder = SHAPE_BORDER * ((m_border <= 1.0) ? 1.0 : m_border); m_cfdg->hasParameter(CFG::BorderFixed, mFixedBorderX, this); m_cfdg->hasParameter(CFG::BorderDynamic, mShapeBorder, this); if (2 * static_cast<int>(fabs(mFixedBorderX)) >= min(m_width, m_height)) mFixedBorderX = 0.0; if (mShapeBorder <= 0.0) mShapeBorder = 1.0; if (m_cfdg->hasParameter(CFG::MaxNatural, mMaxNatural, this) && (mMaxNatural < 1.0 || (mMaxNatural - 1.0) == mMaxNatural)) { const ASTexpression* max = m_cfdg->hasParameter(CFG::MaxNatural); throw CfdgError(max->where, (mMaxNatural < 1.0) ? "CF::MaxNatural must be >= 1" : "CF::MaxNatural must be < 9007199254740992"); } mCurrentPath.reset(new AST::ASTcompiledPath()); m_cfdg->getSymmetry(mSymmetryOps, this); m_cfdg->setBackgroundColor(this); } void RendererImpl::initBounds() { init(); double tile_x, tile_y; m_tiled = m_cfdg->isTiled(nullptr, &tile_x, &tile_y); m_frieze = m_cfdg->isFrieze(nullptr, &tile_x, &tile_y); m_sized = m_cfdg->isSized(&tile_x, &tile_y); m_timed = m_cfdg->isTimed(&mTimeBounds); if (m_tiled || m_sized) { mFixedBorderX = mShapeBorder = 0.0; mBounds.mMin_X = -(mBounds.mMax_X = tile_x / 2.0); mBounds.mMin_Y = -(mBounds.mMax_Y = tile_y / 2.0); rescaleOutput(m_width, m_height, true); mScaleArea = m_currArea; } if (m_frieze == CFDG::frieze_x) m_frieze_size = tile_x / 2.0; if (m_frieze == CFDG::frieze_y) m_frieze_size = tile_y / 2.0; if (m_frieze != CFDG::frieze_y) mFixedBorderY = mFixedBorderX; if (m_frieze == CFDG::frieze_x) mFixedBorderX = 0.0; } void RendererImpl::resetSize(int x, int y) { m_width = x; m_height = y; if (m_tiled || m_sized) { m_currScale = m_currArea = 0.0; rescaleOutput(m_width, m_height, true); mScaleArea = m_currArea; } } RendererImpl::~RendererImpl() { cleanup(); if (AbortEverything) return; #ifdef EXTREME_PARAM_DEBUG AbstractSystem* sys = system(); for (auto &p: StackRule::ParamMap) { if (p.second > 0) sys->message("Parameter at %p is still alive, it is param number %d\n", p.first, p.second); } #endif } class Stopped { }; void RendererImpl::cleanup() { // delete temp files before checking for abort m_finishedFiles.clear(); m_unfinishedFiles.clear(); try { std::function <void (const Shape& s)> releaseParam([](const Shape& s) { if (Renderer::AbortEverything) throw Stopped(); s.releaseParams(); }); for_each(mUnfinishedShapes.begin(), mUnfinishedShapes.end(), releaseParam); for_each(mFinishedShapes.begin(), mFinishedShapes.end(), releaseParam); } catch (Stopped&) { return; } catch (exception& e) { system()->catastrophicError(e.what()); return; } mUnfinishedShapes.clear(); mFinishedShapes.clear(); unwindStack(0, m_cfdg->mCFDGcontents.mParameters); mCurrentPath.reset(); m_cfdg->resetCachedPaths(); } void RendererImpl::setMaxShapes(int n) { m_maxShapes = n ? n : 400000000; } void RendererImpl::resetBounds() { mBounds = Bounds(); } void RendererImpl::outputPrep(Canvas* canvas) { m_canvas = canvas; if (canvas) { m_width = canvas->mWidth; m_height = canvas->mHeight; if (m_tiled || m_frieze) { agg::trans_affine tr; m_cfdg->isTiled(&tr); m_cfdg->isFrieze(&tr); m_tiledCanvas.reset(new tiledCanvas(canvas, tr, m_frieze)); m_tiledCanvas->scale(m_currScale); m_canvas = m_tiledCanvas.get(); } mFrameTimeBounds.load_from(1.0, -Renderer::Infinity, Renderer::Infinity); } requestStop = false; requestFinishUp = false; requestUpdate = false; m_stats.inOutput = false; m_stats.animating = false; m_stats.finalOutput = false; } double RendererImpl::run(Canvas * canvas, bool partialDraw) { if (!m_stats.animating) outputPrep(canvas); int reportAt = 250; Shape initShape = m_cfdg->getInitialShape(this); initShape.mWorldState.mRand64Seed = mCurrentSeed; if (!m_timed) mTimeBounds = initShape.mWorldState.m_time; try { processShape(initShape); } catch (CfdgError& e) { requestStop = true; system()->syntaxError(e); } catch (exception& e) { requestStop = true; system()->catastrophicError(e.what()); } for (;;) { fileIfNecessary(); if (requestStop) break; if (requestFinishUp) break; if (mUnfinishedShapes.empty()) break; if ((m_stats.shapeCount + m_stats.toDoCount) > m_maxShapes) break; // Get the largest unfinished shape Shape s = mUnfinishedShapes.front(); pop_heap(mUnfinishedShapes.begin(), mUnfinishedShapes.end()); mUnfinishedShapes.pop_back(); m_stats.toDoCount--; try { const ASTrule* rule = m_cfdg->findRule(s.mShapeType, s.mWorldState.mRand64Seed.getDouble()); m_drawingMode = false; // shouldn't matter rule->traverse(s, false, this); } catch (CfdgError& e) { requestStop = true; system()->syntaxError(e); break; } catch (exception& e) { requestStop = true; system()->catastrophicError(e.what()); break; } if (requestUpdate || (m_stats.shapeCount > reportAt)) { if (partialDraw) outputPartial(); outputStats(); reportAt = 2 * m_stats.shapeCount; } } if (!m_cfdg->usesTime && !m_timed) mTimeBounds.load_from(1.0, 0.0, mTotalArea); if (!requestStop) { outputFinal(); } if (!requestStop) { outputStats(); if (m_canvas) system()->message("Done."); } if (!m_canvas && m_frieze) rescaleOutput(m_width, m_height, true); return m_currScale; } void RendererImpl::draw(Canvas* canvas) { mFrameTimeBounds.load_from(1.0, -Renderer::Infinity, Renderer::Infinity); outputPrep(canvas); outputFinal(); outputStats(); } class OutputBounds { public: OutputBounds(int frames, const agg::trans_affine_time& timeBounds, int width, int height, RendererImpl& renderer); void apply(const FinishedShape&); const Bounds& frameBounds(int frame) { return mFrameBounds[frame]; } int frameCount(int frame) { return mFrameCounts[frame]; } void finalAccumulate(); // call after all the frames to compute the bounds at each frame void backwardFilter(double framesToHalf); void smooth(int window); private: agg::trans_affine_time mTimeBounds; double mFrameScale; vector<Bounds> mFrameBounds; vector<int> mFrameCounts; double mScale; int mWidth; int mHeight; int mFrames; RendererImpl& mRenderer; OutputBounds& operator=(const OutputBounds&); // not defined }; OutputBounds::OutputBounds(int frames, const agg::trans_affine_time& timeBounds, int width, int height, RendererImpl& renderer) : mTimeBounds(timeBounds), mScale(0.0), mWidth(width), mHeight(height), mFrames(frames), mRenderer(renderer) { mFrameScale = static_cast<double>(frames) / (timeBounds.tend - timeBounds.tbegin); mFrameBounds.resize(frames); mFrameCounts.resize(frames, 0); } void OutputBounds::apply(const FinishedShape& s) { if (mRenderer.requestStop || mRenderer.requestFinishUp) throw Stopped(); if (mScale == 0.0) { // If we don't know the approximate scale yet then just // make an educated guess. mScale = (mWidth + mHeight) / sqrt(fabs(s.mWorldState.m_transform.determinant())); } agg::trans_affine_time frameTime(s.mWorldState.m_time); frameTime.translate(-mTimeBounds.tbegin); frameTime.scale(mFrameScale); int begin = (frameTime.tbegin < mFrames) ? static_cast<int>(floor(frameTime.tbegin)) : (mFrames - 1); int end = (frameTime.tend < mFrames) ? static_cast<int>(floor(frameTime.tend)) : (mFrames - 1); if (begin < 0) begin = 0; if (end < 0) end = 0; for (int frame = begin; frame <= end; ++frame) { mFrameBounds[frame] += s.mBounds; } mFrameCounts[begin] += 1; } void OutputBounds::finalAccumulate() { return; // Accumulation is done in the apply method #if 0 vector<Bounds>::iterator prev, curr, end; prev = mFrameBounds.begin(); end = mFrameBounds.end(); if (prev == end) return; for (curr = prev + 1; curr != end; prev = curr, ++curr) { *curr += *prev; } #endif } void OutputBounds::backwardFilter(double framesToHalf) { double alpha = pow(0.5, 1.0 / framesToHalf); vector<Bounds>::reverse_iterator prev, curr, end; prev = mFrameBounds.rbegin(); end = mFrameBounds.rend(); if (prev == end) return; for (curr = prev + 1; curr != end; prev = curr, ++curr) { *curr = curr->interpolate(*prev, alpha); } } void OutputBounds::smooth(int window) { size_t frames = mFrameBounds.size(); if (frames == 0) return; mFrameBounds.resize(frames + window - 1, mFrameBounds.back()); vector<Bounds>::iterator write, read, end; read = mFrameBounds.begin(); double factor = 1.0 / window; Bounds accum; for (int i = 0; i < window; ++i) accum.gather(*read++, factor); write = mFrameBounds.begin(); end = mFrameBounds.end(); for (;;) { Bounds old = *write; *write++ = accum; accum.gather(old, -factor); if (read == end) break; accum.gather(*read++, factor); } mFrameBounds.resize(frames); } void RendererImpl::animate(Canvas* canvas, int frames, bool zoom) { outputPrep(canvas); const bool ftime = m_cfdg->usesFrameTime; zoom = zoom && !ftime; if (ftime) cleanup(); // start with a blank frame int curr_width = m_width; int curr_height = m_height; rescaleOutput(curr_width, curr_height, true); m_canvas->start(true, m_cfdg->getBackgroundColor(), curr_width, curr_height); m_canvas->end(); double frameInc = (mTimeBounds.tend - mTimeBounds.tbegin) / frames; OutputBounds outputBounds(frames, mTimeBounds, curr_width, curr_height, *this); if (zoom) { system()->message("Computing zoom"); try { forEachShape(true, [&](const FinishedShape& s) { outputBounds.apply(s); }); //outputBounds.finalAccumulate(); outputBounds.backwardFilter(10.0); //outputBounds.smooth(3); } catch (Stopped&) { m_stats.animating = false; return; } catch (exception& e) { system()->catastrophicError(e.what()); return; } } m_stats.shapeCount = 0; m_stats.animating = true; mFrameTimeBounds.tend = mTimeBounds.tbegin; Bounds saveBounds = mBounds; for (int frameCount = 1; frameCount <= frames; ++frameCount) { system()->message("Generating frame %d of %d", frameCount, frames); if (zoom) mBounds = outputBounds.frameBounds(frameCount - 1); m_stats.shapeCount += outputBounds.frameCount(frameCount - 1); mFrameTimeBounds.tbegin = mFrameTimeBounds.tend; mFrameTimeBounds.tend = mTimeBounds.tbegin + frameInc * frameCount; if (ftime) { mCurrentTime = (mFrameTimeBounds.tbegin + mFrameTimeBounds.tend) * 0.5; mCurrentFrame = (frameCount - 1.0)/(frames - 1.0); try { init(); } catch (CfdgError& err) { system()->syntaxError(err); cleanup(); mBounds = saveBounds; m_stats.animating = false; outputStats(); return; } run(canvas, false); m_canvas = canvas; } else { outputFinal(); outputStats(); } if (ftime) cleanup(); if (requestStop || requestFinishUp) break; } mBounds = saveBounds; m_stats.animating = false; outputStats(); system()->message("Animation of %d frames complete", frames); } void RendererImpl::processShape(const Shape& s) { double area = s.area(); if (!isfinite(area)) { requestStop = true; system()->error(); system()->message("A shape got too big."); s.releaseParams(); return; } if (s.mWorldState.m_time.tbegin > s.mWorldState.m_time.tend) { s.releaseParams(); return; } if (m_cfdg->getShapeType(s.mShapeType) == CFDGImpl::ruleType && m_cfdg->shapeHasRules(s.mShapeType)) { // only add it if it's big enough (or if there are no finished shapes yet) if (!mBounds.valid() || (area * mScaleArea >= m_minArea)) { m_stats.toDoCount++; mUnfinishedShapes.push_back(s); push_heap(mUnfinishedShapes.begin(), mUnfinishedShapes.end()); } else { s.releaseParams(); } } else if (m_cfdg->getShapeType(s.mShapeType) == CFDGImpl::pathType) { const ASTrule* rule = m_cfdg->findRule(s.mShapeType, 0.0); processPrimShape(s, rule); } else if (primShape::isPrimShape(s.mShapeType)) { processPrimShape(s); } else { requestStop = true; s.releaseParams(); system()->error(); system()->message("Shape with no rules encountered: %s.", m_cfdg->decodeShapeName(s.mShapeType).c_str()); } } void RendererImpl::processPrimShape(const Shape& s, const ASTrule* path) { size_t num = mSymmetryOps.size(); if (num == 0 || s.mShapeType == primShape::fillType) { processPrimShapeSiblings(s, path); } else { for (size_t i = 0; i < num; ++i) { Shape sym(s); sym.mWorldState.m_transform.multiply(mSymmetryOps[i]); processPrimShapeSiblings(sym, path); } } s.releaseParams(); } void RendererImpl::processPrimShapeSiblings(const Shape& s, const ASTrule* path) { m_stats.shapeCount++; if (mScale == 0.0) { // If we don't know the approximate scale yet then just // make an educated guess. mScale = (m_width + m_height) / sqrt(fabs(s.mWorldState.m_transform.determinant())); } if (path || s.mShapeType != primShape::fillType) { mCurrentCentroid.x = mCurrentCentroid.y = mCurrentArea = 0.0; mPathBounds.invalidate(); m_drawingMode = false; if (path) { mOpsOnly = false; path->traversePath(s, this); } else { CommandInfo* attr = nullptr; if (s.mShapeType < 3) attr = &(shapeMap[s.mShapeType]); processPathCommand(s, attr); } mTotalArea += mCurrentArea; if (!m_tiled && !m_sized) { mBounds.merge(mPathBounds.dilate(mShapeBorder)); if (m_frieze == CFDG::frieze_x) mBounds.mMin_X = -(mBounds.mMax_X = m_frieze_size); if (m_frieze == CFDG::frieze_y) mBounds.mMin_Y = -(mBounds.mMax_Y = m_frieze_size); mScale = mBounds.computeScale(m_width, m_height, mFixedBorderX, mFixedBorderY, false); mScaleArea = mScale * mScale; } } else { mCurrentArea = 1.0; } FinishedShape fs(s, m_stats.shapeCount, mPathBounds); fs.mWorldState.m_Z.sz = mCurrentArea; if (!m_cfdg->usesTime) { fs.mWorldState.m_time.tbegin = mTotalArea; fs.mWorldState.m_time.tend = Renderer::Infinity; } if (fs.mWorldState.m_time.tbegin < mTimeBounds.tbegin && isfinite(fs.mWorldState.m_time.tbegin) && !m_timed) { mTimeBounds.tbegin = fs.mWorldState.m_time.tbegin; } if (fs.mWorldState.m_time.tbegin > mTimeBounds.tend && isfinite(fs.mWorldState.m_time.tbegin) && !m_timed) { mTimeBounds.tend = fs.mWorldState.m_time.tbegin; } if (fs.mWorldState.m_time.tend > mTimeBounds.tend && isfinite(fs.mWorldState.m_time.tend) && !m_timed) { mTimeBounds.tend = fs.mWorldState.m_time.tend; } if (fs.mWorldState.m_time.tend < mTimeBounds.tbegin && isfinite(fs.mWorldState.m_time.tend) && !m_timed) { mTimeBounds.tbegin = fs.mWorldState.m_time.tend; } if (!fs.mWorldState.isFinite()) { requestStop = true; system()->error(); system()->message("A shape got too big."); return; } mFinishedShapes.push_back(fs); if (fs.mParameters) fs.mParameters->retain(this); } void RendererImpl::processSubpath(const Shape& s, bool tr, int expectedType) { const ASTrule* rule = nullptr; if (m_cfdg->getShapeType(s.mShapeType) != CFDGImpl::pathType && primShape::isPrimShape(s.mShapeType) && expectedType == ASTreplacement::op) { static const ASTrule PrimitivePaths[primShape::numTypes] = { { 0 }, { 1 }, { 2 }, { 3 } }; rule = &PrimitivePaths[s.mShapeType]; } else { rule = m_cfdg->findRule(s.mShapeType, 0.0); } if (static_cast<int>(rule->mRuleBody.mRepType) != expectedType) throw CfdgError(rule->mLocation, "Subpath is not of the expected type (path ops/commands)"); bool saveOpsOnly = mOpsOnly; mOpsOnly = mOpsOnly || (expectedType == ASTreplacement::op); rule->mRuleBody.traverse(s, tr, this, true); mOpsOnly = saveOpsOnly; } //-------------------------------------------------------------------------//// void RendererImpl::fileIfNecessary() { if (mFinishedShapes.size() > MoveFinishedAt) moveFinishedToFile(); if (mUnfinishedShapes.size() > MoveUnfinishedAt) moveUnfinishedToTwoFiles(); else if (mUnfinishedShapes.empty()) getUnfinishedFromFile(); } void RendererImpl::moveUnfinishedToTwoFiles() { m_unfinishedFiles.emplace_back(system(), AbstractSystem::ExpensionTemp, "expansion", ++mUnfinishedFileCount); unique_ptr<ostream> f1(m_unfinishedFiles.back().forWrite()); int num1 = m_unfinishedFiles.back().number(); m_unfinishedFiles.emplace_back(system(), AbstractSystem::ExpensionTemp, "expansion", ++mUnfinishedFileCount); unique_ptr<ostream> f2(m_unfinishedFiles.back().forWrite()); int num2 = m_unfinishedFiles.back().number(); system()->message("Writing %s temp files %d & %d", m_unfinishedFiles.back().type().c_str(), num1, num2); size_t count = mUnfinishedShapes.size() / 3; UnfinishedContainer::iterator usi = mUnfinishedShapes.begin(), use = mUnfinishedShapes.end(); usi += count; if (f1->good() && f2->good()) { AbstractSystem::Stats outStats = m_stats; outStats.outputCount = static_cast<int>(count); outStats.outputDone = 0; *f1 << outStats.outputCount; *f2 << outStats.outputCount; outStats.outputCount = static_cast<int>(count * 2); outStats.showProgress = true; // Split the bottom 2/3 of the heap between the two files while (usi != use) { usi->write(*((m_unfinishedInFilesCount & 1) ? f1 : f2)); ++usi; ++m_unfinishedInFilesCount; ++outStats.outputDone; if (requestUpdate) { system()->stats(outStats); requestUpdate = false; } if (requestStop || requestFinishUp) return; } } else { system()->message("Cannot open temporary file for expansions"); requestStop = true; return; } // Remove the written shapes, heap property remains intact static const Shape neverActuallyUsed; mUnfinishedShapes.resize(count, neverActuallyUsed); assert(is_heap(mUnfinishedShapes.begin(), mUnfinishedShapes.end())); } void RendererImpl::getUnfinishedFromFile() { if (m_unfinishedFiles.empty()) return; TempFile t(std::move(m_unfinishedFiles.front())); m_unfinishedFiles.pop_front(); unique_ptr<istream> f(t.forRead()); if (f->good()) { AbstractSystem::Stats outStats = m_stats; *f >> outStats.outputCount; outStats.outputDone = 0; outStats.showProgress = true; istream_iterator<Shape> it(*f); istream_iterator<Shape> eit; back_insert_iterator< UnfinishedContainer > sendto(mUnfinishedShapes); while (it != eit) { *sendto = *it; ++it; ++outStats.outputDone; if (requestUpdate) { system()->stats(outStats); requestUpdate = false; } if (requestStop || requestFinishUp) return; } } else { system()->message("Cannot open temporary file for expansions"); requestStop = true; return; } system()->message("Resorting expansions"); fixupHeap(); } void RendererImpl::fixupHeap() { // Restore heap property to mUnfinishedShapes auto first = mUnfinishedShapes.begin(); auto last = mUnfinishedShapes.end(); typedef UnfinishedContainer::iterator::difference_type difference_type; difference_type n = last - first; if (n < 2) return; AbstractSystem::Stats outStats = m_stats; outStats.outputCount = static_cast<int>(n); outStats.outputDone = 0; outStats.showProgress = true; last = first; ++last; for (difference_type i = 1; i < n; ++i) { push_heap(first, ++last); ++outStats.outputDone; if (requestUpdate) { system()->stats(outStats); requestUpdate = false; } if (requestStop || requestFinishUp) return; } assert(is_heap(mUnfinishedShapes.begin(), mUnfinishedShapes.end())); } //-------------------------------------------------------------------------//// void RendererImpl::moveFinishedToFile() { m_finishedFiles.emplace_back(system(), AbstractSystem::ShapeTemp, "shapes", ++mFinishedFileCount); unique_ptr<ostream> f(m_finishedFiles.back().forWrite()); if (f->good()) { if (mFinishedShapes.size() > 10000) system()->message("Sorting shapes..."); std::sort(mFinishedShapes.begin(), mFinishedShapes.end()); AbstractSystem::Stats outStats = m_stats; outStats.outputCount = static_cast<int>(mFinishedShapes.size()); outStats.outputDone = 0; outStats.showProgress = true; for (const FinishedShape& fs: mFinishedShapes) { *f << fs; ++outStats.outputDone; if (requestUpdate) { system()->stats(outStats); requestUpdate = false; } if (requestStop) return; } } else { system()->message("Cannot open temporary file for shapes"); requestStop = true; return; } mFinishedShapes.clear(); } //-------------------------------------------------------------------------//// void RendererImpl::rescaleOutput(int& curr_width, int& curr_height, bool final) { agg::trans_affine trans; double scale; if (!mBounds.valid()) return; scale = mBounds.computeScale(curr_width, curr_height, mFixedBorderX, mFixedBorderY, true, &trans, m_tiled || m_sized || m_frieze); if (final // if final output || m_currScale == 0.0 // if first time, use this scale || (m_currScale * 0.90) > scale)// if grew by more than 10% { m_currScale = scale; m_currArea = scale * scale; if (m_tiledCanvas) m_tiledCanvas->scale(scale); m_currTrans = trans; m_outputSoFar = 0; m_stats.fullOutput = true; } } void RendererImpl::forEachShape(bool final, ShapeFunction op) { if (!final || m_finishedFiles.empty()) { FinishedContainer::iterator start = mFinishedShapes.begin(); FinishedContainer::iterator last = mFinishedShapes.end(); if (!final) start += m_outputSoFar; for_each(start, last, op); m_outputSoFar = static_cast<int>(mFinishedShapes.size()); } else { deque<TempFile>::iterator begin, last, end; while (m_finishedFiles.size() > MaxMergeFiles) { TempFile t(system(), AbstractSystem::MergeTemp, "merge", ++mFinishedFileCount); { OutputMerge merger; begin = m_finishedFiles.begin(); last = begin + (MaxMergeFiles - 1); end = last + 1; for (auto it = begin; it != end; ++it) merger.addTempFile(*it); std::unique_ptr<ostream> f(t.forWrite()); system()->message("Merging temp files %d through %d", begin->number(), last->number()); merger.merge([&](const FinishedShape& s) { *f << s; }); } // end scope for merger and f for (unsigned i = 0; i < MaxMergeFiles; ++i) m_finishedFiles.pop_front(); m_finishedFiles.push_back(std::move(t)); } OutputMerge merger; begin = m_finishedFiles.begin(); end = m_finishedFiles.end(); for (auto it = begin; it != end; ++it) merger.addTempFile(*it); merger.addShapes(mFinishedShapes.begin(), mFinishedShapes.end()); merger.merge(op); } } void RendererImpl::drawShape(const FinishedShape& s) { if (requestStop) throw Stopped(); if (!mFinal && requestFinishUp) throw Stopped(); if (requestUpdate) outputStats(); if (!s.mWorldState.m_time.overlaps(mFrameTimeBounds)) return; m_stats.outputDone += 1; agg::trans_affine tr = s.mWorldState.m_transform; tr *= m_currTrans; double a = s.mWorldState.m_Z.sz * m_currArea; //fabs(tr.determinant()); if ((!isfinite(a) && s.mShapeType != primShape::fillType) || a < m_minArea) return; if (m_tiledCanvas && s.mShapeType != primShape::fillType) { Bounds b = s.mBounds; m_currTrans.transform(&b.mMin_X, &b.mMin_Y); m_currTrans.transform(&b.mMax_X, &b.mMax_Y); m_tiledCanvas->tileTransform(b); } if (m_cfdg->getShapeType(s.mShapeType) == CFDGImpl::pathType) { //mRenderer.m_canvas->path(s.mColor, tr, *s.mAttributes); const ASTrule* rule = m_cfdg->findRule(s.mShapeType, 0.0); rule->traversePath(s, this); } else { RGBA8 color = m_cfdg->getColor(s.mWorldState.m_Color); switch(s.mShapeType) { case primShape::circleType: m_canvas->circle(color, tr); break; case primShape::squareType: m_canvas->square(color, tr); break; case primShape::triangleType: m_canvas->triangle(color, tr); break; case primShape::fillType: m_canvas->fill(color); break; default: system()->error(); system()->message("Non drawable shape with no rules: %s", m_cfdg->decodeShapeName(s.mShapeType).c_str()); requestStop = true; throw Stopped(); } } } void RendererImpl::output(bool final) { if (!m_canvas) return; if (!final && !m_finishedFiles.empty()) return; // don't do updates once we have temp files m_stats.inOutput = true; m_stats.fullOutput = final; m_stats.finalOutput = final; m_stats.outputCount = m_stats.shapeCount; mFinal = final; int curr_width = m_width; int curr_height = m_height; rescaleOutput(curr_width, curr_height, final); m_stats.outputDone = m_outputSoFar; if (final) { if (mFinishedShapes.size() > 10000) system()->message("Sorting shapes..."); std::sort(mFinishedShapes.begin(), mFinishedShapes.end()); } m_canvas->start(m_outputSoFar == 0, m_cfdg->getBackgroundColor(), curr_width, curr_height); m_drawingMode = true; //OutputDraw draw(*this, final); try { forEachShape(final, [=](const FinishedShape& s) { this->drawShape(s); }); } catch (Stopped&) { } catch (exception& e) { system()->catastrophicError(e.what()); } m_canvas->end(); m_stats.inOutput = false; m_stats.outputTime = m_canvas->mTime; } void RendererImpl::outputStats() { system()->stats(m_stats); requestUpdate = false; } void RendererImpl::processPathCommand(const Shape& s, const AST::CommandInfo* attr) { if (m_drawingMode) { if (m_canvas && attr) { RGBA8 color = m_cfdg->getColor(s.mWorldState.m_Color); agg::trans_affine tr = s.mWorldState.m_transform; tr *= m_currTrans; m_canvas->path(color, tr, *attr); } } else { if (attr) { double area = 0.0; agg::point_d cent(0.0, 0.0); mPathBounds.update(s.mWorldState.m_transform, m_pathIter, mScale, *attr, &cent, &area); mCurrentCentroid.x = (mCurrentCentroid.x * mCurrentArea + cent.x * area) / (mCurrentArea + area); mCurrentCentroid.y = (mCurrentCentroid.x * mCurrentArea + cent.y * area) / (mCurrentArea + area); mCurrentArea = mCurrentArea + area; } } } void RendererImpl::storeParams(const StackRule* p) { p->mRefCount = StackRule::MaxRefCount; m_cfdg->mLongLivedParams.push_back(p); }
burstas/context-free
src-common/renderimpl.cpp
C++
gpl-2.0
35,325
/* Copyright (C) 2003-2015 LiveCode Ltd. This file is part of LiveCode. LiveCode is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License v3 as published by the Free Software Foundation. LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */ #include "prefix.h" #include "globdefs.h" #include "filedefs.h" #include "objdefs.h" #include "parsedef.h" #include "mcio.h" #include "util.h" #include "font.h" #include "sellst.h" #include "stack.h" #include "card.h" #include "field.h" #include "scrolbar.h" #include "mcerror.h" #include "param.h" #include "globals.h" #include "dispatch.h" #include "mctheme.h" #include "exec.h" #include "stackfileformat.h" real8 MCScrollbar::markpos; uint2 MCScrollbar::mode = SM_CLEARED; //////////////////////////////////////////////////////////////////////////////// MCPropertyInfo MCScrollbar::kProperties[] = { DEFINE_RW_OBJ_ENUM_PROPERTY(P_STYLE, InterfaceScrollbarStyle, MCScrollbar, Style) DEFINE_RW_OBJ_PROPERTY(P_THUMB_SIZE, Double, MCScrollbar, ThumbSize) DEFINE_RW_OBJ_PROPERTY(P_THUMB_POS, Double, MCScrollbar, ThumbPos) DEFINE_RW_OBJ_PROPERTY(P_LINE_INC, Double, MCScrollbar, LineInc) DEFINE_RW_OBJ_PROPERTY(P_PAGE_INC, Double, MCScrollbar, PageInc) DEFINE_RO_OBJ_ENUM_PROPERTY(P_ORIENTATION, InterfaceScrollbarOrientation, MCScrollbar, Orientation) DEFINE_RW_OBJ_PROPERTY(P_NUMBER_FORMAT, String, MCScrollbar, NumberFormat) DEFINE_RW_OBJ_PROPERTY(P_START_VALUE, String, MCScrollbar, StartValue) DEFINE_RW_OBJ_PROPERTY(P_END_VALUE, String, MCScrollbar, EndValue) DEFINE_RW_OBJ_PROPERTY(P_SHOW_VALUE, Bool, MCScrollbar, ShowValue) }; MCObjectPropertyTable MCScrollbar::kPropertyTable = { &MCControl::kPropertyTable, sizeof(kProperties) / sizeof(kProperties[0]), &kProperties[0], }; //////////////////////////////////////////////////////////////////////////////// MCScrollbar::MCScrollbar() { flags |= F_HORIZONTAL | F_TRAVERSAL_ON; rect.width = rect.height = DEFAULT_SB_WIDTH; thumbpos = 0.0; thumbsize = 8192.0; pageinc = thumbsize; lineinc = 512.0; // MW-2013-08-27: [[ UnicodifyScrollbar ]] Initialize the members to kMCEmptyString. startstring = MCValueRetain(kMCEmptyString); endstring = MCValueRetain(kMCEmptyString); startvalue = 0.0; endvalue = 65535.0; nffw = 0; nftrailing = 0; nfforce = 0; hover_part = WTHEME_PART_UNDEFINED; linked_control = NULL; m_embedded = false; // MM-2014-07-31: [[ ThreadedRendering ]] Used to ensure the progress bar animate message is only posted from a single thread. m_animate_posted = false; } MCScrollbar::MCScrollbar(const MCScrollbar &sref) : MCControl(sref) { thumbpos = sref.thumbpos; thumbsize = sref.thumbsize; pageinc = sref.pageinc; lineinc = sref.lineinc; // MW-2013-08-27: [[ UnicodifyScrollbar ]] Initialize the members to the other scrollbars values startstring = MCValueRetain(sref . startstring); endstring = MCValueRetain(sref . endstring); startvalue = sref.startvalue; endvalue = sref.endvalue; nffw = sref.nffw; nftrailing = sref.nftrailing; nfforce = sref.nfforce; hover_part = WTHEME_PART_UNDEFINED; linked_control = NULL; m_embedded = false; // MM-2014-07-31: [[ ThreadedRendering ]] Used to ensure the progress bar animate message is only posted from a single thread. m_animate_posted = false; } MCScrollbar::~MCScrollbar() { if (linked_control != NULL) linked_control -> unlink(this); // MW-2013-08-27: [[ UnicodifyScrollbar ]] Release the string members. MCValueRelease(startstring); MCValueRelease(endstring); } Chunk_term MCScrollbar::gettype() const { return CT_SCROLLBAR; } const char *MCScrollbar::gettypestring() { return MCscrollbarstring; } void MCScrollbar::open() { MCControl::open(); // MW-2011-02-03: [[ Bug 7861 ]] Should make working with large Mac progress bars better. if (opened == 1 && !getflag(F_SB_STYLE)) { uint2 oldwidth = MAC_SB_WIDTH; uint2 newwidth = DEFAULT_SB_WIDTH; if (IsMacLFAM()) { oldwidth = DEFAULT_SB_WIDTH; newwidth = MAC_SB_WIDTH; } borderwidth = DEFAULT_BORDER; if (rect.height == oldwidth) rect.height = newwidth; if (rect.width == oldwidth) rect.width = newwidth; } compute_barsize(); } Boolean MCScrollbar::kdown(MCStringRef p_string, KeySym key) { if (!(state & CS_NO_MESSAGES)) if (MCObject::kdown(p_string, key)) return True; Boolean done = False; switch (key) { case XK_Home: update(0.0, MCM_scrollbar_line_inc); done = True; break; case XK_End: update(endvalue, MCM_scrollbar_end); done = True; break; case XK_Right: case XK_Down: update(thumbpos + lineinc, MCM_scrollbar_line_inc); done = True; break; case XK_Left: case XK_Up: update(thumbpos - lineinc, MCM_scrollbar_line_dec); done = True; break; case XK_Prior: update(thumbpos - pageinc, MCM_scrollbar_page_dec); done = True; break; case XK_Next: update(thumbpos + pageinc, MCM_scrollbar_page_inc); done = True; break; default: break; } if (done) message_with_valueref_args(MCM_mouse_up, MCSTR("1")); return done; } Boolean MCScrollbar::mfocus(int2 x, int2 y) { // MW-2007-09-18: [[ Bug 1650 ]] Disabled state linked to thumb size if (!(flags & F_VISIBLE || showinvisible()) || (issbdisabled() && getstack()->gettool(this) == T_BROWSE)) return False; if (state & CS_SCROLL) { // I.M. [[bz 9559]] disable scrolling where start value & end value are the same if (startvalue == endvalue) return True; real8 newpos; double t_thumbsize = thumbsize; if (t_thumbsize > fabs(endvalue - startvalue)) t_thumbsize = fabs(endvalue - startvalue); if (flags & F_SCALE) t_thumbsize = 0; bool t_forward; t_forward = (endvalue > startvalue); MCRectangle t_bar_rect, t_thumb_rect, t_thumb_start_rect, t_thumb_end_rect; t_bar_rect = compute_bar(); t_thumb_rect = compute_thumb(markpos); t_thumb_start_rect = compute_thumb(startvalue); if (t_forward) t_thumb_end_rect = compute_thumb(endvalue - t_thumbsize); else t_thumb_end_rect = compute_thumb(endvalue + t_thumbsize); int32_t t_bar_start, t_bar_length, t_thumb_start, t_thumb_length; int32_t t_movement; if (getstyleint(flags) == F_VERTICAL) { t_bar_start = t_thumb_start_rect.y; t_bar_length = t_thumb_end_rect.y + t_thumb_end_rect.height - t_bar_start; t_thumb_start = t_thumb_rect.y; t_thumb_length = t_thumb_rect.height; t_movement = y - my; } else { t_bar_start = t_thumb_start_rect.x; t_bar_length = t_thumb_end_rect.x + t_thumb_end_rect.width - t_bar_start; t_thumb_start = t_thumb_rect.x; t_thumb_length = t_thumb_rect.width; t_movement = x - mx; } t_bar_start += t_thumb_length / 2; t_bar_length -= t_thumb_length; // AL-2013-07-26: [[ Bug 11044 ]] Prevent divide by zero when computing scrollbar thumbposition if (t_bar_length == 0) t_bar_length = 1; int32_t t_new_position; t_new_position = t_thumb_start + t_thumb_length / 2 + t_movement; t_new_position = MCU_min(t_bar_start + t_bar_length, MCU_max(t_bar_start, t_new_position)); if (t_forward) newpos = startvalue + ((t_new_position - t_bar_start) / (double)t_bar_length) * (fabs(endvalue - startvalue) - t_thumbsize); else newpos = startvalue - ((t_new_position - t_bar_start) / (double)t_bar_length) * (fabs(endvalue - startvalue) - t_thumbsize); update(newpos, MCM_scrollbar_drag); return True; } else if (!MCdispatcher -> isdragtarget() && MCcurtheme && MCcurtheme->getthemepropbool(WTHEME_PROP_SUPPORTHOVERING) && MCU_point_in_rect(rect, x, y) ) { if (!(state & CS_MFOCUSED) && !getstate(CS_SELECTED)) { MCWidgetInfo winfo; winfo.type = (Widget_Type)getwidgetthemetype(); if (MCcurtheme->iswidgetsupported(winfo.type)) { getwidgetthemeinfo(winfo); Widget_Part wpart = MCcurtheme->hittest(winfo,mx,my,rect); if (wpart != hover_part) { hover_part = wpart; // MW-2011-08-18: [[ Layers ]] Invalidate the whole object. redrawall(); } } } } return MCControl::mfocus(x, y); } void MCScrollbar::munfocus() { if (MCcurtheme && hover_part != WTHEME_PART_UNDEFINED && MCcurtheme->getthemepropbool(WTHEME_PROP_SUPPORTHOVERING)) { hover_part = WTHEME_PART_UNDEFINED; // MW-2011-08-18: [[ Layers ]] Invalidate the whole object. redrawall(); } MCControl::munfocus(); } Boolean MCScrollbar::mdown(uint2 which) { if (state & CS_MFOCUSED) return False; if (state & CS_MENU_ATTACHED) return MCObject::mdown(which); state |= CS_MFOCUSED; if (!IsMacEmulatedLF() && flags & F_TRAVERSAL_ON && !(state & CS_KFOCUSED)) getstack()->kfocusset(this); uint2 margin; MCRectangle brect = compute_bar(); if (flags & F_SCALE) margin = 0; else if (getstyleint(flags) == F_VERTICAL) margin = brect.width - 1; else margin = brect.height - 1; Tool tool = state & CS_NO_MESSAGES ? T_BROWSE : getstack()->gettool(this); MCWidgetInfo winfo; winfo.type = (Widget_Type)getwidgetthemetype(); switch (which) { case Button1: switch (tool) { case T_BROWSE: message_with_valueref_args(MCM_mouse_down, MCSTR("1")); if (flags & F_PROGRESS) //progress bar does not respond to mouse down event return False; if (MCcurtheme && MCcurtheme->iswidgetsupported(winfo.type)) { getwidgetthemeinfo(winfo); Widget_Part wpart = MCcurtheme->hittest(winfo,mx,my,rect); // scrollbar needs to check first if mouse-down occured in arrows switch (wpart) { case WTHEME_PART_ARROW_DEC: if (MCmodifierstate & MS_SHIFT) mode = SM_BEGINNING; else mode = SM_LINEDEC; break; case WTHEME_PART_ARROW_INC: if (MCmodifierstate & MS_SHIFT) mode = SM_END; else mode = SM_LINEINC; break; case WTHEME_PART_TRACK_DEC: mode = SM_PAGEDEC; break; case WTHEME_PART_TRACK_INC: mode = SM_PAGEINC; break; } } else { //Non-theme appearence stuff: for vertical scrollbar or scale if (getstyleint(flags) == F_VERTICAL) { uint2 height; if (brect.height <= margin << 1) height = 1; else height = brect.height - (margin << 1); markpos = (my - (brect.y + margin)) * fabs(endvalue - startvalue) / height; if (my < brect.y + margin) if (MCmodifierstate & MS_SHIFT) mode = SM_BEGINNING; else mode = SM_LINEDEC; else if (my > brect.y + brect.height - margin) if (MCmodifierstate & MS_SHIFT) mode = SM_END; else mode = SM_LINEINC; else { MCRectangle thumb = compute_thumb(thumbpos); if (my < thumb.y) mode = SM_PAGEDEC; else if (my > thumb.y + thumb.height) mode = SM_PAGEINC; } } else { //for Horizontal scrollbar or scale uint2 width; if (brect.width <= (margin << 1)) width = 1; else width = brect.width - (margin << 1); markpos = (mx - (brect.x + margin)) * fabs(endvalue - startvalue) / width; if (mx < brect.x + margin) if (MCmodifierstate & MS_SHIFT) mode = SM_BEGINNING; else mode = SM_LINEDEC; else if (mx > brect.x + brect.width - margin) if (MCmodifierstate & MS_SHIFT) mode = SM_END; else mode = SM_LINEINC; else { MCRectangle thumb = compute_thumb(thumbpos); if (mx < thumb.x) mode = SM_PAGEDEC; else if (mx > thumb.x + thumb.width) mode = SM_PAGEINC; } } } //end of Non-MAC-Appearance Manager stuff switch (mode) { case SM_BEGINNING: update(0, MCM_scrollbar_beginning); break; case SM_END: update(endvalue, MCM_scrollbar_end); break; case SM_LINEDEC: case SM_LINEINC: timer(MCM_internal, NULL); redrawarrow(mode); break; case SM_PAGEDEC: case SM_PAGEINC: timer(MCM_internal, NULL); break; default: state |= CS_SCROLL; markpos = thumbpos; if (IsMacEmulatedLF()) movethumb(thumbpos--); else if (MCcurtheme) { // MW-2011-08-18: [[ Layers ]] Invalidate the whole object. redrawall(); } } break; case T_POINTER: case T_SCROLLBAR: start(True); break; case T_HELP: break; default: return False; } break; case Button2: if (message_with_valueref_args(MCM_mouse_down, MCSTR("2")) == ES_NORMAL) return True; state |= CS_SCROLL; { real8 newpos; real8 range = endvalue - startvalue; real8 offset = startvalue; if (flags & F_SCALE) margin = MOTIF_SCALE_THUMB_SIZE >> 1; else if (MCproportionalthumbs) if (startvalue > endvalue) offset += thumbsize / 2.0; else offset -= thumbsize / 2.0; else margin = FIXED_THUMB_SIZE >> 1; if (getstyleint(flags) == F_VERTICAL) newpos = (my - brect.y - margin) * range / (brect.height - (margin << 1)) + offset; else newpos = (mx - brect.x - margin) * range / (brect.width - (margin << 1)) + offset; update(newpos, MCM_scrollbar_drag); markpos = thumbpos; } break; case Button3: message_with_valueref_args(MCM_mouse_down, MCSTR("3")); break; } return True; } Boolean MCScrollbar::mup(uint2 which, bool p_release) { if (!(state & CS_MFOCUSED)) return False; if (state & CS_MENU_ATTACHED) return MCObject::mup(which, p_release); state &= ~CS_MFOCUSED; if (state & CS_GRAB) { ungrab(which); return True; } Tool tool = state & CS_NO_MESSAGES ? T_BROWSE : getstack()->gettool(this); switch (which) { case Button1: switch (tool) { case T_BROWSE: if (state & CS_SCROLL) { state &= ~CS_SCROLL; if (IsMacEmulatedLF()) movethumb(thumbpos--); else if (MCcurtheme) { // MW-2011-08-18: [[ Layers ]] Invalidate the whole object. redrawall(); } } else { uint2 oldmode = mode; mode = SM_CLEARED; if (MCcurtheme) { // MW-2011-08-18: [[ Layers ]] Invalidate the whole object. redrawall(); } else if (oldmode == SM_LINEDEC || oldmode == SM_LINEINC) redrawarrow(oldmode); } if (!p_release && MCU_point_in_rect(rect, mx, my)) message_with_valueref_args(MCM_mouse_up, MCSTR("1")); else message_with_valueref_args(MCM_mouse_release, MCSTR("1")); break; case T_SCROLLBAR: case T_POINTER: end(true, p_release); break; case T_HELP: help(); break; default: return False; } break; case Button2: if (state & CS_SCROLL) { state &= ~CS_SCROLL; // MW-2011-08-18: [[ Layers ]] Invalidate the whole object. redrawall(); } case Button3: if (!p_release && MCU_point_in_rect(rect, mx, my)) message_with_args(MCM_mouse_up, which); else message_with_args(MCM_mouse_release, which); break; } return True; } Boolean MCScrollbar::doubledown(uint2 which) { if (which == Button1 && getstack()->gettool(this) == T_BROWSE) return mdown(which); return MCControl::doubledown(which); } Boolean MCScrollbar::doubleup(uint2 which) { if (which == Button1 && getstack()->gettool(this) == T_BROWSE) return mup(which, false); return MCControl::doubleup(which); } void MCScrollbar::applyrect(const MCRectangle &nrect) { rect = nrect; compute_barsize(); } void MCScrollbar::timer(MCNameRef mptr, MCParameter *params) { if (MCNameIsEqualTo(mptr, MCM_internal, kMCCompareCaseless) || MCNameIsEqualTo(mptr, MCM_internal2, kMCCompareCaseless)) { // MW-2009-06-16: [[ Bug ]] Previously this was only waiting for one // one event (anyevent == True) this meant that it was possible for // the critical 'mouseUp' event to be missed and an effectively // infinite timer loop to be entered if the amount of processing // inbetween timer invocations was too high. So, instead, we process // all events at this point to ensure the mouseUp is handled. // (In the future we should flush mouseUp events to the dispatch queue) // MW-2014-04-16: [[ Bug 12183 ]] This wait does not seem to make much // sense. It seems to be so that a mouseUp in a short space of time // stops the scrollbar from moving. This isn't how things should be I // don't think - so commenting it out for now. // MCscreen->wait(MCsyncrate / 1000.0, True, False); // dispatch mup if (state & CS_MFOCUSED && !MCbuttonstate) { mup(Button1, false); return; } if (mode != SM_CLEARED) { uint2 delay = MCNameIsEqualTo(mptr, MCM_internal, kMCCompareCaseless) ? MCrepeatdelay : MCrepeatrate; MCscreen->addtimer(this, MCM_internal2, delay); MCRectangle thumb; switch (mode) { case SM_LINEDEC: update(thumbpos - lineinc, MCM_scrollbar_line_dec); break; case SM_LINEINC: update(thumbpos + lineinc, MCM_scrollbar_line_inc); break; case SM_PAGEDEC: if ( flags & F_SCALE ) update(thumbpos - pageinc, MCM_scrollbar_page_dec); else { // TH-2008-01-23. Previously was pageinc - lineinc which appeared to be wrong update(thumbpos - (pageinc - lineinc), MCM_scrollbar_page_dec); } thumb = compute_thumb(thumbpos); if (getstyleint(flags) == F_VERTICAL) { if (thumb.y + thumb.height < my) mode = SM_CLEARED; } else if (thumb.x + thumb.height < mx) mode = SM_CLEARED; break; case SM_PAGEINC: if (flags & F_SCALE) update(thumbpos + pageinc, MCM_scrollbar_page_inc); else { // TH-2008-01-23. Previously was pageinc + lineinc which appeared to be wrong. update(thumbpos + (pageinc - lineinc), MCM_scrollbar_page_inc); } thumb = compute_thumb(thumbpos); if (getstyleint(flags) == F_VERTICAL) { if (thumb.y > my) mode = SM_CLEARED; } else if (thumb.x > mx) mode = SM_CLEARED; break; } if (parent->gettype() != CT_CARD) { MCControl *cptr = (MCControl *)parent; cptr->readscrollbars(); } } } else if (MCNameIsEqualTo(mptr, MCM_internal3, kMCCompareCaseless)) { #ifdef _MAC_DESKTOP // MW-2012-09-17: [[ Bug 9212 ]] Mac progress bars do not animate. if (getflag(F_PROGRESS)) { // MM-2014-07-31: [[ ThreadedRendering ]] Flag that there is no longer a progress bar animation message pending. m_animate_posted = false; redrawall(); } #endif } else MCControl::timer(mptr, params); } MCControl *MCScrollbar::clone(Boolean attach, Object_pos p, bool invisible) { MCScrollbar *newscrollbar = new MCScrollbar(*this); if (attach) newscrollbar->attach(p, invisible); return newscrollbar; } void MCScrollbar::compute_barsize() { if (flags & F_SHOW_VALUE && (MClook == LF_MOTIF || getstyleint(flags) == F_VERTICAL)) { if (getstyleint(flags) == F_VERTICAL) { uint2 twidth = rect.width != 0 ? rect.width : 1; barsize = MCU_max(nffw, 1); // MW-2013-08-27: [[ UnicodifyScrollbar ]] Use MCString primitives. if (MCStringGetLength(startstring) > barsize) barsize = MCStringGetLength(startstring); if (MCStringIsEmpty(endstring)) barsize = MCU_max(barsize, 5); else barsize = MCU_max((uindex_t)barsize, MCStringGetLength(endstring)); // MM-2014-04-16: [[ Bug 11964 ]] Pass through the transform of the stack to make sure the measurment is correct for scaled text. barsize *= MCFontMeasureText(m_font, MCSTR("0"), getstack() -> getdevicetransform()); barsize = twidth - (barsize + barsize * (twidth - barsize) / twidth); } else { uint2 theight = rect.height; barsize = theight - gettextheight(); } } else if (getstyleint(flags) == F_VERTICAL) barsize = rect.width; else barsize = rect.height; } MCRectangle MCScrollbar::compute_bar() { MCRectangle brect = rect; if (flags & F_SHOW_VALUE && (MClook == LF_MOTIF || getstyleint(flags) == F_VERTICAL)) { if (getstyleint(flags) == F_VERTICAL) brect.width = barsize; else { brect.y += brect.height - barsize; brect.height = barsize; } } return brect; } MCRectangle MCScrollbar::compute_thumb(real8 pos) { MCRectangle thumb; MCWidgetInfo winfo; winfo.type = (Widget_Type)getwidgetthemetype(); thumb . width = thumb . height = thumb . x = thumb . y = 0 ; // Initialize the values. if (MCcurtheme && MCcurtheme->iswidgetsupported(winfo.type)) { getwidgetthemeinfo(winfo); winfo.part = WTHEME_PART_THUMB; ((MCWidgetScrollBarInfo*)(winfo.data))->thumbpos = pos; MCcurtheme->getwidgetrect(winfo,WTHEME_METRIC_PARTSIZE,rect,thumb); } else { MCRectangle trect = compute_bar(); real8 range = endvalue - startvalue; if (flags & F_SHOW_BORDER && (MClook == LF_MOTIF || !(flags & F_SCALE) || getstyleint(flags) == F_VERTICAL)) { if (IsMacEmulatedLF()) trect = MCU_reduce_rect(trect, 1); else trect = MCU_reduce_rect(trect, borderwidth); } if (getstyleint(flags) == F_VERTICAL) { if (flags & F_SCALE || (thumbsize != 0 && rect.height > rect.width * 3)) { thumb.x = trect.x; thumb.width = trect.width; if (flags & F_SCALE) { real8 height = trect.height - MOTIF_SCALE_THUMB_SIZE; real8 offset = height * (pos - startvalue); thumb.y = trect.y; if (range != 0.0) thumb.y += (int2)(offset / range); thumb.height = MOTIF_SCALE_THUMB_SIZE; } else if (MCproportionalthumbs) { thumb.y = trect.y + trect.width; real8 height = trect.height - (trect.width << 1) + 1; if (range != 0.0 && fabs(endvalue - startvalue) != thumbsize) { int2 miny = thumb.y; real8 offset = height * (pos - startvalue); thumb.y += (int2)(offset / range); range = fabs(range); thumb.height = (uint2)(thumbsize * height / range); uint2 minsize = IsMacEmulatedLF() ? trect.width : MIN_THUMB_SIZE; if (thumb.height < minsize) { uint2 diff = minsize - thumb.height; thumb.height = minsize; thumb.y -= (int2)(diff * (pos + thumbsize - startvalue) / range); if (thumb.y < miny) thumb.y = miny; } } else thumb.height = (int2)height - 1; } else { real8 height = trect.height - (trect.width << 1) - FIXED_THUMB_SIZE; real8 offset = height * (pos - startvalue); if (range < 0) range += thumbsize; else range -= thumbsize; thumb.y = trect.y + trect.width; if (range != 0.0) thumb.y += (int2)(offset / range); thumb.height = FIXED_THUMB_SIZE; } } else thumb.height = 0; } else { // horizontal if (flags & F_SCALE || (thumbsize != 0 && rect.width > rect.height * 3)) { thumb.y = trect.y; thumb.height = trect.height; if (flags & F_SCALE) { switch (MClook) { case LF_MOTIF: thumb.width = MOTIF_SCALE_THUMB_SIZE; break; case LF_MAC: thumb.width = MAC_SCALE_THUMB_SIZE; thumb.height = 16; trect.x += 7; trect.width -= 11; break; default: // Win95's thumb width is computed, varied depends on the height of the rect // if rect.height < 21, scale down the width by a scale factor // WIN_SCALE_THUMB_HEIGHT + space + 4(tic mark) if (trect.height < WIN_SCALE_HEIGHT) thumb.width = trect.height * WIN_SCALE_THUMB_WIDTH / WIN_SCALE_HEIGHT; else thumb.width = WIN_SCALE_THUMB_WIDTH; thumb.height = MCU_min(WIN_SCALE_HEIGHT, trect.height) - 6; } real8 width = trect.width - thumb.width; real8 offset = width * (pos - startvalue); thumb.x = trect.x; if (range != 0.0) thumb.x += (int2)(offset / range); } else if (MCproportionalthumbs) { thumb.x = trect.x + trect.height; real8 width = trect.width - (trect.height << 1) + 1; if (range != 0.0 && fabs(endvalue - startvalue) != thumbsize) { int2 minx = thumb.x; real8 offset = width * (pos - startvalue); thumb.x += (int2)(offset / range); range = fabs(range); thumb.width = (uint2)(thumbsize * width / range); uint2 minsize = IsMacEmulatedLF() ? trect.height : MIN_THUMB_SIZE; if (thumb.width < minsize) { uint2 diff = minsize - thumb.width; thumb.width = minsize; thumb.x -= (int2)(diff * (pos + thumbsize - startvalue) / range); if (thumb.x < minx) thumb.x = minx; } } else thumb.width = (int2)width - 1; } else { real8 width = trect.width - (trect.height << 1) - FIXED_THUMB_SIZE; real8 offset = width * (pos - startvalue); thumb.x = trect.x + trect.height; if (range < 0) range += thumbsize; else range -= thumbsize; if (range != 0.0) thumb.x += (int2)(offset / range); thumb.width = FIXED_THUMB_SIZE; } } else thumb.width = 0; } } return thumb; } void MCScrollbar::update(real8 newpos, MCNameRef mess) { real8 oldpos = thumbpos; real8 ts = thumbsize; if (thumbsize > fabs(endvalue - startvalue)) ts = thumbsize = fabs(endvalue - startvalue); if (flags & F_SB_STYLE) ts = 0; if (startvalue < endvalue) if (newpos < startvalue) thumbpos = startvalue; else if (newpos + ts > endvalue) thumbpos = endvalue - ts; else thumbpos = newpos; else if (newpos > startvalue) thumbpos = startvalue; else if (newpos - ts < endvalue) thumbpos = endvalue + ts; else thumbpos = newpos; if (thumbpos != oldpos) signallisteners(P_THUMB_POS); if ((thumbpos != oldpos || mode == SM_LINEDEC || mode == SM_LINEINC) && opened && (flags & F_VISIBLE || showinvisible())) { if (thumbpos != oldpos) { // MW-2011-08-18: [[ Layers ]] Invalidate the whole object. redrawall(); } MCAutoStringRef t_data; MCU_r8tos(thumbpos, nffw, nftrailing, nfforce, &t_data); switch (message_with_valueref_args(mess, *t_data)) { case ES_NOT_HANDLED: case ES_PASS: if (!MCNameIsEqualTo(mess, MCM_scrollbar_drag, kMCCompareCaseless)) message_with_valueref_args(MCM_scrollbar_drag, *t_data); default: break; } if (linked_control != NULL) linked_control -> readscrollbars(); } } void MCScrollbar::getthumb(real8 &pos) { pos = thumbpos; } void MCScrollbar::setthumb(real8 pos, real8 size, real8 linc, real8 ev) { thumbpos = pos; thumbsize = size; pageinc = size; lineinc = linc; endvalue = ev; // MW-2008-11-02: [[ Bug ]] This method is only used by scrollbars directly // attached to controls. In this case, they are created from the templateScrollbar // and this means 'startValue' could be anything - however we need it to be zero // if we want to avoid strangeness. startvalue = 0.0; } void MCScrollbar::movethumb(real8 pos) { if (thumbpos != pos) { thumbpos = pos; // MW-2011-08-18: [[ Layers ]] Invalidate the whole object. redrawall(); } } void MCScrollbar::setborderwidth(uint1 nw) { int2 d = nw - borderwidth; if (rect.width <= rect.height) { rect.width += d << 1; rect.x -= d; } else { rect.height += d << 1; rect.y -= d; } borderwidth = nw; } void MCScrollbar::reset() { flags &= ~F_HAS_VALUES; startvalue = 0.0; endvalue = 65535.0; // MW-2013-08-27: [[ UnicodifyScrollbar ]] Reset the string values to the empty string. MCValueAssign(startstring, kMCEmptyString); MCValueAssign(endstring, kMCEmptyString); } void MCScrollbar::redrawarrow(uint2 oldmode) { // MW-2011-08-18: [[ Layers ]] Invalidate the whole object. redrawall(); } bool MCScrollbar::issbdisabled(void) const { bool ret; ret = getflag(F_DISABLED) || (MClook != LF_MOTIF && !(flags & F_SB_STYLE) && fabs(endvalue - startvalue) == thumbsize); return ret; } void MCScrollbar::link(MCControl *p_control) { linked_control = p_control; } // MW-2012-09-20: [[ Bug 10395 ]] This method is invoked rather than layer_redrawall() // to ensure that in the embedded case, the parent's layer is updated. void MCScrollbar::redrawall(void) { if (!m_embedded) { layer_redrawall(); return; } ((MCControl *)parent) -> layer_redrawrect(getrect()); } // MW-2012-09-20: [[ Bug 10395 ]] This method marks the control as embedded // thus causing it to redraw through its parent. void MCScrollbar::setembedded(void) { m_embedded = true; } /////////////////////////////////////////////////////////////////////////////// // // SAVING AND LOADING // IO_stat MCScrollbar::extendedsave(MCObjectOutputStream& p_stream, uint4 p_part, uint32_t p_version) { return defaultextendedsave(p_stream, p_part, p_version); } IO_stat MCScrollbar::extendedload(MCObjectInputStream& p_stream, uint32_t p_version, uint4 p_length) { return defaultextendedload(p_stream, p_version, p_length); } IO_stat MCScrollbar::save(IO_handle stream, uint4 p_part, bool p_force_ext, uint32_t p_version) { IO_stat stat; if ((stat = IO_write_uint1(OT_SCROLLBAR, stream)) != IO_NORMAL) return stat; if ((stat = MCControl::save(stream, p_part, p_force_ext, p_version)) != IO_NORMAL) return stat; if (flags & F_SAVE_ATTS) { real8 range = endvalue - startvalue; if (range != 0.0) range = 65535.0 / range; uint2 i2 = (uint2)((thumbpos - startvalue) * range); if ((stat = IO_write_uint2(i2, stream)) != IO_NORMAL) return stat; i2 = (uint2)(thumbsize * range); if ((stat = IO_write_uint2(i2, stream)) != IO_NORMAL) return stat; i2 = (uint2)(lineinc * range); if ((stat = IO_write_uint2(i2, stream)) != IO_NORMAL) return stat; i2 = (uint2)(pageinc * range); if ((stat = IO_write_uint2(i2, stream)) != IO_NORMAL) return stat; if (flags & F_HAS_VALUES) { // MW-2013-08-27: [[ UnicodifyScrollbar ]] Update to use stringref primitives. // MW-2013-11-20: [[ UnicodeFileFormat ]] If sfv >= 7000, use unicode. if ((stat = IO_write_stringref_new(startstring, stream, p_version >= kMCStackFileFormatVersion_7_0)) != IO_NORMAL) return stat; // MW-2013-11-20: [[ UnicodeFileFormat ]] If sfv >= 7000, use unicode. if ((stat = IO_write_stringref_new(endstring, stream, p_version >= kMCStackFileFormatVersion_7_0)) != IO_NORMAL) return stat; if ((stat = IO_write_uint2(nffw, stream)) != IO_NORMAL) return stat; if ((stat = IO_write_uint2(nftrailing, stream)) != IO_NORMAL) return stat; if ((stat = IO_write_uint2(nfforce, stream)) != IO_NORMAL) return stat; } } return savepropsets(stream, p_version); } IO_stat MCScrollbar::load(IO_handle stream, uint32_t version) { IO_stat stat; if ((stat = MCObject::load(stream, version)) != IO_NORMAL) return checkloadstat(stat); if (flags & F_SAVE_ATTS) { uint2 i2; if ((stat = IO_read_uint2(&i2, stream)) != IO_NORMAL) return checkloadstat(stat); thumbpos = (real8)i2; if ((stat = IO_read_uint2(&i2, stream)) != IO_NORMAL) return checkloadstat(stat); thumbsize = (real8)i2; if ((stat = IO_read_uint2(&i2, stream)) != IO_NORMAL) return checkloadstat(stat); lineinc = (real8)i2; if ((stat = IO_read_uint2(&i2, stream)) != IO_NORMAL) return checkloadstat(stat); pageinc = (real8)i2; if (flags & F_HAS_VALUES) { // MW-2013-08-27: [[ UnicodifyScrollbar ]] Update to use stringref primitives. // MW-2013-11-20: [[ UnicodeFileFormat ]] If sfv >= 7000, use unicode. if ((stat = IO_read_stringref_new(startstring, stream, version >= kMCStackFileFormatVersion_7_0)) != IO_NORMAL) return checkloadstat(stat); if (!MCStringToDouble(startstring, startvalue)) startvalue = 0.0; // MW-2013-08-27: [[ UnicodifyScrollbar ]] Update to use stringref primitives. // MW-2013-11-20: [[ UnicodeFileFormat ]] If sfv >= 7000, use unicode. if ((stat = IO_read_stringref_new(endstring, stream, version >= kMCStackFileFormatVersion_7_0)) != IO_NORMAL) return checkloadstat(stat); if (!MCStringToDouble(endstring, endvalue)) endvalue = 0.0; real8 range = (endvalue - startvalue) / 65535.0; thumbpos = thumbpos * range + startvalue; thumbsize *= range; lineinc *= range; pageinc *= range; if ((stat = IO_read_uint2(&nffw, stream)) != IO_NORMAL) return checkloadstat(stat); if ((stat = IO_read_uint2(&nftrailing, stream)) != IO_NORMAL) return checkloadstat(stat); if ((stat = IO_read_uint2(&nfforce, stream)) != IO_NORMAL) return checkloadstat(stat); } } if (version <= kMCStackFileFormatVersion_2_0) { if (flags & F_TRAVERSAL_ON) rect = MCU_reduce_rect(rect, MCfocuswidth); if (flags & F_SHOW_VALUE && getstyleint(flags) == F_HORIZONTAL) rect = MCU_reduce_rect(rect, 4); } return loadpropsets(stream, version); }
PaulMcClernan/livecode
engine/src/scrolbar.cpp
C++
gpl-3.0
33,008
using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; namespace NzbDrone.Core.ImportLists.StevenLu { public class StevenLuSettingsValidator : AbstractValidator<StevenLuSettings> { public StevenLuSettingsValidator() { RuleFor(c => c.Link).ValidRootUrl(); } } public class StevenLuSettings : IProviderConfig { private static readonly StevenLuSettingsValidator Validator = new StevenLuSettingsValidator(); public StevenLuSettings() { Link = "https://s3.amazonaws.com/popular-movies/movies.json"; } [FieldDefinition(0, Label = "URL", HelpText = "Don't change this unless you know what you are doing.")] public string Link { get; set; } public NzbDroneValidationResult Validate() { return new NzbDroneValidationResult(Validator.Validate(this)); } } }
Radarr/Radarr
src/NzbDrone.Core/ImportLists/StevenLu/StevenLuSettings.cs
C#
gpl-3.0
981
static void Button_tick(Button *self) { if(self->onTick) self->onTick(); } void Button::create(Window &parent, unsigned x, unsigned y, unsigned width, unsigned height, const string &text) { object->widget = gtk_button_new_with_label(text); widget->parent = &parent; gtk_widget_set_size_request(object->widget, width, height); g_signal_connect_swapped(G_OBJECT(object->widget), "clicked", G_CALLBACK(Button_tick), (gpointer)this); if(parent.window->defaultFont) setFont(*parent.window->defaultFont); gtk_fixed_put(GTK_FIXED(parent.object->formContainer), object->widget, x, y); gtk_widget_show(object->widget); }
grim210/defimulator
snespurify/phoenix/gtk/button.cpp
C++
gpl-3.0
629
<?php /* Copyright (C) 2001-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004-2016 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2009 Regis Houssin <regis.houssin@capnetworks.com> * Copyright (C) 2013 Antoine Iauch <aiauch@gpcsolutions.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * \file htdocs/compta/stats/cabyuser.php * \brief Page reporting Salesover by user */ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $socid = GETPOST('socid','int'); // Security check if ($user->societe_id > 0) $socid = $user->societe_id; if (! empty($conf->comptabilite->enabled)) $result=restrictedArea($user,'compta','','','resultat'); if (! empty($conf->accounting->enabled)) $result=restrictedArea($user,'accounting','','','comptarapport'); // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') $modecompta = $conf->global->ACCOUNTING_MODE; if (GETPOST("modecompta")) $modecompta=GETPOST("modecompta"); $sortorder=isset($_GET["sortorder"])?$_GET["sortorder"]:$_POST["sortorder"]; $sortfield=isset($_GET["sortfield"])?$_GET["sortfield"]:$_POST["sortfield"]; if (! $sortorder) $sortorder="asc"; if (! $sortfield) $sortfield="name"; // Date range $year=GETPOST("year"); $month=GETPOST("month"); $date_startyear = GETPOST("date_startyear"); $date_startmonth = GETPOST("date_startmonth"); $date_startday = GETPOST("date_startday"); $date_endyear = GETPOST("date_endyear"); $date_endmonth = GETPOST("date_endmonth"); $date_endday = GETPOST("date_endday"); if (empty($year)) { $year_current = strftime("%Y",dol_now()); $month_current = strftime("%m",dol_now()); $year_start = $year_current; } else { $year_current = $year; $month_current = strftime("%m",dol_now()); $year_start = $year; } $date_start=dol_mktime(0,0,0,$_REQUEST["date_startmonth"],$_REQUEST["date_startday"],$_REQUEST["date_startyear"]); $date_end=dol_mktime(23,59,59,$_REQUEST["date_endmonth"],$_REQUEST["date_endday"],$_REQUEST["date_endyear"]); // Quarter if (empty($date_start) || empty($date_end)) // We define date_start and date_end { $q=GETPOST("q")?GETPOST("q"):0; if ($q==0) { // We define date_start and date_end $month_start=GETPOST("month")?GETPOST("month"):($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); $year_end=$year_start; $month_end=$month_start; if (! GETPOST("month")) // If month not forced { if (! GETPOST('year') && $month_start > $month_current) { $year_start--; $year_end--; } $month_end=$month_start-1; if ($month_end < 1) $month_end=12; else $year_end++; } $date_start=dol_get_first_day($year_start,$month_start,false); $date_end=dol_get_last_day($year_end,$month_end,false); } if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } } else { // TODO We define q } $commonparams=array(); $commonparams['modecompta']=$modecompta; $commonparams['sortorder'] = $sortorder; $commonparams['sortfield'] = $sortfield; $headerparams = array(); $headerparams['date_startyear'] = $date_startyear; $headerparams['date_startmonth'] = $date_startmonth; $headerparams['date_startday'] = $date_startday; $headerparams['date_endyear'] = $date_endyear; $headerparams['date_endmonth'] = $date_endmonth; $headerparams['date_endday'] = $date_endday; $headerparams['q'] = $q; $tableparams = array(); $tableparams['search_categ'] = $selected_cat; $tableparams['subcat'] = ($subcat === true)?'yes':''; // Adding common parameters $allparams = array_merge($commonparams, $headerparams, $tableparams); $headerparams = array_merge($commonparams, $headerparams); $tableparams = array_merge($commonparams, $tableparams); foreach($allparams as $key => $value) { $paramslink .= '&' . $key . '=' . $value; } /* * View */ llxHeader(); $form=new Form($db); // Show report header if ($modecompta=="CREANCES-DETTES") { $nom=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice"); $calcmode=$langs->trans("CalcModeDebt"); $calcmode.='<br>('.$langs->trans("SeeReportInInputOutputMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'&modecompta=RECETTES-DEPENSES">','</a>').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); //$periodlink="<a href='".$_SERVER["PHP_SELF"]."?year=".($year-1)."&modecompta=".$modecompta."'>".img_previous()."</a> <a href='".$_SERVER["PHP_SELF"]."?year=".($year+1)."&modecompta=".$modecompta."'>".img_next()."</a>"; $description=$langs->trans("RulesCADue"); if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); else $description.= $langs->trans("DepositsAreIncluded"); $builddate=time(); //$exportlink=$langs->trans("NotYetAvailable"); } else { $nom=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice"); $calcmode=$langs->trans("CalcModeEngagement"); $calcmode.='<br>('.$langs->trans("SeeReportInDueDebtMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'&modecompta=CREANCES-DETTES">','</a>').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); //$periodlink="<a href='".$_SERVER["PHP_SELF"]."?year=".($year-1)."&modecompta=".$modecompta."'>".img_previous()."</a> <a href='".$_SERVER["PHP_SELF"]."?year=".($year+1)."&modecompta=".$modecompta."'>".img_next()."</a>"; $description=$langs->trans("RulesCAIn"); $description.= $langs->trans("DepositsAreIncluded"); $builddate=time(); //$exportlink=$langs->trans("NotYetAvailable"); } $moreparam=array(); if (! empty($modecompta)) $moreparam['modecompta']=$modecompta; report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,$moreparam,$calcmode); if (! empty($conf->accounting->enabled)) { print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); } // Show array print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; // Extra parameters management foreach($headerparams as $key => $value) { print '<input type="hidden" name="'.$key.'" value="'.$value.'">'; } $catotal=0; if ($modecompta == 'CREANCES-DETTES') { $sql = "SELECT u.rowid as rowid, u.lastname as name, u.firstname as firstname, sum(f.total) as amount, sum(f.total_ttc) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.fk_user_author = u.rowid"; $sql.= " WHERE f.fk_statut in (1,2)"; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $sql.= " AND f.type IN (0,1,2,5)"; } else { $sql.= " AND f.type IN (0,1,2,3,5)"; } if ($date_start && $date_end) { $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; } } else { /* * Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les * vieilles versions, ils n'etaient pas lies via paiement_facture. On les ajoute plus loin) */ $sql = "SELECT u.rowid as rowid, u.lastname as name, u.firstname as firstname, sum(pf.amount) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."user as u" ; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.fk_user_author = u.rowid "; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_facture = f.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement as p ON p.rowid = pf.fk_paiement"; $sql.= " WHERE 1=1"; if ($date_start && $date_end) { $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; } } $sql.= " AND f.entity = ".$conf->entity; if ($socid) $sql.= " AND f.fk_soc = ".$socid; $sql .= " GROUP BY u.rowid, u.lastname, u.firstname"; $sql .= " ORDER BY u.rowid"; $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $i=0; while ($i < $num) { $obj = $db->fetch_object($result); $amount_ht[$obj->rowid] = $obj->amount; $amount[$obj->rowid] = $obj->amount_ttc; $name[$obj->rowid] = $obj->name.' '.$obj->firstname; $catotal_ht+=$obj->amount; $catotal+=$obj->amount_ttc; $i++; } } else { dol_print_error($db); } // Adding old-version payments, non-bound by "paiement_facture" then without User if ($modecompta != 'CREANCES-DETTES') { $sql = "SELECT -1 as rowidx, '' as name, '' as firstname, sum(DISTINCT p.amount) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; $sql.= " WHERE pf.rowid IS NULL"; $sql.= " AND p.fk_bank = b.rowid"; $sql.= " AND b.fk_account = ba.rowid"; $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; if ($date_start && $date_end) { $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; } $sql.= " GROUP BY rowidx, name, firstname"; $sql.= " ORDER BY rowidx"; $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $i=0; while ($i < $num) { $obj = $db->fetch_object($result); $amount[$obj->rowidx] = $obj->amount_ttc; $name[$obj->rowidx] = $obj->name.' '.$obj->firstname; $catotal+=$obj->amount_ttc; $i++; } } else { dol_print_error($db); } } $morefilter=''; print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n"; print "<tr class=\"liste_titre\">"; print_liste_field_titre( $langs->trans("User"), $_SERVER["PHP_SELF"], "name", "", $paramslink, "", $sortfield, $sortorder ); if ($modecompta == 'CREANCES-DETTES') { print_liste_field_titre( $langs->trans('AmountHT'), $_SERVER["PHP_SELF"], "amount_ht", "", $paramslink, 'align="right"', $sortfield, $sortorder ); } else { print_liste_field_titre(''); } print_liste_field_titre( $langs->trans("AmountTTC"), $_SERVER["PHP_SELF"], "amount_ttc", "", $paramslink, 'align="right"', $sortfield, $sortorder ); print_liste_field_titre( $langs->trans("Percentage"), $_SERVER["PHP_SELF"],"amount_ttc", "", $paramslink, 'align="right"', $sortfield, $sortorder ); print_liste_field_titre( $langs->trans("OtherStatistics"), $_SERVER["PHP_SELF"], "", "", "", 'align="center" width="20%"' ); print "</tr>\n"; $var=true; if (count($amount)) { $arrayforsort=$name; // We define arrayforsort if ($sortfield == 'name' && $sortorder == 'asc') { asort($name); $arrayforsort=$name; } if ($sortfield == 'name' && $sortorder == 'desc') { arsort($name); $arrayforsort=$name; } if ($sortfield == 'amount_ht' && $sortorder == 'asc') { asort($amount_ht); $arrayforsort=$amount_ht; } if ($sortfield == 'amount_ht' && $sortorder == 'desc') { arsort($amount_ht); $arrayforsort=$amount_ht; } if ($sortfield == 'amount_ttc' && $sortorder == 'asc') { asort($amount); $arrayforsort=$amount; } if ($sortfield == 'amount_ttc' && $sortorder == 'desc') { arsort($amount); $arrayforsort=$amount; } $i = 0; foreach($arrayforsort as $key => $value) { print '<tr class="oddeven">'; // Third party $fullname=$name[$key]; if ($key >= 0) { $linkname='<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$key.'">'.img_object($langs->trans("ShowUser"),'user').' '.$fullname.'</a>'; } else { $linkname=$langs->trans("PaymentsNotLinkedToUser"); } print "<td>".$linkname."</td>\n"; // Amount w/o VAT print '<td align="right">'; if ($modecompta != 'CREANCES-DETTES') { if ($key > 0) { print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?userid='.$key.'">'; } else { print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?userid=-1">'; } } else { if ($key > 0) { print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?userid='.$key.'">'; } else { print '<a href="#">'; } print price($amount_ht[$key]); } print '</td>'; // Amount with VAT print '<td align="right">'; if ($modecompta != 'CREANCES-DETTES') { if ($key > 0) { print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?userid='.$key.'">'; } else { print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?userid=-1">'; } } else { if ($key > 0) { print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?userid='.$key.'">'; } else { print '<a href="#">'; } } print price($amount[$key]); print '</td>'; // Percent print '<td align="right">'.($catotal > 0 ? round(100 * $amount[$key] / $catotal,2).'%' : '&nbsp;').'</td>'; // Other stats print '<td align="center">'; if (! empty($conf->propal->enabled) && $key>0) { print '&nbsp;<a href="'.DOL_URL_ROOT.'/comm/propal/stats/index.php?userid='.$key.'">'.img_picto($langs->trans("ProposalStats"),"stats").'</a>&nbsp;'; } if (! empty($conf->commande->enabled) && $key>0) { print '&nbsp;<a href="'.DOL_URL_ROOT.'/commande/stats/index.php?userid='.$key.'">'.img_picto($langs->trans("OrderStats"),"stats").'</a>&nbsp;'; } if (! empty($conf->facture->enabled) && $key>0) { print '&nbsp;<a href="'.DOL_URL_ROOT.'/compta/facture/stats/index.php?userid='.$key.'">'.img_picto($langs->trans("InvoiceStats"),"stats").'</a>&nbsp;'; } print '</td>'; print "</tr>\n"; $i++; } // Total print '<tr class="liste_total">'; print '<td>'.$langs->trans("Total").'</td>'; if ($modecompta != 'CREANCES-DETTES') { print '<td colspan="1"></td>'; } else { print '<td align="right">'.price($catotal_ht).'</td>'; } print '<td align="right">'.price($catotal).'</td>'; print '<td>&nbsp;</td>'; print '<td>&nbsp;</td>'; print '</tr>'; $db->free($result); } print "</table>"; print '</div>'; print '</form>'; llxFooter(); $db->close();
apachler/dolibarr
htdocs/compta/stats/cabyuser.php
PHP
gpl-3.0
15,636
package utils import ( "os" "path/filepath" "github.com/securityfirst/tent/component" ) func WriteCmp(base string, c component.Component) error { path := filepath.Join(base, c.Path()) if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil { return err } f, err := os.Create(path) if err != nil { return err } if _, err := f.WriteString(c.Contents()); err != nil { return err } return nil }
securityfirst/tent
utils/persistence.go
GO
gpl-3.0
416
System.register(['angular2/core'], function(exports_1) { var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1; var MyComponent; return { setters:[ function (core_1_1) { core_1 = core_1_1; }], execute: function() { MyComponent = (function () { function MyComponent() { } MyComponent = __decorate([ core_1.Component({ selector: 'my-component', template: '<h1>My Component</h1>' }), __metadata('design:paramtypes', []) ], MyComponent); return MyComponent; })(); exports_1("MyComponent", MyComponent); } } }); //# sourceMappingURL=my_component.js.map
burner/AngularVibed
Examples2/Example05/node_modules/angular2/ts/examples/core/ts/prod_mode/my_component.js
JavaScript
gpl-3.0
1,526
<?php // This is a SPIP language file -- Ceci est un fichier langue de SPIP // extrait automatiquement de http://trad.spip.net/tradlang_module/forum?lang_cible=id // ** ne pas modifier le fichier ** if (!defined('_ECRIRE_INC_VERSION')) { return; } $GLOBALS[$GLOBALS['idx_lang']] = array( // B 'bouton_radio_articles_futurs' => 'untuk artikel yang akan dipublikasikan di masa depan saja (tidak ada aksi di database).', 'bouton_radio_articles_tous' => 'untuk semua artikel tanpa pengecualian.', 'bouton_radio_articles_tous_sauf_forum_desactive' => 'untuk semua artikel, terkecuali artikel yang forumnya dinonaktifkan.', 'bouton_radio_enregistrement_obligatoire' => 'Registrasi diperlukan (pengguna harus mendaftarkan diri dengan memberikan alamat e-mailnya sebelum dapat berkontribusi).', 'bouton_radio_moderation_priori' => 'Moderasi awal ( kontribusi hanya akan ditampilkan setelah validasi oleh administrator).', # MODIF 'bouton_radio_modere_abonnement' => 'registrasi diperlukan', 'bouton_radio_modere_posteriori' => 'moderasi akhir', # MODIF 'bouton_radio_modere_priori' => 'moderasi awal', # MODIF 'bouton_radio_publication_immediate' => 'Publikasi pesan segera (kontribusi akan ditampilkan sesegera mungkin setelah dikirimkan, kemudian administrator dapat menghapusnya).', // F 'form_pet_message_commentaire' => 'Ada pesan atau komentar?', 'forum' => 'Forum', 'forum_acces_refuse' => 'Anda tidak memiliki akses ke forum ini lagi.', 'forum_attention_dix_caracteres' => '<b>Peringatan!</b> Pesan anda hendaknya terdiri dari sepuluh karakter atau lebih.', 'forum_attention_trois_caracteres' => '<b>Peringatan!</b> Judul anda hendaknya terdiri dari tiga karakter atau lebih.', 'forum_attention_trop_caracteres' => '<b>Peringatan !</b> pesan anda terlalu panjang (@compte@ karakter) : untuk dapat menyimpannya, pesan tidak boleh lebih dari @max@ karakter.', # MODIF 'forum_avez_selectionne' => 'Anda telah memilih:', 'forum_cliquer_retour' => 'Klik <a href=\'@retour_forum@\'>di sini</a> untuk lanjut.', 'forum_forum' => 'forum', 'forum_info_modere' => 'Forum ini telah dimoderasi: kontribusi anda hanya akan muncul setelah divalidasi oleh administrator situs.', # MODIF 'forum_lien_hyper' => '<b>Tautan web</b> (opsional)', # MODIF 'forum_message_definitif' => 'Pesan akhir: kirim ke situs', 'forum_message_trop_long' => 'Pesan anda terlalu panjang. Panjang maksimum adalah 20000 karakter.', # MODIF 'forum_ne_repondez_pas' => 'Jangan balas ke e-mail ini tapi ke forum yang terdapat di alamat berikut:', # MODIF 'forum_page_url' => '(Jika pesan anda merujuk pada sebuah artikel yang dipublikasi di web atau halaman yang memberikan informasi lebih lanjut, silakan masukkan judul halaman dan URL-nya di bawah).', 'forum_poste_par' => 'Pesan dikirim@parauteur@ mengikuti artikel anda.', # MODIF 'forum_qui_etes_vous' => '<b>Siapa anda?</b> (opsional)', # MODIF 'forum_texte' => 'Teks pesan anda:', # MODIF 'forum_titre' => 'Subyek:', # MODIF 'forum_url' => 'URL:', # MODIF 'forum_valider' => 'Validasi pilihan ini', 'forum_voir_avant' => 'Lihat pesan sebelum dikirim', # MODIF 'forum_votre_email' => 'Alamat e-mail anda:', # MODIF 'forum_votre_nom' => 'Nama anda (atau alias):', # MODIF 'forum_vous_enregistrer' => 'Sebelum berpartisipasi di forum ini, anda harus mendaftarkan diri. Terima kasih telah memasukkan pengidentifikasi pribadi yang diberikan pada anda. Jika anda belum terdaftar, anda harus', 'forum_vous_inscrire' => 'mendaftarkan diri.', // I 'icone_poster_message' => 'Kirim sebuah pesan', 'icone_suivi_forum' => 'Tindak lanjut dari forum umum: @nb_forums@ kontribusi', 'icone_suivi_forums' => 'Kelola forum', 'icone_supprimer_message' => 'Hapus pesan ini', 'icone_valider_message' => 'Validasi pesan ini', 'info_activer_forum_public' => '<i>Untuk mengaktifkan forum-forum umum, silakan pilih mode moderasi standar forum-forum tersebut:</I>', # MODIF 'info_appliquer_choix_moderation' => 'Terapkan pilihan moderasi ini:', 'info_desactiver_forum_public' => 'Non aktifkan penggunaan forum umum. Forum umum dapat digunakan berdasarkan kasus per kasus untuk artikel-artikel; dan penggunannya dilarang untuk bagian, berita, dll.', 'info_envoi_forum' => 'Kirim forum ke penulis artikel', 'info_fonctionnement_forum' => 'Operasi forum:', 'info_gauche_suivi_forum_2' => 'Halaman <i>tindak lanjut forum</i> adalah alat bantu pengelola situs anda (bukan area diskusi atau pengeditan). Halaman ini menampilkan semua kontribusi forum umum artikel ini dan mengizinkan anda untuk mengelola kontribusi-kontribusi ini.', # MODIF 'info_liens_syndiques_3' => 'forum', 'info_liens_syndiques_4' => 'adalah', 'info_liens_syndiques_5' => 'forum', 'info_liens_syndiques_6' => 'adalah', 'info_liens_syndiques_7' => 'validasi tertunda.', 'info_mode_fonctionnement_defaut_forum_public' => 'Mode operasi standar forum-forum umum', 'info_option_email' => 'Ketika seorang pengunjung situs mengirimkan sebuah pesan ke forum yang terasosiasi dengan sebuah artikel, penulis artikel akan diinformasikan melalui e-mail. Anda ingin menggunakan opsi ini?', # MODIF 'info_pas_de_forum' => 'tidak ada forum', 'item_activer_forum_administrateur' => 'Aktifkan forum administrator', 'item_desactiver_forum_administrateur' => 'Non aktifkan forum administrator', // L 'lien_reponse_article' => 'Balasan pada artikel', 'lien_reponse_breve_2' => 'Balasan pada artikel berita', 'lien_reponse_rubrique' => 'Balasan pada bagian', 'lien_reponse_site_reference' => 'Balasan pada situs-situs referensi:', # MODIF // O 'onglet_messages_internes' => 'Pesan internal', 'onglet_messages_publics' => 'Pesan umum', 'onglet_messages_vide' => 'Pesan tanpa teks', // R 'repondre_message' => 'Balasan pada pesan ini', // S 'statut_original' => 'asli', // T 'titre_cadre_forum_administrateur' => 'Forum pribadi para administrator', 'titre_cadre_forum_interne' => 'Forum intern', 'titre_forum' => 'Forum', 'titre_forum_suivi' => 'Tindak lanjut forum', 'titre_page_forum_suivi' => 'Tindak lanjut forum' ); ?>
ernestovi/ups
spip/plugins-dist/forum/lang/forum_id.php
PHP
gpl-3.0
6,067
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. * * The contents of this file are subject to the terms of the GNU General Public License Version 3 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each file. */ package org.openconcerto.sql.view; public interface EditPanelListener { public void cancelled(); public void modified(); public void deleted(); public void inserted(int id); }
eric-lemesre/OpenConcerto
OpenConcerto/src/org/openconcerto/sql/view/EditPanelListener.java
Java
gpl-3.0
830
@extends('hideyo_backend::_layouts.default') @section('main') <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> @include('hideyo_backend::_partials.news-tabs', array('newsEdit' => true)) </div> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <ol class="breadcrumb"> <li><a href="/"><i class="entypo-folder"></i>Dashboard</a></li> <li><a href="{!! URL::route('hideyo.news.index') !!}">News</a></li> <li><a href="{!! URL::route('hideyo.news.edit', $news->id) !!}">edit</a></li> <li><a href="{!! URL::route('hideyo.news.edit', $news->id) !!}">{!! $news->title !!}</a></li> </ol> <h2>News <small>edit</small></h2> <hr/> {!! Notification::showAll() !!} {!! Form::model($news, array('method' => 'put', 'route' => array('hideyo.news.update', $news->id), 'files' => true, 'class' => 'form-horizontal form-groups-bordered validate')) !!} <input type="hidden" name="_token" value="{!! Session::token() !!}"> <div class="form-group"> {!! Form::label('news_group_id', 'Group', array('class' => 'col-sm-3 control-label')) !!} <div class="col-sm-5"> {!! Form::select('news_group_id', [null => '--select--'] + $groups, null, array('class' => 'form-control')) !!} </div> </div> <div class="form-group"> {!! Form::label('title', 'Title', array('class' => 'col-sm-3 control-label')) !!} <div class="col-sm-5"> {!! Form::text('title', null, array('class' => 'form-control', 'data-validate' => 'required', 'data-message-required' => 'This is custom message for required field.')) !!} </div> </div> <div class="form-group"> {!! Form::label('short_description', 'Short description', array('class' => 'col-sm-3 control-label')) !!} <div class="col-sm-5"> {!! Form::text('short_description', null, array('class' => 'form-control', 'data-validate' => 'required', 'data-message-required' => 'This is custom message for required field.')) !!} </div> </div> <div class="form-group"> {!! Form::label('news', 'Content', array('class' => 'col-sm-3 control-label')) !!} <div class="col-sm-9"> {!! Form::textarea('content', null, array('class' => 'form-control ckeditor', 'data-validate' => 'required', 'data-message-required' => 'This is custom message for required field.')) !!} </div> </div> <div class="form-group"> {!! Form::label('published_at', 'Published at', array('class' => 'col-sm-3 control-label')) !!} <div class="col-sm-5"> {!! Form::text('published_at', null, array('class' => 'datepicker form-control', 'data-sign' => '&euro;')) !!} </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-5"> {!! Form::submit('Save', array('class' => 'btn btn-default')) !!} <a href="{!! URL::route('hideyo.news.index') !!}" class="btn btn-large">Cancel</a> </div> </div> </div> </div> @stop
kkorte/backend
src/resources/views/news/edit.blade.php
PHP
gpl-3.0
3,427
package org.sigmah.offline.js; /* * #%L * Sigmah * %% * Copyright (C) 2010 - 2016 URD * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import java.util.HashMap; import java.util.Map; import org.sigmah.offline.fileapi.Int8Array; import org.sigmah.shared.dto.value.FileVersionDTO; import org.sigmah.shared.file.TransfertType; /** * File upload progression. * * @author Raphaël Calabro (rcalabro@ideia.fr) */ public final class TransfertJS extends JavaScriptObject { public static TransfertJS createTransfertJS(FileVersionDTO fileVersionDTO, TransfertType type) { final TransfertJS transfertJS = Values.createJavaScriptObject(TransfertJS.class); transfertJS.setFileVersion(FileVersionJS.toJavaScript(fileVersionDTO)); transfertJS.setData(Values.createTypedJavaScriptArray(Int8Array.class)); transfertJS.setProgress(0); transfertJS.setType(type); return transfertJS; } protected TransfertJS() { } public native int getId() /*-{ return this.id; }-*/; public native void setId(int id) /*-{ this.id = id; }-*/; public TransfertType getType() { return Values.getEnum(this, "type", TransfertType.class); } public void setType(TransfertType type) { Values.setEnum(this, "type", type); } public native FileVersionJS getFileVersion() /*-{ return this.fileVersion; }-*/; public native void setFileVersion(FileVersionJS fileVersion) /*-{ this.fileVersion = fileVersion; }-*/; public native JsArray<Int8Array> getData() /*-{ return this.data; }-*/; public native void setData(JsArray<Int8Array> data) /*-{ this.data = data; }-*/; public native void setData(Int8Array data) /*-{ this.data = [data]; }-*/; public native int getProgress() /*-{ return this.progress; }-*/; public native void setProgress(int progress) /*-{ this.progress = progress; }-*/; public native JsMap<String, String> getProperties() /*-{ return this.properties; }-*/; public native void setProperties(JsMap<String, String> properties) /*-{ this.properties = properties; }-*/; public Map<String, String> getPropertyMap() { if(getProperties() != null) { return new HashMap<String, String>(new AutoBoxingJsMap<String, String>(getProperties(), AutoBoxingJsMap.STRING_BOXER)); } return null; } public void setProperties(Map<String, String> map) { if(map != null) { final JsMap<String, String> jsMap = JsMap.createMap(); jsMap.putAll(map); setProperties(jsMap); } } }
Raphcal/sigmah
src/main/java/org/sigmah/offline/js/TransfertJS.java
Java
gpl-3.0
3,177
#!/usr/bin/python3 from ansible.module_utils.arvados_common import process def main(): additional_argument_spec={ "uuid": dict(required=True, type="str"), "owner_uuid": dict(required=True, type="str"), "name": dict(required=True, type="str"), } filter_property = "uuid" filter_value_module_parameter = "uuid" module_parameter_to_resource_parameter_map = { "owner_uuid": "owner_uuid", "name": "name", } process("repositories", additional_argument_spec, filter_property, filter_value_module_parameter, module_parameter_to_resource_parameter_map) if __name__ == "__main__": main()
wtsi-hgi/hgi-ansible
ansible/library/arvados_repository.py
Python
gpl-3.0
670
/* * This file is part of Flying PhotoBooth. * * Flying PhotoBooth is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Flying PhotoBooth 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 Flying PhotoBooth. If not, see <http://www.gnu.org/licenses/>. */ package com.groundupworks.partyphotobooth.setup.fragments; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.Spinner; import com.groundupworks.partyphotobooth.R; import com.groundupworks.partyphotobooth.helpers.PreferencesHelper; import com.groundupworks.partyphotobooth.helpers.PreferencesHelper.PhotoBoothMode; import com.groundupworks.partyphotobooth.helpers.PreferencesHelper.PhotoBoothTheme; import com.groundupworks.partyphotobooth.helpers.PreferencesHelper.PhotoStripTemplate; import com.groundupworks.partyphotobooth.setup.model.PhotoBoothModeAdapter; import com.groundupworks.partyphotobooth.setup.model.PhotoBoothThemeAdapter; import com.groundupworks.partyphotobooth.setup.model.PhotoStripTemplateAdapter; import java.lang.ref.WeakReference; /** * Ui for setting up the photo booth. * * @author Benedict Lau */ public class PhotoBoothSetupFragment extends Fragment { /** * Callbacks for this fragment. */ private WeakReference<PhotoBoothSetupFragment.ICallbacks> mCallbacks = null; /** * A {@link PreferencesHelper} instance. */ private PreferencesHelper mPreferencesHelper = new PreferencesHelper(); // // Views. // private Spinner mMode; private Spinner mTheme; private Spinner mTemplate; private Button mNext; @Override public void onAttach(Activity activity) { super.onAttach(activity); mCallbacks = new WeakReference<PhotoBoothSetupFragment.ICallbacks>( (PhotoBoothSetupFragment.ICallbacks) activity); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /* * Inflate views from XML. */ View view = inflater.inflate(R.layout.fragment_photo_booth_setup, container, false); mMode = (Spinner) view.findViewById(R.id.setup_photo_booth_mode); mTheme = (Spinner) view.findViewById(R.id.setup_photo_booth_theme); mTemplate = (Spinner) view.findViewById(R.id.setup_photo_booth_template); mNext = (Button) view.findViewById(R.id.setup_photo_booth_button_next); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Activity activity = getActivity(); final Context appContext = activity.getApplicationContext(); /* * Configure views with saved preferences and functionalize. */ final PhotoBoothModeAdapter modeAdapter = new PhotoBoothModeAdapter(activity); mMode.setAdapter(modeAdapter); mMode.setSelection(mPreferencesHelper.getPhotoBoothMode(appContext).ordinal()); mMode.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { PhotoBoothMode selectedMode = modeAdapter.getPhotoBoothMode(position); mPreferencesHelper.storePhotoBoothMode(appContext, selectedMode); } @Override public void onNothingSelected(AdapterView<?> parent) { // Do nothing. } }); final PhotoBoothThemeAdapter themeAdapter = new PhotoBoothThemeAdapter(activity); mTheme.setAdapter(themeAdapter); mTheme.setSelection(mPreferencesHelper.getPhotoBoothTheme(appContext).ordinal()); mTheme.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { PhotoBoothTheme selectedTheme = themeAdapter.getPhotoBoothTheme(position); mPreferencesHelper.storePhotoBoothTheme(appContext, selectedTheme); } @Override public void onNothingSelected(AdapterView<?> parent) { // Do nothing. } }); final PhotoStripTemplateAdapter templateAdapter = new PhotoStripTemplateAdapter(activity); mTemplate.setAdapter(templateAdapter); mTemplate.setSelection(mPreferencesHelper.getPhotoStripTemplate(appContext).ordinal()); mTemplate.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { PhotoStripTemplate selectedTemplate = templateAdapter.getPhotoStripTemplate(position); mPreferencesHelper.storePhotoStripTemplate(appContext, selectedTemplate); } @Override public void onNothingSelected(AdapterView<?> parent) { // Do nothing. } }); mNext.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Call to client. ICallbacks callbacks = getCallbacks(); if (callbacks != null) { callbacks.onPhotoBoothSetupCompleted(); } } }); } // // Private methods. // /** * Gets the callbacks for this fragment. * * @return the callbacks; or null if not set. */ private PhotoBoothSetupFragment.ICallbacks getCallbacks() { PhotoBoothSetupFragment.ICallbacks callbacks = null; if (mCallbacks != null) { callbacks = mCallbacks.get(); } return callbacks; } // // Public methods. // /** * Creates a new {@link PhotoBoothSetupFragment} instance. * * @return the new {@link PhotoBoothSetupFragment} instance. */ public static PhotoBoothSetupFragment newInstance() { return new PhotoBoothSetupFragment(); } // // Interfaces. // /** * Callbacks for this fragment. */ public interface ICallbacks { /** * Setup of the photo booth has completed. */ void onPhotoBoothSetupCompleted(); } }
benhylau/flying-photo-booth
party-photo-booth/src/com/groundupworks/partyphotobooth/setup/fragments/PhotoBoothSetupFragment.java
Java
gpl-3.0
7,157
import React, { PropTypes } from 'react' import classnames from 'classnames' const SettingsPageMenuLayout = ({ children, title, className }) => ( <div className={classnames( 'settings-page-menu-layout bg-white pt3 pr4 pl5 border-only-bottom border-gray94', className )} > <h1 className="h1 mt0 mb3">{title}</h1> {children} </div> ) SettingsPageMenuLayout.propTypes = { children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), className: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), title: PropTypes.string.isRequired } export default SettingsPageMenuLayout
igr-santos/hub-client
app/components/Layout/SettingsPageMenuLayout.js
JavaScript
gpl-3.0
624
'use superstrict'; try { if ((-25 >> 3) === -4) { 'ok'; } else { 'fail'; } } catch (e) { }
vacuumlabs/babel-plugin-superstrict
test/eval_tests/casting_signed_right_shift_numbers.js
JavaScript
gpl-3.0
106
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. # -*- coding: utf-8 -*- """Use AppConf to store sensible defaults for settings. This also documents the settings that lizard_damage defines. Each setting name automatically has "FLOODING_LIB_" prepended to it. By puttng the AppConf in this module and importing the Django settings here, it is possible to import Django's settings with `from flooding_lib.conf import settings` and be certain that the AppConf stuff has also been loaded.""" # Python 3 is coming from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from __future__ import division import os from django.conf import settings settings # Pyflakes... from appconf import AppConf class MyAppConf(AppConf): COLORMAP_DIR = os.path.join( settings.FLOODING_SHARE, 'colormaps')
lizardsystem/flooding
flooding_lib/conf.py
Python
gpl-3.0
875
package edu.hucare.model; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.util.Set; /** * Created by Kuzon on 7/28/2016. */ @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String email; private String name; private String password; @OneToMany(mappedBy = "user") private Set<ControlDevice> controlDevices; @OneToMany(mappedBy = "user") private Set<TerminalDevice> terminalDevices; @OneToMany(mappedBy = "user") private Set<Schedule> schedules; public User() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @JsonIgnore public Set<ControlDevice> getControlDevices() { return controlDevices; } @JsonIgnore public void setControlDevices(Set<ControlDevice> controlDevices) { this.controlDevices = controlDevices; } @JsonIgnore public Set<TerminalDevice> getTerminalDevices() { return terminalDevices; } @JsonIgnore public void setTerminalDevices(Set<TerminalDevice> terminalDevices) { this.terminalDevices = terminalDevices; } @JsonIgnore public Set<Schedule> getSchedules() { return schedules; } @JsonIgnore public void setSchedules(Set<Schedule> schedules) { this.schedules = schedules; } }
adalee-group/watering-system
server/schedule-service/src/main/java/edu/hucare/model/User.java
Java
gpl-3.0
1,897
/** * Copyright 2013 hbz NRW (http://www.hbz-nrw.de/) * * This file is part of regal-drupal. * * regal-drupal is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * regal-drupal 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 regal-drupal. If not, see <http://www.gnu.org/licenses/>. */ (function($) { var translations = { } /** * Common behaviours */ Drupal.behaviors.edoweb = { attach: function (context, settings) { var home_href = Drupal.settings.basePath + 'resource'; if (document.location.pathname == home_href && '' != document.location.search) { var query_params = []; var all_params = document.location.search.substr(1).split('&'); $.each(all_params, function(i, param) { if ('query[0][facets]' == param.substr(0, 16)) { query_params.push(param); } }); if (query_params) { sessionStorage.setItem('edoweb_search', '?' + query_params.join('&')); } } else if (document.location.pathname == home_href) { sessionStorage.removeItem('edoweb_search'); } if (search = sessionStorage.getItem('edoweb_search')) { $('a[href="' + home_href + '"]').attr('href', home_href + search); if ('resource' == Drupal.settings.edoweb.site_frontpage) { $('a[href="/"]').attr('href', home_href + search); } } /** * Date parser for tablesort plugin */ $.tablesorter.addParser({ id: 'edowebDate', is: function(s) { return /^.*, /.test(s); }, format: function(s, table, cell, cellIndex) { return $(cell).closest('tr').attr('data-updated'); }, type: 'text' }); /** * Translations, these have to be defined here (i.e. in a behaviour) * in order for Drupal.t to pick them up. */ translations['Add researchData'] = Drupal.t('Add researchData'); translations['Add monograph'] = Drupal.t('Add monograph'); translations['Add journal'] = Drupal.t('Add journal'); translations['Add volume'] = Drupal.t('Add volume'); translations['Add issue'] = Drupal.t('Add issue'); translations['Add article'] = Drupal.t('Add article'); translations['Add file'] = Drupal.t('Add file'); translations['Add part'] = Drupal.t('Add part'); translations['Add webpage'] = Drupal.t('Add webpage'); translations['Add version'] = Drupal.t('Add version'); } } /** * Edoweb helper functions */ Drupal.edoweb = { /** * URI to CURIE */ compact_uri: function(uri) { var namespaces = Drupal.settings.edoweb.namespaces; for (prefix in namespaces) { if (uri.indexOf(namespaces[prefix]) == 0) { var local_part = uri.substring(namespaces[prefix].length); return prefix + ':' + local_part; } } return uri; }, expand_curie: function(curie) { var namespaces = Drupal.settings.edoweb.namespaces; var curie_parts = curie.split(':'); for (prefix in namespaces) { if (prefix == curie_parts[0]) { return namespaces[prefix] + curie_parts[1]; } } }, t: function(string) { if (string in translations) { return translations[string]; } else { return string; } }, /** * Pending AJAX requests */ pending_requests: [], /** * Function loads a tabular view for a list of linked entities */ entity_table: function(field_items, operations, view_mode) { view_mode = view_mode || 'default'; field_items.each(function() { var container = $(this); var curies = []; container.find('a[data-curie]').each(function() { curies.push(this.getAttribute('data-curie')); }); var columns = container.find('a[data-target-bundle]') .attr('data-target-bundle') .split(' ')[0]; if (columns && curies.length > 0) { container.siblings('table').remove(); var throbber = $('<div class="ajax-progress"><div class="throbber">&nbsp;</div></div>') container.before(throbber); Drupal.edoweb.entity_list('edoweb_basic', curies, columns, view_mode).onload = function () { if (this.status == 200) { var result_table = $(this.responseText).find('table'); result_table.find('a[data-curie]').not('.resolved').not('.edoweb.download').each(function() { Drupal.edoweb.entity_label($(this)); }); result_table.removeClass('sticky-enabled'); var updated_column = result_table.find('th[specifier="updated"]').index(); if (updated_column > -1) { result_table.tablesorter({sortList: [[updated_column,1]]}); } //TODO: check interference with tree navigation block //Drupal.attachBehaviors(result_table); container.find('div.field-item>a[data-curie]').each(function() { if (! result_table.find('tr[data-curie="' + $(this).attr('data-curie') + '"]').length) { var missing_entry = $(this).clone(); var row = $('<tr />'); result_table.find('thead').find('tr>th').each(function() { row.append($('<td />')); }); missing_entry.removeAttr('data-target-bundle'); row.find('td:eq(0)').append(missing_entry); row.find('td:eq(1)').append(missing_entry.attr('data-curie')); //FIXME: how to deal with this with configurable columns? result_table.append(row); } }); container.hide(); container.after(result_table); for (label in operations) { operations[label](result_table); } Drupal.edoweb.last_modified_label(result_table); Drupal.edoweb.hideEmptyTableColumns(result_table); Drupal.edoweb.hideTableHeaders(result_table); } throbber.remove(); }; } }); }, /** * Function loads a tabular view for a list of linked entities */ entity_table_detail: function(field_items, operations, view_mode) { view_mode = 'default'; field_items.each(function() { var container = $(this); var curies = []; container.find('a[data-curie]').each(function() { curies.push(this.getAttribute('data-curie')); }); var columns = container.find('a[data-target-bundle]') .attr('data-target-bundle') .split(' ')[0]; if (columns && curies.length > 0) { container.siblings('table').remove(); var throbber = $('<div class="ajax-progress"><div class="throbber">&nbsp;</div></div>') container.before(throbber); Drupal.edoweb.entity_list_detail('edoweb_basic', curies, columns, view_mode).onload = function () { if (this.status == 200) { result_table = $(this.responseText).find('table'); result_table.find('a[data-curie]').not('.resolved').not('.edoweb.download').each(function() { Drupal.edoweb.entity_label($(this)); }); result_table.removeClass('sticky-enabled'); var updated_column = result_table.find('th[specifier="updated"]').index(); if (updated_column > -1) { result_table.tablesorter({sortList: [[updated_column,1]]}); } //TODO: check interference with tree navigation block //Drupal.attachBehaviors(result_table); container.find('div.field-item>a[data-curie]').each(function() { if (! result_table.find('tr[data-curie="' + $(this).attr('data-curie') + '"]').length) { var missing_entry = $(this).clone(); var row = $('<tr />'); result_table.find('thead').find('tr>th').each(function() { row.append($('<td />')); }); missing_entry.removeAttr('data-target-bundle'); row.find('td:eq(0)').append(missing_entry); row.find('td:eq(1)').append(missing_entry.attr('data-curie')); //FIXME: how to deal with this with configurable columns? result_table.append(row); } }); container.hide(); container.after(result_table); container.after("<br/>"); for (label in operations) { operations[label](result_table); } Drupal.edoweb.last_modified_label(result_table); Drupal.edoweb.hideEmptyTableColumns(result_table); Drupal.edoweb.hideTableHeaders(result_table); } throbber.remove(); }; } }); }, /** * Function returns an entities label. */ entity_label: function(element) { var entity_type = 'edoweb_basic'; var entity_id = element.attr('data-curie'); if (cached_label = sessionStorage.getItem(entity_id)) { element.text(cached_label); } else { $.get(Drupal.settings.basePath + 'edoweb_entity_label/' + entity_type + '/' + entity_id).onload = function() { var label = this.status == 200 ? this.responseText : entity_id; if (this.status == 200) { sessionStorage.setItem(entity_id, label); } element.text(label); element.addClass('resolved'); }; } }, /** * Function returns a list of entities. */ entity_list: function(entity_type, entity_curies, columns, view_mode) { return $.get(Drupal.settings.basePath + 'edoweb_entity_list/' + entity_type + '/' + view_mode + '?' + $.param({'ids': entity_curies, 'columns': columns}) ); }, /** * Function returns a list of entities. */ entity_list_detail: function(entity_type, entity_curies, columns, view_mode) { return $.get(Drupal.settings.basePath + 'edoweb_entity_list_detail/' + entity_type + '/' + view_mode + '?' + $.param({'ids': entity_curies, 'columns': columns}) ); }, last_modified_label: function(container) { $('a.edoweb.lastmodified', container).each(function() { var link = $(this); $.get(link.attr('href'), function(data) { link.replaceWith($(data)); }); }); }, /** * Hides table columns that do not contain any data */ hideEmptyTableColumns: function(table) { // Hide table columns that do not contain any data table.find('th').each(function(i) { var remove = 0; var tds = $(this).parents('table').find('tr td:nth-child(' + (i + 1) + ')') tds.each(function(j) { if ($(this).text() == '') remove++; }); if (remove == (table.find('tr').length - 1)) { $(this).hide(); tds.hide(); } }); }, /** * Hide the th of a table */ hideTableHeaders: function(table) { if (!(table.parent().hasClass('field-name-field-edoweb-struct-child')) && !(table.hasClass('sticky-enabled')) && !(table.closest('form').length)) { table.find('thead').hide(); } }, blockUIMessage: { message: '<div class="ajax-progress"><div class="throbber">&nbsp;</div></div> Bitte warten...' } } // AJAX navigation, if possible if (window.history && history.pushState) { Drupal.edoweb.navigateTo = function(href) { var throbber = $('<div class="ajax-progress"><div class="throbber">&nbsp;</div></div>'); $('#content').html(throbber); $.ajax({ url: href, complete: function(xmlHttp, status) { throbber.remove(); var html = $(xmlHttp.response); Drupal.attachBehaviors(html); $('#content').replaceWith(html.find('#content')); $('#breadcrumb').replaceWith(html.find('#breadcrumb')); if ($('#messages').length) { $('#messages').replaceWith(html.find('#messages')); } else { $('#header').after(html.find('#messages')); } document.title = html.filter('title').text(); $('.edoweb-tree li.active').removeClass('active'); $('.edoweb-tree li>a[href="' + location.pathname + '"]').closest('li').addClass('active'); } }); }; if (!this.attached) { history.replaceState({tree: true}, null, document.location); window.addEventListener("popstate", function(e) { if (e.state && e.state.tree) { Drupal.edoweb.navigateTo(location.pathname); if (Drupal.edoweb.refreshTree) { Drupal.edoweb.refreshTree(); } } }); this.attached = true; } } else { Drupal.edoweb.navigateTo = function(href) { window.location = href; }; } })(jQuery);
jschnasse/regal-drupal
edoweb/js/edoweb.js
JavaScript
gpl-3.0
13,745
/* This file is part of Cute Chess. Copyright (C) 2008-2018 Cute Chess authors Cute Chess is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Cute Chess 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 Cute Chess. If not, see <http://www.gnu.org/licenses/>. */ #include "sprt.h" #include <cmath> #include <QtGlobal> class BayesElo; class SprtProbability; class BayesElo { public: BayesElo(double bayesElo, double drawElo); BayesElo(const SprtProbability& p); double bayesElo() const; double drawElo() const; double scale() const; private: double m_bayesElo; double m_drawElo; }; class SprtProbability { public: SprtProbability(int wins, int losses, int draws); SprtProbability(const BayesElo& b); bool isValid() const; double pWin() const; double pLoss() const; double pDraw() const; private: double m_pWin; double m_pLoss; double m_pDraw; }; BayesElo::BayesElo(double bayesElo, double drawElo) : m_bayesElo(bayesElo), m_drawElo(drawElo) { } BayesElo::BayesElo(const SprtProbability& p) { Q_ASSERT(p.isValid()); m_bayesElo = 200.0 * std::log10(p.pWin() / p.pLoss() * (1.0 - p.pLoss()) / (1.0 - p.pWin())); m_drawElo = 200.0 * std::log10((1.0 - p.pLoss()) / p.pLoss() * (1.0 - p.pWin()) / p.pWin()); } double BayesElo::bayesElo() const { return m_bayesElo; } double BayesElo::drawElo() const { return m_drawElo; } double BayesElo::scale() const { const double x = std::pow(10.0, -m_drawElo / 400.0); return 4.0 * x / ((1.0 + x) * (1.0 + x)); } SprtProbability::SprtProbability(int wins, int losses, int draws) { Q_ASSERT(wins > 0 && losses > 0 && draws > 0); const int count = wins + losses + draws; m_pWin = double(wins) / count; m_pLoss = double(losses) / count; m_pDraw = 1.0 - m_pWin - m_pLoss; } SprtProbability::SprtProbability(const BayesElo& b) { m_pWin = 1.0 / (1.0 + std::pow(10.0, (b.drawElo() - b.bayesElo()) / 400.0)); m_pLoss = 1.0 / (1.0 + std::pow(10.0, (b.drawElo() + b.bayesElo()) / 400.0)); m_pDraw = 1.0 - m_pWin - m_pLoss; } bool SprtProbability::isValid() const { return 0.0 < m_pWin && m_pWin < 1.0 && 0.0 < m_pLoss && m_pLoss < 1.0 && 0.0 < m_pDraw && m_pDraw < 1.0; } double SprtProbability::pWin() const { return m_pWin; } double SprtProbability::pLoss() const { return m_pLoss; } double SprtProbability::pDraw() const { return m_pDraw; } Sprt::Sprt() : m_elo0(0), m_elo1(0), m_alpha(0), m_beta(0), m_wins(0), m_losses(0), m_draws(0) { } bool Sprt::isNull() const { return m_elo0 == 0 && m_elo1 == 0 && m_alpha == 0 && m_beta == 0; } void Sprt::initialize(double elo0, double elo1, double alpha, double beta) { m_elo0 = elo0; m_elo1 = elo1; m_alpha = alpha; m_beta = beta; } Sprt::Status Sprt::status() const { Status status = { Continue, 0.0, 0.0, 0.0 }; if (m_wins <= 0 || m_losses <= 0 || m_draws <= 0) return status; // Estimate draw_elo out of sample const SprtProbability p(m_wins, m_losses, m_draws); const BayesElo b(p); // Probability laws under H0 and H1 const double s = b.scale(); const BayesElo b0(m_elo0 / s, b.drawElo()); const BayesElo b1(m_elo1 / s, b.drawElo()); const SprtProbability p0(b0), p1(b1); // Log-Likelyhood Ratio status.llr = m_wins * std::log(p1.pWin() / p0.pWin()) + m_losses * std::log(p1.pLoss() / p0.pLoss()) + m_draws * std::log(p1.pDraw() / p0.pDraw()); // Bounds based on error levels of the test status.lBound = std::log(m_beta / (1.0 - m_alpha)); status.uBound = std::log((1.0 - m_beta) / m_alpha); if (status.llr > status.uBound) status.result = AcceptH1; else if (status.llr < status.lBound) status.result = AcceptH0; return status; } void Sprt::addGameResult(GameResult result) { if (result == Win) m_wins++; else if (result == Draw) m_draws++; else if (result == Loss) m_losses++; }
joergoster/cutechess
projects/lib/src/sprt.cpp
C++
gpl-3.0
4,340
/* * Copyright (c) 2018 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; mica.contact .factory('ContactsSearchResource', ['$resource', 'ContactSerializationService', function ($resource, ContactSerializationService) { return $resource(contextPath + '/ws/draft/persons/_search?', {}, { 'search': { method: 'GET', params: {query: '@query', 'exclude': '@exclude'}, transformResponse: ContactSerializationService.deserializeList, errorHandler: true } }); }]) .factory('PersonResource', ['$resource', function ($resource) { return $resource(contextPath + '/ws/draft/person/:id', {}, { 'get': {method: 'GET', params: {id: '@id'}}, 'update': {method: 'PUT', params: {id: '@id'}}, 'delete': {method: 'DELETE', params: {id: '@id'}}, 'create': {url: contextPath + '/ws/draft/persons', method: 'POST'}, 'getStudyMemberships': {url: contextPath + '/ws/draft/persons/study/:studyId', method: 'GET', isArray: true, params: {studyId: '@studyId'}}, 'getNetworkMemberships': {url: contextPath + '/ws/draft/persons/network/:networkId', method: 'GET', isArray: true, params: {networkId: '@networkId'}} }); }]) .factory('ContactSerializationService', ['LocalizedValues', function (LocalizedValues) { var it = this; this.serialize = function(person) { if (person.institution) { person.institution.name = LocalizedValues.objectToArray(person.institution.name); person.institution.department = LocalizedValues.objectToArray(person.institution.department); if (person.institution.address) { person.institution.address.street = LocalizedValues.objectToArray(person.institution.address.street); person.institution.address.city = LocalizedValues.objectToArray(person.institution.address.city); if (person.institution.address.country) { person.institution.address.country = {'iso': person.institution.address.country}; } } } return person; }; this.deserializeList = function (personsList) { personsList = angular.fromJson(personsList); if (personsList.persons) { personsList.persons = personsList.persons.map(function (person) { return it.deserialize(person); }); } return personsList; }; this.deserialize = function(person) { person = angular.copy(person); if (person.institution) { person.institution.name = LocalizedValues.arrayToObject(person.institution.name); person.institution.department = LocalizedValues.arrayToObject(person.institution.department); if (person.institution.address) { person.institution.address.street = LocalizedValues.arrayToObject(person.institution.address.street); person.institution.address.city = LocalizedValues.arrayToObject(person.institution.address.city); if (person.institution.address.country) { person.institution.address.country = person.institution.address.country.iso; } } } return person; }; return this; }]);
obiba/mica2
mica-webapp/src/main/webapp/app/contact/contact-service.js
JavaScript
gpl-3.0
3,513
# -*- coding: utf-8 -*- """ <license> CSPLN_MaryKeelerEdition; Manages images to which notes can be added. Copyright (C) 2015, Thomas Kercheval This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ___________________________________________________________</license> Description: Updates README.txt file in the specified directory. Inputs: Functions that are in the specified directory. discover_functions() detects them automatically. Outputs: README.txt file, with Scope&&Details listed. Covers functions in specified directory. Currently: To Do: Done: Update readme file with current functions&&their docstrings. """ import os def discover_functions(directory): """Discorvers python modules in current directory.""" function_names = [] curr_dir = os.listdir(directory) for name in curr_dir: if name[-3:] == '.py': function_names.append(str(name)) return function_names def grab_docstrings(directory): """"Grabs the docstrings of all python modules specified.""" import ast docstrings = {} for name in discover_functions(directory): path_name = os.path.join(directory, name) thing = ast.parse(''.join(open(path_name))) docstring = ast.get_docstring(thing) docstrings[name] = docstring return docstrings def create_readme(doc_dic, directory): """Strips off license statement, formats readme, returns readme text.""" end_lisence = "</license>" scope = '''Scope: {}''' details = '''Details:{}''' scopelist = [] detaillist = [] scopestuff = '' detailstuff = '' # Now to create the contents of the README... for script in doc_dic.keys().sort(): print " Creating readme entry for: {}...".format(script) if doc_dic[script] == None: print " But it has no docstring..." continue scopelist.append(script+'\n ') docstring = doc_dic[script].replace('\n', '\n ') doc_index = docstring.find(end_lisence) + 11 # Stripping off the license in the docstring... docstring = docstring[doc_index:] detaillist.append('\n\n'+script+'\n') detaillist.append(' '+docstring) for item in scopelist: scopestuff += item for ano_item in detaillist: detailstuff += ano_item # Now to put the contents in their correct place... readme = (scope.format(scopestuff[:-4]) + '\n' + details.format(detailstuff) + '\n') # And write the README in its directory... write_readme(readme, directory) return None def write_readme(r_text, directory): """Writes the readme!""" readme_path = os.path.join(directory, 'subreadme.txt') with open(readme_path, 'w') as readme: readme.write(r_text) return None def update_readme(directory): """Updates the readme everytime this script is called.""" documentation_dict = grab_docstrings(directory) create_readme(documentation_dict, directory) return None if __name__ == "__main__": CURR_DIR = os.path.abspath(os.path.dirname(__file__)) update_readme(CURR_DIR)
jjs0sbw/CSPLN
test/update_test_subreadme.py
Python
gpl-3.0
3,717
/** * Marlin 3D Printer Firmware * Copyright (C) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "../../../inc/MarlinConfig.h" #if HAS_TRINAMIC #include "../../gcode.h" #include "../../../feature/tmc_util.h" #include "../../../module/stepper_indirection.h" #include "../../../module/planner.h" #include "../../queue.h" #if ENABLED(MONITOR_DRIVER_STATUS) #define M91x_USE(ST) (AXIS_DRIVER_TYPE(ST, TMC2130) || AXIS_DRIVER_TYPE(ST, TMC2160) || AXIS_DRIVER_TYPE(ST, TMC2208) || AXIS_DRIVER_TYPE(ST, TMC2660) || AXIS_DRIVER_TYPE(ST, TMC5130) || AXIS_DRIVER_TYPE(ST, TMC5160)) #define M91x_USE_E(N) (E_STEPPERS > N && M91x_USE(E##N)) #define M91x_SOME_X (M91x_USE(X) || M91x_USE(X2)) #define M91x_SOME_Y (M91x_USE(Y) || M91x_USE(Y2)) #define M91x_SOME_Z (M91x_USE(Z) || M91x_USE(Z2) || M91x_USE(Z3)) #define M91x_SOME_E (M91x_USE_E(0) || M91x_USE_E(1) || M91x_USE_E(2) || M91x_USE_E(3) || M91x_USE_E(4) || M91x_USE_E(5)) #if !M91x_SOME_X && !M91x_SOME_Y && !M91x_SOME_Z && !M91x_SOME_E #error "MONITOR_DRIVER_STATUS requires at least one TMC2130, TMC2208, or TMC2660." #endif /** * M911: Report TMC stepper driver overtemperature pre-warn flag * This flag is held by the library, persisting until cleared by M912 */ void GcodeSuite::M911() { #if M91x_USE(X) tmc_report_otpw(stepperX); #endif #if M91x_USE(X2) tmc_report_otpw(stepperX2); #endif #if M91x_USE(Y) tmc_report_otpw(stepperY); #endif #if M91x_USE(Y2) tmc_report_otpw(stepperY2); #endif #if M91x_USE(Z) tmc_report_otpw(stepperZ); #endif #if M91x_USE(Z2) tmc_report_otpw(stepperZ2); #endif #if M91x_USE(Z3) tmc_report_otpw(stepperZ3); #endif #if M91x_USE_E(0) tmc_report_otpw(stepperE0); #endif #if M91x_USE_E(1) tmc_report_otpw(stepperE1); #endif #if M91x_USE_E(2) tmc_report_otpw(stepperE2); #endif #if M91x_USE_E(3) tmc_report_otpw(stepperE3); #endif #if M91x_USE_E(4) tmc_report_otpw(stepperE4); #endif #if M91x_USE_E(5) tmc_report_otpw(stepperE5); #endif } /** * M912: Clear TMC stepper driver overtemperature pre-warn flag held by the library * Specify one or more axes with X, Y, Z, X1, Y1, Z1, X2, Y2, Z2, Z3 and E[index]. * If no axes are given, clear all. * * Examples: * M912 X ; clear X and X2 * M912 X1 ; clear X1 only * M912 X2 ; clear X2 only * M912 X E ; clear X, X2, and all E * M912 E1 ; clear E1 only */ void GcodeSuite::M912() { #if M91x_SOME_X const bool hasX = parser.seen(axis_codes[X_AXIS]); #else constexpr bool hasX = false; #endif #if M91x_SOME_Y const bool hasY = parser.seen(axis_codes[Y_AXIS]); #else constexpr bool hasY = false; #endif #if M91x_SOME_Z const bool hasZ = parser.seen(axis_codes[Z_AXIS]); #else constexpr bool hasZ = false; #endif #if M91x_SOME_E const bool hasE = parser.seen(axis_codes[E_AXIS]); #else constexpr bool hasE = false; #endif const bool hasNone = !hasX && !hasY && !hasZ && !hasE; #if M91x_SOME_X const int8_t xval = int8_t(parser.byteval(axis_codes[X_AXIS], 0xFF)); #if M91x_USE(X) if (hasNone || xval == 1 || (hasX && xval < 0)) tmc_clear_otpw(stepperX); #endif #if M91x_USE(X2) if (hasNone || xval == 2 || (hasX && xval < 0)) tmc_clear_otpw(stepperX2); #endif #endif #if M91x_SOME_Y const int8_t yval = int8_t(parser.byteval(axis_codes[Y_AXIS], 0xFF)); #if M91x_USE(Y) if (hasNone || yval == 1 || (hasY && yval < 0)) tmc_clear_otpw(stepperY); #endif #if M91x_USE(Y2) if (hasNone || yval == 2 || (hasY && yval < 0)) tmc_clear_otpw(stepperY2); #endif #endif #if M91x_SOME_Z const int8_t zval = int8_t(parser.byteval(axis_codes[Z_AXIS], 0xFF)); #if M91x_USE(Z) if (hasNone || zval == 1 || (hasZ && zval < 0)) tmc_clear_otpw(stepperZ); #endif #if M91x_USE(Z2) if (hasNone || zval == 2 || (hasZ && zval < 0)) tmc_clear_otpw(stepperZ2); #endif #if M91x_USE(Z3) if (hasNone || zval == 3 || (hasZ && zval < 0)) tmc_clear_otpw(stepperZ3); #endif #endif #if M91x_SOME_E const int8_t eval = int8_t(parser.byteval(axis_codes[E_AXIS], 0xFF)); #if M91x_USE_E(0) if (hasNone || eval == 0 || (hasE && eval < 0)) tmc_clear_otpw(stepperE0); #endif #if M91x_USE_E(1) if (hasNone || eval == 1 || (hasE && eval < 0)) tmc_clear_otpw(stepperE1); #endif #if M91x_USE_E(2) if (hasNone || eval == 2 || (hasE && eval < 0)) tmc_clear_otpw(stepperE2); #endif #if M91x_USE_E(3) if (hasNone || eval == 3 || (hasE && eval < 0)) tmc_clear_otpw(stepperE3); #endif #if M91x_USE_E(4) if (hasNone || eval == 4 || (hasE && eval < 0)) tmc_clear_otpw(stepperE4); #endif #if M91x_USE_E(5) if (hasNone || eval == 5 || (hasE && eval < 0)) tmc_clear_otpw(stepperE5); #endif #endif } #endif // MONITOR_DRIVER_STATUS /** * M913: Set HYBRID_THRESHOLD speed. */ #if ENABLED(HYBRID_THRESHOLD) void GcodeSuite::M913() { #define TMC_SAY_PWMTHRS(A,Q) tmc_print_pwmthrs(stepper##Q) #define TMC_SET_PWMTHRS(A,Q) stepper##Q.set_pwm_thrs(value) #define TMC_SAY_PWMTHRS_E(E) tmc_print_pwmthrs(stepperE##E) #define TMC_SET_PWMTHRS_E(E) stepperE##E.set_pwm_thrs(value) bool report = true; #if AXIS_IS_TMC(X) || AXIS_IS_TMC(X2) || AXIS_IS_TMC(Y) || AXIS_IS_TMC(Y2) || AXIS_IS_TMC(Z) || AXIS_IS_TMC(Z2) || AXIS_IS_TMC(Z3) const uint8_t index = parser.byteval('I'); #endif LOOP_XYZE(i) if (int32_t value = parser.longval(axis_codes[i])) { report = false; switch (i) { case X_AXIS: #if AXIS_HAS_STEALTHCHOP(X) if (index < 2) TMC_SET_PWMTHRS(X,X); #endif #if AXIS_HAS_STEALTHCHOP(X2) if (!(index & 1)) TMC_SET_PWMTHRS(X,X2); #endif break; case Y_AXIS: #if AXIS_HAS_STEALTHCHOP(Y) if (index < 2) TMC_SET_PWMTHRS(Y,Y); #endif #if AXIS_HAS_STEALTHCHOP(Y2) if (!(index & 1)) TMC_SET_PWMTHRS(Y,Y2); #endif break; case Z_AXIS: #if AXIS_HAS_STEALTHCHOP(Z) if (index < 2) TMC_SET_PWMTHRS(Z,Z); #endif #if AXIS_HAS_STEALTHCHOP(Z2) if (index == 0 || index == 2) TMC_SET_PWMTHRS(Z,Z2); #endif #if AXIS_HAS_STEALTHCHOP(Z3) if (index == 0 || index == 3) TMC_SET_PWMTHRS(Z,Z3); #endif break; case E_AXIS: { #if E_STEPPERS const int8_t target_extruder = get_target_extruder_from_command(); if (target_extruder < 0) return; switch (target_extruder) { #if AXIS_HAS_STEALTHCHOP(E0) case 0: TMC_SET_PWMTHRS_E(0); break; #endif #if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1) case 1: TMC_SET_PWMTHRS_E(1); break; #endif #if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2) case 2: TMC_SET_PWMTHRS_E(2); break; #endif #if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3) case 3: TMC_SET_PWMTHRS_E(3); break; #endif #if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4) case 4: TMC_SET_PWMTHRS_E(4); break; #endif #if E_STEPPERS > 5 && AXIS_HAS_STEALTHCHOP(E5) case 5: TMC_SET_PWMTHRS_E(5); break; #endif } #endif // E_STEPPERS } break; } } if (report) { #if AXIS_HAS_STEALTHCHOP(X) TMC_SAY_PWMTHRS(X,X); #endif #if AXIS_HAS_STEALTHCHOP(X2) TMC_SAY_PWMTHRS(X,X2); #endif #if AXIS_HAS_STEALTHCHOP(Y) TMC_SAY_PWMTHRS(Y,Y); #endif #if AXIS_HAS_STEALTHCHOP(Y2) TMC_SAY_PWMTHRS(Y,Y2); #endif #if AXIS_HAS_STEALTHCHOP(Z) TMC_SAY_PWMTHRS(Z,Z); #endif #if AXIS_HAS_STEALTHCHOP(Z2) TMC_SAY_PWMTHRS(Z,Z2); #endif #if AXIS_HAS_STEALTHCHOP(Z3) TMC_SAY_PWMTHRS(Z,Z3); #endif #if E_STEPPERS && AXIS_HAS_STEALTHCHOP(E0) TMC_SAY_PWMTHRS_E(0); #endif #if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1) TMC_SAY_PWMTHRS_E(1); #endif #if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2) TMC_SAY_PWMTHRS_E(2); #endif #if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3) TMC_SAY_PWMTHRS_E(3); #endif #if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4) TMC_SAY_PWMTHRS_E(4); #endif #if E_STEPPERS > 5 && AXIS_HAS_STEALTHCHOP(E5) TMC_SAY_PWMTHRS_E(5); #endif } } #endif // HYBRID_THRESHOLD /** * M914: Set StallGuard sensitivity. */ #if USE_SENSORLESS void GcodeSuite::M914() { bool report = true; const uint8_t index = parser.byteval('I'); LOOP_XYZ(i) if (parser.seen(axis_codes[i])) { const int8_t value = (int8_t)constrain(parser.value_int(), -64, 63); report = false; switch (i) { #if X_SENSORLESS case X_AXIS: #if AXIS_HAS_STALLGUARD(X) if (index < 2) stepperX.sgt(value); #endif #if AXIS_HAS_STALLGUARD(X2) if (!(index & 1)) stepperX2.sgt(value); #endif break; #endif #if Y_SENSORLESS case Y_AXIS: #if AXIS_HAS_STALLGUARD(Y) if (index < 2) stepperY.sgt(value); #endif #if AXIS_HAS_STALLGUARD(Y2) if (!(index & 1)) stepperY2.sgt(value); #endif break; #endif #if Z_SENSORLESS case Z_AXIS: #if AXIS_HAS_STALLGUARD(Z) if (index < 2) stepperZ.sgt(value); #endif #if AXIS_HAS_STALLGUARD(Z2) if (index == 0 || index == 2) stepperZ2.sgt(value); #endif #if AXIS_HAS_STALLGUARD(Z3) if (index == 0 || index == 3) stepperZ3.sgt(value); #endif break; #endif } } if (report) { #if X_SENSORLESS #if AXIS_HAS_STALLGUARD(X) tmc_print_sgt(stepperX); #endif #if AXIS_HAS_STALLGUARD(X2) tmc_print_sgt(stepperX2); #endif #endif #if Y_SENSORLESS #if AXIS_HAS_STALLGUARD(Y) tmc_print_sgt(stepperY); #endif #if AXIS_HAS_STALLGUARD(Y2) tmc_print_sgt(stepperY2); #endif #endif #if Z_SENSORLESS #if AXIS_HAS_STALLGUARD(Z) tmc_print_sgt(stepperZ); #endif #if AXIS_HAS_STALLGUARD(Z2) tmc_print_sgt(stepperZ2); #endif #if AXIS_HAS_STALLGUARD(Z3) tmc_print_sgt(stepperZ3); #endif #endif } } #endif // USE_SENSORLESS #endif // HAS_TRINAMIC
teemuatlut/Marlin
Marlin/src/gcode/feature/trinamic/M911-M914.cpp
C++
gpl-3.0
12,013
<?php /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com> * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com> * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@capnetworks.com> * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr> * Copyright (C) 2010-2012 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr> * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro> * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr> * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr> * Copyright (C) 2015-2016 Ferran Marcet <fmarcet@2byte.es> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * \file htdocs/compta/facture/list.php * \ingroup facture * \brief Page to create/see an invoice */ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } $langs->load('bills'); $langs->load('companies'); $langs->load('products'); $langs->load('main'); $sall=trim(GETPOST('sall')); $projectid=(GETPOST('projectid')?GETPOST('projectid','int'):0); $id=(GETPOST('id','int')?GETPOST('id','int'):GETPOST('facid','int')); // For backward compatibility $ref=GETPOST('ref','alpha'); $socid=GETPOST('socid','int'); $action=GETPOST('action','alpha'); $massaction=GETPOST('massaction','alpha'); $confirm=GETPOST('confirm','alpha'); $lineid=GETPOST('lineid','int'); $userid=GETPOST('userid','int'); $search_product_category=GETPOST('search_product_category','int'); $search_ref=GETPOST('sf_ref')?GETPOST('sf_ref','alpha'):GETPOST('search_ref','alpha'); $search_refcustomer=GETPOST('search_refcustomer','alpha'); $search_societe=GETPOST('search_societe','alpha'); $search_montant_ht=GETPOST('search_montant_ht','alpha'); $search_montant_ttc=GETPOST('search_montant_ttc','alpha'); $search_status=GETPOST('search_status','int'); $search_paymentmode=GETPOST('search_paymentmode','int'); $option = GETPOST('option'); if ($option == 'late') $filter = 'paye:0'; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; $page = GETPOST("page",'int'); if ($page == -1) { $page = 0; } $offset = $limit * $page; if (! $sortorder && ! empty($conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER) && $search_status == 1) $sortorder=$conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER; if (! $sortorder) $sortorder='DESC'; if (! $sortfield) $sortfield='f.datef'; $pageprev = $page - 1; $pagenext = $page + 1; $search_user = GETPOST('search_user','int'); $search_sale = GETPOST('search_sale','int'); $day = GETPOST('day','int'); $month = GETPOST('month','int'); $year = GETPOST('year','int'); $day_lim = GETPOST('day_lim','int'); $month_lim = GETPOST('month_lim','int'); $year_lim = GETPOST('year_lim','int'); $filtre = GETPOST('filtre'); $toselect = GETPOST('toselect', 'array'); // Security check $fieldid = (! empty($ref)?'facnumber':'rowid'); if (! empty($user->societe_id)) $socid=$user->societe_id; $result = restrictedArea($user, 'facture', $id,'','','fk_soc',$fieldid); $object=new Facture($db); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('invoicelist')); $now=dol_now(); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( 'f.facnumber'=>'Ref', 'f.ref_client'=>'RefCustomer', 'fd.description'=>'Description', 's.nom'=>"ThirdParty", 'f.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["f.note_private"]="NotePrivate"; /* * Actions */ if (GETPOST('cancel')) { $action='list'; $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { // Mass actions if (! empty($massaction) && count($toselect) < 1) { $error++; setEventMessages($langs->trans("NoLineChecked"), null, "warnings"); } if (! $error && $massaction == 'confirm_presend') { $resaction = ''; $nbsent = 0; $nbignored = 0; $langs->load("mails"); include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; if (!isset($user->email)) { $error++; setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings'); } if (! $error) { $thirdparty=new Societe($db); $objecttmp=new Facture($db); $listofobjectid=array(); $listofobjectthirdparties=array(); $listofobjectref=array(); foreach($toselect as $toselectid) { $objecttmp=new Facture($db); // must create new instance because instance is saved into $listofobjectref array for future use $result=$objecttmp->fetch($toselectid); if ($result > 0) { $listoinvoicesid[$toselectid]=$toselectid; $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; $listofobjectref[$thirdpartyid][$toselectid]=$objecttmp; } } //var_dump($listofobjectthirdparties);exit; foreach ($listofobjectthirdparties as $thirdpartyid) { $result = $thirdparty->fetch($thirdpartyid); if ($result < 0) { dol_print_error($db); exit; } // Define recipient $sendto and $sendtocc if (trim($_POST['sendto'])) { // Recipient is provided into free text $sendto = trim($_POST['sendto']); $sendtoid = 0; } elseif ($_POST['receiver'] != '-1') { // Recipient was provided from combo list if ($_POST['receiver'] == 'thirdparty') // Id of third party { $sendto = $thirdparty->email; $sendtoid = 0; } else // Id du contact { $sendto = $thirdparty->contact_get_property((int) $_POST['receiver'],'email'); $sendtoid = $_POST['receiver']; } } if (trim($_POST['sendtocc'])) { $sendtocc = trim($_POST['sendtocc']); } elseif ($_POST['receivercc'] != '-1') { // Recipient was provided from combo list if ($_POST['receivercc'] == 'thirdparty') // Id of third party { $sendtocc = $thirdparty->email; } else // Id du contact { $sendtocc = $thirdparty->contact_get_property((int) $_POST['receivercc'],'email'); } } //var_dump($listofobjectref[$thirdpartyid]); // Array of invoice for this thirdparty $attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array()); $listofqualifiedinvoice=array(); $listofqualifiedref=array(); foreach($listofobjectref[$thirdpartyid] as $objectid => $object) { //var_dump($object); //var_dump($thirdpartyid.' - '.$objectid.' - '.$object->statut); if ($object->statut != Facture::STATUS_VALIDATED) { $nbignored++; continue; // Payment done or started or canceled } // Read document // TODO Use future field $object->fullpathdoc to know where is stored default file // TODO If not defined, use $object->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc. $filename=dol_sanitizeFileName($object->ref).'.pdf'; $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref); $file = $filedir . '/' . $filename; $mime = dol_mimetype($file); if (dol_is_file($file)) { if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send) { $object->fetch_thirdparty(); $sendto = $object->thirdparty->email; } if (empty($sendto)) { //print "No recipient for thirdparty ".$object->thirdparty->name; $nbignored++; continue; } if (dol_strlen($sendto)) { // Create form object $attachedfiles=array( 'paths'=>array_merge($attachedfiles['paths'],array($file)), 'names'=>array_merge($attachedfiles['names'],array($filename)), 'mimes'=>array_merge($attachedfiles['mimes'],array($mime)) ); } $listofqualifiedinvoice[$objectid]=$object; $listofqualifiedref[$objectid]=$object->ref; } else { $nbignored++; $langs->load("other"); $resaction.='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div>'; dol_syslog('Failed to read file: '.$file, LOG_WARNING); continue; } //var_dump($listofqualifiedref); } if (count($listofqualifiedinvoice) > 0) { $langs->load("commercial"); $from = $user->getFullName($langs) . ' <' . $user->email .'>'; $replyto = $from; $subject = GETPOST('subject'); $message = GETPOST('message'); $sendtocc = GETPOST('sentocc'); $sendtobcc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO); $substitutionarray=array( '__ID__' => join(', ',array_keys($listofqualifiedinvoice)), '__EMAIL__' => $thirdparty->email, '__CHECK_READ__' => '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>', //'__LASTNAME__' => $obj2->lastname, //'__FIRSTNAME__' => $obj2->firstname, '__FACREF__' => join(', ',$listofqualifiedref), // For backward compatibility '__REF__' => join(', ',$listofqualifiedref), '__REFCLIENT__' => $thirdparty->name ); $subject=make_substitutions($subject, $substitutionarray); $message=make_substitutions($message, $substitutionarray); $filepath = $attachedfiles['paths']; $filename = $attachedfiles['names']; $mimetype = $attachedfiles['mimes']; //var_dump($filepath); // Send mail require_once(DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'); $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1); if ($mailfile->error) { $resaction.='<div class="error">'.$mailfile->error.'</div>'; } else { $result=$mailfile->sendfile(); if ($result) { $resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'<br>'; // Must not contain " $error=0; // Insert logs into agenda foreach($listofqualifiedinvoice as $invid => $object) { $actiontypecode='AC_FAC'; $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; if ($message) { if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); $actionmsg = dol_concatdesc($actionmsg, $message); } // Initialisation donnees $object->sendtoid = 0; $object->actiontypecode = $actiontypecode; $object->actionmsg = $actionmsg; // Long text $object->actionmsg2 = $actionmsg2; // Short text $object->fk_element = $invid; $object->elementtype = $object->element; // Appel des triggers include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); $interface=new Interfaces($db); $result=$interface->run_triggers('BILL_SENTBYMAIL',$object,$user,$langs,$conf); if ($result < 0) { $error++; $errors=$interface->errors; } // Fin appel triggers if ($error) { setEventMessages($db->lasterror(), $errors, 'errors'); dol_syslog("Error in trigger BILL_SENTBYMAIL ".$db->lasterror(), LOG_ERR); } $nbsent++; } } else { $langs->load("other"); if ($mailfile->error) { $resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto); $resaction.='<br><div class="error">'.$mailfile->error.'</div>'; } else { $resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>'; } } } } } $resaction.=($resaction?'<br>':$resaction); $resaction.='<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n"; $resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n<br>"; $resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n<br>"; $resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n<br>"; if ($nbsent) { $action=''; // Do not show form post if there was at least one successfull sent setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs'); setEventMessages($resaction, null, 'mesgs'); } else { //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file setEventMessages($resaction, null, 'warnings'); } } $action='list'; $massaction=''; } } // Do we click on purge search criteria ? if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers { $search_user=''; $search_sale=''; $search_product_category=''; $search_ref=''; $search_refcustomer=''; $search_societe=''; $search_montant_ht=''; $search_montant_ttc=''; $search_status=''; $search_paymentmode=''; $day=''; $year=''; $month=''; $toselect=''; $option=''; $filter=''; $day_lim=''; $year_lim=''; $month_lim=''; } /* * View */ llxHeader('',$langs->trans('Bill'),'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes'); $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); $bankaccountstatic=new Account($db); $facturestatic=new Facture($db); $sql = 'SELECT'; if ($sall || $search_product_category > 0) $sql = 'SELECT DISTINCT'; $sql.= ' f.rowid as facid, f.facnumber, f.ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.total as total_ht, f.tva as total_tva, f.total_ttc,'; $sql.= ' f.datef as df, f.date_lim_reglement as datelimite,'; $sql.= ' f.paye as paye, f.fk_statut,'; $sql.= ' s.nom as name, s.rowid as socid, s.code_client, s.client '; if (! $sall) $sql.= ', SUM(pf.amount) as am'; // To be able to sort on status $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql.= ', '.MAIN_DB_PREFIX.'facture as f'; if (! $sall) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid'; else $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'facturedet as fd ON fd.fk_facture = f.rowid'; if ($sall || $search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'facturedet as pd ON f.rowid=pd.fk_facture'; if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; // We'll need this table joined to the select in order to filter by sale if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE f.fk_soc = s.rowid'; $sql.= " AND f.entity = ".$conf->entity; if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$search_product_category; if ($socid > 0) $sql.= ' AND s.rowid = '.$socid; if ($userid) { if ($userid == -1) $sql.=' AND f.fk_user_author IS NULL'; else $sql.=' AND f.fk_user_author = '.$userid; } if ($filtre) { $aFilter = explode(',', $filtre); foreach ($aFilter as $filter) { $filt = explode(':', $filter); $sql .= ' AND ' . trim($filt[0]) . ' = ' . trim($filt[1]); } } if ($search_ref) $sql .= natural_search('f.facnumber', $search_ref); if ($search_refcustomer) $sql .= natural_search('f.ref_client', $search_refcustomer); if ($search_societe) $sql .= natural_search('s.nom', $search_societe); if ($search_montant_ht != '') $sql.= natural_search('f.total', $search_montant_ht, 1); if ($search_montant_ttc != '') $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1); if ($search_status != '' && $search_status >= 0) $sql.= " AND f.fk_statut = ".$db->escape($search_status); if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$search_paymentmode.""; if ($month > 0) { if ($year > 0 && empty($day)) $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; else if ($year > 0 && ! empty($day)) $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; else $sql.= " AND date_format(f.datef, '%m') = '".$month."'"; } else if ($year > 0) { $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } if ($month_lim > 0) { if ($year_lim > 0 && empty($day_lim)) $sql.= " AND f.date_lim_reglement BETWEEN '".$db->idate(dol_get_first_day($year_lim,$month_lim,false))."' AND '".$db->idate(dol_get_last_day($year_lim,$month_lim,false))."'"; else if ($year_lim > 0 && ! empty($day_lim)) $sql.= " AND f.date_lim_reglement BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_lim, $day_lim, $year_lim))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month_lim, $day_lim, $year_lim))."'"; else $sql.= " AND date_format(f.date_lim_reglement, '%m') = '".$month_lim."'"; } else if ($year_lim > 0) { $sql.= " AND f.date_lim_reglement BETWEEN '".$db->idate(dol_get_first_day($year_lim,1,false))."' AND '".$db->idate(dol_get_last_day($year_lim,12,false))."'"; } if ($option == 'late') $sql.=" AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->client->warning_delay)."'"; if ($filter == 'paye:0') $sql.= " AND f.fk_statut = 1"; if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale; if ($search_user > 0) { $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; } if (! $sall) { $sql.= ' GROUP BY f.rowid, f.facnumber, ref_client, f.type, f.note_private, f.note_public, f.increment, f.total, f.tva, f.total_ttc,'; $sql.= ' f.datef, f.date_lim_reglement,'; $sql.= ' f.paye, f.fk_statut,'; $sql.= ' s.nom, s.rowid, s.code_client, s.client'; } else { $sql .= natural_search(array_keys($fieldstosearchall), $sall); } $sql.= ' ORDER BY '; $listfield=explode(',',$sortfield); foreach ($listfield as $key => $value) $sql.= $listfield[$key].' '.$sortorder.','; $sql.= ' f.rowid DESC '; $nbtotalofrecords = 0; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit+1,$offset); //print $sql; $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $arrayofselected=is_array($toselect)?$toselect:array(); if ($socid) { $soc = new Societe($db); $soc->fetch($socid); } $param='&socid='.$socid; if ($day) $param.='&day='.$day; if ($month) $param.='&month='.$month; if ($year) $param.='&year=' .$year; if ($day_lim) $param.='&day_lim='.$day_lim; if ($month_lim) $param.='&month_lim='.$month_lim; if ($year_lim) $param.='&year_lim=' .$year_lim; if ($search_ref) $param.='&search_ref=' .$search_ref; if ($search_refcustomer) $param.='&search_refcustomer=' .$search_refcustomer; if ($search_societe) $param.='&search_societe=' .$search_societe; if ($search_sale > 0) $param.='&search_sale=' .$search_sale; if ($search_user > 0) $param.='&search_user=' .$search_user; if ($search_product_category > 0) $param.='$search_product_category=' .$search_product_category; if ($search_montant_ht != '') $param.='&search_montant_ht='.$search_montant_ht; if ($search_montant_ttc != '') $param.='&search_montant_ttc='.$search_montant_ttc; if ($search_status != '') $param.='&search_status='.$search_status; if ($search_paymentmode > 0) $param.='search_paymentmode='.$search_paymentmode; $param.=(! empty($option)?"&amp;option=".$option:""); $massactionbutton=$form->selectMassAction('', $massaction ? array() : array('presend'=>$langs->trans("SendByMail"))); $i = 0; print '<form method="POST" name="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,$massactionbutton,$num,$nbtotalofrecords,'title_accountancy.png'); if ($massaction == 'presend') { $langs->load("mails"); if (! GETPOST('cancel')) { $objecttmp=new Facture($db); $listofselectedid=array(); $listofselectedthirdparties=array(); $listofselectedref=array(); foreach($arrayofselected as $toselectid) { $result=$objecttmp->fetch($toselectid); if ($result > 0) { $listofselectedid[$toselectid]=$toselectid; $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; $listofselectedthirdparties[$thirdpartyid]=$thirdpartyid; $listofselectedref[$thirdpartyid][$toselectid]=$objecttmp->ref; } } } print '<input type="hidden" name="massaction" value="confirm_presend">'; include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); dol_fiche_head(null, '', ''); $topicmail="SendBillRef"; $modelmail="facture_send"; // Cree l'objet formulaire mail include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); $formmail->withform=-1; $formmail->fromtype = 'user'; $formmail->fromid = $user->id; $formmail->fromname = $user->getFullName($langs); $formmail->frommail = $user->email; if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 1)) // If bit 1 is set { $formmail->trackid='inv'.$object->id; } if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set { include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'inv'.$object->id); } $formmail->withfrom=1; $liste=$langs->trans("AllRecipientSelected"); if (count($listofselectedthirdparties) == 1) { $liste=array(); $thirdpartyid=array_shift($listofselectedthirdparties); $soc=new Societe($db); $soc->fetch($thirdpartyid); foreach ($soc->thirdparty_and_contact_email_array(1) as $key=>$value) { $liste[$key]=$value; } $formmail->withtoreadonly=0; } else { $formmail->withtoreadonly=1; } $formmail->withto=$liste; $formmail->withtofree=0; $formmail->withtocc=1; $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; $formmail->withtopic=$langs->transnoentities($topicmail, '__REF__', '__REFCLIENT__'); $formmail->withfile=$langs->trans("OnlyPDFattachmentSupported"); $formmail->withbody=1; $formmail->withdeliveryreceipt=1; $formmail->withcancel=1; // Tableau des substitutions $formmail->substit['__REF__']='__REF__'; // We want to keep the tag $formmail->substit['__SIGNATURE__']=$user->signature; $formmail->substit['__REFCLIENT__']='__REFCLIENT__'; // We want to keep the tag $formmail->substit['__PERSONALIZED__']=''; $formmail->substit['__CONTACTCIVNAME__']=''; // Tableau des parametres complementaires du post $formmail->param['action']=$action; $formmail->param['models']=$modelmail; $formmail->param['models_id']=GETPOST('modelmailselected','int'); $formmail->param['facid']=join(',',$arrayofselected); //$formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id; print $formmail->get_form(); dol_fiche_end(); } if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="viewstatut" value="'.$viewstatut.'">'; if ($sall) { foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } // If the user can view prospects other than his' $moreforfilter=''; if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); $moreforfilter.='<div class="divsearchfield">'; $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; $moreforfilter.=$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth300'); $moreforfilter.='</div>'; } // If the user can view prospects other than his' if ($user->rights->societe->client->voir || $socid) { $moreforfilter.='<div class="divsearchfield">'; $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); $moreforfilter.='</div>'; } // If the user can view prospects other than his' if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter.='<div class="divsearchfield">'; $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, '', 1); $moreforfilter.='</div>'; } $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; else $moreforfilter = $hookmanager->resPrint; if ($moreforfilter) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; } print '<table class="liste '.($moreforfilter?"listwithfilterbefore":"").'">'; print '<tr class="liste_titre">'; print_liste_field_titre($langs->trans('Ref'),$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans('RefCustomer'),$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Date'),$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("DateDue"),$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('ThirdParty'),$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("PaymentModeShort"),$_SERVER["PHP_SELF"],"f.fk_mode_reglement","",$param,"",$sortfield,$sortorder); print_liste_field_titre($langs->trans('AmountHT'),$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Taxes'),$_SERVER['PHP_SELF'],'f.tva','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('AmountTTC'),$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Received'),$_SERVER['PHP_SELF'],'am','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Status'),$_SERVER['PHP_SELF'],'fk_statut,paye,am','',$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch '); print "</tr>\n"; // Filters lines print '<tr class="liste_titre">'; print '<td class="liste_titre" align="left">'; print '<input class="flat" size="6" type="text" name="search_ref" value="'.$search_ref.'">'; print '</td>'; print '<td class="liste_titre">'; print '<input class="flat" size="6" type="text" name="search_refcustomer" value="'.$search_refcustomer.'">'; print '</td>'; print '<td class="liste_titre" align="center">'; if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.$day.'">'; print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">'; $formother->select_year($year?$year:-1,'year',1, 20, 5); print '</td>'; print '<td class="liste_titre" align="center">'; if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day_lim" value="'.$day_lim.'">'; print '<input class="flat" type="text" size="1" maxlength="2" name="month_lim" value="'.$month_lim.'">'; $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); print '<br><input type="checkbox" name="option" value="late"'.($option == 'late'?' checked':'').'> '.$langs->trans("Late"); print '</td>'; print '<td class="liste_titre" align="left"><input class="flat" type="text" size="8" name="search_societe" value="'.$search_societe.'"></td>'; print '<td class="liste_titre" align="left">'; $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); print '</td>'; print '<td class="liste_titre" align="right"><input class="flat" type="text" size="6" name="search_montant_ht" value="'.$search_montant_ht.'"></td>'; print '<td class="liste_titre"></td>'; print '<td class="liste_titre" align="right"><input class="flat" type="text" size="6" name="search_montant_ttc" value="'.$search_montant_ttc.'"></td>'; print '<td class="liste_titre"></td>'; print '<td class="liste_titre" align="right">'; $liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled")); print $form->selectarray('search_status', $liststatus, $search_status, 1); print '</td>'; print '<td class="liste_titre" align="right"><input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"),'search.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">'; print '<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"),'searchclear.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">'; print "</td></tr>\n"; if ($num > 0) { $var=true; $total_ht=0; $total_tva=0; $total_ttc=0; $totalrecu=0; while ($i < min($num,$limit)) { $objp = $db->fetch_object($resql); $var=!$var; $datelimit=$db->jdate($objp->datelimite); print '<tr '.$bc[$var].'>'; print '<td class="nowrap">'; $facturestatic->id=$objp->facid; $facturestatic->ref=$objp->facnumber; $facturestatic->type=$objp->type; $facturestatic->statut=$objp->fk_statut; $facturestatic->date_lim_reglement=$db->jdate($objp->datelimite); $notetoshow=dol_string_nohtmltag(($user->societe_id>0?$objp->note_public:$objp->note_private),1); $paiement = $facturestatic->getSommePaiement(); print '<table class="nobordernopadding"><tr class="nocellnopadd">'; print '<td class="nobordernopadding nowrap">'; print $facturestatic->getNomUrl(1,'',200,0,$notetoshow); print $objp->increment; print '</td>'; print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; if (! empty($objp->note_private)) { print ' <span class="note">'; print '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$objp->facid.'">'.img_picto($langs->trans("ViewPrivateNote"),'object_generic').'</a>'; print '</span>'; } $filename=dol_sanitizeFileName($objp->facnumber); $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($objp->facnumber); $urlsource=$_SERVER['PHP_SELF'].'?id='.$objp->facid; print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir); print '</td>'; print '</tr>'; print '</table>'; print "</td>\n"; // Customer ref print '<td class="nowrap">'; print $objp->ref_client; print '</td>'; // Date print '<td align="center" class="nowrap">'; print dol_print_date($db->jdate($objp->df),'day'); print '</td>'; // Date limit print '<td align="center" class="nowrap">'.dol_print_date($datelimit,'day'); if ($facturestatic->hasDelay()) { print img_warning($langs->trans('Late')); } print '</td>'; print '<td>'; $thirdparty=new Societe($db); $thirdparty->id=$objp->socid; $thirdparty->name=$objp->name; $thirdparty->client=$objp->client; $thirdparty->code_client=$objp->code_client; print $thirdparty->getNomUrl(1,'customer'); print '</td>'; // Payment mode print '<td>'; $form->form_modes_reglement($_SERVER['PHP_SELF'], $objp->fk_mode_reglement, 'none', '', -1); print '</td>'; print '<td align="right">'.price($objp->total_ht,0,$langs).'</td>'; print '<td align="right">'.price($objp->total_tva,0,$langs).'</td>'; print '<td align="right">'.price($objp->total_ttc,0,$langs).'</td>'; print '<td align="right">'.(! empty($paiement)?price($paiement,0,$langs):'&nbsp;').'</td>'; // Status print '<td align="right" class="nowrap">'; print $facturestatic->LibStatut($objp->paye,$objp->fk_statut,5,$paiement,$objp->type); print "</td>"; // Checkbox print '<td class="nowrap" align="center">'; $selected=0; if (in_array($objp->facid, $arrayofselected)) $selected=1; print '<input id="cb'.$objp->facid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$objp->facid.'"'.($selected?' checked="checked"':'').'>'; print '</td>' ; print "</tr>\n"; $total_ht+=$objp->total_ht; $total_tva+=$objp->total_tva; $total_ttc+=$objp->total_ttc; $totalrecu+=$paiement; $i++; } if (($offset + $num) <= $limit) { // Print total print '<tr class="liste_total">'; print '<td class="liste_total" colspan="6" align="left">'.$langs->trans('Total').'</td>'; print '<td class="liste_total" align="right">'.price($total_ht,0,$langs).'</td>'; print '<td class="liste_total" align="right">'.price($total_tva,0,$langs).'</td>'; print '<td class="liste_total" align="right">'.price($total_ttc,0,$langs).'</td>'; print '<td class="liste_total" align="right">'.price($totalrecu,0,$langs).'</td>'; print '<td class="liste_total"></td>'; print '<td class="liste_total"></td>'; print '</tr>'; } } print "</table>\n"; print "</form>\n"; $db->free($resql); } else { dol_print_error($db); } llxFooter(); $db->close();
IndustriaLeuven/dolibarr
htdocs/compta/facture/list.php
PHP
gpl-3.0
38,537
/*! * web-SplayChat v0.4.0 - messaging web application for MTProto * http://SplayChat.com/ * Copyright (C) 2014 SplayChat Messenger <igor.beatle@gmail.com> * http://SplayChat.com//blob/master/LICENSE */ chrome.app.runtime.onLaunched.addListener(function(launchData) { chrome.app.window.create('../index.html', { id: 'web-SplayChat-chat', innerBounds: { width: 1000, height: 700 }, minWidth: 320, minHeight: 400, frame: 'chrome' }); });
ishmaelchibvuri/splayweb.io
app/js/background.js
JavaScript
gpl-3.0
481
/** * Copyright (C) 2019 Takima * * This file is part of OSM Contributor. * * OSM Contributor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OSM Contributor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OSM Contributor. If not, see <http://www.gnu.org/licenses/>. */ package io.jawg.osmcontributor.ui.utils; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.view.ScaleGestureDetector; import android.view.animation.DecelerateInterpolator; import java.util.Queue; import io.jawg.osmcontributor.utils.LimitedQueue; /** * @author Tommy Buonomo on 16/06/16. */ public abstract class ZoomAnimationGestureDetector extends ScaleGestureDetector.SimpleOnScaleGestureListener { private static final float MAX_SPEED = 50.0f; private static final float MIN_SPEED = 2.0f; private Queue<Float> previousSpeedQueue = new LimitedQueue<>(5); @Override public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) { previousSpeedQueue.clear(); return true; } @Override public boolean onScale(ScaleGestureDetector scaleGestureDetector) { float currentSpeed = scaleGestureDetector.getPreviousSpan() - scaleGestureDetector.getCurrentSpan(); previousSpeedQueue.add(currentSpeed); return true; } @Override public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) { float sum = 0; for (Float speed : previousSpeedQueue) { sum += speed; } float moy = sum / previousSpeedQueue.size(); if (Math.abs(moy) > MAX_SPEED) { moy = moy > 0 ? MAX_SPEED : -MAX_SPEED; } ValueAnimator valueAnimator = ObjectAnimator.ofFloat(-moy / 1000, 0); int duration = (int) (Math.abs(moy) * 12); valueAnimator.setDuration(duration); valueAnimator.setInterpolator(new DecelerateInterpolator()); onZoomAnimationEnd(valueAnimator); if (Math.abs(moy) > MIN_SPEED) { onZoomAnimationEnd(valueAnimator); } } public abstract void onZoomAnimationEnd(ValueAnimator animator); }
mapsquare/osm-contributor
src/main/java/io/jawg/osmcontributor/ui/utils/ZoomAnimationGestureDetector.java
Java
gpl-3.0
2,599
#region License /* Microsoft Public License (Ms-PL) MonoGame - Copyright © 2009 The MonoGame Team All rights reserved. This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. */ #endregion License // // Author: Kenneth James Pouncey // using System; using Microsoft.Xna.Framework.Content; namespace Microsoft.Xna.Framework.Content { internal class TimeSpanReader : ContentTypeReader<TimeSpan> { internal TimeSpanReader () { } protected internal override TimeSpan Read (ContentReader input, TimeSpan existingInstance) { // Could not find any information on this really but from all the searching it looks // like the constructor of number of ticks is long so I have placed that here for now // long is a Int64 so we read with 64 // <Duration>PT2S</Duration> // return new TimeSpan(input.ReadInt64 ()); } } }
Blucky87/Otiose2D
src/libs/MonoGame/MonoGame.Framework/Content/ContentReaders/TimeSpanReader.cs
C#
gpl-3.0
3,388
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- #include "AP_TECS.h" #include <AP_HAL.h> extern const AP_HAL::HAL& hal; #if CONFIG_HAL_BOARD == HAL_BOARD_AVR_SITL #include <stdio.h> # define Debug(fmt, args ...) do {printf("%s:%d: " fmt "\n", __FUNCTION__, __LINE__, ## args); hal.scheduler->delay(1); } while(0) #else # define Debug(fmt, args ...) #endif //Debug("%.2f %.2f %.2f %.2f \n", var1, var2, var3, var4); // table of user settable parameters const AP_Param::GroupInfo AP_TECS::var_info[] PROGMEM = { // @Param: CLMB_MAX // @DisplayName: Maximum Climb Rate (metres/sec) // @Description: This is the best climb rate that the aircraft can achieve with the throttle set to THR_MAX and the airspeed set to the default value. For electric aircraft make sure this number can be achieved towards the end of flight when the battery voltage has reduced. The setting of this parameter can be checked by commanding a positive altitude change of 100m in loiter, RTL or guided mode. If the throttle required to climb is close to THR_MAX and the aircraft is maintaining airspeed, then this parameter is set correctly. If the airspeed starts to reduce, then the parameter is set to high, and if the throttle demand require to climb and maintain speed is noticeably less than THR_MAX, then either CLMB_MAX should be increased or THR_MAX reduced. // @Increment: 0.1 // @User: User AP_GROUPINFO("CLMB_MAX", 0, AP_TECS, _maxClimbRate, 5.0f), // @Param: SINK_MIN // @DisplayName: Minimum Sink Rate (metres/sec) // @Description: This is the sink rate of the aircraft with the throttle set to THR_MIN and the same airspeed as used to measure CLMB_MAX. // @Increment: 0.1 // @User: User AP_GROUPINFO("SINK_MIN", 1, AP_TECS, _minSinkRate, 2.0f), // @Param: TIME_CONST // @DisplayName: Controller time constant (sec) // @Description: This is the time constant of the TECS control algorithm. Smaller values make it faster to respond, large values make it slower to respond. // @Range: 3.0-10.0 // @Increment: 0.2 // @User: Advanced AP_GROUPINFO("TIME_CONST", 2, AP_TECS, _timeConst, 5.0f), // @Param: THR_DAMP // @DisplayName: Controller throttle damping // @Description: This is the damping gain for the throttle demand loop. Increase to add damping to correct for oscillations in speed and height. // @Range: 0.1-1.0 // @Increment: 0.1 // @User: Advanced AP_GROUPINFO("THR_DAMP", 3, AP_TECS, _thrDamp, 0.5f), // @Param: INTEG_GAIN // @DisplayName: Controller integrator // @Description: This is the integrator gain on the control loop. Increase to increase the rate at which speed and height offsets are trimmed out // @Range: 0.0-0.5 // @Increment: 0.02 // @User: Advanced AP_GROUPINFO("INTEG_GAIN", 4, AP_TECS, _integGain, 0.1f), // @Param: VERT_ACC // @DisplayName: Vertical Acceleration Limit (metres/sec^2) // @Description: This is the maximum vertical acceleration either up or down that the controller will use to correct speed or height errors. // @Range: 1.0-10.0 // @Increment: 0.5 // @User: Advanced AP_GROUPINFO("VERT_ACC", 5, AP_TECS, _vertAccLim, 7.0f), // @Param: HGT_OMEGA // @DisplayName: Height complementary filter frequency (radians/sec) // @Description: This is the cross-over frequency of the complementary filter used to fuse vertical acceleration and baro alt to obtain an estimate of height rate and height. // @Range: 1.0-5.0 // @Increment: 0.05 // @User: Advanced AP_GROUPINFO("HGT_OMEGA", 6, AP_TECS, _hgtCompFiltOmega, 3.0f), // @Param: SPD_OMEGA // @DisplayName: Speed complementary filter frequency (radians/sec) // @Description: This is the cross-over frequency of the complementary filter used to fuse longitudinal acceleration and airspeed to obtain a lower noise and lag estimate of airspeed. // @Range: 0.5-2.0 // @Increment: 0.05 // @User: Advanced AP_GROUPINFO("SPD_OMEGA", 7, AP_TECS, _spdCompFiltOmega, 2.0f), // @Param: RLL2THR // @DisplayName: Bank angle compensation gain // @Description: Increasing this gain turn increases the amount of throttle that will be used to compensate for the additional drag created by turning. Ideally this should be set to approximately 10 x the extra sink rate in m/s created by a 45 degree bank turn. Increase this gain if the aircraft initially loses energy in turns and reduce if the aircraft initially gains energy in turns. Efficient high aspect-ratio aircraft (eg powered sailplanes) can use a lower value, whereas inefficient low aspect-ratio models (eg delta wings) can use a higher value. // @Range: 5.0 to 30.0 // @Increment: 1.0 // @User: Advanced AP_GROUPINFO("RLL2THR", 8, AP_TECS, _rollComp, 10.0f), // @Param: SPDWEIGHT // @DisplayName: Weighting applied to speed control // @Description: This parameter adjusts the amount of weighting that the pitch control applies to speed vs height errors. Setting it to 0.0 will cause the pitch control to control height and ignore speed errors. This will normally improve height accuracy but give larger airspeed errors. Setting it to 2.0 will cause the pitch control loop to control speed and ignore height errors. This will normally reduce airsped errors, but give larger height errors. A value of 1.0 gives a balanced response and is the default. // @Range: 0.0 to 2.0 // @Increment: 0.1 // @User: Advanced AP_GROUPINFO("SPDWEIGHT", 9, AP_TECS, _spdWeight, 1.0f), // @Param: PTCH_DAMP // @DisplayName: Controller pitch damping // @Description: This is the damping gain for the pitch demand loop. Increase to add damping to correct for oscillations in speed and height. // @Range: 0.1-1.0 // @Increment: 0.1 // @User: Advanced AP_GROUPINFO("PTCH_DAMP", 10, AP_TECS, _ptchDamp, 0.0f), // @Param: SINK_MAX // @DisplayName: Maximum Descent Rate (metres/sec) // @Description: This sets the maximum descent rate that the controller will use. If this value is too large, the aircraft will reach the pitch angle limit first and be enable to achieve the descent rate. This should be set to a value that can be achieved at the lower pitch angle limit. // @Increment: 0.1 // @User: User AP_GROUPINFO("SINK_MAX", 11, AP_TECS, _maxSinkRate, 5.0f), // @Param: LAND_ARSPD // @DisplayName: Airspeed during landing approach (m/s) // @Description: When performing an autonomus landing, this value is used as the goal airspeed during approach. Note that this parameter is not useful if your platform does not have an airspeed sensor (use TECS_LAND_THR instead). If negative then this value is not used during landing. // @Range: -1 to 127 // @Increment: 1 // @User: User AP_GROUPINFO("LAND_ARSPD", 12, AP_TECS, _landAirspeed, -1), // @Param: LAND_THR // @DisplayName: Cruise throttle during landing approach (percentage) // @Description: Use this parameter instead of LAND_ASPD if your platform does not have an airspeed sensor. It is the cruise throttle during landing approach. If it is negative if TECS_LAND_ASPD is in use then this value is not used during landing. // @Range: -1 to 100 // @Increment: 0.1 // @User: User AP_GROUPINFO("LAND_THR", 13, AP_TECS, _landThrottle, -1), // @Param: LAND_SPDWGT // @DisplayName: Weighting applied to speed control during landing. // @Description: Same as SPDWEIGHT parameter, with the exception that this parameter is applied during landing flight stages. A value closer to 2 will result in the plane ignoring height error during landing and our experience has been that the plane will therefore keep the nose up -- sometimes good for a glider landing (with the side effect that you will likely glide a ways past the landing point). A value closer to 0 results in the plane ignoring speed error -- use caution when lowering the value below 1 -- ignoring speed could result in a stall. // @Range: 0.0 to 2.0 // @Increment: 0.1 // @User: Advanced AP_GROUPINFO("LAND_SPDWGT", 14, AP_TECS, _spdWeightLand, 1.0f), // @Param: PITCH_MAX // @DisplayName: Maximum pitch in auto flight // @Description: This controls maximum pitch up in automatic throttle modes. If this is set to zero then LIM_PITCH_MAX is used instead. The purpose of this parameter is to allow the use of a smaller pitch range when in automatic flight than what is used in FBWA mode. // @Range: 0 45 // @Increment: 1 // @User: Advanced AP_GROUPINFO("PITCH_MAX", 15, AP_TECS, _pitch_max, 0), // @Param: PITCH_MIN // @DisplayName: Minimum pitch in auto flight // @Description: This controls minimum pitch in automatic throttle modes. If this is set to zero then LIM_PITCH_MIN is used instead. The purpose of this parameter is to allow the use of a smaller pitch range when in automatic flight than what is used in FBWA mode. Note that TECS_PITCH_MIN should be a negative number. // @Range: -45 0 // @Increment: 1 // @User: Advanced AP_GROUPINFO("PITCH_MIN", 16, AP_TECS, _pitch_min, 0), // @Param: LAND_SINK // @DisplayName: Sink rate for final landing stage // @Description: The sink rate in meters/second for the final stage of landing. // @Range: 0.0 to 2.0 // @Increment: 0.1 // @User: Advanced AP_GROUPINFO("LAND_SINK", 17, AP_TECS, _land_sink, 0.25f), // @Param: TECS_LAND_TCONST // @DisplayName: Land controller time constant (sec) // @Description: This is the time constant of the TECS control algorithm when in final landing stage of flight. It should be smaller than TECS_TIME_CONST to allow for faster flare // @Range: 1.0-5.0 // @Increment: 0.2 // @User: Advanced AP_GROUPINFO("LAND_TCONST", 18, AP_TECS, _landTimeConst, 2.0f), AP_GROUPEND }; /* * Written by Paul Riseborough 2013 to provide: * - Combined control of speed and height using throttle to control * total energy and pitch angle to control exchange of energy between * potential and kinetic. * Selectable speed or height priority modes when calculating pitch angle * - Fallback mode when no airspeed measurement is available that * sets throttle based on height rate demand and switches pitch angle control to * height priority * - Underspeed protection that demands maximum throttle and switches pitch angle control * to speed priority mode * - Relative ease of tuning through use of intuitive time constant, integrator and damping gains and the use * of easy to measure aircraft performance data * */ void AP_TECS::update_50hz(float hgt_afe) { // Implement third order complementary filter for height and height rate // estimted height rate = _climb_rate // estimated height above field elevation = _integ3_state // Reference Paper : // Optimising the Gains of the Baro-Inertial Vertical Channel // Widnall W.S, Sinha P.K, // AIAA Journal of Guidance and Control, 78-1307R // Calculate time in seconds since last update uint32_t now = hal.scheduler->micros(); float DT = max((now - _update_50hz_last_usec),0)*1.0e-6f; if (DT > 1.0f) { _integ3_state = hgt_afe; _climb_rate = 0.0f; _integ1_state = 0.0f; DT = 0.02f; // when first starting TECS, use a // small time constant } _update_50hz_last_usec = now; // USe inertial nav verical velocity and height if available Vector3f posned, velned; if (_ahrs.get_velocity_NED(velned) && _ahrs.get_relative_position_NED(posned)) { _climb_rate = - velned.z; _integ3_state = - posned.z; } else { // Get height acceleration float hgt_ddot_mea = -(_ahrs.get_accel_ef().z + GRAVITY_MSS); // Perform filter calculation using backwards Euler integration // Coefficients selected to place all three filter poles at omega float omega2 = _hgtCompFiltOmega*_hgtCompFiltOmega; float hgt_err = hgt_afe - _integ3_state; float integ1_input = hgt_err * omega2 * _hgtCompFiltOmega; _integ1_state = _integ1_state + integ1_input * DT; float integ2_input = _integ1_state + hgt_ddot_mea + hgt_err * omega2 * 3.0f; _climb_rate = _climb_rate + integ2_input * DT; float integ3_input = _climb_rate + hgt_err * _hgtCompFiltOmega * 3.0f; // If more than 1 second has elapsed since last update then reset the integrator state // to the measured height if (DT > 1.0f) { _integ3_state = hgt_afe; } else { _integ3_state = _integ3_state + integ3_input*DT; } } // Update and average speed rate of change // Get DCM const Matrix3f &rotMat = _ahrs.get_dcm_matrix(); // Calculate speed rate of change float temp = rotMat.c.x * GRAVITY_MSS + _ahrs.get_ins().get_accel().x; // take 5 point moving average _vel_dot = _vdot_filter.apply(temp); } void AP_TECS::_update_speed(void) { // Calculate time in seconds since last update uint32_t now = hal.scheduler->micros(); float DT = max((now - _update_speed_last_usec),0)*1.0e-6f; _update_speed_last_usec = now; // Convert equivalent airspeeds to true airspeeds float EAS2TAS = _ahrs.get_EAS2TAS(); _TAS_dem = _EAS_dem * EAS2TAS; _TASmax = aparm.airspeed_max * EAS2TAS; _TASmin = aparm.airspeed_min * EAS2TAS; if (_landAirspeed >= 0 && _ahrs.airspeed_sensor_enabled() && (_flight_stage == FLIGHT_LAND_APPROACH || _flight_stage== FLIGHT_LAND_FINAL)) { _TAS_dem = _landAirspeed * EAS2TAS; if (_TASmin > _TAS_dem) { _TASmin = _TAS_dem; } } // Reset states of time since last update is too large if (DT > 1.0f) { _integ5_state = (_EAS * EAS2TAS); _integ4_state = 0.0f; DT = 0.1f; // when first starting TECS, use a // small time constant } // Get airspeed or default to halfway between min and max if // airspeed is not being used and set speed rate to zero if (!_ahrs.airspeed_sensor_enabled() || !_ahrs.airspeed_estimate(&_EAS)) { // If no airspeed available use average of min and max _EAS = 0.5f * (aparm.airspeed_min.get() + (float)aparm.airspeed_max.get()); } // Implement a second order complementary filter to obtain a // smoothed airspeed estimate // airspeed estimate is held in _integ5_state float aspdErr = (_EAS * EAS2TAS) - _integ5_state; float integ4_input = aspdErr * _spdCompFiltOmega * _spdCompFiltOmega; // Prevent state from winding up if (_integ5_state < 3.1f){ integ4_input = max(integ4_input , 0.0f); } _integ4_state = _integ4_state + integ4_input * DT; float integ5_input = _integ4_state + _vel_dot + aspdErr * _spdCompFiltOmega * 1.4142f; _integ5_state = _integ5_state + integ5_input * DT; // limit the airspeed to a minimum of 3 m/s _integ5_state = max(_integ5_state, 3.0f); } void AP_TECS::_update_speed_demand(void) { // Set the airspeed demand to the minimum value if an underspeed condition exists // or a bad descent condition exists // This will minimise the rate of descent resulting from an engine failure, // enable the maximum climb rate to be achieved and prevent continued full power descent // into the ground due to an unachievable airspeed value if ((_badDescent) || (_underspeed)) { _TAS_dem = _TASmin; } // Constrain speed demand _TAS_dem = constrain_float(_TAS_dem, _TASmin, _TASmax); // calculate velocity rate limits based on physical performance limits // provision to use a different rate limit if bad descent or underspeed condition exists // Use 50% of maximum energy rate to allow margin for total energy contgroller float velRateMax; float velRateMin; if ((_badDescent) || (_underspeed)) { velRateMax = 0.5f * _STEdot_max / _integ5_state; velRateMin = 0.5f * _STEdot_min / _integ5_state; } else { velRateMax = 0.5f * _STEdot_max / _integ5_state; velRateMin = 0.5f * _STEdot_min / _integ5_state; } // Apply rate limit if ((_TAS_dem - _TAS_dem_adj) > (velRateMax * 0.1f)) { _TAS_dem_adj = _TAS_dem_adj + velRateMax * 0.1f; _TAS_rate_dem = velRateMax; } else if ((_TAS_dem - _TAS_dem_adj) < (velRateMin * 0.1f)) { _TAS_dem_adj = _TAS_dem_adj + velRateMin * 0.1f; _TAS_rate_dem = velRateMin; } else { _TAS_dem_adj = _TAS_dem; _TAS_rate_dem = (_TAS_dem - _TAS_dem_last) / 0.1f; } // Constrain speed demand again to protect against bad values on initialisation. _TAS_dem_adj = constrain_float(_TAS_dem_adj, _TASmin, _TASmax); _TAS_dem_last = _TAS_dem; } void AP_TECS::_update_height_demand(void) { // Apply 2 point moving average to demanded height // This is required because height demand is only updated at 5Hz _hgt_dem = 0.5f * (_hgt_dem + _hgt_dem_in_old); _hgt_dem_in_old = _hgt_dem; // Limit height rate of change if ((_hgt_dem - _hgt_dem_prev) > (_maxClimbRate * 0.1f)) { _hgt_dem = _hgt_dem_prev + _maxClimbRate * 0.1f; } else if ((_hgt_dem - _hgt_dem_prev) < (-_maxSinkRate * 0.1f)) { _hgt_dem = _hgt_dem_prev - _maxSinkRate * 0.1f; } _hgt_dem_prev = _hgt_dem; // Apply first order lag to height demand _hgt_dem_adj = 0.05f * _hgt_dem + 0.95f * _hgt_dem_adj_last; _hgt_dem_adj_last = _hgt_dem_adj; // in final landing stage force height rate demand to the // configured sink rate if (_flight_stage == FLIGHT_LAND_FINAL) { if (_flare_counter == 0) { _hgt_rate_dem = _climb_rate; } // bring it in over 1s to prevent overshoot if (_flare_counter < 10) { _hgt_rate_dem = _hgt_rate_dem * 0.8f - 0.2f * _land_sink; _flare_counter++; } else { _hgt_rate_dem = - _land_sink; } } else { _hgt_rate_dem = (_hgt_dem_adj - _hgt_dem_adj_last) / 0.1f; _flare_counter = 0; } } void AP_TECS::_detect_underspeed(void) { if (((_integ5_state < _TASmin * 0.9f) && (_throttle_dem >= _THRmaxf * 0.95f) && _flight_stage != AP_TECS::FLIGHT_LAND_FINAL) || ((_integ3_state < _hgt_dem_adj) && _underspeed)) { _underspeed = true; } else { _underspeed = false; } } void AP_TECS::_update_energies(void) { // Calculate specific energy demands _SPE_dem = _hgt_dem_adj * GRAVITY_MSS; _SKE_dem = 0.5f * _TAS_dem_adj * _TAS_dem_adj; // Calculate specific energy rate demands _SPEdot_dem = _hgt_rate_dem * GRAVITY_MSS; _SKEdot_dem = _integ5_state * _TAS_rate_dem; // Calculate specific energy _SPE_est = _integ3_state * GRAVITY_MSS; _SKE_est = 0.5f * _integ5_state * _integ5_state; // Calculate specific energy rate _SPEdot = _climb_rate * GRAVITY_MSS; _SKEdot = _integ5_state * _vel_dot; } /* current time constant. It is lower in landing to try to give a precise approach */ float AP_TECS::timeConstant(void) { if (_flight_stage==FLIGHT_LAND_FINAL || _flight_stage==FLIGHT_LAND_APPROACH) { return _landTimeConst; } return _timeConst; } void AP_TECS::_update_throttle(void) { // Calculate limits to be applied to potential energy error to prevent over or underspeed occurring due to large height errors float SPE_err_max = 0.5f * _TASmax * _TASmax - _SKE_dem; float SPE_err_min = 0.5f * _TASmin * _TASmin - _SKE_dem; // Calculate total energy error _STE_error = constrain_float((_SPE_dem - _SPE_est), SPE_err_min, SPE_err_max) + _SKE_dem - _SKE_est; float STEdot_dem = constrain_float((_SPEdot_dem + _SKEdot_dem), _STEdot_min, _STEdot_max); float STEdot_error = STEdot_dem - _SPEdot - _SKEdot; // Apply 0.5 second first order filter to STEdot_error // This is required to remove accelerometer noise from the measurement STEdot_error = 0.2f*STEdot_error + 0.8f*_STEdotErrLast; _STEdotErrLast = STEdot_error; // Calculate throttle demand // If underspeed condition is set, then demand full throttle if (_underspeed) { _throttle_dem_unc = 1.0f; } else { // Calculate gain scaler from specific energy error to throttle float K_STE2Thr = 1 / (timeConstant() * (_STEdot_max - _STEdot_min)); // Calculate feed-forward throttle float ff_throttle = 0; float nomThr = aparm.throttle_cruise * 0.01f; const Matrix3f &rotMat = _ahrs.get_dcm_matrix(); // Use the demanded rate of change of total energy as the feed-forward demand, but add // additional component which scales with (1/cos(bank angle) - 1) to compensate for induced // drag increase during turns. float cosPhi = sqrtf((rotMat.a.y*rotMat.a.y) + (rotMat.b.y*rotMat.b.y)); STEdot_dem = STEdot_dem + _rollComp * (1.0f/constrain_float(cosPhi * cosPhi , 0.1f, 1.0f) - 1.0f); ff_throttle = nomThr + STEdot_dem / (_STEdot_max - _STEdot_min) * (_THRmaxf - _THRminf); // Calculate PD + FF throttle _throttle_dem = (_STE_error + STEdot_error * _thrDamp) * K_STE2Thr + ff_throttle; // Rate limit PD + FF throttle // Calculate the throttle increment from the specified slew time if (aparm.throttle_slewrate != 0) { float thrRateIncr = _DT * (_THRmaxf - _THRminf) * aparm.throttle_slewrate * 0.01f; _throttle_dem = constrain_float(_throttle_dem, _last_throttle_dem - thrRateIncr, _last_throttle_dem + thrRateIncr); _last_throttle_dem = _throttle_dem; } // Calculate integrator state upper and lower limits // Set to a value thqat will allow 0.1 (10%) throttle saturation to allow for noise on the demand float integ_max = (_THRmaxf - _throttle_dem + 0.1f); float integ_min = (_THRminf - _throttle_dem - 0.1f); // Calculate integrator state, constraining state // Set integrator to a max throttle value during climbout _integ6_state = _integ6_state + (_STE_error * _integGain) * _DT * K_STE2Thr; if (_flight_stage == AP_TECS::FLIGHT_TAKEOFF) { _integ6_state = integ_max; } else { _integ6_state = constrain_float(_integ6_state, integ_min, integ_max); } // Sum the components. // Only use feed-forward component if airspeed is not being used if (_ahrs.airspeed_sensor_enabled()) { _throttle_dem = _throttle_dem + _integ6_state; } else { _throttle_dem = ff_throttle; } } // Constrain throttle demand _throttle_dem = constrain_float(_throttle_dem, _THRminf, _THRmaxf); } void AP_TECS::_update_throttle_option(int16_t throttle_nudge) { // Calculate throttle demand by interpolating between pitch and throttle limits float nomThr; //If landing and we don't have an airspeed sensor and we have a non-zero //TECS_LAND_THR param then use it if ((_flight_stage == FLIGHT_LAND_APPROACH || _flight_stage== FLIGHT_LAND_FINAL) && _landThrottle >= 0) { nomThr = (_landThrottle + throttle_nudge) * 0.01f; } else { //not landing or not using TECS_LAND_THR parameter nomThr = (aparm.throttle_cruise + throttle_nudge)* 0.01f; } if (_flight_stage == AP_TECS::FLIGHT_TAKEOFF) { _throttle_dem = _THRmaxf; } else if (_pitch_dem > 0.0f && _PITCHmaxf > 0.0f) { _throttle_dem = nomThr + (_THRmaxf - nomThr) * _pitch_dem / _PITCHmaxf; } else if (_pitch_dem < 0.0f && _PITCHminf < 0.0f) { _throttle_dem = nomThr + (_THRminf - nomThr) * _pitch_dem / _PITCHminf; } else { _throttle_dem = nomThr; } // Calculate additional throttle for turn drag compensation including throttle nudging const Matrix3f &rotMat = _ahrs.get_dcm_matrix(); // Use the demanded rate of change of total energy as the feed-forward demand, but add // additional component which scales with (1/cos(bank angle) - 1) to compensate for induced // drag increase during turns. float cosPhi = sqrtf((rotMat.a.y*rotMat.a.y) + (rotMat.b.y*rotMat.b.y)); float STEdot_dem = _rollComp * (1.0f/constrain_float(cosPhi * cosPhi , 0.1f, 1.0f) - 1.0f); _throttle_dem = _throttle_dem + STEdot_dem / (_STEdot_max - _STEdot_min) * (_THRmaxf - _THRminf); } void AP_TECS::_detect_bad_descent(void) { // Detect a demanded airspeed too high for the aircraft to achieve. This will be // evident by the the following conditions: // 1) Underspeed protection not active // 2) Specific total energy error > 200 (greater than ~20m height error) // 3) Specific total energy reducing // 4) throttle demand > 90% // If these four conditions exist simultaneously, then the protection // mode will be activated. // Once active, the following condition are required to stay in the mode // 1) Underspeed protection not active // 2) Specific total energy error > 0 // This mode will produce an undulating speed and height response as it cuts in and out but will prevent the aircraft from descending into the ground if an unachievable speed demand is set float STEdot = _SPEdot + _SKEdot; if ((!_underspeed && (_STE_error > 200.0f) && (STEdot < 0.0f) && (_throttle_dem >= _THRmaxf * 0.9f)) || (_badDescent && !_underspeed && (_STE_error > 0.0f))) { _badDescent = true; } else { _badDescent = false; } } void AP_TECS::_update_pitch(void) { // Calculate Speed/Height Control Weighting // This is used to determine how the pitch control prioritises speed and height control // A weighting of 1 provides equal priority (this is the normal mode of operation) // A SKE_weighting of 0 provides 100% priority to height control. This is used when no airspeed measurement is available // A SKE_weighting of 2 provides 100% priority to speed control. This is used when an underspeed condition is detected. In this instance, if airspeed // rises above the demanded value, the pitch angle will be increased by the TECS controller. float SKE_weighting = constrain_float(_spdWeight, 0.0f, 2.0f); if (!_ahrs.airspeed_sensor_enabled()) { SKE_weighting = 0.0f; } else if ( _underspeed || _flight_stage == AP_TECS::FLIGHT_TAKEOFF) { SKE_weighting = 2.0f; } else if (_flight_stage == AP_TECS::FLIGHT_LAND_APPROACH || _flight_stage == AP_TECS::FLIGHT_LAND_FINAL) { SKE_weighting = constrain_float(_spdWeightLand, 0.0f, 2.0f); } float SPE_weighting = 2.0f - SKE_weighting; // Calculate Specific Energy Balance demand, and error float SEB_dem = _SPE_dem * SPE_weighting - _SKE_dem * SKE_weighting; float SEBdot_dem = _SPEdot_dem * SPE_weighting - _SKEdot_dem * SKE_weighting; float SEB_error = SEB_dem - (_SPE_est * SPE_weighting - _SKE_est * SKE_weighting); float SEBdot_error = SEBdot_dem - (_SPEdot * SPE_weighting - _SKEdot * SKE_weighting); // Calculate integrator state, constraining input if pitch limits are exceeded float integ7_input = SEB_error * _integGain; if (_pitch_dem_unc > _PITCHmaxf) { integ7_input = min(integ7_input, _PITCHmaxf - _pitch_dem_unc); } else if (_pitch_dem_unc < _PITCHminf) { integ7_input = max(integ7_input, _PITCHminf - _pitch_dem_unc); } _integ7_state = _integ7_state + integ7_input * _DT; // Apply max and min values for integrator state that will allow for no more than // 5deg of saturation. This allows for some pitch variation due to gusts before the // integrator is clipped. Otherwise the effectiveness of the integrator will be reduced in turbulence // During climbout/takeoff, bias the demanded pitch angle so that zero speed error produces a pitch angle // demand equal to the minimum value (which is )set by the mission plan during this mode). Otherwise the // integrator has to catch up before the nose can be raised to reduce speed during climbout. float gainInv = (_integ5_state * timeConstant() * GRAVITY_MSS); float temp = SEB_error + SEBdot_error * _ptchDamp + SEBdot_dem * timeConstant(); if (_flight_stage == AP_TECS::FLIGHT_TAKEOFF) { temp += _PITCHminf * gainInv; } _integ7_state = constrain_float(_integ7_state, (gainInv * (_PITCHminf - 0.0783f)) - temp, (gainInv * (_PITCHmaxf + 0.0783f)) - temp); // Calculate pitch demand from specific energy balance signals _pitch_dem_unc = (temp + _integ7_state) / gainInv; // Constrain pitch demand _pitch_dem = constrain_float(_pitch_dem_unc, _PITCHminf, _PITCHmaxf); _pitch_dem = constrain_float(_pitch_dem_unc, _PITCHminf, _PITCHmaxf); // Rate limit the pitch demand to comply with specified vertical // acceleration limit float ptchRateIncr = _DT * _vertAccLim / _integ5_state; if ((_pitch_dem - _last_pitch_dem) > ptchRateIncr) { _pitch_dem = _last_pitch_dem + ptchRateIncr; } else if ((_pitch_dem - _last_pitch_dem) < -ptchRateIncr) { _pitch_dem = _last_pitch_dem - ptchRateIncr; } _last_pitch_dem = _pitch_dem; } void AP_TECS::_initialise_states(int32_t ptchMinCO_cd, float hgt_afe) { // Initialise states and variables if DT > 1 second or in climbout if (_DT > 1.0f) { _integ6_state = 0.0f; _integ7_state = 0.0f; _last_throttle_dem = aparm.throttle_cruise * 0.01f; _last_pitch_dem = _ahrs.pitch; _hgt_dem_adj_last = hgt_afe; _hgt_dem_adj = _hgt_dem_adj_last; _hgt_dem_prev = _hgt_dem_adj_last; _hgt_dem_in_old = _hgt_dem_adj_last; _TAS_dem_last = _TAS_dem; _TAS_dem_adj = _TAS_dem; _underspeed = false; _badDescent = false; _DT = 0.1f; // when first starting TECS, use a // small time constant } else if (_flight_stage == AP_TECS::FLIGHT_TAKEOFF) { _PITCHminf = 0.000174533f * ptchMinCO_cd; _THRminf = _THRmaxf - 0.01f; _hgt_dem_adj_last = hgt_afe; _hgt_dem_adj = _hgt_dem_adj_last; _hgt_dem_prev = _hgt_dem_adj_last; _TAS_dem_last = _TAS_dem; _TAS_dem_adj = _TAS_dem; _underspeed = false; _badDescent = false; } } void AP_TECS::_update_STE_rate_lim(void) { // Calculate Specific Total Energy Rate Limits // This is a trivial calculation at the moment but will get bigger once we start adding altitude effects _STEdot_max = _maxClimbRate * GRAVITY_MSS; _STEdot_min = - _minSinkRate * GRAVITY_MSS; } void AP_TECS::update_pitch_throttle(int32_t hgt_dem_cm, int32_t EAS_dem_cm, enum FlightStage flight_stage, int32_t ptchMinCO_cd, int16_t throttle_nudge, float hgt_afe) { // Calculate time in seconds since last update uint32_t now = hal.scheduler->micros(); _DT = max((now - _update_pitch_throttle_last_usec),0)*1.0e-6f; _update_pitch_throttle_last_usec = now; // Update the speed estimate using a 2nd order complementary filter _update_speed(); // Convert inputs _hgt_dem = hgt_dem_cm * 0.01f; _EAS_dem = EAS_dem_cm * 0.01f; _THRmaxf = aparm.throttle_max * 0.01f; _THRminf = aparm.throttle_min * 0.01f; // work out the maximum and minimum pitch // if TECS_PITCH_{MAX,MIN} isn't set then use // LIM_PITCH_{MAX,MIN}. Don't allow TECS_PITCH_{MAX,MIN} to be // larger than LIM_PITCH_{MAX,MIN} if (_pitch_max <= 0) { _PITCHmaxf = aparm.pitch_limit_max_cd * 0.01f; } else { _PITCHmaxf = min(_pitch_max, aparm.pitch_limit_max_cd * 0.01f); } if (_pitch_min >= 0) { _PITCHminf = aparm.pitch_limit_min_cd * 0.01f; } else { _PITCHminf = max(_pitch_min, aparm.pitch_limit_min_cd * 0.01f); } if (flight_stage == FLIGHT_LAND_FINAL) { // in flare use min pitch from LAND_PITCH_CD _PITCHminf = max(_PITCHminf, aparm.land_pitch_cd * 0.01f); // and allow zero throttle _THRminf = 0; } // convert to radians _PITCHmaxf = radians(_PITCHmaxf); _PITCHminf = radians(_PITCHminf); _flight_stage = flight_stage; // initialise selected states and variables if DT > 1 second or in climbout _initialise_states(ptchMinCO_cd, hgt_afe); // Calculate Specific Total Energy Rate Limits _update_STE_rate_lim(); // Calculate the speed demand _update_speed_demand(); // Calculate the height demand _update_height_demand(); // Detect underspeed condition _detect_underspeed(); // Calculate specific energy quantitiues _update_energies(); // Calculate throttle demand - use simple pitch to throttle if no airspeed sensor if (_ahrs.airspeed_sensor_enabled()) { _update_throttle(); } else { _update_throttle_option(throttle_nudge); } // Detect bad descent due to demanded airspeed being too high _detect_bad_descent(); // Calculate pitch demand _update_pitch(); // Write internal variables to the log_tuning structure. This // structure will be logged in dataflash at 10Hz log_tuning.hgt_dem = _hgt_dem_adj; log_tuning.hgt = _integ3_state; log_tuning.dhgt_dem = _hgt_rate_dem; log_tuning.dhgt = _climb_rate; log_tuning.spd_dem = _TAS_dem_adj; log_tuning.spd = _integ5_state; log_tuning.dspd = _vel_dot; log_tuning.ithr = _integ6_state; log_tuning.iptch = _integ7_state; log_tuning.thr = _throttle_dem; log_tuning.ptch = _pitch_dem; log_tuning.dspd_dem = _TAS_rate_dem; log_tuning.time_ms = hal.scheduler->millis(); } // log the contents of the log_tuning structure to dataflash void AP_TECS::log_data(DataFlash_Class &dataflash, uint8_t msgid) { log_tuning.head1 = HEAD_BYTE1; log_tuning.head2 = HEAD_BYTE2; log_tuning.msgid = msgid; dataflash.WriteBlock(&log_tuning, sizeof(log_tuning)); }
mrpollo/ardupilot
libraries/AP_TECS/AP_TECS.cpp
C++
gpl-3.0
33,291
'use strict'; /** * A class representation of the BSON Double type. */ class Double { /** * Create a Double type * * @param {number} value the number we want to represent as a double. * @return {Double} */ constructor(value) { this.value = value; } /** * Access the number value. * * @method * @return {number} returns the wrapped double number. */ valueOf() { return this.value; } /** * @ignore */ toJSON() { return this.value; } /** * @ignore */ toExtendedJSON(options) { if (options && options.relaxed && isFinite(this.value)) return this.value; return { $numberDouble: this.value.toString() }; } /** * @ignore */ static fromExtendedJSON(doc, options) { return options && options.relaxed ? parseFloat(doc.$numberDouble) : new Double(parseFloat(doc.$numberDouble)); } } Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); module.exports = Double;
TamataOcean/TamataSpiru
node_modules/bson/lib/double.js
JavaScript
gpl-3.0
993
/* * Copyright (C) 2013-2014 Dominik Schürmann <dominik@dominikschuermann.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.sufficientlysecure.keychain.ui.adapter; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.keyimport.ImportKeysListEntry; import org.sufficientlysecure.keychain.pgp.KeyRing; import org.sufficientlysecure.keychain.ui.util.FormattingUtils; import org.sufficientlysecure.keychain.ui.util.Highlighter; import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils; import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils.State; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; public class ImportKeysAdapter extends ArrayAdapter<ImportKeysListEntry> { protected LayoutInflater mInflater; protected Activity mActivity; protected List<ImportKeysListEntry> mData; static class ViewHolder { public TextView mainUserId; public TextView mainUserIdRest; public TextView keyId; public TextView fingerprint; public TextView algorithm; public ImageView status; public View userIdsDivider; public LinearLayout userIdsList; public CheckBox checkBox; } public ImportKeysAdapter(Activity activity) { super(activity, -1); mActivity = activity; mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void setData(List<ImportKeysListEntry> data) { clear(); if (data != null) { this.mData = data; // add data to extended ArrayAdapter if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { addAll(data); } else { for (ImportKeysListEntry entry : data) { add(entry); } } } } public List<ImportKeysListEntry> getData() { return mData; } /** This method returns a list of all selected entries, with public keys sorted * before secret keys, see ImportExportOperation for specifics. * @see org.sufficientlysecure.keychain.operations.ImportExportOperation */ public ArrayList<ImportKeysListEntry> getSelectedEntries() { ArrayList<ImportKeysListEntry> result = new ArrayList<>(); ArrayList<ImportKeysListEntry> secrets = new ArrayList<>(); if (mData == null) { return result; } for (ImportKeysListEntry entry : mData) { if (entry.isSelected()) { // add this entry to either the secret or the public list (entry.isSecretKey() ? secrets : result).add(entry); } } // add secret keys at the end of the list result.addAll(secrets); return result; } @Override public boolean hasStableIds() { return true; } public View getView(int position, View convertView, ViewGroup parent) { ImportKeysListEntry entry = mData.get(position); Highlighter highlighter = new Highlighter(mActivity, entry.getQuery()); ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.import_keys_list_item, null); holder.mainUserId = (TextView) convertView.findViewById(R.id.import_item_user_id); holder.mainUserIdRest = (TextView) convertView.findViewById(R.id.import_item_user_id_email); holder.keyId = (TextView) convertView.findViewById(R.id.import_item_key_id); holder.fingerprint = (TextView) convertView.findViewById(R.id.import_item_fingerprint); holder.algorithm = (TextView) convertView.findViewById(R.id.import_item_algorithm); holder.status = (ImageView) convertView.findViewById(R.id.import_item_status); holder.userIdsDivider = convertView.findViewById(R.id.import_item_status_divider); holder.userIdsList = (LinearLayout) convertView.findViewById(R.id.import_item_user_ids_list); holder.checkBox = (CheckBox) convertView.findViewById(R.id.import_item_selected); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // main user id String userId = entry.getUserIds().get(0); KeyRing.UserId userIdSplit = KeyRing.splitUserId(userId); // name if (userIdSplit.name != null) { // show red user id if it is a secret key if (entry.isSecretKey()) { holder.mainUserId.setText(mActivity.getString(R.string.secret_key) + " " + userIdSplit.name); } else { holder.mainUserId.setText(highlighter.highlight(userIdSplit.name)); } } else { holder.mainUserId.setText(R.string.user_id_no_name); } // email if (userIdSplit.email != null) { holder.mainUserIdRest.setVisibility(View.VISIBLE); holder.mainUserIdRest.setText(highlighter.highlight(userIdSplit.email)); } else { holder.mainUserIdRest.setVisibility(View.GONE); } holder.keyId.setText(KeyFormattingUtils.beautifyKeyIdWithPrefix(getContext(), entry.getKeyIdHex())); // don't show full fingerprint on key import holder.fingerprint.setVisibility(View.GONE); if (entry.getAlgorithm() != null) { holder.algorithm.setText(entry.getAlgorithm()); holder.algorithm.setVisibility(View.VISIBLE); } else { holder.algorithm.setVisibility(View.GONE); } if (entry.isRevoked()) { KeyFormattingUtils.setStatusImage(getContext(), holder.status, null, State.REVOKED, R.color.bg_gray); } else if (entry.isExpired()) { KeyFormattingUtils.setStatusImage(getContext(), holder.status, null, State.EXPIRED, R.color.bg_gray); } if (entry.isRevoked() || entry.isExpired()) { holder.status.setVisibility(View.VISIBLE); // no more space for algorithm display holder.algorithm.setVisibility(View.GONE); holder.mainUserId.setTextColor(getContext().getResources().getColor(R.color.bg_gray)); holder.mainUserIdRest.setTextColor(getContext().getResources().getColor(R.color.bg_gray)); holder.keyId.setTextColor(getContext().getResources().getColor(R.color.bg_gray)); } else { holder.status.setVisibility(View.GONE); holder.algorithm.setVisibility(View.VISIBLE); if (entry.isSecretKey()) { holder.mainUserId.setTextColor(Color.RED); } else { holder.mainUserId.setTextColor(Color.WHITE); } holder.mainUserIdRest.setTextColor(Color.WHITE); holder.keyId.setTextColor(Color.WHITE); } if (entry.getUserIds().size() == 1) { holder.userIdsList.setVisibility(View.GONE); holder.userIdsDivider.setVisibility(View.GONE); } else { holder.userIdsList.setVisibility(View.VISIBLE); holder.userIdsDivider.setVisibility(View.VISIBLE); // destroyLoader view from holder holder.userIdsList.removeAllViews(); // we want conventional gpg UserIDs first, then Keybase ”proofs” HashMap<String, HashSet<String>> mergedUserIds = entry.getMergedUserIds(); ArrayList<Map.Entry<String, HashSet<String>>> sortedIds = new ArrayList<Map.Entry<String, HashSet<String>>>(mergedUserIds.entrySet()); java.util.Collections.sort(sortedIds, new java.util.Comparator<Map.Entry<String, HashSet<String>>>() { @Override public int compare(Map.Entry<String, HashSet<String>> entry1, Map.Entry<String, HashSet<String>> entry2) { // sort keybase UserIds after non-Keybase boolean e1IsKeybase = entry1.getKey().contains(":"); boolean e2IsKeybase = entry2.getKey().contains(":"); if (e1IsKeybase != e2IsKeybase) { return (e1IsKeybase) ? 1 : -1; } return entry1.getKey().compareTo(entry2.getKey()); } }); for (Map.Entry<String, HashSet<String>> pair : sortedIds) { String cUserId = pair.getKey(); HashSet<String> cEmails = pair.getValue(); TextView uidView = (TextView) mInflater.inflate( R.layout.import_keys_list_entry_user_id, null); uidView.setText(highlighter.highlight(cUserId)); uidView.setPadding(0, 0, FormattingUtils.dpToPx(getContext(), 8), 0); if (entry.isRevoked() || entry.isExpired()) { uidView.setTextColor(getContext().getResources().getColor(R.color.bg_gray)); } else { uidView.setTextColor(getContext().getResources().getColor(R.color.black)); } holder.userIdsList.addView(uidView); for (String email : cEmails) { TextView emailView = (TextView) mInflater.inflate( R.layout.import_keys_list_entry_user_id, null); emailView.setPadding( FormattingUtils.dpToPx(getContext(), 16), 0, FormattingUtils.dpToPx(getContext(), 8), 0); emailView.setText(highlighter.highlight(email)); if (entry.isRevoked() || entry.isExpired()) { emailView.setTextColor(getContext().getResources().getColor(R.color.bg_gray)); } else { emailView.setTextColor(getContext().getResources().getColor(R.color.black)); } holder.userIdsList.addView(emailView); } } } holder.checkBox.setChecked(entry.isSelected()); return convertView; } }
bresalio/apg
OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java
Java
gpl-3.0
11,323
package engine.gameScene; import engine.gameController.GameController; import engine.gameScene.url.Url; import java.io.IOException; import java.net.URL; import java.util.Collection; import javafx.fxml.FXMLLoader; import javafx.geometry.Pos; import javafx.scene.CacheHint; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Button; import javafx.scene.control.ToolBar; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import static javafx.scene.input.KeyCode.E; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import javafx.scene.layout.StackPane; import javafx.stage.Stage; /** * * @author Saeed */ public class SceneBuilder { /** * change stage to full screen * @param stage Game Stage * @return Stage */ public static Stage setFullScreen(Stage stage){ stage.setFullScreen(true); stage.setResizable(true); stage.setFullScreenExitHint(""); stage.setTitle("Stupid Warriors V1.0"); stage.getIcons().add(new Image(Url.ICON)); return stage ; } /** * * @param url url needed to create a fxmlLoader * @param obj controller to set in fxml loader * @return return Parent to add to scene * @throws IOException */ public static Parent setFxmlLoader(URL url, Object obj) throws IOException{ FXMLLoader fxmlLoader = new FXMLLoader(url); fxmlLoader.setController(obj); return fxmlLoader.load(); } public static ToolBar createGameToolBar(ToolBar toolbar){ Region spacer = new Region(); spacer.getStyleClass().setAll("spacer"); HBox buttonBar = new HBox(); buttonBar.getStyleClass().setAll("segmented-button-bar"); Button sampleButton = new Button("Tasks"); sampleButton.getStyleClass().addAll("first"); Button sampleButton2 = new Button("Administrator"); Button sampleButton3 = new Button("Search"); Button sampleButton4 = new Button("Line"); Button sampleButton5 = new Button("Process"); sampleButton5.getStyleClass().addAll("last", "capsule"); buttonBar.getChildren().addAll(sampleButton, sampleButton2, sampleButton3, sampleButton4, sampleButton5); toolbar.getItems().addAll(spacer, buttonBar); return toolbar; } public static void createTableBoardRight(ImageView scoutTower, ImageView hammerHeadTower, ImageView bulletTower, ImageView teamUpgrade2, ImageView teamUpgrade3, ImageView teamUpgrade, StackPane mainStack) { //add to stack mainStack.getChildren().addAll(scoutTower,hammerHeadTower,bulletTower,teamUpgrade,teamUpgrade2,teamUpgrade3); //set position StackPane.setAlignment(scoutTower, Pos.BOTTOM_RIGHT); StackPane.setAlignment(hammerHeadTower, Pos.BOTTOM_RIGHT); StackPane.setAlignment(bulletTower, Pos.BOTTOM_RIGHT); StackPane.setAlignment(teamUpgrade, Pos.BOTTOM_RIGHT); StackPane.setAlignment(teamUpgrade2, Pos.BOTTOM_RIGHT); StackPane.setAlignment(teamUpgrade3, Pos.BOTTOM_RIGHT); //set translate x,y scoutTower.setTranslateX(-10); scoutTower.setTranslateY(-80); hammerHeadTower.setTranslateX(-200); hammerHeadTower.setTranslateY(-90); bulletTower.setTranslateX(-100); bulletTower.setTranslateY(-80); teamUpgrade.setTranslateX(-10); teamUpgrade.setTranslateY(-10); teamUpgrade2.setTranslateX(-200); teamUpgrade2.setTranslateY(-10); teamUpgrade3.setTranslateX(-100); teamUpgrade3.setTranslateY(-10); } public static void createTableBoardLeftSoldier(ImageView infantrySoldier, ImageView tankSoldier, StackPane mainStack) { StackPane.setAlignment(infantrySoldier, Pos.BOTTOM_LEFT); StackPane.setAlignment(tankSoldier, Pos.BOTTOM_LEFT); double x = 40; double y = -50; double imgX = infantrySoldier.getImage().getWidth(); infantrySoldier.setTranslateX(x); infantrySoldier.setTranslateY(y); tankSoldier.setTranslateX(x+imgX+30); tankSoldier.setTranslateY(y); mainStack.getChildren().addAll(infantrySoldier,tankSoldier); } public static void createTableBoarderLeftTower(ImageView towerAutoRepair, ImageView towerPowerUpgrade, ImageView towerRangeUpgrade, ImageView towerReloadUpgrade,StackPane mainStack) { StackPane.setAlignment(towerReloadUpgrade, Pos.BOTTOM_LEFT); StackPane.setAlignment(towerPowerUpgrade, Pos.BOTTOM_LEFT); StackPane.setAlignment(towerRangeUpgrade, Pos.BOTTOM_LEFT); StackPane.setAlignment(towerAutoRepair, Pos.BOTTOM_LEFT); //posotion double x = 20; double y = -78; double imgX = towerRangeUpgrade.getImage().getWidth(); towerPowerUpgrade.setTranslateX(x); towerPowerUpgrade.setTranslateY(y); towerRangeUpgrade.setTranslateX(imgX+x+10); towerRangeUpgrade.setTranslateY(y); towerReloadUpgrade.setTranslateX(imgX*2+x+20); towerReloadUpgrade.setTranslateY(y); towerAutoRepair.setTranslateX(120); towerAutoRepair.setTranslateY(-10); //tooltip mainStack.getChildren().addAll(towerAutoRepair,towerPowerUpgrade,towerRangeUpgrade,towerReloadUpgrade); } public static void createTableBoardLeftMap(StackPane mainStack) { } }
smasoumi/stupidwarriors
src/engine/gameScene/SceneBuilder.java
Java
gpl-3.0
5,638
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Measure * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * Implement needed classes */ // require_once 'Zend/Measure/Abstract.php'; // require_once 'Zend/Locale.php'; /** * Class for handling capacitance conversions * * @category Zend * @package Zend_Measure * @subpackage Zend_Measure_Capacitance * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Measure_Capacitance extends Zend_Measure_Abstract { const STANDARD = 'FARAD'; const ABFARAD = 'ABFARAD'; const AMPERE_PER_SECOND_VOLT = 'AMPERE_PER_SECOND_VOLT'; const CENTIFARAD = 'CENTIFARAD'; const COULOMB_PER_VOLT = 'COULOMB_PER_VOLT'; const DECIFARAD = 'DECIFARAD'; const DEKAFARAD = 'DEKAFARAD'; const ELECTROMAGNETIC_UNIT = 'ELECTROMAGNETIC_UNIT'; const ELECTROSTATIC_UNIT = 'ELECTROSTATIC_UNIT'; const FARAD = 'FARAD'; const FARAD_INTERNATIONAL = 'FARAD_INTERNATIONAL'; const GAUSSIAN = 'GAUSSIAN'; const GIGAFARAD = 'GIGAFARAD'; const HECTOFARAD = 'HECTOFARAD'; const JAR = 'JAR'; const KILOFARAD = 'KILOFARAD'; const MEGAFARAD = 'MEGAFARAD'; const MICROFARAD = 'MICROFARAD'; const MILLIFARAD = 'MILLIFARAD'; const NANOFARAD = 'NANOFARAD'; const PICOFARAD = 'PICOFARAD'; const PUFF = 'PUFF'; const SECOND_PER_OHM = 'SECOND_PER_OHM'; const STATFARAD = 'STATFARAD'; const TERAFARAD = 'TERAFARAD'; /** * Calculations for all capacitance units * * @var array */ protected $_units = array( 'ABFARAD' => array('1.0e+9', 'abfarad'), 'AMPERE_PER_SECOND_VOLT' => array('1', 'A/sV'), 'CENTIFARAD' => array('0.01', 'cF'), 'COULOMB_PER_VOLT' => array('1', 'C/V'), 'DECIFARAD' => array('0.1', 'dF'), 'DEKAFARAD' => array('10', 'daF'), 'ELECTROMAGNETIC_UNIT' => array('1.0e+9', 'capacity emu'), 'ELECTROSTATIC_UNIT' => array('1.11265e-12', 'capacity esu'), 'FARAD' => array('1', 'F'), 'FARAD_INTERNATIONAL' => array('0.99951', 'F'), 'GAUSSIAN' => array('1.11265e-12', 'G'), 'GIGAFARAD' => array('1.0e+9', 'GF'), 'HECTOFARAD' => array('100', 'hF'), 'JAR' => array('1.11265e-9', 'jar'), 'KILOFARAD' => array('1000', 'kF'), 'MEGAFARAD' => array('1000000', 'MF'), 'MICROFARAD' => array('0.000001', 'µF'), 'MILLIFARAD' => array('0.001', 'mF'), 'NANOFARAD' => array('1.0e-9', 'nF'), 'PICOFARAD' => array('1.0e-12', 'pF'), 'PUFF' => array('1.0e-12', 'pF'), 'SECOND_PER_OHM' => array('1', 's/Ohm'), 'STATFARAD' => array('1.11265e-12', 'statfarad'), 'TERAFARAD' => array('1.0e+12', 'TF'), 'STANDARD' => 'FARAD' ); }
boydjd/openfisma
library/Zend/Measure/Capacitance.php
PHP
gpl-3.0
4,107
/// <reference path = "EscenaActividad.ts" /> /// <reference path = "../../dependencias/pilasweb.d.ts"/> /// <reference path = "../actores/Cuadricula.ts"/> /// <reference path = "../actores/PerroCohete.ts"/> /// <reference path = "../comportamientos/MovimientosEnCuadricula.ts"/> /** * @class TresNaranjas * */ class TresNaranjas extends EscenaActividad { fondo; automata; cuadricula; objetos = []; iniciar() { this.fondo = new Fondo('fondo.tresNaranjas.png',0,0); this.cuadricula = new Cuadricula(0,0,1,4, {separacionEntreCasillas: 5}, {grilla: 'casilla.tresNaranjas.png', ancho:100,alto:100}); //se cargan los Naranjas var hayAlMenosUno = false; for(var i = 0; i < 3; i++) { if (Math.random() < .5) { hayAlMenosUno = true; this.agregarNaranja(i+1); } } if (!hayAlMenosUno) { var columna = 1; var rand = Math.random() if (rand> 0.33 && rand<0.66) { columna = 2; } else if (rand > 0.66) { columna = 3 } this.agregarNaranja(columna); } // se crea el personaje this.automata = new MarcianoAnimado(0,0); this.cuadricula.agregarActor(this.automata,0,0); } agregarNaranja(columna) { var objeto = new NaranjaAnimada(0,0); this.cuadricula.agregarActor(objeto,0,columna); this.objetos.push(objeto); } estaResueltoElProblema(){ return this.contarActoresConEtiqueta('NaranjaAnimada')==0 && this.automata.estaEnCasilla(null,3); } }
bit0Ar/pilas-bloques
releases/pilas-engine-bloques-linux-ia32/resources/app/ejerciciosPilas/src/escenas/TresNaranjas.ts
TypeScript
gpl-3.0
1,676
/* * Copyright (C) 2015-2016 Willi Ye <williye97@gmail.com> * * This file is part of Kernel Adiutor. * * Kernel Adiutor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Kernel Adiutor 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 Kernel Adiutor. If not, see <http://www.gnu.org/licenses/>. * */ package com.grarak.kerneladiutor.activities; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.AppBarLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatDelegate; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Window; import android.view.WindowManager; import com.grarak.kerneladiutor.R; import com.grarak.kerneladiutor.utils.Prefs; import com.grarak.kerneladiutor.utils.Utils; import com.grarak.kerneladiutor.utils.ViewUtils; import java.util.HashMap; /** * Created by willi on 14.04.16. */ public class BaseActivity extends AppCompatActivity { private static HashMap<String, Integer> sAccentColors = new HashMap<>(); private static HashMap<String, Integer> sAccentDarkColors = new HashMap<>(); static { sAccentColors.put("red_accent", R.style.Theme_Red); sAccentColors.put("pink_accent", R.style.Theme_Pink); sAccentColors.put("purple_accent", R.style.Theme_Purple); sAccentColors.put("blue_accent", R.style.Theme_Blue); sAccentColors.put("green_accent", R.style.Theme_Green); sAccentColors.put("orange_accent", R.style.Theme_Orange); sAccentColors.put("brown_accent", R.style.Theme_Brown); sAccentColors.put("grey_accent", R.style.Theme_Grey); sAccentColors.put("blue_grey_accent", R.style.Theme_BlueGrey); sAccentColors.put("teal_accent", R.style.Theme_Teal); sAccentDarkColors.put("red_accent", R.style.Theme_Red_Dark); sAccentDarkColors.put("pink_accent", R.style.Theme_Pink_Dark); sAccentDarkColors.put("purple_accent", R.style.Theme_Purple_Dark); sAccentDarkColors.put("blue_accent", R.style.Theme_Blue_Dark); sAccentDarkColors.put("green_accent", R.style.Theme_Green_Dark); sAccentDarkColors.put("orange_accent", R.style.Theme_Orange_Dark); sAccentDarkColors.put("brown_accent", R.style.Theme_Brown_Dark); sAccentDarkColors.put("grey_accent", R.style.Theme_Grey_Dark); sAccentDarkColors.put("blue_grey_accent", R.style.Theme_BlueGrey_Dark); sAccentDarkColors.put("teal_accent", R.style.Theme_Teal_Dark); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); Utils.DARK_THEME = Prefs.getBoolean("darktheme", false, this); int theme; String accent = Prefs.getString("accent_color", "pink_accent", this); if (Utils.DARK_THEME) { theme = sAccentDarkColors.get(accent); AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); } else { theme = sAccentColors.get(accent); AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); } setTheme(theme); super.onCreate(savedInstanceState); if (Prefs.getBoolean("forceenglish", false, this)) { Utils.setLocale("en_US", this); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && setStatusBarColor()) { Window window = getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(statusBarColor()); } } public AppBarLayout getAppBarLayout() { return (AppBarLayout) findViewById(R.id.appbarlayout); } public Toolbar getToolBar() { return (Toolbar) findViewById(R.id.toolbar); } public void initToolBar() { Toolbar toolbar = getToolBar(); if (toolbar != null) { setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } protected boolean setStatusBarColor() { return true; } protected int statusBarColor() { return ViewUtils.getColorPrimaryDarkColor(this); } }
randomstuffpaul/KernelAdiutor
app/src/main/java/com/grarak/kerneladiutor/activities/BaseActivity.java
Java
gpl-3.0
5,069
/* * Copyright (C) 2007-2017 Crafter Software Corporation. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.craftercms.commons.logging; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used to indicate that a method (or all methods of a class, if used in a class) should be logged. * * @author avasquez */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Logged { }
dejan-brkic/commons
utilities/src/main/java/org/craftercms/commons/logging/Logged.java
Java
gpl-3.0
1,171
using System; using AutoMapper; using Machete.Web.Helpers; using static Machete.Web.Helpers.Extensions; namespace Machete.Web.Maps { public class WorkerSigninProfile : Profile { public WorkerSigninProfile() { CreateMap<Domain.WorkerSignin, Service.DTO.WorkerSigninList>() .ForMember(v => v.englishlevel, opt => opt.MapFrom(d => d == null ? 0 : d.worker.englishlevelID)) .ForMember(v => v.waid, opt => opt.MapFrom(d => d.WorkAssignmentID)) .ForMember(v => v.skill1, opt => opt.MapFrom(d => d == null ? null : d.worker.skill1)) .ForMember(v => v.skill2, opt => opt.MapFrom(d => d == null ? null : d.worker.skill2)) .ForMember(v => v.skill3, opt => opt.MapFrom(d => d == null ? null : d.worker.skill3)) .ForMember(v => v.program, opt => opt.MapFrom(d => d.worker.typeOfWork)) .ForMember(v => v.skillCodes, opt => opt.MapFrom(d => d.worker.skillCodes)) .ForMember(v => v.lotterySequence, opt => opt.MapFrom(d => d.lottery_sequence)) .ForMember(v => v.fullname, opt => opt.MapFrom(d => $"{d.worker.Person.firstname1} {d.worker.Person.firstname2} {d.worker.Person.lastname1} {d.worker.Person.lastname2}") ) .ForMember(v => v.firstname1, opt => opt.MapFrom(d => d.worker.Person.firstname1)) .ForMember(v => v.firstname2, opt => opt.MapFrom(d => d.worker.Person.firstname2)) .ForMember(v => v.lastname1, opt => opt.MapFrom(d => d.worker.Person.lastname1)) .ForMember(v => v.lastname2, opt => opt.MapFrom(d => d.worker.Person.lastname2)) .ForMember(v => v.expirationDate, opt => opt.MapFrom(d => d.worker.memberexpirationdate)) .ForMember(v => v.memberStatusID, opt => opt.MapFrom(d => d.worker.memberStatusID)) .ForMember(v => v.memberStatusEN, opt => opt.MapFrom(d => d.worker.memberStatusEN)) .ForMember(v => v.memberStatusES, opt => opt.MapFrom(d => d.worker.memberStatusES)) .ForMember(v => v.memberExpired, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iExpired)) .ForMember(v => v.memberInactive, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iInactive)) .ForMember(v => v.memberSanctioned, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iSanctioned)) .ForMember(v => v.memberExpelled, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iExpelled)) .ForMember(v => v.imageRef, opt => opt.MapFrom(d => d.worker.ImageID == null ? "/Content/images/NO-IMAGE-AVAILABLE.jpg" : "/Image/GetImage/" + d.worker.ImageID)) .ForMember(v => v.imageID, opt => opt.MapFrom(d => d.worker.ImageID)) .ForMember(v => v.typeOfWorkID, opt => opt.MapFrom(d => d.worker.typeOfWorkID)) .ForMember(v => v.signinID, opt => opt.MapFrom(d => d.ID)) ; CreateMap<Domain.WorkerSignin, ViewModel.WorkerSignin>() .ForMember(v => v.memberExpired, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iExpired)) .ForMember(v => v.memberInactive, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iInactive)) .ForMember(v => v.memberSanctioned, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iSanctioned)) .ForMember(v => v.memberExpelled, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iExpelled)) .ForMember(v => v.imageRef, opt => opt.MapFrom(d => d.worker.ImageID == null ? "/Content/images/NO-IMAGE-AVAILABLE.jpg" : "/Image/GetImage/" + d.worker.ImageID)) .ForMember(v => v.message, opt => opt.MapFrom(src => "success")) .ForMember(v => v.worker, opt => opt.Ignore()) .ForMember(v => v.def, opt => opt.Ignore()) .ForMember(v => v.idString, opt => opt.Ignore()) .ForMember(v => v.tabref, opt => opt.Ignore()) .ForMember(v => v.tablabel, opt => opt.Ignore()) ; CreateMap<Service.DTO.WorkerSigninList, ViewModel.WorkerSigninList>() .ForMember(v => v.recordid, opt => opt.MapFrom(d => d.ID)) .ForMember(v => v.WSIID, opt => opt.MapFrom(d => d.ID)) .ForMember(v => v.expirationDate, opt => opt.MapFrom(d => d.expirationDate.ToShortDateString())) .ForMember(v => v.memberStatus, opt => opt.MapFrom(d => getCI() == "ES" ? d.memberStatusES : d.memberStatusEN)) .ForMember(v => v.dateforsignin, opt => opt.MapFrom(d => d.dateforsignin)) .ForMember(v => v.dateforsigninstring, opt => opt.MapFrom(d => d.dateforsignin.UtcToClientString("hh:mm:ss tt")) ) ; } } }
SavageLearning/Machete
Machete.Web/Maps/Legacy/WorkerSigninProfile.cs
C#
gpl-3.0
5,028
<?php /** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Quote\Model\GuestCartManagement\Plugin; use Magento\Framework\Exception\StateException; class Authorization { /** * @var \Magento\Authorization\Model\UserContextInterface */ protected $userContext; /** * @param \Magento\Authorization\Model\UserContextInterface $userContext */ public function __construct( \Magento\Authorization\Model\UserContextInterface $userContext ) { $this->userContext = $userContext; } /** * @param \Magento\Quote\Model\GuestCart\GuestCartManagement $subject * @param string $cartId * @param int $customerId * @param int $storeId * @throws StateException * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function beforeAssignCustomer( \Magento\Quote\Model\GuestCart\GuestCartManagement $subject, $cartId, $customerId, $storeId ) { if ($customerId !== (int)$this->userContext->getUserId()) { throw new StateException( __('Cannot assign customer to the given cart. You don\'t have permission for this operation.') ); } } }
rajmahesh/magento2-master
vendor/magento/module-quote/Model/GuestCartManagement/Plugin/Authorization.php
PHP
gpl-3.0
1,301
package nl.knaw.huygens.timbuctoo.v5.dropwizard.contenttypes; import nl.knaw.huygens.timbuctoo.v5.dropwizard.SupportedExportFormats; import java.util.HashMap; import java.util.Optional; import java.util.Set; import static java.lang.String.format; public class SerializerWriterRegistry implements SupportedExportFormats { private HashMap<String, SerializerWriter> supportedMimeTypes; public SerializerWriterRegistry(SerializerWriter... writers) { supportedMimeTypes = new HashMap<>(); for (SerializerWriter writer : writers) { register(writer); } } @Override public Set<String> getSupportedMimeTypes() { return supportedMimeTypes.keySet(); } private void register(SerializerWriter serializerWriter) { String mimeType = serializerWriter.getMimeType(); SerializerWriter added = supportedMimeTypes.putIfAbsent(mimeType, serializerWriter); if (added != null) { throw new RuntimeException(format("Timbuctoo supports only one serializer writer for '%s'", mimeType)); } } public Optional<SerializerWriter> getBestMatch(String acceptHeader) { return MimeParser.bestMatch(supportedMimeTypes.keySet(), acceptHeader).map(supportedMimeTypes::get); } }
HuygensING/timbuctoo
timbuctoo-instancev4/src/main/java/nl/knaw/huygens/timbuctoo/v5/dropwizard/contenttypes/SerializerWriterRegistry.java
Java
gpl-3.0
1,216
package org.bukkit.craftbukkit.event; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import org.bukkit.event.player.PlayerInteractEvent; public class CraftEventFactory { public static org.bukkit.event.player.PlayerInteractEvent callPlayerInteractEvent(EntityPlayer player, org.bukkit.event.block.Action action, ItemStack stack){ return callPlayerInteractEvent(player, action, 0, 256, 0, 0, stack); } public static org.bukkit.event.player.PlayerInteractEvent callPlayerInteractEvent(EntityPlayer player, org.bukkit.event.block.Action action, int x, int y, int z, int face, ItemStack stack){ return new PlayerInteractEvent(); } }
GotoLink/Battlegear2
src/api/java/org/bukkit/craftbukkit/event/CraftEventFactory.java
Java
gpl-3.0
693
package tsb.examenFinal.util; import java.util.Stack; /** * * Verifica el balanceo de caractertes de apertura y cierre * como [] {} <> */ public abstract class Balance { public static boolean isBalanced(final String str, final char c0, final char c1) { boolean toReturn; if (c0 == c1) { toReturn = isSameBalanced(str, c0); } else { toReturn = isNotSameBalanced(str, c0, c1); } return toReturn; } private static boolean isSameBalanced(final String str, final char c0) { char[] array = str.toCharArray(); int count = 0; for (int i = 0; i < array.length; i++) { char c = array[i]; if (c == c0) { count++; } } int proc = (count / 2) * 2; return (count == proc); } private static boolean isNotSameBalanced(final String str, final char c0, final char c1) { char[] array = str.toCharArray(); Stack<String> stack = new Stack<String>(); for (int i = 0; i < array.length; i++) { char c = array[i]; if (c == c0) { stack.add(String.valueOf(c)); } else if (c == c1) { if (stack.isEmpty() == false && stack.peek().charAt(0) == c0) { stack.pop(); } else { stack.push(String.valueOf(c)); } } } return stack.isEmpty(); } }
javiermatias/jbc-utn-frc
3ro/TSB/final/util/src/tsb/examenFinal/util/Balance.java
Java
gpl-3.0
1,495
/* Scripts for cnprog.com Project Name: Lanai All Rights Resevred 2008. CNPROG.COM */ var lanai = { /** * Finds any <pre><code></code></pre> tags which aren't registered for * pretty printing, adds the appropriate class name and invokes prettify. */ highlightSyntax: function(){ var styled = false; $("pre code").parent().each(function(){ if (!$(this).hasClass('prettyprint')){ $(this).addClass('prettyprint'); styled = true; } }); if (styled){ prettyPrint(); } } }; //todo: clean-up now there is utils:WaitIcon function appendLoader(element) { loading = gettext('loading...') element.append('<img class="ajax-loader" ' + 'src="' + mediaUrl("media/images/indicator.gif") + '" title="' + loading + '" alt="' + loading + '" />'); } function removeLoader() { $("img.ajax-loader").remove(); } function setSubmitButtonDisabled(form, isDisabled) { form.find('input[type="submit"]').attr("disabled", isDisabled); } function enableSubmitButton(form) { setSubmitButtonDisabled(form, false); } function disableSubmitButton(form) { setSubmitButtonDisabled(form, true); } function setupFormValidation(form, validationRules, validationMessages, onSubmitCallback) { enableSubmitButton(form); form.validate({ debug: true, rules: (validationRules ? validationRules : {}), messages: (validationMessages ? validationMessages : {}), errorElement: "span", errorClass: "form-error", errorPlacement: function(error, element) { var span = element.next().find("span.form-error"); if (span.length === 0) { span = element.parent().find("span.form-error"); if (span.length === 0){ //for resizable textarea var element_id = element.attr('id'); span = $('label[for="' + element_id + '"]'); } } span.replaceWith(error); }, submitHandler: function(form_dom) { disableSubmitButton($(form_dom)); if (onSubmitCallback){ onSubmitCallback(); } else{ form_dom.submit(); } } }); } /** * generic tag cleaning function, settings * are from askbot live settings and askbot.const */ var cleanTag = function(tag_name, settings) { var tag_regex = new RegExp(settings['tag_regex']); if (tag_regex.test(tag_name) === false) { throw settings['messages']['wrong_chars'] } var max_length = settings['max_tag_length']; if (tag_name.length > max_length) { throw interpolate( ngettext( 'must be shorter than %(max_chars)s character', 'must be shorter than %(max_chars)s characters', max_length ), {'max_chars': max_length }, true ); } if (settings['force_lowercase_tags']) { return tag_name.toLowerCase(); } else { return tag_name; } }; var validateTagLength = function(value){ var tags = getUniqueWords(value); var are_tags_ok = true; $.each(tags, function(index, value){ if (value.length > askbot['settings']['maxTagLength']){ are_tags_ok = false; } }); return are_tags_ok; }; var validateTagCount = function(value){ var tags = getUniqueWords(value); return (tags.length <= askbot['settings']['maxTagsPerPost']); }; $.validator.addMethod('limit_tag_count', validateTagCount); $.validator.addMethod('limit_tag_length', validateTagLength); var CPValidator = function() { return { getQuestionFormRules : function() { return { tags: { required: askbot['settings']['tagsAreRequired'], maxlength: 105, limit_tag_count: true, limit_tag_length: true }, text: { minlength: askbot['settings']['minQuestionBodyLength'] }, title: { minlength: askbot['settings']['minTitleLength'] } }; }, getQuestionFormMessages: function(){ return { tags: { required: " " + gettext('tags cannot be empty'), maxlength: askbot['messages']['tagLimits'], limit_tag_count: askbot['messages']['maxTagsPerPost'], limit_tag_length: askbot['messages']['maxTagLength'] }, text: { required: " " + gettext('details are required'), minlength: interpolate( ngettext( 'details must have > %s character', 'details must have > %s characters', askbot['settings']['minQuestionBodyLength'] ), [askbot['settings']['minQuestionBodyLength'], ] ) }, title: { required: " " + gettext('enter your question'), minlength: interpolate( ngettext( 'question must have > %s character', 'question must have > %s characters', askbot['settings']['minTitleLength'] ), [askbot['settings']['minTitleLength'], ] ) } }; }, getAnswerFormRules : function(){ return { text: { minlength: askbot['settings']['minAnswerBodyLength'] }, }; }, getAnswerFormMessages: function(){ return { text: { required: " " + gettext('content cannot be empty'), minlength: interpolate( ngettext( 'answer must be > %s character', 'answer must be > %s characters', askbot['settings']['minAnswerBodyLength'] ), [askbot['settings']['minAnswerBodyLength'], ] ) }, } } }; }(); /** * @constructor */ var ThreadUsersDialog = function() { SimpleControl.call(this); this._heading_text = 'Add heading with the setHeadingText()'; }; inherits(ThreadUsersDialog, SimpleControl); ThreadUsersDialog.prototype.setHeadingText = function(text) { this._heading_text = text; }; ThreadUsersDialog.prototype.showUsers = function(html) { this._dialog.setContent(html); this._dialog.show(); }; ThreadUsersDialog.prototype.startShowingUsers = function() { var me = this; var threadId = this._threadId; var url = this._url; $.ajax({ type: 'GET', data: {'thread_id': threadId}, dataType: 'json', url: url, cache: false, success: function(data){ if (data['success'] == true){ me.showUsers(data['html']); } else { showMessage(me.getElement(), data['message'], 'after'); } } }); }; ThreadUsersDialog.prototype.decorate = function(element) { this._element = element; ThreadUsersDialog.superClass_.decorate.call(this, element); this._threadId = element.data('threadId'); this._url = element.data('url'); var dialog = new ModalDialog(); dialog.setRejectButtonText(''); dialog.setAcceptButtonText(gettext('Back to the question')); dialog.setHeadingText(this._heading_text); dialog.setAcceptHandler(function(){ dialog.hide(); }); var dialog_element = dialog.getElement(); $(dialog_element).find('.modal-footer').css('text-align', 'center'); $(document).append(dialog_element); this._dialog = dialog; var me = this; this.setHandler(function(){ me.startShowingUsers(); }); }; /** * @constructor */ var DraftPost = function() { WrappedElement.call(this); }; inherits(DraftPost, WrappedElement); /** * @return {string} */ DraftPost.prototype.getUrl = function() { throw 'Not Implemented'; }; /** * @return {boolean} */ DraftPost.prototype.shouldSave = function() { throw 'Not Implemented'; }; /** * @return {object} data dict */ DraftPost.prototype.getData = function() { throw 'Not Implemented'; }; DraftPost.prototype.backupData = function() { this._old_data = this.getData(); }; DraftPost.prototype.showNotification = function() { var note = $('.editor-status span'); note.hide(); note.html(gettext('draft saved...')); note.fadeIn().delay(3000).fadeOut(); }; DraftPost.prototype.getSaveHandler = function() { var me = this; return function(save_synchronously) { if (me.shouldSave()) { $.ajax({ type: 'POST', cache: false, dataType: 'json', async: save_synchronously ? false : true, url: me.getUrl(), data: me.getData(), success: function(data) { if (data['success'] && !save_synchronously) { me.showNotification(); } me.backupData(); } }); } }; }; DraftPost.prototype.decorate = function(element) { this._element = element; this.assignContentElements(); this.backupData(); setInterval(this.getSaveHandler(), 30000);//auto-save twice a minute var me = this; window.onbeforeunload = function() { var saveHandler = me.getSaveHandler(); saveHandler(true); //var msg = gettext("%s, we've saved your draft, but..."); //return interpolate(msg, [askbot['data']['userName']]); }; }; /** * @contstructor */ var DraftQuestion = function() { DraftPost.call(this); }; inherits(DraftQuestion, DraftPost); DraftQuestion.prototype.getUrl = function() { return askbot['urls']['saveDraftQuestion']; }; DraftQuestion.prototype.shouldSave = function() { var newd = this.getData(); var oldd = this._old_data; return ( newd['title'] !== oldd['title'] || newd['text'] !== oldd['text'] || newd['tagnames'] !== oldd['tagnames'] ); }; DraftQuestion.prototype.getData = function() { return { 'title': this._title_element.val(), 'text': this._text_element.val(), 'tagnames': this._tagnames_element.val() }; }; DraftQuestion.prototype.assignContentElements = function() { this._title_element = $('#id_title'); this._text_element = $('#editor'); this._tagnames_element = $('#id_tags'); }; var DraftAnswer = function() { DraftPost.call(this); }; inherits(DraftAnswer, DraftPost); DraftAnswer.prototype.setThreadId = function(id) { this._threadId = id; }; DraftAnswer.prototype.getUrl = function() { return askbot['urls']['saveDraftAnswer']; }; DraftAnswer.prototype.shouldSave = function() { return this.getData()['text'] !== this._old_data['text']; }; DraftAnswer.prototype.getData = function() { return { 'text': this._textElement.val(), 'thread_id': this._threadId }; }; DraftAnswer.prototype.assignContentElements = function() { this._textElement = $('#editor'); }; /** * @constructor * @extends {SimpleControl} * @param {Comment} comment to upvote */ var CommentVoteButton = function(comment){ SimpleControl.call(this); /** * @param {Comment} */ this._comment = comment; /** * @type {boolean} */ this._voted = false; /** * @type {number} */ this._score = 0; }; inherits(CommentVoteButton, SimpleControl); /** * @param {number} score */ CommentVoteButton.prototype.setScore = function(score){ this._score = score; if (this._element){ this._element.html(score); } }; /** * @param {boolean} voted */ CommentVoteButton.prototype.setVoted = function(voted){ this._voted = voted; if (this._element){ this._element.addClass('upvoted'); } }; CommentVoteButton.prototype.getVoteHandler = function(){ var me = this; var comment = this._comment; return function(){ var voted = me._voted; var post_id = me._comment.getId(); var data = { cancel_vote: voted ? true:false, post_id: post_id }; $.ajax({ type: 'POST', data: data, dataType: 'json', url: askbot['urls']['upvote_comment'], cache: false, success: function(data){ if (data['success'] == true){ me.setScore(data['score']); me.setVoted(true); } else { showMessage(comment.getElement(), data['message'], 'after'); } } }); }; }; CommentVoteButton.prototype.decorate = function(element){ this._element = element; this.setHandler(this.getVoteHandler()); var element = this._element; var comment = this._comment; /* can't call comment.getElement() here due * an issue in the getElement() of comment * so use an "illegal" access to comment._element here */ comment._element.mouseenter(function(){ //outside height may not be known //var height = comment.getElement().height(); //element.height(height); element.addClass('hover'); }); comment._element.mouseleave(function(){ element.removeClass('hover'); }); }; CommentVoteButton.prototype.createDom = function(){ this._element = this.makeElement('div'); if (this._score > 0){ this._element.html(this._score); } this._element.addClass('upvote'); if (this._voted){ this._element.addClass('upvoted'); } this.decorate(this._element); }; /** * legacy Vote class * handles all sorts of vote-like operations */ var Vote = function(){ // All actions are related to a question var questionId; //question slug to build redirect urls var questionSlug; // The object we operate on actually. It can be a question or an answer. var postId; var questionAuthorId; var currentUserId; var answerContainerIdPrefix = 'post-id-'; var voteContainerId = 'vote-buttons'; var imgIdPrefixAccept = 'answer-img-accept-'; var classPrefixFollow= 'button follow'; var classPrefixFollowed= 'button followed'; var imgIdPrefixQuestionVoteup = 'question-img-upvote-'; var imgIdPrefixQuestionVotedown = 'question-img-downvote-'; var imgIdPrefixAnswerVoteup = 'answer-img-upvote-'; var imgIdPrefixAnswerVotedown = 'answer-img-downvote-'; var divIdFavorite = 'favorite-number'; var commentLinkIdPrefix = 'comment-'; var voteNumberClass = "vote-number"; var offensiveIdPrefixQuestionFlag = 'question-offensive-flag-'; var removeOffensiveIdPrefixQuestionFlag = 'question-offensive-remove-flag-'; var removeAllOffensiveIdPrefixQuestionFlag = 'question-offensive-remove-all-flag-'; var offensiveIdPrefixAnswerFlag = 'answer-offensive-flag-'; var removeOffensiveIdPrefixAnswerFlag = 'answer-offensive-remove-flag-'; var removeAllOffensiveIdPrefixAnswerFlag = 'answer-offensive-remove-all-flag-'; var offensiveClassFlag = 'offensive-flag'; var questionControlsId = 'question-controls'; var removeAnswerLinkIdPrefix = 'answer-delete-link-'; var questionSubscribeUpdates = 'question-subscribe-updates'; var questionSubscribeSidebar= 'question-subscribe-sidebar'; var acceptAnonymousMessage = gettext('insufficient privilege'); var acceptOwnAnswerMessage = gettext('cannot pick own answer as best'); var pleaseLogin = " <a href='" + askbot['urls']['user_signin'] + ">" + gettext('please login') + "</a>"; var favoriteAnonymousMessage = gettext('anonymous users cannot follow questions') + pleaseLogin; var subscribeAnonymousMessage = gettext('anonymous users cannot subscribe to questions') + pleaseLogin; var voteAnonymousMessage = gettext('anonymous users cannot vote') + pleaseLogin; //there were a couple of more messages... var offensiveConfirmation = gettext('please confirm offensive'); var removeOffensiveConfirmation = gettext('please confirm removal of offensive flag'); var offensiveAnonymousMessage = gettext('anonymous users cannot flag offensive posts') + pleaseLogin; var removeConfirmation = gettext('confirm delete'); var removeAnonymousMessage = gettext('anonymous users cannot delete/undelete') + pleaseLogin; var recoveredMessage = gettext('post recovered'); var deletedMessage = gettext('post deleted'); var VoteType = { acceptAnswer : 0, questionUpVote : 1, questionDownVote : 2, favorite : 4, answerUpVote: 5, answerDownVote:6, offensiveQuestion : 7, removeOffensiveQuestion : 7.5, removeAllOffensiveQuestion : 7.6, offensiveAnswer:8, removeOffensiveAnswer:8.5, removeAllOffensiveAnswer:8.6, removeQuestion: 9,//deprecate removeAnswer:10,//deprecate questionSubscribeUpdates:11, questionUnsubscribeUpdates:12 }; var getFavoriteButton = function(){ var favoriteButton = 'div.'+ voteContainerId +' a[class="'+ classPrefixFollow +'"]'; favoriteButton += ', div.'+ voteContainerId +' a[class="'+ classPrefixFollowed +'"]'; return $(favoriteButton); }; var getFavoriteNumber = function(){ var favoriteNumber = '#'+ divIdFavorite ; return $(favoriteNumber); }; var getQuestionVoteUpButton = function(){ var questionVoteUpButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixQuestionVoteup +'"]'; return $(questionVoteUpButton); }; var getQuestionVoteDownButton = function(){ var questionVoteDownButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixQuestionVotedown +'"]'; return $(questionVoteDownButton); }; var getAnswerVoteUpButtons = function(){ var answerVoteUpButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAnswerVoteup +'"]'; return $(answerVoteUpButton); }; var getAnswerVoteDownButtons = function(){ var answerVoteDownButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAnswerVotedown +'"]'; return $(answerVoteDownButton); }; var getAnswerVoteUpButton = function(id){ var answerVoteUpButton = 'div.'+ voteContainerId +' div[id="'+ imgIdPrefixAnswerVoteup + id + '"]'; return $(answerVoteUpButton); }; var getAnswerVoteDownButton = function(id){ var answerVoteDownButton = 'div.'+ voteContainerId +' div[id="'+ imgIdPrefixAnswerVotedown + id + '"]'; return $(answerVoteDownButton); }; var getOffensiveQuestionFlag = function(){ var offensiveQuestionFlag = '.question-card span[id^="'+ offensiveIdPrefixQuestionFlag +'"]'; return $(offensiveQuestionFlag); }; var getRemoveOffensiveQuestionFlag = function(){ var removeOffensiveQuestionFlag = '.question-card span[id^="'+ removeOffensiveIdPrefixQuestionFlag +'"]'; return $(removeOffensiveQuestionFlag); }; var getRemoveAllOffensiveQuestionFlag = function(){ var removeAllOffensiveQuestionFlag = '.question-card span[id^="'+ removeAllOffensiveIdPrefixQuestionFlag +'"]'; return $(removeAllOffensiveQuestionFlag); }; var getOffensiveAnswerFlags = function(){ var offensiveQuestionFlag = 'div.answer span[id^="'+ offensiveIdPrefixAnswerFlag +'"]'; return $(offensiveQuestionFlag); }; var getRemoveOffensiveAnswerFlag = function(){ var removeOffensiveAnswerFlag = 'div.answer span[id^="'+ removeOffensiveIdPrefixAnswerFlag +'"]'; return $(removeOffensiveAnswerFlag); }; var getRemoveAllOffensiveAnswerFlag = function(){ var removeAllOffensiveAnswerFlag = 'div.answer span[id^="'+ removeAllOffensiveIdPrefixAnswerFlag +'"]'; return $(removeAllOffensiveAnswerFlag); }; var getquestionSubscribeUpdatesCheckbox = function(){ return $('#' + questionSubscribeUpdates); }; var getquestionSubscribeSidebarCheckbox= function(){ return $('#' + questionSubscribeSidebar); }; var getremoveAnswersLinks = function(){ var removeAnswerLinks = 'div.answer-controls a[id^="'+ removeAnswerLinkIdPrefix +'"]'; return $(removeAnswerLinks); }; var setVoteImage = function(voteType, undo, object){ var flag = undo ? false : true; if (object.hasClass("on")) { object.removeClass("on"); }else{ object.addClass("on"); } if(undo){ if(voteType == VoteType.questionUpVote || voteType == VoteType.questionDownVote){ $(getQuestionVoteUpButton()).removeClass("on"); $(getQuestionVoteDownButton()).removeClass("on"); } else{ $(getAnswerVoteUpButton(postId)).removeClass("on"); $(getAnswerVoteDownButton(postId)).removeClass("on"); } } }; var setVoteNumber = function(object, number){ var voteNumber = object.parent('div.'+ voteContainerId).find('div.'+ voteNumberClass); $(voteNumber).text(number); }; var bindEvents = function(){ // accept answers var acceptedButtons = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAccept +'"]'; $(acceptedButtons).unbind('click').click(function(event){ Vote.accept($(event.target)); }); // set favorite question var favoriteButton = getFavoriteButton(); favoriteButton.unbind('click').click(function(event){ //Vote.favorite($(event.target)); Vote.favorite(favoriteButton); }); // question vote up var questionVoteUpButton = getQuestionVoteUpButton(); questionVoteUpButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.questionUpVote); }); var questionVoteDownButton = getQuestionVoteDownButton(); questionVoteDownButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.questionDownVote); }); var answerVoteUpButton = getAnswerVoteUpButtons(); answerVoteUpButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.answerUpVote); }); var answerVoteDownButton = getAnswerVoteDownButtons(); answerVoteDownButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.answerDownVote); }); getOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveQuestion); }); getRemoveOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveQuestion); }); getRemoveAllOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.remove_all_offensive(this, VoteType.removeAllOffensiveQuestion); }); getOffensiveAnswerFlags().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveAnswer); }); getRemoveOffensiveAnswerFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveAnswer); }); getRemoveAllOffensiveAnswerFlag().unbind('click').click(function(event){ Vote.remove_all_offensive(this, VoteType.removeAllOffensiveAnswer); }); getquestionSubscribeUpdatesCheckbox().unbind('click').click(function(event){ //despeluchar esto if (this.checked){ getquestionSubscribeSidebarCheckbox().attr({'checked': true}); Vote.vote($(event.target), VoteType.questionSubscribeUpdates); } else { getquestionSubscribeSidebarCheckbox().attr({'checked': false}); Vote.vote($(event.target), VoteType.questionUnsubscribeUpdates); } }); getquestionSubscribeSidebarCheckbox().unbind('click').click(function(event){ if (this.checked){ getquestionSubscribeUpdatesCheckbox().attr({'checked': true}); Vote.vote($(event.target), VoteType.questionSubscribeUpdates); } else { getquestionSubscribeUpdatesCheckbox().attr({'checked': false}); Vote.vote($(event.target), VoteType.questionUnsubscribeUpdates); } }); getremoveAnswersLinks().unbind('click').click(function(event){ Vote.remove(this, VoteType.removeAnswer); }); }; var submit = function(object, voteType, callback) { //this function submits votes $.ajax({ type: "POST", cache: false, dataType: "json", url: askbot['urls']['vote_url'], data: { "type": voteType, "postId": postId }, error: handleFail, success: function(data) { callback(object, voteType, data); } }); }; var handleFail = function(xhr, msg){ alert("Callback invoke error: " + msg); }; // callback function for Accept Answer action var callback_accept = function(object, voteType, data){ if(data.allowed == "0" && data.success == "0"){ showMessage(object, acceptAnonymousMessage); } else if(data.allowed == "-1"){ showMessage(object, acceptOwnAnswerMessage); } else if(data.status == "1"){ $("#"+answerContainerIdPrefix+postId).removeClass("accepted-answer"); $("#"+commentLinkIdPrefix+postId).removeClass("comment-link-accepted"); } else if(data.success == "1"){ var answers = ('div[id^="'+answerContainerIdPrefix +'"]'); $(answers).removeClass('accepted-answer'); var commentLinks = ('div[id^="'+answerContainerIdPrefix +'"] div[id^="'+ commentLinkIdPrefix +'"]'); $(commentLinks).removeClass("comment-link-accepted"); $("#"+answerContainerIdPrefix+postId).addClass("accepted-answer"); $("#"+commentLinkIdPrefix+postId).addClass("comment-link-accepted"); } else{ showMessage(object, data.message); } }; var callback_favorite = function(object, voteType, data){ if(data.allowed == "0" && data.success == "0"){ showMessage( object, favoriteAnonymousMessage.replace( '{{QuestionID}}', questionId).replace( '{{questionSlug}}', '' ) ); } else if(data.status == "1"){ var follow_html = gettext('Follow'); object.attr("class", 'button follow'); object.html(follow_html); var fav = getFavoriteNumber(); fav.removeClass("my-favorite-number"); if(data.count === 0){ data.count = ''; fav.text(''); }else{ var fmts = ngettext('%s follower', '%s followers', data.count); fav.text(interpolate(fmts, [data.count])); } } else if(data.success == "1"){ var followed_html = gettext('<div>Following</div><div class="unfollow">Unfollow</div>'); object.html(followed_html); object.attr("class", 'button followed'); var fav = getFavoriteNumber(); var fmts = ngettext('%s follower', '%s followers', data.count); fav.text(interpolate(fmts, [data.count])); fav.addClass("my-favorite-number"); } else{ showMessage(object, data.message); } }; var callback_vote = function(object, voteType, data){ if (data.success == '0'){ showMessage(object, data.message); return; } else { if (data.status == '1'){ setVoteImage(voteType, true, object); } else { setVoteImage(voteType, false, object); } setVoteNumber(object, data.count); if (data.message && data.message.length > 0){ showMessage(object, data.message); } return; } //may need to take a look at this again if (data.status == "1"){ setVoteImage(voteType, true, object); setVoteNumber(object, data.count); } else if (data.success == "1"){ setVoteImage(voteType, false, object); setVoteNumber(object, data.count); if (data.message.length > 0){ showMessage(object, data.message); } } }; var callback_offensive = function(object, voteType, data){ //todo: transfer proper translations of these from i18n.js //to django.po files //_('anonymous users cannot flag offensive posts') + pleaseLogin; if (data.success == "1"){ if(data.count > 0) $(object).children('span[class="darkred"]').text("("+ data.count +")"); else $(object).children('span[class="darkred"]').text(""); // Change the link text and rebind events $(object).find("a.question-flag").html(gettext("remove flag")); var obj_id = $(object).attr("id"); $(object).attr("id", obj_id.replace("flag-", "remove-flag-")); getRemoveOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveQuestion); }); getRemoveOffensiveAnswerFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveAnswer); }); } else { object = $(object); showMessage(object, data.message) } }; var callback_remove_offensive = function(object, voteType, data){ //todo: transfer proper translations of these from i18n.js //to django.po files //_('anonymous users cannot flag offensive posts') + pleaseLogin; if (data.success == "1"){ if(data.count > 0){ $(object).children('span[class="darkred"]').text("("+ data.count +")"); } else{ $(object).children('span[class="darkred"]').text(""); // Remove "remove all flags link" since there are no more flags to remove var remove_all = $(object).siblings('span.offensive-flag[id*="-offensive-remove-all-flag-"]'); $(remove_all).next("span.sep").remove(); $(remove_all).remove(); } // Change the link text and rebind events $(object).find("a.question-flag").html(gettext("flag offensive")); var obj_id = $(object).attr("id"); $(object).attr("id", obj_id.replace("remove-flag-", "flag-")); getOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveQuestion); }); getOffensiveAnswerFlags().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveAnswer); }); } else { object = $(object); showMessage(object, data.message) } }; var callback_remove_all_offensive = function(object, voteType, data){ //todo: transfer proper translations of these from i18n.js //to django.po files //_('anonymous users cannot flag offensive posts') + pleaseLogin; if (data.success == "1"){ if(data.count > 0) $(object).children('span[class="darkred"]').text("("+ data.count +")"); else $(object).children('span[class="darkred"]').text(""); // remove the link. All flags are gone var remove_own = $(object).siblings('span.offensive-flag[id*="-offensive-remove-flag-"]'); $(remove_own).find("a.question-flag").html(gettext("flag offensive")); $(remove_own).attr("id", $(remove_own).attr("id").replace("remove-flag-", "flag-")); $(object).next("span.sep").remove(); $(object).remove(); getOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveQuestion); }); getOffensiveAnswerFlags().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveAnswer); }); } else { object = $(object); showMessage(object, data.message) } }; var callback_remove = function(object, voteType, data){ if (data.success == "1"){ if (removeActionType == 'delete'){ postNode.addClass('deleted'); postRemoveLink.innerHTML = gettext('undelete'); showMessage(object, deletedMessage); } else if (removeActionType == 'undelete') { postNode.removeClass('deleted'); postRemoveLink.innerHTML = gettext('delete'); showMessage(object, recoveredMessage); } } else { showMessage(object, data.message) } }; return { init : function(qId, qSlug, questionAuthor, userId){ questionId = qId; questionSlug = qSlug; questionAuthorId = questionAuthor; currentUserId = '' + userId;//convert to string bindEvents(); }, //accept answer accept: function(object){ postId = object.attr("id").substring(imgIdPrefixAccept.length); submit(object, VoteType.acceptAnswer, callback_accept); }, //mark question as favorite favorite: function(object){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( object, favoriteAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } postId = questionId; submit(object, VoteType.favorite, callback_favorite); }, vote: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE") { if (voteType == VoteType.questionSubscribeUpdates || voteType == VoteType.questionUnsubscribeUpdates){ getquestionSubscribeSidebarCheckbox().removeAttr('checked'); getquestionSubscribeUpdatesCheckbox().removeAttr('checked'); showMessage(object, subscribeAnonymousMessage); } else { showMessage( $(object), voteAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); } return false; } // up and downvote processor if (voteType == VoteType.answerUpVote){ postId = object.attr("id").substring(imgIdPrefixAnswerVoteup.length); } else if (voteType == VoteType.answerDownVote){ postId = object.attr("id").substring(imgIdPrefixAnswerVotedown.length); } else { postId = questionId; } submit(object, voteType, callback_vote); }, //flag offensive offensive: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), offensiveAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } if (confirm(offensiveConfirmation)){ postId = object.id.substr(object.id.lastIndexOf('-') + 1); submit(object, voteType, callback_offensive); } }, //remove flag offensive remove_offensive: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), offensiveAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } if (confirm(removeOffensiveConfirmation)){ postId = object.id.substr(object.id.lastIndexOf('-') + 1); submit(object, voteType, callback_remove_offensive); } }, remove_all_offensive: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), offensiveAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } if (confirm(removeOffensiveConfirmation)){ postId = object.id.substr(object.id.lastIndexOf('-') + 1); submit(object, voteType, callback_remove_all_offensive); } }, //delete question or answer (comments are deleted separately) remove: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), removeAnonymousMessage.replace( '{{QuestionID}}', questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } bits = object.id.split('-'); postId = bits.pop();/* this seems to be used within submit! */ postType = bits.shift(); var do_proceed = false; postNode = $('#post-id-' + postId); postRemoveLink = object; if (postNode.hasClass('deleted')) { removeActionType = 'undelete'; do_proceed = true; } else { removeActionType = 'delete'; do_proceed = confirm(removeConfirmation); } if (do_proceed) { submit($(object), voteType, callback_remove); } } }; } (); var questionRetagger = function(){ var oldTagsHTML = ''; var tagInput = null; var tagsDiv = null; var retagLink = null; var restoreEventHandlers = function(){ $(document).unbind('click'); }; var cancelRetag = function(){ tagsDiv.html(oldTagsHTML); tagsDiv.removeClass('post-retag'); tagsDiv.addClass('post-tags'); restoreEventHandlers(); initRetagger(); }; var drawNewTags = function(new_tags){ tagsDiv.empty(); if (new_tags === ''){ return; } new_tags = new_tags.split(/\s+/); var tags_html = '' $.each(new_tags, function(index, name){ var tag = new Tag(); tag.setName(name); tagsDiv.append(tag.getElement()); }); }; var doRetag = function(){ $.ajax({ type: "POST", url: retagUrl,//todo add this url to askbot['urls'] dataType: "json", data: { tags: getUniqueWords(tagInput.val()).join(' ') }, success: function(json) { if (json['success'] === true){ new_tags = getUniqueWords(json['new_tags']); oldTagsHtml = ''; cancelRetag(); drawNewTags(new_tags.join(' ')); if (json['message']) { notify.show(json['message']); } } else { cancelRetag(); showMessage(tagsDiv, json['message']); } }, error: function(xhr, textStatus, errorThrown) { showMessage(tagsDiv, gettext('sorry, something is not right here')); cancelRetag(); } }); return false; } var setupInputEventHandlers = function(input){ input.keydown(function(e){ if ((e.which && e.which == 27) || (e.keyCode && e.keyCode == 27)){ cancelRetag(); } }); $(document).unbind('click').click(cancelRetag, false); input.click(function(){return false}); }; var createRetagForm = function(old_tags_string){ var div = $('<form method="post"></form>'); tagInput = $('<input id="retag_tags" type="text" autocomplete="off" name="tags" size="30"/>'); //var tagLabel = $('<label for="retag_tags" class="error"></label>'); //populate input var tagAc = new AutoCompleter({ url: askbot['urls']['get_tag_list'], minChars: 1, useCache: true, matchInside: true, maxCacheLength: 100, delay: 10 }); tagAc.decorate(tagInput); tagInput.val(old_tags_string); div.append(tagInput); //div.append(tagLabel); setupInputEventHandlers(tagInput); //button = $('<input type="submit" />'); //button.val(gettext('save tags')); //div.append(button); //setupButtonEventHandlers(button); div.validate({//copy-paste from utils.js rules: { tags: { required: askbot['settings']['tagsAreRequired'], maxlength: askbot['settings']['maxTagsPerPost'] * askbot['settings']['maxTagLength'], limit_tag_count: true, limit_tag_length: true } }, messages: { tags: { required: gettext('tags cannot be empty'), maxlength: askbot['messages']['tagLimits'], limit_tag_count: askbot['messages']['maxTagsPerPost'], limit_tag_length: askbot['messages']['maxTagLength'] } }, submitHandler: doRetag, errorClass: "retag-error" }); return div; }; var getTagsAsString = function(tags_div){ var links = tags_div.find('a'); var tags_str = ''; links.each(function(index, element){ if (index === 0){ //this is pretty bad - we should use Tag.getName() tags_str = $(element).data('tagName'); } else { tags_str += ' ' + $(element).data('tagName'); } }); return tags_str; }; var noopHandler = function(){ tagInput.focus(); return false; }; var deactivateRetagLink = function(){ retagLink.unbind('click').click(noopHandler); retagLink.unbind('keypress').keypress(noopHandler); }; var startRetag = function(){ tagsDiv = $('#question-tags'); oldTagsHTML = tagsDiv.html();//save to restore on cancel var old_tags_string = getTagsAsString(tagsDiv); var retag_form = createRetagForm(old_tags_string); tagsDiv.html(''); tagsDiv.append(retag_form); tagsDiv.removeClass('post-tags'); tagsDiv.addClass('post-retag'); tagInput.focus(); deactivateRetagLink(); return false; }; var setupClickAndEnterHandler = function(element, callback){ element.unbind('click').click(callback); element.unbind('keypress').keypress(function(e){ if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)){ callback(); } }); } var initRetagger = function(){ setupClickAndEnterHandler(retagLink, startRetag); }; return { init: function(){ retagLink = $('#retag'); initRetagger(); } }; }(); /** * @constructor * Controls vor voting for a post */ var VoteControls = function() { WrappedElement.call(this); this._postAuthorId = undefined; this._postId = undefined; }; inherits(VoteControls, WrappedElement); VoteControls.prototype.setPostId = function(postId) { this._postId = postId; }; VoteControls.prototype.getPostId = function() { return this._postId; }; VoteControls.prototype.setPostAuthorId = function(userId) { this._postAuthorId = userId; }; VoteControls.prototype.setSlug = function(slug) { this._slug = slug; }; VoteControls.prototype.setPostType = function(postType) { this._postType = postType; }; VoteControls.prototype.getPostType = function() { return this._postType; }; VoteControls.prototype.clearVotes = function() { this._upvoteButton.removeClass('on'); this._downvoteButton.removeClass('on'); }; VoteControls.prototype.toggleButton = function(button) { if (button.hasClass('on')) { button.removeClass('on'); } else { button.addClass('on'); } }; VoteControls.prototype.toggleVote = function(voteType) { if (voteType === 'upvote') { this.toggleButton(this._upvoteButton); } else { this.toggleButton(this._downvoteButton); } }; VoteControls.prototype.setVoteCount = function(count) { this._voteCount.html(count); }; VoteControls.prototype.updateDisplay = function(voteType, data) { if (data['status'] == '1'){ this.clearVotes(); } else { this.toggleVote(voteType); } this.setVoteCount(data['count']); if (data['message'] && data['message'].length > 0){ showMessage(this._element, data.message); } }; VoteControls.prototype.getAnonymousMessage = function(message) { var pleaseLogin = " <a href='" + askbot['urls']['user_signin'] + ">" + gettext('please login') + "</a>"; message += pleaseLogin; message = message.replace("{{QuestionID}}", this._postId); return message.replace('{{questionSlug}}', this._slug); }; VoteControls.prototype.getVoteHandler = function(voteType) { var me = this; return function() { if (askbot['data']['userIsAuthenticated'] === false) { var message = me.getAnonymousMessage(gettext('anonymous users cannot vote')); showMessage(me.getElement(), message); } else { //this function submits votes var voteMap = { 'question': { 'upvote': 1, 'downvote': 2 }, 'answer': { 'upvote': 5, 'downvote': 6 } }; var legacyVoteType = voteMap[me.getPostType()][voteType]; $.ajax({ type: "POST", cache: false, dataType: "json", url: askbot['urls']['vote_url'], data: { "type": legacyVoteType, "postId": me.getPostId() }, error: function() { showMessage(me.getElement(), gettext('sorry, something is not right here')); }, success: function(data) { if (data['success']) { me.updateDisplay(voteType, data); } else { showMessage(me.getElement(), data['message']); } } }); } }; }; VoteControls.prototype.decorate = function(element) { this._element = element; var upvoteButton = element.find('.upvote'); this._upvoteButton = upvoteButton; setupButtonEventHandlers(upvoteButton, this.getVoteHandler('upvote')); var downvoteButton = element.find('.downvote'); this._downvoteButton = downvoteButton; setupButtonEventHandlers(downvoteButton, this.getVoteHandler('downvote')); this._voteCount = element.find('.vote-number'); }; var DeletePostLink = function(){ SimpleControl.call(this); this._post_id = null; }; inherits(DeletePostLink, SimpleControl); DeletePostLink.prototype.setPostId = function(id){ this._post_id = id; }; DeletePostLink.prototype.getPostId = function(){ return this._post_id; }; DeletePostLink.prototype.getPostElement = function(){ return $('#post-id-' + this.getPostId()); }; DeletePostLink.prototype.isPostDeleted = function(){ return this._post_deleted; }; DeletePostLink.prototype.setPostDeleted = function(is_deleted){ var post = this.getPostElement(); if (is_deleted === true){ post.addClass('deleted'); this._post_deleted = true; this.getElement().html(gettext('undelete')); } else if (is_deleted === false){ post.removeClass('deleted'); this._post_deleted = false; this.getElement().html(gettext('delete')); } }; DeletePostLink.prototype.getDeleteHandler = function(){ var me = this; var post_id = this.getPostId(); return function(){ var data = { 'post_id': me.getPostId(), //todo rename cancel_vote -> undo 'cancel_vote': me.isPostDeleted() ? true: false }; $.ajax({ type: 'POST', data: data, dataType: 'json', url: askbot['urls']['delete_post'], cache: false, success: function(data){ if (data['success'] == true){ me.setPostDeleted(data['is_deleted']); } else { showMessage(me.getElement(), data['message']); } } }); }; }; DeletePostLink.prototype.decorate = function(element){ this._element = element; this._post_deleted = this.getPostElement().hasClass('deleted'); this.setHandler(this.getDeleteHandler()); } /** * Form for editing and posting new comment * supports 3 editors: markdown, tinymce and plain textarea. * There is only one instance of this form in use on the question page. * It can be attached to any comment on the page, or to a new blank * comment. */ var EditCommentForm = function(){ WrappedElement.call(this); this._comment = null; this._comment_widget = null; this._element = null; this._editorReady = false; this._text = ''; }; inherits(EditCommentForm, WrappedElement); EditCommentForm.prototype.setWaitingStatus = function(isWaiting) { if (isWaiting === true) { this._editor.getElement().hide(); this._submit_btn.hide(); this._cancel_btn.hide(); this._minorEditBox.hide(); this._element.hide(); } else { this._element.show(); this._editor.getElement().show(); this._submit_btn.show(); this._cancel_btn.show(); this._minorEditBox.show(); } }; EditCommentForm.prototype.getEditorType = function() { if (askbot['settings']['commentsEditorType'] === 'rich-text') { return askbot['settings']['editorType']; } else { return 'plain-text'; } }; EditCommentForm.prototype.startTinyMCEEditor = function() { var editorId = this.makeId('comment-editor'); var opts = { mode: 'exact', content_css: mediaUrl('media/style/tinymce/comments-content.css'), elements: editorId, plugins: 'autoresize', theme: 'advanced', theme_advanced_toolbar_location: 'top', theme_advanced_toolbar_align: 'left', theme_advanced_buttons1: 'bold, italic, |, link, |, numlist, bullist', theme_advanced_buttons2: '', theme_advanced_path: false, plugins: '', width: '100%', height: '70' }; var editor = new TinyMCE(opts); editor.setId(editorId); editor.setText(this._text); this._editorBox.prepend(editor.getElement()); editor.start(); this._editor = editor; }; EditCommentForm.prototype.startWMDEditor = function() { var editor = new WMD(); editor.setEnabledButtons('bold italic link code ol ul'); editor.setPreviewerEnabled(false); editor.setText(this._text); this._editorBox.prepend(editor.getElement());//attach DOM before start editor.start();//have to start after attaching DOM this._editor = editor; }; EditCommentForm.prototype.startSimpleEditor = function() { this._editor = new SimpleEditor(); this._editorBox.prepend(this._editor.getElement()); }; EditCommentForm.prototype.startEditor = function() { var editorType = this.getEditorType(); if (editorType === 'tinymce') { this.startTinyMCEEditor(); //@todo: implement save on enter and character counter in tinyMCE return; } else if (editorType === 'markdown') { this.startWMDEditor(); } else { this.startSimpleEditor(); } //code below is common to SimpleEditor and WMD var editorElement = this._editor.getElement(); var updateCounter = this.getCounterUpdater(); var escapeHandler = makeKeyHandler(27, this.getCancelHandler()); //todo: try this on the div var editor = this._editor; //this should be set on the textarea! editorElement.blur(updateCounter); editorElement.focus(updateCounter); editorElement.keyup(updateCounter) editorElement.keyup(escapeHandler); if (askbot['settings']['saveCommentOnEnter']){ var save_handler = makeKeyHandler(13, this.getSaveHandler()); editor.getElement().keydown(save_handler); } }; /** * attaches comment editor to a particular comment */ EditCommentForm.prototype.attachTo = function(comment, mode){ this._comment = comment; this._type = mode;//action: 'add' or 'edit' this._comment_widget = comment.getContainerWidget(); this._text = comment.getText(); comment.getElement().after(this.getElement()); comment.getElement().hide(); this._comment_widget.hideButton();//hide add comment button //fix up the comment submit button, depending on the mode if (this._type == 'add'){ this._submit_btn.html(gettext('add comment')); if (this._minorEditBox) { this._minorEditBox.hide(); } } else { this._submit_btn.html(gettext('save comment')); if (this._minorEditBox) { this._minorEditBox.show(); } } //enable the editor this.getElement().show(); this.enableForm(); this.startEditor(); this._editor.setText(this._text); var ed = this._editor var onFocus = function() { ed.putCursorAtEnd(); }; this._editor.focus(onFocus); setupButtonEventHandlers(this._submit_btn, this.getSaveHandler()); setupButtonEventHandlers(this._cancel_btn, this.getCancelHandler()); }; EditCommentForm.prototype.getCounterUpdater = function(){ //returns event handler var counter = this._text_counter; var editor = this._editor; var handler = function(){ var length = editor.getText().length; var length1 = maxCommentLength - 100; if (length1 < 0){ length1 = Math.round(0.7*maxCommentLength); } var length2 = maxCommentLength - 30; if (length2 < 0){ length2 = Math.round(0.9*maxCommentLength); } /* todo make smooth color transition, from gray to red * or rather - from start color to end color */ var color = 'maroon'; var chars = 10; if (length === 0){ var feedback = interpolate(gettext('enter at least %s characters'), [chars]); } else if (length < 10){ var feedback = interpolate(gettext('enter at least %s more characters'), [chars - length]); } else { if (length > length2) { color = '#f00'; } else if (length > length1) { color = '#f60'; } else { color = '#999'; } chars = maxCommentLength - length; var feedback = interpolate(gettext('%s characters left'), [chars]); } counter.html(feedback); counter.css('color', color); return true; }; return handler; }; /** * @todo: clean up this method so it does just one thing */ EditCommentForm.prototype.canCancel = function(){ if (this._element === null){ return true; } if (this._editor === undefined) { return true; }; var ctext = this._editor.getText(); if ($.trim(ctext) == $.trim(this._text)){ return true; } else if (this.confirmAbandon()){ return true; } this._editor.focus(); return false; }; EditCommentForm.prototype.getCancelHandler = function(){ var form = this; return function(evt){ if (form.canCancel()){ form.detach(); evt.preventDefault(); } return false; }; }; EditCommentForm.prototype.detach = function(){ if (this._comment === null){ return; } this._comment.getContainerWidget().showButton(); if (this._comment.isBlank()){ this._comment.dispose(); } else { this._comment.getElement().show(); } this.reset(); this._element = this._element.detach(); this._editor.dispose(); this._editor = undefined; removeButtonEventHandlers(this._submit_btn); removeButtonEventHandlers(this._cancel_btn); }; EditCommentForm.prototype.createDom = function(){ this._element = $('<form></form>'); this._element.attr('class', 'post-comments'); var div = $('<div></div>'); this._element.append(div); /** a stub container for the editor */ this._editorBox = div; /** * editor itself will live at this._editor * and will be initialized by the attachTo() */ this._controlsBox = this.makeElement('div'); this._controlsBox.addClass('edit-comment-buttons'); div.append(this._controlsBox); this._text_counter = $('<span></span>').attr('class', 'counter'); this._controlsBox.append(this._text_counter); this._submit_btn = $('<button class="submit"></button>'); this._controlsBox.append(this._submit_btn); this._cancel_btn = $('<button class="submit"></button>'); this._cancel_btn.html(gettext('cancel')); this._controlsBox.append(this._cancel_btn); //if email alerts are enabled, add a checkbox "suppress_email" if (askbot['settings']['enableEmailAlerts'] === true) { this._minorEditBox = this.makeElement('div'); this._minorEditBox.addClass('checkbox'); this._controlsBox.append(this._minorEditBox); var checkBox = this.makeElement('input'); checkBox.attr('type', 'checkbox'); checkBox.attr('name', 'suppress_email'); this._minorEditBox.append(checkBox); var label = this.makeElement('label'); label.attr('for', 'suppress_email'); label.html(gettext("minor edit (don't send alerts)")); this._minorEditBox.append(label); } }; EditCommentForm.prototype.isEnabled = function() { return (this._submit_btn.attr('disabled') !== 'disabled');//confusing! setters use boolean }; EditCommentForm.prototype.enableForm = function() { this._submit_btn.attr('disabled', false); this._cancel_btn.attr('disabled', false); }; EditCommentForm.prototype.disableForm = function() { this._submit_btn.attr('disabled', true); this._cancel_btn.attr('disabled', true); }; EditCommentForm.prototype.reset = function(){ this._comment = null; this._text = ''; this._editor.setText(''); this.enableForm(); }; EditCommentForm.prototype.confirmAbandon = function(){ this._editor.focus(); this._editor.getElement().scrollTop(); this._editor.setHighlight(true); var answer = confirm( gettext("Are you sure you don't want to post this comment?") ); this._editor.setHighlight(false); return answer; }; EditCommentForm.prototype.getSuppressEmail = function() { return this._element.find('input[name="suppress_email"]').is(':checked'); }; EditCommentForm.prototype.setSuppressEmail = function(bool) { this._element.find('input[name="suppress_email"]').prop('checked', bool); }; EditCommentForm.prototype.getSaveHandler = function(){ var me = this; var editor = this._editor; return function(){ if (me.isEnabled() === false) {//prevent double submits return false; } me.disableForm(); var text = editor.getText(); if (text.length < askbot['settings']['minCommentBodyLength']){ editor.focus(); me.enableForm(); return false; } //display the comment and show that it is not yet saved me.setWaitingStatus(true); me._comment.getElement().show(); var commentData = me._comment.getData(); var timestamp = commentData['comment_added_at'] || gettext('just now'); var userName = commentData['user_display_name'] || askbot['data']['userName']; me._comment.setContent({ 'html': editor.getHtml(), 'text': text, 'user_display_name': userName, 'comment_added_at': timestamp }); me._comment.setDraftStatus(true); me._comment.getContainerWidget().showButton(); var post_data = { comment: text }; if (me._type == 'edit'){ post_data['comment_id'] = me._comment.getId(); post_url = askbot['urls']['editComment']; post_data['suppress_email'] = me.getSuppressEmail(); me.setSuppressEmail(false); } else { post_data['post_type'] = me._comment.getParentType(); post_data['post_id'] = me._comment.getParentId(); post_url = askbot['urls']['postComments']; } $.ajax({ type: "POST", url: post_url, dataType: "json", data: post_data, success: function(json) { //type is 'edit' or 'add' me._comment.setDraftStatus(false); if (me._type == 'add'){ me._comment.dispose(); me._comment.getContainerWidget().reRenderComments(json); } else { me._comment.setContent(json); } me.setWaitingStatus(false); me.detach(); }, error: function(xhr, textStatus, errorThrown) { me._comment.getElement().show(); showMessage(me._comment.getElement(), xhr.responseText, 'after'); me._comment.setDraftStatus(false); me.setWaitingStatus(false); me.detach(); me.enableForm(); } }); return false; }; }; var Comment = function(widget, data){ WrappedElement.call(this); this._container_widget = widget; this._data = data || {}; this._blank = true;//set to false by setContent this._element = null; this._is_convertible = askbot['data']['userIsAdminOrMod']; this.convert_link = null; this._delete_prompt = gettext('delete this comment'); this._editorForm = undefined; if (data && data['is_deletable']){ this._deletable = data['is_deletable']; } else { this._deletable = false; } if (data && data['is_editable']){ this._editable = data['is_deletable']; } else { this._editable = false; } }; inherits(Comment, WrappedElement); Comment.prototype.getData = function() { return this._data; }; Comment.prototype.startEditing = function() { var form = this._editorForm || new EditCommentForm(); this._editorForm = form; // if new comment: if (this.isBlank()) { form.attachTo(this, 'add'); } else { form.attachTo(this, 'edit'); } }; Comment.prototype.decorate = function(element){ this._element = $(element); var parent_type = this._element.parent().parent().attr('id').split('-')[2]; var comment_id = this._element.attr('id').replace('comment-',''); this._data = {id: comment_id}; this._contentBox = this._element.find('.comment-content'); var timestamp = this._element.find('abbr.timeago'); this._data['comment_added_at'] = timestamp.attr('title'); var userLink = this._element.find('a.author'); this._data['user_display_name'] = userLink.html(); // @todo: read other data var commentBody = this._element.find('.comment-body'); if (commentBody.length > 0) { this._comment_body = commentBody; } var delete_img = this._element.find('span.delete-icon'); if (delete_img.length > 0){ this._deletable = true; this._delete_icon = new DeleteIcon(this.deletePrompt); this._delete_icon.setHandler(this.getDeleteHandler()); this._delete_icon.decorate(delete_img); } var edit_link = this._element.find('a.edit'); if (edit_link.length > 0){ this._editable = true; this._edit_link = new EditLink(); this._edit_link.setHandler(this.getEditHandler()); this._edit_link.decorate(edit_link); } var convert_link = this._element.find('form.convert-comment'); if (this._is_convertible){ this._convert_link = new CommentConvertLink(comment_id); this._convert_link.decorate(convert_link); } var deleter = this._element.find('.comment-delete'); if (deleter.length > 0) { this._comment_delete = deleter; }; var vote = new CommentVoteButton(this); vote.decorate(this._element.find('.comment-votes .upvote')); this._blank = false; }; Comment.prototype.setDraftStatus = function(isDraft) { return; //@todo: implement nice feedback about posting in progress //maybe it should be an element that lasts at least a second //to avoid the possible brief flash if (isDraft === true) { this._normalBackground = this._element.css('background'); this._element.css('background', 'rgb(255, 243, 195)'); } else { this._element.css('background', this._normalBackground); } }; Comment.prototype.isBlank = function(){ return this._blank; }; Comment.prototype.getId = function(){ return this._data['id']; }; Comment.prototype.hasContent = function(){ return ('id' in this._data); //shortcut for 'user_url' 'html' 'user_display_name' 'comment_age' }; Comment.prototype.hasText = function(){ return ('text' in this._data); } Comment.prototype.getContainerWidget = function(){ return this._container_widget; }; Comment.prototype.getParentType = function(){ return this._container_widget.getPostType(); }; Comment.prototype.getParentId = function(){ return this._container_widget.getPostId(); }; /** * this function is basically an "updateDom" * for which we don't have the convention */ Comment.prototype.setContent = function(data){ this._data = $.extend(this._data, data); this._element.addClass('comment'); this._element.css('display', 'table');//@warning: hardcoded //display is set to "block" if .show() is called, but we need table. this._element.attr('id', 'comment-' + this._data['id']); // 1) create the votes element if it is not there var votesBox = this._element.find('.comment-votes'); if (votesBox.length === 0) { votesBox = this.makeElement('div'); votesBox.addClass('comment-votes'); this._element.append(votesBox); var vote = new CommentVoteButton(this); if (this._data['upvoted_by_user']){ vote.setVoted(true); } vote.setScore(this._data['score']); var voteElement = vote.getElement(); votesBox.append(vote.getElement()); } // 2) create the comment content container if (this._contentBox === undefined) { var contentBox = this.makeElement('div'); contentBox.addClass('comment-content'); this._contentBox = contentBox; this._element.append(contentBox); } // 2) create the comment deleter if it is not there if (this._comment_delete === undefined) { this._comment_delete = $('<div class="comment-delete"></div>'); if (this._deletable){ this._delete_icon = new DeleteIcon(this._delete_prompt); this._delete_icon.setHandler(this.getDeleteHandler()); this._comment_delete.append(this._delete_icon.getElement()); } this._contentBox.append(this._comment_delete); } // 3) create or replace the comment body if (this._comment_body === undefined) { this._comment_body = $('<div class="comment-body"></div>'); this._contentBox.append(this._comment_body); } if (EditCommentForm.prototype.getEditorType() === 'tinymce') { var theComment = $('<div/>'); theComment.html(this._data['html']); //sanitize, just in case this._comment_body.empty(); this._comment_body.append(theComment); this._data['text'] = this._data['html']; } else { this._comment_body.empty(); this._comment_body.html(this._data['html']); } //this._comment_body.append(' &ndash; '); // 4) create user link if absent if (this._user_link !== undefined) { this._user_link.detach(); this._user_link = undefined; } this._user_link = $('<a></a>').attr('class', 'author'); this._user_link.attr('href', this._data['user_url']); this._user_link.html(this._data['user_display_name']); this._comment_body.append(' '); this._comment_body.append(this._user_link); // 5) create or update the timestamp if (this._comment_added_at !== undefined) { this._comment_added_at.detach(); this._comment_added_at = undefined; } this._comment_body.append(' ('); this._comment_added_at = $('<abbr class="timeago"></abbr>'); this._comment_added_at.html(this._data['comment_added_at']); this._comment_added_at.attr('title', this._data['comment_added_at']); this._comment_added_at.timeago(); this._comment_body.append(this._comment_added_at); this._comment_body.append(')'); if (this._editable) { if (this._edit_link !== undefined) { this._edit_link.dispose(); } this._edit_link = new EditLink(); this._edit_link.setHandler(this.getEditHandler()) this._comment_body.append(this._edit_link.getElement()); } if (this._is_convertible) { if (this._convert_link !== undefined) { this._convert_link.dispose(); } this._convert_link = new CommentConvertLink(this._data['id']); this._comment_body.append(this._convert_link.getElement()); } this._blank = false; }; Comment.prototype.dispose = function(){ if (this._comment_body){ this._comment_body.remove(); } if (this._comment_delete){ this._comment_delete.remove(); } if (this._user_link){ this._user_link.remove(); } if (this._comment_added_at){ this._comment_added_at.remove(); } if (this._delete_icon){ this._delete_icon.dispose(); } if (this._edit_link){ this._edit_link.dispose(); } if (this._convert_link){ this._convert_link.dispose(); } this._data = null; Comment.superClass_.dispose.call(this); }; Comment.prototype.getElement = function(){ Comment.superClass_.getElement.call(this); if (this.isBlank() && this.hasContent()){ this.setContent(); if (askbot['settings']['mathjaxEnabled'] === true){ MathJax.Hub.Queue(['Typeset', MathJax.Hub]); } } return this._element; }; Comment.prototype.loadText = function(on_load_handler){ var me = this; $.ajax({ type: "GET", url: askbot['urls']['getComment'], data: {id: this._data['id']}, success: function(json){ if (json['success']) { me._data['text'] = json['text']; on_load_handler() } else { showMessage(me.getElement(), json['message'], 'after'); } }, error: function(xhr, textStatus, exception) { showMessage(me.getElement(), xhr.responseText, 'after'); } }); }; Comment.prototype.getText = function(){ if (!this.isBlank()){ if ('text' in this._data){ return this._data['text']; } } return ''; } Comment.prototype.getEditHandler = function(){ var me = this; return function(){ if (me.hasText()){ me.startEditing(); } else { me.loadText(function(){ me.startEditing() }); } }; }; Comment.prototype.getDeleteHandler = function(){ var comment = this; var del_icon = this._delete_icon; return function(){ if (confirm(gettext('confirm delete comment'))){ comment.getElement().hide(); $.ajax({ type: 'POST', url: askbot['urls']['deleteComment'], data: { comment_id: comment.getId() }, success: function(json, textStatus, xhr) { comment.dispose(); }, error: function(xhr, textStatus, exception) { comment.getElement().show() showMessage(del_icon.getElement(), xhr.responseText); }, dataType: "json" }); } }; }; var PostCommentsWidget = function(){ WrappedElement.call(this); this._denied = false; }; inherits(PostCommentsWidget, WrappedElement); PostCommentsWidget.prototype.decorate = function(element){ var element = $(element); this._element = element; var widget_id = element.attr('id'); var id_bits = widget_id.split('-'); this._post_id = id_bits[3]; this._post_type = id_bits[2]; this._is_truncated = askbot['data'][widget_id]['truncated']; this._user_can_post = askbot['data'][widget_id]['can_post']; //see if user can comment here var controls = element.find('.controls'); this._activate_button = controls.find('.button'); if (this._user_can_post == false){ setupButtonEventHandlers( this._activate_button, this.getReadOnlyLoadHandler() ); } else { setupButtonEventHandlers( this._activate_button, this.getActivateHandler() ); } this._cbox = element.find('.content'); var comments = new Array(); var me = this; this._cbox.children('.comment').each(function(index, element){ var comment = new Comment(me); comments.push(comment) comment.decorate(element); }); this._comments = comments; }; PostCommentsWidget.prototype.getPostType = function(){ return this._post_type; }; PostCommentsWidget.prototype.getPostId = function(){ return this._post_id; }; PostCommentsWidget.prototype.hideButton = function(){ this._activate_button.hide(); }; PostCommentsWidget.prototype.showButton = function(){ if (this._is_truncated === false){ this._activate_button.html(askbot['messages']['addComment']); } this._activate_button.show(); } PostCommentsWidget.prototype.startNewComment = function(){ var opts = { 'is_deletable': true, 'is_editable': true }; var comment = new Comment(this, opts); this._cbox.append(comment.getElement()); comment.startEditing(); }; PostCommentsWidget.prototype.needToReload = function(){ return this._is_truncated; }; PostCommentsWidget.prototype.userCanPost = function() { var data = askbot['data']; if (data['userIsAuthenticated']) { //true if admin, post owner or high rep user if (data['userIsAdminOrMod']) { return true; } else if (this.getPostId() in data['user_posts']) { return true; } } return false; }; PostCommentsWidget.prototype.getActivateHandler = function(){ var me = this; var button = this._activate_button; return function() { if (me.needToReload()){ me.reloadAllComments(function(json){ me.reRenderComments(json); //2) change button text to "post a comment" button.html(gettext('post a comment')); }); } else { //if user can't post, we tell him something and refuse if (askbot['data']['userIsAuthenticated']) { me.startNewComment(); } else { var message = gettext('please sign in or register to post comments'); showMessage(button, message, 'after'); } } }; }; PostCommentsWidget.prototype.getReadOnlyLoadHandler = function(){ var me = this; return function(){ me.reloadAllComments(function(json){ me.reRenderComments(json); me._activate_button.remove(); }); }; }; PostCommentsWidget.prototype.reloadAllComments = function(callback){ var post_data = {post_id: this._post_id, post_type: this._post_type}; var me = this; $.ajax({ type: "GET", url: askbot['urls']['postComments'], data: post_data, success: function(json){ callback(json); me._is_truncated = false; }, dataType: "json" }); }; PostCommentsWidget.prototype.reRenderComments = function(json){ $.each(this._comments, function(i, item){ item.dispose(); }); this._comments = new Array(); var me = this; $.each(json, function(i, item){ var comment = new Comment(me, item); me._cbox.append(comment.getElement()); me._comments.push(comment); }); }; var socialSharing = function(){ var SERVICE_DATA = { //url - template for the sharing service url, params are for the popup identica: { url: "http://identi.ca/notice/new?status_textarea={TEXT}%20{URL}", params: "width=820, height=526,toolbar=1,status=1,resizable=1,scrollbars=1" }, twitter: { url: "http://twitter.com/share?url={URL}&ref=twitbtn&text={TEXT}", params: "width=820,height=526,toolbar=1,status=1,resizable=1,scrollbars=1" }, facebook: { url: "http://www.facebook.com/sharer.php?u={URL}&ref=fbshare&t={TEXT}", params: "width=630,height=436,toolbar=1,status=1,resizable=1,scrollbars=1" }, linkedin: { url: "http://www.linkedin.com/shareArticle?mini=true&url={URL}&title={TEXT}", params: "width=630,height=436,toolbar=1,status=1,resizable=1,scrollbars=1" } }; var URL = ""; var TEXT = ""; var share_page = function(service_name){ if (SERVICE_DATA[service_name]){ var url = SERVICE_DATA[service_name]['url']; url = url.replace('{TEXT}', TEXT); url = url.replace('{URL}', URL); var params = SERVICE_DATA[service_name]['params']; if(!window.open(url, "sharing", params)){ window.location.href=url; } return false; //@todo: change to some other url shortening service $.ajax({ url: "http://json-tinyurl.appspot.com/?&callback=?", dataType: "json", data: {'url':URL}, success: function(data) { url = url.replace('{URL}', data.tinyurl); }, error: function(xhr, opts, error) { url = url.replace('{URL}', URL); }, complete: function(data) { url = url.replace('{TEXT}', TEXT); var params = SERVICE_DATA[service_name]['params']; if(!window.open(url, "sharing", params)){ window.location.href=url; } } }); } } return { init: function(){ URL = window.location.href; var urlBits = URL.split('/'); URL = urlBits.slice(0, -2).join('/') + '/'; TEXT = encodeURIComponent($('h1 > a').html()); var hashtag = encodeURIComponent( askbot['settings']['sharingSuffixText'] ); TEXT = TEXT.substr(0, 134 - URL.length - hashtag.length); TEXT = TEXT + '... ' + hashtag; var fb = $('a.facebook-share') var tw = $('a.twitter-share'); var ln = $('a.linkedin-share'); var ica = $('a.identica-share'); copyAltToTitle(fb); copyAltToTitle(tw); copyAltToTitle(ln); copyAltToTitle(ica); setupButtonEventHandlers(fb, function(){ share_page("facebook") }); setupButtonEventHandlers(tw, function(){ share_page("twitter") }); setupButtonEventHandlers(ln, function(){ share_page("linkedin") }); setupButtonEventHandlers(ica, function(){ share_page("identica") }); } } }(); /** * @constructor * @extends {SimpleControl} */ var QASwapper = function(){ SimpleControl.call(this); this._ans_id = null; }; inherits(QASwapper, SimpleControl); QASwapper.prototype.decorate = function(element){ this._element = element; this._ans_id = parseInt(element.attr('id').split('-').pop()); var me = this; this.setHandler(function(){ me.startSwapping(); }); }; QASwapper.prototype.startSwapping = function(){ while (true){ var title = prompt(gettext('Please enter question title (>10 characters)')); if (title.length >= 10){ var data = {new_title: title, answer_id: this._ans_id}; $.ajax({ type: "POST", cache: false, dataType: "json", url: askbot['urls']['swap_question_with_answer'], data: data, success: function(data){ window.location.href = data['question_url']; } }); break; } } }; /** * @constructor * An element that encloses an editor and everything inside it. * By default editor is hidden and user sees a box with a prompt * suggesting to make a post. * When user clicks, editor becomes accessible. */ var FoldedEditor = function() { WrappedElement.call(this); }; inherits(FoldedEditor, WrappedElement); FoldedEditor.prototype.getEditor = function() { return this._editor; }; FoldedEditor.prototype.getEditorInputId = function() { return this._element.find('textarea').attr('id'); }; FoldedEditor.prototype.onAfterOpenHandler = function() { var editor = this.getEditor(); if (editor) { setTimeout(function() {editor.focus()}, 500); } }; FoldedEditor.prototype.getOpenHandler = function() { var editorBox = this._editorBox; var promptBox = this._prompt; var externalTrigger = this._externalTrigger; var me = this; return function() { promptBox.hide(); editorBox.show(); var element = me.getElement(); element.addClass('unfolded'); /* make the editor one shot - once it unfolds it's * not accepting any events */ element.unbind('click'); element.unbind('focus'); /* this function will open the editor * and focus cursor on the editor */ me.onAfterOpenHandler(); /* external trigger is a clickable target * placed outside of the this._element * that will cause the editor to unfold */ if (externalTrigger) { var label = me.makeElement('label'); label.html(externalTrigger.html()); //set what the label is for label.attr('for', me.getEditorInputId()); externalTrigger.replaceWith(label); } }; }; FoldedEditor.prototype.setExternalTrigger = function(element) { this._externalTrigger = element; }; FoldedEditor.prototype.decorate = function(element) { this._element = element; this._prompt = element.find('.prompt'); this._editorBox = element.find('.editor-proper'); var editorType = askbot['settings']['editorType']; if (editorType === 'tinymce') { var editor = new TinyMCE(); editor.decorate(element.find('textarea')); this._editor = editor; } else if (editorType === 'markdown') { var editor = new WMD(); editor.decorate(element); this._editor = editor; } var openHandler = this.getOpenHandler(); element.click(openHandler); element.focus(openHandler); if (this._externalTrigger) { this._externalTrigger.click(openHandler); } }; /** * @constructor * a simple textarea-based editor */ var SimpleEditor = function(attrs) { WrappedElement.call(this); attrs = attrs || {}; this._rows = attrs['rows'] || 10; this._cols = attrs['cols'] || 60; this._maxlength = attrs['maxlength'] || 1000; }; inherits(SimpleEditor, WrappedElement); SimpleEditor.prototype.focus = function(onFocus) { this._textarea.focus(); if (onFocus) { onFocus(); } }; SimpleEditor.prototype.putCursorAtEnd = function() { putCursorAtEnd(this._textarea); }; /** * a noop function */ SimpleEditor.prototype.start = function() {}; SimpleEditor.prototype.setHighlight = function(isHighlighted) { if (isHighlighted === true) { this._textarea.addClass('highlight'); } else { this._textarea.removeClass('highlight'); } }; SimpleEditor.prototype.getText = function() { return $.trim(this._textarea.val()); }; SimpleEditor.prototype.getHtml = function() { return '<div class="transient-comment">' + this.getText() + '</div>'; }; SimpleEditor.prototype.setText = function(text) { this._text = text; if (this._textarea) { this._textarea.val(text); }; }; /** * a textarea inside a div, * the reason for this is that we subclass this * in WMD, and that one requires a more complex structure */ SimpleEditor.prototype.createDom = function() { this._element = this.makeElement('div'); this._element.addClass('wmd-container'); var textarea = this.makeElement('textarea'); this._element.append(textarea); this._textarea = textarea; if (this._text) { textarea.val(this._text); }; textarea.attr({ 'cols': this._cols, 'rows': this._rows, 'maxlength': this._maxlength }); } /** * @constructor * a wrapper for the WMD editor */ var WMD = function(){ SimpleEditor.call(this); this._text = undefined; this._enabled_buttons = 'bold italic link blockquote code ' + 'image attachment ol ul heading hr'; this._is_previewer_enabled = true; }; inherits(WMD, SimpleEditor); //@todo: implement getHtml method that runs text through showdown renderer WMD.prototype.setEnabledButtons = function(buttons){ this._enabled_buttons = buttons; }; WMD.prototype.setPreviewerEnabled = function(state){ this._is_previewer_enabled = state; if (this._previewer){ this._previewer.hide(); } }; WMD.prototype.createDom = function(){ this._element = this.makeElement('div'); var clearfix = this.makeElement('div').addClass('clearfix'); this._element.append(clearfix); var wmd_container = this.makeElement('div'); wmd_container.addClass('wmd-container'); this._element.append(wmd_container); var wmd_buttons = this.makeElement('div') .attr('id', this.makeId('wmd-button-bar')) .addClass('wmd-panel'); wmd_container.append(wmd_buttons); var editor = this.makeElement('textarea') .attr('id', this.makeId('editor')); wmd_container.append(editor); this._textarea = editor; if (this._text){ editor.val(this._text); } var previewer = this.makeElement('div') .attr('id', this.makeId('previewer')) .addClass('wmd-preview'); wmd_container.append(previewer); this._previewer = previewer; if (this._is_previewer_enabled === false) { previewer.hide(); } }; WMD.prototype.decorate = function(element) { this._element = element; this._textarea = element.find('textarea'); this._previewer = element.find('.wmd-preview'); }; WMD.prototype.start = function(){ Attacklab.Util.startEditor(true, this._enabled_buttons, this.getIdSeed()); }; /** * @constructor */ var TinyMCE = function(config) { WrappedElement.call(this); this._config = config || {}; this._id = 'editor';//desired id of the textarea }; inherits(TinyMCE, WrappedElement); /* * not passed onto prototoype on purpose!!! */ TinyMCE.onInitHook = function() { //set initial content var ed = tinyMCE.activeEditor; ed.setContent(askbot['data']['editorContent'] || ''); //if we have spellchecker - enable it by default if (inArray('spellchecker', askbot['settings']['tinyMCEPlugins'])) { setTimeout(function() { ed.controlManager.setActive('spellchecker', true); tinyMCE.execCommand('mceSpellCheck', true); }, 1); } }; /* 3 dummy functions to match WMD api */ TinyMCE.prototype.setEnabledButtons = function() {}; TinyMCE.prototype.start = function() { //copy the options, because we need to modify them var opts = $.extend({}, this._config); var me = this; var extraOpts = { 'mode': 'exact', 'elements': this._id, }; opts = $.extend(opts, extraOpts); tinyMCE.init(opts); $('.mceStatusbar').remove(); }; TinyMCE.prototype.setPreviewerEnabled = function() {}; TinyMCE.prototype.setHighlight = function() {}; TinyMCE.prototype.putCursorAtEnd = function() { var ed = tinyMCE.activeEditor; //add an empty span with a unique id var endId = tinymce.DOM.uniqueId(); ed.dom.add(ed.getBody(), 'span', {'id': endId}, ''); //select that span var newNode = ed.dom.select('span#' + endId); ed.selection.select(newNode[0]); }; TinyMCE.prototype.focus = function(onFocus) { var editorId = this._id; var winH = $(window).height(); var winY = $(window).scrollTop(); var edY = this._element.offset().top; var edH = this._element.height(); //@todo: the fallacy of this method is timeout - should instead use queue //because at the time of calling focus() the editor may not be initialized yet setTimeout( function() { tinyMCE.execCommand('mceFocus', false, editorId); //@todo: make this general to all editors //if editor bottom is below viewport var isBelow = ((edY + edH) > (winY + winH)); var isAbove = (edY < winY); if (isBelow || isAbove) { //then center on screen $(window).scrollTop(edY - edH/2 - winY/2); } if (onFocus) { onFocus(); } }, 100 ); }; TinyMCE.prototype.setId = function(id) { this._id = id; }; TinyMCE.prototype.setText = function(text) { this._text = text; if (this.isLoaded()) { tinymce.get(this._id).setContent(text); } }; TinyMCE.prototype.getText = function() { return tinyMCE.activeEditor.getContent(); }; TinyMCE.prototype.getHtml = TinyMCE.prototype.getText; TinyMCE.prototype.isLoaded = function() { return (tinymce.get(this._id) !== undefined); }; TinyMCE.prototype.createDom = function() { var editorBox = this.makeElement('div'); editorBox.addClass('wmd-container'); this._element = editorBox; var textarea = this.makeElement('textarea'); textarea.attr('id', this._id); textarea.addClass('editor'); this._element.append(textarea); }; TinyMCE.prototype.decorate = function(element) { this._element = element; this._id = element.attr('id'); }; /** * @constructor * @todo: change this to generic object description editor */ var TagWikiEditor = function(){ WrappedElement.call(this); this._state = 'display';//'edit' or 'display' this._content_backup = ''; this._is_editor_loaded = false; this._enabled_editor_buttons = null; this._is_previewer_enabled = false; }; inherits(TagWikiEditor, WrappedElement); TagWikiEditor.prototype.backupContent = function(){ this._content_backup = this._content_box.contents(); }; TagWikiEditor.prototype.setEnabledEditorButtons = function(buttons){ this._enabled_editor_buttons = buttons; }; TagWikiEditor.prototype.setPreviewerEnabled = function(state){ this._is_previewer_enabled = state; if (this.isEditorLoaded()){ this._editor.setPreviewerEnabled(this._is_previewer_enabled); } }; TagWikiEditor.prototype.setContent = function(content){ this._content_box.empty(); this._content_box.append(content); }; TagWikiEditor.prototype.setState = function(state){ if (state === 'edit'){ this._state = state; this._edit_btn.hide(); this._cancel_btn.show(); this._save_btn.show(); this._cancel_sep.show(); } else if (state === 'display'){ this._state = state; this._edit_btn.show(); this._cancel_btn.hide(); this._cancel_sep.hide(); this._save_btn.hide(); } }; TagWikiEditor.prototype.restoreContent = function(){ var content_box = this._content_box; content_box.empty(); $.each(this._content_backup, function(idx, element){ content_box.append(element); }); }; TagWikiEditor.prototype.getTagId = function(){ return this._tag_id; }; TagWikiEditor.prototype.isEditorLoaded = function(){ return this._is_editor_loaded; }; TagWikiEditor.prototype.setEditorLoaded = function(){ return this._is_editor_loaded = true; }; /** * loads initial data for the editor input and activates * the editor */ TagWikiEditor.prototype.startActivatingEditor = function(){ var editor = this._editor; var me = this; var data = { object_id: me.getTagId(), model_name: 'Group' }; $.ajax({ type: 'GET', url: askbot['urls']['load_object_description'], data: data, cache: false, success: function(data){ me.backupContent(); editor.setText(data); me.setContent(editor.getElement()); me.setState('edit'); if (me.isEditorLoaded() === false){ editor.start(); me.setEditorLoaded(); } } }); }; TagWikiEditor.prototype.saveData = function(){ var me = this; var text = this._editor.getText(); var data = { object_id: me.getTagId(), model_name: 'Group',//todo: fixme text: text }; $.ajax({ type: 'POST', dataType: 'json', url: askbot['urls']['save_object_description'], data: data, cache: false, success: function(data){ if (data['success']){ me.setState('display'); me.setContent(data['html']); } else { showMessage(me.getElement(), data['message']); } } }); }; TagWikiEditor.prototype.cancelEdit = function(){ this.restoreContent(); this.setState('display'); }; TagWikiEditor.prototype.decorate = function(element){ //expect <div id='group-wiki-{{id}}'><div class="content"/><a class="edit"/></div> this._element = element; var edit_btn = element.find('.edit-description'); this._edit_btn = edit_btn; //adding two buttons... var save_btn = this.makeElement('a'); save_btn.html(gettext('save')); edit_btn.after(save_btn); save_btn.hide(); this._save_btn = save_btn; var cancel_btn = this.makeElement('a'); cancel_btn.html(gettext('cancel')); save_btn.after(cancel_btn); cancel_btn.hide(); this._cancel_btn = cancel_btn; this._cancel_sep = $('<span> | </span>'); cancel_btn.before(this._cancel_sep); this._cancel_sep.hide(); this._content_box = element.find('.content'); this._tag_id = element.attr('id').split('-').pop(); var me = this; if (askbot['settings']['editorType'] === 'markdown') { var editor = new WMD(); } else { var editor = new TinyMCE({//override defaults theme_advanced_buttons1: 'bold, italic, |, link, |, numlist, bullist', theme_advanced_buttons2: '', theme_advanced_path: false, plugins: '' }); } if (this._enabled_editor_buttons){ editor.setEnabledButtons(this._enabled_editor_buttons); } editor.setPreviewerEnabled(this._is_previewer_enabled); this._editor = editor; setupButtonEventHandlers(edit_btn, function(){ me.startActivatingEditor() }); setupButtonEventHandlers(cancel_btn, function(){me.cancelEdit()}); setupButtonEventHandlers(save_btn, function(){me.saveData()}); }; var ImageChanger = function(){ WrappedElement.call(this); this._image_element = undefined; this._delete_button = undefined; this._save_url = undefined; this._delete_url = undefined; this._messages = undefined; }; inherits(ImageChanger, WrappedElement); ImageChanger.prototype.setImageElement = function(image_element){ this._image_element = image_element; }; ImageChanger.prototype.setMessages = function(messages){ this._messages = messages; }; ImageChanger.prototype.setDeleteButton = function(delete_button){ this._delete_button = delete_button; }; ImageChanger.prototype.setSaveUrl = function(url){ this._save_url = url; }; ImageChanger.prototype.setDeleteUrl = function(url){ this._delete_url = url; }; ImageChanger.prototype.setAjaxData = function(data){ this._ajax_data = data; }; ImageChanger.prototype.showImage = function(image_url){ this._image_element.attr('src', image_url); this._image_element.show(); }; ImageChanger.prototype.deleteImage = function(){ this._image_element.attr('src', ''); this._image_element.css('display', 'none'); var me = this; var delete_url = this._delete_url; var data = this._ajax_data; $.ajax({ type: 'POST', dataType: 'json', url: delete_url, data: data, cache: false, success: function(data){ if (data['success'] === true){ showMessage(me.getElement(), data['message'], 'after'); } } }); }; ImageChanger.prototype.saveImageUrl = function(image_url){ var me = this; var data = this._ajax_data; data['image_url'] = image_url; var save_url = this._save_url; $.ajax({ type: 'POST', dataType: 'json', url: save_url, data: data, cache: false, success: function(data){ if (!data['success']){ showMessage(me.getElement(), data['message'], 'after'); } } }); }; ImageChanger.prototype.startDialog = function(){ //reusing the wmd's file uploader var me = this; var change_image_text = this._messages['change_image']; var change_image_button = this._element; Attacklab.Util.prompt( "<h3>" + gettext('Enter the logo url or upload an image') + '</h3>', 'http://', function(image_url){ if (image_url){ me.saveImageUrl(image_url); me.showImage(image_url); change_image_button.html(change_image_text); me.showDeleteButton(); } }, 'image' ); }; ImageChanger.prototype.showDeleteButton = function(){ this._delete_button.show(); this._delete_button.prev().show(); }; ImageChanger.prototype.hideDeleteButton = function(){ this._delete_button.hide(); this._delete_button.prev().hide(); }; ImageChanger.prototype.startDeleting = function(){ if (confirm(gettext('Do you really want to remove the image?'))){ this.deleteImage(); this._element.html(this._messages['add_image']); this.hideDeleteButton(); this._delete_button.hide(); var sep = this._delete_button.prev(); sep.hide(); }; }; /** * decorates an element that will serve as the image changer button */ ImageChanger.prototype.decorate = function(element){ this._element = element; var me = this; setupButtonEventHandlers( element, function(){ me.startDialog(); } ); setupButtonEventHandlers( this._delete_button, function(){ me.startDeleting(); } ) }; var UserGroupProfileEditor = function(){ TagWikiEditor.call(this); }; inherits(UserGroupProfileEditor, TagWikiEditor); UserGroupProfileEditor.prototype.toggleEmailModeration = function(){ var btn = this._moderate_email_btn; var group_id = this.getTagId(); $.ajax({ type: 'POST', dataType: 'json', cache: false, data: {group_id: group_id}, url: askbot['urls']['toggle_group_email_moderation'], success: function(data){ if (data['success']){ btn.html(data['new_button_text']); } else { showMessage(btn, data['message']); } } }); }; UserGroupProfileEditor.prototype.decorate = function(element){ this.setEnabledEditorButtons('bold italic link ol ul'); this.setPreviewerEnabled(false); UserGroupProfileEditor.superClass_.decorate.call(this, element); var change_logo_btn = element.find('.change-logo'); this._change_logo_btn = change_logo_btn; var moderate_email_toggle = new TwoStateToggle(); moderate_email_toggle.setPostData({ group_id: this.getTagId(), property_name: 'moderate_email' }); var moderate_email_btn = element.find('#moderate-email'); this._moderate_email_btn = moderate_email_btn; moderate_email_toggle.decorate(moderate_email_btn); var moderate_publishing_replies_toggle = new TwoStateToggle(); moderate_publishing_replies_toggle.setPostData({ group_id: this.getTagId(), property_name: 'moderate_answers_to_enquirers' }); var btn = element.find('#moderate-answers-to-enquirers'); moderate_publishing_replies_toggle.decorate(btn); var vip_toggle = new TwoStateToggle(); vip_toggle.setPostData({ group_id: this.getTagId(), property_name: 'is_vip' }); var btn = element.find('#vip-toggle'); vip_toggle.decorate(btn); var opennessSelector = new DropdownSelect(); var selectorElement = element.find('#group-openness-selector'); opennessSelector.setPostData({ group_id: this.getTagId(), property_name: 'openness' }); opennessSelector.decorate(selectorElement); var email_editor = new TextPropertyEditor(); email_editor.decorate(element.find('#preapproved-emails')); var domain_editor = new TextPropertyEditor(); domain_editor.decorate(element.find('#preapproved-email-domains')); var logo_changer = new ImageChanger(); logo_changer.setImageElement(element.find('.group-logo')); logo_changer.setAjaxData({ group_id: this.getTagId() }); logo_changer.setSaveUrl(askbot['urls']['save_group_logo_url']); logo_changer.setDeleteUrl(askbot['urls']['delete_group_logo_url']); logo_changer.setMessages({ change_image: gettext('change logo'), add_image: gettext('add logo') }); var delete_logo_btn = element.find('.delete-logo'); logo_changer.setDeleteButton(delete_logo_btn); logo_changer.decorate(change_logo_btn); }; var GroupJoinButton = function(){ TwoStateToggle.call(this); }; inherits(GroupJoinButton, TwoStateToggle); GroupJoinButton.prototype.getPostData = function(){ return { group_id: this._group_id }; }; GroupJoinButton.prototype.getHandler = function(){ var me = this; return function(){ $.ajax({ type: 'POST', dataType: 'json', cache: false, data: me.getPostData(), url: askbot['urls']['join_or_leave_group'], success: function(data){ if (data['success']){ var level = data['membership_level']; var new_state = 'off-state'; if (level == 'full' || level == 'pending') { new_state = 'on-state'; } me.setState(new_state); } else { showMessage(me.getElement(), data['message']); } } }); }; }; GroupJoinButton.prototype.decorate = function(elem) { GroupJoinButton.superClass_.decorate.call(this, elem); this._group_id = this._element.data('groupId'); }; var TagEditor = function() { WrappedElement.call(this); this._has_hot_backspace = false; this._settings = JSON.parse(askbot['settings']['tag_editor']); }; inherits(TagEditor, WrappedElement); TagEditor.prototype.getSelectedTags = function() { return $.trim(this._hidden_tags_input.val()).split(/\s+/); }; TagEditor.prototype.setSelectedTags = function(tag_names) { this._hidden_tags_input.val($.trim(tag_names.join(' '))); }; TagEditor.prototype.addSelectedTag = function(tag_name) { var tag_names = this._hidden_tags_input.val(); this._hidden_tags_input.val(tag_names + ' ' + tag_name); $('.acResults').hide();//a hack to hide the autocompleter }; TagEditor.prototype.isSelectedTagName = function(tag_name) { var tag_names = this.getSelectedTags(); return $.inArray(tag_name, tag_names) != -1; }; TagEditor.prototype.removeSelectedTag = function(tag_name) { var tag_names = this.getSelectedTags(); var idx = $.inArray(tag_name, tag_names); if (idx !== -1) { tag_names.splice(idx, 1) } this.setSelectedTags(tag_names); }; TagEditor.prototype.getTagDeleteHandler = function(tag){ var me = this; return function(){ me.removeSelectedTag(tag.getName()); me.clearErrorMessage(); tag.dispose(); $('.acResults').hide();//a hack to hide the autocompleter me.fixHeight(); }; }; TagEditor.prototype.cleanTag = function(tag_name, reject_dupe) { tag_name = $.trim(tag_name); tag_name = tag_name.replace(/\s+/, ' '); var force_lowercase = this._settings['force_lowercase_tags']; if (force_lowercase) { tag_name = tag_name.toLowerCase(); } if (reject_dupe && this.isSelectedTagName(tag_name)) { throw interpolate( gettext('tag "%s" was already added, no need to repeat (press "escape" to delete)'), [tag_name] ); } var max_tags = this._settings['max_tags_per_post']; if (this.getSelectedTags().length + 1 > max_tags) {//count current throw interpolate( ngettext( 'a maximum of %s tag is allowed', 'a maximum of %s tags are allowed', max_tags ), [max_tags] ); } //generic cleaning return cleanTag(tag_name, this._settings); }; TagEditor.prototype.addTag = function(tag_name) { var tag = new Tag(); tag.setName(tag_name); tag.setDeletable(true); tag.setLinkable(true); tag.setDeleteHandler(this.getTagDeleteHandler(tag)); this._tags_container.append(tag.getElement()); this.addSelectedTag(tag_name); }; TagEditor.prototype.immediateClearErrorMessage = function() { this._error_alert.html(''); this._error_alert.show(); //this._element.css('margin-top', '18px');//todo: the margin thing is a hack } TagEditor.prototype.clearErrorMessage = function(fade) { if (fade) { var me = this; this._error_alert.fadeOut(function(){ me.immediateClearErrorMessage(); }); } else { this.immediateClearErrorMessage(); } }; TagEditor.prototype.setErrorMessage = function(text) { var old_text = this._error_alert.html(); this._error_alert.html(text); if (old_text == '') { this._error_alert.hide(); this._error_alert.fadeIn(100); } //this._element.css('margin-top', '0');//todo: remove this hack }; TagEditor.prototype.getAddTagHandler = function() { var me = this; return function(tag_name) { if (me.isSelectedTagName(tag_name)) { return; } try { var clean_tag_name = me.cleanTag($.trim(tag_name)); me.addTag(clean_tag_name); me.clearNewTagInput(); me.fixHeight(); } catch (error) { me.setErrorMessage(error); setTimeout(function(){ me.clearErrorMessage(true); }, 1000); } }; }; TagEditor.prototype.getRawNewTagValue = function() { return this._visible_tags_input.val();//without trimming }; TagEditor.prototype.clearNewTagInput = function() { return this._visible_tags_input.val(''); }; TagEditor.prototype.editLastTag = function() { //delete rendered tag var tc = this._tags_container; tc.find('li:last').remove(); //remove from hidden tags input var tags = this.getSelectedTags(); var last_tag = tags.pop(); this.setSelectedTags(tags); //populate the tag editor this._visible_tags_input.val(last_tag); putCursorAtEnd(this._visible_tags_input); }; TagEditor.prototype.setHotBackspace = function(is_hot) { this._has_hot_backspace = is_hot; }; TagEditor.prototype.hasHotBackspace = function() { return this._has_hot_backspace; }; TagEditor.prototype.completeTagInput = function(reject_dupe) { var tag_name = $.trim(this._visible_tags_input.val()); try { tag_name = this.cleanTag(tag_name, reject_dupe); this.addTag(tag_name); this.clearNewTagInput(); } catch (error) { this.setErrorMessage(error); } }; TagEditor.prototype.saveHeight = function() { return; var elem = this._visible_tags_input; this._height = elem.offset().top; }; TagEditor.prototype.fixHeight = function() { return; var new_height = this._visible_tags_input.offset().top; //@todo: replace this by real measurement var element_height = parseInt( this._element.css('height').replace('px', '') ); if (new_height > this._height) { this._element.css('height', element_height + 28);//magic number!!! } else if (new_height < this._height) { this._element.css('height', element_height - 28);//magic number!!! } this.saveHeight(); }; TagEditor.prototype.closeAutoCompleter = function() { this._autocompleter.finish(); }; TagEditor.prototype.getTagInputKeyHandler = function() { var new_tags = this._visible_tags_input; var me = this; return function(e) { if (e.shiftKey) { return; } me.saveHeight(); var key = e.which || e.keyCode; var text = me.getRawNewTagValue(); //space 32, enter 13 if (key == 32 || key == 13) { var tag_name = $.trim(text); if (tag_name.length > 0) { me.completeTagInput(true);//true for reject dupes } me.fixHeight(); return false; } if (text == '') { me.clearErrorMessage(); me.closeAutoCompleter(); } else { try { /* do-nothing validation here * just to report any errors while * the user is typing */ me.cleanTag(text); me.clearErrorMessage(); } catch (error) { me.setErrorMessage(error); } } //8 is backspace if (key == 8 && text.length == 0) { if (me.hasHotBackspace() === true) { me.editLastTag(); me.setHotBackspace(false); } else { me.setHotBackspace(true); } } //27 is escape if (key == 27) { me.clearNewTagInput(); me.clearErrorMessage(); } if (key !== 8) { me.setHotBackspace(false); } me.fixHeight(); return false; }; } TagEditor.prototype.decorate = function(element) { this._element = element; this._hidden_tags_input = element.find('input[name="tags"]');//this one is hidden this._tags_container = element.find('ul.tags'); this._error_alert = $('.tag-editor-error-alert > span'); var me = this; this._tags_container.children().each(function(idx, elem){ var tag = new Tag(); tag.setDeletable(true); tag.setLinkable(false); tag.decorate($(elem)); tag.setDeleteHandler(me.getTagDeleteHandler(tag)); }); var visible_tags_input = element.find('.new-tags-input'); this._visible_tags_input = visible_tags_input; this.saveHeight(); var me = this; var tagsAc = new AutoCompleter({ url: askbot['urls']['get_tag_list'], onItemSelect: function(item){ if (me.isSelectedTagName(item['value']) === false) { me.completeTagInput(); } else { me.clearNewTagInput(); } }, minChars: 1, useCache: true, matchInside: true, maxCacheLength: 100, delay: 10 }); tagsAc.decorate(visible_tags_input); this._autocompleter = tagsAc; visible_tags_input.keyup(this.getTagInputKeyHandler()); element.click(function(e) { visible_tags_input.focus(); return false; }); }; /** * @constructor * Category is a select box item * that has CategoryEditControls */ var Category = function() { SelectBoxItem.call(this); this._state = 'display'; this._settings = JSON.parse(askbot['settings']['tag_editor']); }; inherits(Category, SelectBoxItem); Category.prototype.setCategoryTree = function(tree) { this._tree = tree; }; Category.prototype.getCategoryTree = function() { return this._tree; }; Category.prototype.getName = function() { return this.getContent().getContent(); }; Category.prototype.getPath = function() { return this._tree.getPathToItem(this); }; Category.prototype.setState = function(state) { this._state = state; if ( !this._element ) { return; } this._input_box.val(''); if (state === 'display') { this.showContent(); this.hideEditor(); this.hideEditControls(); } else if (state === 'editable') { this._tree._state = 'editable';//a hack this.showContent(); this.hideEditor(); this.showEditControls(); } else if (state === 'editing') { this._prev_tree_state = this._tree.getState(); this._tree._state = 'editing';//a hack this._input_box.val(this.getName()); this.hideContent(); this.showEditor(); this.hideEditControls(); } }; Category.prototype.hideEditControls = function() { this._delete_button.hide(); this._edit_button.hide(); this._element.unbind('mouseenter mouseleave'); }; Category.prototype.showEditControls = function() { var del = this._delete_button; var edit = this._edit_button; this._element.hover( function(){ del.show(); edit.show(); }, function(){ del.hide(); edit.hide(); } ); }; Category.prototype.showEditControlsNow = function() { this._delete_button.show(); this._edit_button.show(); }; Category.prototype.hideContent = function() { this.getContent().getElement().hide(); }; Category.prototype.showContent = function() { this.getContent().getElement().show(); }; Category.prototype.showEditor = function() { this._input_box.show(); this._input_box.focus(); this._save_button.show(); this._cancel_button.show(); }; Category.prototype.hideEditor = function() { this._input_box.hide(); this._save_button.hide(); this._cancel_button.hide(); }; Category.prototype.getInput = function() { return this._input_box.val(); }; Category.prototype.getDeleteHandler = function() { var me = this; return function() { if (confirm(gettext('Delete category?'))) { var tree = me.getCategoryTree(); $.ajax({ type: 'POST', dataType: 'json', data: JSON.stringify({ tag_name: me.getName(), path: me.getPath() }), cache: false, url: askbot['urls']['delete_tag'], success: function(data) { if (data['success']) { //rebuild category tree based on data tree.setData(data['tree_data']); //re-open current branch tree.selectPath(tree.getCurrentPath()); tree.setState('editable'); } else { alert(data['message']); } } }); } return false; }; }; Category.prototype.getSaveHandler = function() { var me = this; var settings = this._settings; //here we need old value and new value return function(){ var to_name = me.getInput(); try { to_name = cleanTag(to_name, settings); var data = { from_name: me.getOriginalName(), to_name: to_name, path: me.getPath() }; $.ajax({ type: 'POST', dataType: 'json', data: JSON.stringify(data), cache: false, url: askbot['urls']['rename_tag'], success: function(data) { if (data['success']) { me.setName(to_name); me.setState('editable'); me.showEditControlsNow(); } else { alert(data['message']); } } }); } catch (error) { alert(error); } return false; }; }; Category.prototype.addControls = function() { var input_box = this.makeElement('input'); this._input_box = input_box; this._element.append(input_box); var save_button = this.makeButton( gettext('save'), this.getSaveHandler() ); this._save_button = save_button; this._element.append(save_button); var me = this; var cancel_button = this.makeButton( 'x', function(){ me.setState('editable'); me.showEditControlsNow(); return false; } ); this._cancel_button = cancel_button; this._element.append(cancel_button); var edit_button = this.makeButton( gettext('edit'), function(){ //todo: I would like to make only one at a time editable //var tree = me.getCategoryTree(); //tree.closeAllEditors(); //tree.setState('editable'); //calc path, then select it var tree = me.getCategoryTree(); tree.selectPath(me.getPath()); me.setState('editing'); return false; } ); this._edit_button = edit_button; this._element.append(edit_button); var delete_button = this.makeButton( 'x', this.getDeleteHandler() ); this._delete_button = delete_button; this._element.append(delete_button); }; Category.prototype.getOriginalName = function() { return this._original_name; }; Category.prototype.createDom = function() { Category.superClass_.createDom.call(this); this.addControls(); this.setState('display'); this._original_name = this.getName(); }; Category.prototype.decorate = function(element) { Category.superClass_.decorate.call(this, element); this.addControls(); this.setState('display'); this._original_name = this.getName(); }; var CategoryAdder = function() { WrappedElement.call(this); this._state = 'disabled';//waitedit this._tree = undefined;//category tree this._settings = JSON.parse(askbot['settings']['tag_editor']); }; inherits(CategoryAdder, WrappedElement); CategoryAdder.prototype.setCategoryTree = function(tree) { this._tree = tree; }; CategoryAdder.prototype.setLevel = function(level) { this._level = level; }; CategoryAdder.prototype.setState = function(state) { this._state = state; if (!this._element) { return; } if (state === 'waiting') { this._element.show(); this._input.val(''); this._input.hide(); this._save_button.hide(); this._cancel_button.hide(); this._trigger.show(); } else if (state === 'editable') { this._element.show(); this._input.show(); this._input.val(''); this._input.focus(); this._save_button.show(); this._cancel_button.show(); this._trigger.hide(); } else if (state === 'disabled') { this.setState('waiting');//a little hack this._state = 'disabled'; this._element.hide(); } }; CategoryAdder.prototype.cleanCategoryName = function(name) { name = $.trim(name); if (name === '') { throw gettext('category name cannot be empty'); } //if ( this._tree.hasCategory(name) ) { //throw interpolate( //throw gettext('this category already exists'); // [this._tree.getDisplayPathByName(name)] //) //} return cleanTag(name, this._settings); }; CategoryAdder.prototype.getPath = function() { var path = this._tree.getCurrentPath(); if (path.length > this._level + 1) { return path.slice(0, this._level + 1); } else { return path; } }; CategoryAdder.prototype.getSelectBox = function() { return this._tree.getSelectBox(this._level); }; CategoryAdder.prototype.startAdding = function() { try { var name = this._input.val(); name = this.cleanCategoryName(name); } catch (error) { alert(error); return; } //don't add dupes to the same level var existing_names = this.getSelectBox().getNames(); if ($.inArray(name, existing_names) != -1) { alert(gettext('already exists at the current level!')); return; } var me = this; var tree = this._tree; var adder_path = this.getPath(); $.ajax({ type: 'POST', dataType: 'json', data: JSON.stringify({ path: adder_path, new_category_name: name }), url: askbot['urls']['add_tag_category'], cache: false, success: function(data) { if (data['success']) { //rebuild category tree based on data tree.setData(data['tree_data']); tree.selectPath(data['new_path']); tree.setState('editable'); me.setState('waiting'); } else { alert(data['message']); } } }); }; CategoryAdder.prototype.createDom = function() { this._element = this.makeElement('li'); //add open adder link var trigger = this.makeElement('a'); this._trigger = trigger; trigger.html(gettext('add category')); this._element.append(trigger); //add input box and the add button var input = this.makeElement('input'); this._input = input; input.addClass('add-category'); input.attr('name', 'add_category'); this._element.append(input); //add save category button var save_button = this.makeElement('button'); this._save_button = save_button; save_button.html(gettext('save')); this._element.append(save_button); var cancel_button = this.makeElement('button'); this._cancel_button = cancel_button; cancel_button.html('x'); this._element.append(cancel_button); this.setState(this._state); var me = this; setupButtonEventHandlers( trigger, function(){ me.setState('editable'); } ) setupButtonEventHandlers( save_button, function() { me.startAdding(); return false;//prevent form submit } ); setupButtonEventHandlers( cancel_button, function() { me.setState('waiting'); return false;//prevent submit } ); //create input box, button and the "activate" link }; /** * @constructor * SelectBox subclass to create/edit/delete * categories */ var CategorySelectBox = function() { SelectBox.call(this); this._item_class = Category; this._category_adder = undefined; this._tree = undefined;//cat tree this._level = undefined; }; inherits(CategorySelectBox, SelectBox); CategorySelectBox.prototype.setState = function(state) { this._state = state; if (state === 'select') { if (this._category_adder) { this._category_adder.setState('disabled'); } $.each(this._items, function(idx, item){ item.setState('display'); }); } else if (state === 'editable') { this._category_adder.setState('waiting'); $.each(this._items, function(idx, item){ item.setState('editable'); }); } }; CategorySelectBox.prototype.setCategoryTree = function(tree) { this._tree = tree; }; CategorySelectBox.prototype.getCategoryTree = function() { }; CategorySelectBox.prototype.setLevel = function(level) { this._level = level; }; CategorySelectBox.prototype.getNames = function() { var names = []; $.each(this._items, function(idx, item) { names.push(item.getName()); }); return names; }; CategorySelectBox.prototype.appendCategoryAdder = function() { var adder = new CategoryAdder(); adder.setLevel(this._level); adder.setCategoryTree(this._tree); this._category_adder = adder; this._element.append(adder.getElement()); }; CategorySelectBox.prototype.createDom = function() { CategorySelectBox.superClass_.createDom(); if (askbot['data']['userIsAdmin']) { this.appendCategoryAdder(); } }; CategorySelectBox.prototype.decorate = function(element) { CategorySelectBox.superClass_.decorate.call(this, element); this.setState(this._state); if (askbot['data']['userIsAdmin']) { this.appendCategoryAdder(); } }; /** * @constructor * turns on/off the category editor */ var CategoryEditorToggle = function() { TwoStateToggle.call(this); }; inherits(CategoryEditorToggle, TwoStateToggle); CategoryEditorToggle.prototype.setCategorySelector = function(sel) { this._category_selector = sel; }; CategoryEditorToggle.prototype.getCategorySelector = function() { return this._category_selector; }; CategoryEditorToggle.prototype.decorate = function(element) { CategoryEditorToggle.superClass_.decorate.call(this, element); }; CategoryEditorToggle.prototype.getDefaultHandler = function() { var me = this; return function() { var editor = me.getCategorySelector(); if (me.isOn()) { me.setState('off-state'); editor.setState('select'); } else { me.setState('on-state'); editor.setState('editable'); } }; }; var CategorySelector = function() { Widget.call(this); this._data = null; this._select_handler = function(){};//dummy default this._current_path = [0];//path points to selected item in tree }; inherits(CategorySelector, Widget); /** * propagates state to the individual selectors */ CategorySelector.prototype.setState = function(state) { this._state = state; if (state === 'editing') { return;//do not propagate this state } $.each(this._selectors, function(idx, selector){ selector.setState(state); }); }; CategorySelector.prototype.getPathToItem = function(item) { function findPathToItemInTree(tree, item) { for (var i = 0; i < tree.length; i++) { var node = tree[i]; if (node[2] === item) { return [i]; } var path = findPathToItemInTree(node[1], item); if (path.length > 0) { path.unshift(i); return path; } } return []; }; return findPathToItemInTree(this._data, item); }; CategorySelector.prototype.applyToDataItems = function(func) { function applyToDataItems(tree) { $.each(tree, function(idx, item) { func(item); applyToDataItems(item[1]); }); }; if (this._data) { applyToDataItems(this._data); } }; CategorySelector.prototype.setData = function(data) { this._clearData this._data = data; var tree = this; function attachCategory(item) { var cat = new Category(); cat.setName(item[0]); cat.setCategoryTree(tree); item[2] = cat; }; this.applyToDataItems(attachCategory); }; /** * clears contents of selector boxes starting from * the given level, in range 0..2 */ CategorySelector.prototype.clearCategoryLevels = function(level) { for (var i = level; i < 3; i++) { this._selectors[i].detachAllItems(); } }; CategorySelector.prototype.getLeafItems = function(selection_path) { //traverse the tree down to items pointed to by the path var data = this._data[0]; for (var i = 1; i < selection_path.length; i++) { data = data[1][selection_path[i]]; } return data[1]; } /** * called when a sub-level needs to open */ CategorySelector.prototype.populateCategoryLevel = function(source_path) { var level = source_path.length - 1; if (level >= 3) { return; } //clear all items downstream this.clearCategoryLevels(level); //populate current selector var selector = this._selectors[level]; var items = this.getLeafItems(source_path); $.each(items, function(idx, item) { var category_name = item[0]; var category_subtree = item[1]; var category_object = item[2]; selector.addItemObject(category_object); if (category_subtree.length > 0) { category_object.addCssClass('tree'); } }); this.setState(this._state);//update state selector.clearSelection(); }; CategorySelector.prototype.selectPath = function(path) { for (var i = 1; i <= path.length; i++) { this.populateCategoryLevel(path.slice(0, i)); } for (var i = 1; i < path.length; i++) { var sel_box = this._selectors[i-1]; var category = sel_box.getItemByIndex(path[i]); sel_box.selectItem(category); } }; CategorySelector.prototype.getSelectBox = function(level) { return this._selectors[level]; }; CategorySelector.prototype.getSelectedPath = function(selected_level) { var path = [0];//root, todo: better use names for path??? /* * upper limit capped by current clicked level * we ignore all selection above the current level */ for (var i = 0; i < selected_level + 1; i++) { var selector = this._selectors[i]; var item = selector.getSelectedItem(); if (item) { path.push(selector.getItemIndex(item)); } else { return path; } } return path; }; /** getter and setter are not symmetric */ CategorySelector.prototype.setSelectHandler = function(handler) { this._select_handler = handler; }; CategorySelector.prototype.getSelectHandlerInternal = function() { return this._select_handler; }; CategorySelector.prototype.setCurrentPath = function(path) { return this._current_path = path; }; CategorySelector.prototype.getCurrentPath = function() { return this._current_path; }; CategorySelector.prototype.getEditorToggle = function() { return this._editor_toggle; }; /*CategorySelector.prototype.closeAllEditors = function() { $.each(this._selectors, function(idx, sel) { sel._category_adder.setState('wait'); $.each(sel._items, function(idx2, item) { item.setState('editable'); }); }); };*/ CategorySelector.prototype.getSelectHandler = function(level) { var me = this; return function(item_data) { if (me.getState() === 'editing') { return;//don't navigate when editing } //1) run the assigned select handler var tag_name = item_data['title'] if (me.getState() === 'select') { /* this one will actually select the tag * maybe a bit too implicit */ me.getSelectHandlerInternal()(tag_name); } //2) if appropriate, populate the higher level if (level < 2) { var current_path = me.getSelectedPath(level); me.setCurrentPath(current_path); me.populateCategoryLevel(current_path); } } }; CategorySelector.prototype.decorate = function(element) { this._element = element; this._selectors = []; var selector0 = new CategorySelectBox(); selector0.setLevel(0); selector0.setCategoryTree(this); selector0.decorate(element.find('.cat-col-0')); selector0.setSelectHandler(this.getSelectHandler(0)); this._selectors.push(selector0); var selector1 = new CategorySelectBox(); selector1.setLevel(1); selector1.setCategoryTree(this); selector1.decorate(element.find('.cat-col-1')); selector1.setSelectHandler(this.getSelectHandler(1)); this._selectors.push(selector1) var selector2 = new CategorySelectBox(); selector2.setLevel(2); selector2.setCategoryTree(this); selector2.decorate(element.find('.cat-col-2')); selector2.setSelectHandler(this.getSelectHandler(2)); this._selectors.push(selector2); if (askbot['data']['userIsAdminOrMod']) { var editor_toggle = new CategoryEditorToggle(); editor_toggle.setCategorySelector(this); var toggle_element = $('.category-editor-toggle'); toggle_element.show(); editor_toggle.decorate(toggle_element); this._editor_toggle = editor_toggle; } this.populateCategoryLevel([0]); }; /** * @constructor * loads html for the category selector from * the server via ajax and activates the * CategorySelector on the loaded HTML */ var CategorySelectorLoader = function() { WrappedElement.call(this); this._is_loaded = false; }; inherits(CategorySelectorLoader, WrappedElement); CategorySelectorLoader.prototype.setCategorySelector = function(sel) { this._category_selector = sel; }; CategorySelectorLoader.prototype.setLoaded = function(is_loaded) { this._is_loaded = is_loaded; }; CategorySelectorLoader.prototype.isLoaded = function() { return this._is_loaded; }; CategorySelectorLoader.prototype.setEditor = function(editor) { this._editor = editor; }; CategorySelectorLoader.prototype.closeEditor = function() { this._editor.hide(); this._editor_buttons.hide(); this._display_tags_container.show(); this._question_body.show(); this._question_controls.show(); }; CategorySelectorLoader.prototype.openEditor = function() { this._editor.show(); this._editor_buttons.show(); this._display_tags_container.hide(); this._question_body.hide(); this._question_controls.hide(); var sel = this._category_selector; sel.setState('select'); sel.getEditorToggle().setState('off-state'); }; CategorySelectorLoader.prototype.addEditorButtons = function() { this._editor.after(this._editor_buttons); }; CategorySelectorLoader.prototype.getOnLoadHandler = function() { var me = this; return function(html){ me.setLoaded(true); //append loaded html to dom var editor = $('<div>' + html + '</div>'); me.setEditor(editor); $('#question-tags').after(editor); var selector = askbot['functions']['initCategoryTree'](); me.setCategorySelector(selector); me.addEditorButtons(); me.openEditor(); //add the save button }; }; CategorySelectorLoader.prototype.startLoadingHTML = function(on_load) { var me = this; $.ajax({ type: 'GET', dataType: 'json', data: { template_name: 'widgets/tag_category_selector.html' }, url: askbot['urls']['get_html_template'], cache: true, success: function(data) { if (data['success']) { on_load(data['html']); } else { showMessage(me.getElement(), data['message']); } } }); }; CategorySelectorLoader.prototype.getRetagHandler = function() { var me = this; return function() { if (me.isLoaded() === false) { me.startLoadingHTML(me.getOnLoadHandler()); } else { me.openEditor(); } return false; } }; CategorySelectorLoader.prototype.drawNewTags = function(new_tags) { if (new_tags === ''){ this._display_tags_container.html(''); return; } new_tags = new_tags.split(/\s+/); var tags_html = '' $.each(new_tags, function(index, name){ var tag = new Tag(); tag.setName(name); tags_html += tag.getElement().outerHTML(); }); this._display_tags_container.html(tags_html); }; CategorySelectorLoader.prototype.getSaveHandler = function() { var me = this; return function() { var tagInput = $('input[name="tags"]'); $.ajax({ type: "POST", url: retagUrl,//add to askbot['urls'] dataType: "json", data: { tags: getUniqueWords(tagInput.val()).join(' ') }, success: function(json) { if (json['success'] === true){ var new_tags = getUniqueWords(json['new_tags']); oldTagsHtml = ''; me.closeEditor(); me.drawNewTags(new_tags.join(' ')); } else { me.closeEditor(); showMessage(me.getElement(), json['message']); } }, error: function(xhr, textStatus, errorThrown) { showMessage(tagsDiv, 'sorry, something is not right here'); cancelRetag(); } }); return false; }; }; CategorySelectorLoader.prototype.getCancelHandler = function() { var me = this; return function() { me.closeEditor(); }; }; CategorySelectorLoader.prototype.decorate = function(element) { this._element = element; this._display_tags_container = $('#question-tags'); this._question_body = $('.question .post-body'); this._question_controls = $('#question-controls'); this._editor_buttons = this.makeElement('div'); this._done_button = this.makeElement('button'); this._done_button.html(gettext('save tags')); this._editor_buttons.append(this._done_button); this._cancel_button = this.makeElement('button'); this._cancel_button.html(gettext('cancel')); this._editor_buttons.append(this._cancel_button); this._editor_buttons.find('button').addClass('submit'); this._editor_buttons.addClass('retagger-buttons'); //done button setupButtonEventHandlers( this._done_button, this.getSaveHandler() ); //cancel button setupButtonEventHandlers( this._cancel_button, this.getCancelHandler() ); //retag button setupButtonEventHandlers( element, this.getRetagHandler() ); }; $(document).ready(function() { $('[id^="comments-for-"]').each(function(index, element){ var comments = new PostCommentsWidget(); comments.decorate(element); }); $('[id^="swap-question-with-answer-"]').each(function(idx, element){ var swapper = new QASwapper(); swapper.decorate($(element)); }); $('[id^="post-id-"]').each(function(idx, element){ var deleter = new DeletePostLink(); //confusingly .question-delete matches the answers too need rename var post_id = element.id.split('-').pop(); deleter.setPostId(post_id); deleter.decorate($(element).find('.question-delete')); }); //todo: convert to "control" class var publishBtns = $('.answer-publish, .answer-unpublish'); publishBtns.each(function(idx, btn) { setupButtonEventHandlers($(btn), function() { var answerId = $(btn).data('answerId'); $.ajax({ type: 'POST', dataType: 'json', data: {'answer_id': answerId}, url: askbot['urls']['publishAnswer'], success: function(data) { if (data['success']) { window.location.reload(true); } else { showMessage($(btn), data['message']); } } }); }); }); if (askbot['settings']['tagSource'] == 'category-tree') { var catSelectorLoader = new CategorySelectorLoader(); catSelectorLoader.decorate($('#retag')); } else { questionRetagger.init(); } socialSharing.init(); var proxyUserNameInput = $('#id_post_author_username'); var proxyUserEmailInput = $('#id_post_author_email'); if (proxyUserNameInput.length === 1) { var userSelectHandler = function(data) { proxyUserEmailInput.val(data['data'][0]); }; var fakeUserAc = new AutoCompleter({ url: '/get-users-info/',//askbot['urls']['get_users_info'], promptText: gettext('User name:'), minChars: 1, useCache: true, matchInside: true, maxCacheLength: 100, delay: 10, onItemSelect: userSelectHandler }); fakeUserAc.decorate(proxyUserNameInput); if (proxyUserEmailInput.length === 1) { var tip = new TippedInput(); tip.decorate(proxyUserEmailInput); } } //if groups are enabled - activate share functions var groupsInput = $('#share_group_name'); if (groupsInput.length === 1) { var groupsAc = new AutoCompleter({ url: askbot['urls']['getGroupsList'], promptText: gettext('Group name:'), minChars: 1, useCache: false, matchInside: true, maxCacheLength: 100, delay: 10 }); groupsAc.decorate(groupsInput); } var usersInput = $('#share_user_name'); if (usersInput.length === 1) { var usersAc = new AutoCompleter({ url: '/get-users-info/', promptText: gettext('User name:'), minChars: 1, useCache: false, matchInside: true, maxCacheLength: 100, delay: 10 }); usersAc.decorate(usersInput); } var showSharedUsers = $('.see-related-users'); if (showSharedUsers.length) { var usersPopup = new ThreadUsersDialog(); usersPopup.setHeadingText(gettext('Shared with the following users:')); usersPopup.decorate(showSharedUsers); } var showSharedGroups = $('.see-related-groups'); if (showSharedGroups.length) { var groupsPopup = new ThreadUsersDialog(); groupsPopup.setHeadingText(gettext('Shared with the following groups:')); groupsPopup.decorate(showSharedGroups); } }); /* google prettify.js from google code */ var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c<i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2<i&&"-"===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d<65||j>122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c<b.length;++c)i=b[c],i[0]<=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=["["];o&&b.push("^");b.push.apply(b,a);for(c=0;c< f.length;++c)i=f[c],b.push(e(i[0])),i[1]>i[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c<b;++c){var j=f[c];j==="("?++i:"\\"===j.charAt(0)&&(j=+j.substring(1))&&j<=i&&(d[j]=-1)}for(c=1;c<d.length;++c)-1===d[c]&&(d[c]=++t);for(i=c=0;c<b;++c)j=f[c],j==="("?(++i,d[i]===void 0&&(f[c]="(?:")):"\\"===j.charAt(0)&& (j=+j.substring(1))&&j<=i&&(f[c]="\\"+d[i]);for(i=c=0;c<b;++c)"^"===f[c]&&"^"!==f[c+1]&&(f[c]="");if(a.ignoreCase&&s)for(c=0;c<b;++c)j=f[c],a=j.charAt(0),j.length>=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p<d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,""))){s=!0;l=!1;break}}for(var r= {b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p<d;++p){g=a[p];if(g.global||g.multiline)throw Error(""+g);n.push("(?:"+y(g)+")")}return RegExp(n.join("|"),l?"gi":"g")}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if("BR"===g||"LI"===g)h[s]="\n",t[s<<1]=y++,t[s++<<1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&&(g=p?g.replace(/\r\n?/g,"\n"):g.replace(/[\t\n\r ]+/g," "),h[s]=g,t[s<<1]=y,y+=g.length, t[s++<<1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=document.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);m(a);return{a:h.join("").replace(/\n$/,""),c:t}}function B(a,m,e,h){m&&(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,"pln"],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n<z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b=== "string")c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c<t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b="pln")}if((c=b.length>=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), l=[],p={},d=0,g=e.length;d<g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k>=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g<d.length;++g)e(d[g]);m===(m|0)&&d[0].setAttribute("value", m);var r=s.createElement("OL");r.className="linenums";for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g<z;++g)l=d[g],l.className="L"+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode("\xa0")),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e>=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*</.test(m)?"default-markup":"default-code";return A[a]}function E(a){var m= a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n<g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n<g;){for(var z=d[n],f=d[n+1],b=n+2;b+2<=g&&d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h<p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&&(j=t.substring(e,b))){k&&(j=j.replace(m,"\r"));i.nodeValue= j;var u=i.ownerDocument,v=u.createElement("SPAN");v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e<o&&(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e>=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p<h.length&&l.now()<e;p++){var n=h[p],k=n.className;if(k.indexOf("prettyprint")>=0){var k=k.match(g),f,b;if(b= !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p<h.length?setTimeout(m, 250):a&&a()}for(var e=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],h=[],k=0;k<e.length;++k)for(var t=0,s=e[k].length;t<s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit", PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();
simalytics/askbot-devel
static/default/media/js/post.js
JavaScript
gpl-3.0
160,054
/* * This file is part of ADDIS (Aggregate Data Drug Information System). * ADDIS is distributed from http://drugis.org/. * Copyright © 2009 Gert van Valkenhoef, Tommi Tervonen. * Copyright © 2010 Gert van Valkenhoef, Tommi Tervonen, Tijs Zwinkels, * Maarten Jacobs, Hanno Koeslag, Florin Schimbinschi, Ahmad Kamal, Daniel * Reid. * Copyright © 2011 Gert van Valkenhoef, Ahmad Kamal, Daniel Reid, Florin * Schimbinschi. * Copyright © 2012 Gert van Valkenhoef, Daniel Reid, Joël Kuiper, Wouter * Reckman. * Copyright © 2013 Gert van Valkenhoef, Joël Kuiper. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.drugis.addis.entities.relativeeffect; import org.apache.commons.math3.distribution.NormalDistribution; import org.drugis.common.beans.AbstractObservable; public abstract class GaussianBase extends AbstractObservable implements Distribution { private double d_mu; private double d_sigma; private NormalDistribution d_dist; public GaussianBase(double mu, double sigma) { if (Double.isNaN(mu)) throw new IllegalArgumentException("mu may not be NaN"); if (Double.isNaN(sigma)) throw new IllegalArgumentException("sigma may not be NaN"); if (sigma < 0.0) throw new IllegalArgumentException("sigma must be >= 0.0"); d_mu = mu; d_sigma = sigma; if (getSigma() != 0.0) { d_dist = new NormalDistribution(d_mu, d_sigma); } } protected double calculateQuantile(double p) { if (getSigma() == 0.0) { return getMu(); } return d_dist.inverseCumulativeProbability(p); } protected double calculateCumulativeProbability(double x) { return d_dist.cumulativeProbability(x); } public double getSigma() { return d_sigma; } public double getMu() { return d_mu; } public GaussianBase plus(GaussianBase other) { if (!canEqual(other)) throw new IllegalArgumentException( "Cannot add together " + getClass().getSimpleName() + " and " + other.getClass().getSimpleName()); return newInstance(getMu() + other.getMu(), Math.sqrt(getSigma() * getSigma() + other.getSigma() * other.getSigma())); } protected abstract GaussianBase newInstance(double mu, double sigma); abstract protected boolean canEqual(GaussianBase other); @Override public boolean equals(Object obj) { if (obj instanceof GaussianBase) { GaussianBase other = (GaussianBase) obj; return canEqual(other) && d_mu == other.d_mu && d_sigma == other.d_sigma; } return false; } @Override public int hashCode() { return ((Double)d_mu).hashCode() + 31 * ((Double)d_sigma).hashCode(); } @Override public String toString() { return getClass().getSimpleName() + "(mu=" + getMu() + ", sigma=" + getSigma() + ")"; } }
drugis/addis
application/src/main/java/org/drugis/addis/entities/relativeeffect/GaussianBase.java
Java
gpl-3.0
3,288
// http://eslint.org/docs/user-guide/configuring module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, env: { browser: true, }, extends: 'airbnb-base', // required to lint *.vue files plugins: [ 'html' ], // check if imports actually resolve 'settings': { 'import/resolver': { 'webpack': { 'config': 'scripts/webpack.conf.js' } } }, // add your custom rules here 'rules': { // don't require .vue extension when importing 'import/extensions': ['error', 'always', { 'js': 'never', 'vue': 'never' }], // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, 'no-console': ['warn', { allow: ['error', 'warn', 'info'], }], 'no-param-reassign': ['error', { props: false, }], 'consistent-return': 'off', 'no-use-before-define': ['error', 'nofunc'], 'object-shorthand': ['error', 'always'], 'no-mixed-operators': 'off', 'no-bitwise': ['error', { int32Hint: true }], 'no-underscore-dangle': 'off', 'arrow-parens': ['error', 'as-needed'], 'prefer-promise-reject-errors': 'off', 'prefer-destructuring': ['error', { array: false }], indent: ['error', 2, { MemberExpression: 0, flatTernaryExpressions: true, }], }, globals: { browser: true, zip: true, }, }
gera2ld/Stylish-mx
.eslintrc.js
JavaScript
gpl-3.0
1,429
# -*- coding: UTF-8 -*- """ Lastship Add-on (C) 2019 Credits to Lastship, Placenta and Covenant; our thanks go to their creators This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ # Addon Name: Lastship # Addon id: plugin.video.lastship # Addon Provider: Lastship import re import urlparse from resources.lib.modules import cache from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import source_utils from resources.lib.modules import dom_parser from resources.lib.modules import source_faultlog from resources.lib.modules.handler.requestHandler import cRequestHandler class source: def __init__(self): self.priority = 1 self.language = ['de'] self.domains = ['movie4k.sg', 'movie4k.lol', 'movie4k.pe', 'movie4k.tv', 'movie.to', 'movie4k.me', 'movie4k.org', 'movie2k.cm', 'movie2k.nu', 'movie4k.am', 'movie4k.io'] self._base_link = None self.search_link = '/movies.php?list=search&search=%s' @property def base_link(self): if not self._base_link: self._base_link = cache.get(self.__get_base_url, 120, 'http://%s' % self.domains[0]) return self._base_link def movie(self, imdb, title, localtitle, aliases, year): try: url = self.__search(False, [localtitle] + source_utils.aliases_to_array(aliases), year) if not url and title != localtitle: url = self.__search(False, [title] + source_utils.aliases_to_array(aliases), year) return url except: return def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year): try: url = self.__search(True, [localtvshowtitle] + source_utils.aliases_to_array(aliases), year) if not url and tvshowtitle != localtvshowtitle: url = self.__search(True, [tvshowtitle] + source_utils.aliases_to_array(aliases), year) if url: return url except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode): try: if url is None: return url = urlparse.urljoin(self.base_link, url) oRequest = cRequestHandler(url) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) r = oRequest.request() seasonMapping = dom_parser.parse_dom(r, 'select', attrs={'name': 'season'}) seasonMapping = dom_parser.parse_dom(seasonMapping, 'option', req='value') seasonIndex = [i.attrs['value'] for i in seasonMapping if season in i.content] seasonIndex = int(seasonIndex[0]) - 1 seasons = dom_parser.parse_dom(r, 'div', attrs={'id': re.compile('episodediv.+?')}) seasons = seasons[seasonIndex] episodes = dom_parser.parse_dom(seasons, 'option', req='value') url = [i.attrs['value'] for i in episodes if episode == re.findall('\d+', i.content)[0]] if len(url) > 0: return url[0] except: return def sources(self, url, hostDict, hostprDict): sources = [] try: if not url: return sources url = urlparse.urljoin(self.base_link, url) oRequest = cRequestHandler(url) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) r = oRequest.request() r = r.replace('\\"', '"') links = dom_parser.parse_dom(r, 'tr', attrs={'id': 'tablemoviesindex2'}) for i in links: try: host = dom_parser.parse_dom(i, 'img', req='alt')[0].attrs['alt'] host = host.split()[0].rsplit('.', 1)[0].strip().lower() host = host.encode('utf-8') valid, host = source_utils.is_host_valid(host, hostDict) if not valid: continue link = dom_parser.parse_dom(i, 'a', req='href')[0].attrs['href'] link = client.replaceHTMLCodes(link) link = urlparse.urljoin(self.base_link, link) link = link.encode('utf-8') sources.append({'source': host, 'quality': 'SD', 'language': 'de', 'url': link, 'direct': False, 'debridonly': False}) except: pass if len(sources) == 0: raise Exception() return sources except: source_faultlog.logFault(__name__,source_faultlog.tagScrape, url) return sources def resolve(self, url): try: h = urlparse.urlparse(url.strip().lower()).netloc oRequest = cRequestHandler(url) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) r = oRequest.request() r = r.rsplit('"underplayer"')[0].rsplit("'underplayer'")[0] u = re.findall('\'(.+?)\'', r) + re.findall('\"(.+?)\"', r) u = [client.replaceHTMLCodes(i) for i in u] u = [i for i in u if i.startswith('http') and not h in i] url = u[-1].encode('utf-8') if 'bit.ly' in url: oRequest = cRequestHandler(url) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) oRequest.request() url = oRequest.getHeaderLocationUrl() elif 'nullrefer.com' in url: url = url.replace('nullrefer.com/?', '') return url except: source_faultlog.logFault(__name__,source_faultlog.tagResolve) return def __search(self, isSerieSearch, titles, year): try: q = self.search_link % titles[0] q = urlparse.urljoin(self.base_link, q) t = [cleantitle.get(i) for i in set(titles) if i] oRequest = cRequestHandler(q) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) r = oRequest.request() links = dom_parser.parse_dom(r, 'tr', attrs={'id': re.compile('coverPreview.+?')}) tds = [dom_parser.parse_dom(i, 'td') for i in links] tuples = [(dom_parser.parse_dom(i[0], 'a')[0], re.findall('>(\d{4})', i[1].content)) for i in tds if 'ger' in i[4].content] tuplesSortByYear = [(i[0].attrs['href'], i[0].content) for i in tuples if year in i[1]] if len(tuplesSortByYear) > 0 and not isSerieSearch: tuples = tuplesSortByYear elif isSerieSearch: tuples = [(i[0].attrs['href'], i[0].content) for i in tuples if "serie" in i[0].content.lower()] else: tuples = [(i[0].attrs['href'], i[0].content) for i in tuples] urls = [i[0] for i in tuples if cleantitle.get(i[1]) in t] if len(urls) == 0: urls = [i[0] for i in tuples if 'untertitel' not in i[1]] if len(urls) > 0: return source_utils.strip_domain(urls[0]) except: try: source_faultlog.logFault(__name__, source_faultlog.tagSearch, titles[0]) except: return return def __get_base_url(self, fallback): try: for domain in self.domains: try: url = 'http://%s' % domain oRequest = cRequestHandler(url) oRequest.removeBreakLines(False) oRequest.removeNewLines(False) r = oRequest.request() r = dom_parser.parse_dom(r, 'meta', attrs={'name': 'author'}, req='content') if r and 'movie4k.io' in r[0].attrs.get('content').lower(): return url except: pass except: pass return fallback
lastship/plugin.video.lastship
resources/lib/sources/de/movie4k.py
Python
gpl-3.0
8,599
var interval = setInterval(function () { $("button[type=submit]").hide(); $("p.info").hide(); try { var prompting = loadTXT("/data/status.json"); if (prompting.indexOf("started")>0 || prompting.indexOf("active")>0 ) { $("button[type=submit]").show(); $("p.warning").hide(); $("p.info").show(); clearInterval(interval); } } catch (e) { // Silently quit } }, 1000);
opendomo/OpenDomoOS
src/odbase/var/www/scripts/wizFirstConfigurationStep5.sh.js
JavaScript
gpl-3.0
389