repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
JpressProjects/jpress
jpress-web/src/main/java/io/jpress/web/admin/_WechatController.java
8511
/** * Copyright (c) 2016-2020, Michael Yang 杨福海 (fuhai999@gmail.com). * <p> * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl-3.0.txt * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jpress.web.admin; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.jfinal.aop.Inject; import com.jfinal.kit.Ret; import com.jfinal.plugin.activerecord.Page; import com.jfinal.weixin.sdk.api.ApiResult; import io.jboot.web.controller.annotation.RequestMapping; import io.jboot.web.validate.EmptyValidate; import io.jboot.web.validate.Form; import io.jboot.wechat.WechatApis; import io.jpress.JPressConsts; import io.jpress.commons.layer.SortKit; import io.jpress.core.menu.annotation.AdminMenu; import io.jpress.core.wechat.WechatAddonInfo; import io.jpress.core.wechat.WechatAddonManager; import io.jpress.model.WechatMenu; import io.jpress.model.WechatReply; import io.jpress.service.OptionService; import io.jpress.service.WechatMenuService; import io.jpress.service.WechatReplyService; import io.jpress.web.base.AdminControllerBase; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Michael Yang 杨福海 (fuhai999@gmail.com) * @version V1.0 * @Title: 首页 * @Package io.jpress.web.admin */ @RequestMapping(value = "/admin/wechat", viewPath = JPressConsts.DEFAULT_ADMIN_VIEW) public class _WechatController extends AdminControllerBase { @Inject private WechatReplyService replyService; @Inject private OptionService optionService; @Inject private WechatMenuService wechatMenuService; @AdminMenu(text = "默认回复", groupId = JPressConsts.SYSTEM_MENU_WECHAT_PUBULIC_ACCOUNT, order = 1) public void reply() { render("wechat/reply_base.html"); } @AdminMenu(text = "自动回复", groupId = JPressConsts.SYSTEM_MENU_WECHAT_PUBULIC_ACCOUNT, order = 2) public void keyword() { Page<WechatReply> page = replyService._paginate(getPagePara(), 10, getPara("keyword"), getPara("content")); setAttr("page", page); render("wechat/reply_list.html"); } @AdminMenu(text = "运营插件", groupId = JPressConsts.SYSTEM_MENU_WECHAT_PUBULIC_ACCOUNT, order = 5) public void addons() { List<WechatAddonInfo> wechatAddons = WechatAddonManager.me().getWechatAddons(); setAttr("wechatAddons", wechatAddons); render("wechat/addons.html"); } @AdminMenu(text = "菜单设置", groupId = JPressConsts.SYSTEM_MENU_WECHAT_PUBULIC_ACCOUNT, order = 12) public void menu() { List<WechatMenu> menus = wechatMenuService.findAll(); SortKit.toLayer(menus); setAttr("menus", menus); int id = getParaToInt(0, 0); if (id > 0) { for (WechatMenu menu : menus) { if (menu.getId() == id) { setAttr("menu", menu); } } } render("wechat/menu.html"); } @AdminMenu(text = "基础设置", groupId = JPressConsts.SYSTEM_MENU_WECHAT_PUBULIC_ACCOUNT, order = 21) public void base() { render("wechat/setting_base.html"); } @AdminMenu(text = "小程序", groupId = JPressConsts.SYSTEM_MENU_WECHAT_PUBULIC_ACCOUNT, order = 99) public void miniprogram() { render("wechat/miniprogram.html"); } public void doDelReply() { Long id = getIdPara(); replyService.deleteById(id); renderOkJson(); } @EmptyValidate(@Form(name = "ids")) public void doDelReplyByIds() { Set<String> idsSet = getParaSet("ids"); render(replyService.deleteByIds(idsSet.toArray()) ? OK : FAIL); } public void doEnableAddon(String id) { WechatAddonManager.me().doEnableAddon(id); renderOkJson(); } public void doCloseAddon(String id) { WechatAddonManager.me().doCloseAddon(id); renderOkJson(); } public void keywordWrite() { int id = getParaToInt(0, 0); WechatReply wechatReply = id > 0 ? replyService.findById(id) : null; setAttr("reply", wechatReply); Map map = wechatReply == null ? new HashMap<>() : wechatReply.getOptionMap(); setAttr("option", map); render("wechat/reply_write.html"); } @EmptyValidate({ @Form(name = "keyword", message = "关键字不能为空"), }) public void doReplySave() { WechatReply reply = getBean(WechatReply.class, ""); Map<String, String> map = getParas(); if (map != null) { for (Map.Entry<String, String> e : map.entrySet()) { if (e.getKey() != null && e.getKey().startsWith("option.")) { reply.putOption(e.getKey().substring(7), e.getValue()); } } } WechatReply existModel = replyService.findByKey(reply.getKeyword()); if (existModel != null && !existModel.getId().equals(reply.getId())){ renderFailJson("已经存在该关键字了"); return; } replyService.saveOrUpdate(reply); renderOkJson(); } @EmptyValidate({ @Form(name = "menu.text", message = "菜单名称不能为空"), @Form(name = "menu.keyword", message = "菜单关键字不能为空"), }) public void doMenuSave() { WechatMenu menu = getModel(WechatMenu.class, "menu"); wechatMenuService.saveOrUpdate(menu); renderOkJson(); } public void doMenuDel() { wechatMenuService.deleteById(getParaToLong()); renderOkJson(); } /** * 微信菜单同步 */ public void doMenuSync() { List<WechatMenu> wechatMenus = wechatMenuService.findAll(); SortKit.toTree(wechatMenus); if (wechatMenus == null || wechatMenus.isEmpty()) { renderJson(Ret.fail().set("message", "微信菜单为空")); return; } JSONArray button = new JSONArray(); for (WechatMenu wechatMenu : wechatMenus) { if (wechatMenu.hasChild()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", wechatMenu.getText()); List<WechatMenu> childMenus = wechatMenu.getChilds(); JSONArray sub_buttons = new JSONArray(); for (WechatMenu child : childMenus) { createJsonObjectButton(sub_buttons, child); } jsonObject.put("sub_button", sub_buttons); button.add(jsonObject); } else { createJsonObjectButton(button, wechatMenu); } } JSONObject wechatMenuJson = new JSONObject(); wechatMenuJson.put("button", button); String jsonString = wechatMenuJson.toJSONString(); ApiResult result = WechatApis.createMenu(jsonString); if (result.isSucceed()) { renderJson(Ret.ok().set("message", "微信菜单同步成功")); } else { renderJson(Ret.fail().set("message", "错误码:" + result.getErrorCode() + "," + result.getErrorMsg())); } } private void createJsonObjectButton(JSONArray button, WechatMenu content) { JSONObject jsonObject = new JSONObject(); jsonObject.put("type", content.getType()); jsonObject.put("name", content.getText()); //跳转网页 if ("view".equals(content.getType())) { jsonObject.put("url", content.getKeyword()); } //跳转微信小程序 else if ("miniprogram".equals(content.getType())) { String[] appIdAndPage = content.getKeyword().split(":"); jsonObject.put("appid", appIdAndPage[0]); jsonObject.put("pagepath", appIdAndPage[1]); jsonObject.put("url", getBaseUrl()); } //其他 else { jsonObject.put("key", content.getKeyword()); } button.add(jsonObject); } }
lgpl-3.0
SirmaITT/conservation-space-1.7.0
docker/sep-ui/src/administration/model-management/services/model-management-route-interrupter.js
871
import {Injectable, Inject} from 'app/app'; import {RouteInterrupter} from 'adapters/router/route-interrupter'; import {ModelManagementStateRegistry} from 'administration/model-management/services/model-management-state-registry'; import {MODEL_MANAGEMENT_EXTENSION_POINT} from 'administration/model-management/model-management'; /** * Prevents navigation when there are unsaved changes in the model management page. * * @author Mihail Radkov */ @Injectable() @Inject(ModelManagementStateRegistry) export class ModelManagementRouteInterrupter extends RouteInterrupter { constructor(modelManagementStateRegistry) { super(); this.modelManagementStateRegistry = modelManagementStateRegistry; } shouldInterrupt(router) { return router.getCurrentState() === MODEL_MANAGEMENT_EXTENSION_POINT && this.modelManagementStateRegistry.hasDirtyState(); } }
lgpl-3.0
tedconf/propel-unofficial
runtime/classes/propel/adapter/DBMSSQL.php
6008
<?php /* * $Id$ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under version 3 of the LGPL. For more information please see * <http://propel.phpdb.org>. */ /** * This is used to connect to a MSSQL database. * * @author Hans Lellelid <hans@xmpl.org> (Propel) * @version $Revision$ * @package propel.adapter */ class DBMSSQL extends DBAdapter { /** * This method is used to ignore case. * * @param in The string to transform to upper case. * @return The upper case string. */ public function toUpperCase($in) { return "UPPER(" . $in . ")"; } /** * This method is used to ignore case. * * @param in The string whose case to ignore. * @return The string in a case that can be ignored. */ public function ignoreCase($in) { return "UPPER(" . $in . ")"; } /** * Returns SQL which concatenates the second string to the first. * * @param string String to concatenate. * @param string String to append. * @return string */ public function concatString($s1, $s2) { return "($s1 + $s2)"; } /** * Returns SQL which extracts a substring. * * @param string String to extract from. * @param int Offset to start from. * @param int Number of characters to extract. * @return string */ public function subString($s, $pos, $len) { return "SUBSTRING($s, $pos, $len)"; } /** * Returns SQL which calculates the length (in chars) of a string. * * @param string String to calculate length of. * @return string */ public function strLength($s) { return "LEN($s)"; } /** * @see DBAdapter::quoteIdentifier() */ public function quoteIdentifier($text) { return '[' . $text . ']'; } /** * @see DBAdapter::random() */ public function random($seed = null) { return 'rand('.((int) $seed).')'; } /** * Simulated Limit/Offset * This rewrites the $sql query to apply the offset and limit. * @see DBAdapter::applyLimit() * @author Justin Carlson <justin.carlson@gmail.com> */ public function applyLimit(&$sql, $offset, $limit) { // make sure offset and limit are numeric if (!is_numeric($offset) || !is_numeric($limit)){ throw new Exception("DBMSSQL ::applyLimit() expects a number for argument 2 and 3"); } // obtain the original select statement preg_match('/\A(.*)select(.*)from/si',$sql,$select_segment); if (count($select_segment)>0) { $original_select = $select_segment[0]; } else { throw new Exception("DBMSSQL ::applyLimit() could not locate the select statement at the start of the query. "); } $modified_select = substr_replace($original_select, null, stristr($original_select,'select') , 6 ); // obtain the original order by clause, or create one if there isn't one preg_match('/order by(.*)\Z/si',$sql,$order_segment); if (count($order_segment)>0) { $order_by = $order_segment[0]; } else { // no order by clause, if there are columns we can attempt to sort by the columns in the select statement $select_items = split(',',$modified_select); if (count($select_items)>0) { $item_number = 0; $order_by = null; while ($order_by === null && $item_number<count($select_items)) { if ($select_items[$item_number]!='*' && !strstr($select_items[$item_number],'(')) { $order_by = 'order by ' . $select_items[0] . ' asc'; } $item_number++; } } if ($order_by === null) { throw new Exception("DBMSSQL ::applyLimit() could not locate the order by statement at the end of your query or any columns at the start of your query. "); } else { $sql.= ' ' . $order_by; } } // remove the original select statement $sql = str_replace($original_select , null, $sql); /* modify the sort order by for paging */ $inverted_order = ''; $order_columns = split(',',str_ireplace('order by ','',$order_by)); $original_order_by = $order_by; $order_by = ''; foreach ($order_columns as $column) { // strip "table." from order by columns $column = array_reverse(split("\.",$column)); $column = $column[0]; // commas if we have multiple sort columns if (strlen($inverted_order)>0){ $order_by.= ', '; $inverted_order.=', '; } // put together order for paging wrapper if (stristr($column,' desc')) { $order_by .= $column; $inverted_order .= str_ireplace(' desc',' asc',$column); } elseif (stristr($column,' asc')) { $order_by .= $column; $inverted_order .= str_ireplace(' asc',' desc',$column); } else { $order_by .= $column; $inverted_order .= $column .' desc'; } } $order_by = 'order by ' . $order_by; $inverted_order = 'order by ' . $inverted_order; // build the query $offset = ($limit+$offset); $modified_sql = 'select * from ('; $modified_sql.= 'select top '.$limit.' * from ('; $modified_sql.= 'select top '.$offset.' '.$modified_select.$sql; $modified_sql.= ') deriveda '.$inverted_order.') derivedb '.$order_by; $sql = $modified_sql; } }
lgpl-3.0
AndreasTruetschel/AsyncEnumerable
src/AsyncEnumerable/AsyncEnumerable.cs
6172
/* Copyright (C) 2017 Andreas Trütschel * * 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 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 LESSER GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Dieses Programm ist Freie Software: Sie können es unter den Bedingungen * der GNU LESSER GENERAL PUBLIC LICENSE, wie von der Free Software Foundation veröffentlicht, * in Version 3 der Lizenz oder (nach Ihrer Wahl) jeder neueren * veröffentlichten Version, weiterverbreiten und/oder modifizieren. * Dieses Programm wird in der Hoffnung, dass es nützlich sein wird, aber * OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite * Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. * Siehe in die GNU LESSER GENERAL PUBLIC LICENSE für weitere Details. * * Sie sollten eine Kopie der GNU LESSER GENERAL PUBLIC LICENSE zusammen mit diesem * Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace AsyncEnumerable { public static partial class AsyncEnumerable { #if VS2015 private static async Task<IEnumerable<TSource>> Evaluate<TSource>(IAsyncEnumerable<TSource> source) { List<TSource> list = new List<TSource>(); using (var enumerator = source.GetAsyncEnumerator()) { Debug.Assert(enumerator != null); while (await enumerator.MoveNext()) { var item = enumerator.Current; list.Add(item); } } return list; } #endif public static TaskAwaiter<IEnumerable<TSource>> GetAwaiter<TSource>(this IAsyncEnumerable<TSource> source) { #if VS2015 { SynchronousEnumerable<TSource> sync = source as SynchronousEnumerable<TSource>; if (sync != null) { return Task.FromResult(sync._source).GetAwaiter(); } } #else if (source is SynchronousEnumerable<TSource> sync) { return Task.FromResult(sync._source).GetAwaiter(); } #endif if (source == null) throw new ArgumentNullException(nameof(source)); #if !VS2015 async Task<IEnumerable<TSource>> Evaluate() { List<TSource> list = new List<TSource>(); using (var enumerator = source.GetAsyncEnumerator()) { Debug.Assert(enumerator != null); while (await enumerator.MoveNext()) { var item = enumerator.Current; list.Add(item); } } return list; } return Evaluate().GetAwaiter(); #else return Evaluate(source).GetAwaiter(); #endif } public static IAsyncEnumerable<TSource> AsEnumerable<TSource>(this IAsyncEnumerable<TSource> source) { return source; } public static IAsyncEnumerable<TSource> FromSynchronous<TSource>(IEnumerable<TSource> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return new SynchronousEnumerable<TSource>(source); } public static IAsyncEnumerable<TSource> AsAsync<TSource>(this IEnumerable<TSource> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return new SynchronousEnumerable<TSource>(source); } public static IAsyncEnumerable<T> Empty<T>() { return new EmptyAsyncEnumerable<T>(); } private class EmptyAsyncEnumerable<T> : IAsyncEnumerable<T> { private static readonly EmptyAsyncEnumerator _instance = new EmptyAsyncEnumerator(); public IAsyncEnumerator<T> GetAsyncEnumerator() { return _instance; } private class EmptyAsyncEnumerator : IAsyncEnumerator<T> { public T Current => default(T); public void Dispose() { } public Task<bool> MoveNext() => Task.FromResult(false); } } private class SynchronousEnumerable<T> : IAsyncEnumerable<T> { internal readonly IEnumerable<T> _source; public SynchronousEnumerable(IEnumerable<T> source) { Debug.Assert(source != null); _source = source; } public IAsyncEnumerator<T> GetAsyncEnumerator() { return new SynchronousEnumerator(_source.GetEnumerator()); } private class SynchronousEnumerator : IAsyncEnumerator<T> { private readonly IEnumerator<T> _source; public SynchronousEnumerator(IEnumerator<T> source) { Debug.Assert(source != null); _source = source; } public T Current => _source.Current; public void Dispose() { _source.Dispose(); } public Task<bool> MoveNext() { return Task.FromResult(_source.MoveNext()); } } } } }
lgpl-3.0
BigBrotherTeam/BigBrother
src/shoghicp/BigBrother/network/protocol/Play/Client/HeldItemChangePacket.php
1447
<?php /** * ______ __ ______ __ __ * | __ \|__|.-----.| __ \.----..-----.| |_ | |--..-----..----. * | __ <| || _ || __ <| _|| _ || _|| || -__|| _| * |______/|__||___ ||______/|__| |_____||____||__|__||_____||__| * |_____| * * BigBrother plugin for PocketMine-MP * Copyright (C) 2014-2015 shoghicp <https://github.com/shoghicp/BigBrother> * Copyright (C) 2016- BigBrotherTeam * * 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 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. * * @author BigBrotherTeam * @link https://github.com/BigBrotherTeam/BigBrother * */ declare(strict_types=1); namespace shoghicp\BigBrother\network\protocol\Play\Client; use shoghicp\BigBrother\network\InboundPacket; class HeldItemChangePacket extends InboundPacket{ /** @var int */ public $selectedSlot; public function pid() : int{ return self::HELD_ITEM_CHANGE_PACKET; } protected function decode() : void{ $this->selectedSlot = $this->getSignedShort(); } }
lgpl-3.0
cismet/cids-custom-sudplan
src/main/java/de/cismet/cids/custom/objecteditors/sudplan/EmissionDatabaseEditor.java
42133
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.cids.custom.objecteditors.sudplan; import Sirius.navigator.connection.SessionManager; import Sirius.navigator.ui.ComponentRegistry; import Sirius.server.middleware.types.MetaClass; import com.vividsolutions.jts.geom.Geometry; import org.apache.log4j.Logger; import org.jdesktop.swingx.JXErrorPane; import org.jdesktop.swingx.error.ErrorInfo; import org.openide.util.NbBundle; import java.awt.EventQueue; import java.util.Collection; import java.util.List; import java.util.logging.Level; import javax.swing.DefaultListSelectionModel; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.text.AbstractDocument; import de.cismet.cids.custom.sudplan.AbstractCidsBeanRenderer; import de.cismet.cids.custom.sudplan.airquality.emissionupload.EmissionUpload; import de.cismet.cids.custom.sudplan.airquality.emissionupload.EmissionUploadDialog; import de.cismet.cids.custom.sudplan.airquality.emissionupload.EmissionUploadVisualPanelEmissionScenario; import de.cismet.cids.custom.sudplan.airquality.emissionupload.EmissionUploadWizardAction; import de.cismet.cids.custom.sudplan.airquality.emissionupload.GridHeight; import de.cismet.cids.custom.sudplan.airquality.emissionupload.Substance; import de.cismet.cids.custom.sudplan.airquality.emissionupload.TimeVariation; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cids.editors.EditorClosedEvent; import de.cismet.cids.editors.EditorSaveListener; import de.cismet.cids.navigator.utils.ClassCacheMultiple; import de.cismet.tools.Converter; import de.cismet.tools.gui.StaticSwingTools; import de.cismet.tools.gui.TitleComponentProvider; import de.cismet.tools.gui.downloadmanager.ByteArrayDownload; import de.cismet.tools.gui.downloadmanager.DownloadManager; import de.cismet.tools.gui.downloadmanager.DownloadManagerDialog; /** * DOCUMENT ME! * * @author jweintraut * @version $Revision$, $Date$ */ public class EmissionDatabaseEditor extends AbstractCidsBeanRenderer implements EditorSaveListener, TitleComponentProvider { //~ Static fields/initializers --------------------------------------------- private static final transient Logger LOG = Logger.getLogger(EmissionDatabaseEditor.class); //~ Instance fields -------------------------------------------------------- private final transient boolean editable; private Object recentlySelectedEmissionGrid; private final transient SilentSelectionModel silentSelectionModel; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAdd; private javax.swing.JButton btnCopy; private javax.swing.JButton btnDownload; private javax.swing.JButton btnRemove; private javax.swing.JButton btnSave; private javax.swing.JButton btnUpload; private javax.swing.JLabel lblDescription; private javax.swing.JLabel lblEmissionGrids; private javax.swing.JLabel lblGeneralInformation; private javax.swing.JLabel lblName; private javax.swing.JLabel lblSRS; private javax.swing.JLabel lblTitle; private javax.swing.JList lstEmissionGrids; private javax.swing.JPanel pnlControls; private de.cismet.cids.custom.objecteditors.sudplan.EmissionDatabaseGridEditor pnlEmissionGrid; private javax.swing.JPanel pnlTitle; private de.cismet.tools.gui.RoundedPanel rpEmissionGrids; private de.cismet.tools.gui.RoundedPanel rpGeneralInformation; private javax.swing.JScrollPane scpDescription; private javax.swing.JScrollPane scpEmissionGrids; private de.cismet.tools.gui.SemiRoundedPanel srpEmissionGrids; private de.cismet.tools.gui.SemiRoundedPanel srpGeneralInformation; private javax.swing.Box.Filler strControls; private javax.swing.JTextArea txaDescription; private javax.swing.JTextField txtName; private javax.swing.JTextField txtSRS; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables //~ Constructors ----------------------------------------------------------- /** * Creates new form EmissionDatabaseEditor. */ public EmissionDatabaseEditor() { this(true); } /** * Creates a new EmissionDatabaseEditor object. * * @param editable DOCUMENT ME! */ public EmissionDatabaseEditor(final boolean editable) { this.editable = editable; silentSelectionModel = new SilentSelectionModel(); initComponents(); if (editable) { ((AbstractDocument)txtName.getDocument()).setDocumentFilter( new EmissionUploadVisualPanelEmissionScenario.EmissionScenarioNameFilter()); } txtName.setEditable(editable); txtSRS.setEditable(editable); txaDescription.setEditable(editable); btnAdd.setEnabled(editable); } //~ Methods ---------------------------------------------------------------- /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The * content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); pnlTitle = new javax.swing.JPanel(); lblTitle = new javax.swing.JLabel(); btnUpload = new javax.swing.JButton(); btnCopy = new javax.swing.JButton(); btnDownload = new javax.swing.JButton(); rpGeneralInformation = new de.cismet.tools.gui.RoundedPanel(); srpGeneralInformation = new de.cismet.tools.gui.SemiRoundedPanel(); lblGeneralInformation = new javax.swing.JLabel(); lblName = new javax.swing.JLabel(); scpDescription = new javax.swing.JScrollPane(); txaDescription = new javax.swing.JTextArea(); lblSRS = new javax.swing.JLabel(); txtSRS = new javax.swing.JTextField(); lblDescription = new javax.swing.JLabel(); txtName = new javax.swing.JTextField(); rpEmissionGrids = new de.cismet.tools.gui.RoundedPanel(); srpEmissionGrids = new de.cismet.tools.gui.SemiRoundedPanel(); lblEmissionGrids = new javax.swing.JLabel(); scpEmissionGrids = new javax.swing.JScrollPane(); lstEmissionGrids = new javax.swing.JList(); pnlControls = new javax.swing.JPanel(); btnAdd = new javax.swing.JButton(); btnRemove = new javax.swing.JButton(); strControls = new javax.swing.Box.Filler(new java.awt.Dimension(100, 0), new java.awt.Dimension(100, 0), new java.awt.Dimension(32767, 32767)); btnSave = new javax.swing.JButton(); pnlEmissionGrid = new EmissionDatabaseGridEditor(editable); pnlTitle.setOpaque(false); pnlTitle.setLayout(new java.awt.GridBagLayout()); lblTitle.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N lblTitle.setForeground(java.awt.Color.white); lblTitle.setText(org.openide.util.NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.lblTitle.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlTitle.add(lblTitle, gridBagConstraints); btnUpload.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/sudplan/airquality/emissionupload/upload_16.png"))); // NOI18N btnUpload.setToolTipText(org.openide.util.NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.btnUpload.toolTipText")); // NOI18N btnUpload.setBorderPainted(false); btnUpload.setContentAreaFilled(false); btnUpload.setFocusPainted(false); btnUpload.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnUploadActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlTitle.add(btnUpload, gridBagConstraints); btnCopy.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/sudplan/airquality/emissionupload/copy_16.png"))); // NOI18N btnCopy.setToolTipText(org.openide.util.NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.btnCopy.toolTipText")); // NOI18N btnCopy.setBorderPainted(false); btnCopy.setContentAreaFilled(false); btnCopy.setFocusPainted(false); btnCopy.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnCopyActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlTitle.add(btnCopy, gridBagConstraints); btnDownload.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/sudplan/airquality/emissionupload/download_16.png"))); // NOI18N btnDownload.setToolTipText(org.openide.util.NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.btnDownload.toolTipText")); // NOI18N btnDownload.setBorderPainted(false); btnDownload.setContentAreaFilled(false); btnDownload.setFocusPainted(false); btnDownload.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnDownloadActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlTitle.add(btnDownload, gridBagConstraints); setLayout(new java.awt.GridBagLayout()); rpGeneralInformation.setLayout(new java.awt.GridBagLayout()); srpGeneralInformation.setBackground(java.awt.Color.black); srpGeneralInformation.setLayout(new java.awt.GridBagLayout()); lblGeneralInformation.setBackground(new java.awt.Color(0, 0, 0)); lblGeneralInformation.setForeground(new java.awt.Color(255, 255, 255)); lblGeneralInformation.setText(org.openide.util.NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.lblGeneralInformation.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); srpGeneralInformation.add(lblGeneralInformation, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; rpGeneralInformation.add(srpGeneralInformation, gridBagConstraints); lblName.setText(org.openide.util.NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.lblName.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); rpGeneralInformation.add(lblName, gridBagConstraints); txaDescription.setColumns(20); txaDescription.setRows(5); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.description}"), txaDescription, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); scpDescription.setViewportView(txaDescription); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(5, 5, 10, 10); rpGeneralInformation.add(scpDescription, gridBagConstraints); lblSRS.setText(org.openide.util.NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.lblSRS.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); rpGeneralInformation.add(lblSRS, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.srs}"), txtSRS, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); rpGeneralInformation.add(txtSRS, gridBagConstraints); lblDescription.setText(org.openide.util.NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.lblDescription.text")); // NOI18N lblDescription.setVerticalAlignment(javax.swing.SwingConstants.TOP); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(5, 10, 10, 5); rpGeneralInformation.add(lblDescription, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.name}"), txtName, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); rpGeneralInformation.add(txtName, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.3; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0); add(rpGeneralInformation, gridBagConstraints); rpEmissionGrids.setLayout(new java.awt.GridBagLayout()); srpEmissionGrids.setBackground(java.awt.Color.black); srpEmissionGrids.setForeground(java.awt.Color.white); srpEmissionGrids.setLayout(new java.awt.GridBagLayout()); lblEmissionGrids.setForeground(java.awt.Color.white); lblEmissionGrids.setText(org.openide.util.NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.lblEmissionGrids.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); srpEmissionGrids.add(lblEmissionGrids, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; rpEmissionGrids.add(srpEmissionGrids, gridBagConstraints); lstEmissionGrids.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); lstEmissionGrids.setSelectionModel(silentSelectionModel); final org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create( "${cidsBean.grids}"); final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings .createJListBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstEmissionGrids); bindingGroup.addBinding(jListBinding); lstEmissionGrids.addListSelectionListener(new javax.swing.event.ListSelectionListener() { @Override public void valueChanged(final javax.swing.event.ListSelectionEvent evt) { lstEmissionGridsValueChanged(evt); } }); scpEmissionGrids.setViewportView(lstEmissionGrids); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); rpEmissionGrids.add(scpEmissionGrids, gridBagConstraints); pnlControls.setOpaque(false); pnlControls.setLayout(new java.awt.GridBagLayout()); btnAdd.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/sudplan/airquality/emissionupload/edit_add.png"))); // NOI18N btnAdd.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnAddActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); pnlControls.add(btnAdd, gridBagConstraints); btnRemove.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/sudplan/airquality/emissionupload/edit_remove.png"))); // NOI18N btnRemove.setEnabled(false); btnRemove.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnRemoveActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0); pnlControls.add(btnRemove, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; pnlControls.add(strControls, gridBagConstraints); btnSave.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/sudplan/airquality/emissionupload/edit_save.png"))); // NOI18N btnSave.setEnabled(false); btnSave.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnSaveActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); pnlControls.add(btnSave, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(5, 10, 10, 5); rpEmissionGrids.add(pnlControls, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.1; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); rpEmissionGrids.add(pnlEmissionGrid, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weighty = 0.7; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0); add(rpEmissionGrids, gridBagConstraints); bindingGroup.bind(); } // </editor-fold>//GEN-END:initComponents /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void lstEmissionGridsValueChanged(final javax.swing.event.ListSelectionEvent evt) { //GEN-FIRST:event_lstEmissionGridsValueChanged if (evt.getValueIsAdjusting()) { return; } if (lstEmissionGrids.getSelectedValue() instanceof CidsBean) { if (pnlEmissionGrid.isDirty()) { final int userDecision = JOptionPane.showConfirmDialog( ComponentRegistry.getRegistry().getMainWindow(), java.util.ResourceBundle.getBundle("de/cismet/cids/custom/objecteditors/sudplan/Bundle") .getString( "EmissionDatabaseEditor.lstEmissionGridsValueChanged(ListSelectionEvent).JOptionPane.message"), java.util.ResourceBundle.getBundle("de/cismet/cids/custom/objecteditors/sudplan/Bundle") .getString( "EmissionDatabaseEditor.lstEmissionGridsValueChanged(ListSelectionEvent).JOptionPane.title"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (userDecision == JOptionPane.CANCEL_OPTION) { silentSelectionModel.setIsSilent(true); lstEmissionGrids.setSelectedValue(recentlySelectedEmissionGrid, true); silentSelectionModel.setIsSilent(false); return; } if (userDecision == JOptionPane.YES_OPTION) { pnlEmissionGrid.persistDisplayedEmissionGrid(); } } pnlEmissionGrid.setCidsBean((CidsBean)lstEmissionGrids.getSelectedValue(), (Boolean)cidsBean.getProperty("uploaded")); // NOI18N } else { pnlEmissionGrid.setCidsBean(null); } recentlySelectedEmissionGrid = lstEmissionGrids.getSelectedValue(); btnRemove.setEnabled(editable && (lstEmissionGrids.getSelectedValue() instanceof CidsBean)); btnSave.setEnabled(editable && (lstEmissionGrids.getSelectedValue() instanceof CidsBean)); } //GEN-LAST:event_lstEmissionGridsValueChanged /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnUploadActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnUploadActionPerformed if (cidsBean == null) { return; } final Object uploadedObj = cidsBean.getProperty("uploaded"); // NOI18N final Boolean uploaded; if (uploadedObj instanceof Boolean) { uploaded = (Boolean)uploadedObj; } else { uploaded = Boolean.FALSE; } if (uploaded) { return; } try { cidsBean.setProperty("file", Converter.toString(EmissionUpload.zip(cidsBean))); // NOI18N cidsBean.persist(); } catch (final Exception ex) { LOG.warn("Couldn't generate zip file for emission database.", ex); // NOI18N return; } final EmissionUploadDialog uploadDialog = new EmissionUploadDialog(ComponentRegistry.getRegistry() .getMainWindow(), cidsBean); uploadDialog.pack(); StaticSwingTools.showDialog(uploadDialog); uploadDialog.toFront(); } //GEN-LAST:event_btnUploadActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnRemoveActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnRemoveActionPerformed final List<CidsBean> grids = cidsBean.getBeanCollectionProperty("grids"); // NOI18N grids.remove((CidsBean)lstEmissionGrids.getSelectedValue()); } //GEN-LAST:event_btnRemoveActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnAddActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnAddActionPerformed final String gridName = JOptionPane.showInputDialog( ComponentRegistry.getRegistry().getMainWindow(), NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.btnAddActionPerformed(ActionEvent).JOptionPane.message"), NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.btnAddActionPerformed(ActionEvent).JOptionPane.title"), JOptionPane.QUESTION_MESSAGE); if ((gridName == null) || gridName.trim().isEmpty()) { return; } final MetaClass metaClassEmissionDatabaseGrid; try { metaClassEmissionDatabaseGrid = ClassCacheMultiple.getMetaClass(SessionManager.getSession().getUser() .getDomain(), EmissionUploadWizardAction.TABLENAME_EMISSION_DATABASE_GRID); } catch (final Exception ex) { final String errorMessage = "The meta classes can't be retrieved."; // NOI18N LOG.warn(errorMessage, ex); try { final ErrorInfo errorInfo = new ErrorInfo( "Error", // NOI18N "Couldn't add a new emission database.", // NOI18N errorMessage, "ERROR", // NOI18N ex, Level.SEVERE, null); EventQueue.invokeAndWait(new Runnable() { @Override public void run() { JXErrorPane.showDialog(EmissionDatabaseEditor.this, errorInfo); } }); } catch (final Exception ex1) { LOG.error("Can't display error dialog", ex1); // NOI18N } return; } try { final CidsBean grid = metaClassEmissionDatabaseGrid.getEmptyInstance().getBean(); grid.setProperty("name", gridName); // NOI18N grid.setProperty("substance", Substance.NOX.getRepresentationFile()); // NOI18N grid.setProperty("timevariation", TimeVariation.CONSTANT.getRepresentationFile()); // NOI18N grid.setProperty("height", GridHeight.ZERO.getRepresentationFile()); // NOI18N cidsBean.getBeanCollectionProperty("grids").add(grid); // NOI18N } catch (final Exception ex) { final String errorMessage = "Something went wrong while initializing a new emission grid."; // NOI18N LOG.warn(errorMessage, ex); try { final ErrorInfo errorInfo = new ErrorInfo( "Error", // NOI18N "Couldn't add a new emission database.", // NOI18N errorMessage, "ERROR", // NOI18N ex, Level.SEVERE, null); EventQueue.invokeAndWait(new Runnable() { @Override public void run() { JXErrorPane.showDialog(EmissionDatabaseEditor.this, errorInfo); } }); } catch (final Exception ex1) { LOG.error("Can't display error dialog", ex1); // NOI18N } } } //GEN-LAST:event_btnAddActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnSaveActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnSaveActionPerformed pnlEmissionGrid.persistDisplayedEmissionGrid(); } //GEN-LAST:event_btnSaveActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnCopyActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnCopyActionPerformed final String name = JOptionPane.showInputDialog( ComponentRegistry.getRegistry().getMainWindow(), NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.btnCopyActionPerformed(ActionEvent).JOptionPane.message"), // NOI18N NbBundle.getMessage( EmissionDatabaseEditor.class, "EmissionDatabaseEditor.btnCopyActionPerformed(ActionEvent).JOptionPane.title"), // NOI18N JOptionPane.QUESTION_MESSAGE); if ((name == null) || name.trim().isEmpty()) { LOG.info("User aborted creation of a new emission database."); // NOI18N } final CidsBean newBean; try { newBean = cloneCidsBean(cidsBean, true); newBean.setProperty("name", name); // NOI18N newBean.setProperty("uploaded", Boolean.FALSE); // NOI18N newBean.persist(); } catch (final Exception ex) { final String errorMessage = "Couldn't clone CidsBean."; // NOI18N LOG.error(errorMessage, ex); try { final ErrorInfo errorInfo = new ErrorInfo( "Error", // NOI18N "The emission database couldn't be copied.", // NOI18N errorMessage, "ERROR", // NOI18N ex, Level.SEVERE, null); EventQueue.invokeAndWait(new Runnable() { @Override public void run() { JXErrorPane.showDialog(EmissionDatabaseEditor.this, errorInfo); } }); } catch (final Exception ex1) { LOG.error("Can't display error dialog", ex1); // NOI18N } return; } ComponentRegistry.getRegistry().getDescriptionPane().gotoMetaObject(newBean.getMetaObject(), ""); // NOI18N ComponentRegistry.getRegistry().getCatalogueTree().requestRefreshNode("airquality.edb"); // NOI18N } //GEN-LAST:event_btnCopyActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnDownloadActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnDownloadActionPerformed byte[] fileContent = null; if ((cidsBean != null) && (cidsBean.getProperty("file") instanceof String)) { // NOI18N fileContent = Converter.fromString((String)cidsBean.getProperty("file")); // NOI18N } else { try { fileContent = EmissionUpload.zip(cidsBean); } catch (Exception ex) { final String errorMessage = "Couldn't zip emission database."; // NOI18N LOG.warn(errorMessage, ex); try { final ErrorInfo errorInfo = new ErrorInfo( "Error", // NOI18N "The emission database couldn't be downloaded.", // NOI18N errorMessage, "WARN", // NOI18N ex, Level.SEVERE, null); EventQueue.invokeAndWait(new Runnable() { @Override public void run() { JXErrorPane.showDialog(EmissionDatabaseEditor.this, errorInfo); } }); } catch (final Exception ex1) { LOG.error("Can't display error dialog", ex1); // NOI18N } } } if ((fileContent == null) || (fileContent.length <= 0)) { LOG.info("Nothing to download for emission database."); // NOI18N // TODO: User feeedback. } if (!DownloadManagerDialog.showAskingForUserTitle(EmissionDatabaseEditor.this)) { return; } final String title; final String filename; if (cidsBean.getProperty("name") instanceof String) { // NOI18N title = (String)cidsBean.getProperty("name"); // NOI18N filename = (String)cidsBean.getProperty("name"); // NOI18N } else { title = "Emission database"; // NOI18N filename = "emissionDatabase"; // NOI18N } DownloadManager.instance() .add( new ByteArrayDownload(fileContent, title, DownloadManagerDialog.getJobname(), filename, ".zip")); // NOI18N } //GEN-LAST:event_btnDownloadActionPerformed @Override protected void init() { bindingGroup.unbind(); btnUpload.setEnabled(false); if (cidsBean != null) { btnUpload.setEnabled((cidsBean.getProperty("uploaded") instanceof Boolean) // NOI18N && !((Boolean)cidsBean.getProperty("uploaded"))); // NOI18N lblTitle.setText((String)cidsBean.getProperty("name")); // NOI18N } bindingGroup.bind(); } @Override public void editorClosed(final EditorClosedEvent event) { // NoOp } @Override public boolean prepareForSave() { if (pnlEmissionGrid.isDirty()) { pnlEmissionGrid.persistDisplayedEmissionGrid(); } return true; } @Override public JComponent getTitleComponent() { return pnlTitle; } @Override public void setTitle(final String title) { super.setTitle(title); lblTitle.setText(title); } /** * DOCUMENT ME! * * @param bean DOCUMENT ME! * @param cloneBeans DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ private static CidsBean cloneCidsBean(final CidsBean bean, final boolean cloneBeans) throws Exception { if (bean == null) { return null; } final CidsBean clone = bean.getMetaObject().getMetaClass().getEmptyInstance().getBean(); for (final String propName : bean.getPropertyNames()) { if (!propName.toLowerCase().equals("id")) { // NOI18N final Object o = bean.getProperty(propName); if (o instanceof CidsBean) { if (cloneBeans) { clone.setProperty(propName, cloneCidsBean((CidsBean)o, true)); } else { clone.setProperty(propName, (CidsBean)o); } } else if (o instanceof Collection) { final List<CidsBean> list = (List<CidsBean>)o; final List<CidsBean> newList = clone.getBeanCollectionProperty(propName); for (final CidsBean tmpBean : list) { if (cloneBeans) { newList.add(cloneCidsBean(tmpBean, true)); } else { newList.add(tmpBean); } } } else if (o instanceof Geometry) { clone.setProperty(propName, ((Geometry)o).clone()); } else if (o instanceof Long) { clone.setProperty(propName, new Long(o.toString())); } else if (o instanceof Double) { clone.setProperty(propName, new Double(o.toString())); } else if (o instanceof Integer) { clone.setProperty(propName, new Integer(o.toString())); } else if (o instanceof Boolean) { clone.setProperty(propName, new Boolean(o.toString())); } else if (o instanceof String) { clone.setProperty(propName, o); } else { if (o != null) { LOG.error("Unknown property type '" + o.getClass().getName() + "' of property '" + propName + "'."); // NOI18N } clone.setProperty(propName, o); } } } return clone; } //~ Inner Classes ---------------------------------------------------------- /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private static class SilentSelectionModel extends DefaultListSelectionModel { //~ Instance fields ---------------------------------------------------- private boolean isSilent = false; //~ Methods ------------------------------------------------------------ /** * DOCUMENT ME! * * @param isSilent DOCUMENT ME! */ public void setIsSilent(final boolean isSilent) { this.isSilent = isSilent; } @Override protected void fireValueChanged(final int firstIndex, final int lastIndex, final boolean isAdjusting) { if (isSilent) { return; } super.fireValueChanged(firstIndex, lastIndex, isAdjusting); } } }
lgpl-3.0
Builders-SonarSource/sonarqube-bis
server/sonar-server/src/test/java/org/sonar/server/computation/task/projectanalysis/issue/commonrule/LineCoverageRuleTest.java
2003
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.computation.task.projectanalysis.issue.commonrule; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.rule.RuleKey; import org.sonar.server.rule.CommonRuleKeys; public class LineCoverageRuleTest extends CoverageRuleTest { @Override protected CommonRule createRule() { return new LineCoverageRule(activeRuleHolder, metricRepository, measureRepository); } @Override protected RuleKey getRuleKey() { return RuleKey.of("common-java", CommonRuleKeys.INSUFFICIENT_LINE_COVERAGE); } @Override protected String getMinPropertyKey() { return CommonRuleKeys.INSUFFICIENT_LINE_COVERAGE_PROPERTY; } @Override protected String getCoverageMetricKey() { return CoreMetrics.LINE_COVERAGE_KEY; } @Override protected String getToCoverMetricKey() { return CoreMetrics.LINES_TO_COVER_KEY; } @Override protected String getUncoveredMetricKey() { return CoreMetrics.UNCOVERED_LINES_KEY; } @Override protected String getExpectedIssueMessage() { return "23 more lines of code need to be covered by tests to reach the minimum threshold of 65.0% lines coverage."; } }
lgpl-3.0
DavidS/MailSystem.NET
Samples/CS/ActiveUp.Net.Samples/Properties/Settings.Designer.cs
1101
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.4927 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ActiveUp.Net.Samples.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
lgpl-3.0
zenframework/z8
org.zenframework.z8.pde/src/main/java/org/zenframework/z8/pde/editor/ContentOutlinePage.java
10285
package org.zenframework.z8.pde.editor; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; import org.zenframework.z8.compiler.core.ILanguageElement; import org.zenframework.z8.compiler.core.IMethod; import org.zenframework.z8.compiler.core.ISource; import org.zenframework.z8.compiler.core.IType; import org.zenframework.z8.compiler.core.IVariable; import org.zenframework.z8.compiler.workspace.CompilationUnit; import org.zenframework.z8.compiler.workspace.Resource; import org.zenframework.z8.compiler.workspace.ResourceListener; import org.zenframework.z8.compiler.workspace.Workspace; import org.zenframework.z8.pde.navigator.Z8LabelProvider; import org.zenframework.z8.pde.navigator.ISourceProvider; import org.zenframework.z8.pde.navigator.NavigatorTreeContentProvider; import org.zenframework.z8.pde.refactoring.LanguageElementImageProvider; import org.zenframework.z8.pde.source.InitHelper; import org.zenframework.z8.pde.source.MultipleTransactions; import org.zenframework.z8.pde.source.Transaction; @SuppressWarnings("deprecation") public class ContentOutlinePage extends org.eclipse.ui.views.contentoutline.ContentOutlinePage { Menu fMenu; private final ViewerFilter FILTER = new ViewerFilter() { @Override public boolean select(Viewer viewer, Object parentElement, Object element) { if(element instanceof ILanguageElement) { CompilationUnit compilationUnit = ((ILanguageElement)element).getCompilationUnit(); return compilationUnit == m_compilationUnit; } if(element instanceof ISource) { ISource src = (ISource)element; if(src.getCompilationUnit() != m_compilationUnit) return false; } return true; } }; private ITextEditor m_editor; private CompilationUnit m_compilationUnit; private ResourceListener m_listener = new ResourceListener() { @Override public void event(int type, Resource resource, Object object) { if(type == RESOURCE_CHANGED && resource == m_compilationUnit || type == BUILD_COMPLETE) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if(getTreeViewer() != null && !getTreeViewer().getTree().isDisposed()) { getTreeViewer().refresh(); getTreeViewer().expandToLevel(2); } } }); } if(type == RESOURCE_REMOVED && resource == m_compilationUnit) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if(getTreeViewer() != null) { setInput(null); } } }); } } }; public ContentOutlinePage(IDocumentProvider provider, ITextEditor editor) { super(); m_editor = editor; } @Override public void createControl(Composite parent) { super.createControl(parent); Workspace.getInstance().installResourceListener(m_listener); TreeViewer treeViewer = getTreeViewer(); treeViewer.setContentProvider(new NavigatorTreeContentProvider()); treeViewer.setLabelProvider(new Z8LabelProvider(false)); treeViewer.addSelectionChangedListener(this); treeViewer.setSorter(new ViewerSorter() { @Override public int compare(Viewer viewer, Object e1, Object e2) { if(e1 == e2) return 0; ISource s1, s2; if(e1 instanceof ISource) { s1 = (ISource)e1; } else { return -1; } if(e2 instanceof ISource) { s2 = (ISource)e2; } else { return 1; } return s1.getPosition().getOffset() > s2.getPosition().getOffset() ? 1 : -1; } }); treeViewer.addFilter(FILTER); if(m_compilationUnit != null) { treeViewer.setInput(m_compilationUnit); } } @Override public void dispose() { super.dispose(); Workspace.getInstance().uninstallResourceListener(m_listener); if(fMenu != null && !fMenu.isDisposed()) { fMenu.dispose(); fMenu = null; } } @Override public void selectionChanged(SelectionChangedEvent event) { super.selectionChanged(event); IStructuredSelection selection = (IStructuredSelection)event.getSelection(); Object element = selection.getFirstElement(); if(element == null) return; if(element instanceof ISourceProvider) { ISourceProvider prov = (ISourceProvider)element; element = prov.getSource(); } if(element instanceof ISource) { ISource source = (ISource)element; m_editor.getSelectionProvider().setSelection(new TextSelection(source.getPosition().getOffset(), source.getPosition().getLength())); } return; } public void setInput(FileEditorInput input) { if(input != null) { m_compilationUnit = Workspace.getInstance().getCompilationUnit(input.getFile()); } else { m_compilationUnit = null; } update(); } public void update() { TreeViewer viewer = getTreeViewer(); if(viewer != null) { Control control = viewer.getTree(); if(control != null && !control.isDisposed()) { control.setRedraw(false); viewer.setInput(m_compilationUnit); control.setRedraw(true); } } } @Override public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager) { // menuManager.setRemoveAllWhenShown(true); // menuManager.add(new Action("1"){}); menuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(final IMenuManager manager) { manager.removeAll(); final CompilationUnit unit = Workspace.getInstance().getCompilationUnit(((FileEditorInput)m_editor.getEditorInput()).getFile()); final IType type = unit.getReconciledType(); final LanguageElementImageProvider leip = new LanguageElementImageProvider(); List<IAction> actions = new ArrayList<IAction>(); IType curr = type.getBaseType(); while(curr != null) { for(final IMethod m : curr.getMethods()) if(m.getBody() == null && m.isVirtual()) { IType curr1 = type; boolean found = false; while(curr1 != curr) { for(IMethod m1 : curr1.getMethods()) if(m1.getSignature().equals(m.getSignature())) { found = true; break; } curr1 = curr1.getBaseType(); } if(!found) { String method = m.getName() + "("; boolean first = true; for(IVariable v : m.getParameters()) { method += (first ? "" : ", ") + v.getSignature() + " " + v.getName(); first = false; } method += ") "; method += m.getVariableType().getSignature(); actions.add(new Action(method) { @Override public ImageDescriptor getImageDescriptor() { return leip.getImageDescriptor(m, LanguageElementImageProvider.SMALL_ICONS); } @Override public void run() { MultipleTransactions mt = new MultipleTransactions((Z8Editor)m_editor); InitHelper.checkImport(mt, type, m.getVariableType().getType()); String call = "super."; call += m.getName() + "("; String sign = m.getVariableType().getSignature() + " " + m.getName() + "("; if(m.isPublic()) sign = "public " + sign; if(m.isProtected()) sign = "protected " + sign; if(m.isPrivate()) sign = "private " + sign; if(m.isStatic()) sign = "static " + sign; if(m.isVirtual()) sign = "virtual " + sign; boolean first = true; for(IVariable arg : m.getParameters()) { if(!first) { sign += ", "; call += ", "; } else first = false; call += arg.getName(); sign += arg.getVariableType().getSignature() + " " + arg.getName(); InitHelper.checkImport(mt, type, arg.getVariableType().getType()); } call += ");"; sign += ") {"; String methodString = "\r\n\t" + sign + "\r\n\t\t"; int len = methodString.length(); methodString = methodString + "\r\n\t\t" + (m.getVariableType().getSignature().equals("void") ? "" : "return ") + call; List<Transaction> trs = mt.getTransactions(); for(int i = 0; i < trs.size(); i++) { len += trs.get(i).getWhat().length(); } methodString += "\r\n\t}"; int posToInsert = new InitHelper(type).getNewMethodPosition(((Z8Editor)m_editor).getDocument(), m.getName()); mt.add(0, posToInsert, methodString); mt.execute(); m_editor.setFocus(); m_editor.getSelectionProvider().setSelection(new TextSelection(posToInsert + len, 0)); } }); // methodsStrings.add(method); // methods.add(m); } } curr = curr.getBaseType(); } IAction[] as = actions.toArray(new IAction[0]); Arrays.sort(as, new Comparator<IAction>() { @Override public int compare(IAction o1, IAction o2) { return o1.getText().compareToIgnoreCase(o2.getText()); } }); for(IAction a : as) manager.add(a); } }); } }
lgpl-3.0
Staon/otest2
lib/testroot.cpp
1644
/* * Copyright (C) 2020 Ondrej Starek * * This file is part of OTest2 * * OTest2 is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OTest2 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 OTest2. If not, see <http://www.gnu.org/licenses/>. */ #include <testroot.h> #include <assert.h> #include <memory> #include <cmdnextobject.h> #include <commandstack.h> #include <context.h> #include <scenario.h> namespace OTest2 { TestRoot::TestRoot( const std::string& name_) : name(name_) { assert(!name.empty()); } TestRoot::~TestRoot() { } std::string TestRoot::getName() const { return name; } bool TestRoot::startUpObject( const Context& context_, int index_) { return false; /* -- no start-up functions */ } void TestRoot::scheduleBody( const Context& context_, ScenarioPtr scenario_, ObjectPtr me_) { ScenarioIterPtr children_(scenario_->getChildren()); context_.command_stack->pushCommand( std::make_shared<CmdNextObject>(children_, me_)); } void TestRoot::tearDownObject( const Context& context_, int index_) { assert(index_ == 0); /* -- no tear-down functions */ } } /* -- namespace OTest2 */
lgpl-3.0
peterstevens130561/sonarlint-vs
its/Mvc-dev_b245996949/src/Microsoft.AspNet.Mvc.Core/ModelBinding/CancellationTokenModelBinder.cs
1246
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.AspNet.Mvc.ModelBinding { /// <summary> /// Represents a model binder which can bind models of type <see cref="CancellationToken"/>. /// </summary> public class CancellationTokenModelBinder : IModelBinder { /// <inheritdoc /> public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelType == typeof(CancellationToken)) { var model = bindingContext.OperationBindingContext.HttpContext.RequestAborted; var validationNode = new ModelValidationNode(bindingContext.ModelName, bindingContext.ModelMetadata, model); return Task.FromResult(new ModelBindingResult( model, bindingContext.ModelName, isModelSet: true, validationNode: validationNode)); } return Task.FromResult<ModelBindingResult>(null); } } }
lgpl-3.0
Albloutant/Galacticraft
common/micdoodle8/mods/galacticraft/core/GalacticraftCore.java
28228
package micdoodle8.mods.galacticraft.core; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import micdoodle8.mods.galacticraft.api.GalacticraftRegistry; import micdoodle8.mods.galacticraft.api.recipe.CircuitFabricatorRecipes; import micdoodle8.mods.galacticraft.api.recipe.CompressorRecipes; import micdoodle8.mods.galacticraft.api.recipe.SchematicRegistry; import micdoodle8.mods.galacticraft.api.transmission.compatibility.NetworkConfigHandler; import micdoodle8.mods.galacticraft.api.transmission.core.grid.ChunkPowerHandler; import micdoodle8.mods.galacticraft.api.world.ICelestialBody; import micdoodle8.mods.galacticraft.api.world.IGalaxy; import micdoodle8.mods.galacticraft.api.world.IMoon; import micdoodle8.mods.galacticraft.api.world.IPlanet; import micdoodle8.mods.galacticraft.core.blocks.GCCoreBlockFluid; import micdoodle8.mods.galacticraft.core.blocks.GCCoreBlocks; import micdoodle8.mods.galacticraft.core.client.gui.GCCoreGuiHandler; import micdoodle8.mods.galacticraft.core.command.GCCoreCommandPlanetTeleport; import micdoodle8.mods.galacticraft.core.command.GCCoreCommandSpaceStationAddOwner; import micdoodle8.mods.galacticraft.core.command.GCCoreCommandSpaceStationRemoveOwner; import micdoodle8.mods.galacticraft.core.dimension.GCCoreOrbitTeleportType; import micdoodle8.mods.galacticraft.core.dimension.GCCoreOverworldTeleportType; import micdoodle8.mods.galacticraft.core.dimension.GCCoreWorldProviderSpaceStation; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityAlienVillager; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityArrow; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityBuggy; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityCreeper; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityFlag; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityLander; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityMeteor; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityMeteorChunk; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityOxygenBubble; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityParaChest; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityRocketT1; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntitySkeleton; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntitySkeletonBoss; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntitySpider; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityZombie; import micdoodle8.mods.galacticraft.core.entities.player.GCCorePlayerMP; import micdoodle8.mods.galacticraft.core.entities.player.GCCorePlayerSP; import micdoodle8.mods.galacticraft.core.entities.player.PlayerTracker; import micdoodle8.mods.galacticraft.core.event.GCCoreEvents; import micdoodle8.mods.galacticraft.core.items.GCCoreItemBasic; import micdoodle8.mods.galacticraft.core.items.GCCoreItemBlock; import micdoodle8.mods.galacticraft.core.items.GCCoreItems; import micdoodle8.mods.galacticraft.core.network.GCCoreConnectionHandler; import micdoodle8.mods.galacticraft.core.network.GCCorePacketHandlerServer; import micdoodle8.mods.galacticraft.core.network.GCCorePacketManager; import micdoodle8.mods.galacticraft.core.recipe.GCCoreRecipeManager; import micdoodle8.mods.galacticraft.core.schematic.GCCoreSchematicAdd; import micdoodle8.mods.galacticraft.core.schematic.GCCoreSchematicMoonBuggy; import micdoodle8.mods.galacticraft.core.schematic.GCCoreSchematicRocketT1; import micdoodle8.mods.galacticraft.core.tick.GCCoreTickHandlerServer; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityAdvancedCraftingTable; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityAirLock; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityAirLockController; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityAluminumWire; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityBuggyFueler; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityBuggyFuelerSingle; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityCargoLoader; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityCargoUnloader; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityCircuitFabricator; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityCoalGenerator; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityDungeonSpawner; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityElectricFurnace; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityElectricIngotCompressor; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityEnergyStorageModule; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityFallenMeteor; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityFuelLoader; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityIngotCompressor; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityLandingPad; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityLandingPadSingle; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityOxygenCollector; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityOxygenCompressor; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityOxygenDecompressor; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityOxygenDetector; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityOxygenDistributor; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityOxygenPipe; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityOxygenSealer; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityOxygenStorageModule; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityParachest; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityRefinery; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntitySolar; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntitySpaceStationBase; import micdoodle8.mods.galacticraft.core.tile.GCCoreTileEntityTreasureChest; import micdoodle8.mods.galacticraft.core.tile.TileEntityMulti; import micdoodle8.mods.galacticraft.core.util.GCCoreUtil; import micdoodle8.mods.galacticraft.core.util.WorldUtil; import micdoodle8.mods.galacticraft.core.world.ChunkLoadingCallback; import micdoodle8.mods.galacticraft.core.world.gen.GCCoreOverworldGenerator; import micdoodle8.mods.galacticraft.moon.GalacticraftMoon; import micdoodle8.mods.galacticraft.moon.dimension.GCMoonWorldProvider; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.WorldProviderSurface; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.Event; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartedEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.event.FMLServerStoppedEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.TickRegistry; import cpw.mods.fml.relauncher.Side; /** * GalacticraftCore.java * * This file is part of the Galacticraft project * * @author micdoodle8 * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) * */ @Mod(name = GalacticraftCore.NAME, version = GalacticraftCore.LOCALMAJVERSION + "." + GalacticraftCore.LOCALMINVERSION + "." + GalacticraftCore.LOCALBUILDVERSION, useMetadata = true, modid = GalacticraftCore.MODID, dependencies = "required-after:Forge@[9.10.0.837,); after:ICBM|Explosion; after:IC2; after:BuildCraft|Core; after:BuildCraft|Energy; after:IC2") @NetworkMod(channels = { GalacticraftCore.CHANNEL }, clientSideRequired = true, serverSideRequired = false, connectionHandler = GCCoreConnectionHandler.class, packetHandler = GCCorePacketManager.class) public class GalacticraftCore { public static final String NAME = "Galacticraft Core"; public static final String MODID = "GalacticraftCore"; public static final String CHANNEL = "GalacticraftCore"; public static final String CHANNELENTITIES = "GCCoreEntities"; public static final int LOCALMAJVERSION = 2; public static final int LOCALMINVERSION = 0; public static final int LOCALBUILDVERSION = 11; public static int remoteMajVer; public static int remoteMinVer; public static int remoteBuildVer; @SidedProxy(clientSide = "micdoodle8.mods.galacticraft.core.client.ClientProxyCore", serverSide = "micdoodle8.mods.galacticraft.core.CommonProxyCore") public static CommonProxyCore proxy; @Instance(GalacticraftCore.MODID) public static GalacticraftCore instance; private static GCCoreThreadRequirementMissing missingRequirementThread; public static Map<String, GCCorePlayerSP> playersClient = new HashMap<String, GCCorePlayerSP>(); public static Map<String, GCCorePlayerMP> playersServer = new HashMap<String, GCCorePlayerMP>(); public static List<IPlanet> mapPlanets = new ArrayList<IPlanet>(); public static HashMap<IPlanet, ArrayList<IMoon>> mapMoons = new HashMap<IPlanet, ArrayList<IMoon>>(); public static CreativeTabs galacticraftTab; public static final IGalaxy galaxyMilkyWay = new GCCoreGalaxyBlockyWay(); public static final String FILE_PATH = "/micdoodle8/mods/galacticraft/core/"; public static final String CLIENT_PATH = "client/"; public static final String LANGUAGE_PATH = "/assets/galacticraftcore/lang/"; public static final String BLOCK_TEXTURE_FILE = GalacticraftCore.FILE_PATH + GalacticraftCore.CLIENT_PATH + "blocks/core.png"; public static final String ITEM_TEXTURE_FILE = GalacticraftCore.FILE_PATH + GalacticraftCore.CLIENT_PATH + "items/core.png"; public static final String CONFIG_FILE = "Galacticraft/core.conf"; public static final String POWER_CONFIG_FILE = "Galacticraft/power.conf"; public static final String CHUNKLOADER_CONFIG_FILE = "Galacticraft/chunkloading.conf"; public static String ASSET_DOMAIN = "galacticraftcore"; public static String ASSET_PREFIX = GalacticraftCore.ASSET_DOMAIN + ":"; public static boolean setSpaceStationRecipe = false; public static GCCorePlanetOverworld overworld; public static GCCorePlanetSun sun; public static Fluid gcFluidOil; public static Fluid gcFluidFuel; public static Fluid fluidOil; public static Fluid fluidFuel; public static HashMap<String, ItemStack> itemList = new HashMap<String, ItemStack>(); public static HashMap<String, ItemStack> blocksList = new HashMap<String, ItemStack>(); @EventHandler public void preInit(FMLPreInitializationEvent event) { GalacticraftMoon.preLoad(event); MinecraftForge.EVENT_BUS.register(new GCCoreEvents()); GalacticraftCore.proxy.preInit(event); GCCoreConfigManager.setDefaultValues(new File(event.getModConfigurationDirectory(), GalacticraftCore.CONFIG_FILE)); NetworkConfigHandler.setDefaultValues(new File(event.getModConfigurationDirectory(), GalacticraftCore.POWER_CONFIG_FILE)); ChunkLoadingCallback.loadConfig(new File(event.getModConfigurationDirectory(), GalacticraftCore.CHUNKLOADER_CONFIG_FILE)); GalacticraftCore.gcFluidOil = new Fluid("oil").setDensity(800).setViscosity(1500); GalacticraftCore.gcFluidFuel = new Fluid("fuel").setDensity(200).setViscosity(900); FluidRegistry.registerFluid(GalacticraftCore.gcFluidOil); FluidRegistry.registerFluid(GalacticraftCore.gcFluidFuel); GalacticraftCore.fluidOil = FluidRegistry.getFluid("oil"); GalacticraftCore.fluidFuel = FluidRegistry.getFluid("fuel"); if (GalacticraftCore.fluidOil.getBlockID() == -1) { GCCoreBlocks.crudeOilStill = new GCCoreBlockFluid(GCCoreConfigManager.idBlockCrudeOilStill, GalacticraftCore.fluidOil, "oil"); ((GCCoreBlockFluid) GCCoreBlocks.crudeOilStill).setQuantaPerBlock(3); GCCoreBlocks.crudeOilStill.setUnlocalizedName("crudeOilStill"); GameRegistry.registerBlock(GCCoreBlocks.crudeOilStill, GCCoreItemBlock.class, GCCoreBlocks.crudeOilStill.getUnlocalizedName(), GalacticraftCore.MODID); GalacticraftCore.fluidOil.setBlockID(GCCoreBlocks.crudeOilStill); } else { GCCoreBlocks.crudeOilStill = Block.blocksList[GalacticraftCore.fluidOil.getBlockID()]; } if (GalacticraftCore.fluidFuel.getBlockID() == -1) { GCCoreBlocks.fuelStill = new GCCoreBlockFluid(GCCoreConfigManager.idBlockFuel, GalacticraftCore.fluidFuel, "fuel"); ((GCCoreBlockFluid) GCCoreBlocks.fuelStill).setQuantaPerBlock(6); GCCoreBlocks.fuelStill.setUnlocalizedName("fuel"); GameRegistry.registerBlock(GCCoreBlocks.fuelStill, GCCoreItemBlock.class, GCCoreBlocks.fuelStill.getUnlocalizedName(), GalacticraftCore.MODID); GalacticraftCore.fluidFuel.setBlockID(GCCoreBlocks.fuelStill); } else { GCCoreBlocks.fuelStill = Block.blocksList[GalacticraftCore.fluidFuel.getBlockID()]; } GCCoreBlocks.initBlocks(); GCCoreItems.initItems(); } @EventHandler public void init(FMLInitializationEvent event) { GalacticraftCore.galacticraftTab = new GCCoreCreativeTab(CreativeTabs.getNextID(), GalacticraftCore.CHANNEL, GCCoreItems.rocketTier1.itemID, 0); GalacticraftCore.overworld = new GCCorePlanetOverworld(); GalacticraftRegistry.registerCelestialBody(GalacticraftCore.overworld); GalacticraftCore.sun = new GCCorePlanetSun(); GalacticraftRegistry.registerCelestialBody(GalacticraftCore.sun); GalacticraftRegistry.registerGalaxy(GalacticraftCore.galaxyMilkyWay); DimensionManager.registerProviderType(GCCoreConfigManager.idDimensionOverworldOrbit, GCCoreWorldProviderSpaceStation.class, false); GalacticraftCore.proxy.init(event); GalacticraftRegistry.registerTeleportType(WorldProviderSurface.class, new GCCoreOverworldTeleportType()); GalacticraftRegistry.registerTeleportType(GCCoreWorldProviderSpaceStation.class, new GCCoreOrbitTeleportType()); ForgeChunkManager.setForcedChunkLoadingCallback(GalacticraftCore.instance, new ChunkLoadingCallback()); GameRegistry.registerPlayerTracker(new PlayerTracker()); GalacticraftMoon.load(event); for (int i = GCCoreItems.fuelCanister.getMaxDamage() - 1; i > 0; i--) { FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(GalacticraftCore.fluidFuel, GCCoreItems.fuelCanister.getMaxDamage() - i), new ItemStack(GCCoreItems.fuelCanister, 1, i), new ItemStack(GCCoreItems.oilCanister, 1, GCCoreItems.fuelCanister.getMaxDamage()))); } for (int i = GCCoreItems.oilCanister.getMaxDamage() - 1; i > 0; i--) { FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(GalacticraftCore.fluidOil, GCCoreItems.oilCanister.getMaxDamage() - i), new ItemStack(GCCoreItems.oilCanister, 1, i), new ItemStack(GCCoreItems.oilCanister, 1, GCCoreItems.fuelCanister.getMaxDamage()))); } SchematicRegistry.registerSchematicRecipe(new GCCoreSchematicRocketT1()); SchematicRegistry.registerSchematicRecipe(new GCCoreSchematicMoonBuggy()); SchematicRegistry.registerSchematicRecipe(new GCCoreSchematicAdd()); ChunkPowerHandler.initiate(); NetworkConfigHandler.initGas(); this.registerCreatures(); this.registerOtherEntities(); NetworkRegistry.instance().registerChannel(new GCCorePacketManager(), GalacticraftCore.CHANNELENTITIES, Side.CLIENT); NetworkRegistry.instance().registerChannel(new GCCorePacketManager(), GalacticraftCore.CHANNELENTITIES, Side.SERVER); GalacticraftRegistry.registerRocketGui(GCCoreWorldProviderSpaceStation.class, new ResourceLocation(GalacticraftCore.ASSET_DOMAIN, "textures/gui/overworldRocketGui.png")); GalacticraftRegistry.registerRocketGui(WorldProviderSurface.class, new ResourceLocation(GalacticraftCore.ASSET_DOMAIN, "textures/gui/overworldRocketGui.png")); GalacticraftRegistry.registerRocketGui(GCMoonWorldProvider.class, new ResourceLocation(GalacticraftCore.ASSET_DOMAIN, "textures/gui/moonRocketGui.png")); GalacticraftRegistry.addDungeonLoot(1, new ItemStack(GCCoreItems.schematic, 1, 0)); GalacticraftRegistry.addDungeonLoot(1, new ItemStack(GCCoreItems.schematic, 1, 1)); if (GCCoreConfigManager.enableCopperOreGen) { GameRegistry.registerWorldGenerator(new GCCoreOverworldGenerator(GCCoreBlocks.basicBlock, 5, 24, 0, 75, 7)); } if (GCCoreConfigManager.enableTinOreGen) { GameRegistry.registerWorldGenerator(new GCCoreOverworldGenerator(GCCoreBlocks.basicBlock, 6, 22, 0, 60, 7)); } if (GCCoreConfigManager.enableAluminumOreGen) { GameRegistry.registerWorldGenerator(new GCCoreOverworldGenerator(GCCoreBlocks.basicBlock, 7, 18, 0, 45, 7)); } if (GCCoreConfigManager.enableSiliconOreGen) { GameRegistry.registerWorldGenerator(new GCCoreOverworldGenerator(GCCoreBlocks.basicBlock, 8, 3, 0, 25, 7)); } } @EventHandler public void postInit(FMLPostInitializationEvent event) { for (ICelestialBody celestialBody : GalacticraftRegistry.getCelestialBodies()) { if (celestialBody.autoRegister()) { DimensionManager.registerProviderType(celestialBody.getDimensionID(), celestialBody.getWorldProvider(), false); } } GCCoreCompatibilityManager.checkForCompatibleMods(); this.registerTileEntities(); GCCoreRecipeManager.loadRecipes(); NetworkRegistry.instance().registerGuiHandler(this, new GCCoreGuiHandler()); GalacticraftCore.proxy.postInit(event); GalacticraftCore.proxy.registerRenderInformation(); for (int i = 3; i < 8; i++) { if (GCCoreItemBasic.names[i].contains("ingot")) { for (ItemStack stack : OreDictionary.getOres(GCCoreItemBasic.names[i])) { CompressorRecipes.addShapelessRecipe(new ItemStack(GCCoreItems.basicItem, 1, i + 3), stack, stack); } } } // Support for the other spelling of Aluminum if (OreDictionary.getOres("ingotAluminium").size() > 0 || OreDictionary.getOres("ingotNaturalAluminum").size() > 0) { List<ItemStack> aluminumIngotList = new ArrayList<ItemStack>(); aluminumIngotList.addAll(OreDictionary.getOres("ingotAluminium")); aluminumIngotList.addAll(OreDictionary.getOres("ingotNaturalAluminum")); for (ItemStack stack : aluminumIngotList) { CompressorRecipes.addShapelessRecipe(new ItemStack(GCCoreItems.basicItem, 1, 8), stack, stack); } } if (OreDictionary.getOres("ingotBronze").size() > 0) { for (ItemStack stack : OreDictionary.getOres("ingotBronze")) { CompressorRecipes.addShapelessRecipe(new ItemStack(GCCoreItems.basicItem, 1, 10), stack, stack); } } if (OreDictionary.getOres("ingotSteel").size() > 0) { for (ItemStack stack : OreDictionary.getOres("ingotSteel")) { CompressorRecipes.addShapelessRecipe(new ItemStack(GCCoreItems.basicItem, 1, 9), stack, stack); } } CompressorRecipes.addShapelessRecipe(new ItemStack(GCCoreItems.basicItem, 1, 9), Item.coal, new ItemStack(GCCoreItems.basicItem, 1, 11), Item.coal); CompressorRecipes.addShapelessRecipe(new ItemStack(GCCoreItems.basicItem, 1, 10), new ItemStack(GCCoreItems.basicItem, 1, 6), new ItemStack(GCCoreItems.basicItem, 1, 7)); CompressorRecipes.addShapelessRecipe(new ItemStack(GCCoreItems.basicItem, 1, 11), Item.ingotIron, Item.ingotIron); CompressorRecipes.addShapelessRecipe(new ItemStack(GCCoreItems.meteoricIronIngot, 1, 1), new ItemStack(GCCoreItems.meteoricIronIngot, 1, 0)); CompressorRecipes.addRecipe(new ItemStack(GCCoreItems.heavyPlatingTier1, 1, 0), "XYZ", "XYZ", 'X', new ItemStack(GCCoreItems.basicItem, 1, 9), 'Y', new ItemStack(GCCoreItems.basicItem, 1, 8), 'Z', new ItemStack(GCCoreItems.basicItem, 1, 10)); CircuitFabricatorRecipes.addRecipe(new ItemStack(GCCoreItems.basicItem, 9, 12), new ItemStack[] { new ItemStack(Item.diamond), new ItemStack(GCCoreItems.basicItem, 1, 2), new ItemStack(GCCoreItems.basicItem, 1, 2), new ItemStack(Item.redstone), new ItemStack(Item.dyePowder, 1, 4) }); CircuitFabricatorRecipes.addRecipe(new ItemStack(GCCoreItems.basicItem, 3, 13), new ItemStack[] { new ItemStack(Item.diamond), new ItemStack(GCCoreItems.basicItem, 1, 2), new ItemStack(GCCoreItems.basicItem, 1, 2), new ItemStack(Item.redstone), new ItemStack(Block.torchRedstoneActive) }); CircuitFabricatorRecipes.addRecipe(new ItemStack(GCCoreItems.basicItem, 1, 14), new ItemStack[] { new ItemStack(Item.diamond), new ItemStack(GCCoreItems.basicItem, 1, 2), new ItemStack(GCCoreItems.basicItem, 1, 2), new ItemStack(Item.redstone), new ItemStack(Item.redstoneRepeater) }); } @EventHandler public void serverInit(FMLServerStartedEvent event) { if (GalacticraftCore.missingRequirementThread == null) { GalacticraftCore.missingRequirementThread = new GCCoreThreadRequirementMissing(FMLCommonHandler.instance().getEffectiveSide()); GalacticraftCore.missingRequirementThread.start(); } GCCoreUtil.checkVersion(Side.SERVER); TickRegistry.registerTickHandler(new GCCoreTickHandlerServer(), Side.SERVER); NetworkRegistry.instance().registerChannel(new GCCorePacketHandlerServer(), GalacticraftCore.CHANNEL, Side.SERVER); } @EventHandler public void serverStarting(FMLServerStartingEvent event) { event.registerServerCommand(new GCCoreCommandSpaceStationAddOwner()); event.registerServerCommand(new GCCoreCommandSpaceStationRemoveOwner()); event.registerServerCommand(new GCCoreCommandPlanetTeleport()); WorldUtil.registerSpaceStations(event.getServer().worldServerForDimension(0).getSaveHandler().getMapFileFromName("dummy").getParentFile()); for (ICelestialBody celestialBody : GalacticraftRegistry.getCelestialBodies()) { if (celestialBody.autoRegister()) { WorldUtil.registerPlanet(celestialBody.getDimensionID(), true); } } } @EventHandler public void unregisterDims(FMLServerStoppedEvent var1) { WorldUtil.unregisterPlanets(); WorldUtil.unregisterSpaceStations(); } public void registerTileEntities() { GameRegistry.registerTileEntity(GCCoreTileEntityTreasureChest.class, GCCoreCompatibilityManager.isAIILoaded() ? "Space Treasure Chest" : "Treasure Chest"); GameRegistry.registerTileEntity(GCCoreTileEntityOxygenDistributor.class, "Air Distributor"); GameRegistry.registerTileEntity(GCCoreTileEntityOxygenCollector.class, "Air Collector"); GameRegistry.registerTileEntity(GCCoreTileEntityOxygenPipe.class, "Oxygen Pipe"); GameRegistry.registerTileEntity(GCCoreTileEntityAirLock.class, "Air Lock Frame"); GameRegistry.registerTileEntity(GCCoreTileEntityRefinery.class, "Refinery"); GameRegistry.registerTileEntity(GCCoreTileEntityAdvancedCraftingTable.class, "NASA Workbench"); GameRegistry.registerTileEntity(GCCoreTileEntityOxygenCompressor.class, "Air Compressor"); GameRegistry.registerTileEntity(GCCoreTileEntityFuelLoader.class, "Fuel Loader"); GameRegistry.registerTileEntity(GCCoreTileEntityLandingPadSingle.class, "Landing Pad"); GameRegistry.registerTileEntity(GCCoreTileEntityLandingPad.class, "Landing Pad Full"); GameRegistry.registerTileEntity(GCCoreTileEntitySpaceStationBase.class, "Space Station"); GameRegistry.registerTileEntity(TileEntityMulti.class, "Dummy Block"); GameRegistry.registerTileEntity(GCCoreTileEntityOxygenSealer.class, "Air Sealer"); GameRegistry.registerTileEntity(GCCoreTileEntityDungeonSpawner.class, "Dungeon Boss Spawner"); GameRegistry.registerTileEntity(GCCoreTileEntityOxygenDetector.class, "Oxygen Detector"); GameRegistry.registerTileEntity(GCCoreTileEntityBuggyFueler.class, "Buggy Fueler"); GameRegistry.registerTileEntity(GCCoreTileEntityBuggyFuelerSingle.class, "Buggy Fueler Single"); GameRegistry.registerTileEntity(GCCoreTileEntityCargoLoader.class, "Cargo Loader"); GameRegistry.registerTileEntity(GCCoreTileEntityCargoUnloader.class, "Cargo Unloader"); GameRegistry.registerTileEntity(GCCoreTileEntityParachest.class, "Parachest Tile"); GameRegistry.registerTileEntity(GCCoreTileEntitySolar.class, "Galacticraft Solar Panel"); GameRegistry.registerTileEntity(GCCoreTileEntityEnergyStorageModule.class, "Energy Storage Module"); GameRegistry.registerTileEntity(GCCoreTileEntityCoalGenerator.class, "Galacticraft Coal Generator"); GameRegistry.registerTileEntity(GCCoreTileEntityElectricFurnace.class, "Galacticraft Electric Furnace"); GameRegistry.registerTileEntity(GCCoreTileEntityAluminumWire.class, "Galacticraft Aluminum Wire"); GameRegistry.registerTileEntity(GCCoreTileEntityFallenMeteor.class, "Fallen Meteor"); GameRegistry.registerTileEntity(GCCoreTileEntityIngotCompressor.class, "Ingot Compressor"); GameRegistry.registerTileEntity(GCCoreTileEntityElectricIngotCompressor.class, "Electric Ingot Compressor"); GameRegistry.registerTileEntity(GCCoreTileEntityCircuitFabricator.class, "Circuit Fabricator"); GameRegistry.registerTileEntity(GCCoreTileEntityAirLockController.class, "Air Lock Controller"); GameRegistry.registerTileEntity(GCCoreTileEntityOxygenStorageModule.class, "Oxygen Storage Module"); GameRegistry.registerTileEntity(GCCoreTileEntityOxygenDecompressor.class, "Oxygen Decompressor"); } public void registerCreatures() { GCCoreUtil.registerGalacticraftCreature(GCCoreEntitySpider.class, "EvolvedSpider", GCCoreConfigManager.idEntityEvolvedSpider, 3419431, 11013646); GCCoreUtil.registerGalacticraftCreature(GCCoreEntityZombie.class, "EvolvedZombie", GCCoreConfigManager.idEntityEvolvedZombie, 44975, 7969893); GCCoreUtil.registerGalacticraftCreature(GCCoreEntityCreeper.class, "EvolvedCreeper", GCCoreConfigManager.idEntityEvolvedCreeper, 894731, 0); GCCoreUtil.registerGalacticraftCreature(GCCoreEntitySkeleton.class, "EvolvedSkeleton", GCCoreConfigManager.idEntityEvolvedSkeleton, 12698049, 4802889); GCCoreUtil.registerGalacticraftCreature(GCCoreEntitySkeletonBoss.class, "EvolvedSkeletonBoss", GCCoreConfigManager.idEntityEvolvedSkeletonBoss, 12698049, 4802889); GCCoreUtil.registerGalacticraftCreature(GCCoreEntityAlienVillager.class, "AlienVillager", GCCoreConfigManager.idEntityAlienVillager, GCCoreUtil.convertTo32BitColor(255, 103, 181, 145), 12422002); } public void registerOtherEntities() { GCCoreUtil.registerGalacticraftNonMobEntity(GCCoreEntityRocketT1.class, "Spaceship", GCCoreConfigManager.idEntitySpaceship, 150, 1, false); GCCoreUtil.registerGalacticraftNonMobEntity(GCCoreEntityArrow.class, "GravityArrow", GCCoreConfigManager.idEntityAntiGravityArrow, 150, 5, true); GCCoreUtil.registerGalacticraftNonMobEntity(GCCoreEntityMeteor.class, "Meteor", GCCoreConfigManager.idEntityMeteor, 150, 5, true); GCCoreUtil.registerGalacticraftNonMobEntity(GCCoreEntityBuggy.class, "Buggy", GCCoreConfigManager.idEntityBuggy, 150, 5, true); GCCoreUtil.registerGalacticraftNonMobEntity(GCCoreEntityFlag.class, "Flag", GCCoreConfigManager.idEntityFlag, 150, 5, true); GCCoreUtil.registerGalacticraftNonMobEntity(GCCoreEntityParaChest.class, "ParaChest", GCCoreConfigManager.idEntityParaChest, 150, 5, true); GCCoreUtil.registerGalacticraftNonMobEntity(GCCoreEntityOxygenBubble.class, "OxygenBubble", GCCoreConfigManager.idEntityOxygenBubble, 150, 20, false); GCCoreUtil.registerGalacticraftNonMobEntity(GCCoreEntityLander.class, "Lander", GCCoreConfigManager.idEntityLander, 150, 5, false); GCCoreUtil.registerGalacticraftNonMobEntity(GCCoreEntityMeteorChunk.class, "MeteorChunk", GCCoreConfigManager.idEntityMeteorChunk, 150, 5, true); } public static class SleepCancelledEvent extends Event { } public static class OrientCameraEvent extends Event { } }
lgpl-3.0
dvad924/ez-robots
EZ-B SDK Windows/C#/Tutorial 60 - HT16K33 8x8/Form1.Designer.cs
3417
namespace Tutorial_60___HT16K33_8x8 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.panel1 = new System.Windows.Forms.Panel(); this.button1 = new System.Windows.Forms.Button(); this.ucezB_Connect1 = new EZ_B.UCEZB_Connect(); this.button2 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // panel1 // this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Location = new System.Drawing.Point(83, 88); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(620, 427); this.panel1.TabIndex = 1; // // button1 // this.button1.Location = new System.Drawing.Point(83, 37); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 45); this.button1.TabIndex = 2; this.button1.Text = "Init"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // ucezB_Connect1 // this.ucezB_Connect1.Location = new System.Drawing.Point(0, 0); this.ucezB_Connect1.Name = "ucezB_Connect1"; this.ucezB_Connect1.Port = "192.168.1.1:23"; this.ucezB_Connect1.ShowDebugButton = true; this.ucezB_Connect1.Size = new System.Drawing.Size(283, 31); this.ucezB_Connect1.TabIndex = 0; this.ucezB_Connect1.TCPPassword = null; // // button2 // this.button2.Location = new System.Drawing.Point(164, 37); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(75, 45); this.button2.TabIndex = 3; this.button2.Text = "Clear"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(908, 527); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.panel1); this.Controls.Add(this.ucezB_Connect1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion private EZ_B.UCEZB_Connect ucezB_Connect1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; } }
lgpl-3.0
OpenSoftwareSolutions/PDFReporter-Studio
com.jaspersoft.studio.data.hbase/src/com/jaspersoft/hbase/deserialize/Deserializer.java
1283
/******************************************************************************* * Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com. * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package com.jaspersoft.hbase.deserialize; /** * * @author Eric Diaz * */ public interface Deserializer { public Object deserializeRowId(byte[] rowID); public String deserializeColumnFamily(byte[] columnFamily); public String deserializeQualifier(byte[] qualifier); public Object deserializeValue(String tableName, String columnFamily, String qualifier, byte[] value); public byte[] serializeRowId(String rowID); public byte[] serializeColumnFamily(String columnFamily); public byte[] serializeQualifier(String qualifier); public byte[] serializeValue(String tableName, String columnFamily, String qualifier, Object value); }
lgpl-3.0
tobbad/pydwf
examples/aDiscovery.py
9123
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 10.10.2013 @author: Tobias Badertscher """ import sys import os from pydwf import dwf import numpy as np import time import matplotlib.pyplot as plt from math import * import re def Usage(error=None): text=["filename","bla bla blar",\ "Gugus da da."] lineStart=" " if error != None: if isinstance(error, (list, tuple)): maxLen=max(len(i) for i in error) print("*"*(maxLen+len(lineStart)+2), maxLen) for item in error: print("%s%s *" % (lineStart,item)) print("*"*(maxLen+len(lineStart)+2), maxLen) elif isinstance(error, str): print("*"*(len(error)+len(lineStart)+2)) print("%s%s *" %(lineStart,error)) print("*"*(len(error)+len(lineStart)+2)) progName=sys.argv[0].split(os.sep)[-1] print("Usage %s %s" % (progName, text[0])) for line in text[1:]: print("%s%s" % (lineStart,line)) sys.exit() def SysMon(fd, t=60): for i in xrange(t): time.sleep(1) dwf.AnalogIOStatus(fd) v = dwf.AnalogIOChannelNodeStatus(fd, 2, 0) i = dwf.AnalogIOChannelNodeStatus(fd, 2, 1) i*=1000 T = dwf.AnalogIOChannelNodeStatus(fd, 2, 2) print("Output Voltage %4.2f V, Output Current %5.2f mA, Temperature %5.1f C" %(v,i,T)) def AcquireAnalog(fd, cnt, fSample=2E6, chNr=0): ''' Aquire analog input data: fd Descriptor for the file cnt Sample count to aquire fSample Sample frequency in [Hz] chNr Input channel 0..1 ''' data = None if 0 <= chNr < 2 : data = np.zeros(cnt, dtype=np.double) dwf.AnalogInFrequencySet(fd, fSample) dwf.AnalogInBufferSizeSet(fd, cnt) dwf.AnalogInChannelEnableSet(fd, chNr, True) dwf.AnalogInChannelRangeSet(fd, chNr, 5) time.sleep(2) dwf.AnalogInConfigure(fd, False, True) sts=dwf.stsCfg while not sts==dwf.stsDone: sts=dwf.AnalogInStatus(fd, True) print("Current analog status: %d" % sts) dwf.AnalogInStatusData(fd, chNr, data) return data def generateSinus(fd, chNr, fSignal, ampl, offset = 0): ''' Generate Sinus on channel output chNr: fd Descriptor for the file chNr Channel output 0..1 fSignal Frequency of sinus in Hz ampl Amplitude of signal in V offset Offset of signal in V ''' dwf.AnalogOutEnableSet(fd, chNr, True) dwf.AnalogOutFunctionSet(fd, chNr, dwf.funcSine) dwf.AnalogOutFrequencySet(fd, chNr, fSignal) dwf.AnalogOutAmplitudeSet(fd, chNr, ampl) dwf.AnalogOutOffsetSet(fd, chNr, offset) dwf.AnalogOutConfigure(fd, chNr, True) def DigitalIO(fd): ''' Check if Output/Input [0:7] correctly maps to Input/Output [8:15] fd : File descriptor fotr AnalogDiscovery ''' ioEnable = 0x00FF dwf.DigitalIOOutputEnableSet(fd, ioEnable) for i in xrange(8): bitSet = 1 << i bitExp = 1 << (i+8) dwf.DigitalIOOutputSet(fd, bitSet) dwf.DigitalIOStatus(fd) ioState = dwf.DigitalIOInputStatus(fd) ioState = ioState & (~ ioEnable) if ioState != bitExp: print("Set Output %d, Expected Input bit %d is not set!" %(i ,i+8)) ioEnable = 0xFF00 dwf.DigitalIOOutputEnableSet(fd, ioEnable) for i in xrange(8): bitSet = 1 << (i+8) bitExp = 1 << i dwf.DigitalIOOutputSet(fd, bitSet) dwf.DigitalIOStatus(fd) ioState = dwf.DigitalIOInputStatus(fd) ioState = ioState & (~ ioEnable) if ioState != bitExp: print("Set Output %d, Expected Input bit %d is not set!" %(i+8 ,i)) ioEnable = 0x0000 dwf.DigitalIOOutputEnableSet(fd, ioEnable) return def generateDigitalPattern8(fd, outChannels, oClkHz): ''' Generate a digital pattern on the given channels. Precondition is that output channel i and i+8 are not allowed. fd Descriptor for the file chnnels List which contains the output pins on which the signal is generated ''' isOk = True for i in outChannels: iCh = i+8 if i<8 else i-8 if iCh in outChannels: isOk = False break if not isOk: print("Invalid output channel %d and %d+/-8" % (i,i)) else: cntOfDigChannels = dwf.DigitalOutCount(fd) print("Maximal count of output Channels= %d" %(cntOfDigChannels)) oMsk = sum([2**i if i in outChannels else 0 for i in xrange(cntOfDigChannels)]) print("OutputMask 0x%04x/Used outputpins %d" % (oMsk, len(outChannels))) dwf.DigitalIOOutputEnableSet(fd, oMsk) iClkHz = dwf.DigitalOutInternalClockInfo(fd) print("Output base clock is %f MHz" % (iClkHz/1E6)) div = int(floor(iClkHz/oClkHz)) print("Divider = %d" % div) maxOutStateCnt = dwf.DigitalOutDataInfo(fd,0) maxOutStateCnt=16 print("Maximal output state count= %d" % maxOutStateCnt) data = [np.zeros(maxOutStateCnt, dtype='bool') for i in xrange(len(outChannels))] if 1==1: print(data) for i in xrange(len(outChannels)): for j in xrange(maxOutStateCnt): data[i][j] = ( (j & (1<<i)) != 0) print(i,1<<i,j, (j & (1<<i))) print(" ".join(["%5d" % i for i in xrange(len(data[0]))])) for vec in data: print(" ".join(["%5s" % i for i in vec])) #sys.exit() for i in xrange(cntOfDigChannels): if i in outChannels: dwf.DigitalOutEnableSet(fd, i, True) dwf.DigitalOutDividerSet(fd, i, div) dwf.DigitalOutCounterSet(fd, i, 9, 1) dwf.DigitalOutCounterInitSet(fd, i, i==0, 0 if i==0 else i) #dwf.DigitalOutTypeSet(fd, i, dwf.DwfDigitalOutTypeCustom) #dwf.DigitalOutOutputSet(fd, i, dwf.DwfDigitalOutOutputPushPull) #dwf.DigitalOutDataSet(fd, i, data[i] ) else: dwf.DigitalOutEnableSet(fd, i, False) dwf.DigitalOutDividerSet(fd, i, div) mins, maxs = dwf.DigitalOutRunInfo(fd) rmin, rMax = dwf.DigitalOutRepeatInfo(fd) print(rmin, rMax) dwf.DigitalOutRepeatSet(fd, rmin) dwf.DigitalOutConfigure(fd, True) def AcquireDigital(hdwf, cnt): '''\ Capture digital input as in digitalin_aquisation.c ''' hzSys = dwf.DigitalInInternalClockInfo(hdwf) div = int(floor(hzSys/1E6)) print(div) dwf.DigitalInDividerSet(hdwf, div) dwf.DigitalInSampleFormatSet(hdwf, 16) cSamples = dwf.DigitalInBufferSizeInfo(hdwf) print("Deveice has buffer of size %d bytes" % cSamples) # default buffer size is set to maximum dwf.DigitalInBufferSizeSet(hdwf, cSamples) rgwSamples = np.zeros(cnt, dtype=np.uint16) # set trigger position to the middle dwf.DigitalInTriggerPositionSet(hdwf, cSamples/2) # trigger on any pin transition dwf.DigitalInTriggerSourceSet(hdwf, dwf.trigsrcDetectorDigitalIn) dwf.DigitalInTriggerAutoTimeoutSet(hdwf, 1.0) dwf.DigitalInTriggerSet(hdwf, 0,0,0xFFFF,0xFFFF) # start dwf.DigitalInConfigure(hdwf, False, True ) print("Waiting for triggered or auto acquisition"); sts=dwf.stsCfg idx = 0 while not sts==dwf.stsDone: sts=dwf.DigitalInStatus(hdwf, True) print("Current digital status: %d" % sts) idx+=1 if (idx==50): break # get the samples dwf.DigitalInStatusData(hdwf, rgwSamples) print(rgwSamples) print("done\n"); return rgwSamples def main(): sel = 0x0010 a = dwf.Enum(dwf.enumfilterAll) print(a) a = dwf.EnumDeviceType(0) print(a) a = dwf.EnumDeviceIsOpened(0) print(a) fd = dwf.DeviceOpen(0) print(fd) if sel & 0x0001: a = dwf.EnumDeviceIsOpened(0) print(a) a = dwf.EnumUserName(0) print(a) a = dwf.EnumSN(0) print(a) a = dwf.GetVersion() print(a) a = dwf.EnumDeviceName(0) print(a) a = dwf.GetLastErrorMsg() print(a) if sel & 0x0002: generateSinus(fd, 0, 12346, 1.41, sqrt(2)) data = AcquireAnalog(fd, 1000, 1000E3) plt.plot(data) print(np.mean(data), np.std(data)) plt.show() generateSinus(fd, 1, 12346, 1.00, sqrt(2)) data = AcquireAnalog(fd, 1000, 1000E3, 1) plt.plot(data) print(np.mean(data), np.std(data)) plt.show() if sel & 0x0004: generateDigitalPattern8(fd, [0,1,2,3,4,5,6,7], 1E3) data = AcquireDigital(fd, 1024) print(data, len(data)) if sel & 0x0008: DigitalIO(fd) if sel & 0x0010: SysMon(fd, 10) dwf.DeviceClose(fd) if __name__ == '__main__': main()
lgpl-3.0
revelator/Revelation-Engine
Extras/ModSources/sikkmod/game/Item.cpp
36747
// Copyright (C) 2004 Id Software, Inc. // #include "../idlib/precompiled.h" #pragma hdrstop #include "Game_local.h" /* =============================================================================== idItem =============================================================================== */ const idEventDef EV_DropToFloor("<dropToFloor>"); const idEventDef EV_RespawnItem("respawn"); const idEventDef EV_RespawnFx("<respawnFx>"); const idEventDef EV_GetPlayerPos("<getplayerpos>"); const idEventDef EV_HideObjective("<hideobjective>", "e"); const idEventDef EV_CamShot("<camshot>"); CLASS_DECLARATION(idEntity, idItem) EVENT(EV_DropToFloor, idItem::Event_DropToFloor) EVENT(EV_Touch, idItem::Event_Touch) EVENT(EV_Activate, idItem::Event_Trigger) EVENT(EV_RespawnItem, idItem::Event_Respawn) EVENT(EV_RespawnFx, idItem::Event_RespawnFx) END_CLASS /* ================ idItem::idItem ================ */ idItem::idItem() { spin = false; inView = false; inViewTime = 0; lastCycle = 0; lastRenderViewTime = -1; itemShellHandle = -1; shellMaterial = NULL; orgOrigin.Zero(); canPickUp = true; fl.networkSync = true; noPickup = false; // sikk - Item Management: Manual Item Pickup } /* ================ idItem::~idItem ================ */ idItem::~idItem() { // remove the highlight shell if (itemShellHandle != -1) { gameRenderWorld->FreeEntityDef(itemShellHandle); } } /* ================ idItem::Save ================ */ void idItem::Save(idSaveGame *savefile) const { savefile->WriteVec3(orgOrigin); savefile->WriteBool(spin); savefile->WriteBool(pulse); savefile->WriteBool(canPickUp); savefile->WriteMaterial(shellMaterial); savefile->WriteBool(inView); savefile->WriteInt(inViewTime); savefile->WriteInt(lastCycle); savefile->WriteInt(lastRenderViewTime); } /* ================ idItem::Restore ================ */ void idItem::Restore(idRestoreGame *savefile) { savefile->ReadVec3(orgOrigin); savefile->ReadBool(spin); savefile->ReadBool(pulse); savefile->ReadBool(canPickUp); savefile->ReadMaterial(shellMaterial); savefile->ReadBool(inView); savefile->ReadInt(inViewTime); savefile->ReadInt(lastCycle); savefile->ReadInt(lastRenderViewTime); itemShellHandle = -1; } /* ================ idItem::UpdateRenderEntity ================ */ bool idItem::UpdateRenderEntity(renderEntity_s *renderEntity, const renderView_t *renderView) const { if (lastRenderViewTime == renderView->time) { return false; } lastRenderViewTime = renderView->time; // check for glow highlighting if near the center of the view idVec3 dir = renderEntity->origin - renderView->vieworg; dir.Normalize(); float d = dir * renderView->viewaxis[0]; // two second pulse cycle float cycle = (renderView->time - inViewTime) / 2000.0f; if (d > 0.94f) { if (!inView) { inView = true; if (cycle > lastCycle) { // restart at the beginning inViewTime = renderView->time; cycle = 0.0f; } } } else { if (inView) { inView = false; lastCycle = ceil(cycle); } } // fade down after the last pulse finishes if (!inView && cycle > lastCycle) { renderEntity->shaderParms[4] = 0.0f; } else { // pulse up in 1/4 second cycle -= (int)cycle; if (cycle < 0.1f) { renderEntity->shaderParms[4] = cycle * 10.0f; } else if (cycle < 0.2f) { renderEntity->shaderParms[4] = 1.0f; } else if (cycle < 0.3f) { renderEntity->shaderParms[4] = 1.0f - (cycle - 0.2f) * 10.0f; } else { // stay off between pulses renderEntity->shaderParms[4] = 0.0f; } } // update every single time this is in view return true; } /* ================ idItem::ModelCallback ================ */ bool idItem::ModelCallback(renderEntity_t *renderEntity, const renderView_t *renderView) { const idItem *ent; // this may be triggered by a model trace or other non-view related source if (!renderView) { return false; } ent = static_cast<idItem *>(gameLocal.entities[renderEntity->entityNum]); if (!ent) { gameLocal.Error("idItem::ModelCallback: callback with NULL game entity"); } return ent->UpdateRenderEntity(renderEntity, renderView); } /* ================ idItem::Think ================ */ void idItem::Think(void) { if (thinkFlags & TH_THINK) { if (spin) { idAngles ang; idVec3 org; ang.pitch = ang.roll = 0.0f; ang.yaw = (gameLocal.time & 4095) * 360.0f / -4096.0f; SetAngles(ang); float scale = 0.005f + entityNumber * 0.00001f; org = orgOrigin; org.z += 4.0f + cos((gameLocal.time + 2000) * scale) * 4.0f; SetOrigin(org); } } Present(); } /* ================ idItem::Present ================ */ void idItem::Present(void) { idEntity::Present(); if (!fl.hidden && pulse) { // also add a highlight shell model renderEntity_t shell; shell = renderEntity; // we will mess with shader parms when the item is in view // to give the "item pulse" effect shell.callback = idItem::ModelCallback; shell.entityNum = entityNumber; shell.customShader = shellMaterial; if (itemShellHandle == -1) { itemShellHandle = gameRenderWorld->AddEntityDef(&shell); } else { gameRenderWorld->UpdateEntityDef(itemShellHandle, &shell); } } } // sikk---> Item Management: Random Item Value /* ================ idItem::GetRandomValue ================ */ int idItem::GetRandomValue(const char *invName) { int n = spawnArgs.GetInt(invName) * (1.0f - g_itemValueFactor.GetFloat() * gameLocal.random.RandomFloat()); n = (n < 1) ? 1 : n; return n; } // <---sikk /* ================ idItem::Spawn ================ */ void idItem::Spawn(void) { idStr giveTo; idEntity *ent; float tsize; if (spawnArgs.GetBool("dropToFloor")) { PostEventMS(&EV_DropToFloor, 0); } if (spawnArgs.GetFloat("triggersize", "0", tsize)) { GetPhysics()->GetClipModel()->LoadModel(idTraceModel(idBounds(vec3_origin).Expand(tsize))); GetPhysics()->GetClipModel()->Link(gameLocal.clip); } if (spawnArgs.GetBool("start_off")) { GetPhysics()->SetContents(0); Hide(); } else { GetPhysics()->SetContents(CONTENTS_TRIGGER); } giveTo = spawnArgs.GetString("owner"); if (giveTo.Length()) { ent = gameLocal.FindEntity(giveTo); if (!ent) { gameLocal.Error("Item couldn't find owner '%s'", giveTo.c_str()); } PostEventMS(&EV_Touch, 0, ent, NULL); } if (spawnArgs.GetBool("spin") || gameLocal.isMultiplayer) { spin = true; BecomeActive(TH_THINK); } //pulse = !spawnArgs.GetBool( "nopulse" ); //temp hack for tim pulse = false; orgOrigin = GetPhysics()->GetOrigin(); canPickUp = !(spawnArgs.GetBool("triggerFirst") || spawnArgs.GetBool("no_touch")); inViewTime = -1000; lastCycle = -1; itemShellHandle = -1; shellMaterial = declManager->FindMaterial("itemHighlightShell"); // sikk---> Item Management: Random Item Value if (g_itemValueFactor.GetFloat()) { // random ammo values if (spawnArgs.GetInt("inv_ammo_shells")) { spawnArgs.SetInt("inv_ammo_shells", GetRandomValue("inv_ammo_shells")); } if (spawnArgs.GetInt("inv_ammo_bullets")) { spawnArgs.SetInt("inv_ammo_bullets", GetRandomValue("inv_ammo_bullets")); } if (spawnArgs.GetInt("inv_ammo_rockets")) { spawnArgs.SetInt("inv_ammo_rockets", GetRandomValue("inv_ammo_rockets")); } if (spawnArgs.GetInt("inv_ammo_cells")) { spawnArgs.SetInt("inv_ammo_cells", GetRandomValue("inv_ammo_cells")); } if (spawnArgs.GetInt("inv_ammo_grenades")) { spawnArgs.SetInt("inv_ammo_grenades", GetRandomValue("inv_ammo_grenades")); } if (spawnArgs.GetInt("inv_ammo_bfg")) { spawnArgs.SetInt("inv_ammo_bfg", GetRandomValue("inv_ammo_bfg")); } if (spawnArgs.GetInt("inv_ammo_clip")) { spawnArgs.SetInt("inv_ammo_clip", GetRandomValue("inv_ammo_clip")); } if (spawnArgs.GetInt("inv_ammo_belt")) { spawnArgs.SetInt("inv_ammo_belt", GetRandomValue("inv_ammo_belt")); } // random health values if (spawnArgs.GetInt("inv_health")) { spawnArgs.SetInt("inv_health", GetRandomValue("inv_health")); } // random armor values if (spawnArgs.GetInt("inv_armor")) { spawnArgs.SetInt("inv_armor", GetRandomValue("inv_armor")); } // random air values if (spawnArgs.GetInt("inv_air")) { spawnArgs.SetInt("inv_air", GetRandomValue("inv_air")); } } // <---sikk } /* ================ idItem::GetAttributes ================ */ void idItem::GetAttributes(idDict &attributes) { int i; const idKeyValue *arg; for (i = 0; i < spawnArgs.GetNumKeyVals(); i++) { arg = spawnArgs.GetKeyVal(i); if (arg->GetKey().Left(4) == "inv_") { attributes.Set(arg->GetKey().Right(arg->GetKey().Length() - 4), arg->GetValue()); } } } /* ================ idItem::GiveToPlayer ================ */ bool idItem::GiveToPlayer(idPlayer *player) { if (player == NULL) { return false; } // sikk---> Item Management: Manual Item Pickup if (noPickup) { return false; } // <---sikk if (spawnArgs.GetBool("inv_carry")) { return player->GiveInventoryItem(&spawnArgs); } return player->GiveItem(this); } /* ================ idItem::Pickup ================ */ bool idItem::Pickup(idPlayer *player) { if (!GiveToPlayer(player)) { return false; } if (gameLocal.isServer) { ServerSendEvent(EVENT_PICKUP, NULL, false, -1); } // play pickup sound StartSound("snd_acquire", SND_CHANNEL_ITEM, 0, false, NULL); // trigger our targets ActivateTargets(player); // clear our contents so the object isn't picked up twice GetPhysics()->SetContents(0); // hide the model Hide(); // add the highlight shell if (itemShellHandle != -1) { gameRenderWorld->FreeEntityDef(itemShellHandle); itemShellHandle = -1; } float respawn = spawnArgs.GetFloat("respawn"); bool dropped = spawnArgs.GetBool("dropped"); bool no_respawn = spawnArgs.GetBool("no_respawn"); if (gameLocal.isMultiplayer && respawn == 0.0f) { respawn = 20.0f; } if (respawn && !dropped && !no_respawn) { const char *sfx = spawnArgs.GetString("fxRespawn"); if (sfx && *sfx) { PostEventSec(&EV_RespawnFx, respawn - 0.5f); } PostEventSec(&EV_RespawnItem, respawn); } else if (!spawnArgs.GetBool("inv_objective") && !no_respawn) { // give some time for the pickup sound to play // FIXME: Play on the owner if (!spawnArgs.GetBool("inv_carry")) { PostEventMS(&EV_Remove, 5000); } } noPickup = true; // sikk - Item Management: Manual Item Pickup BecomeInactive(TH_THINK); return true; } /* ================ idItem::ClientPredictionThink ================ */ void idItem::ClientPredictionThink(void) { // only think forward because the state is not synced through snapshots if (!gameLocal.isNewFrame) { return; } Think(); } /* ================ idItem::WriteFromSnapshot ================ */ void idItem::WriteToSnapshot(idBitMsgDelta &msg) const { msg.WriteBits(IsHidden(), 1); } /* ================ idItem::ReadFromSnapshot ================ */ void idItem::ReadFromSnapshot(const idBitMsgDelta &msg) { if (msg.ReadBits(1)) { Hide(); } else { Show(); } } /* ================ idItem::ClientReceiveEvent ================ */ bool idItem::ClientReceiveEvent(int event, int time, const idBitMsg &msg) { switch (event) { case EVENT_PICKUP: { // play pickup sound StartSound("snd_acquire", SND_CHANNEL_ITEM, 0, false, NULL); // hide the model Hide(); // remove the highlight shell if (itemShellHandle != -1) { gameRenderWorld->FreeEntityDef(itemShellHandle); itemShellHandle = -1; } return true; } case EVENT_RESPAWN: { Event_Respawn(); return true; } case EVENT_RESPAWNFX: { Event_RespawnFx(); return true; } default: { break; } } return idEntity::ClientReceiveEvent(event, time, msg); } /* ================ idItem::Event_DropToFloor ================ */ void idItem::Event_DropToFloor(void) { trace_t trace; // don't drop the floor if bound to another entity if (GetBindMaster() != NULL && GetBindMaster() != this) { return; } gameLocal.clip.TraceBounds(trace, renderEntity.origin, renderEntity.origin - idVec3(0, 0, 64), renderEntity.bounds, MASK_SOLID | CONTENTS_CORPSE, this); SetOrigin(trace.endpos); } /* ================ idItem::Event_Touch ================ */ void idItem::Event_Touch(idEntity *other, trace_t *trace) { if (!other->IsType(idPlayer::Type)) { return; } if (!canPickUp) { return; } // sikk---> Manual Item Pickup if (!g_itemPickupType.GetBool() || spawnArgs.GetBool("autopickup")) { Pickup(static_cast<idPlayer *>(other)); } // <---sikk } /* ================ idItem::Event_Trigger ================ */ void idItem::Event_Trigger(idEntity *activator) { if (!canPickUp && spawnArgs.GetBool("triggerFirst")) { canPickUp = true; return; } if (activator && activator->IsType(idPlayer::Type)) { Pickup(static_cast<idPlayer *>(activator)); } } /* ================ idItem::Event_Respawn ================ */ void idItem::Event_Respawn(void) { if (gameLocal.isServer) { ServerSendEvent(EVENT_RESPAWN, NULL, false, -1); } BecomeActive(TH_THINK); Show(); inViewTime = -1000; lastCycle = -1; GetPhysics()->SetContents(CONTENTS_TRIGGER); SetOrigin(orgOrigin); StartSound("snd_respawn", SND_CHANNEL_ITEM, 0, false, NULL); CancelEvents(&EV_RespawnItem); // don't double respawn } /* ================ idItem::Event_RespawnFx ================ */ void idItem::Event_RespawnFx(void) { if (gameLocal.isServer) { ServerSendEvent(EVENT_RESPAWNFX, NULL, false, -1); } const char *sfx = spawnArgs.GetString("fxRespawn"); if (sfx && *sfx) { idEntityFx::StartFx(sfx, NULL, NULL, this, true); } } /* =============================================================================== idItemPowerup =============================================================================== */ /* =============== idItemPowerup =============== */ CLASS_DECLARATION(idItem, idItemPowerup) END_CLASS /* ================ idItemPowerup::idItemPowerup ================ */ idItemPowerup::idItemPowerup() { time = 0; type = 0; } /* ================ idItemPowerup::Save ================ */ void idItemPowerup::Save(idSaveGame *savefile) const { savefile->WriteInt(time); savefile->WriteInt(type); } /* ================ idItemPowerup::Restore ================ */ void idItemPowerup::Restore(idRestoreGame *savefile) { savefile->ReadInt(time); savefile->ReadInt(type); } /* ================ idItemPowerup::Spawn ================ */ void idItemPowerup::Spawn(void) { time = spawnArgs.GetInt("time", "30"); type = spawnArgs.GetInt("type", "0"); } /* ================ idItemPowerup::GiveToPlayer ================ */ bool idItemPowerup::GiveToPlayer(idPlayer *player) { if (player->spectating) { return false; } // sikk---> Adrenaline Pack System // player->GivePowerUp( type, time * 1000 ); // return true; return player->GivePowerUp(type, time * 1000); // <---sikk } /* =============================================================================== idObjective =============================================================================== */ CLASS_DECLARATION(idItem, idObjective) EVENT(EV_Activate, idObjective::Event_Trigger) EVENT(EV_HideObjective, idObjective::Event_HideObjective) EVENT(EV_GetPlayerPos, idObjective::Event_GetPlayerPos) EVENT(EV_CamShot, idObjective::Event_CamShot) END_CLASS /* ================ idObjective::idObjective ================ */ idObjective::idObjective() { playerPos.Zero(); } /* ================ idObjective::Save ================ */ void idObjective::Save(idSaveGame *savefile) const { savefile->WriteVec3(playerPos); } /* ================ idObjective::Restore ================ */ void idObjective::Restore(idRestoreGame *savefile) { savefile->ReadVec3(playerPos); PostEventMS(&EV_CamShot, 250); } /* ================ idObjective::Spawn ================ */ void idObjective::Spawn(void) { Hide(); PostEventMS(&EV_CamShot, 250); } /* ================ idObjective::Event_Screenshot ================ */ void idObjective::Event_CamShot() { const char *camName; idStr shotName = gameLocal.GetMapName(); shotName.StripFileExtension(); shotName += "/"; shotName += spawnArgs.GetString("screenshot"); shotName.SetFileExtension(".tga"); if (spawnArgs.GetString("camShot", "", &camName)) { idEntity *ent = gameLocal.FindEntity(camName); if (ent && ent->cameraTarget) { const renderView_t *view = ent->cameraTarget->GetRenderView(); renderView_t fullView = *view; fullView.width = SCREEN_WIDTH; fullView.height = SCREEN_HEIGHT; // sikk---> Portal Sky Box // HACK : always draw sky-portal view if there is one in the map, this isn't real-time if (gameLocal.portalSkyEnt.GetEntity() && g_enablePortalSky.GetBool()) { renderView_t portalView = fullView; portalView.vieworg = gameLocal.portalSkyEnt.GetEntity()->GetPhysics()->GetOrigin(); // setup global fixup projection vars int i, w, h; renderSystem->GetGLSettings(w, h); for (i = 1; i < w; i <<= 1) {} fullView.shaderParms[4] = (float)w / (float)i; for (i = 1; i < h; i <<= 1) {} fullView.shaderParms[5] = (float)h / (float)i; gameRenderWorld->RenderScene(&portalView); renderSystem->CaptureRenderToImage("_currentRender"); } // <---sikk // draw a view to a texture renderSystem->CropRenderSize(256, 256, true); gameRenderWorld->RenderScene(&fullView); renderSystem->CaptureRenderToFile(shotName); renderSystem->UnCrop(); } } } /* ================ idObjective::Event_Trigger ================ */ void idObjective::Event_Trigger(idEntity *activator) { idPlayer *player = gameLocal.GetLocalPlayer(); if (player) { //Pickup( player ); if (spawnArgs.GetString("inv_objective", NULL)) { if (player && player->hud) { idStr shotName = gameLocal.GetMapName(); shotName.StripFileExtension(); shotName += "/"; shotName += spawnArgs.GetString("screenshot"); shotName.SetFileExtension(".tga"); player->hud->SetStateString("screenshot", shotName); player->hud->SetStateString("objective", "1"); player->hud->SetStateString("objectivetext", spawnArgs.GetString("objectivetext")); player->hud->SetStateString("objectivetitle", spawnArgs.GetString("objectivetitle")); player->GiveObjective(spawnArgs.GetString("objectivetitle"), spawnArgs.GetString("objectivetext"), shotName); // a tad slow but keeps from having to update all objectives in all maps with a name ptr for (int i = 0; i < gameLocal.num_entities; i++) { if (gameLocal.entities[i] && gameLocal.entities[i]->IsType(idObjectiveComplete::Type)) { if (idStr::Icmp(spawnArgs.GetString("objectivetitle"), gameLocal.entities[i]->spawnArgs.GetString("objectivetitle")) == 0) { gameLocal.entities[i]->spawnArgs.SetBool("objEnabled", true); break; } } } PostEventMS(&EV_GetPlayerPos, 2000); } } } } /* ================ idObjective::Event_GetPlayerPos ================ */ void idObjective::Event_GetPlayerPos() { idPlayer *player = gameLocal.GetLocalPlayer(); if (player) { playerPos = player->GetPhysics()->GetOrigin(); PostEventMS(&EV_HideObjective, 100, player); } } /* ================ idObjective::Event_HideObjective ================ */ void idObjective::Event_HideObjective(idEntity *e) { idPlayer *player = gameLocal.GetLocalPlayer(); if (player) { idVec3 v = player->GetPhysics()->GetOrigin() - playerPos; if (v.Length() > 64.0f) { player->HideObjective(); PostEventMS(&EV_Remove, 0); } else { PostEventMS(&EV_HideObjective, 100, player); } } } /* =============================================================================== idVideoCDItem =============================================================================== */ CLASS_DECLARATION(idItem, idVideoCDItem) END_CLASS /* ================ idVideoCDItem::Spawn ================ */ void idVideoCDItem::Spawn(void) { } /* ================ idVideoCDItem::GiveToPlayer ================ */ bool idVideoCDItem::GiveToPlayer(idPlayer *player) { idStr str = spawnArgs.GetString("video"); if (player && str.Length()) { player->GiveVideo(str, &spawnArgs); } return true; } /* =============================================================================== idPDAItem =============================================================================== */ CLASS_DECLARATION(idItem, idPDAItem) END_CLASS /* ================ idPDAItem::GiveToPlayer ================ */ bool idPDAItem::GiveToPlayer(idPlayer *player) { const char *str = spawnArgs.GetString("pda_name"); if (player) { player->GivePDA(str, &spawnArgs); } return true; } /* =============================================================================== idMoveableItem =============================================================================== */ CLASS_DECLARATION(idItem, idMoveableItem) EVENT(EV_DropToFloor, idMoveableItem::Event_DropToFloor) EVENT(EV_Gib, idMoveableItem::Event_Gib) END_CLASS /* ================ idMoveableItem::idMoveableItem ================ */ idMoveableItem::idMoveableItem() { trigger = NULL; smoke = NULL; smokeTime = 0; nextSoundTime = 0; // sikk - Moveable Items Collision Sound } /* ================ idMoveableItem::~idMoveableItem ================ */ idMoveableItem::~idMoveableItem() { if (trigger) { delete trigger; } } /* ================ idMoveableItem::Save ================ */ void idMoveableItem::Save(idSaveGame *savefile) const { savefile->WriteStaticObject(physicsObj); savefile->WriteClipModel(trigger); savefile->WriteParticle(smoke); savefile->WriteInt(smokeTime); savefile->WriteInt(nextSoundTime); // sikk - Moveable Items Collision Sound } /* ================ idMoveableItem::Restore ================ */ void idMoveableItem::Restore(idRestoreGame *savefile) { savefile->ReadStaticObject(physicsObj); RestorePhysics(&physicsObj); savefile->ReadClipModel(trigger); savefile->ReadParticle(smoke); savefile->ReadInt(smokeTime); savefile->ReadInt(nextSoundTime); // sikk - Moveable Items Collision Sound } /* ================ idMoveableItem::Spawn ================ */ void idMoveableItem::Spawn(void) { idTraceModel trm; float density, friction, bouncyness, tsize; idStr clipModelName; idBounds bounds; // create a trigger for item pickup spawnArgs.GetFloat("triggersize", "24.0", tsize); // sikk - Increased default triggersize from 16 to 24 trigger = new idClipModel(idTraceModel(idBounds(vec3_origin).Expand(tsize))); trigger->Link(gameLocal.clip, this, 0, GetPhysics()->GetOrigin(), GetPhysics()->GetAxis()); trigger->SetContents(CONTENTS_TRIGGER); // check if a clip model is set spawnArgs.GetString("clipmodel", "", clipModelName); if (!clipModelName[0]) { clipModelName = spawnArgs.GetString("model"); // use the visual model } // load the trace model if (!collisionModelManager->TrmFromModel(clipModelName, trm)) { gameLocal.Error("idMoveableItem '%s': cannot load collision model %s", name.c_str(), clipModelName.c_str()); return; } // if the model should be shrinked if (spawnArgs.GetBool("clipshrink")) { trm.Shrink(CM_CLIP_EPSILON); } // get rigid body properties spawnArgs.GetFloat("density", "0.5", density); density = idMath::ClampFloat(0.001f, 1000.0f, density); spawnArgs.GetFloat("friction", "0.05", friction); friction = idMath::ClampFloat(0.0f, 1.0f, friction); spawnArgs.GetFloat("bouncyness", "0.6", bouncyness); bouncyness = idMath::ClampFloat(0.0f, 1.0f, bouncyness); // sikk---> Temp Fix for moveable items that spawn inside geometry idVec3 offset = idVec3(0.0f, 0.0f, 0.0f); if (!idStr::Icmp(spawnArgs.GetString("bind"), "")) { offset = idVec3(0.0f, 0.0f, 4.0f); } // <---sikk // setup the physics physicsObj.SetSelf(this); physicsObj.SetClipModel(new idClipModel(trm), density); physicsObj.SetOrigin(GetPhysics()->GetOrigin() + offset); // sikk - Temp Fix for moveable items that spawn inside geometry physicsObj.SetAxis(GetPhysics()->GetAxis()); physicsObj.SetBouncyness(bouncyness); physicsObj.SetFriction(0.6f, 0.6f, friction); physicsObj.SetGravity(gameLocal.GetGravity()); // sikk---> We want moveable items to clip with other items and we also want ragdolls to clip with items //physicsObj.SetContents( CONTENTS_RENDERMODEL ); //physicsObj.SetClipMask( MASK_SOLID | CONTENTS_MOVEABLECLIP ); physicsObj.SetContents(CONTENTS_RENDERMODEL | CONTENTS_CORPSE); physicsObj.SetClipMask(MASK_SOLID | CONTENTS_CORPSE | CONTENTS_MOVEABLECLIP | CONTENTS_RENDERMODEL); // <---sikk SetPhysics(&physicsObj); smoke = NULL; smokeTime = 0; nextSoundTime = 0; // sikk - Moveable Items Collision Sound const char *smokeName = spawnArgs.GetString("smoke_trail"); if (*smokeName != '\0') { smoke = static_cast<const idDeclParticle *>(declManager->FindType(DECL_PARTICLE, smokeName)); smokeTime = gameLocal.time; BecomeActive(TH_UPDATEPARTICLES); } } /* ================ idMoveableItem::Think ================ */ void idMoveableItem::Think(void) { RunPhysics(); if (thinkFlags & TH_PHYSICS) { // update trigger position trigger->Link(gameLocal.clip, this, 0, GetPhysics()->GetOrigin(), mat3_identity); } if (thinkFlags & TH_UPDATEPARTICLES) { if (!gameLocal.smokeParticles->EmitSmoke(smoke, smokeTime, gameLocal.random.CRandomFloat(), GetPhysics()->GetOrigin(), GetPhysics()->GetAxis())) { smokeTime = 0; BecomeInactive(TH_UPDATEPARTICLES); } } Present(); } // sikk---> Moveable Items Collision Sound /* ================= idMoveableItem::Collide ================= */ bool idMoveableItem::Collide(const trace_t &collision, const idVec3 &velocity) { float v, f; v = -(velocity * collision.c.normal); if (v > 80 && gameLocal.time > nextSoundTime) { f = v > 200 ? 1.0f : idMath::Sqrt(v - 80) * 0.091f; if (StartSound("snd_bounce", SND_CHANNEL_ANY, 0, false, NULL)) { // don't set the volume unless there is a bounce sound as it overrides the entire channel // which causes footsteps on ai's to not honor their shader parms SetSoundVolume(f); } nextSoundTime = gameLocal.time + 500; } return false; } // <---sikk /* ================ idMoveableItem::Pickup ================ */ bool idMoveableItem::Pickup(idPlayer *player) { bool ret = idItem::Pickup(player); if (ret) { trigger->SetContents(0); } return ret; } /* ================ idMoveableItem::DropItem ================ */ idEntity *idMoveableItem::DropItem(const char *classname, const idVec3 &origin, const idMat3 &axis, const idVec3 &velocity, int activateDelay, int removeDelay) { idDict args; idEntity *item; args.Set("classname", classname); args.Set("dropped", "1"); // we sometimes drop idMoveables here, so set 'nodrop' to 1 so that it doesn't get put on the floor args.Set("nodrop", "1"); if (activateDelay) { args.SetBool("triggerFirst", true); } gameLocal.SpawnEntityDef(args, &item); if (item) { // set item position item->GetPhysics()->SetOrigin(origin); item->GetPhysics()->SetAxis(axis); item->GetPhysics()->SetLinearVelocity(velocity); item->UpdateVisuals(); if (activateDelay) { item->PostEventMS(&EV_Activate, activateDelay, item); } if (!removeDelay) { removeDelay = 5 * 60 * 1000; } // always remove a dropped item after 5 minutes in case it dropped to an unreachable location // item->PostEventMS( &EV_Remove, removeDelay ); // sikk - Dropped moveable items are no longer removed } return item; } /* ================ idMoveableItem::DropItems The entity should have the following key/value pairs set: "def_drop<type>Item" "item def" "drop<type>ItemJoint" "joint name" "drop<type>ItemRotation" "pitch yaw roll" "drop<type>ItemOffset" "x y z" "skin_drop<type>" "skin name" To drop multiple items the following key/value pairs can be used: "def_drop<type>Item<X>" "item def" "drop<type>Item<X>Joint" "joint name" "drop<type>Item<X>Rotation" "pitch yaw roll" "drop<type>Item<X>Offset" "x y z" where <X> is an aribtrary string. ================ */ void idMoveableItem::DropItems(idAnimatedEntity *ent, const char *type, idList<idEntity *> *list) { const idKeyValue *kv; const char *skinName, *c, *jointName; idStr key, key2; idVec3 origin; idMat3 axis; idAngles angles; const idDeclSkin *skin; jointHandle_t joint; idEntity *item; // drop all items kv = ent->spawnArgs.MatchPrefix(va("def_drop%sItem", type), NULL); while (kv) { c = kv->GetKey().c_str() + kv->GetKey().Length(); if (idStr::Icmp(c - 5, "Joint") != 0 && idStr::Icmp(c - 8, "Rotation") != 0) { key = kv->GetKey().c_str() + 4; key2 = key; key += "Joint"; key2 += "Offset"; jointName = ent->spawnArgs.GetString(key); joint = ent->GetAnimator()->GetJointHandle(jointName); if (!ent->GetJointWorldTransform(joint, gameLocal.time, origin, axis)) { gameLocal.Warning("%s refers to invalid joint '%s' on entity '%s'\n", key.c_str(), jointName, ent->name.c_str()); origin = ent->GetPhysics()->GetOrigin(); axis = ent->GetPhysics()->GetAxis(); } if (g_dropItemRotation.GetString()[0]) { angles.Zero(); sscanf(g_dropItemRotation.GetString(), "%f %f %f", &angles.pitch, &angles.yaw, &angles.roll); } else { key = kv->GetKey().c_str() + 4; key += "Rotation"; ent->spawnArgs.GetAngles(key, "0 0 0", angles); } axis = angles.ToMat3() * axis; origin += ent->spawnArgs.GetVector(key2, "0 0 0"); item = DropItem(kv->GetValue(), origin, axis, vec3_origin, 0, 0); if (list && item) { list->Append(item); } } kv = ent->spawnArgs.MatchPrefix(va("def_drop%sItem", type), kv); } // change the skin to hide all items skinName = ent->spawnArgs.GetString(va("skin_drop%s", type)); if (skinName[0]) { skin = declManager->FindSkin(skinName); ent->SetSkin(skin); } } /* ====================== idMoveableItem::WriteToSnapshot ====================== */ void idMoveableItem::WriteToSnapshot(idBitMsgDelta &msg) const { physicsObj.WriteToSnapshot(msg); } /* ====================== idMoveableItem::ReadFromSnapshot ====================== */ void idMoveableItem::ReadFromSnapshot(const idBitMsgDelta &msg) { physicsObj.ReadFromSnapshot(msg); if (msg.HasChanged()) { UpdateVisuals(); } } /* ============ idMoveableItem::Gib ============ */ void idMoveableItem::Gib(const idVec3 &dir, const char *damageDefName) { // spawn smoke puff const char *smokeName = spawnArgs.GetString("smoke_gib"); if (*smokeName != '\0') { const idDeclParticle *smoke = static_cast<const idDeclParticle *>(declManager->FindType(DECL_PARTICLE, smokeName)); gameLocal.smokeParticles->EmitSmoke(smoke, gameLocal.time, gameLocal.random.CRandomFloat(), renderEntity.origin, renderEntity.axis); } // remove the entity PostEventMS(&EV_Remove, 0); } /* ================ idMoveableItem::Event_DropToFloor ================ */ void idMoveableItem::Event_DropToFloor(void) { // the physics will drop the moveable to the floor } /* ============ idMoveableItem::Event_Gib ============ */ void idMoveableItem::Event_Gib(const char *damageDefName) { Gib(idVec3(0, 0, 1), damageDefName); } /* =============================================================================== idMoveablePDAItem =============================================================================== */ CLASS_DECLARATION(idMoveableItem, idMoveablePDAItem) END_CLASS /* ================ idMoveablePDAItem::GiveToPlayer ================ */ bool idMoveablePDAItem::GiveToPlayer(idPlayer *player) { const char *str = spawnArgs.GetString("pda_name"); if (player) { player->GivePDA(str, &spawnArgs); } return true; } // sikk---> Moveable Video CD /* =============================================================================== idMoveableVideoCDItem =============================================================================== */ CLASS_DECLARATION(idMoveableItem, idMoveableVideoCDItem) END_CLASS /* ================ idMoveableVideoCDItem::Spawn ================ */ void idMoveableVideoCDItem::Spawn(void) { } /* ================ idMoveableVideoCDItem::GiveToPlayer ================ */ bool idMoveableVideoCDItem::GiveToPlayer(idPlayer *player) { idStr str = spawnArgs.GetString("video"); if (player && str.Length()) { player->GiveVideo(str, &spawnArgs); } return true; } // <---sikk // sikk---> Moveable Powerup /* =============================================================================== idMoveableItemPowerup =============================================================================== */ /* =============== idMoveableItemPowerup =============== */ CLASS_DECLARATION(idMoveableItem, idMoveableItemPowerup) END_CLASS /* ================ idMoveableItemPowerup::idMoveableItemPowerup ================ */ idMoveableItemPowerup::idMoveableItemPowerup() { time = 0; type = 0; } /* ================ idMoveableItemPowerup::Save ================ */ void idMoveableItemPowerup::Save(idSaveGame *savefile) const { savefile->WriteInt(time); savefile->WriteInt(type); } /* ================ idMoveableItemPowerup::Restore ================ */ void idMoveableItemPowerup::Restore(idRestoreGame *savefile) { savefile->ReadInt(time); savefile->ReadInt(type); } /* ================ idMoveableItemPowerup::Spawn ================ */ void idMoveableItemPowerup::Spawn(void) { time = spawnArgs.GetInt("time", "30"); type = spawnArgs.GetInt("type", "0"); } /* ================ idMoveableItemPowerup::GiveToPlayer ================ */ bool idMoveableItemPowerup::GiveToPlayer(idPlayer *player) { if (player->spectating) { return false; } // sikk---> Adrenaline Pack System // player->GivePowerUp( type, time * 1000 ); // return true; return player->GivePowerUp(type, time * 1000); // <---sikk } // <---sikk /* =============================================================================== idItemRemover =============================================================================== */ CLASS_DECLARATION(idEntity, idItemRemover) EVENT(EV_Activate, idItemRemover::Event_Trigger) END_CLASS /* ================ idItemRemover::Spawn ================ */ void idItemRemover::Spawn(void) { } /* ================ idItemRemover::RemoveItem ================ */ void idItemRemover::RemoveItem(idPlayer *player) { const char *remove; remove = spawnArgs.GetString("remove"); player->RemoveInventoryItem(remove); } /* ================ idItemRemover::Event_Trigger ================ */ void idItemRemover::Event_Trigger(idEntity *activator) { if (activator->IsType(idPlayer::Type)) { RemoveItem(static_cast<idPlayer *>(activator)); } } /* =============================================================================== idObjectiveComplete =============================================================================== */ CLASS_DECLARATION(idItemRemover, idObjectiveComplete) EVENT(EV_Activate, idObjectiveComplete::Event_Trigger) EVENT(EV_HideObjective, idObjectiveComplete::Event_HideObjective) EVENT(EV_GetPlayerPos, idObjectiveComplete::Event_GetPlayerPos) END_CLASS /* ================ idObjectiveComplete::idObjectiveComplete ================ */ idObjectiveComplete::idObjectiveComplete() { playerPos.Zero(); } /* ================ idObjectiveComplete::Save ================ */ void idObjectiveComplete::Save(idSaveGame *savefile) const { savefile->WriteVec3(playerPos); } /* ================ idObjectiveComplete::Restore ================ */ void idObjectiveComplete::Restore(idRestoreGame *savefile) { savefile->ReadVec3(playerPos); } /* ================ idObjectiveComplete::Spawn ================ */ void idObjectiveComplete::Spawn(void) { spawnArgs.SetBool("objEnabled", false); Hide(); } /* ================ idObjectiveComplete::Event_Trigger ================ */ void idObjectiveComplete::Event_Trigger(idEntity *activator) { if (!spawnArgs.GetBool("objEnabled")) { return; } idPlayer *player = gameLocal.GetLocalPlayer(); if (player) { RemoveItem(player); if (spawnArgs.GetString("inv_objective", NULL)) { if (player->hud) { player->hud->SetStateString("objective", "2"); player->hud->SetStateString("objectivetext", spawnArgs.GetString("objectivetext")); player->hud->SetStateString("objectivetitle", spawnArgs.GetString("objectivetitle")); player->CompleteObjective(spawnArgs.GetString("objectivetitle")); PostEventMS(&EV_GetPlayerPos, 2000); } } } } /* ================ idObjectiveComplete::Event_GetPlayerPos ================ */ void idObjectiveComplete::Event_GetPlayerPos() { idPlayer *player = gameLocal.GetLocalPlayer(); if (player) { playerPos = player->GetPhysics()->GetOrigin(); PostEventMS(&EV_HideObjective, 100, player); } } /* ================ idObjectiveComplete::Event_HideObjective ================ */ void idObjectiveComplete::Event_HideObjective(idEntity *e) { idPlayer *player = gameLocal.GetLocalPlayer(); if (player) { idVec3 v = player->GetPhysics()->GetOrigin(); v -= playerPos; if (v.Length() > 64.0f) { player->hud->HandleNamedEvent("closeObjective"); PostEventMS(&EV_Remove, 0); } else { PostEventMS(&EV_HideObjective, 100, player); } } }
lgpl-3.0
kingjiang/SharpDevelopLite
samples/CodeConverter/Source/ICSharpCode.CodeConversion/SnippetConversion.cs
3286
using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using ICSharpCode.NRefactory; using ICSharpCode.SharpDevelop.Dom; using ICSharpCode.SharpDevelop.Dom.NRefactoryResolver; namespace ICSharpCode.CodeConversion { public class ConvertCSharpSnippetToVbNet : IConvertCode { public bool Convert(string ProvidedSource, out string ConvertedSource, out string ErrorMessage) { CodeSnippetConverter converter = new CodeSnippetConverter() { ReferencedContents = ReferencedContentsSingleton.ReferencedContents }; ConvertedSource = converter.CSharpToVB(ProvidedSource, out ErrorMessage); return (ErrorMessage.Length == 0); } } public class ConvertVbNetSnippetToCSharp : IConvertCode { public bool Convert(string ProvidedSource, out string ConvertedSource, out string ErrorMessage) { CodeSnippetConverter converter = new CodeSnippetConverter() { ReferencedContents = ReferencedContentsSingleton.ReferencedContents }; ConvertedSource = converter.VBToCSharp(ProvidedSource, out ErrorMessage); return (ErrorMessage.Length == 0); } } public class ConvertCSharpToBoo : IConvertCode { public bool Convert(string ProvidedSource, out string ConvertedSource, out string ErrorMessage) { bool bSuccessfulConversion = BooHelpers.ConvertToBoo("convert.cs", ProvidedSource, out ConvertedSource, out ErrorMessage); return bSuccessfulConversion; } } public class ConvertVbNetToBoo : IConvertCode { public bool Convert(string ProvidedSource, out string ConvertedSource, out string ErrorMessage) { bool bSuccessfulConversion = BooHelpers.ConvertToBoo("convert.vb", ProvidedSource, out ConvertedSource, out ErrorMessage); return bSuccessfulConversion; } } public class ConvertCSharpToPython : IConvertCode { public bool Convert(string ProvidedSource, out string ConvertedSource, out string ErrorMessage) { return PythonHelpers.Convert(SupportedLanguage.CSharp, ProvidedSource, out ConvertedSource, out ErrorMessage); } } public class ConvertCSharpToRuby : IConvertCode { public bool Convert(string ProvidedSource, out string ConvertedSource, out string ErrorMessage) { return RubyHelpers.Convert(SupportedLanguage.CSharp, ProvidedSource, out ConvertedSource, out ErrorMessage); } } public class ConvertVbNetToPython : IConvertCode { public bool Convert(string ProvidedSource, out string ConvertedSource, out string ErrorMessage) { return PythonHelpers.Convert(SupportedLanguage.VBNet, ProvidedSource, out ConvertedSource, out ErrorMessage); } } public class ConvertVbNetToRuby : IConvertCode { public bool Convert(string ProvidedSource, out string ConvertedSource, out string ErrorMessage) { return RubyHelpers.Convert(SupportedLanguage.VBNet, ProvidedSource, out ConvertedSource, out ErrorMessage); } } }
lgpl-3.0
kyungtaekLIM/PSI-BLASTexB
src/ncbi-blast-2.5.0+/c++/include/objects/biblio/PubStatusDate_.hpp
5590
/* $Id$ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * */ /// @file PubStatusDate_.hpp /// Data storage class. /// /// This file was generated by application DATATOOL /// using the following specifications: /// 'biblio.asn'. /// /// ATTENTION: /// Don't edit or commit this file into CVS as this file will /// be overridden (by DATATOOL) without warning! #ifndef OBJECTS_BIBLIO_PUBSTATUSDATE_BASE_HPP #define OBJECTS_BIBLIO_PUBSTATUSDATE_BASE_HPP // standard includes #include <serial/serialbase.hpp> // generated includes #include <objects/biblio/PubStatus.hpp> BEGIN_NCBI_SCOPE #ifndef BEGIN_objects_SCOPE # define BEGIN_objects_SCOPE BEGIN_SCOPE(objects) # define END_objects_SCOPE END_SCOPE(objects) #endif BEGIN_objects_SCOPE // namespace ncbi::objects:: // forward declarations class CDate; // generated classes ///////////////////////////////////////////////////////////////////////////// /// done as a structure so fields can be added class NCBI_BIBLIO_EXPORT CPubStatusDate_Base : public CSerialObject { typedef CSerialObject Tparent; public: // constructor CPubStatusDate_Base(void); // destructor virtual ~CPubStatusDate_Base(void); // type info DECLARE_INTERNAL_TYPE_INFO(); // types typedef int TPubstatus; typedef CDate TDate; // getters // setters /// mandatory /// typedef int TPubstatus /// Check whether the Pubstatus data member has been assigned a value. bool IsSetPubstatus(void) const; /// Check whether it is safe or not to call GetPubstatus method. bool CanGetPubstatus(void) const; void ResetPubstatus(void); TPubstatus GetPubstatus(void) const; void SetPubstatus(TPubstatus value); TPubstatus& SetPubstatus(void); /// time may be added later /// mandatory /// typedef CDate TDate /// Check whether the Date data member has been assigned a value. bool IsSetDate(void) const; /// Check whether it is safe or not to call GetDate method. bool CanGetDate(void) const; void ResetDate(void); const TDate& GetDate(void) const; void SetDate(TDate& value); TDate& SetDate(void); /// Reset the whole object virtual void Reset(void); private: // Prohibit copy constructor and assignment operator CPubStatusDate_Base(const CPubStatusDate_Base&); CPubStatusDate_Base& operator=(const CPubStatusDate_Base&); // data Uint4 m_set_State[1]; int m_Pubstatus; CRef< TDate > m_Date; }; /////////////////////////////////////////////////////////// ///////////////////// inline methods ////////////////////// /////////////////////////////////////////////////////////// inline bool CPubStatusDate_Base::IsSetPubstatus(void) const { return ((m_set_State[0] & 0x3) != 0); } inline bool CPubStatusDate_Base::CanGetPubstatus(void) const { return IsSetPubstatus(); } inline void CPubStatusDate_Base::ResetPubstatus(void) { m_Pubstatus = (int)(0); m_set_State[0] &= ~0x3; } inline CPubStatusDate_Base::TPubstatus CPubStatusDate_Base::GetPubstatus(void) const { if (!CanGetPubstatus()) { ThrowUnassigned(0); } return m_Pubstatus; } inline void CPubStatusDate_Base::SetPubstatus(CPubStatusDate_Base::TPubstatus value) { m_Pubstatus = value; m_set_State[0] |= 0x3; } inline CPubStatusDate_Base::TPubstatus& CPubStatusDate_Base::SetPubstatus(void) { #ifdef _DEBUG if (!IsSetPubstatus()) { memset(&m_Pubstatus,UnassignedByte(),sizeof(m_Pubstatus)); } #endif m_set_State[0] |= 0x1; return m_Pubstatus; } inline bool CPubStatusDate_Base::IsSetDate(void) const { return m_Date.NotEmpty(); } inline bool CPubStatusDate_Base::CanGetDate(void) const { return true; } inline const CPubStatusDate_Base::TDate& CPubStatusDate_Base::GetDate(void) const { if ( !m_Date ) { const_cast<CPubStatusDate_Base*>(this)->ResetDate(); } return (*m_Date); } inline CPubStatusDate_Base::TDate& CPubStatusDate_Base::SetDate(void) { if ( !m_Date ) { ResetDate(); } return (*m_Date); } /////////////////////////////////////////////////////////// ////////////////// end of inline methods ////////////////// /////////////////////////////////////////////////////////// END_objects_SCOPE // namespace ncbi::objects:: END_NCBI_SCOPE #endif // OBJECTS_BIBLIO_PUBSTATUSDATE_BASE_HPP
lgpl-3.0
ScriptFUSION/Porter
src/Provider/Resource/NullResource.php
229
<?php declare(strict_types=1); namespace ScriptFUSION\Porter\Provider\Resource; final class NullResource extends StaticResource { public function __construct() { parent::__construct(new \EmptyIterator); } }
lgpl-3.0
stephane-martin/cycapture
includes/libtins/src/ip_reassembler.cpp
4874
/* * Copyright (c) 2014, Matias Fontanini * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "ip.h" #include "rawpdu.h" #include "constants.h" #include "internals.h" #include "ip_reassembler.h" namespace Tins { namespace Internals { IPv4Stream::IPv4Stream() : received_end(false), received_size(), total_size() { } void IPv4Stream::add_fragment(IP *ip) { fragments_type::iterator it = fragments.begin(); uint16_t offset = extract_offset(ip); while(it != fragments.end() && offset > it->offset()) { ++it; } // No duplicates plx if(it != fragments.end() && it->offset() == offset) return; fragments.insert(it, IPv4Fragment(ip->inner_pdu(), offset)); received_size += ip->inner_pdu()->size(); if(!extract_more_frag(ip)) { total_size = offset + ip->inner_pdu()->size(); received_end = true; } if(offset == 0) transport_proto = ip->protocol(); } bool IPv4Stream::is_complete() const { return received_end && received_size == total_size; } PDU *IPv4Stream::allocate_pdu() const { PDU::serialization_type buffer; buffer.reserve(total_size); // Check if we actually have all the data we need. Otherwise return nullptr; uint16_t expected = 0; for(fragments_type::const_iterator it = fragments.begin(); it != fragments.end(); ++it) { if(expected != it->offset()) return 0; expected = it->offset() + it->payload().size(); buffer.insert(buffer.end(), it->payload().begin(), it->payload().end()); } return Internals::pdu_from_flag( static_cast<Constants::IP::e>(transport_proto), buffer.empty() ? 0 : &buffer[0], buffer.size() ); } uint16_t IPv4Stream::extract_offset(const IP *ip) { return (ip->frag_off() & 0x1fff) * 8; } bool IPv4Stream::extract_more_frag(const IP *ip) { return ip->frag_off() & 0x2000; } } // namespace Internals IPv4Reassembler::IPv4Reassembler(overlapping_technique technique) : technique(technique) { } IPv4Reassembler::packet_status IPv4Reassembler::process(PDU &pdu) { IP *ip = pdu.find_pdu<IP>(); if(ip && ip->inner_pdu()) { // There's fragmentation if(ip->is_fragmented()) { // Create it or look it up, it's the same Internals::IPv4Stream &stream = streams[make_key(ip)]; stream.add_fragment(ip); if(stream.is_complete()) { PDU *pdu = stream.allocate_pdu(); // The packet is corrupt if(!pdu) { streams.erase(make_key(ip)); return FRAGMENTED; } ip->inner_pdu(pdu); ip->frag_off(0); return REASSEMBLED; } else return FRAGMENTED; } } return NOT_FRAGMENTED; } IPv4Reassembler::key_type IPv4Reassembler::make_key(const IP *ip) const { return std::make_pair( ip->id(), make_address_pair(ip->src_addr(), ip->dst_addr()) ); } IPv4Reassembler::address_pair IPv4Reassembler::make_address_pair(IPv4Address addr1, IPv4Address addr2) const { if(addr1 < addr2) return std::make_pair(addr1, addr2); else return std::make_pair(addr2, addr1); } void IPv4Reassembler::clear_streams() { streams.clear(); } void IPv4Reassembler::remove_stream(uint16_t id, IPv4Address addr1, IPv4Address addr2) { streams.erase( std::make_pair( id, make_address_pair(addr1, addr2) ) ); } } // namespace Tins
lgpl-3.0
molszewski/dante
module/Simulation/src/net/java/dante/sim/data/common/PositionData.java
1181
/* * Created on 2006-07-15 * * @author M.Olszewski */ package net.java.dante.sim.data.common; /** * Class containing data about position in Cartesian system (only 'x' and 'y' * coordinates are supported). * * @author M.Olszewski */ public class PositionData { /** 'x' coordinate of start position. */ private double x; /** 'y' coordinate of start position. */ private double y; /** * Creates object of {@link PositionData} with specified starting position. * * @param startX - 'x' coordinate of start position. * @param startY - 'y' coordinate of start position. * * @throws IllegalArgumentException if <code>startX</code>/<code>startY</code> * are not a positive real numbers. */ public PositionData(double startX, double startY) { x = startX; y = startY; } /** * Gets 'x' coordinate of start position. * * @return Returns 'x' coordinate of start position. */ public double getStartX() { return x; } /** * Gets 'y' coordinate of start position. * * @return Returns 'y' coordinate of start position. */ public double getStartY() { return y; } }
lgpl-3.0
gityopie/odoo-addons
web_google_maps/models/res_config_settings.py
4248
# -*- coding: utf-8 -*- # License AGPL-3 from odoo import api, fields, models GMAPS_LANG_LOCALIZATION = [ ('af', 'Afrikaans'), ('ja', 'Japanese'), ('sq', 'Albanian'), ('kn', 'Kannada'), ('am', 'Amharic'), ('kk', 'Kazakh'), ('ar', 'Arabic'), ('km', 'Khmer'), ('ar', 'Armenian'), ('ko', 'Korean'), ('az', 'Azerbaijani'), ('ky', 'Kyrgyz'), ('eu', 'Basque'), ('lo', 'Lao'), ('be', 'Belarusian'), ('lv', 'Latvian'), ('bn', 'Bengali'), ('lt', 'Lithuanian'), ('bs', 'Bosnian'), ('mk', 'Macedonian'), ('bg', 'Bulgarian'), ('ms', 'Malay'), ('my', 'Burmese'), ('ml', 'Malayalam'), ('ca', 'Catalan'), ('mr', 'Marathi'), ('zh', 'Chinese'), ('mn', 'Mongolian'), ('zh-CN', 'Chinese (Simplified)'), ('ne', 'Nepali'), ('zh-HK', 'Chinese (Hong Kong)'), ('no', 'Norwegian'), ('zh-TW', 'Chinese (Traditional)'), ('pl', 'Polish'), ('hr', 'Croatian'), ('pt', 'Portuguese'), ('cs', 'Czech'), ('pt-BR', 'Portuguese (Brazil)'), ('da', 'Danish'), ('pt-PT', 'Portuguese (Portugal)'), ('nl', 'Dutch'), ('pa', 'Punjabi'), ('en', 'English'), ('ro', 'Romanian'), ('en-AU', 'English (Australian)'), ('ru', 'Russian'), ('en-GB', 'English (Great Britain)'), ('sr', 'Serbian'), ('et', 'Estonian'), ('si', 'Sinhalese'), ('fa', 'Farsi'), ('sk', 'Slovak'), ('fi', 'Finnish'), ('sl', 'Slovenian'), ('fil', 'Filipino'), ('es', 'Spanish'), ('fr', 'French'), ('es-419', 'Spanish (Latin America)'), ('fr-CA', 'French (Canada)'), ('sw', 'Swahili'), ('gl', 'Galician'), ('sv', 'Swedish'), ('ka', 'Georgian'), ('ta', 'Tamil'), ('de', 'German'), ('te', 'Telugu'), ('el', 'Greek'), ('th', 'Thai'), ('gu', 'Gujarati'), ('tr', 'Turkish'), ('iw', 'Hebrew'), ('uk', 'Ukrainian'), ('hi', 'Hindi'), ('ur', 'Urdu'), ('hu', 'Hungarian'), ('uz', 'Uzbek'), ('is', 'Icelandic'), ('vi', 'Vietnamese'), ('id', 'Indonesian'), ('zu', 'Zulu'), ('it', 'Italian'), ] class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' @api.model def get_region_selection(self): country_ids = self.env['res.country'].search([]) values = [(country.code, country.name) for country in country_ids] return values google_maps_view_api_key = fields.Char( string='Google Maps View Api Key', config_parameter='web_google_maps.api_key') google_maps_lang_localization = fields.Selection( selection=GMAPS_LANG_LOCALIZATION, string='Google Maps Language Localization', config_parameter='web_google_maps.lang_localization') google_maps_region_localization = fields.Selection( selection=get_region_selection, string='Google Maps Region Localization', config_parameter='web_google_maps.region_localization') google_maps_theme = fields.Selection( selection=[('default', 'Default'), ('aubergine', 'Aubergine'), ('night', 'Night'), ('dark', 'Dark'), ('retro', 'Retro'), ('silver', 'Silver'), ('atlas', 'Atlas'), ('muted_blue', 'Muted blue'), ('pale_down', 'Pale down'), ('subtle_gray', 'Subtle gray'), ('shift_worker', 'Shift worker'), ('even_lighter', 'Even lighter'), ('unsaturated_brown', 'Unsaturated brown'), ('uber', 'Uber')], string='Map theme', config_parameter='web_google_maps.theme') google_maps_libraries = fields.Char( string='Libraries', config_parameter='web_google_maps.libraries') google_autocomplete_lang_restrict = fields.Boolean( string='Google Autocomplete Language Restriction', config_parameter='web_google_maps.autocomplete_lang_restrict') @api.onchange('google_maps_lang_localization') def onchange_lang_localization(self): if not self.google_maps_lang_localization: self.google_maps_region_localization = ''
lgpl-3.0
jjm223/MyPet
modules/v1_8_R1/src/main/java/de/Keyle/MyPet/compat/v1_8_R1/entity/MyPetInfo.java
1582
/* * This file is part of MyPet * * Copyright © 2011-2016 Keyle * MyPet is licensed under the GNU Lesser General Public License. * * MyPet 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. * * MyPet 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 de.Keyle.MyPet.compat.v1_8_R1.entity; import de.Keyle.MyPet.MyPetApi; import de.Keyle.MyPet.api.entity.MyPetType; import de.Keyle.MyPet.api.exceptions.MyPetTypeNotFoundException; import de.Keyle.MyPet.api.util.Compat; import org.bukkit.entity.EntityType; @Compat("v1_8_R1") public class MyPetInfo extends de.Keyle.MyPet.api.entity.MyPetInfo { @Override public boolean isLeashableEntityType(EntityType bukkitType) { if (bukkitType == EntityType.ENDER_DRAGON) { return MyPetApi.getPluginHookManager().isPluginUsable("ProtocolLib"); //ToDo & active } try { MyPetType type = MyPetType.byEntityTypeName(bukkitType.name()); return type != null; } catch (MyPetTypeNotFoundException e) { return false; } } }
lgpl-3.0
kejace/go-ethereum
core/vm/runtime/runtime_example_test.go
1169
// Copyright 2015 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package runtime_test import ( "fmt" "github.com/kejace/go-ethereum/common" "github.com/kejace/go-ethereum/core/vm/runtime" ) func ExampleExecute() { ret, _, err := runtime.Execute(common.Hex2Bytes("6060604052600a8060106000396000f360606040526008565b00"), nil, nil) if err != nil { fmt.Println(err) } fmt.Println(ret) // Output: // [96 96 96 64 82 96 8 86 91 0] }
lgpl-3.0
seagull-js/seagull
packages/deploy-aws/test/templates/seagull_project.ts
13714
import { PolicyStatement, Role } from '@aws-cdk/aws-iam' import { FS } from '@seagull/commands-fs' import { BasicTest } from '@seagull/testing' import { DistributionSummary } from 'aws-sdk/clients/cloudfront' import { expect, use } from 'chai' import * as promisedChai from 'chai-as-promised' import 'chai/register-should' import { cloneDeep, find } from 'lodash' import { suite, test } from 'mocha-typescript' import { SeagullApp, SeagullProject } from '../../src' import * as Handlers from '../../src/aws_sdk_handler' import { isInList } from '../test-helper/template_searching' use(promisedChai) const s3Name = 'another-s3' const customizationCode = `import { SeagullApp } from '../src' export default function(app: SeagullApp) { app.stack.addS3('another-s3', app.role) }` const customizeAsync = `import { SeagullApp } from '../../src' export default async function(app: SeagullApp) { await new Promise(resolve => { const addS3Async = () => { app.stack.addS3('another-s3', app.role) resolve() } setTimeout(addS3Async, 50) }) }` @suite('SeagullProject') export class Test extends BasicTest { appPath = `${process.cwd()}/test_data` async before() { await BasicTest.prototype.before.bind(this)() process.env.AWS_REGION = 'eu-central-1' const assetFolder = `${this.appPath}/dist/assets` const backendFolder = `${assetFolder}/backend` const createBackendFolder = new FS.CreateFolder(backendFolder) await createBackendFolder.execute() await new FS.WriteFile(`${backendFolder}/server.js`, '').execute() await new FS.WriteFile(`${backendFolder}/lambda.js`, '').execute() await new FS.WriteFile( `${this.appPath}/dist/cron.json`, JSON.stringify([]) ).execute() } async after() { await BasicTest.prototype.after.bind(this)() } @test async 'can create a project'() { const props = getTestProps(this.appPath) const project = await new SeagullProject(props).createSeagullApp() const synthStack = project.synthesizeStack('helloworld') Object.keys(synthStack.template.Resources).length.should.be.above(1) } @test async 'assigns a default role to role property of SeagullApp'() { const props = getTestProps(this.appPath) const app = await new SeagullProject(props).createSeagullApp() expect(app.role).to.be.instanceOf(Role) } @test async 'can add policies after creating SeagullApp'() { const props = getTestProps(this.appPath) const app = await new SeagullProject(props).createSeagullApp() const stmt = new PolicyStatement().addAllResources().addAction('action3') app.role!.addToPolicy(stmt) const synth = app.synthesizeStack('helloworld') const newPolicyCriterion = resourceHasNewAction('action3') const hasNewPolicy = !!find(synth.template.Resources, newPolicyCriterion) hasNewPolicy.should.be.equal(true) } @test async 'adds the right lambda'() { const props = getTestProps(this.appPath) const customDotEnv = new FS.WriteFile( `${this.appPath}/.env.prod`, `FOO=bar QUX="17 * 2"` ) await customDotEnv.execute() const project = await new SeagullProject(props).createSeagullApp() const synthStack = project.synthesizeStack('helloworld') const lambdaFnKey = Object.keys(synthStack.template.Resources).filter( key => synthStack.template.Resources[key].Type === 'AWS::Lambda::Function' ) expect(lambdaFnKey.length).to.equal(1) const lambdaFn = synthStack.template.Resources[lambdaFnKey[0]] // tslint:disable-next-line:no-unused-expression expect(lambdaFn.Properties).to.have.property('Environment') const expectedEnv = { APP: 'helloworld', FOO: 'bar', LOG_BUCKET: 'eu-central-1-test-account-id-helloworld-master-logs', MODE: 'cloud', NODE_ENV: 'production', QUX: '17 * 2', STAGE: 'prod', } expect(lambdaFn.Properties.Environment.Variables).to.deep.equal(expectedEnv) await new FS.DeleteFile(`${this.appPath}/.env.prod`).execute() } @test async 'can create a project and customize stack'() { const props = getTestProps(this.appPath) await writeCustomInfraFile(this.appPath) const project = new SeagullProject(props) const app = await project.createSeagullApp() const stackName = 'helloworld' await project.customizeStack(app) const synthStack = app.synthesizeStack(stackName) const resources = Object.keys(synthStack.template.Resources) const metadata = Object.keys(synthStack.metadata) const stackNameNoDash = stackName.replace(/-/g, '') const s3NameNoDash = s3Name.replace(/-/g, '') const s3InTemp = isInList(resources, s3NameNoDash, stackNameNoDash) const s3InMeta = isInList(metadata, s3Name, stackName) s3InTemp.should.be.equal(true) s3InMeta.should.be.equal(true) await deleteCustomInfra(this.appPath) } /** This test needs to use another directory, because imports are cached * and here the import of infrastructure-aws.ts needs to be something * other than the infrastructure-aws.ts above */ @test async 'can create a project and customize stack asynchronously'() { const newCWD = `${this.appPath}/async-customization` const assetFolder = `${newCWD}/dist/assets` const backendFolder = `${assetFolder}/backend` const createBackendFolder = new FS.CreateFolder(backendFolder) await createBackendFolder.execute() await new FS.WriteFile(`${backendFolder}/server.js`, '').execute() await new FS.WriteFile(`${backendFolder}/lambda.js`, '').execute() await new FS.WriteFile(`${newCWD}/dist/cron.json`, '[]').execute() await writeCustomInfraFile(newCWD, customizeAsync) const props = getTestProps(newCWD) const project = new SeagullProject(props) const app = await project.createSeagullApp() const stackName = 'helloworld' await project.customizeStack(app) const synthStack = app.synthesizeStack(stackName) const resources = Object.keys(synthStack.template.Resources) const metadata = Object.keys(synthStack.metadata) const stackNameNoDash = stackName.replace(/-/g, '') const s3NameNoDash = s3Name.replace(/-/g, '') const s3InTemp = isInList(resources, s3NameNoDash, stackNameNoDash) const s3InMeta = isInList(metadata, s3Name, stackName) s3InTemp.should.be.equal(true) s3InMeta.should.be.equal(true) await deleteCustomInfra(newCWD) } /** This test needs to use another directory, because imports are cached * and here the import of infrastructure-aws.ts needs to be something * other than the infrastructure-aws.ts above */ @test async 'customize stack throws when infrastructure-aws.ts is corrupted'() { const newCWD = `${this.appPath}/corrupted-infrastructure` const assetFolder = `${newCWD}/dist/assets` const backendFolder = `${assetFolder}/backend` const createBackendFolder = new FS.CreateFolder(backendFolder) await createBackendFolder.execute() await new FS.WriteFile(`${backendFolder}/server.js`, '').execute() await new FS.WriteFile(`${backendFolder}/lambda.js`, '').execute() await new FS.WriteFile(`${newCWD}/dist/cron.json`, '[]').execute() await writeCustomInfraFile(newCWD, 'export default 123') const props = getTestProps(newCWD) const project = new SeagullProject(props) const app = await project.createSeagullApp() const customize = () => project.customizeStack(app) await expect(customize()).to.be.rejectedWith(Error) await deleteCustomInfra(newCWD) } @test async 'customizeStack should do nothing but return false without an infrastructure-aws.ts-file'() { const props = getTestProps(this.appPath) const project = new SeagullProject(props) const app = await project.createSeagullApp() const appBeforeCustomization = cloneDeep(app) const returnValue = await project.customizeStack(app) expect(app).to.deep.equal(appBeforeCustomization) expect(returnValue).to.be.equal(false) } @test async 'can deploy a project without customized stack'() { const props = getTestProps(this.appPath) const project = new SeagullProject(props) let hasBeenCalled = false const deployStack = () => (hasBeenCalled = true) project.createSeagullApp = () => Promise.resolve(({ deployStack } as unknown) as SeagullApp) await project.deployProject() expect(hasBeenCalled).to.be.equal(true) } @test async 'can deploy a project with customized stack'() { await writeCustomInfraFile(this.appPath) const props = getTestProps(this.appPath) const project = new SeagullProject(props) let hasBeenCalled = false const deployStack = async () => { hasBeenCalled = true } const createSeagullApp = project.createSeagullApp let app: SeagullApp project.createSeagullApp = async () => { app = await createSeagullApp.bind(project)() app.deployStack = deployStack return app } // project.createSeagullApp.bind(project) const stackName = 'helloworld' await project.deployProject() const synthStack = app!.synthesizeStack(stackName) const resources = Object.keys(synthStack.template.Resources) const metadata = Object.keys(synthStack.metadata) const stackNameNoDash = stackName.replace(/-/g, '') const s3NameNoDash = s3Name.replace(/-/g, '') const s3InTemp = isInList(resources, s3NameNoDash, stackNameNoDash) const s3InMeta = isInList(metadata, s3Name, stackName) s3InTemp.should.be.equal(true) s3InMeta.should.be.equal(true) hasBeenCalled.should.be.equal(true) await deleteCustomInfra(this.appPath) } @test async 'can diff a project without customized stack'() { const props = getTestProps(this.appPath) const project = new SeagullProject(props) let hasBeenCalled = false const diffStack = () => (hasBeenCalled = true) project.createSeagullApp = () => Promise.resolve(({ diffStack } as unknown) as SeagullApp) await project.diffProject() expect(hasBeenCalled).to.be.equal(true) } @test async 'can diff a project with customized stack'() { await writeCustomInfraFile(this.appPath) const props = getTestProps(this.appPath) const project = new SeagullProject(props) let hasBeenCalled = false const diffStack = async () => { hasBeenCalled = true } const createSeagullApp = project.createSeagullApp let app: SeagullApp project.createSeagullApp = async () => { app = await createSeagullApp.bind(project)() app.diffStack = diffStack return app } const stackName = 'helloworld' await project.diffProject() const synthStack = app!.synthesizeStack(stackName) const resources = Object.keys(synthStack.template.Resources) const metadata = Object.keys(synthStack.metadata) const stackNameNoDash = stackName.replace(/-/g, '') const s3NameNoDash = s3Name.replace(/-/g, '') const s3InTemp = isInList(resources, s3NameNoDash, stackNameNoDash) const s3InMeta = isInList(metadata, s3Name, stackName) s3InTemp.should.be.equal(true) s3InMeta.should.be.equal(true) hasBeenCalled.should.be.equal(true) await deleteCustomInfra(this.appPath) } } class TestACMHandler extends Handlers.ACMHandler { private arnsWithDomains: { [arn: string]: string[] } constructor(testData?: { [arn: string]: string[] }) { super() this.arnsWithDomains = testData || { arn1: ['www.aida.de', 'www2.aida.de'] } } async listCertificates() { return Object.keys(this.arnsWithDomains) } async describeCertificate(acmCertRef: string) { return this.arnsWithDomains[acmCertRef] || [] } } class TestCloudfrontHandler extends Handlers.CloudfrontHandler { private cloudfrontList: Array<{ Comment: string; DomainName: string }> constructor(testData?: Array<{ Comment: string; DomainName: string }>) { super() const defaultData = [{ Comment: 'helloworld', DomainName: 'abcdef.cf.net' }] this.cloudfrontList = testData || defaultData } async listDistributions() { return this.cloudfrontList as DistributionSummary[] } } class TestSTSHandler extends Handlers.STSHandler { private accountId: string constructor(testAccount?: string) { super() this.accountId = testAccount || 'test-account-id' } async getAccountId() { return this.accountId } } const getTestProps = (appPath: string) => ({ account: '1234567890', appPath, branch: 'master', githubToken: 'Token123', handlers: { acmHandler: new TestACMHandler(), cloudfrontHandler: new TestCloudfrontHandler(), stsHandler: new TestSTSHandler(), }, owner: 'me', profile: 'default', region: 'eu-central-1', repository: 'test-repo', stage: 'prod', vpcId: 'vpc-12345678', subnetIds: 'subnet-12345678,subnet-abcdefgh' }) const deleteCustomInfra = async (appPath: string) => { const customInfraDel = new FS.DeleteFile(`${appPath}/infrastructure-aws.ts`) await customInfraDel.execute() customInfraDel.mode = { environment: 'edge' } await customInfraDel.execute() } const writeCustomInfraFile = async ( appPath: string, code = customizationCode ) => { const customizationPath = `${appPath}/infrastructure-aws.ts` const customInfraGen = new FS.WriteFile(customizationPath, code) await customInfraGen.execute() customInfraGen.mode = { environment: 'edge' } await customInfraGen.execute() } const resPropHasNewAction = (action: string) => (resProp: any) => !!resProp.Statement && !!find(resProp.Statement, (s: any) => s.Action.includes(action)) const resourceHasNewAction = (action: string) => (res: any) => !!find(res.Properties, resPropHasNewAction(action))
lgpl-3.0
JerreS/AbstractCode
AbstractCode.Ast/Members/EnumMemberDeclaration.cs
2628
// This file is part of AbstractCode. // // AbstractCode is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // AbstractCode 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 AbstractCode. If not, see <http://www.gnu.org/licenses/>. // using AbstractCode.Ast.Expressions; namespace AbstractCode.Ast.Members { public class EnumMemberDeclaration : MemberDeclaration { public EnumMemberDeclaration() { } public EnumMemberDeclaration(string identifier) : this(new Identifier(identifier)) { } public EnumMemberDeclaration(Identifier identifier) : this(identifier, null) { } public EnumMemberDeclaration(string identifier, Expression value) : this(new VariableDeclarator(identifier, value)) { } public EnumMemberDeclaration(Identifier identifier, Expression value) : this(new VariableDeclarator(identifier, value)) { } public EnumMemberDeclaration(VariableDeclarator declarator) { Declarator = declarator; } public VariableDeclarator Declarator { get { return GetChildByTitle(AstNodeTitles.Declarator); } set { SetChildByTitle(AstNodeTitles.Declarator, value); } } public override bool Match(AstNode other) { var declaration = other as EnumMemberDeclaration; return declaration != null && MatchModifiersAndAttributes(declaration) && Declarator.MatchOrNull(declaration.Declarator); } public override void AcceptVisitor(IAstVisitor visitor) { visitor.VisitEnumMemberDeclaration(this); } public override TResult AcceptVisitor<TResult>(IAstVisitor<TResult> visitor) { return visitor.VisitEnumMemberDeclaration(this); } public override TResult AcceptVisitor<TData, TResult>(IAstVisitor<TData, TResult> visitor, TData data) { return visitor.VisitEnumMemberDeclaration(this, data); } } }
lgpl-3.0
acasteigts/JBotSim
apps/examples/src/main/java/examples/fancy/canadairs/Main.java
2327
/* * Copyright 2008 - 2020, Arnaud Casteigts and the JBotSim contributors <contact@jbotsim.io> * * * This file is part of JBotSim. * * JBotSim is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JBotSim 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 JBotSim. If not, see <https://www.gnu.org/licenses/>. * */ package examples.fancy.canadairs; import io.jbotsim.core.*; import io.jbotsim.ui.JViewer; /** * Created by acasteig on 22/03/15. */ public class Main extends LinkResolver { static Topology topology; @Override public boolean isHeardBy(Node n1, Node n2) { if ((n1 instanceof Sensor && n2 instanceof Canadair) || (n2 instanceof Sensor && n1 instanceof Canadair)) return false; return (n1.isWirelessEnabled() && n2.isWirelessEnabled() && n1.distance(n2) < n1.getCommunicationRange()); } public static void createMap(Topology topology){ for (int i=0; i<6; i++) for (int j=0; j<4; j++) topology.addNode(i*100+180-(j%2)*30, j*100+100, new Sensor()); topology.addNode(50, 400, new Station()); for (Link link : topology.getLinks()) link.setColor(Color.gray); topology.addNode(50, 500, new Canadair()); topology.addNode(100, 500, new Canadair()); topology.addNode(50, 50, new Lake()); } public static void main(String[] args) { topology = new Topology(800,600); topology.setLinkResolver(new Main()); DelayMessageEngine messageEngine = new DelayMessageEngine(topology); messageEngine.setDelay(10); topology.setMessageEngine(messageEngine); createMap(topology); topology.setTimeUnit(30); topology.setDefaultNodeModel(Fire.class); new JViewer(topology); topology.start(); } }
lgpl-3.0
cswaroop/Catalano-Framework
Catalano.Image/src/Catalano/Imaging/Filters/Artistic/SpecularBloom.java
4050
// Catalano Imaging Library // The Catalano Framework // // Copyright © Diego Catalano, 2015 // diego.catalano at live.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // package Catalano.Imaging.Filters.Artistic; import Catalano.Imaging.FastBitmap; import Catalano.Imaging.Filters.GaussianBoxBlur; import Catalano.Imaging.Filters.OtsuThreshold; import Catalano.Imaging.Filters.RosinThreshold; import Catalano.Imaging.Filters.SISThreshold; import Catalano.Imaging.Filters.Threshold; import Catalano.Imaging.IBaseInPlace; /** * Specular Bloom effect. * @author Diego Catalano */ public class SpecularBloom implements IBaseInPlace{ public static enum AdaptiveThreshold {Otsu, Rosin, Sis}; private AdaptiveThreshold adaptive = AdaptiveThreshold.Rosin; private int threshold = 180; private int radius = 20; private boolean auto = true; /** * Get Threshold * @return Threshold. */ public int getThreshold() { return threshold; } /** * Set Threshold. * @param threshold Threshold. */ public void setThreshold(int threshold) { this.threshold = Math.max(1, Math.min(255, threshold)); } /** * Get Radius. * @return Radius. */ public double getRadius() { return radius; } /** * Set Radius. * @param radius Radius. */ public void setRadius(int radius) { this.radius = Math.max(1, radius); } /** * Initialize a new instance of the SpecularBloom class. */ public SpecularBloom() {} /** * Initialize a new instance of the SpecularBloom class. * @param threshold Threshold. * @param radius Radius. */ public SpecularBloom(int threshold, int radius){ this.threshold = threshold; this.radius = radius; this.auto = false; } /** * Initialize a new instance of the SpecularBloom class. * @param threshold Adaptive Threshold. * @param radius Radius. */ public SpecularBloom(AdaptiveThreshold threshold, int radius){ this.adaptive = threshold; this.radius = radius; this.auto = true; } @Override public void applyInPlace(FastBitmap fastBitmap) { FastBitmap layerA = new FastBitmap(fastBitmap); layerA.toGrayscale(); switch(adaptive){ case Otsu: OtsuThreshold o = new OtsuThreshold(); o.applyInPlace(layerA); break; case Rosin: RosinThreshold r = new RosinThreshold(); r.applyInPlace(layerA); break; case Sis: SISThreshold s = new SISThreshold(); s.applyInPlace(layerA); break; } if (!auto){ Threshold t = new Threshold(threshold); t.applyInPlace(layerA); } layerA.toRGB(); GaussianBoxBlur fgb = new GaussianBoxBlur(radius); fgb.applyInPlace(layerA); Blend b = new Blend(layerA, Blend.Algorithm.Screen); b.applyInPlace(fastBitmap); } }
lgpl-3.0
jlpoolen/libreveris
data/www/branding/js/expansion.js
2298
/* -------------------------------------------------------------------------- */ /* e x p a n s i o n . j s */ /* -------------------------------------------------------------------------- */ // Choice between smooth/immediate expansions // Can be overwritten in the HTML source file smoothExpansion = true; // The mechanism uses additional items (myFullHeight and myExpanded) // created in each expandable element // Remember height of all expandable elements in the document // And precollapse all of them function collapseAll() { if (document.querySelector) { var exps = document.querySelectorAll(".expandable"); for (var i = 0; i < exps.length; i++) { var exp = exps[i]; exp.style.myFullHeight = exp.clientHeight; collapse(exp); } } // Pre-expand only the ones flagged as .expanded preExpand(); } // Pre-expand the classes flagged as such function preExpand() { if (document.querySelector) { var exps = document.querySelectorAll(".expanded"); for (var i = 0; i < exps.length; i++) { expand(exps[i]); } } } // Toggle the expansion of all expandable elements // that are siblings of the provided expander element function toggleExpansion(expander) { if (document.querySelector) { var exps = expander.parentNode.querySelectorAll(".expandable"); for (var i = 0; i < exps.length; i++) { var exp = exps[i]; if (exp.style.myExpanded) { collapse(exp); } else { expand(exp); } } } } // Collapse the provided expandable function collapse(exp) { if (smoothExpansion) { exp.style.height = 0; } else { exp.style.display = "none"; } exp.style.myExpanded = false; } // Expand the provided expandable function expand(exp) { if (smoothExpansion) { exp.style.height = exp.style.myFullHeight + "px"; } else { exp.style.display = "block"; } exp.style.myExpanded = true; } // Toggle the expansion and the expander input function toggleInput(input) { toggleExpansion(input); // Toggle input value input.value = input.value === '+' ? '-' : '+'; }
lgpl-3.0
aclex/peli
test/variant_expl_ctor_object.cpp
1247
/* * This file is part of Peli - universal JSON interaction library * Copyright (C) 2014 Alexey Chernov <4ernov@gmail.com> * * Peli is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. * */ #include "peli/json/value.h" using namespace std; using namespace peli; int main(int, char**) { json::object sample; sample["test"] = json::number { 52 }; json::value v(sample); json::object& obj(get<json::object>(v)); if (sample != obj) return -1; json::wobject wsample; wsample[L"wtest"] = json::number { 64 }; json::wvalue wv(wsample); json::wobject& wobj(get<json::wobject>(wv)); if (wsample != wobj) return -2; return 0; }
lgpl-3.0
Ajrose/heizfabrik
web/schedule/app/plugins/pjLocale/views/pjLocale/pjActionLocales.php
1351
<?php if (isset($tpl['status'])) { $status = __('status', true); switch ($tpl['status']) { case 2: pjUtil::printNotice(NULL, $status[2]); break; } } else { include_once PJ_VIEWS_PATH . 'pjLayouts/elements/optmenu.php'; include dirname(__FILE__) . '/elements/menu.php'; if (isset($_GET['err'])) { $titles = __('error_titles', true); $bodies = __('error_bodies', true); pjUtil::printNotice(@$titles[$_GET['err']], @$bodies[$_GET['err']]); } pjUtil::printNotice(__('plugin_locale_index_title', true), __('plugin_locale_index_body', true)); ?> <div class="b10"> <a href="#" class="pj-button btn-add"><?php __('plugin_locale_add_lang'); ?></a> </div> <div id="grid"></div> <?php $languages = array(); foreach ($tpl['language_arr'] as $item) { $languages[] = '{value: "'.$item['iso'].'", label: "'.$item['title'].'"}'; } ?> <script type="text/javascript"> var pjGrid = pjGrid || {}; pjGrid.languages = []; <?php if (count($languages) > 0) { printf('pjGrid.languages.push('.join(",", $languages).');'); } ?> var myLabel = myLabel || {}; myLabel.title = "<?php __('plugin_locale_lbl_title'); ?>"; myLabel.flag = "<?php __('plugin_locale_lbl_flag'); ?>"; myLabel.is_default = "<?php __('plugin_locale_lbl_is_default'); ?>"; myLabel.order = "<?php __('plugin_locale_lbl_order'); ?>"; </script> <?php } ?>
lgpl-3.0
scalable-networks/my-gui
Tools/SkinEditor/SelectorControl.cpp
5055
/*! @file @author Albert Semenov @date 08/2010 */ #include "Precompiled.h" #include "SelectorControl.h" #include "SettingsManager.h" namespace tools { SelectorControl::SelectorControl(const std::string& _layout, MyGUI::Widget* _parent) : wraps::BaseLayout(_layout, _parent), mScaleValue(1.0) { assignWidget(mProjection, "Projection", false, false); if (mProjection != nullptr) { mCoordReal = mProjection->getCoord(); mProjectionDiff = mMainWidget->getAbsoluteCoord() - mProjection->getAbsoluteCoord(); } else { mCoordReal = mMainWidget->getCoord(); } MyGUI::Window* window = mMainWidget->castType<MyGUI::Window>(false); if (window != nullptr) window->eventWindowChangeCoord += MyGUI::newDelegate(this, &SelectorControl::notifyWindowChangeCoord); SettingsManager::getInstance().eventSettingsChanged += MyGUI::newDelegate(this, &SelectorControl::notifySettingsChanged); } SelectorControl::~SelectorControl() { SettingsManager::getInstance().eventSettingsChanged -= MyGUI::newDelegate(this, &SelectorControl::notifySettingsChanged); MyGUI::Window* window = mMainWidget->castType<MyGUI::Window>(false); if (window != nullptr) window->eventWindowChangeCoord -= MyGUI::newDelegate(this, &SelectorControl::notifyWindowChangeCoord); } void SelectorControl::setVisible(bool _value) { mMainWidget->setVisible(_value); } void SelectorControl::setSize(const MyGUI::IntSize& _value) { mCoordValue = _value; updateCoord(); } void SelectorControl::setPosition(const MyGUI::IntPoint& _value) { mCoordValue = _value; updateCoord(); } void SelectorControl::setCoord(const MyGUI::IntCoord& _value) { mCoordValue = _value; updateCoord(); } void SelectorControl::setScale(double _value) { mScaleValue = _value; updateCoord(); } void SelectorControl::updateCoord() { mCoordReal.left = (int)((double)mCoordValue.left * mScaleValue) + mProjectionDiff.left; mCoordReal.top = (int)((double)mCoordValue.top * mScaleValue) + mProjectionDiff.top; mCoordReal.width = (int)((double)mCoordValue.width * mScaleValue) + mProjectionDiff.width; mCoordReal.height = (int)((double)mCoordValue.height * mScaleValue) + mProjectionDiff.height; mMainWidget->setCoord(mCoordReal); } void SelectorControl::notifyWindowChangeCoord(MyGUI::Window* _sender) { MyGUI::IntCoord coord = _sender->getCoord() - mProjectionDiff; const MyGUI::IntCoord& actionScale = _sender->getActionScale(); if (actionScale.left != 0 && actionScale.width != 0) { int right = mCoordValue.right(); mCoordValue.width = (int)((double)coord.width / mScaleValue); mCoordValue.left = right - mCoordValue.width; } else { mCoordValue.left = (int)((double)coord.left / mScaleValue); mCoordValue.width = (int)((double)coord.width / mScaleValue); } if (actionScale.top != 0 && actionScale.height != 0) { int bottom = mCoordValue.bottom(); mCoordValue.height = (int)((double)coord.height / mScaleValue); mCoordValue.top = bottom - mCoordValue.height; } else { mCoordValue.top = (int)((double)coord.top / mScaleValue); mCoordValue.height = (int)((double)coord.height / mScaleValue); } updateCoord(); eventChangePosition(); } MyGUI::IntPoint SelectorControl::getPosition() { return mCoordValue.point(); } MyGUI::IntSize SelectorControl::getSize() { return mCoordValue.size(); } const MyGUI::IntCoord& SelectorControl::getCoord() const { return mCoordValue; } void SelectorControl::setEnabled(bool _value) { mMainWidget->setNeedMouseFocus(_value); } bool SelectorControl::getCapture() { MyGUI::Window* window = mMainWidget->castType<MyGUI::Window>(false); if (window != nullptr) return !window->getActionScale().empty(); return false; } MyGUI::IntCoord SelectorControl::getActionScale() { MyGUI::Window* window = mMainWidget->castType<MyGUI::Window>(false); if (window != nullptr) return window->getActionScale(); return MyGUI::IntCoord(); } void SelectorControl::setColour(MyGUI::Colour _value) { mMainWidget->setColour(_value); mMainWidget->setAlpha(_value.alpha); } void SelectorControl::notifySettingsChanged(const MyGUI::UString& _sectorName, const MyGUI::UString& _propertyName) { if (!mPropertyColour.empty() && _sectorName == "Settings" && _propertyName == mPropertyColour) { MyGUI::Colour colour = SettingsManager::getInstance().getSector("Settings")->getPropertyValue<MyGUI::Colour>(mPropertyColour); setColour(colour); } } void SelectorControl::setPropertyColour(const std::string& _propertyName) { mPropertyColour = _propertyName; MyGUI::Colour colour = SettingsManager::getInstance().getSector("Settings")->getPropertyValue<MyGUI::Colour>(mPropertyColour); setColour(colour); } MyGUI::Widget* SelectorControl::getMainWidget() { return mMainWidget; } } // namespace tools
lgpl-3.0
webmotion-framework/webmotion-netbeans
src/org/debux/webmotion/netbeans/WebMotionBracesMatcherFactory.java
1377
/* * #%L * WebMotion plugin netbeans * * $Id$ * $HeadURL$ * %% * Copyright (C) 2012 Debux * %% * 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 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package org.debux.webmotion.netbeans; import org.netbeans.spi.editor.bracesmatching.BracesMatcher; import org.netbeans.spi.editor.bracesmatching.BracesMatcherFactory; import org.netbeans.spi.editor.bracesmatching.MatcherContext; import org.netbeans.spi.editor.bracesmatching.support.BracesMatcherSupport; /** * * @author julien */ public class WebMotionBracesMatcherFactory implements BracesMatcherFactory { @Override public BracesMatcher createMatcher(MatcherContext context) { return BracesMatcherSupport.defaultMatcher(context, -1, -1); } }
lgpl-3.0
kidaa/Awakening-Core3
bin/scripts/mobile/lair/creature_lair/corellia_plumed_rasp_eyrie_neutral_medium.lua
335
-- Generated by LairTool corellia_plumed_rasp_eyrie_neutral_medium = Lair:new { mobiles = {}, spawnLimit = 15, buildingsVeryEasy = {}, buildingsEasy = {}, buildingsMedium = {}, buildingsHard = {}, buildingsVeryHard = {} } addLairTemplate("corellia_plumed_rasp_eyrie_neutral_medium", corellia_plumed_rasp_eyrie_neutral_medium)
lgpl-3.0
PHPPre/Phing-PHPPre
source/operators/PHPPreNotEqualOperator.php
1825
<?php /** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information please see * <http://phing.info>. * * @author Maciej Trynkowski <maciej.trynkowski@miltar.pl> * @author Wojciech Trynkowski <wojciech.trynkowski@miltar.pl> * @license GNU Lesser General Public License, version 3 * @version $Id$ * @package phing.tasks.ext * @subpackage phppre * @link https://github.com/PHPPre/Phing-PHPPre */ /** * Class NotEqualOperator * * @author Maciej Trynkowski <maciej.trynkowski@miltar.pl> * @author Wojciech Trynkowski <wojciech.trynkowski@miltar.pl> * @license GNU Lesser General Public License, version 3 * @version $Id$ * @package phing.tasks.ext * @subpackage phppre * @link https://github.com/PHPPre/Phing-PHPPre */ class NotEqualOperator extends AbstractPHPPreBinaryOperator { public function getValue() { return $this->left->getValue() !== $this->right->getValue(); } }
lgpl-3.0
nythil/kgascii
3rdparty/gil_2/boost/gil/extension/io_new/detail/read_view.hpp
9532
/* Copyright 2007-2008 Christian Henning, Andreas Pokorny, Lubomir Bourdev Use, modification and distribution are subject to 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). */ /*************************************************************************************************/ #ifndef BOOST_GIL_EXTENSION_IO_READ_VIEW_HPP #define BOOST_GIL_EXTENSION_IO_READ_VIEW_HPP //////////////////////////////////////////////////////////////////////////////////////// /// \file /// \brief /// \author Christian Henning, Andreas Pokorny, Lubomir Bourdev \n /// /// \date 2007-2008 \n /// //////////////////////////////////////////////////////////////////////////////////////// #include <boost/type_traits/is_base_and_derived.hpp> #include <boost/mpl/and.hpp> #include <boost/utility/enable_if.hpp> #include "base.hpp" #include "io_device.hpp" #include "path_spec.hpp" namespace boost{ namespace gil { /// \ingroup IO /// \brief Reads an image view without conversion. No memory is allocated. /// \param file It's a device. Must satisfy is_input_device metafunction. /// \param view The image view in which the data is read into. /// \param settings Specifies read settings depending on the image format. /// \throw std::ios_base::failure template < typename Device , typename View , typename FormatTag > inline void read_view( Device& file , const View& view , const image_read_settings< FormatTag >& settings , typename enable_if< typename mpl::and_< typename detail::is_input_device< Device >::type , typename is_format_tag < FormatTag >::type , typename is_read_supported < typename get_pixel_type< View >::type , FormatTag >::type >::type >::type* /* ptr */ = 0 ) { detail::reader< Device , FormatTag , detail::read_and_no_convert > reader( file , settings ); reader.init_view( view , reader.get_info() ); reader.apply( view ); } /// \brief Reads an image view without conversion. No memory is allocated. /// \param file It's a device. Must satisfy is_adaptable_input_device metafunction. /// \param view The image view in which the data is read into. /// \param settings Specifies read settings depending on the image format. /// \throw std::ios_base::failure template < typename Device , typename View , typename FormatTag > inline void read_view( Device& file , const View& view , const image_read_settings< FormatTag >& settings , typename enable_if< typename mpl::and_< typename detail::is_adaptable_input_device< FormatTag , Device >::type , typename is_format_tag<FormatTag>::type , typename is_read_supported< typename get_pixel_type< View >::type , FormatTag >::type >::type >::type* /* ptr */ = 0 ) { typedef typename detail::is_adaptable_input_device< FormatTag , Device >::device_type device_type; device_type dev( file ); detail::reader< device_type , FormatTag , detail::read_and_no_convert > reader( dev , settings ); reader.init_view( view , reader.get_info() ); reader.apply( view ); } /// \brief Reads an image view without conversion. No memory is allocated. /// \param file_name File name. Must satisfy is_supported_path_spec metafunction. /// \param view The image view in which the data is read into. /// \param settings Specifies read settings depending on the image format. /// \throw std::ios_base::failure template < typename String , typename View , typename FormatTag > inline void read_view( const String& file_name , const View& view , const image_read_settings< FormatTag >& settings , typename enable_if< typename mpl::and_< typename detail::is_supported_path_spec< String >::type , typename is_format_tag< FormatTag >::type , typename is_read_supported< typename get_pixel_type< View >::type , FormatTag >::type >::type >::type* /* ptr */ = 0 ) { detail::file_stream_device<FormatTag> device( detail::convert_to_string( file_name ) , typename detail::file_stream_device< FormatTag >::read_tag() ); read_view( device , view , settings ); } /// \brief Reads an image view without conversion. No memory is allocated. /// \param file_name File name. Must satisfy is_supported_path_spec metafunction. /// \param view The image view in which the data is read into. /// \param tag Defines the image format. Must satisfy is_format_tag metafunction. /// \throw std::ios_base::failure template < typename String , typename View , typename FormatTag > inline void read_view( const String& file_name , const View& view , const FormatTag& , typename enable_if< typename mpl::and_< typename detail::is_supported_path_spec< String >::type , typename is_format_tag< FormatTag >::type , typename is_read_supported< typename get_pixel_type< View >::type , FormatTag >::type >::type >::type* /* ptr */ = 0 ) { read_view( file_name , view , image_read_settings< FormatTag >() ); } /// \brief Reads an image view without conversion. No memory is allocated. /// \param file It's a device. Must satisfy is_input_device metafunction or is_adaptable_input_device. /// \param view The image view in which the data is read into. /// \param tag Defines the image format. Must satisfy is_format_tag metafunction. /// \throw std::ios_base::failure template< typename Device , typename View , typename FormatTag > inline void read_view( Device& device , const View& view , const FormatTag& , typename enable_if< typename mpl::and_< typename is_format_tag< FormatTag >::type , typename mpl::or_< typename detail::is_input_device< Device >::type , typename detail::is_adaptable_input_device< FormatTag , Device >::type >::type , typename is_read_supported< typename get_pixel_type< View >::type , FormatTag >::type >::type >::type* /* ptr */ = 0 ) { read_view( device , view , image_read_settings< FormatTag >() ); } } // namespace gil } // namespace boost #endif // BOOST_GIL_EXTENSION_IO_READ_VIEW_HPP
lgpl-3.0
IfcOpenShell/IfcOpenShell
src/ifcopenshell-python/ifcopenshell/api/unit/add_monetary_unit.py
1126
# IfcOpenShell - IFC toolkit and geometry engine # Copyright (C) 2021 Dion Moult <dion@thinkmoult.com> # # This file is part of IfcOpenShell. # # IfcOpenShell is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # IfcOpenShell 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 IfcOpenShell. If not, see <http://www.gnu.org/licenses/>. class Usecase: def __init__(self, file, **settings): self.file = file self.settings = {"currency": "DOLLARYDOO"} for key, value in settings.items(): self.settings[key] = value def execute(self): return self.file.create_entity("IfcMonetaryUnit", self.settings["currency"])
lgpl-3.0
V0idWa1k3r/ExPetrum
src/main/java/v0id/exp/proxy/ExPProxyServer.java
1516
package v0id.exp.proxy; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.util.IThreadListener; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import v0id.api.exp.client.EnumParticle; import v0id.api.exp.player.EnumPlayerProgression; public class ExPProxyServer implements IExPProxy { @Override public void handleSpecialAttackPacket(NBTTagCompound tag) { } @Override public void spawnParticle(EnumParticle particle, float[] positionMotion, float[] color, byte flags, int lifetime, float scale, short[] lmap) { } @Override public void handleNewAge(EnumPlayerProgression age) { } @Override public World getClientWorld() { return null; } @Override public IThreadListener getClientThreadListener() { return null; } @Override public EntityPlayer getClientPlayer() { return null; } @Override public int getViewDistance() { MinecraftServer server = DimensionManager.getWorld(0).getMinecraftServer(); //Should always be true if (server instanceof DedicatedServer) { return ((DedicatedServer) server).getIntProperty("view-distance", 10); } return 10; } @Override public int getGrassColor(IBlockAccess world, BlockPos pos) { return -1; } }
lgpl-3.0
aimeos/ai-filesystem
lib/custom/src/MW/Filesystem/FlyZip.php
952
<?php /** * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0 * @copyright Aimeos (aimeos.org), 2015-2022 * @package MW * @subpackage Filesystem */ namespace Aimeos\MW\Filesystem; use League\Flysystem\Filesystem; use League\Flysystem\ZipArchive\ZipArchiveAdapter; /** * Implementation of Flysystem Zip archive file system adapter * * @package MW * @subpackage Filesystem */ class FlyZip extends FlyBase implements Iface, DirIface, MetaIface { private $fs; /** * Returns the file system provider * * @return \League\Flysystem\FilesystemInterface File system provider */ protected function getProvider() { if( !isset( $this->fs ) ) { $config = $this->getConfig(); if( !isset( $config['filepath'] ) ) { throw new Exception( sprintf( 'Configuration option "%1$s" missing', 'filepath' ) ); } $this->fs = new Filesystem( new ZipArchiveAdapter( $config['filepath'] ) ); } return $this->fs; } }
lgpl-3.0
arbrick/thermoservice
src/main/java/com/thermoservice/data/Record.java
886
package com.thermoservice.data; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import java.time.LocalDateTime; @Entity @Table(name = "thermostat_data") public class Record { @Id @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) private LocalDateTime recorded; private double tempC; private double relativeHumidity; protected Record() {} public Record(LocalDateTime recorded, double tempC, double relativeHumidity) { this.recorded = recorded; this.tempC = tempC; this.relativeHumidity = relativeHumidity; } public LocalDateTime getRecorded() { return recorded; } public double getTempC() { return tempC; } public double getTempF() { return tempC * 1.8 + 32;} public double getRelativeHumidity() { return relativeHumidity; } }
lgpl-3.0
followcat/predator
storage/fsinterface.py
689
import glob import os.path class FSInterface(object): def __init__(self, path): self.path = path def lsfiles(self, prefix, filterfile): return [os.path.split(f)[1] for f in glob.glob( os.path.join(self.path, prefix, filterfile))] def add_file(self, filename, filedate, *args, **kwargs): file_path = os.path.join(self.path, filename) with open(file_path, 'w') as f: f.write(filedate) return True def modify_file(self, filename, filedate, *args, **kwargs): file_path = os.path.join(self.path, filename) with open(file_path, 'w') as f: f.write(filedate) return True
lgpl-3.0
xinghuangxu/xinghuangxu.sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/issue/RubyIssueService.java
4398
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.issue; import org.sonar.api.ServerComponent; import java.util.Map; /** * Facade for JRuby on Rails extensions to request issues. * <p> * Reference from Ruby code : <code>Api.issues</code> * </p> * * @since 3.6 */ public interface RubyIssueService extends ServerComponent { /** * Search for an issue by its key. * <p/> * Ruby example: <code>result = Api.issues.find('ABCDE-12345')</code> */ IssueQueryResult find(String issueKey); /** * Search for issues. * <p/> * Ruby example: <code>Api.issues.find({'statuses' => ['OPEN', 'RESOLVED'], 'assignees' => 'john,carla')}</code> * <p/> * <b>Keys of parameters must be Ruby strings but not symbols</b>. Multi-value parameters can be arrays (<code>['OPEN', 'RESOLVED']</code>) or * comma-separated list of strings (<code>'OPEN,RESOLVED'</code>). * <p/> * Optional parameters are: * <ul> * <li>'issues': list of issue keys</li> * <li>'severities': list of severity to match. See constants in {@link org.sonar.api.rule.Severity}</li> * <li>'statuses': list of status to match. See constants in {@link Issue}</li> * <li>'resolutions': list of resolutions to match. See constants in {@link Issue}</li> * <li>'resolved': true to match only resolved issues, false to match only unresolved issues. By default no filtering is done.</li> * <li>'components': list of component keys to match, for example 'org.apache.struts:struts:org.apache.struts.Action'</li> * <li>'componentRoots': list of keys of root components. All the issues related to descendants of these roots are returned.</li> * <li>'rules': list of keys of rules to match. Format is &lt;repository&gt;:&lt;rule&gt;, for example 'squid:AvoidCycles'</li> * <li>'actionPlans': list of keys of the action plans to match. Note that plan names are not accepted.</li> * <li>'planned': true to get only issues associated to an action plan, false to get only non associated issues. By default no filtering is done.</li> * <li>'reporters': list of reporter logins. Note that reporters are defined only on "manual" issues.</li> * <li>'assignees': list of assignee logins.</li> * <li>'assigned': true to get only assigned issues, false to get only not assigned issues. By default no filtering is done.</li> * <li>'createdAfter': match all the issues created after the given date (strictly). * Both date and datetime ISO formats are supported: 2013-05-18 or 2010-05-18T15:50:45+0100</li> * <li>'createdAt': match all the issues created at the given date (require second precision). * Both date and datetime ISO formats are supported: 2013-05-18 or 2010-05-18T15:50:45+0100</li> * <li>'createdBefore': match all the issues created before the given date (exclusive). * Both date and datetime ISO formats are supported: 2013-05-18 or 2010-05-18T15:50:45+0100</li> * <li>'pageSize': maximum number of results per page. Default is {@link org.sonar.api.issue.IssueQuery#DEFAULT_PAGE_SIZE}, * except when the parameter 'components' is set. In this case there's no limit by default (all results in the same page).</li> * <li>'pageIndex': index of the selected page. Default is 1.</li> * <li>'sort': field to sort on. See supported values in {@link IssueQuery}</li> * <li>'asc': ascending or descending sort? Value can be a boolean or strings 'true'/'false'</li> * </ul> */ IssueQueryResult find(Map<String, Object> parameters); }
lgpl-3.0
esotericpig/senpi
src/main/java/com/esotericpig/senpi/BigNumBaseApp.java
7308
/** * This file is part of senpi. * Copyright (c) 2017 Jonathan Bradley Whited (@esotericpig) * * senpi is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * senpi 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 senpi. If not, see <http://www.gnu.org/licenses/>. */ package com.esotericpig.senpi; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Scanner; // TODO: Add BigDecimal & BigDecBase /** * <pre> * This ignores unchecked warnings in order to write less code that can use both BigInteger and BigNumBase. * </pre> * * @author Jonathan Bradley Whited (@esotericpig) */ @SuppressWarnings("unchecked") public class BigNumBaseApp { protected final int BIG_NUMS_COUNT = 9; // Must be a multiple of 3 protected Object[] bigNums = new Object[BIG_NUMS_COUNT]; protected String[] bigNumStrs = new String[BIG_NUMS_COUNT + 3]; // +3 for BigInteger conversion to base protected int[] maxLens = new int[3]; // x, y, z public static void main(String[] args) { BigNumBaseApp app = new BigNumBaseApp(); app.runLoop(args); } public void runLoop(String[] args) { System.out.println("<base#> <#> <op> <#>"); System.out.println(" <op>: +, -, *, /, % (mod), r (rem), f (floor mod)"); System.out.println(" Exit: <any other value>"); System.out.println(" Example: 12 2 + 2"); System.out.println(); Scanner stdin = new Scanner(System.in); while(true) { System.out.print("> "); String s = stdin.nextLine(); System.out.println(); // 7 for "2 1 + 1" if(s == null || s.length() < 7) { System.out.println("Invalid input; exiting..."); break; } String[] parts = s.trim().split("\\s+"); if(parts.length < 4) { System.out.println("Invalid input; exiting..."); break; } int base = Integer.parseInt(parts[0]); char operator = parts[2].charAt(0); String xStr = parts[1]; String yStr = parts[3]; bigNums[0] = new BigInteger(xStr,base); bigNums[1] = new BigInteger(yStr,base); bigNums[2] = null; bigNums[3] = new BigIntBase(xStr,base); bigNums[4] = new BigIntBase(yStr,base); bigNums[5] = null; bigNums[6] = new MutBigIntBase(xStr,base); bigNums[7] = new MutBigIntBase(yStr,base); bigNums[8] = null; doOperators(operator); genBigNumStrs(base); printBigNumStrs(operator); System.out.println(); } } public void doOperators(char operator) { for(int i = 0; i < bigNums.length; ++i) { Object x = bigNums[i]; Object y = bigNums[++i]; ++i; // z // Copy MutBigIntBase because it's mutable if(x instanceof MutBigIntBase) { x = ((BigNumBase)x).copy(); } // If an operator doesn't exist, use ZERO for #genBigNumStrs(...) switch(operator) { case '+': if(x instanceof BigInteger) { bigNums[i] = ((BigInteger)x).add((BigInteger)y); } else if(x instanceof BigNumBase) { bigNums[i] = ((BigNumBase)x).plus((BigNumBase)y); } break; case '-': if(x instanceof BigInteger) { bigNums[i] = ((BigInteger)x).subtract((BigInteger)y); } else if(x instanceof BigNumBase) { bigNums[i] = ((BigNumBase)x).minus((BigNumBase)y); } break; case '*': if(x instanceof BigInteger) { bigNums[i] = ((BigInteger)x).multiply((BigInteger)y); } else if(x instanceof BigNumBase) { bigNums[i] = ((BigNumBase)x).times((BigNumBase)y); } break; case '/': if(x instanceof BigInteger) { bigNums[i] = ((BigInteger)x).divide((BigInteger)y); } else if(x instanceof BigNumBase) { bigNums[i] = ((BigNumBase)x).over((BigNumBase)y); } break; case '%': if(x instanceof BigInteger) { // BigInteger#mod(...) can't accept -#s for y so do #abs() bigNums[i] = ((BigInteger)x).mod(((BigInteger)y).abs()); } else if(x instanceof BigNumBase) { bigNums[i] = ((BigNumBase)x).mod((BigNumBase)y); } break; case 'r': if(x instanceof BigInteger) { bigNums[i] = ((BigInteger)x).remainder((BigInteger)y); } else if(x instanceof BigNumBase) { bigNums[i] = ((BigNumBase)x).rem((BigNumBase)y); } break; case 'f': if(x instanceof BigInteger) { bigNums[i] = BigInteger.ZERO; } else if(x instanceof BigNumBase) { bigNums[i] = ((BigNumBase)x).floorMod((BigNumBase)y); } break; default: throw new UnsupportedOperationException("Invalid operator: " + operator); } } } public void genBigNumStrs(int base) { for(int i = 0; i < maxLens.length; ++i) { maxLens[i] = 0; } for(int i = 0,j = 0; i < BIG_NUMS_COUNT; ++i,++j) { int xi = i; int yi = ++i; int zi = ++i; int sxi = j; int syi = ++j; int szi = ++j; bigNumStrs[sxi] = bigNums[xi].toString(); bigNumStrs[syi] = bigNums[yi].toString(); bigNumStrs[szi] = bigNums[zi].toString(); maxLens[0] = Math.max(maxLens[0],bigNumStrs[sxi].length()); maxLens[1] = Math.max(maxLens[1],bigNumStrs[syi].length()); maxLens[2] = Math.max(maxLens[2],bigNumStrs[szi].length()); if(bigNums[xi] instanceof BigInteger) { sxi = ++j; syi = ++j; szi = ++j; bigNumStrs[sxi] = ((BigInteger)bigNums[xi]).toString(base); bigNumStrs[syi] = ((BigInteger)bigNums[yi]).toString(base); bigNumStrs[szi] = ((BigInteger)bigNums[zi]).toString(base); maxLens[0] = Math.max(maxLens[0],bigNumStrs[sxi].length()); maxLens[1] = Math.max(maxLens[1],bigNumStrs[syi].length()); maxLens[2] = Math.max(maxLens[2],bigNumStrs[szi].length()); } } } public void printBigNumStrs(char operator) { String opStr = (operator != '%') ? String.valueOf(operator) : "%%"; String fmtStr = String.format(" %%%ds %s %%%ds = %%%ds%n",maxLens[0],opStr,maxLens[1],maxLens[2]); String[] titles = {"BigInteger",null,"BigIntBase","MutBigIntBase"}; int i = 0; for(String title: titles) { if(title != null) { System.out.println(title); } System.out.printf(fmtStr,bigNumStrs[i++],bigNumStrs[i++],bigNumStrs[i++]); } } }
lgpl-3.0
mgm8/eel510253_project
tools/src/global_var.cpp
1132
/* * global_var.cpp * * Copyright 2017, Gabriel Mariano Marcelino <gabriel.mm8@gmail.com> * * This file is part of Smart-Panel-Control. * * Smart-Panel-Control 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. * * Smart-Panel-Control 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 Smart-Panel-Control. If not, see <http://www.gnu.org/licenses/>. * */ /** * \file global_var.cpp * * \brief Global variables declaration. * * \author Gabriel Mariano Marcelino <gabriel.mm8@gmail.com> * * \version 1.0 * * \date 07/05/2017 * * \addtogroup global_var * \{ */ #include "global_var.h" Widgets widgets; UART uart; //! \} End of global_var group
lgpl-3.0
kidaa/Awakening-Core3
bin/scripts/mobile/dantooine/voritor_dasher.lua
859
voritor_dasher = Creature:new { objectName = "@mob/creature_names:voritor_dasher", socialGroup = "voritor", pvpFaction = "", faction = "", level = 30, chanceHit = 0.39, damageMin = 345, damageMax = 400, baseXp = 3005, baseHAM = 9300, baseHAMmax = 11300, armor = 0, resists = {0,0,0,0,0,0,0,0,0}, meatType = "meat_carnivore", meatAmount = 40, hideType = "hide_leathery", hideAmount = 30, boneType = "bone_avian", boneAmount = 35, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE, creatureBitmask = PACK, optionsBitmask = 0, diet = NONE, templates = {"object/mobile/voritor_dasher.iff"}, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { {"creatureareapoison",""}, {"dizzyattack","dizzyChance=50"} } } CreatureTemplates:addCreatureTemplate(voritor_dasher, "voritor_dasher")
lgpl-3.0
ProfoundGames/YoutubeMusicStoreAndPlay
YoutubeMusicStoreAndPlay/Properties/Settings.Designer.cs
1081
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace YoutubeMusicStoreAndPlay.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
lgpl-3.0
MartinSojka/Stellar-Generator
src/main/java/de/vernideas/space/data/City.java
1031
package de.vernideas.space.data; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.NonNull; import lombok.ToString; import lombok.experimental.Accessors; /** Place on (or near) surface of a rounded body, like a planet or moon, or in close orbit around it */ @ToString @Accessors(fluent = true) @EqualsAndHashCode(callSuper=true) public class City extends Place { /** On which planet or moon this city lies on */ @NonNull public final Satellite planet; /** Position relative to the planet's prime meridian; -180.0 to +180.0 */ public final float longitude; /** Offset in minute */ public final int dayOffset; @Builder protected City(@NonNull String name, Satellite planet, float longitude) { super(name, planet.dayLength()); if( longitude < -180.0f || longitude > 180.0f ) { throw new IllegalArgumentException("Longitude" + longitude + " outside of [-180, +180]"); } this.planet = planet; this.longitude = longitude; this.dayOffset = (int)(longitude * dayLength / 360.0f); } }
lgpl-3.0
amjames/psi4
psi4/src/psi4/libsapt_solver/sapt.cc
11943
/* * @BEGIN LICENSE * * Psi4: an open-source quantum chemistry software package * * Copyright (c) 2007-2018 The Psi4 Developers. * * The copyrights for code used from other parties are included in * the corresponding files. * * This file is part of Psi4. * * Psi4 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * @END LICENSE */ #include "sapt.h" #include "psi4/libmints/matrix.h" #include "psi4/libmints/vector.h" #include "psi4/libmints/factory.h" #include "psi4/libmints/molecule.h" #include "psi4/libmints/integral.h" #include "psi4/libmints/potential.h" #include "psi4/libmints/basisset.h" #include <cstring> namespace psi { namespace sapt { SAPT::SAPT(SharedWavefunction Dimer, SharedWavefunction MonomerA, SharedWavefunction MonomerB, Options &options, std::shared_ptr<PSIO> psio) : Wavefunction(options) { shallow_copy(Dimer); if ((Dimer->nirrep() != 1) || (MonomerA->nirrep() != 1) || (MonomerA->nirrep() != 1)) { throw PSIEXCEPTION("SAPT must be run in C1 symmetry. Period."); } if ((Dimer->soccpi().sum() != 0) || (MonomerA->soccpi().sum() != 0) || (MonomerA->soccpi().sum() != 0)) { throw PSIEXCEPTION("This is a RHF SAPT constructor. Pair those electrons up cracker!"); } psio_ = psio; #ifdef USING_LAPACK_MKL mkl_set_dynamic(1); #endif #ifdef _OPENMP omp_set_nested(0); #endif initialize(MonomerA, MonomerB); get_denom(); } SAPT::~SAPT() { if (evalsA_ != nullptr) free(evalsA_); if (evalsB_ != nullptr) free(evalsB_); if (diagAA_ != nullptr) free(diagAA_); if (diagBB_ != nullptr) free(diagBB_); if (CA_ != nullptr) free_block(CA_); if (CB_ != nullptr) free_block(CB_); if (CHFA_ != nullptr) free_block(CHFA_); if (CHFB_ != nullptr) free_block(CHFB_); if (sAB_ != nullptr) free_block(sAB_); if (vABB_ != nullptr) free_block(vABB_); if (vBAA_ != nullptr) free_block(vBAA_); if (vAAB_ != nullptr) free_block(vAAB_); if (vBAB_ != nullptr) free_block(vBAB_); zero_.reset(); } void SAPT::initialize(SharedWavefunction MonomerA, SharedWavefunction MonomerB) { evalsA_ = NULL; evalsB_ = NULL; diagAA_ = NULL; diagBB_ = NULL; CA_ = NULL; CB_ = NULL; CHFA_ = NULL; CHFB_ = NULL; sAB_ = NULL; vABB_ = NULL; vBAA_ = NULL; vAAB_ = NULL; vBAB_ = NULL; // We inherit from the dimer basis ribasis_ = get_basisset("DF_BASIS_SAPT"); elstbasis_ = get_basisset("DF_BASIS_ELST"); // Compare pointers if (ribasis_ == elstbasis_){ elst_basis_ = 0; } else { elst_basis_ = 1; } zero_ = std::shared_ptr<BasisSet>(BasisSet::zero_ao_basis_set()); if(options_.get_str("EXCH_SCALE_ALPHA") == "FALSE") { exch_scale_alpha_ = 0.0; } else if (options_.get_str("EXCH_SCALE_ALPHA") == "TRUE") { exch_scale_alpha_ = 1.0; // Default value for alpha } else { exch_scale_alpha_ = std::atof(options_.get_str("EXCH_SCALE_ALPHA").c_str()); } Process::environment.globals["SAPT ALPHA"] = exch_scale_alpha_; print_ = options_.get_int("PRINT"); debug_ = options_.get_int("DEBUG"); schwarz_ = options_.get_double("INTS_TOLERANCE"); mem_ = (long int) ((double) memory_*options_.get_double("SAPT_MEM_SAFETY")); mem_ /= 8L; std::vector<int> realsA; realsA.push_back(0); std::vector<int> ghostsA; ghostsA.push_back(1); auto monomerA = std::shared_ptr<Molecule>(molecule_->extract_subsets(realsA, ghostsA)); foccA_ = MonomerA->basisset()->n_frozen_core(options_.get_str("FREEZE_CORE"), monomerA); std::vector<int> realsB; realsB.push_back(1); std::vector<int> ghostsB; ghostsB.push_back(0); auto monomerB = std::shared_ptr<Molecule>(molecule_->extract_subsets(realsB, ghostsB)); foccB_ = MonomerB->basisset()->n_frozen_core(options_.get_str("FREEZE_CORE"), monomerB); natomsA_ = 0; natomsB_ = 0; for (int n=0; n<monomerA->natom(); n++) if (monomerA->Z(n)) natomsA_++; for (int n=0; n<monomerB->natom(); n++) if (monomerB->Z(n)) natomsB_++; ndf_ = ribasis_->nbf(); double enucD, enucA, enucB; double eHFD, eHFA, eHFB; eHFD = energy_; enucD = molecule_->nuclear_repulsion_energy(dipole_field_strength_); // Monomer A info nsoA_ = MonomerA->nso(); nmoA_ = MonomerA->nmo(); noccA_ = MonomerA->doccpi().sum(); nvirA_ = nmoA_ - noccA_; NA_ = 2 * noccA_; eHFA = MonomerA->reference_energy(); enucA = MonomerA->molecule()->nuclear_repulsion_energy(dipole_field_strength_); aoccA_ = noccA_ - foccA_; // Monomer B info nsoB_ = MonomerB->nso(); nmoB_ = MonomerB->nmo(); noccB_ = MonomerB->doccpi().sum(); nvirB_ = nmoB_ - noccB_; NB_ = 2 * noccB_; eHFB = MonomerB->reference_energy(); enucB = MonomerB->molecule()->nuclear_repulsion_energy(dipole_field_strength_); aoccB_ = noccB_ - foccB_; enuc_ = enucD - enucA - enucB; eHF_ = eHFD - eHFA - eHFB; evalsA_ = init_array(nmoA_); std::memcpy(evalsA_, MonomerA->epsilon_a()->pointer(), sizeof(double) * nmoA_); evalsB_ = init_array(nmoB_); std::memcpy(evalsB_, MonomerB->epsilon_a()->pointer(), sizeof(double) * nmoB_); CA_ = block_matrix(nso_,nmoA_); double **tempA = block_matrix(nsoA_,nmoA_); std::memcpy(tempA[0], MonomerA->Ca()->pointer()[0], sizeof(double) * nmoA_ * nsoA_); if (nsoA_ != nso_) { for (int n=0; n<nsoA_; n++) C_DCOPY(nmoA_,tempA[n],1,CA_[n],1); } else C_DCOPY(nso_*nmoA_,tempA[0],1,CA_[0],1); free_block(tempA); CB_ = block_matrix(nso_,nmoB_); double **tempB = block_matrix(nsoB_,nmoB_); std::memcpy(tempB[0], MonomerB->Ca()->pointer()[0], sizeof(double) * nmoB_ * nsoB_); if (nsoB_ != nso_) { for (int n=0; n<nsoB_; n++) C_DCOPY(nmoB_,tempB[n],1,CB_[n+nsoA_],1); } else C_DCOPY(nso_*nmoB_,tempB[0],1,CB_[0],1); free_block(tempB); int nbf[8]; nbf[0] = nso_; auto fact = std::make_shared<MatrixFactory>(); fact->init_with(1, nbf, nbf); auto intfact = std::make_shared<IntegralFactory>(basisset_, basisset_, basisset_, basisset_); std::shared_ptr<OneBodyAOInt> Sint(intfact->ao_overlap()); auto Smat = std::make_shared<Matrix>(fact->create_matrix("Overlap")); Sint->compute(Smat); double **sIJ = Smat->pointer(); double **sAJ = block_matrix(nmoA_,nso_); sAB_ = block_matrix(nmoA_,nmoB_); C_DGEMM('T','N',nmoA_,nso_,nso_,1.0,CA_[0],nmoA_,sIJ[0],nso_, 0.0,sAJ[0],nso_); C_DGEMM('N','N',nmoA_,nmoB_,nso_,1.0,sAJ[0],nso_,CB_[0],nmoB_, 0.0,sAB_[0],nmoB_); free_block(sAJ); auto potA = std::shared_ptr<PotentialInt>(dynamic_cast<PotentialInt*>(intfact->ao_potential())); SharedMatrix ZxyzA(new Matrix("Charges A (Z,x,y,z)", natomsA_, 4)); for (int n=0, p=0; n<monomerA->natom(); n++) { if (monomerA->Z(n)) { double Z = (double) monomerA->Z(n); double x = monomerA->x(n); double y = monomerA->y(n); double z = monomerA->z(n); ZxyzA->set(0, p, 0, Z); ZxyzA->set(0, p, 1, x); ZxyzA->set(0, p, 2, y); ZxyzA->set(0, p, 3, z); p++; } } potA->set_charge_field(ZxyzA); auto VAmat = std::make_shared<Matrix>(fact->create_matrix("Nuclear Attraction (Monomer A)")); potA->compute(VAmat); auto potB = std::shared_ptr<PotentialInt>(dynamic_cast<PotentialInt*>(intfact->ao_potential())); auto ZxyzB = std::make_shared<Matrix>("Charges B (Z,x,y,z)", natomsB_, 4); for (int n=0, p=0; n<monomerB->natom(); n++) { if (monomerB->Z(n)) { double Z = (double) monomerB->Z(n); double x = monomerB->x(n); double y = monomerB->y(n); double z = monomerB->z(n); ZxyzB->set(0, p, 0, Z); ZxyzB->set(0, p, 1, x); ZxyzB->set(0, p, 2, y); ZxyzB->set(0, p, 3, z); p++; } } potB->set_charge_field(ZxyzB); auto VBmat = std::make_shared<Matrix>(fact->create_matrix("Nuclear Attraction (Monomer B)")); potB->compute(VBmat); double **vIB = block_matrix(nso_,nmoB_); double **vAJ = block_matrix(nmoA_,nso_); vAAB_ = block_matrix(nmoA_,nmoB_); vABB_ = block_matrix(nmoB_,nmoB_); vBAA_ = block_matrix(nmoA_,nmoA_); vBAB_ = block_matrix(nmoA_,nmoB_); double **vIJ = VAmat->pointer(); C_DGEMM('N','N',nso_,nmoB_,nso_,1.0,vIJ[0],nso_,CB_[0],nmoB_,0.0, vIB[0],nmoB_); C_DGEMM('T','N',nmoA_,nmoB_,nso_,1.0,CA_[0],nmoA_,vIB[0],nmoB_,0.0, vAAB_[0],nmoB_); C_DGEMM('T','N',nmoB_,nmoB_,nso_,1.0,CB_[0],nmoB_,vIB[0],nmoB_,0.0, vABB_[0],nmoB_); vIJ = VBmat->pointer(); C_DGEMM('T','N',nmoA_,nso_,nso_,1.0,CA_[0],nmoA_,vIJ[0],nso_,0.0, vAJ[0],nso_); C_DGEMM('N','N',nmoA_,nmoA_,nso_,1.0,vAJ[0],nso_,CA_[0],nmoA_,0.0, vBAA_[0],nmoA_); C_DGEMM('N','N',nmoA_,nmoB_,nso_,1.0,vAJ[0],nso_,CB_[0],nmoB_,0.0, vBAB_[0],nmoB_); free_block(vIB); free_block(vAJ); } void SAPT::get_denom() { auto evals_aoccA = std::make_shared<Vector>(aoccA_); auto evals_virA = std::make_shared<Vector>(nvirA_); auto evals_aoccB = std::make_shared<Vector>(aoccB_); auto evals_virB = std::make_shared<Vector>(nvirB_); for (int a = 0; a < aoccA_; a++) evals_aoccA->set(0, a, evalsA_[a + foccA_]); for (int r = 0; r < nvirA_; r++) evals_virA->set(0, r, evalsA_[r + noccA_]); for (int b = 0; b < aoccB_; b++) evals_aoccB->set(0, b, evalsB_[b + foccB_]); for (int s = 0; s < nvirB_; s++) evals_virB->set(0, s, evalsB_[s + noccB_]); denom_ = SAPTDenominator::buildDenominator(options_.get_str("DENOMINATOR_ALGORITHM"), evals_aoccA, evals_virA, evals_aoccB, evals_virB, options_.get_double("DENOMINATOR_DELTA"), debug_); if (debug_ > 1) denom_->debug(); SharedMatrix tauAR = denom_->denominatorA(); SharedMatrix tauBS = denom_->denominatorB(); dAR_ = tauAR->pointer(); dBS_ = tauBS->pointer(); nvec_ = denom_->nvector(); } CPHFDIIS::CPHFDIIS(int length, int maxvec) { max_diis_vecs_ = maxvec; vec_length_ = length; curr_vec_ = 0; num_vecs_ = 0; t_vecs_ = block_matrix(maxvec, length); err_vecs_ = block_matrix(maxvec, length); } CPHFDIIS::~CPHFDIIS() { free_block(t_vecs_); free_block(err_vecs_); } void CPHFDIIS::store_vectors(double *t_vec, double *err_vec) { C_DCOPY(vec_length_, t_vec, 1, t_vecs_[curr_vec_], 1); C_DCOPY(vec_length_, err_vec, 1, err_vecs_[curr_vec_], 1); curr_vec_ = (curr_vec_ + 1) % max_diis_vecs_; num_vecs_++; if (num_vecs_ > max_diis_vecs_) num_vecs_ = max_diis_vecs_; } void CPHFDIIS::get_new_vector(double *t_vec) { int *ipiv; double *Cvec; double **Bmat; ipiv = init_int_array(num_vecs_ + 1); Bmat = block_matrix(num_vecs_ + 1, num_vecs_ + 1); Cvec = (double *)malloc((num_vecs_ + 1) * sizeof(double)); for (int i = 0; i < num_vecs_; i++) { for (int j = 0; j <= i; j++) { Bmat[i][j] = Bmat[j][i] = C_DDOT(vec_length_, err_vecs_[i], 1, err_vecs_[j], 1); } } for (int i = 0; i < num_vecs_; i++) { Bmat[num_vecs_][i] = -1.0; Bmat[i][num_vecs_] = -1.0; Cvec[i] = 0.0; } Bmat[num_vecs_][num_vecs_] = 0.0; Cvec[num_vecs_] = -1.0; C_DGESV(num_vecs_ + 1, 1, &(Bmat[0][0]), num_vecs_ + 1, &(ipiv[0]), &(Cvec[0]), num_vecs_ + 1); for (int i = 0; i < num_vecs_; i++) { C_DAXPY(vec_length_, Cvec[i], t_vecs_[i], 1, t_vec, 1); } free(ipiv); free(Cvec); free_block(Bmat); } } }
lgpl-3.0
catedrasaes-umu/vagrantweb
protected/models/OperationModel.php
2897
<?php /** * This is the model class for table "operation_table". * * The followings are the available columns in table 'operation_table': * @property integer $id * @property string $operation_command * @property string $node_name * @property integer $operation_status * @property string $operation_result */ class OperationModel extends CActiveRecord { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return OperationModel the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'operation_table'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('node_name, operation_status, operation_result', 'required'), array('operation_status', 'numerical', 'integerOnly'=>true), array('operation_command, operation_specific', 'length', 'max'=>255), array('node_name', 'length', 'max'=>128), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, operation_command,operation_specific, node_name, operation_status, operation_result', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'operation_command' => 'Operation Command', 'operation_specific' => 'Operation Specific', 'node_name' => 'Node Name', 'operation_status' => 'Operation Status', 'operation_result' => 'Operation Result', ); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('operation_command',$this->operation_command,true); $criteria->compare('operation_specific',$this->operation_specific,true); $criteria->compare('node_name',$this->node_name,true); $criteria->compare('operation_status',$this->operation_status); $criteria->compare('operation_result',$this->operation_result,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } }
lgpl-3.0
roccosportal/pvik
Core/Core.php
1644
<?php namespace Pvik\Core; use Pvik\Core\Path; use Pvik\Core\Config; use Pvik\Web\RouteManager; use Pvik\Web\ErrorManager; /** * Contains the core functionalities */ class Core { /** * Initializes the web functionalities. * Initializes the error manager. * Starts the route manager. */ public function startWeb() { ErrorManager::init(); $routeManager = new RouteManager(); $routeManager->start(); } /** * Loads the given configs into \Pvik\Core\Config. * @param array $configPaths * @return \Pvik\Core\Core */ public function loadConfig(array $configPaths) { foreach ($configPaths as $configPath) { Config::load(Path::realPath($configPath)); } Log::writeLine('[Info] Loaded: ' . implode(",", $configPaths)); return $this; } /** * Creates an guid. * @return string */ public static function createGuid() { if (function_exists('com_create_guid')) { return com_create_guid(); } else { mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up. $charId = strtoupper(md5(uniqid(rand(), true))); $hyphen = chr(45); // "-" $uuid = chr(123)// "{" . substr($charId, 0, 8) . $hyphen . substr($charId, 8, 4) . $hyphen . substr($charId, 12, 4) . $hyphen . substr($charId, 16, 4) . $hyphen . substr($charId, 20, 12) . chr(125); // "}" return $uuid; } } }
lgpl-3.0
mdPlusPlus/mhb-vs
src/FHBingen/Bundle/MHBBundle/Tests/DBTestCases.php
933
<?php /** * Created by PhpStorm. * User: Mischa * Date: 12.05.2015 * Time: 15:53 */ namespace FHBingen\Bundle\MHBBundle\Tests\Controller; use PHPUnit_Extensions_Database_TestCase; use PDO; use DomAssertions; class DBTestCase extends PHPUnit_Extensions_Database_TestCase { final public function getConnection() { $connection = new PDO($GLOBALS['DB_DSN'], $GLOBALS['DB_USER'], $GLOBALS['DB_PASSWD']); return $this->createDefaultDBConnection($connection, $GLOBALS['DB_DBNAME']); } public function getSetUpOperation() { // return new \PHPUnit_Extensions_Database_Operation_Composite( // array( // new TruncateOperation(true), // \PHPUnit_Extensions_Database_Operation_Factory::INSERT() // ) // ); } public function getDataSet() { return $this->createFlatXMLDataSet(dirname(__FILE__).'/mhb.xml'); } }
lgpl-3.0
islog/liblogicalaccess
plugins/logicalaccess/plugins/readers/axesstmc13/readercardadapters/axesstmc13serialportdatatransport.hpp
2165
/** * \file axesstmc13serialportdatatransport.hpp * \author Adrien J. <adrien.jund@islog.com> * \brief Axesstmc13 DataTransport. */ #ifndef AXESSTMC13SERIALPORTDATATRANSPORT_HPP #define AXESSTMC13SERIALPORTDATATRANSPORT_HPP #include <logicalaccess/readerproviders/serialportdatatransport.hpp> #include <logicalaccess/plugins/readers/axesstmc13/readercardadapters/axesstmc13bufferparser.hpp> #include <string> #include <vector> #include <boost/property_tree/ptree.hpp> namespace logicalaccess { class LLA_READERS_AXESSTMC13_API AxessTMC13SerialPortDataTransport : public SerialPortDataTransport { public: explicit AxessTMC13SerialPortDataTransport(const std::string &portname = "") : SerialPortDataTransport(portname) { } void setSerialPort(std::shared_ptr<SerialPortXml> port) override { d_port = port; d_port->getSerialPort()->setCircularBufferParser(new AxessTMC13BufferParser()); } /** * \brief Get the transport type of this instance. * \return The transport type. */ std::string getTransportType() const override { return "AxessTMC13SerialPort"; } /** * \brief Serialize the current object to XML. * \param parentNode The parent node. */ void serialize(boost::property_tree::ptree &parentNode) override { boost::property_tree::ptree node; SerialPortDataTransport::serialize(node); parentNode.add_child(getDefaultXmlNodeName(), node); } /** * \brief UnSerialize a XML node to the current object. * \param node The XML node. */ void unSerialize(boost::property_tree::ptree &node) override { SerialPortDataTransport::unSerialize( node.get_child(SerialPortDataTransport::getDefaultXmlNodeName())); d_port->getSerialPort()->setCircularBufferParser(new AxessTMC13BufferParser()); } /** * \brief Get the default Xml Node name for this object. * \return The Xml node name. */ std::string getDefaultXmlNodeName() const override { return "AxessTMC13DataTransport"; } }; } #endif /* AXESSTMC13SERIALPORTDATATRANSPORT_HPP */
lgpl-3.0
pcolby/libqtaws
src/kinesisvideomedia/kinesisvideomediarequest.cpp
8974
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "kinesisvideomediarequest.h" #include "kinesisvideomediarequest_p.h" namespace QtAws { namespace KinesisVideoMedia { /*! * \class QtAws::KinesisVideoMedia::KinesisVideoMediaRequest * \brief The KinesisVideoMediaRequest class provides an interface for KinesisVideoMedia requests. * * \inmodule QtAwsKinesisVideoMedia */ /*! * \enum KinesisVideoMediaRequest::Action * * This enum describes the actions that can be performed as KinesisVideoMedia * requests. * * \value GetMediaAction KinesisVideoMedia GetMedia action. */ /*! * Constructs a KinesisVideoMediaRequest object for KinesisVideoMedia \a action. */ KinesisVideoMediaRequest::KinesisVideoMediaRequest(const Action action) : QtAws::Core::AwsAbstractRequest(new KinesisVideoMediaRequestPrivate(action, this)) { } /*! * Constructs a copy of \a other. */ KinesisVideoMediaRequest::KinesisVideoMediaRequest(const KinesisVideoMediaRequest &other) : QtAws::Core::AwsAbstractRequest(new KinesisVideoMediaRequestPrivate(*other.d_func(), this)) { } /*! * Sets the KinesisVideoMediaRequest object to be equal to \a other. */ KinesisVideoMediaRequest& KinesisVideoMediaRequest::operator=(const KinesisVideoMediaRequest &other) { Q_D(KinesisVideoMediaRequest); d->action = other.d_func()->action; d->apiVersion = other.d_func()->apiVersion; d->parameters = other.d_func()->parameters; return *this; } /*! * Constructs aa KinesisVideoMediaRequest object with private implementation \a d. * * This overload allows derived classes to provide their own private class * implementation that inherits from KinesisVideoMediaRequestPrivate. */ KinesisVideoMediaRequest::KinesisVideoMediaRequest(KinesisVideoMediaRequestPrivate * const d) : QtAws::Core::AwsAbstractRequest(d) { } /*! * Returns the KinesisVideoMedia action to be performed by this request. */ KinesisVideoMediaRequest::Action KinesisVideoMediaRequest::action() const { Q_D(const KinesisVideoMediaRequest); return d->action; } /*! * Returns the name of the KinesisVideoMedia action to be performed by this request. */ QString KinesisVideoMediaRequest::actionString() const { return KinesisVideoMediaRequestPrivate::toString(action()); } /*! * Returns the KinesisVideoMedia API version implemented by this request. */ QString KinesisVideoMediaRequest::apiVersion() const { Q_D(const KinesisVideoMediaRequest); return d->apiVersion; } /*! * Sets the KinesisVideoMedia action to be performed by this request to \a action. */ void KinesisVideoMediaRequest::setAction(const Action action) { Q_D(KinesisVideoMediaRequest); d->action = action; } /*! * Sets the KinesisVideoMedia API version to include in this request to \a version. */ void KinesisVideoMediaRequest::setApiVersion(const QString &version) { Q_D(KinesisVideoMediaRequest); d->apiVersion = version; } /*! * Returns \c true if this request is equal to \a other; \c false otherwise. * * Note, most derived *Request classes do not need to provider their own * implementations of this function, since most such request classes rely on * this class' parameters functionality for all request parameters, and that * parameters map is already checked via this implementation. */ bool KinesisVideoMediaRequest::operator==(const KinesisVideoMediaRequest &other) const { return ((action() == other.action()) && (apiVersion() == other.apiVersion()) && (parameters() == other.parameters()) && (QtAws::Core::AwsAbstractRequest::operator ==(other))); } /* * Returns \c tue if \a queueName is a valid KinesisVideoMedia queue name. * * @par From KinesisVideoMedia FAQs: * Queue names are limited to 80 characters. Alphanumeric characters plus * hyphens (-) and underscores (_) are allowed. * * @param queueName Name to check for validity. * * @return \c true if \a queueName is a valid KinesisVideoMedia queue name, \c false otherwise. * * @see http://aws.amazon.com/sqs/faqs/ */ /*bool KinesisVideoMediaRequest::isValidQueueName(const QString &queueName) { const QRegExp pattern(QLatin1String("[a-zA-Z0-9-_]{1,80}")); return pattern.exactMatch(queueName); }*/ /*! * Removes the a \a name parameter from the request, then returns the number of * paramters removed (typically \c 0 or \c 1). */ int KinesisVideoMediaRequest::clearParameter(const QString &name) { Q_D(KinesisVideoMediaRequest); return d->parameters.remove(name); } /*! * Removes all parameters from the request. */ void KinesisVideoMediaRequest::clearParameters() { Q_D(KinesisVideoMediaRequest); d->parameters.clear(); } /*! * Returns the value of the \a name pararemter if set; \a defaultValue otherwise. */ QVariant KinesisVideoMediaRequest::parameter(const QString &name, const QVariant &defaultValue) const { Q_D(const KinesisVideoMediaRequest); return d->parameters.value(name, defaultValue); } /*! * Returns the parameters included in this request. */ const QVariantMap &KinesisVideoMediaRequest::parameters() const { Q_D(const KinesisVideoMediaRequest); return d->parameters; } /*! * Sets the \a name parameter to \a value. */ void KinesisVideoMediaRequest::setParameter(const QString &name, const QVariant &value) { Q_D(KinesisVideoMediaRequest); d->parameters.insert(name, value); } /*! * Sets the paramters for this request to \a parameters. Any request parameters * set previously will be discarded. */ void KinesisVideoMediaRequest::setParameters(const QVariantMap &parameters) { Q_D(KinesisVideoMediaRequest); d->parameters = parameters; } /*! * Returns a network request for the KinesisVideoMedia request using the given * \a endpoint. * * This KinesisVideoMedia implementation builds request URLs by combining the * common query parameters (such as Action and Version), with any that have * been added (via setParameter) by child classes. */ QNetworkRequest KinesisVideoMediaRequest::unsignedRequest(const QUrl &endpoint) const { //Q_D(const KinesisVideoMediaRequest); QUrl url(endpoint); /// @todo url.setQuery(d->urlQuery()); return QNetworkRequest(url); } /*! * \class QtAws::KinesisVideoMedia::KinesisVideoMediaRequestPrivate * \brief The KinesisVideoMediaRequestPrivate class provides private implementation for KinesisVideoMediaRequest. * \internal * * \inmodule QtAwsKinesisVideoMedia */ /*! * Constructs a KinesisVideoMediaRequestPrivate object for KinesisVideoMedia \a action, * with public implementation \a q. */ KinesisVideoMediaRequestPrivate::KinesisVideoMediaRequestPrivate(const KinesisVideoMediaRequest::Action action, KinesisVideoMediaRequest * const q) : QtAws::Core::AwsAbstractRequestPrivate(q), action(action), apiVersion(QLatin1String("2012-11-05")) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor copies everything from \a other, except for the * the object's pointer to its public instance - for that, \a q is used instead. * * This is required to support the KinesisVideoMediaRequest class's copy constructor. */ KinesisVideoMediaRequestPrivate::KinesisVideoMediaRequestPrivate(const KinesisVideoMediaRequestPrivate &other, KinesisVideoMediaRequest * const q) : QtAws::Core::AwsAbstractRequestPrivate(q), action(other.action), apiVersion(other.apiVersion), parameters(other.parameters) { } /*! * Returns a string represention of \a action, or a null string if \a action is * invalid. * * This function converts KinesisVideoMediaRequest::Action enumerator values to their respective * string representations, appropriate for use with the KinesisVideoMedia service's Action * query parameters. */ QString KinesisVideoMediaRequestPrivate::toString(const KinesisVideoMediaRequest::Action &action) { #define ActionToString(action) \ case KinesisVideoMediaRequest::action##Action: return QStringLiteral(#action) switch (action) { ActionToString(GetMedia); default: Q_ASSERT_X(false, Q_FUNC_INFO, "invalid action"); } #undef ActionToString return QString(); } } // namespace KinesisVideoMedia } // namespace QtAws
lgpl-3.0
hostinet/sdk-php
examples/upload-file.php
278
<?php /** * The Hostinet API Example. * Upload a file */ require_once ( "../src/HostinetAPI.php"); define('API_KEY', ''); define('API_SECRET', ''); $api = new HostinetApi(API_KEY,API_SECRET); $response = $api->upload('/absolute/path/to/file.txt'); print_r($response);
lgpl-3.0
mbring/sonar-java
java-checks/src/main/java/org/sonar/java/checks/helpers/JavaPropertiesHelper.java
3288
/* * SonarQube Java * Copyright (C) 2012-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.java.checks.helpers; import org.sonar.plugins.java.api.semantic.Symbol; import org.sonar.plugins.java.api.tree.ExpressionTree; import org.sonar.plugins.java.api.tree.IdentifierTree; import org.sonar.plugins.java.api.tree.MethodInvocationTree; import org.sonar.plugins.java.api.tree.Tree; import org.sonar.plugins.java.api.tree.VariableTree; import javax.annotation.CheckForNull; public class JavaPropertiesHelper { private JavaPropertiesHelper() { } /** * If the provided expression is an {@link IdentifierTree} or a {@link MethodInvocationTree}, it will check if it used to retrieve * a property with a default value provided (using {@link java.util.Properties#getProperty(String, String)}). * @param expression * @return null The default value of the getProperty method invocation, or null if the expression is not of the expected kind * or if is not used to retrieve a property with a default value. * . */ @CheckForNull public static ExpressionTree retrievedPropertyDefaultValue(ExpressionTree expression) { if (expression.is(Tree.Kind.IDENTIFIER)) { return retrievedPropertyDefaultValue((IdentifierTree) expression); } else if (expression.is(Tree.Kind.METHOD_INVOCATION)) { return retrievedPropertyDefaultValue((MethodInvocationTree) expression); } return null; } @CheckForNull private static ExpressionTree retrievedPropertyDefaultValue(IdentifierTree identifier) { Symbol symbol = identifier.symbol(); if (symbol.usages().size() == 1) { VariableTree declaration = ((Symbol.VariableSymbol) symbol).declaration(); if (declaration != null) { ExpressionTree initializer = declaration.initializer(); if (initializer != null && initializer.is(Tree.Kind.METHOD_INVOCATION)) { return retrievedPropertyDefaultValue((MethodInvocationTree) initializer); } } } return null; } @CheckForNull private static ExpressionTree retrievedPropertyDefaultValue(MethodInvocationTree mit) { if (isGetPropertyWithDefaultValue(mit)) { return mit.arguments().get(1); } return null; } private static boolean isGetPropertyWithDefaultValue(MethodInvocationTree mit) { Symbol symbol = mit.symbol(); if (symbol.owner().type().is("java.util.Properties")) { return "getProperty".equals(symbol.name()) && mit.arguments().size() == 2; } return false; } }
lgpl-3.0
joodicator/PageBot
page/upoopia_lib.py
14748
#=============================================================================== # uppoopa_lib.py - reusable components of upoopia.py. from itertools import * import random import re import util #--------------------------------------------------------------------------- # Constants representing aspects of the state of a Upoopia game. BLACK, WHITE = 'Black', 'White' LEFT, RIGHT, UP, DOWN = (-1,0), (1,0), (0,-1), (0,1) WIDTH, HEIGHT = 19, 10 WORM = { BLACK:'X', WHITE:'O' } POOP = { BLACK:'x', WHITE:'o' } GLXY = { BLACK:'+', WHITE:'=' } DIE = { BLACK:'B', WHITE:'W' } BHOLE, EMPTY = '@', '.' #------------------------------------------------------------------------------- # Utility functions. def other_colour(colour): return WHITE if colour == BLACK else BLACK def roll_die(die_colour, owner_colour): sides = 6 if die_colour == owner_colour else 3 return (die_colour, random.randint(1, sides)) def strip_irc_len(text): codes = re.finditer(r'[\x02\x1f\x16\x0f]|\x03(\d\d?(,\d\d?)?)?', text) return len(text) - sum(len(m.group()) for m in codes) #------------------------------------------------------------------------------- # Hierarcy of exceptions related to Upoopia. class UpoopiaError(Exception): pass class IllegalMove(UpoopiaError): pass #=============================================================================== # The essential state of an ongoing game of Upoopia. class Upoopia(object): __slots__ = ( 'round_beginner', # round_beginner in {BLACK,WHITE} 'round_number', # round_number >= 1, or 0 if not started. 'names', # names[c] in {string,None}, c in {BLACK,WHITE} 'player', # player in {BLACK, WHITE} 'winner', # winner in {BLACK, WHITE, NONE} 'resigned', # resigned in {True, False} 'worm', # worm[colour] == x,y --> board[x,y] == WORM[colour] 'direction', # direction[colour] in {LEFT, RIGHT, UP, DOWN} 'dice', # dice[colour] == [(die_colour,value), ...] 'galaxies', # galaxies[colour] == [GLXY[galaxy_colour], ...] 'has_xray', # xray[colour] in {True,False} 'board' ) # board.get((x,y), EMPTY) # in {WORM[c], POOP[c], GLXY[c], BHOLE, EMPTY} # for 1<=x<=WIDTH, 1<=y<=HEIGHT, c in {BLACK,WHITE} def __init__(self, *args, **kwds): if 'prev' in kwds: self.init_reload(*args, **kwds) else: self.init_normal(*args, **kwds) def init_reload(self, prev): self.init_normal() for attr in Upoopia.__slots__: if hasattr(prev, attr): setattr(self, attr, getattr(prev, attr)) def init_normal(self, black_name=None, white_name=None, first_player=BLACK ): self.round_beginner = first_player self.round_number = 1 self.names = { BLACK:black_name, WHITE:white_name } self.player = first_player self.winner = None self.resigned = False self.worm = { WHITE:(17,8), BLACK:(03,8) } self.direction = { BLACK:RIGHT, WHITE:LEFT } self.dice = { BLACK:[], WHITE:[] } self.galaxies = { BLACK:[], WHITE:[] } self.has_xray = { BLACK:False, WHITE:False } self.board = { self.worm[BLACK]:WORM[BLACK], self.worm[WHITE]:WORM[WHITE], (01,8):POOP[BLACK], (02,8):POOP[BLACK], (19,8):POOP[WHITE], (18,8):POOP[WHITE], (04,4):GLXY[BLACK], (16,4):GLXY[WHITE], (10,4):BHOLE, (10,8):BHOLE } self._start_round() #--------------------------------------------------------------------------- # If this constitutes a legal move, and the player possesses a corresponding # die, move the "colour" worm "length" units (or half, as appropriate) in # "direction", remove the die, and end the current player's turn. def move(self, colour, value, direction): if self.winner: raise IllegalMove('the game is over.') if (colour,value) not in self.dice[self.player]: raise IllegalMove('%s does not possess a %s die of value %s.' % (self.player, colour.lower(), value)) self._just_move(colour, value, direction) self.dice[self.player].remove((colour,value)) self._end_turn() #--------------------------------------------------------------------------- # If this constitutes a legal move, sacrifice a die possessed by the current # player, of the opposite colour to them, and with the given value, # in exchange for allowing them to see their opponents' dice. def xray(self, die_value): die = (other_colour(self.player), die_value) if die not in self.dice[self.player]: raise IllegalMove('%s does not possess a %s die of value %s.' % (self.player, other_colour(self.player).lower(), die_value)) self.dice[self.player].remove(die) self.has_xray[self.player] = True self._end_turn() #--------------------------------------------------------------------------- # Cause the current player to lose the game by resignation. def resign(self): self._loss(self.player, resign=True) #--------------------------------------------------------------------------- # If this constitutes a legal move (ignoring the current player and their # dice), move "colour" worm "length" units in direction "dx,dy", possibly # resulting in the player "colour" losing the game; else, raise IllegalMove. def _just_move(self, colour, length, (dx,dy)): prev_dx, prev_dy = self.direction[colour] if (-prev_dx, -prev_dy) == (dx, dy): raise IllegalMove('worms may not move backwards.') x, y = self.worm[colour] for i in range(length): self.board[x, y] = POOP[colour] x, y = (x+dx-1)%WIDTH+1, (y+dy-1)%HEIGHT+1 target = self.board.get((x,y), EMPTY) if target in GLXY.itervalues(): # Pick up a galaxy. self.galaxies[colour].append(target) elif target != EMPTY: # Run into an obstacle. x, y = (x-dx-1)%WIDTH+1, (y-dy-1)%HEIGHT+1 self._loss(colour) break self.board[x, y] = WORM[colour] self.worm[colour] = x, y self.direction[colour] = dx, dy #--------------------------------------------------------------------------- # Start a new round of gameplay, without adjusting the current player, # round beginner or round number, or x-ray status. def _start_round(self): for colour in BLACK, WHITE: # Roll standard dice. self.dice[colour][:] = [ roll_die(colour, colour), roll_die(colour, colour), roll_die(other_colour(colour), colour) ] # Roll dice for any galaxies held. for galaxy in self.galaxies[colour]: for galaxy_colour in BLACK, WHITE: if galaxy != GLXY[galaxy_colour]: continue self.dice[colour].append(roll_die(galaxy_colour, colour)) break else: raise Exception('invalid galaxy: %s' % galaxy) self.galaxies[colour] = [] #--------------------------------------------------------------------------- # End the current round of gameplay and start a new round. def _end_round(self): self.round_beginner = other_colour(self.round_beginner) self.player = self.round_beginner self.round_number += 1 self.has_xray[BLACK] = False self.has_xray[WHITE] = False self._start_round() #--------------------------------------------------------------------------- # End the current player's turn. def _end_turn(self): other_player = other_colour(self.player) if self.dice[other_player]: # Other player has some dice. self.player = other_player elif not self.dice[self.player]: # Neither player has any dice. self._end_round() #--------------------------------------------------------------------------- # Cause the given player to lose the game, possibly by resignation. def _loss(self, colour, resign=False): self.resigned = resign self.winner = other_colour(colour) #=============================================================================== # A game of Upoopia, equipped to produce text representations of its state. class UpoopiaText(Upoopia): def __init__(self, *args, **kwds): Upoopia.__init__(self, *args, **kwds) # Return a list of strings giving rows in a (monospaced) text representation # of the current game state. If "viewer" is given as BLACK or WHITE, only # the information visible to that player is shown in the output. def game_lines(self, viewer=None, **kwds): return util.join_cols( self.board_lines(viewer, **kwds), self.status_lines(viewer, **kwds) + self.legend_lines(viewer, **kwds), lenf=strip_irc_len) + ['---'] def symbol_text(self, s, **kwds): return 'Blue' if s == BLACK else \ 'Red' if s == WHITE else \ 'B' if s == DIE[BLACK] else \ 'R' if s == DIE[WHITE] else \ '#' if s == WORM[BLACK] else \ '8' if s == WORM[WHITE] else \ 'x' if s == POOP[BLACK] else \ 'o' if s == POOP[WHITE] else \ '$' if s == GLXY[BLACK] else \ '%' if s == GLXY[WHITE] else \ '@' if s == BHOLE else \ '.' if s == EMPTY else None def symbol_colour(self, s, **kwds): return '12' if s in (WORM[BLACK],POOP[BLACK],DIE[BLACK],BLACK) \ else '04' if s in (WORM[WHITE],POOP[WHITE],DIE[WHITE],WHITE) \ else '10' if s == GLXY[BLACK] \ else '06' if s == GLXY[WHITE] \ else '14' if s == EMPTY else None def symbol_colour_text(self, s, **kwds): text = self.symbol_text(s) if kwds.get('irc'): colour = self.symbol_colour(s, **kwds) if colour: text = '\x03%s%s\x03' % (colour, text) return text def board_lines(self, viewer=None, **kwds): lines = [] for y in xrange(1,HEIGHT+1): colour = None cells = [] for x in xrange(1,WIDTH+1): symbol = self.board.get((x, y), EMPTY) new_colour = self.symbol_colour(symbol, **kwds) cell = self.symbol_text(symbol, **kwds) if colour != new_colour: cell = '\x03' + (new_colour or '') + cell colour = new_colour cells.append(cell) line = ' '.join(cells) if kwds.get('irc') and colour: line += '\x0f' lines.append(line) return lines def status_lines(self, viewer=None, **kwds): if self.winner: return [ '', '%(bo)sGame over!%(bo)s' % { 'bo': '\x02' if kwds.get('irc') else ''}, '', '%(bo)s%(pl)s%(pn)s wins%(re)s.%(bo)s' % { 'bo': '\x02' if kwds.get('irc') else '', 'pl': self.symbol_text(self.winner, **kwds), 'pn': ' (%s)' % self.names[self.winner] if self.names[self.winner] else '', 're': ' by resignation' if self.resigned else ''}, ''] else: h_black = viewer == self.player == BLACK and kwds.get('irc') h_white = viewer == self.player == WHITE and kwds.get('irc') return [ '%(pl)s to play (round %(rn)s, started by %(rb)s)' % { 'pl': self.symbol_text(self.player, **kwds), 'rn': self.round_number, 'rb': self.symbol_text(self.round_beginner, **kwds) }, '', '%(cs)s%(pl)s%(pn)s: %(is)s%(ce)s' % { 'cs': '\x03'+self.symbol_colour(BLACK) if h_black else '', 'ce': '\x03' if h_black else '', 'pl': self.symbol_text(BLACK, **kwds), 'pn': ' (%s)' % self.names[BLACK] if self.names[BLACK] else '', 'is': ', '.join(self.item_names(BLACK, viewer, **kwds)) }, '%(cs)s%(pl)s%(pn)s: %(is)s%(ce)s' % { 'cs': '\x03'+self.symbol_colour(WHITE) if h_white else '', 'ce': '\x03' if h_white else '', 'pl': self.symbol_text(WHITE, **kwds), 'pn': ' (%s)' % self.names[WHITE] if self.names[WHITE] else '', 'is': ', '.join(self.item_names(WHITE, viewer, **kwds)) }, ''] def legend_lines(self, viewer=None, **kwds): s = lambda s: self.symbol_text(s, **kwds) black, white = s(BLACK).lower(), s(WHITE).lower() return util.join_rows( ['%s %s die' % (s(DIE[BLACK]), black), '%s %s die' % (s(DIE[WHITE]), white) ], ['%s %s worm' % (s(WORM[BLACK]), black), '%s %s worm' % (s(WORM[WHITE]), white) ], ['%s %s poop' % (s(POOP[BLACK]), black), '%s %s poop' % (s(POOP[WHITE]), white) ], ['%s %s galaxy' % (s(GLXY[BLACK]), black), '%s %s galaxy' % (s(GLXY[WHITE]), white), ], ['%s black hole' % s(BHOLE), '%s empty' % s(EMPTY) ], lenf=strip_irc_len) def item_names(self, player, viewer=None, **kwds): sorted_dice = sorted(self.dice[player], key=lambda (dc,dv): (0 if dc == player else 1, dv)) for (die_colour, value) in sorted_dice: if viewer is None or viewer == player or self.has_xray[viewer]: text = '%s(%s)' % ( self.symbol_text(DIE[die_colour], **kwds), value) else: text = '%s(%s)' % ( self.symbol_text(DIE[die_colour], **kwds), '?') # colour = self.symbol_colour(DIE[die_colour], **kwds) # if colour and kwds.get('irc'): # text = '\x03%s%s\x03' % (colour, text) yield text for galaxy in self.galaxies[player]: yield self.symbol_text(galaxy, **kwds) if self.has_xray[player]: yield 'x-ray vision'
lgpl-3.0
locusf/monotooth
src/mono/Model/Service/Service.cs
564
using System; using System.Runtime.InteropServices; namespace monotooth.Service { /// <summary>A structure to describe a service.</summary> [StructLayout (LayoutKind.Sequential, Pack = 1)] public struct Service { /// <summary>A port of the service. </summary> public int rfcomm_port; /// <summary>Name of the service. </summary> [MarshalAs(UnmanagedType.ByValTStr,SizeConst=256)] public string name; /// <summary>Description of the service.</summary> [MarshalAs(UnmanagedType.ByValTStr,SizeConst=256)] public string description; } }
lgpl-3.0
philjord/jnif
jnif/src/nif/niobject/particle/NiPSysModifierBoolCtlr.java
551
package nif.niobject.particle; import java.nio.ByteBuffer; import nif.NifVer; public abstract class NiPSysModifierBoolCtlr extends NiPSysModifierCtlr { /** <niobject name="NiPSysModifierBoolCtlr" abstract="1" inherit="NiPSysModifierCtlr" ver1="10.2.0.0"> A particle system modifier controller that deals with boolean data? </niobject> */ public boolean readFromStream(ByteBuffer stream, NifVer nifVer) throws java.io.IOException { boolean success = super.readFromStream(stream, nifVer); return success; } }
lgpl-3.0
yawlfoundation/editor
source/org/yawlfoundation/yawl/editor/ui/properties/data/validation/ExpressionMatcher.java
1719
/* * Copyright (c) 2004-2015 The YAWL Foundation. All rights reserved. * The YAWL Foundation is a collaboration of individuals and * organisations who are committed to improving workflow technology. * * This file is part of YAWL. YAWL 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. * * YAWL 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 YAWL. If not, see <http://www.gnu.org/licenses/>. */ package org.yawlfoundation.yawl.editor.ui.properties.data.validation; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Michael Adams * @date 17/02/15 */ public class ExpressionMatcher { private Pattern pattern; public ExpressionMatcher(String regex) { pattern = Pattern.compile(regex); } public boolean contains(String predicate) { return pattern.matcher(predicate).find(); } public String replaceAll(String predicate, String value) { return pattern.matcher(predicate).replaceAll(value); } public List<String> getMatches(String binding) { List<String> matches = new ArrayList<String>(); Matcher matcher = pattern.matcher(binding); while (matcher.find()) { matches.add(matcher.group()); } return matches; } }
lgpl-3.0
Bartlebys/BartlebyServer
Commons/_generated/EndPoints/CreateBlock.php
4237
<?php /** * Generated by BARTLEBY'S Flexions for [Benoit Pereira da Silva] (https://pereira-da-silva.com/contact) on ? * https://github.com/Bartlebys * * DO NOT MODIFY THIS FILE YOUR MODIFICATIONS WOULD BE ERASED ON NEXT GENERATION! * * Copyright (c) 2016 [Bartleby's org] (https://bartlebys.org) All rights reserved. */ namespace Bartleby\EndPoints; require_once BARTLEBY_ROOT_FOLDER . 'Core/KeyPath.php'; //require_once BARTLEBY_ROOT_FOLDER.'Core/RunAndLock.php'; require_once BARTLEBY_ROOT_FOLDER.'Core/RunUnlocked.php'; require_once BARTLEBY_ROOT_FOLDER . 'Mongo/MongoEndPoint.php'; require_once BARTLEBY_ROOT_FOLDER . 'Mongo/MongoCallDataRawWrapper.php'; require_once BARTLEBY_PUBLIC_FOLDER . 'Configuration.php'; use Bartleby\Mongo\MongoEndPoint; use Bartleby\Mongo\MongoCallDataRawWrapper; use Bartleby\Core\JsonResponse; use \MongoCollection; use Bartleby\Configuration; use Bartleby\Core\KeyPath; use Closure; //use Bartleby\Core\RunAndLock; // To keep the generated code we have replaced RunAndLock by RunUnlocked use Bartleby\Core\RunUnlocked; class CreateBlockCallData extends MongoCallDataRawWrapper { const block='block'; } class CreateBlock extends MongoEndPoint { function call() { /* @var CreateBlockCallData */ $parameters=$this->getModel(); $db=$this->getDB(); /* @var \MongoCollection */ $collection = $db->blocks; // Write Acknowlegment policy $options = $this->getConfiguration()->getDefaultMongoWriteConcern(); $obj=$parameters->getValueForKey(CreateBlockCallData::block); if(!isset($obj) || count($parameters->getDictionary())==0){ return new JsonResponse('Void submission',406); } try { // Inject the rootUID and the spaceUID in any entity $obj[OBSERVATION_UID_KEY]=$this->getObservationUID(false); $obj[SPACE_UID_KEY]=$this->getSpaceUID(false); //Insert via a locked Closure /* @var $mongoAction \Closure*/ $mongoAction=function () use($collection,$obj,$options) { return $collection->insert($obj,$options ); }; $lockName='blocks'; $r=RunUnlocked::run($mongoAction,$lockName); if ($r['ok']==1) { $s=$this->responseStringWithTriggerInformations($this->createTrigger($parameters),NULL); return new JsonResponse($s,201); } else { return new JsonResponse($r,412); } } catch ( \Exception $e ) { // MONGO E11000 duplicate key error if ( $e->getCode() == 11000 && $this->getConfiguration()->IGNORE_MULTIPLE_CREATION_IN_CRUD_MODE() == true){ // We return A 200 not a 201 $s=$this->responseStringWithTriggerInformations($this->createTrigger($parameters),'This is not the first attempt.'); return new JsonResponse($s,200); } return new JsonResponse( [ 'code'=>$e->getCode(), 'message'=>$e->getMessage(), 'file'=>$e->getFile(), 'line'=>$e->getLine(), 'trace'=>$e->getTraceAsString() ], 417 ); } } /** * Creates and relay the action using a trigger * * @param CreateBlockCallData $parameters * @return array composed of two components * [0] is an int * -2 if the trigger relay has been discarded * -1 if an error has occured * > 0 the trigger index on success * [1] correspond to the requestDuration * @throws \Exception */ function createTrigger(CreateBlockCallData $parameters){ $ref=$parameters->getValueForKey(CreateBlockCallData::block); $homologousAction="ReadBlockById"; $senderUID=$this->getCurrentUserID($this->getSpaceUID(true)); return $this->relayTrigger($senderUID,"blocks","CreateBlock",$homologousAction,$ref,false); } } ?>
lgpl-3.0
pcolby/libqtaws
src/devopsguru/getresourcecollectionrequest.cpp
4436
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "getresourcecollectionrequest.h" #include "getresourcecollectionrequest_p.h" #include "getresourcecollectionresponse.h" #include "devopsgururequest_p.h" namespace QtAws { namespace DevOpsGuru { /*! * \class QtAws::DevOpsGuru::GetResourceCollectionRequest * \brief The GetResourceCollectionRequest class provides an interface for DevOpsGuru GetResourceCollection requests. * * \inmodule QtAwsDevOpsGuru * * Amazon DevOps Guru is a fully managed service that helps you identify anomalous behavior in business critical * operational applications. You specify the AWS resources that you want DevOps Guru to cover, then the Amazon CloudWatch * metrics and AWS CloudTrail events related to those resources are analyzed. When anomalous behavior is detected, DevOps * Guru creates an <i>insight</i> that includes recommendations, related events, and related metrics that can help you * improve your operational applications. For more information, see <a * href="https://docs.aws.amazon.com/devops-guru/latest/userguide/welcome.html">What is Amazon DevOps Guru</a>. * * </p * * You can specify 1 or 2 Amazon Simple Notification Service topics so you are notified every time a new insight is * created. You can also enable DevOps Guru to generate an OpsItem in AWS Systems Manager for each insight to help you * manage and track your work addressing insights. * * </p * * To learn about the DevOps Guru workflow, see <a * href="https://docs.aws.amazon.com/devops-guru/latest/userguide/welcome.html#how-it-works">How DevOps Guru works</a>. To * learn about DevOps Guru concepts, see <a * href="https://docs.aws.amazon.com/devops-guru/latest/userguide/concepts.html">Concepts in DevOps Guru</a>. * * \sa DevOpsGuruClient::getResourceCollection */ /*! * Constructs a copy of \a other. */ GetResourceCollectionRequest::GetResourceCollectionRequest(const GetResourceCollectionRequest &other) : DevOpsGuruRequest(new GetResourceCollectionRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a GetResourceCollectionRequest object. */ GetResourceCollectionRequest::GetResourceCollectionRequest() : DevOpsGuruRequest(new GetResourceCollectionRequestPrivate(DevOpsGuruRequest::GetResourceCollectionAction, this)) { } /*! * \reimp */ bool GetResourceCollectionRequest::isValid() const { return false; } /*! * Returns a GetResourceCollectionResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * GetResourceCollectionRequest::response(QNetworkReply * const reply) const { return new GetResourceCollectionResponse(*this, reply); } /*! * \class QtAws::DevOpsGuru::GetResourceCollectionRequestPrivate * \brief The GetResourceCollectionRequestPrivate class provides private implementation for GetResourceCollectionRequest. * \internal * * \inmodule QtAwsDevOpsGuru */ /*! * Constructs a GetResourceCollectionRequestPrivate object for DevOpsGuru \a action, * with public implementation \a q. */ GetResourceCollectionRequestPrivate::GetResourceCollectionRequestPrivate( const DevOpsGuruRequest::Action action, GetResourceCollectionRequest * const q) : DevOpsGuruRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the GetResourceCollectionRequest * class' copy constructor. */ GetResourceCollectionRequestPrivate::GetResourceCollectionRequestPrivate( const GetResourceCollectionRequestPrivate &other, GetResourceCollectionRequest * const q) : DevOpsGuruRequestPrivate(other, q) { } } // namespace DevOpsGuru } // namespace QtAws
lgpl-3.0
sones/sones-RemoteTagExample
java/RemoteTagExample/src/com/sones/GetPropertyDefinitionsByNameListByEdgeTypeResponse.java
2109
package com.sones; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="GetPropertyDefinitionsByNameListByEdgeTypeResult" type="{http://www.sones.com}ArrayOfServicePropertyDefinition" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "getPropertyDefinitionsByNameListByEdgeTypeResult" }) @XmlRootElement(name = "GetPropertyDefinitionsByNameListByEdgeTypeResponse") public class GetPropertyDefinitionsByNameListByEdgeTypeResponse { @XmlElement(name = "GetPropertyDefinitionsByNameListByEdgeTypeResult", nillable = true) protected ArrayOfServicePropertyDefinition getPropertyDefinitionsByNameListByEdgeTypeResult; /** * Gets the value of the getPropertyDefinitionsByNameListByEdgeTypeResult property. * * @return * possible object is * {@link ArrayOfServicePropertyDefinition } * */ public ArrayOfServicePropertyDefinition getGetPropertyDefinitionsByNameListByEdgeTypeResult() { return getPropertyDefinitionsByNameListByEdgeTypeResult; } /** * Sets the value of the getPropertyDefinitionsByNameListByEdgeTypeResult property. * * @param value * allowed object is * {@link ArrayOfServicePropertyDefinition } * */ public void setGetPropertyDefinitionsByNameListByEdgeTypeResult(ArrayOfServicePropertyDefinition value) { this.getPropertyDefinitionsByNameListByEdgeTypeResult = value; } }
lgpl-3.0
prokhor-ozornin/Catharsis.NET.Web.Widgets
doc/html/search/all_17.js
393
var searchData= [ ['x',['X',['../namespace_catharsis_1_1_web_1_1_widgets.html#ac0f8f20b065d6bc3d15ab6ad72b0bc2ca02129bb861061d1a052c592e2dc6b383',1,'Catharsis::Web::Widgets']]], ['xml',['Xml',['../class_catharsis_1_1_web_1_1_widgets_1_1_i_gravatar_profile_url_widget_extensions.html#aa44219b00102b307b65d4501b2001dd3',1,'Catharsis::Web::Widgets::IGravatarProfileUrlWidgetExtensions']]] ];
lgpl-3.0
jayfella/WebOp2
src/me/jayfella/webop2/WebPages/JavaScript/jayfella.serverwhitelist.js
2112
$("#serverWhitelistList").selectable({ stop: function() { $("#serverWhitelistRemoveSelectedSpan").val(''); var output = ''; $( ".ui-selected", this ).each(function() { output = output + $(this).text() + ", "; }); $("#serverWhitelistRemoveSelectedSpan").text(output); } }); $(document).on('click', '#whitelistModeButton', function (e) { var thisButton = this; $(thisButton).attr('disabled','disabled'); var btnClass = ($(thisButton).attr("class") === "smallGreenButton") ? "enable" : "disable"; $.post("whitelist.php", { action: "toggleWhitelistMode", mode: btnClass }, function(value) { switch (value) { case "true": { $(thisButton).attr("class","smallRedButton"); $(thisButton).html("ON - Only whitelisted players can join"); break; } case "false": { $(thisButton).attr("class","smallGreenButton"); $(thisButton).html("OFF - Anybody can join"); break; } } $(thisButton).removeAttr('disabled'); }); }); $("#serverWhitelistAddPlayersButton").click(function () { var usersToAdd = $("#ServerWhitelistAddPlayersInput").val(); $.post("whitelist.php", { action: "add", listType: "server", users: usersToAdd }, function(value) { $('#serverWhitelistList > li').each(function (index, element) { $(element).remove(); }); $("#serverWhitelistList").html(value); }); }); $("#serverWhitelistRemoveSelectedButton").click(function() { var removeNames = $("#serverWhitelistRemoveSelectedSpan").text(); $.post("whitelist.php", { action: "remove", listType: "server", users: removeNames }, function(value) { $('#serverWhitelistList > li').each(function (index, element) { $(element).remove(); }); $("#serverWhitelistList").html(value); $("#serverWhitelistRemoveSelectedSpan").text(""); }); });
lgpl-3.0
LukeDS-it/ng-synchronicity-II
protractor.conf.js
837
// Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts /*global jasmine */ var SpecReporter = require('jasmine-spec-reporter'); exports.config = { allScriptsTimeout: 11000, specs: [ './e2e/**/*.e2e-spec.ts' ], capabilities: { 'browserName': 'chrome' }, directConnect: true, baseUrl: 'http://localhost:4200/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function () { } }, useAllAngular2AppRoots: true, beforeLaunch: function () { require('ts-node').register({ project: 'e2e' }); }, onPrepare: function () { jasmine.getEnv().addReporter(new SpecReporter()); } };
lgpl-3.0
okorach/audio-video-tools
mediatools/exceptions.py
2087
#!python3 # # media-tools # Copyright (C) 2019-2021 Olivier Korach # mailto:olivier.korach AT gmail DOT com # # 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 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser 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. # class FileTypeError(Exception): '''Error when passing a non media file''' def __init__(self, file="file", expected_type='media', message=None): self.file = file self.message = message if message is None: self.message = "File {} is not of the expected {} type".format(file, expected_type) super().__init__(self.message) class InputError(Exception): '''Error when passing wrong input arguments for media transformation''' def __init__(self, message=None, operation=None): self.message = message self.operation = operation if message is None: self.message = "Input parameters error" if operation is not None: self.message = "{}: {}".format(operation, self.message) super().__init__(self.message) class DimensionError(Exception): '''Error when copputing image or video dimensions''' def __init__(self, message=None, operation=None): self.message = message self.operation = operation if message is None: self.message = "Dimensions error" if operation is not None: self.message = "{}: {}".format(operation, self.message) super().__init__(self.message)
lgpl-3.0
kstateome/canvas-api
src/main/java/edu/ksu/canvas/util/HttpParameterBuilder.java
1703
package edu.ksu.canvas.util; import edu.ksu.canvas.constants.CanvasConstants; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * This class transforms a map into a parameter string * * EX: '{ array[]: [a, b], item: [c] } would return the following string * ?array[]=a&array[]=b&item=c */ public class HttpParameterBuilder { private static final Logger LOG = LoggerFactory.getLogger(HttpParameterBuilder.class); public static String buildParameters(Map<String, List<String>> parameters) { return parameters.entrySet().stream() .map(HttpParameterBuilder::buildParameter) .reduce((a, b) -> a + b) .filter(s -> s.length() > 0) .map(s -> s.substring(1)) .map(paramString -> "?" + paramString) .orElse(""); } private static String buildParameter(Map.Entry<String, List<String>> entry) { String paramName = entry.getKey(); return entry.getValue() .stream() .reduce("", (a, paramValue) -> { String urlParams = ""; try { urlParams = (a + "&" + URLEncoder.encode(paramName, CanvasConstants.URLENCODING_TYPE) + "=" + URLEncoder.encode(paramValue, CanvasConstants.URLENCODING_TYPE)); } catch (UnsupportedEncodingException e){ LOG.warn("Failed to encode parameter " + paramName); } return urlParams; }); } }
lgpl-3.0
hamekoz/hamekoz-sharp
Hamekoz.Shared/Reportes/ParametrosInsuficientesException.cs
2389
// // ParametrosInsuficientesException.cs // // Author: // Claudio Rodrigo Pereyra Diaz <claudiorodrigo@pereyradiaz.com.ar> // // Copyright (c) 2014 Hamekoz - www.hamekoz.com.ar // // 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 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; namespace Hamekoz.Reportes { [Serializable] public class ParametrosInsuficientesException : Exception { /// <summary> /// Initializes a new instance of the <see cref="T:DatosInsuficientesException"/> class /// </summary> public ParametrosInsuficientesException () { } /// <summary> /// Initializes a new instance of the <see cref="T:DatosInsuficientesException"/> class /// </summary> /// <param name="message">A <see cref="T:System.String"/> that describes the exception. </param> public ParametrosInsuficientesException (string message) : base (message) { } /// <summary> /// Initializes a new instance of the <see cref="T:DatosInsuficientesException"/> class /// </summary> /// <param name="message">A <see cref="T:System.String"/> that describes the exception. </param> /// <param name="inner">The exception that is the cause of the current exception. </param> public ParametrosInsuficientesException (string message, Exception inner) : base (message, inner) { } /// <summary> /// Initializes a new instance of the <see cref="T:DatosInsuficientesException"/> class /// </summary> /// <param name="context">The contextual information about the source or destination.</param> /// <param name="info">The object that holds the serialized object data.</param> protected ParametrosInsuficientesException (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (info, context) { } } }
lgpl-3.0
mkloubert/CLRToolboxReloaded
MarcelJoachimKloubert.CLRToolboxReloaded.NET4_0/Extensions/Data.ExecuteEnumerableReader.cs
1442
// LICENSE: LGPL 3 - https://www.gnu.org/licenses/lgpl-3.0.txt // s. https://github.com/mkloubert/CLRToolboxReloaded using System; using System.Collections.Generic; using System.Data; namespace MarcelJoachimKloubert.CLRToolbox.Extensions.Data { static partial class ClrToolboxDataExtensionMethods { #region Methods (2) /// <summary> /// Executes a command and returns it as sequence of underlying data record. /// </summary> /// <param name="cmd">The command to execute.</param> /// <returns>The (lazy) sequence of command.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="cmd" /> is <see langword="null" />. /// </exception> public static IEnumerable<IDataRecord> ExecuteEnumerableReader(this IDbCommand cmd) { return ExecuteEnumerableReaderInner<IDataRecord>(cmd); } private static IEnumerable<TRec> ExecuteEnumerableReaderInner<TRec>(IDbCommand cmd) where TRec : global::System.Data.IDataRecord { if (cmd == null) { throw new ArgumentNullException("cmd"); } using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { yield return (TRec)reader; } } } #endregion Methods } }
lgpl-3.0
thmarth/SEServerExtender
SEModAPIInternal/API/Entity/Sector/SectorObject/CubeGrid/CubeBlock/BatteryBlockEntity.cs
15943
namespace SEModAPIInternal.API.Entity.Sector.SectorObject.CubeGrid.CubeBlock { using System; using System.ComponentModel; using System.Reflection; using System.Runtime.Serialization; using Sandbox; using Sandbox.Common.ObjectBuilders; using SEModAPI.API.Utility; using SEModAPIInternal.API.Common; using SEModAPIInternal.Support; [DataContract] public class BatteryBlockEntity : FunctionalBlockEntity { #region "Attributes" private BatteryBlockNetworkManager m_batteryBlockNetManager; private float m_maxPowerOutput; private float m_maxStoredPower; //Internal class public static string BatteryBlockNamespace = "Sandbox.Game.Entities"; public static string BatteryBlockClass = "MyBatteryBlock"; //Internal methods public static string BatteryBlockGetCurrentStoredPowerMethod = "get_CurrentStoredPower"; public static string BatteryBlockSetCurrentStoredPowerMethod = "set_CurrentStoredPower"; public static string BatteryBlockGetMaxStoredPowerMethod = "get_MaxStoredPower"; public static string BatteryBlockSetMaxStoredPowerMethod = "set_MaxStoredPower"; public static string BatteryBlockGetProducerEnabledMethod = "get_ProductionEnabled"; public static string BatteryBlockSetProducerEnabledMethod = "set_ProductionEnabled"; public static string BatteryBlockGetSemiautoEnabledMethod = "get_SemiautoEnabled"; public static string BatteryBlockSetSemiautoEnabledMethod = "set_SemiautoEnabled"; //Internal fields public static string BatteryBlockCurrentStoredPowerField = "m_currentStoredPower"; public static string BatteryBlockMaxStoredPowerField = "m_maxStoredPower"; public static string BatteryBlockProducerEnabledField = "m_producerEnabled"; public static string BatteryBlockSemiautoEnabledField = "m_semiautoEnabled"; public static string BatteryBlockBatteryDefinitionField = "m_batteryBlockDefinition"; public static string BatteryBlockNetManagerField = "SyncObject"; #endregion "Attributes" #region "Constructors and Initializers" public BatteryBlockEntity( CubeGridEntity parent, MyObjectBuilder_BatteryBlock definition ) : base( parent, definition ) { } public BatteryBlockEntity( CubeGridEntity parent, MyObjectBuilder_BatteryBlock definition, Object backingObject ) : base( parent, definition, backingObject ) { m_maxPowerOutput = 0; m_maxStoredPower = definition.MaxStoredPower; m_batteryBlockNetManager = new BatteryBlockNetworkManager( this, InternalGetNetManager( ) ); } #endregion "Constructors and Initializers" #region "Properties" [IgnoreDataMember] [Category( "Battery Block" )] [Browsable( false )] [ReadOnly( true )] new internal static Type InternalType { get { Type type = SandboxGameAssemblyWrapper.Instance.GetAssemblyType( BatteryBlockNamespace, BatteryBlockClass ); return type; } } [IgnoreDataMember] [Category( "Battery Block" )] [Browsable( false )] [ReadOnly( true )] internal new MyObjectBuilder_BatteryBlock ObjectBuilder { get { MyObjectBuilder_BatteryBlock batteryBlock = (MyObjectBuilder_BatteryBlock)base.ObjectBuilder; batteryBlock.MaxStoredPower = m_maxStoredPower; return batteryBlock; } set { base.ObjectBuilder = value; } } [DataMember] [Category( "Battery Block" )] [DisplayName("Current Stored Power (MWh)")] public float CurrentStoredPower { get { return ObjectBuilder.CurrentStoredPower; } set { if ( ObjectBuilder.CurrentStoredPower == value ) return; ObjectBuilder.CurrentStoredPower = value; Changed = true; if ( BackingObject != null ) { MySandboxGame.Static.Invoke( InternalUpdateBatteryBlockCurrentStoredPower ); } } } [DataMember] [Category( "Battery Block" )] [DisplayName("Maximum Stored Power (MWh)")] [ReadOnly(true)] public float MaxStoredPower { get { float maxStoredPower = 0; if ( ActualObject != null ) { maxStoredPower = (float)InvokeEntityMethod( ActualObject, BatteryBlockGetMaxStoredPowerMethod ); } else { maxStoredPower = m_maxStoredPower; } return maxStoredPower; } set { if ( m_maxStoredPower == value ) return; m_maxStoredPower = value; Changed = true; if ( BackingObject != null ) { MySandboxGame.Static.Invoke( InternalUpdateBatteryBlockMaxStoredPower ); } } } [DataMember] [Category( "Battery Block" )] [DisplayName("Discharge")] public bool ProducerEnabled { get { return ObjectBuilder.ProducerEnabled; } set { if ( ObjectBuilder.ProducerEnabled == value ) return; ObjectBuilder.ProducerEnabled = value; Changed = true; if ( BackingObject != null ) { MySandboxGame.Static.Invoke( InternalUpdateBatteryBlockProducerEnabled ); } } } [DataMember] [Category( "Battery Block" )] [DisplayName("Semi-Automatic")] public bool SemiautoEnabled { get { return ObjectBuilder.SemiautoEnabled; } set { if ( ObjectBuilder.SemiautoEnabled == value ) return; ObjectBuilder.SemiautoEnabled = value; Changed = true; if ( BackingObject != null ) { MySandboxGame.Static.Invoke( InternalUpdateBatteryBlockSemiautoEnabled ); } } } [DataMember] [Category( "Battery Block" )] [ReadOnly(true)] [DisplayName("Power Input (MW)")] public float RequiredPowerInput { get { return PowerReceiver.MaxRequiredInput; } set { if ( PowerReceiver.MaxRequiredInput == value ) return; PowerReceiver.MaxRequiredInput = value; Changed = true; } } [DataMember] [Category( "Battery Block" )] [ReadOnly(true)] [DisplayName("Maximum Power Output")] public float MaxPowerOutput { get { return m_maxPowerOutput; } set { if ( m_maxPowerOutput == value ) return; m_maxPowerOutput = value; Changed = true; if ( BackingObject != null ) { MySandboxGame.Static.Invoke( InternalUpdateBatteryBlockMaxPowerOutput ); } } } [IgnoreDataMember] [Browsable( false )] [ReadOnly( true )] internal BatteryBlockNetworkManager BatteryNetManager { get { return m_batteryBlockNetManager; } } #endregion "Properties" #region "Methods" new public static bool ReflectionUnitTest( ) { try { bool result = true; Type type = SandboxGameAssemblyWrapper.Instance.GetAssemblyType( BatteryBlockNamespace, BatteryBlockClass ); if ( type == null ) throw new Exception( "Could not find internal type for BatteryBlockEntity" ); result &= Reflection.HasMethod( type, BatteryBlockGetCurrentStoredPowerMethod ); result &= Reflection.HasMethod( type, BatteryBlockSetCurrentStoredPowerMethod ); result &= Reflection.HasMethod( type, BatteryBlockGetMaxStoredPowerMethod ); result &= Reflection.HasMethod( type, BatteryBlockSetMaxStoredPowerMethod ); result &= Reflection.HasMethod( type, BatteryBlockGetProducerEnabledMethod ); result &= Reflection.HasMethod( type, BatteryBlockSetProducerEnabledMethod ); result &= Reflection.HasMethod( type, BatteryBlockGetSemiautoEnabledMethod ); result &= Reflection.HasMethod( type, BatteryBlockSetSemiautoEnabledMethod ); result &= Reflection.HasField( type, BatteryBlockCurrentStoredPowerField ); result &= Reflection.HasField( type, BatteryBlockMaxStoredPowerField ); result &= Reflection.HasField( type, BatteryBlockProducerEnabledField ); result &= Reflection.HasField( type, BatteryBlockSemiautoEnabledField ); result &= Reflection.HasField( type, BatteryBlockBatteryDefinitionField ); result &= Reflection.HasField( type, BatteryBlockNetManagerField ); return result; } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); return false; } } #region "Internal" protected override float InternalPowerReceiverCallback( ) { if ( ProducerEnabled || ( CurrentStoredPower / MaxStoredPower ) >= 0.98 ) { return 0.0f; } else { return PowerReceiver.MaxRequiredInput; } } protected Object InternalGetNetManager( ) { try { FieldInfo field = GetEntityField( ActualObject, BatteryBlockNetManagerField ); Object result = field.GetValue( ActualObject ); return result; } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); return null; } } protected void InternalUpdateBatteryBlockCurrentStoredPower( ) { try { InvokeEntityMethod( ActualObject, BatteryBlockSetCurrentStoredPowerMethod, new object[ ] { CurrentStoredPower } ); BatteryNetManager.BroadcastCurrentStoredPower( ); } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); } } protected void InternalUpdateBatteryBlockMaxStoredPower( ) { try { InvokeEntityMethod( ActualObject, BatteryBlockSetMaxStoredPowerMethod, new object[ ] { m_maxStoredPower } ); } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); } } protected void InternalUpdateBatteryBlockProducerEnabled( ) { try { InvokeEntityMethod( ActualObject, BatteryBlockSetProducerEnabledMethod, new object[ ] { ProducerEnabled } ); BatteryNetManager.BroadcastProducerEnabled( ); } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); } } protected void InternalUpdateBatteryBlockSemiautoEnabled( ) { try { InvokeEntityMethod( ActualObject, BatteryBlockSetSemiautoEnabledMethod, new object[ ] { SemiautoEnabled } ); BatteryNetManager.BroadcastSemiautoEnabled( ); } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); } } protected void InternalUpdateBatteryBlockMaxPowerOutput( ) { //TODO - Do stuff } #endregion "Internal" #endregion "Methods" } public class BatteryBlockNetworkManager { #region "Attributes" private BatteryBlockEntity m_parent; private Object m_backingObject; private static bool m_isRegistered; public static string BatteryBlockNetworkManagerNamespace = BatteryBlockEntity.BatteryBlockNamespace + "." + BatteryBlockEntity.BatteryBlockClass; public static string BatteryBlockNetworkManagerClass = "MySyncBatteryBlock"; public static string BatteryBlockNetManagerBroadcastProducerEnabledMethod = "SendProducerEnableChange"; public static string BatteryBlockNetManagerBroadcastCurrentStoredPowerMethod = "CapacityChange"; public static string BatteryBlockNetManagerBroadcastSemiautoEnabledMethod = "SendSemiautoEnableChange"; public static string BatteryBlockNetManagerCurrentPowerPacketReceiver = "CapacityChange"; /////////////////////////////////////////////////////////////////////// //Packets //1587 - CurrentStoredPower //1588 - ?? //15870 - ProducerEnabled On/Off //15871 - SemiautoEnabled On/Off //public static string BatteryBlockNetManagerCurrentStoredPowerPacketGetIdMethod = "300F0FF97B3FABBCEBB539E8935D6930"; //public static string BatteryBlockNetManagerCurrentStoredPowerPacketGetIdMethod = "12133389A918B17D9822AB1721C55497"; public static string BatteryBlockNetManagerCurrentStoredPowerPacketClass = "CapacityMsg"; public static string BatteryBlockNetManagerCurrentStoredPowerPacketValueField = "capacity"; #endregion "Attributes" #region "Constructors and Initializers" public BatteryBlockNetworkManager( BatteryBlockEntity parent, Object backingObject ) { m_parent = parent; m_backingObject = backingObject; MySandboxGame.Static.Invoke( RegisterPacketHandlers ); } #endregion "Constructors and Initializers" #region "Properties" internal Object BackingObject { get { return m_backingObject; } } public static Type InternalType { get { Type type = BatteryBlockEntity.InternalType.GetNestedType( BatteryBlockNetworkManagerClass, BindingFlags.Public | BindingFlags.NonPublic ); return type; } } #endregion "Properties" #region "Methods" public static bool ReflectionUnitTest( ) { try { bool result = true; Type type = InternalType; if ( type == null ) throw new Exception( "Could not find internal type for BatteryBlockNetworkManager" ); result &= Reflection.HasMethod( type, BatteryBlockNetManagerBroadcastProducerEnabledMethod ); result &= Reflection.HasMethod( type, BatteryBlockNetManagerBroadcastCurrentStoredPowerMethod ); result &= Reflection.HasMethod( type, BatteryBlockNetManagerBroadcastSemiautoEnabledMethod ); Type packetType = InternalType.GetNestedType( BatteryBlockNetManagerCurrentStoredPowerPacketClass, BindingFlags.Public | BindingFlags.NonPublic ); //result &= BaseObject.HasMethod( packetType, BatteryBlockNetManagerCurrentStoredPowerPacketGetIdMethod ); result &= Reflection.HasField( packetType, BatteryBlockNetManagerCurrentStoredPowerPacketValueField ); // result &= BaseObject.HasField(packetType, BatteryBlockNetManagerCurrentStoredPowerPacketGetIdField); Type refPacketType = packetType.MakeByRefType( ); return result; } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); return false; } } public void BroadcastProducerEnabled( ) { BaseObject.InvokeEntityMethod( BackingObject, BatteryBlockNetManagerBroadcastProducerEnabledMethod, new object[ ] { m_parent.ProducerEnabled } ); } public void BroadcastCurrentStoredPower( ) { BaseObject.InvokeEntityMethod( BackingObject, BatteryBlockNetManagerBroadcastCurrentStoredPowerMethod, new object[ ] { m_parent.CurrentStoredPower } ); } public void BroadcastSemiautoEnabled( ) { BaseObject.InvokeEntityMethod( BackingObject, BatteryBlockNetManagerBroadcastSemiautoEnabledMethod, new object[ ] { m_parent.SemiautoEnabled } ); } protected static void RegisterPacketHandlers( ) { try { if ( m_isRegistered ) return; Type packetType = InternalType.GetNestedType( BatteryBlockNetManagerCurrentStoredPowerPacketClass, BindingFlags.Public | BindingFlags.NonPublic ); MethodInfo method = typeof( BatteryBlockNetworkManager ).GetMethod( "ReceiveCurrentPowerPacket", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ); bool result = NetworkManager.RegisterCustomPacketHandler( PacketRegistrationType.Static, packetType, method, InternalType ); if ( !result ) return; m_isRegistered = true; } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); } } protected static void ReceiveCurrentPowerPacket<T>( ref T packet, Object netManager ) where T : struct { try { //object result = BaseObject.InvokeEntityMethod( packet, BatteryBlockNetManagerCurrentStoredPowerPacketGetIdMethod ); //object result = BaseObject.GetEntityFieldValue(packet, BatteryBlockNetManagerCurrentStoredPowerPacketGetIdField); object result = null; if ( result == null ) return; long entityId = (long)result; BaseObject matchedEntity = GameEntityManager.GetEntity( entityId ); if ( matchedEntity == null ) return; if ( !( matchedEntity is BatteryBlockEntity ) ) return; BatteryBlockEntity battery = (BatteryBlockEntity)matchedEntity; result = BaseObject.GetEntityFieldValue( packet, BatteryBlockNetManagerCurrentStoredPowerPacketValueField ); if ( result == null ) return; float packetPowerLevel = (float)result; if ( packetPowerLevel == 1.0f ) return; BaseObject.SetEntityFieldValue( packet, BatteryBlockNetManagerCurrentStoredPowerPacketValueField, battery.CurrentStoredPower ); Type refPacketType = packet.GetType( ).MakeByRefType( ); MethodInfo basePacketHandlerMethod = BaseObject.GetStaticMethod( InternalType, BatteryBlockNetManagerCurrentPowerPacketReceiver, new Type[ ] { refPacketType, netManager.GetType( ) } ); basePacketHandlerMethod.Invoke( null, new object[ ] { packet, netManager } ); } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); } } #endregion "Methods" } }
lgpl-3.0
anlambert/tulip
plugins/view/ParallelCoordinatesView/src/ParallelCoordinatesViewQuickAccessbar.cpp
2963
/** * * Copyright (C) 2019-2021 The Talipot developers * * Talipot is a fork of Tulip, created by David Auber * and the Tulip development Team from LaBRI, University of Bordeaux * * See the AUTHORS file at the top-level directory of this distribution * License: GNU General Public License version 3, or any later version * See top-level LICENSE file for more information * */ #include "ParallelCoordinatesViewQuickAccessbar.h" #include "ParallelCoordsDrawConfigWidget.h" #include <talipot/TlpQtTools.h> #include <talipot/ColorButton.h> namespace tlp { ParallelCoordinatesViewQuickAccessBar::ParallelCoordinatesViewQuickAccessBar( ParallelCoordsDrawConfigWidget *opt, QWidget *parent) : QuickAccessBarImpl(nullptr, QuickAccessBarImpl::QuickAccessButtons( QuickAccessBarImpl::SCREENSHOT | QuickAccessBarImpl::BACKGROUNDCOLOR | QuickAccessBarImpl::SHOWLABELS | QuickAccessBarImpl::SHOWNODES | QuickAccessBarImpl::LABELSSCALED | QuickAccessBarImpl::NODECOLOR | QuickAccessBarImpl::EDGECOLOR | QuickAccessBarImpl::NODEBORDERCOLOR | QuickAccessBarImpl::LABELCOLOR), parent), _optionsWidget(opt) {} void ParallelCoordinatesViewQuickAccessBar::setNodesVisible(bool visible) { _optionsWidget->setDrawPointOnAxis(visible); showNodesButton()->setIcon((visible ? QIcon(":/talipot/gui/icons/20/nodes_enabled.png") : QIcon(":/talipot/gui/icons/20/nodes_disabled.png"))); emit settingsChanged(); } void ParallelCoordinatesViewQuickAccessBar::reset() { QuickAccessBarImpl::reset(); showNodesButton()->setChecked(_optionsWidget->drawPointOnAxis()); showNodesButton()->setIcon((_optionsWidget->drawPointOnAxis() ? QIcon(":/talipot/gui/icons/20/nodes_enabled.png") : QIcon(":/talipot/gui/icons/20/nodes_disabled.png"))); showLabelsButton()->setChecked(_optionsWidget->displayNodeLabels()); showLabelsButton()->setIcon((_optionsWidget->displayNodeLabels() ? QIcon(":/talipot/gui/icons/20/labels_enabled.png") : QIcon(":/talipot/gui/icons/20/labels_disabled.png"))); backgroundColorButton()->setColor(_optionsWidget->getBackgroundColor()); } void ParallelCoordinatesViewQuickAccessBar::setBackgroundColor(const QColor &col) { _optionsWidget->setBackgroundColor(tlp::QColorToColor(col)); emit settingsChanged(); } void ParallelCoordinatesViewQuickAccessBar::setLabelsVisible(bool visible) { _optionsWidget->setDisplayNodeLabels(visible); showLabelsButton()->setIcon((visible ? QIcon(":/talipot/gui/icons/20/labels_enabled.png") : QIcon(":/talipot/gui/icons/20/labels_disabled.png"))); emit settingsChanged(); } }
lgpl-3.0
amazingSurge/jquery-asBreadcrumbs
dist/jquery-asBreadcrumbs.es.js
10232
/** * jQuery asBreadcrumbs v0.2.3 * https://github.com/amazingSurge/jquery-asBreadcrumbs * * Copyright (c) amazingSurge * Released under the LGPL-3.0 license */ import $ from 'jquery'; var DEFAULTS = { namespace: 'breadcrumb', overflow: "left", responsive: true, ellipsisText: "&#8230;", ellipsisClass: null, hiddenClass: 'is-hidden', dropdownClass: null, dropdownMenuClass: null, dropdownItemClass: null, dropdownItemDisableClass: 'disabled', toggleClass: null, toggleIconClass: 'caret', getItems: function($parent) { return $parent.children(); }, getItemLink: function($item) { return $item.find('a'); }, // templates ellipsis: function(classes, label) { return `<li class="${classes.ellipsisClass}">${label}</li>`; }, dropdown: function(classes) { const dropdownClass = 'dropdown'; let dropdownMenuClass = 'dropdown-menu'; if (this.options.overflow === 'right') { dropdownMenuClass += ' dropdown-menu-right'; } return `<li class="${dropdownClass} ${classes.dropdownClass}"> <a href="javascript:void(0);" class="${classes.toggleClass}" data-toggle="dropdown"> <i class="${classes.toggleIconClass}"></i> </a> <ul class="${dropdownMenuClass} ${classes.dropdownMenuClass}"></ul> </li>`; }, dropdownItem: function(classes, label, href) { if(!href) { return `<li class="${classes.dropdownItemClass} ${classes.dropdownItemDisableClass}"><a href="#">${label}</a></li>`; } return `<li class="${classes.dropdownItemClass}"><a href="${href}">${label}</a></li>`; }, // callbacks onInit: null, onReady: null }; const NAMESPACE = 'asBreadcrumbs'; let instanceId = 0; /** * Plugin constructor **/ class asBreadcrumbs { constructor(element, options) { this.element = element; this.$element = $(element); this.options = $.extend({}, DEFAULTS, options, this.$element.data()); this.namespace = this.options.namespace; this.$element.addClass(this.namespace); this.classes = { toggleClass: this.options.toggleClass? this.options.toggleClass: `${this.namespace}-toggle`, toggleIconClass: this.options.toggleIconClass, dropdownClass: this.options.dropdownClass? this.options.dropdownClass: `${this.namespace}-dropdown`, dropdownMenuClass: this.options.dropdownMenuClass? this.options.dropdownMenuClass: `${this.namespace}-dropdown-menu`, dropdownItemClass: this.options.dropdownItemClass? this.options.dropdownItemClass: '', dropdownItemDisableClass: this.options.dropdownItemDisableClass? this.options.dropdownItemDisableClass: '', ellipsisClass: this.options.ellipsisClass? this.options.ellipsisClass: `${this.namespace}-ellipsis`, hiddenClass: this.options.hiddenClass }; // flag this.initialized = false; this.instanceId = (++instanceId); this.$children = this.options.getItems(this.$element); this.$firstChild = this.$children.eq(0); this.$dropdown = null; this.$dropdownMenu = null; this.gap = 6; this.items = []; this._trigger('init'); this.init(); } init() { this.$element.addClass(`${this.namespace}-${this.options.overflow}`); this._prepareItems(); this._createDropdown(); this._createEllipsis(); this.render(); if (this.options.responsive) { $(window).on(this.eventNameWithId('resize'), this._throttle(() => { this.resize(); }, 250)); } this.initialized = true; this._trigger('ready'); } _prepareItems() { const that = this; this.$children.each(function(){ const $this = $(this); const $link = that.options.getItemLink($this); const $dropdownItem = $(that.options.dropdownItem.call(that, that.classes, $this.text(), $link.attr('href'))); that.items.push({ $this, outerWidth: $this.outerWidth(), $item: $dropdownItem }); }); if (this.options.overflow === "left") { this.items.reverse(); } } _createDropdown() { this.$dropdown = $(this.options.dropdown.call(this, this.classes)).addClass(this.classes.hiddenClass).appendTo(this.$element); this.$dropdownMenu = this.$dropdown.find(`.${this.classes.dropdownMenuClass}`); this._createDropdownItems(); if (this.options.overflow === 'right') { this.$dropdown.appendTo(this.$element); } else { this.$dropdown.prependTo(this.$element); } } _createDropdownItems() { for (let i = 0; i < this.items.length; i++) { this.items[i].$item.appendTo(this.$dropdownMenu).addClass(this.classes.hiddenClass); } } _createEllipsis() { if (!this.options.ellipsisText) { return; } this.$ellipsis = $(this.options.ellipsis.call(this, this.classes, this.options.ellipsisText)).addClass(this.classes.hiddenClass); if (this.options.overflow === 'right') { this.$ellipsis.insertBefore(this.$dropdown); } else { this.$ellipsis.insertAfter(this.$dropdown); } } render() { const dropdownWidth = this.getDropdownWidth(); let childrenWidthTotal = 0; let containerWidth = this.getConatinerWidth(); let showDropdown = false; for (let i = 0; i < this.items.length; i++) { childrenWidthTotal += this.items[i].outerWidth; if (childrenWidthTotal + dropdownWidth > containerWidth) { showDropdown = true; this._showDropdownItem(i); } else { this._hideDropdownItem(i); } } if(showDropdown) { this.$ellipsis.removeClass(this.classes.hiddenClass); this.$dropdown.removeClass(this.classes.hiddenClass); } else { this.$ellipsis.addClass(this.classes.hiddenClass); this.$dropdown.addClass(this.classes.hiddenClass); } this._trigger('update'); } resize() { this.render(); } getDropdownWidth() { return this.$dropdown.outerWidth() + (this.options.ellipsisText? this.$ellipsis.outerWidth() : 0); } getConatinerWidth() { let width = 0; const that = this; this.$element.children().each(function() { if ($(this).css('display') === 'inline-block' && $(this).css('float') === 'none') { width += that.gap; } }); return this.$element.width() - width; } _showDropdownItem(i) { this.items[i].$item.removeClass(this.classes.hiddenClass); this.items[i].$this.addClass(this.classes.hiddenClass); } _hideDropdownItem(i) { this.items[i].$this.removeClass(this.classes.hiddenClass); this.items[i].$item.addClass(this.classes.hiddenClass); } _trigger(eventType, ...params) { let data = [this].concat(params); // event this.$element.trigger(`${NAMESPACE}::${eventType}`, data); // callback eventType = eventType.replace(/\b\w+\b/g, (word) => { return word.substring(0, 1).toUpperCase() + word.substring(1); }); let onFunction = `on${eventType}`; if (typeof this.options[onFunction] === 'function') { this.options[onFunction].apply(this, params); } } eventName(events) { if (typeof events !== 'string' || events === '') { return `.${this.options.namespace}`; } events = events.split(' '); let length = events.length; for (let i = 0; i < length; i++) { events[i] = `${events[i]}.${this.options.namespace}`; } return events.join(' '); } eventNameWithId(events) { if (typeof events !== 'string' || events === '') { return `.${this.options.namespace}-${this.instanceId}`; } events = events.split(' '); let length = events.length; for (let i = 0; i < length; i++) { events[i] = `${events[i]}.${this.options.namespace}-${this.instanceId}`; } return events.join(' '); } _throttle(func, wait) { const _now = Date.now || function() { return new Date().getTime(); }; let timeout; let context; let args; let result; let previous = 0; let later = function() { previous = _now(); timeout = null; result = func.apply(context, args); if (!timeout) { context = args = null; } }; return (...params) => { /*eslint consistent-this: "off"*/ let now = _now(); let remaining = wait - (now - previous); context = this; args = params; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) { context = args = null; } } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; } destroy() { this.$element.children().removeClass(this.classes.hiddenClass); this.$dropdown.remove(); if (this.options.ellipsisText) { this.$ellipsis.remove(); } this.initialized = false; this.$element.data(NAMESPACE, null); $(window).off(this.eventNameWithId('resize')); this._trigger('destroy'); } static setDefaults(options) { $.extend(DEFAULTS, $.isPlainObject(options) && options); } } var info = { version:'0.2.3' }; const NAME = 'asBreadcrumbs'; const OtherAsBreadcrumbs = $.fn.asBreadcrumbs; const jQueryAsBreadcrumbs = function(options, ...args) { if (typeof options === 'string') { let method = options; if (/^_/.test(method)) { return false; } else if ((/^(get)/.test(method))) { let instance = this.first().data(NAME); if (instance && typeof instance[method] === 'function') { return instance[method](...args); } } else { return this.each(function() { let instance = $.data(this, NAME); if (instance && typeof instance[method] === 'function') { instance[method](...args); } }); } } return this.each(function() { if (!$(this).data(NAME)) { $(this).data(NAME, new asBreadcrumbs(this, options)); } }); }; $.fn.asBreadcrumbs = jQueryAsBreadcrumbs; $.asBreadcrumbs = $.extend({ setDefaults: asBreadcrumbs.setDefaults, noConflict: function() { $.fn.asBreadcrumbs = OtherAsBreadcrumbs; return jQueryAsBreadcrumbs; } }, info);
lgpl-3.0
teryk/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/task/TaskComponent.java
1085
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.task; /** * All the classes implementing this interface can be injected in public constructors of {@link TaskExtension}. * * @since 3.6 */ public interface TaskComponent { }
lgpl-3.0
SonarSource/sonarqube
server/sonar-process/src/main/java/org/sonar/process/systeminfo/SystemInfoUtils.java
3139
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.systeminfo; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Section; import static java.util.Arrays.stream; public class SystemInfoUtils { private SystemInfoUtils() { // prevent instantiation } public static void setAttribute(Section.Builder section, String key, @Nullable String value) { if (value != null) { section.addAttributesBuilder() .setKey(key) .setStringValue(value) .build(); } } public static void setAttribute(Section.Builder section, String key, @Nullable Collection<String> values) { if (values != null) { section.addAttributesBuilder() .setKey(key) .addAllStringValues(values) .build(); } } public static void setAttribute(Section.Builder section, String key, @Nullable Boolean value) { if (value != null) { section.addAttributesBuilder() .setKey(key) .setBooleanValue(value) .build(); } } public static void setAttribute(Section.Builder section, String key, long value) { section.addAttributesBuilder() .setKey(key) .setLongValue(value) .build(); } @CheckForNull public static ProtobufSystemInfo.Attribute attribute(Section section, String key) { for (ProtobufSystemInfo.Attribute attribute : section.getAttributesList()) { if (attribute.getKey().equals(key)) { return attribute; } } return null; } public static List<Section> order(Collection<Section> sections, String... orderedNames) { Map<String, Section> alphabeticalOrderedMap = new TreeMap<>(); sections.forEach(section -> alphabeticalOrderedMap.put(section.getName(), section)); List<Section> result = new ArrayList<>(sections.size()); stream(orderedNames).forEach(name -> { Section section = alphabeticalOrderedMap.remove(name); if (section != null) { result.add(section); } }); result.addAll(alphabeticalOrderedMap.values()); return result; } }
lgpl-3.0
Kirro/CSCI-Final-Project
change_password_code.php
1895
<?php is_login(); ?> <script language="javascript" > function check_valid (th) { if (th.old_pswd.value=="") { alert ("Please Enter Old Password!"); th.old_pswd.focus(); th.old_pswd.select(); return false; } if (th.new_pswd.value=="") { alert ("Please Enter New Password!"); th.new_pswd.focus(); th.new_pswd.select(); return false; } if (th.con_pswd.value!=th.new_pswd.value) { alert ("Both New & Confirm Passwords do not matched!"); th.con_pswd.focus(); th.con_pswd.select(); return false; } // return false; } </script> <form action="change_password_db.php" method="post" name="fnm" onsubmit="return check_valid(this)"> <table align="center" border="0" width="50%"> <?php if ($_SESSION['MSG'] != "") { ?> <tr> <td colspan="2" height="25" align="center"> <font color="#FF0000"><?php echo $_SESSION['MSG']; ?></font> </td> </tr> <?php $_SESSION['MSG']=""; } ?> <tr> <td colspan="2" height="25" align="center"> <font size="+1" color="#993399">Change Password</font> </td> </tr> <tr> <td width="40%" align="right">Old Password:</td> <td align="left"> <input type="password" name="old_pswd" id="old_pswd" size="25" class="user-inputbox"/> </td> </tr> <tr> <td width="40%" align="right">New Password:</td> <td align="left"> <input type="password" name="new_pswd" id="new_pswd" size="25" class="user-inputbox"/> </td> </tr> <tr> <td width="40%" align="right">Confirm Password:</td> <td align="left"> <input type="password" name="con_pswd" id="con_pswd" size="25" class="user-inputbox"/> </td> </tr> <tr> <td align="right"><input type="submit" value="Submit" class="user-inputbox"/></td> <td> <input type="button" value="Cancel" onclick="window.location='index.php'" class="user-inputbox"/> </td> </tr> </table> </form>
lgpl-3.0
Blimster/three4g
net.blimster.gwt.threejs/src-gen/net/blimster/gwt/threejs/lights/DirectionalLight.java
1247
/* * * This file is part of three4g. * * three4g is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesse General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * three4g 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 three4g. If not, see <http://www.gnu.org/licenses/>. * * (c) 2012 by Oliver Damm, Am Wasserberg 8, 22869 Schenefeld * * mail: oliver [dot] damm [at] gmx [dot] de * web: http://www.blimster.net */ package net.blimster.gwt.threejs.lights; import net.blimster.gwt.threejs.lights.Light; /** * This file is generated, do not edit. */ public final class DirectionalLight extends Light { protected DirectionalLight() { super(); } public static native DirectionalLight create(int hex) /*-{ return new $wnd.THREE.DirectionalLight(hex); }-*/; }
lgpl-3.0
advanced-online-marketing/AOM
Platforms/AbstractPlatform.php
12212
<?php /** * AOM - Piwik Advanced Online Marketing Plugin * * @author Daniel Stonies <daniel.stonies@googlemail.com> * @author André Kolell <andre.kolell@gmail.com> */ namespace Piwik\Plugins\AOM\Platforms; use Exception; use Piwik\Common; use Piwik\Db; use Piwik\Piwik; use Piwik\Plugins\AOM\AOM; use Piwik\Plugins\AOM\Services\DatabaseHelperService; use Piwik\Plugins\AOM\SystemSettings; use Psr\Log\LoggerInterface; use Piwik\Tracker\Request; abstract class AbstractPlatform { /** * @var LoggerInterface */ private $logger; /** * @var SystemSettings */ private $settings; /** * @param LoggerInterface|null $logger */ public function __construct(LoggerInterface $logger = null) { $this->settings = new SystemSettings(); $this->logger = (null === $logger ? AOM::getLogger() : $logger); } /** * @return LoggerInterface */ public function getLogger() { return $this->logger; } /** * Returns this plugin's settings. * * @return SystemSettings */ public function getSettings() { return $this->settings; } /** * Whether or not this platform has been activated in the plugin's configuration. * * @return bool */ public function isActive() { return $this->settings->{'platform' . $this->getName() . 'IsActive'}->getValue(); } /** * Sets up a platform (e.g. adds tables and indices). * * @throws Exception */ public function installPlugin() { $this->getInstaller()->installPlugin(); } /** * Cleans up platform specific stuff such as tables and indices when the plugin is being uninstalled. * * @throws Exception */ public function uninstallPlugin() { $this->getInstaller()->uninstallPlugin(); } /** * Returns the translated localized name of the platform. * * @return string */ public function getLocalizedPlatformName() { return Piwik::translate('AOM_Platform_Name_' . $this->getName()); } /** * Returns true if the visit is coming from this platform. False otherwise. * * TODO: Check if we should use $action->getActionUrl() instead of or in addition to $request->getParams()['url']. * * @param Request $request * @return bool */ public function isVisitComingFromPlatform(Request $request) { // Check current URL first before referrer URL $urlsToCheck = []; if (isset($request->getParams()['url'])) { $urlsToCheck[] = $request->getParams()['url']; } // Only consider the referrer when it is an internal URL if (isset($request->getParams()['urlref']) && $request->getIdSite() && $this->isReferrerAnInternalUrl($request->getParams()['urlref'], $request->getIdSite()) ) { $urlsToCheck[] = $request->getParams()['urlref']; } foreach ($urlsToCheck as $urlToCheck) { if ($this->isPlatformParamForThisPlatformInUrl($urlToCheck)) { return true; } } return false; } /** * Extracts advertisement platform specific data from the request (referrer, query params) and returns it as an * associative array. * * TODO: Check if we should use $action->getActionUrl() instead of or in addition to $request->getParams()['url']. * TODO: Rename adParams into something which also makes sense for data extracted from the referrer * * @param Request $request * @return null|array */ public function getAdParamsFromRequest(Request $request) { $paramPrefix = $this->getSettings()->paramPrefix->getValue(); $platform = AOM::getPlatformInstance($this->getUnqualifiedClassName()); // Check current URL before referrer URL $urlsToCheck = []; if (isset($request->getParams()['url'])) { $urlsToCheck[] = $request->getParams()['url']; } if (isset($request->getParams()['urlref'])) { $urlsToCheck[] = $request->getParams()['urlref']; } // TODO: Should we combine the results of all the different checks instead of simply return the first match? $failures = []; foreach ($urlsToCheck as $urlToCheck) { $queryString = parse_url($urlToCheck, PHP_URL_QUERY); parse_str($queryString, $queryParams); // Individual campaigns return false but no missing params list($success, $params) = $platform->getAdParamsFromUrl($urlToCheck, $queryParams, $paramPrefix, $request); if ($success) { return $params; } elseif (false === $success && count($params) > 0) { $failures[] = ['url' => $urlToCheck, 'missingParams' => $params]; } } if (count($failures) > 0) { $message = 'Visit from platform ' . $platform->getName() . ' '; for ($i = 0; $i < count($failures); $i++) { if ($i > 0) { $message .= ' and '; } $message .= 'without required param' . (count($failures[$i]['missingParams']) != 1 ? 's' : '') . ' "' . implode('", "', $failures[$i]['missingParams']) . '" in URL "' . $failures[$i]['url'] . '"'; } $this->logger->warning($message . '.'); } return null; } /** * Extracts and returns advertisement platform specific data from an URL. * $queryParams and $paramPrefix are only passed as params for convenience reasons. * * @param string $url * @param array $queryParams * @param string $paramPrefix * @param Request $request * @return array|null */ abstract protected function getAdParamsFromUrl($url, array $queryParams, $paramPrefix, Request $request); /** * Instantiates and returns the platform specific installer. * * @return InstallerInterface */ private function getInstaller() { $className = 'Piwik\\Plugins\\AOM\\Platforms\\' . $this->getUnqualifiedClassName() . '\\Installer'; /** @var InstallerInterface $installer */ $installer = new $className($this); return $installer; } public function import($mergeAfterwards = false, $startDate = null, $endDate = null) { if (!$this->isActive()) { return; } /** @var ImporterInterface $importer */ $importer = AOM::getPlatformInstance($this->getUnqualifiedClassName(), 'Importer'); $importer->setPeriod($startDate, $endDate); $importer->import(); if ($mergeAfterwards) { // We must use the importer's period, as $startDate and $endDate can be null or could have been modified $this->logger->debug( 'Will merge ' . $this->getUnqualifiedClassName() . ' for period from ' . $importer->getStartDate() . ' until ' . $importer->getEndDate() . ' on a daily basis now.' ); // We merge on a daily basis, primarily due to performance issues foreach (AOM::getPeriodAsArrayOfDates($importer->getStartDate(), $importer->getEndDate()) as $date) { $this->merge($date, $date); } } } /** * Platforms can add items to the admin menu. By default, no menu items are being added. * * @return array */ public function getMenuAdminItems() { return []; } /** * Platforms can load additional JS files in the admin view. Be default, no additional JS files are being loaded. * The JS file AOM/Platform/{PlatformName}javascripts/{PlatformName}.js is loaded by naming convention. * * @return array */ public function getJsFiles() { return []; } public function merge($startDate, $endDate) { if (!$this->isActive()) { return; } /** @var MergerInterface $merger */ $merger = AOM::getPlatformInstance($this->getUnqualifiedClassName(), 'Merger'); $merger->setPeriod($startDate, $endDate); $merger->merge(); } /** * Deletes all imported data for the given combination of platform account, website and date. * * @param string $platformName * @param string $accountId * @param int $websiteId * @param string $date * @return array */ public static function deleteImportedData($platformName, $accountId, $websiteId, $date) { $timeStart = microtime(true); $deletedImportedDataRecords = Db::deleteAllRows( DatabaseHelperService::getTableNameByPlatformName($platformName), 'WHERE id_account_internal = ? AND idsite = ? AND date = ?', 'date', 100000, [ $accountId, $websiteId, $date, ] ); $timeToDeleteImportedData = microtime(true) - $timeStart; return [$deletedImportedDataRecords, $timeToDeleteImportedData]; } /** * Returns the platform's unqualified class name. * * @return string */ protected function getUnqualifiedClassName() { return substr(strrchr(get_class($this), '\\'), 1); } /** * Returns the platform's name. * * @return string */ public function getName() { return $this->getUnqualifiedClassName(); } /** * Returns the platform's data table name. * * @return string */ public function getDataTableName() { return Common::prefixTable('aom_' . strtolower($this->getName())); } /** * Returns a platform-specific description of a specific visit optimized for being read by humans or false when no * platform-specific description is available. * * @param int $idVisit * @return false|string * @throws Exception */ public static function getHumanReadableDescriptionForVisit($idVisit) { $platform = Db::fetchOne( 'SELECT aom_platform FROM ' . Common::prefixTable('log_visit') . ' WHERE idvisit = ?', [$idVisit] ); if (in_array($platform, AOM::getPlatforms())) { $platform = AOM::getPlatformInstance($platform); return $platform->getHumanReadableDescriptionForVisit($idVisit); } return false; } /** * Returns true if the platform param exists in the given URL and if its value is the current's platform's name. * False otherwise. * * @param string $url * @return bool */ protected function isPlatformParamForThisPlatformInUrl($url) { $paramPrefix = $this->getSettings()->paramPrefix->getValue(); $queryString = parse_url($url, PHP_URL_QUERY); parse_str($queryString, $queryParams); return (is_array($queryParams) && array_key_exists($paramPrefix . '_platform', $queryParams) && $this->getName() === $queryParams[$paramPrefix . '_platform'] ); } /** * Returns true if the given referrer is an internal URL with the same host as the Piwik site. False otherwise. * * @param string $referrerUrl * @param int $idSite * @return bool */ protected function isReferrerAnInternalUrl($referrerUrl, $idSite) { // Site::getMainUrlFor($request->getIdSite()) does not work in tests $hostOfSiteUrl = parse_url( Db::fetchOne( 'SELECT main_url FROM ' . Common::prefixTable('site') . ' WHERE idsite = ?', [$idSite,] ), PHP_URL_HOST ); if (!$hostOfSiteUrl) { return false; } $hostOfSiteUrl = str_replace('www.', '', $hostOfSiteUrl); // TODO: Does this really cover all relevant URLs? $hostOfReferrer = parse_url($referrerUrl, PHP_URL_HOST); return ($hostOfReferrer && $hostOfSiteUrl && (false !== strpos($hostOfReferrer, $hostOfSiteUrl))); } }
lgpl-3.0
integry/integry-framework
renderer/PHPRenderer.php
1302
<?php ClassLoader::import('framework.renderer.Renderer'); /** * Renderer implementation based on raw PHP files ("PHP itself is a templating engine") * * @package framework.renderer * @author Integry Systems */ class PHPRenderer extends Renderer { protected $values = array(); public function __construct(Application $application) { $this->application = $application; } /** * Gets application instance * * @return Smarty */ public function getApplication() { return $this->application; } public function set($name, $value) { $this->values[$name] = $value; } public function appendValue($name, $value) { $this->values[$name] = $value; } public function setValueArray($array) { $this->values[$name] = $array; } public function setObject($name, $object) { $this->values[$name] = $object; } public function unsetValue($name) { unset($this->values[$name]); } public function unsetAll() { $this->values = array(); } public function render($view) { if (file_exists($view)) { ob_start(); extract($this->values); include $view; $contents = ob_get_contents(); ob_end_clean(); return $contents; } else { throw new ViewNotFoundException($view); } } public function getViewExtension() { return 'php'; } } ?>
lgpl-3.0
nightscape/JMathLib
src/jmathlib/toolbox/jmathlib/graphics/graph3d/meshz.java
397
package jmathlib.toolbox.jmathlib.graphics.graph3d; import jmathlib.core.tokens.*; import jmathlib.core.functions.ExternalFunction; import jmathlib.core.interpreter.GlobalValues; public class meshz extends ExternalFunction { public OperandToken evaluate(Token[] operands, GlobalValues globals) { throwMathLibException("meshz: not implemented yet"); return null; } }
lgpl-3.0
viffer/geowebcache-1.5.0
arcgiscache/src/main/java/org/geowebcache/arcgis/config/TileImageInfo.java
1061
package org.geowebcache.arcgis.config; /** * Represents a {@code TileImageInfo} element in an ArcGIS tile cache config file. * <p> * XML representation: * * <pre> * <code> * &lt;TileImageInfo xsi:type='typens:TileImageInfo'&gt; * &lt;CacheTileFormat&gt;JPEG&lt;/CacheTileFormat&gt; * &lt;CompressionQuality&gt;80&lt;/CompressionQuality&gt; * &lt;Antialiasing&gt;true&lt;/Antialiasing&gt; * &lt;/TileImageInfo&gt; * </code> * </pre> * * </p> * * @author Gabriel Roldan * */ public class TileImageInfo { private String cacheTileFormat; private float compressionQuality; private boolean antialiasing; /** * One of {@code PNG8, PNG24, PNG32, JPEG, Mixed} * <p> * {@code Mixed} uses mostly JPEG, but 32 on the borders of the cache * </p> */ public String getCacheTileFormat() { return cacheTileFormat; } public float getCompressionQuality() { return compressionQuality; } public boolean isAntialiasing() { return antialiasing; } }
lgpl-3.0
realn/TicTacToe
Game/Source/GUIMenuScreen.cpp
6190
#include "GUIMenuScreen.h" #include "GUITextButton.h" #include "GUIMain.h" #include "GUISelectableItem.h" namespace T3{ namespace GUI{ CMenuScreen::CMenuScreen(CMain& Main, const CB::CString& strTitle, const CB::Math::CVector2D& vSize, const uint32 uItemPerPage) : CScreen(Main, vSize), m_uItemsPerPage(uItemPerPage), m_vPercMargin(0.05f, 0.05f), m_vPercPardding(0.1f, 0.005f), m_fPercTitleSize(0.2f), m_uTransitionMode(TransitionMode::None), m_Linear(0.0f, 1.0f, 2.0f) { this->m_pTitleItem = new CTextItem( strTitle ); CScreen::AddItem(this->m_pTitleItem.Get()); this->RecalcItems(); } void CMenuScreen::Render(){ this->m_pParent->GetBackground().Render(CB::Math::CColor(0.0f, 0.0f, 0.0f, 0.5f)); CScreen::Render(); } void CMenuScreen::Update(const float fTD){ switch (this->m_uTransitionMode) { case TransitionMode::Show: this->m_Linear.Decrement( fTD ); if(this->m_Linear.IsMin()){ this->m_uTransitionMode = TransitionMode::None; } break; case TransitionMode::Hide: this->m_Linear.Increment(fTD); if(this->m_Linear.IsMax()){ this->m_uTransitionMode = TransitionMode::None; } break; default: CScreen::Update(fTD); break; } } void CMenuScreen::SetTitle(const CB::CString& strTitle){ this->m_pTitleItem->SetText(strTitle); } void CMenuScreen::AddMenuButton(const CB::CString& strName, CB::Signals::CFunc<>& Action){ CB::CRefPtr<CTextButton> pButton = new CTextButton(strName); pButton->OnClick += Action; if(CScreen::AddItem(pButton.Cast<GUI::IItem>())){ this->m_MenuItemList.Add(pButton.Cast<GUI::IItem>()); this->RecalcItems(); } } void CMenuScreen::RecalcItems(){ auto vMargin = this->m_vSize * this->m_vPercMargin; auto vPadding = this->m_vSize * this->m_vPercPardding; float32 fTitleSizeY = this->m_vSize.Y * this->m_fPercTitleSize; auto vTitlePos = CB::Math::CVector2D(vMargin.X, this->m_vSize.Y - vMargin.Y - fTitleSizeY); float32 fListTop = vTitlePos.Y - vMargin.Y; float32 fListSizeY = fListTop - vMargin.Y; float32 fMenuSizeX = this->m_vSize.X - vMargin.X * 2.0f; float32 fItemSizeY = fListSizeY / (float32)this->m_uItemsPerPage; CB::Math::CVector2D vPaddedItemSize = CB::Math::CVector2D(fMenuSizeX, fItemSizeY) - vPadding * 2.0f; { CB::Math::CRectangleF32 rect(vTitlePos, fMenuSizeX, fTitleSizeY); this->m_pTitleItem->SetRect( rect ); } for(uint32 uIndex = 0; uIndex < this->m_MenuItemList.GetLength(); uIndex++){ CB::Math::CVector2D vPos; vPos.X = vMargin.X + vPadding.X; vPos.Y = fListTop - (uIndex + 1) * fItemSizeY + vPadding.Y; CB::Math::CRectangleF32 rect(vPos, vPaddedItemSize); this->m_MenuItemList[uIndex]->SetRect(rect); } } void CMenuScreen::SetTransitionMode(const TransitionMode uMode){ this->m_uTransitionMode = uMode; switch (this->m_uTransitionMode) { case TransitionMode::Show: this->m_Linear.Fill(); break; case TransitionMode::Hide: this->m_Linear.Reset(); break; default: break; } } void CMenuScreen::ProcessEvent(const CEvent& Event){ if(this->m_uTransitionMode != TransitionMode::None) return; if(Event.Type == EventType::KeyPress){ using namespace CB::Window; switch (Event.Key) { case VirtualKey::UP: MoveUp(); break; case VirtualKey::DOWN: MoveDown(); break; default: break; } } CScreen::ProcessEvent(Event); } const TransitionMode CMenuScreen::GetTransitionMode() const{ return this->m_uTransitionMode; } const CB::Math::CMatrix CMenuScreen::GetTransform() const{ if(this->m_uTransitionMode == TransitionMode::None){ return CScreen::GetTransform(); } else{ auto mMove = CB::Math::CMatrix::GetTranslation(this->m_vSize.X * this->m_Linear.GetValue(), 0.0f, 0.0f); return CScreen::GetTransform() * mMove; } } void CMenuScreen::ClearSelection(){ for(uint32 i = 0; i < this->m_MenuItemList.GetLength(); i++){ auto pItem = dynamic_cast<ISelectableItem*>(this->m_MenuItemList[i].Get()); if(pItem != nullptr){ pItem->SetSelected(false); } } } const bool PredSelectable(const CB::CRefPtr<GUI::IItem>& Item){ auto pItem = dynamic_cast<ISelectableItem*>(const_cast<GUI::IItem*>(Item.Get())); return pItem != nullptr; } CB::CPtr<ISelectableItem> CMenuScreen::GetFirstSelectable(int32& uOutIndex) const{ CB::CRefPtr<GUI::IItem> pItem; uint32 uIndex = 0; if(CB::Collection::TrySearch(this->m_MenuItemList, PredSelectable, pItem, uIndex)){ uOutIndex = (int32)uIndex; return dynamic_cast<ISelectableItem*>(pItem.Get()); } uOutIndex = -1; return CB::CPtr<ISelectableItem>(); } CB::CPtr<ISelectableItem> CMenuScreen::GetLastSelectable(int32& uOutIndex) const{ CB::CRefPtr<GUI::IItem> pItem; uint32 uIndex = 0; if(CB::Collection::TrySearchLast(this->m_MenuItemList, PredSelectable, pItem, uIndex)){ uOutIndex = (int32)uIndex; return dynamic_cast<ISelectableItem*>(pItem.Get()); } uOutIndex = -1; return CB::CPtr<ISelectableItem>(); } void CMenuScreen::MoveUp(){ this->ClearSelection(); this->m_iCurItem--; if(this->m_iCurItem >= 0){ for(uint32 i = (int32)this->m_iCurItem + 1; i > 0; i--){ auto pItem = dynamic_cast<ISelectableItem*>(this->m_MenuItemList[i-1].Get()); if(pItem != nullptr) { this->m_iCurItem = i - 1; pItem->SetSelected(true); return; } } } auto pLastItem = this->GetLastSelectable(this->m_iCurItem); if(pLastItem.IsValid()){ pLastItem->SetSelected(true); } } void CMenuScreen::MoveDown(){ this->ClearSelection(); if(this->m_iCurItem >= 0){ for(uint32 i = (int32)this->m_iCurItem + 1; i < this->m_MenuItemList.GetLength(); i++){ auto pItem = dynamic_cast<ISelectableItem*>(this->m_MenuItemList[i].Get()); if(pItem != nullptr) { this->m_iCurItem = i; pItem->SetSelected(true); return; } } } auto pFirstItem = this->GetFirstSelectable(this->m_iCurItem); if(pFirstItem.IsValid()){ pFirstItem->SetSelected(true); } } } }
lgpl-3.0
integry/integry-framework-locale
I18Nv2/time/bn.php
1797
<?php $data = array ( 'AmPmMarkers' => array ( 0 => 'পূর্বাহ্ণ', 1 => 'অপরাহ্ণ', ), 'dayNames' => array ( 'format' => array ( 'abbreviated' => array ( 0 => 'রবি', 1 => 'সোম', 2 => 'মঙ্গল', 3 => 'বুধ', 4 => 'বৃহস্পতি', 5 => 'শুক্র', 6 => 'শনি', ), 'wide' => array ( 0 => 'রবিবার', 1 => 'সোমবার', 2 => 'মঙ্গলবার', 3 => 'বুধবার', 4 => 'বৃহষ্পতিবার', 5 => 'শুক্রবার', 6 => 'শনিবার', ), ), ), 'monthNames' => array ( 'format' => array ( 'abbreviated' => array ( 0 => 'জানুয়ারী', 1 => 'ফেব্রুয়ারী', 2 => 'মার্চ', 3 => 'এপ্রিল', 4 => 'মে', 5 => 'জুন', 6 => 'জুলাই', 7 => 'আগস্ট', 8 => 'সেপ্টেম্বর', 9 => 'অক্টোবর', 10 => 'নভেম্বর', 11 => 'ডিসেম্বর', ), 'wide' => array ( 0 => 'জানুয়ারী', 1 => 'ফেব্রুয়ারী', 2 => 'মার্চ', 3 => 'এপ্রিল', 4 => 'মে', 5 => 'জুন', 6 => 'জুলাই', 7 => 'আগস্ট', 8 => 'সেপ্টেম্বর', 9 => 'অক্টোবর', 10 => 'নভেম্বর', 11 => 'ডিসেম্বর', ), ), ), ); ?>
lgpl-3.0
WarpOrganization/warp
core/src/main/java/net/warpgame/engine/core/execution/Executor.java
172
package net.warpgame.engine.core.execution; /** * @author Jaca777 * Created 2017-09-23 at 16 */ public interface Executor { void scheduleOnce(Runnable runnable); }
lgpl-3.0
Siyy/HaoCodeBuilder
src/HaoCodeBuilder/HaoCodeBuilder.IData/ICreateCode.cs
1029
using System; namespace HaoCodeBuilder.IData { public interface ICreateCode { /// <summary> /// 得到数据层命名空间 /// </summary> /// <returns></returns> string GetDataNameSpace(); /// <summary> /// 得到参数名称 /// </summary> /// <returns></returns> string GetParamsName(string name); /// <summary> /// 得到参数名称1 /// </summary> /// <returns></returns> string GetParamsName1(string name); /// <summary> /// 得到参数类型 /// </summary> /// <returns></returns> string GetParamsType(); /// <summary> /// 得到DataReader类型 /// </summary> /// <returns></returns> string GetDataReaderType(); /// <summary> /// 查询自增ID的方法 /// </summary> /// <returns></returns> string GetIdentityMethod(); } }
lgpl-3.0
FEniCS/dolfin
dolfin/fem/LinearVariationalProblem.cpp
4455
// Copyright (C) 2011 Anders Logg // // This file is part of DOLFIN. // // DOLFIN is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>. #include <dolfin/function/Function.h> #include <dolfin/function/FunctionSpace.h> #include "Form.h" #include "DirichletBC.h" #include "LinearVariationalProblem.h" using namespace dolfin; //----------------------------------------------------------------------------- LinearVariationalProblem::LinearVariationalProblem( std::shared_ptr<const Form> a, std::shared_ptr<const Form> L, std::shared_ptr<Function> u, std::vector<std::shared_ptr<const DirichletBC>> bcs) : Hierarchical<LinearVariationalProblem>(*this), _a(a), _l(L), _u(u), _bcs(bcs) { // Check forms check_forms(); } //----------------------------------------------------------------------------- std::shared_ptr<const Form> LinearVariationalProblem::bilinear_form() const { return _a; } //----------------------------------------------------------------------------- std::shared_ptr<const Form> LinearVariationalProblem::linear_form() const { return _l; } //----------------------------------------------------------------------------- std::shared_ptr<Function> LinearVariationalProblem::solution() { return _u; } //----------------------------------------------------------------------------- std::shared_ptr<const Function> LinearVariationalProblem::solution() const { return _u; } //----------------------------------------------------------------------------- std::vector<std::shared_ptr<const DirichletBC>> LinearVariationalProblem::bcs() const { return _bcs; } //----------------------------------------------------------------------------- std::shared_ptr<const FunctionSpace> LinearVariationalProblem::trial_space() const { dolfin_assert(_u); return _u->function_space(); } //----------------------------------------------------------------------------- std::shared_ptr<const FunctionSpace> LinearVariationalProblem::test_space() const { dolfin_assert(_a); return _a->function_space(0); } //----------------------------------------------------------------------------- void LinearVariationalProblem::check_forms() const { // Check rank of bilinear form a dolfin_assert(_a); if (_a->rank() != 2) { dolfin_error("LinearVariationalProblem.cpp", "define linear variational problem a(u, v) == L(v) for all v", "Expecting the left-hand side to be a bilinear form (not rank %d)", _a->rank()); } // Check rank of linear form L dolfin_assert(_l); if (_l->rank() != 1) { dolfin_error("LinearVariationalProblem.cpp", "define linear variational problem a(u, v) = L(v) for all v", "Expecting the right-hand side to be a linear form (not rank %d)", _l->rank()); } // Check that function space of solution variable matches trial space dolfin_assert(_a); dolfin_assert(_u); const auto trial_space = _a->function_space(1); dolfin_assert(trial_space); if (!_u->in(*trial_space)) { dolfin_error("LinearVariationalProblem.cpp", "define linear variational problem a(u, v) = L(v) for all v", "Expecting the solution variable u to be a member of the trial space"); } // Check that function spaces of bcs are contained in trial space for (const auto bc: _bcs) { dolfin_assert(bc); const auto bc_space = bc->function_space(); dolfin_assert(bc_space); if (!trial_space->contains(*bc_space)) { dolfin_error("LinearVariationalProblem.cpp", "define linear variational problem a(u, v) = L(v) for all v", "Expecting the boundary conditions to to live on (a " "subspace of) the trial space"); } } } //-----------------------------------------------------------------------------
lgpl-3.0
agentsoz/bdi-abm-integration
examples/bushfire-old/src/main/java/io/github/agentsoz/bushfire/jill/goals/EvacHouse.java
1038
package io.github.agentsoz.bushfire.jill.goals; /* * #%L * BDI-ABM Integration Package * %% * Copyright (C) 2014 - 2016 by its authors. See AUTHORS file. * %% * 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 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import io.github.agentsoz.jill.lang.Goal; /** * * @author Sewwandi Perera * */ public class EvacHouse extends Goal { public EvacHouse(String str) { super(str); } }
lgpl-3.0
marceltschoppch/osa
setup.py
956
from setuptools import setup, find_packages import sys CLASSIFIERS = """\ Development Status :: 5 - Production/Stable Environment :: Console Environment :: Web Environment Intended Audience :: Developers Intended Audience :: End Users/Desktop License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+) Natural Language :: English Operating System :: OS Independent Programming Language :: Python Topic :: Internet Topic :: Internet :: WWW/HTTP Topic :: Software Development :: Libraries Topic :: Software Development :: Object Brokering""".split("\n") setup( name='osa', version='0.1.6.6', description='Python fast/slim/convenient SOAP/WSDL client.', author="Sergey A. Bozhenkov", author_email='ba-serge@yandex.ru', url="https://bitbucket.org/sboz/osa", download_url="https://bitbucket.org/sboz/osa/get/v0.1.6-p6.tar.gz", packages=["osa",], license="LGPLv3", classifiers=CLASSIFIERS, )
lgpl-3.0
MatthewBishop/Poseidon
src/info/jupiter/net/ISAACCipher.java
5271
package info.jupiter.net; /** * <p>An implementation of an ISAAC cipher. See * <a href="http://en.wikipedia.org/wiki/ISAAC_(cipher)"> * http://en.wikipedia.org/wiki/ISAAC_(cipher)</a> for more information.</p> * * <p>This implementation is based on the one written by Bob Jenkins, which is * available at <a href="http://www.burtleburtle.net/bob/java/rand/Rand.java"> * http://www.burtleburtle.net/bob/java/rand/Rand.java</a>.</p> * @author Graham Edgecombe * */ public class ISAACCipher { /** * The golden ratio. */ private static final int RATIO = 0x9e3779b9; /** * The log of the size of the results and memory arrays. */ private static final int SIZE_LOG = 8; /** * The size of the results and memory arrays. */ private static final int SIZE = 1 << SIZE_LOG; /** * For pseudorandom lookup. */ private static final int MASK = (SIZE - 1) << 2; /** * The count through the results. */ private int count = 0; /** * The results. */ private int results[] = new int[SIZE]; /** * The internal memory state. */ private int memory[] = new int[SIZE]; /** * The accumulator. */ private int a; /** * The last result. */ private int b; /** * The counter. */ private int c; /** * Creates the ISAAC cipher. * @param seed The seed. */ public ISAACCipher(int[] seed) { for(int i = 0; i < seed.length; i++) { results[i] = seed[i]; } init(true); } /** * Gets the next value. * @return The next value. */ public int getNextValue() { if(count-- == 0) { isaac(); count = SIZE - 1; } return results[count]; } /** * Generates 256 results. */ private void isaac() { int i, j, x, y; b += ++c; for(i = 0, j = SIZE / 2; i < SIZE / 2;) { x = memory[i]; a ^= a << 13; a += memory[j++]; memory[i] = y = memory[(x & MASK) >> 2] + a + b; results[i++] = b = memory[((y >> SIZE_LOG) & MASK) >> 2] + x; x = memory[i]; a ^= a >>> 6; a += memory[j++]; memory[i] = y = memory[(x & MASK) >> 2] + a + b; results[i++] = b = memory[((y >> SIZE_LOG) & MASK) >> 2] + x; x = memory[i]; a ^= a << 2; a += memory[j++]; memory[i] = y = memory[(x & MASK) >> 2] + a + b; results[i++] = b = memory[((y >> SIZE_LOG) & MASK) >> 2] + x; x = memory[i]; a ^= a >>> 16; a += memory[j++]; memory[i] = y = memory[(x & MASK) >> 2] + a + b; results[i++] = b = memory[((y >> SIZE_LOG) & MASK) >> 2] + x; } for(j = 0; j < SIZE / 2;) { x = memory[i]; a ^= a << 13; a += memory[j++]; memory[i] = y = memory[(x & MASK) >> 2] + a + b; results[i++] = b = memory[((y >> SIZE_LOG) & MASK) >> 2] + x; x = memory[i]; a ^= a >>> 6; a += memory[j++]; memory[i] = y = memory[(x & MASK) >> 2] + a + b; results[i++] = b = memory[((y >> SIZE_LOG) & MASK) >> 2] + x; x = memory[i]; a ^= a << 2; a += memory[j++]; memory[i] = y = memory[(x & MASK) >> 2] + a + b; results[i++] = b = memory[((y >> SIZE_LOG) & MASK) >> 2] + x; x = memory[i]; a ^= a >>> 16; a += memory[j++]; memory[i] = y = memory[(x & MASK) >> 2] + a + b; results[i++] = b = memory[((y >> SIZE_LOG) & MASK) >> 2] + x; } } /** * Initialises the ISAAC. * @param flag Flag indicating if we should perform a second pass. */ private void init(boolean flag) { int i; int a, b, c, d, e, f, g, h; a = b = c = d = e = f = g = h = RATIO; for(i = 0; i < 4; ++i) { a ^= b << 11; d += a; b += c; b ^= c >>> 2; e += b; c += d; c ^= d << 8; f += c; d += e; d ^= e >>> 16; g += d; e += f; e ^= f << 10; h += e; f += g; f ^= g >>> 4; a += f; g += h; g ^= h << 8; b += g; h += a; h ^= a >>> 9; c += h; a += b; } for(i = 0; i < SIZE; i += 8) { if(flag) { a += results[i]; b += results[i + 1]; c += results[i + 2]; d += results[i + 3]; e += results[i + 4]; f += results[i + 5]; g += results[i + 6]; h += results[i + 7]; } a ^= b << 11; d += a; b += c; b ^= c >>> 2; e += b; c += d; c ^= d << 8; f += c; d += e; d ^= e >>> 16; g += d; e += f; e ^= f << 10; h += e; f += g; f ^= g >>> 4; a += f; g += h; g ^= h << 8; b += g; h += a; h ^= a >>> 9; c += h; a += b; memory[i] = a; memory[i + 1] = b; memory[i + 2] = c; memory[i + 3] = d; memory[i + 4] = e; memory[i + 5] = f; memory[i + 6] = g; memory[i + 7] = h; } if(flag) { for(i = 0; i < SIZE; i += 8) { a += memory[i]; b += memory[i + 1]; c += memory[i + 2]; d += memory[i + 3]; e += memory[i + 4]; f += memory[i + 5]; g += memory[i + 6]; h += memory[i + 7]; a ^= b << 11; d += a; b += c; b ^= c >>> 2; e += b; c += d; c ^= d << 8; f += c; d += e; d ^= e >>> 16; g += d; e += f; e ^= f << 10; h += e; f += g; f ^= g >>> 4; a += f; g += h; g ^= h << 8; b += g; h += a; h ^= a >>> 9; c += h; a += b; memory[i] = a; memory[i + 1] = b; memory[i + 2] = c; memory[i + 3] = d; memory[i + 4] = e; memory[i + 5] = f; memory[i + 6] = g; memory[i + 7] = h; } } isaac(); count = SIZE; } }
lgpl-3.0
ecologylab/ecologylabFundamental
src/ecologylab/serialization/TranslationContext.java
7557
package ecologylab.serialization; import java.io.File; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import ecologylab.collections.MultiMap; import ecologylab.generic.Debug; import ecologylab.net.ParsedURL; import ecologylab.serialization.SimplTypesScope.GRAPH_SWITCH; /** * * @author nabeelshahzad * */ public class TranslationContext extends Debug implements ScalarUnmarshallingContext, FieldTypes { public static final String SIMPL_NAMESPACE = " xmlns:simpl=\"http://ecologylab.net/research/simplGuide/serialization/index.html\""; public static final String SIMPL = "simpl"; public static final String REF = "ref"; public static final String ID = "id"; public static final String SIMPL_ID = "simpl:id"; public static final String SIMPL_REF = "simpl:ref"; public static final String JSON_SIMPL_ID = "simpl.id"; public static final String JSON_SIMPL_REF = "simpl.ref"; private MultiMap<Integer, Object> marshalledObjects; private MultiMap<Integer, Object> visitedElements; private MultiMap<Integer, Object> needsAttributeHashCode; private HashMap<String, Object> unmarshalledObjects; protected ParsedURL baseDirPurl; protected File baseDirFile; protected String delimiter = ","; /** * */ public TranslationContext() { } /** * * @param fileDirContext */ public TranslationContext(File fileDirContext) { if (fileDirContext != null) setBaseDirFile(fileDirContext); } /** * * @param purlContext */ public TranslationContext(ParsedURL purlContext) { this.baseDirPurl = purlContext; if (purlContext.isFile()) this.baseDirFile = purlContext.file(); } /** * * @param fileDirContext */ public void setBaseDirFile(File fileDirContext) { this.baseDirFile = fileDirContext; this.baseDirPurl = new ParsedURL(fileDirContext); } public void initializeMultiMaps() { marshalledObjects = new MultiMap<Integer, Object>(); visitedElements = new MultiMap<Integer, Object>(); needsAttributeHashCode = new MultiMap<Integer, Object>(); unmarshalledObjects = new HashMap<String, Object>(); } /** * * @param value * @param elementState */ public void markAsUnmarshalled(String value, Object elementState) { if (unmarshalledObjects == null) initializeMultiMaps(); this.unmarshalledObjects.put(value, elementState); } public void resolveGraph(Object object) { if (visitedElements == null) initializeMultiMaps(); resolveGraphRecursvie(object); } /** * * @param elementState */ public void resolveGraphRecursvie(Object elementState) { if (SimplTypesScope.graphSwitch == GRAPH_SWITCH.ON) { // this.visitedElements.put(System.identityHashCode(elementState), elementState); this.visitedElements.put(elementState.hashCode(), elementState); ClassDescriptor.getClassDescriptor(elementState); ArrayList<? extends FieldDescriptor> elementFieldDescriptors = ClassDescriptor .getClassDescriptor(elementState).elementFieldDescriptors(); for (FieldDescriptor elementFieldDescriptor : elementFieldDescriptors) { Object thatReferenceObject = null; Field childField = elementFieldDescriptor.getField(); try { thatReferenceObject = childField.get(elementState); } catch (IllegalAccessException e) { debugA("WARNING re-trying access! " + e.getStackTrace()[0]); childField.setAccessible(true); try { thatReferenceObject = childField.get(elementState); } catch (IllegalAccessException e1) { error("Can't access " + childField.getName()); e1.printStackTrace(); } } catch (Exception e) { System.out.println(e); } // ignore null reference objects if (thatReferenceObject == null) continue; FieldType childFdType = elementFieldDescriptor.getType(); Collection thatCollection; switch (childFdType) { case COLLECTION_ELEMENT: case COLLECTION_SCALAR: case MAP_ELEMENT: case MAP_SCALAR: thatCollection = XMLTools.getCollection(thatReferenceObject); break; default: thatCollection = null; break; } if (thatCollection != null && (thatCollection.size() > 0)) { for (Object next : thatCollection) { if (next instanceof Object) { Object compositeElement = next; if (this.alreadyVisited(compositeElement)) { // this.needsAttributeHashCode.put(System.identityHashCode(compositeElement), // compositeElement); this.needsAttributeHashCode.put(compositeElement.hashCode(), compositeElement); } else { this.resolveGraph(compositeElement); } } } } else if (thatReferenceObject instanceof Object) { Object compositeElement = thatReferenceObject; if (this.alreadyVisited(compositeElement)) { // this.needsAttributeHashCode.put(System.identityHashCode(compositeElement), // compositeElement); this.needsAttributeHashCode.put(compositeElement.hashCode(), compositeElement); } else { resolveGraph(compositeElement); } } } } } /** * * @param elementState * @return */ public boolean alreadyVisited(Object elementState) { if (unmarshalledObjects == null) initializeMultiMaps(); return this.visitedElements.contains(elementState.hashCode(), elementState) != -1; } /** * * @param object */ public void mapObject(Object object) { if (SimplTypesScope.graphSwitch == GRAPH_SWITCH.ON) { if (object != null) this.marshalledObjects.put(object.hashCode(), object); } } /** * * @param compositeObject * @return */ public boolean alreadyMarshalled(Object compositeObject) { if (compositeObject == null) return false; return this.marshalledObjects.contains(compositeObject.hashCode(), compositeObject) != -1; } /** * * @param elementState * @return */ public boolean needsHashCode(Object elementState) { return this.needsAttributeHashCode.contains(elementState.hashCode(), elementState) != -1; } /** * * @return */ public boolean isGraph() { return this.needsAttributeHashCode.size() > 0; } /** * * @param value * @return */ public Object getFromMap(String value) { return this.unmarshalledObjects.get(value); } /** * */ @Override public ParsedURL purlContext() { return (baseDirPurl != null) ? baseDirPurl : (baseDirFile != null) ? new ParsedURL(baseDirFile) : null; } public String getSimplId(Object object) { Integer objectHashCode = object.hashCode(); Integer orderedIndex = marshalledObjects.contains(objectHashCode, object); if (orderedIndex > 0) return objectHashCode.toString() + "," + orderedIndex.toString(); else return objectHashCode.toString(); } /** * */ @Override public File fileContext() { return (baseDirFile != null) ? baseDirFile : (baseDirPurl != null) ? baseDirPurl.file() : null; } /** * * @return */ public String getDelimiter() { return delimiter; } void clean() { if (marshalledObjects != null) marshalledObjects.clear(); if (visitedElements != null) visitedElements.clear(); if (needsAttributeHashCode != null) needsAttributeHashCode.clear(); if (needsAttributeHashCode != null) unmarshalledObjects.clear(); baseDirPurl = null; baseDirFile = null; delimiter = ","; } }
lgpl-3.0
cncyan/digitalshop
digitalshop/registe.php
2587
<!doctype html> <html> <head> <meta charset="utf-8"> <title>注册</title> <link type="text/css" rel="stylesheet" href="css/reset.css"> <link type="text/css" rel="stylesheet" href="css/main.css"> <!--[if IE 6]> <script type="text/javascript" src="js/DD_belatedPNG_0.0.8a-min.js"></script> <script type="text/javascript" src="js/ie6Fixpng.js"></script> <![endif]--> </head> <body> <div class="headerBar"> <div class="logoBar red_logo"> <div class="comWidth"> <div class="logo fl"> <a href="#"><img src="img/logo.jpg" alt="慕课网"></a> </div> <h3 class="welcome_title">欢迎注册</h3> </div> </div> </div> <div class="regBox"> <div class="login_cont"> <form method="post" action="doaction.php?act=reg" enctype="multipart/form-data"> <ul class="login"> <li><span class="reg_item"><i>*</i>账户名:</span><div class="input_item"> <input type="text" name="username" placeholder="请输入用户名" class="login_input user_icon"></div></li> <li><span class="reg_item"><i>*</i>密码:</span><div class="input_item"> <input type="password" name="password" class="login_input user_icon"></div></li> <li><span class="reg_item"><i>*</i>邮箱:</span><div class="input_item"> <input type="email" class="login_input user_icon"></div></li> <li><span class="reg_item"><i>*</i>性别:</span><div class="input_item"> <input type="radio" name="sex" value="0" checked="checked" >boy <input type="radio" name="sex" value="1" >girl <input type="radio" name="sex" value="2" >serect </div></li> <li><span class="reg_item"><i>*</i>邮箱:</span><div class="input_item"> <input type="file" name="myface"></div></li> <li><span class="reg_item">&nbsp;</span><input type="submit" value="" class="login_btn"></li> </ul> </form> </div> </div> <div class="hr_25"></div> <div class="footer"> <p><a href="#">慕课简介</a><i>|</i><a href="#">慕课公告</a><i>|</i> <a href="#">招纳贤士</a><i>|</i><a href="#">联系我们</a><i>|</i>客服热线:400-675-1234</p> <p>Copyright &copy; 2006 - 2014 慕课版权所有&nbsp;&nbsp;&nbsp;京ICP备09037834号&nbsp;&nbsp;&nbsp;京ICP证B1034-8373号&nbsp;&nbsp;&nbsp;某市公安局XX分局备案编号:123456789123</p> <p class="web"><a href="#"><img src="img/webLogo.jpg" alt="logo"></a><a href="#"><img src="img/webLogo.jpg" alt="logo"></a><a href="#"><img src="img/webLogo.jpg" alt="logo"></a><a href="#"><img src="img/webLogo.jpg" alt="logo"></a></p> </div> </body> </html>
lgpl-3.0
integer-net/solr-base
src/Solr/Request/ApplicationContext.php
5730
<?php /** * integer_net Magento Module * * @category IntegerNet * @package IntegerNet_Solr * @copyright Copyright (c) 2015 integer_net GmbH (http://www.integer-net.de/) * @author Fabian Schmengler <fs@integer-net.de> */ namespace IntegerNet\Solr\Request; use IntegerNet\Solr\Config\AutosuggestConfig; use IntegerNet\Solr\Config\FuzzyConfig; use IntegerNet\Solr\Config\ResultsConfig; use IntegerNet\Solr\Config\CategoryConfig; use IntegerNet\Solr\Config\CmsConfig; use IntegerNet\Solr\Implementor\AttributeRepository; use IntegerNet\Solr\Implementor\EventDispatcher; use IntegerNet\Solr\Implementor\Pagination; use IntegerNet\Solr\Implementor\HasUserQuery; use Psr\Log\LoggerInterface; use UnexpectedValueException; /** * Holds application context (bridge objects) for RequestFactory * * @package IntegerNet\Solr\Factory */ final class ApplicationContext { /** * @var $attributeRepository AttributeRepository */ private $attributeRepository; /** * @var $resultsConfig ResultsConfig */ private $resultsConfig; /** * @var $fuzzyConfig FuzzyConfig */ private $fuzzyConfig; /** * @var $autosuggestConfig AutosuggestConfig */ private $autosuggestConfig; /** * @var $categoryConfig CategoryConfig */ private $categoryConfig; /** * @var $cmsConfig CmsConfig */ private $cmsConfig; /** * @var $pagination Pagination */ private $pagination; /** * @var $query HasUserQuery */ private $query; /** * @var $eventDispatcher EventDispatcher */ private $eventDispatcher; /** * @var $logger LoggerInterface */ private $logger; /** * @param AttributeRepository $attributeRepository * @param ResultsConfig $resultsConfig * @param AutosuggestConfig $autosuggestConfig * @param EventDispatcher $eventDispatcher * @param LoggerInterface $logger */ public function __construct(AttributeRepository $attributeRepository, ResultsConfig $resultsConfig, AutosuggestConfig $autosuggestConfig, EventDispatcher $eventDispatcher, LoggerInterface $logger) { $this->attributeRepository = $attributeRepository; $this->resultsConfig = $resultsConfig; $this->autosuggestConfig = $autosuggestConfig; $this->eventDispatcher = $eventDispatcher; $this->logger = $logger; } /** * @param FuzzyConfig $fuzzyConfig * @return ApplicationContext */ public function setFuzzyConfig($fuzzyConfig) { $this->fuzzyConfig = $fuzzyConfig; return $this; } /** * @param CategoryConfig $categoryConfig * @return ApplicationContext */ public function setCategoryConfig($categoryConfig) { $this->categoryConfig = $categoryConfig; return $this; } /** * @param CmsConfig $cmsConfig * @return ApplicationContext */ public function setCmsConfig($cmsConfig) { $this->cmsConfig = $cmsConfig; return $this; } /** * @param Pagination $pagination * @return ApplicationContext */ public function setPagination($pagination) { $this->pagination = $pagination; return $this; } /** * @param HasUserQuery $query * @return ApplicationContext */ public function setQuery($query) { $this->query = $query; return $this; } /** * @return AttributeRepository */ public function getAttributeRepository() { return $this->attributeRepository; } /** * @return ResultsConfig */ public function getResultsConfig() { return $this->resultsConfig; } /** * @return FuzzyConfig */ public function getFuzzyConfig() { if ($this->fuzzyConfig === null) { throw new UnexpectedValueException('ApplicationContext::$fuzzyConfig is not initialized.'); } return $this->fuzzyConfig; } /** * @return CategoryConfig */ public function getCategoryConfig() { if ($this->categoryConfig === null) { throw new UnexpectedValueException('ApplicationContext::$categoryConfig is not initialized.'); } return $this->categoryConfig; } /** * @return CmsConfig */ public function getCmsConfig() { if ($this->cmsConfig === null) { throw new UnexpectedValueException('ApplicationContext::$cmsConfig is not initialized.'); } return $this->cmsConfig; } /** * @return AutosuggestConfig */ public function getAutosuggestConfig() { return $this->autosuggestConfig; } /** * @return bool */ public function hasPagination() { return $this->pagination !== null; } /** * @return Pagination */ public function getPagination() { if ($this->pagination === null) { throw new UnexpectedValueException('ApplicationContext::$pagination is not initialized.'); } return $this->pagination; } /** * @return HasUserQuery */ public function getQuery() { if ($this->query === null) { throw new UnexpectedValueException('ApplicationContext::$query is not initialized.'); } return $this->query; } /** * @return EventDispatcher */ public function getEventDispatcher() { return $this->eventDispatcher; } /** * @return LoggerInterface */ public function getLogger() { return $this->logger; } }
lgpl-3.0
SonarSource/sonarqube
server/sonar-web/src/main/js/apps/quality-profiles/components/ProfileLink.tsx
1308
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import * as React from 'react'; import { Link } from 'react-router'; import { getProfilePath } from '../utils'; interface Props { className?: string; children?: React.ReactElement<any> | string; language: string; name: string; } export default function ProfileLink({ name, language, children, ...other }: Props) { return ( <Link activeClassName="link-no-underline" to={getProfilePath(name, language)} {...other}> {children} </Link> ); }
lgpl-3.0
nmalservet/ebiose
ebiose/protected/views/fichier/admin.php
1316
<?php /* @var $this FichierController */ /* @var $model Fichier */ $this->breadcrumbs=array( 'Fichiers'=>array('index'), 'Manage', ); $this->menu=array( array('label'=>'List Fichier', 'url'=>array('index')), array('label'=>'Create Fichier', 'url'=>array('create')), ); Yii::app()->clientScript->registerScript('search', " $('.search-button').click(function(){ $('.search-form').toggle(); return false; }); $('.search-form form').submit(function(){ $.fn.yiiGridView.update('fichier-grid', { data: $(this).serialize() }); return false; }); "); ?> <h1>Manage Fichiers</h1> <p> You may optionally enter a comparison operator (<b>&lt;</b>, <b>&lt;=</b>, <b>&gt;</b>, <b>&gt;=</b>, <b>&lt;&gt;</b> or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done. </p> <?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?> <div class="search-form" style="display:none"> <?php $this->renderPartial('_search',array( 'model'=>$model, )); ?> </div><!-- search-form --> <?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'fichier-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'columns'=>array( 'id', 'nom', 'description', 'suffixe', 'dossier_id', array( 'class'=>'CButtonColumn', ), ), )); ?>
lgpl-3.0
kristianmandrup/log4r-color
lib/log4r-color.rb
519
# :include: log4r-color/rdoc/log4r # # == Other Info # # Author:: Leon Torres # Version:: $Id$ require "log4r-color/outputter/fileoutputter" require "log4r-color/outputter/consoleoutputters" require "log4r-color/outputter/staticoutputter" require "log4r-color/outputter/rollingfileoutputter" require "log4r-color/formatter/patternformatter" require "log4r-color/loggerfactory" require "log4r-color/GDC" require "log4r-color/NDC" require "log4r-color/MDC" module Log4r Log4rVersion = [1, 1, 9].join '.' end
lgpl-3.0
kidaa/Awakening-Core3
bin/scripts/object/tangible/deed/pet_deed/deed_surgical_basic.lua
4050
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --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 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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser 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 --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_deed_pet_deed_deed_surgical_basic = object_tangible_deed_pet_deed_shared_deed_surgical_basic:new { templateType = DROIDDEED, controlDeviceObjectTemplate = "object/intangible/pet/21b_surgical_droid.iff", generatedObjectTemplate = "object/creature/npc/droid/crafted/2_1b_surgical_droid.iff", mobileTemplate = "surgical_droid_21b_crafted", numberExperimentalProperties = {1, 1, 3, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, experimentalProperties = {"XX", "XX", "OQ", "SR", "UT", "XX", "XX", "OQ", "SR", "UT", "OQ", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX"}, experimentalWeights = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, experimentalGroupTitles = {"null", "null", "exp_durability", "null", "null", "exp_quality", "exp_effectiveness", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"}, experimentalSubGroupTitles = {"null", "null", "decayrate", "armor_toughness", "armorencumbrance", "mechanism_quality", "power_level", "storage_module", "data_module", "personality_module", "medical_module", "crafting_module", "repair_module", "armor_module", "armoreffectiveness", "playback_module", "struct_module", "harvest_power", "trap_bonus", "merchant_barker", "bomb_level", "stimpack_capacity", "stimpack_speed", "auto_repair_power", "entertainer_effects"}, experimentalMin = {0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, experimentalMax = {0, 0, 15, 0, 0, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, experimentalPrecision = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, experimentalCombineType = {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, } ObjectTemplates:addTemplate(object_tangible_deed_pet_deed_deed_surgical_basic, "object/tangible/deed/pet_deed/deed_surgical_basic.iff")
lgpl-3.0
philiplaureano/LinFu
src/LinFu.IoC/Configuration/Injectors/AttributedPropertyInjectionFilter.cs
3964
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using LinFu.IoC.Configuration.Interfaces; using LinFu.IoC.Interfaces; namespace LinFu.IoC.Configuration { /// <summary> /// A default implementation of the <see cref="IMemberInjectionFilter{TMember}" /> /// class that returns properties which have the <see cref="InjectAttribute" /> /// defined. /// </summary> [Implements(typeof(IMemberInjectionFilter<PropertyInfo>), LifecycleType.OncePerRequest)] public class AttributedPropertyInjectionFilter : BaseMemberInjectionFilter<PropertyInfo> { private readonly Type _attributeType; /// <summary> /// Initializes the class and uses the <see cref="InjectAttribute" /> /// to specify which properties should be automatically injected with /// services from the container. /// </summary> public AttributedPropertyInjectionFilter() { _attributeType = typeof(InjectAttribute); } /// <summary> /// Initializes the class and uses the <paramref name="attributeType" /> /// to specify which properties should be automatically injected with /// services from the container. /// </summary> /// <param name="attributeType">The custom property attribute that will be used to mark properties for automatic injection.</param> public AttributedPropertyInjectionFilter(Type attributeType) { _attributeType = attributeType; } /// <summary> /// Determines which properties should be injected from the <see cref="IServiceContainer" /> instance. /// </summary> /// <param name="container">The source container that will supply the property values for the selected properties.</param> /// <param name="properties">The list of properties to be filtered.</param> /// <returns>A list of properties that should be injected.</returns> protected override IEnumerable<PropertyInfo> Filter(IServiceContainer container, IEnumerable<PropertyInfo> properties) { // The property must have the custom attribute defined var results = from p in properties let propertyType = p.PropertyType let attributes = p.GetCustomAttributes(_attributeType, false) where attributes != null && attributes.Length > 0 select p; return results; } /// <summary> /// Determines which members should be selected from the <paramref name="targetType" /> /// using the <paramref name="container" /> /// </summary> /// <param name="targetType">The target type that will supply the list of members that will be filtered.</param> /// <param name="container">The target container.</param> /// <returns>A list of <see cref="PropertyInfo" /> objects that pass the filter description.</returns> protected override IEnumerable<PropertyInfo> GetMembers(Type targetType, IServiceContainer container) { IEnumerable<PropertyInfo> results; try { var items = from p in targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance) let propertyType = p == null ? typeof(void) : p.PropertyType let isServiceArray = propertyType != null ? propertyType.ExistsAsServiceArray() : ioc => false let isCompatible = isServiceArray(container) || container.Contains(propertyType) where p != null && p.CanWrite && isCompatible select p; results = items; } catch (Exception ex) { throw ex; } return results; } } }
lgpl-3.0
jjettenn/molgenis
molgenis-data/src/main/java/org/molgenis/data/support/EntityTypeUtils.java
7746
package org.molgenis.data.support; import org.molgenis.data.Fetch; import org.molgenis.data.meta.AttributeType; import org.molgenis.data.meta.model.Attribute; import org.molgenis.data.meta.model.EntityType; import org.molgenis.data.meta.model.Package; import org.molgenis.util.EntityUtils; import static java.lang.String.format; import static java.util.stream.StreamSupport.stream; import static org.molgenis.data.meta.model.Package.PACKAGE_SEPARATOR; public class EntityTypeUtils { private EntityTypeUtils() { } /** * Returns whether the attribute type references single entities (e.g. is 'XREF'). * * @param attr attribute * @return true if an attribute references a single entity */ public static boolean isSingleReferenceType(Attribute attr) { AttributeType attrType = attr.getDataType(); switch (attrType) { case CATEGORICAL: case FILE: case XREF: return true; case BOOL: case CATEGORICAL_MREF: case COMPOUND: case DATE: case DATE_TIME: case DECIMAL: case EMAIL: case ENUM: case HTML: case HYPERLINK: case INT: case LONG: case MREF: case ONE_TO_MANY: case SCRIPT: case STRING: case TEXT: return false; default: throw new RuntimeException(format("Unknown attribute type [%s]", attrType.toString())); } } /** * Returns whether the attribute type references multiple entities (e.g. is 'MREF'). * * @param attr attribute * @return true if an attribute references multiple entities */ public static boolean isMultipleReferenceType(Attribute attr) { AttributeType attrType = attr.getDataType(); switch (attrType) { case CATEGORICAL_MREF: case MREF: case ONE_TO_MANY: return true; case BOOL: case CATEGORICAL: case COMPOUND: case DATE: case DATE_TIME: case DECIMAL: case EMAIL: case ENUM: case FILE: case HTML: case HYPERLINK: case INT: case LONG: case SCRIPT: case STRING: case TEXT: case XREF: return false; default: throw new RuntimeException(format("Unknown attribute type [%s]", attrType.toString())); } } /** * Returns whether the attribute references other entities (e.g. is 'XREF' or 'MREF'). * * @param attr attribute * @return true if the attribute references other entities */ public static boolean isReferenceType(Attribute attr) { return isReferenceType(attr.getDataType()); } /** * Returns whether the attribute type references other entities (e.g. is 'XREF' or 'MREF'). * * @param attrType attribute type * @return true if the attribute type references other entities */ public static boolean isReferenceType(AttributeType attrType) { switch (attrType) { case CATEGORICAL: case CATEGORICAL_MREF: case FILE: case MREF: case ONE_TO_MANY: case XREF: return true; case BOOL: case COMPOUND: case DATE: case DATE_TIME: case DECIMAL: case EMAIL: case ENUM: case HTML: case HYPERLINK: case INT: case LONG: case SCRIPT: case STRING: case TEXT: return false; default: throw new RuntimeException(format("Unknown attribute type [%s]", attrType.toString())); } } /** * Returns whether the attribute type is a string type. * * @param attr attribute * @return true if the attribute is a string type. */ public static boolean isStringType(Attribute attr) { AttributeType attrType = attr.getDataType(); switch (attrType) { case EMAIL: case HYPERLINK: case STRING: return true; case ONE_TO_MANY: case BOOL: case CATEGORICAL: case CATEGORICAL_MREF: case COMPOUND: case DATE: case DATE_TIME: case DECIMAL: case ENUM: case FILE: case HTML: // text type is not a string type case INT: case LONG: case MREF: case SCRIPT: // text type is not a string type case TEXT: // text type is not a string type case XREF: return false; default: throw new RuntimeException(format("Unknown attribute type [%s]", attrType.toString())); } } /** * Returns whether the attribute type is a text type. * * @param attr attribute * @return true if the attribute is a text type. */ public static boolean isTextType(Attribute attr) { AttributeType attrType = attr.getDataType(); switch (attrType) { case HTML: case SCRIPT: case TEXT: return true; case BOOL: case CATEGORICAL: case CATEGORICAL_MREF: case ONE_TO_MANY: case COMPOUND: case DATE: case DATE_TIME: case DECIMAL: case EMAIL: case ENUM: case FILE: case HYPERLINK: case INT: case LONG: case MREF: case STRING: case XREF: return false; default: throw new RuntimeException(format("Unknown attribute type [%s]", attrType.toString())); } } /** * Returns whether the attribute is an integer type. * * @param attrType attribute type * @return true if the attribute is an integer type. */ public static boolean isIntegerType(AttributeType attrType) { switch (attrType) { case INT: case LONG: return true; case HTML: case SCRIPT: case TEXT: case BOOL: case CATEGORICAL: case CATEGORICAL_MREF: case COMPOUND: case ONE_TO_MANY: case DATE: case DATE_TIME: case DECIMAL: case EMAIL: case ENUM: case FILE: case HYPERLINK: case MREF: case STRING: case XREF: return false; default: throw new RuntimeException(format("Unknown attribute type [%s]", attrType.toString())); } } /** * Returns whether the attribute is a date type. * * @param attrType attribute type * @return true if the attribute is a date type. */ public static boolean isDateType(AttributeType attrType) { switch (attrType) { case DATE: case DATE_TIME: return true; case LONG: case INT: case HTML: case SCRIPT: case TEXT: case BOOL: case CATEGORICAL: case CATEGORICAL_MREF: case COMPOUND: case ONE_TO_MANY: case DECIMAL: case EMAIL: case ENUM: case FILE: case HYPERLINK: case MREF: case STRING: case XREF: return false; default: throw new RuntimeException(format("Unknown attribute type [%s]", attrType.toString())); } } /** * Returns attribute names for the given attributes * * @return attribute names */ public static Iterable<String> getAttributeNames(Iterable<Attribute> attrs) { return () -> stream(attrs.spliterator(), false).map(Attribute::getName).iterator(); } /** * Builds and returns an entity full name based on a package and a simpleName * * @param package_ * @param simpleName * @return String entity full name */ public static String buildFullName(Package package_, String simpleName) { if (package_ != null) { StringBuilder sb = new StringBuilder(); sb.append(package_.getName()); sb.append(PACKAGE_SEPARATOR); sb.append(simpleName); return sb.toString(); } else { return simpleName; } } public static Fetch createFetchForReindexing(EntityType refEntityType) { Fetch fetch = new Fetch(); for (Attribute attr : refEntityType.getAtomicAttributes()) { if (attr.getRefEntity() != null) { Fetch attributeFetch = new Fetch(); for (Attribute refAttr : attr.getRefEntity().getAtomicAttributes()) { attributeFetch.field(refAttr.getName()); } fetch.field(attr.getName(), attributeFetch); } else { fetch.field(attr.getName()); } } return fetch; } public static boolean hasSelfReferences(EntityType entityType) { for (Attribute attr : entityType.getAtomicAttributes()) { if (attr.getRefEntity() != null) { if (EntityUtils.equals(attr.getRefEntity(), entityType)) { return true; } } } return false; } }
lgpl-3.0
yesan/Spacebuilder
Common/ViewModels/SimpleHomeEditModel.cs
1559
//------------------------------------------------------------------------------ // <copyright company="Tunynet"> // Copyright (c) Tunynet Inc. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel.DataAnnotations; namespace Spacebuilder.Common { public class SimpleHomeEditModel : LoginEditModel { /// <summary> /// 是否属于模式窗口登录 /// </summary> public bool loginInModal { get; set; } /// <summary> /// 回跳网页 /// </summary> public string ReturnUrl { get; set; } /// <summary> /// 密码 /// </summary> [Required(ErrorMessage = "请输入密码")] public string Password { get; set; } /// <summary> /// 用户名 /// </summary> [Required(ErrorMessage = "请输入帐号或邮箱")] [DataType(DataType.Text)] public string UserName { get; set; } /// <summary> /// 是否记得密码 /// </summary> public bool RememberPassword { get; set; } /// <summary> /// 将EditModel转换成User /// </summary> /// <returns></returns> public User AsUser() { User user = User.New(); user.UserName = UserName; user.Password = Password; return user; } } }
lgpl-3.0
viffer/geowebcache-1.5.0
core/src/main/java/org/geowebcache/storage/TileRangeIterator.java
5517
/** * 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 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 Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @author Arne OpenGeo 2010 */ package org.geowebcache.storage; import java.util.concurrent.atomic.AtomicLong; public class TileRangeIterator { final private TileRange tr; final private DiscontinuousTileRange dtr; final private int metaX; final private int metaY; private AtomicLong tilesSkippedCount = new AtomicLong(); private AtomicLong tilesRenderedCount = new AtomicLong(); private volatile long[] lastGridLoc; /** * Note that the bounds of the tile range must already be expanded to the meta tile factors for * this to work. * * @param tr * @param metaTilingFactors */ public TileRangeIterator(TileRange tr, int[] metaTilingFactors) { this.tr = tr; this.metaX = metaTilingFactors[0]; this.metaY = metaTilingFactors[1]; if (tr instanceof DiscontinuousTileRange) { dtr = (DiscontinuousTileRange) tr; } else { dtr = null; } } /** * Returns the underlying tile range * * @return */ public TileRange getTileRange() { return tr; } /** * This loops over all the possible metatile locations and returns a tile location within each * metatile. * * If the TileRange object provided is a DiscontinuousTileRange implementation, each location is * checked against the filter of that class. * * @param gridLoc as an optimization, re-use the previous gridLoc. It will be changed and used * as the return value. The values passed in will not impact the result. For the first call, * use a new 3 element array. * * @return {@code null} if there're no more tiles to return, the next grid location in the * iterator otherwise. The array has three elements: {x,y,z} */ public synchronized long[] nextMetaGridLocation(final long[] gridLoc) { long[] levelBounds; long x; long y; int z; // Figure out the starting point if (lastGridLoc == null) { z = tr.getZoomStart(); levelBounds = tr.rangeBounds(z); x = levelBounds[0]; y = levelBounds[1]; } else { z = (int) lastGridLoc[2]; levelBounds = tr.rangeBounds(z); x = lastGridLoc[0] + metaX; y = lastGridLoc[1]; } // Loop over any remaining zoom levels for (; z <= tr.getZoomStop(); z++) { for (; y <= levelBounds[3]; y += metaY) { for (; x <= levelBounds[2]; x += metaX) { gridLoc[0] = x; gridLoc[1] = y; gridLoc[2] = z; int tileCount = tilesForLocation(gridLoc, levelBounds); if (checkGridLocation(gridLoc)) { tilesRenderedCount.addAndGet(tileCount); lastGridLoc = gridLoc.clone(); return gridLoc; } tilesSkippedCount.addAndGet(tileCount); } x = levelBounds[0]; } // Get ready for the next level if (z < tr.getZoomStop()) {// but be careful not to go out of index levelBounds = tr.rangeBounds(z + 1); x = levelBounds[0]; y = levelBounds[1]; } } return null; } /** * Calculates the number of tiles covered by the meta tile for this grid location. * * @param gridLoc * @param levelBounds * @return */ private int tilesForLocation(long x, long y, long[] levelBounds) { long boundsMaxX = levelBounds[2]; long boundsMaxY = levelBounds[3]; return (int) Math.min(metaX, 1 + (boundsMaxX - x)) * (int) Math.min(metaY, 1 + (boundsMaxY - y)); } private int tilesForLocation(long[] gridLoc, long[] levelBounds) { return tilesForLocation(gridLoc[0], gridLoc[1], levelBounds); } /** * Checks whether this grid location, or any on the same meta tile, should be included according * to the DiscontinuousTileRange * * @param gridLoc * @return */ private boolean checkGridLocation(long[] gridLoc) { if (dtr == null) { return true; } else { long[] subIdx = new long[3]; subIdx[2] = gridLoc[2]; for (int i = 0; i < this.metaX; i++) { for (int j = 0; j < this.metaY; j++) { subIdx[0] = gridLoc[0] + i; subIdx[1] = gridLoc[1] + j; if (dtr.contains(subIdx)) { return true; } } } } return false; } }
lgpl-3.0
open-io/oio-api-java
src/main/java/io/openio/sds/exceptions/ReferenceNotFoundException.java
318
package io.openio.sds.exceptions; /** * * @author Christopher Dedeurwaerder * */ public class ReferenceNotFoundException extends OioException { /** * */ private static final long serialVersionUID = 1L; public ReferenceNotFoundException(String message) { super(message); } }
lgpl-3.0