code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/******************************************************************************* * This file is part of Minebot. * * Minebot 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. * * Minebot 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 Minebot. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package net.famzangl.minecraft.minebot.build.block; import net.famzangl.minecraft.minebot.ai.BlockItemFilter; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; /** * A filter that filters for half slabs. * * @author michael * */ public class SlabFilter extends BlockItemFilter { private final SlabType type; public SlabFilter(SlabType type) { super(type.slabBlock); this.type = type; } @Override protected boolean matchesItem(ItemStack itemStack, ItemBlock item) { return super.matchesItem(itemStack, item) && (itemStack.getItemDamage() & 7) == type.meta; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (type == null ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } final SlabFilter other = (SlabFilter) obj; if (type != other.type) { return false; } return true; } @Override public String getDescription() { return type.toString().toLowerCase() + " slabs"; } }
iAmRinzler/minebot
Minebot/src/net/famzangl/minecraft/minebot/build/block/SlabFilter.java
Java
gpl-3.0
2,030
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sshd.agent.unix; import java.io.IOException; import java.io.InterruptedIOException; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.sshd.agent.common.AbstractAgentProxy; import org.apache.sshd.common.SshException; import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.common.util.threads.ThreadUtils; import org.apache.tomcat.jni.Local; import org.apache.tomcat.jni.Pool; import org.apache.tomcat.jni.Socket; import org.apache.tomcat.jni.Status; /** * A client for a remote SSH agent */ public class AgentClient extends AbstractAgentProxy implements Runnable { private final String authSocket; private final long pool; private final long handle; private final Buffer receiveBuffer; private final Queue<Buffer> messages; private Future<?> pumper; private final AtomicBoolean open = new AtomicBoolean(true); public AgentClient(String authSocket) throws IOException { this(authSocket, null, false); } public AgentClient(String authSocket, ExecutorService executor, boolean shutdownOnExit) throws IOException { this.authSocket = authSocket; setExecutorService((executor == null) ? ThreadUtils.newSingleThreadExecutor("AgentClient[" + authSocket + "]") : executor); setShutdownOnExit((executor == null) ? true : shutdownOnExit); try { pool = Pool.create(AprLibrary.getInstance().getRootPool()); handle = Local.create(authSocket, pool); int result = Local.connect(handle, 0); if (result != Status.APR_SUCCESS) { throwException(result); } receiveBuffer = new ByteArrayBuffer(); messages = new ArrayBlockingQueue<Buffer>(10); ExecutorService service = getExecutorService(); pumper = service.submit(this); } catch (IOException e) { throw e; } catch (Exception e) { throw new SshException(e); } } @Override public boolean isOpen() { return open.get(); } @Override public void run() { try { byte[] buf = new byte[1024]; while (isOpen()) { int result = Socket.recv(handle, buf, 0, buf.length); if (result < Status.APR_SUCCESS) { throwException(result); } messageReceived(new ByteArrayBuffer(buf, 0, result)); } } catch (Exception e) { if (isOpen()) { log.warn(e.getClass().getSimpleName() + " while still open: " + e.getMessage()); } else { if (log.isDebugEnabled()) { log.debug("Closed client loop exception", e); } } } finally { try { close(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(e.getClass().getSimpleName() + " while closing: " + e.getMessage()); } } } } protected void messageReceived(Buffer buffer) throws Exception { Buffer message = null; synchronized (receiveBuffer) { receiveBuffer.putBuffer(buffer); if (receiveBuffer.available() >= 4) { int rpos = receiveBuffer.rpos(); int len = receiveBuffer.getInt(); receiveBuffer.rpos(rpos); if (receiveBuffer.available() >= 4 + len) { message = new ByteArrayBuffer(receiveBuffer.getBytes()); receiveBuffer.compact(); } } } if (message != null) { synchronized (messages) { messages.offer(message); messages.notifyAll(); } } } @Override public void close() throws IOException { if (open.getAndSet(false)) { Socket.close(handle); } if ((pumper != null) && isShutdownOnExit() && (!pumper.isDone())) { pumper.cancel(true); } super.close(); } @Override protected synchronized Buffer request(Buffer buffer) throws IOException { int wpos = buffer.wpos(); buffer.wpos(0); buffer.putInt(wpos - 4); buffer.wpos(wpos); synchronized (messages) { try { int result = Socket.send(handle, buffer.array(), buffer.rpos(), buffer.available()); if (result < Status.APR_SUCCESS) { throwException(result); } if (messages.isEmpty()) { messages.wait(); } return messages.poll(); } catch (InterruptedException e) { throw (IOException) new InterruptedIOException(authSocket + ": Interrupted while polling for messages").initCause(e); } } } /** * transform an APR error number in a more fancy exception * * @param code APR error code * @throws java.io.IOException the produced exception for the given APR error number */ private void throwException(int code) throws IOException { throw new IOException( org.apache.tomcat.jni.Error.strerror(-code) + " (code: " + code + ")"); } }
Niky4000/UsefulUtils
projects/ssh/apache_mina/apache-sshd-1.2.0/sshd-core/src/main/java/org/apache/sshd/agent/unix/AgentClient.java
Java
gpl-3.0
6,427
<?php /****************************************************************************** * * * This file is part of RPB Calendar, a Wordpress plugin. * * Copyright (C) 2014 Yoann Le Montagner <yo35 -at- melix.net> * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ******************************************************************************/ require_once(RPBCALENDAR_ABSPATH . 'models/abstract/customposteditlist.php'); /** * Model for the table showing the list of event categories. */ class RPBCalendarModelCategoryList extends RPBCalendarAbstractModelCustomPostEditList { public function __construct() { parent::__construct(); $this->loadTrait('Category'); $this->loadTrait('AdminPageURLs'); } }
yo35/rpb-calendar
models/categorylist.php
PHP
gpl-3.0
1,899
using System.Runtime.InteropServices; using System.Security; using System; using System.Runtime.Remoting.Contexts; using System.Runtime.Remoting; using System.Runtime.Remoting.Activation; namespace System.Runtime.Remoting.Proxies { /// <summary>Indicates that an object type requires a custom proxy.</summary> [ComVisibleAttribute(true)] [SecurityCriticalAttribute()] [AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class ProxyAttribute : Attribute, IContextAttribute { public ProxyAttribute() { throw new NotImplementedException(); } /// <summary>Creates either an uninitialized <see cref="T:System.MarshalByRefObject" /> or a transparent proxy, depending on whether the specified type can exist in the current context.</summary><returns>An uninitialized <see cref="T:System.MarshalByRefObject" /> or a transparent proxy.</returns><param name="serverType">The object type to create an instance of. </param><PermissionSet><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /><IPermission class="System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="MemberAccess" /><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence, Infrastructure" /></PermissionSet> [SecurityCriticalAttribute()] public virtual MarshalByRefObject CreateInstance(Type serverType) { throw new NotImplementedException(); } /// <summary>Creates an instance of a remoting proxy for a remote object described by the specified <see cref="T:System.Runtime.Remoting.ObjRef" />, and located on the server.</summary><returns>The new instance of remoting proxy for the remote object that is described in the specified <see cref="T:System.Runtime.Remoting.ObjRef" />.</returns><param name="objRef">The object reference to the remote object for which to create a proxy. </param><param name="serverType">The type of the server where the remote object is located. </param><param name="serverObject">The server object. </param><param name="serverContext">The context in which the server object is located. </param><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /></PermissionSet> [SecurityCriticalAttribute()] public virtual RealProxy CreateProxy(ObjRef objRef, Type serverType, object serverObject, Context serverContext) { throw new NotImplementedException(); } /// <summary>Checks the specified context.</summary><returns>The specified context.</returns><param name="ctx">The context to be verified.</param><param name="msg">The message for the remote call.</param><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /></PermissionSet> [ComVisibleAttribute(true)] [SecurityCriticalAttribute()] public bool IsContextOK(Context ctx, IConstructionCallMessage msg) { throw new NotImplementedException(); } /// <summary>Gets properties for a new context.</summary><param name="msg">The message for which the context is to be retrieved.</param><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /></PermissionSet> [SecurityCriticalAttribute()] [ComVisibleAttribute(true)] public void GetPropertiesForNewContext(IConstructionCallMessage msg) { throw new NotImplementedException(); } } }
zebraxxl/CIL2Java
StdLibs/corlib/System/Runtime/Remoting/Proxies/ProxyAttribute.cs
C#
gpl-3.0
4,267
package script import ( evbus "github.com/asaskevich/EventBus" "github.com/mudler/artemide/pkg/context" plugin "github.com/mudler/artemide/plugin" jww "github.com/spf13/jwalterweatherman" ) // Script construct the container arguments from the boson file type Script struct{} // Process builds a list of packages from the boson file func (s *Script) Register(bus *evbus.EventBus, context *context.Context) { //returns args and volumes to mount bus.Subscribe("artemide:start", Start) //Subscribing to artemide:start, Hello will be called bus.Subscribe("artemide:artifact:recipe:script:event:after_unpack", afterUnpackHandler) //Subscribing to artemide:artifact:recipe:script:event:after_unpack, the After unpack handler } func afterUnpackHandler() { jww.DEBUG.Printf("afterUnpackHandler() called") } func Start() { jww.DEBUG.Printf("[recipe] Script is available") } func init() { plugin.RegisterRecipe(&Script{}) }
mudler/artemide
plugin/recipe/script/script.go
GO
gpl-3.0
978
class KuiristoWeb # # Recipe # head '/recipe/:source/:x/:id.raw' do |source,x,id| src = Kuiristo.source(source) # Find recipe and get rawid row = DB[:recipes].select(:rawid) .first(:source => src::ID, :id => id.to_i) not_found if row.nil? # Ensure data is found! # Get raw data row = DB[:rawdata].select(:updated) .first(:source => src::ID, :id => row[:rawid]) last_modified row[:updated] end get '/recipe/:source/:x/:id.raw' do |source,x,id| src = Kuiristo.source(source) # Find recipe and get rawid row = DB[:recipes].select(:rawid) .first(:source => src::ID, :id => id.to_i) not_found if row.nil? # Ensure data is found! # Get raw data row = DB[:rawdata].select(:zdata, :updated) .first(:source => src::ID, :id => row[:rawid]) last_modified row[:updated] data = Zlib::Inflate.inflate(row[:zdata]) content_type :text begin JSON.parse(data) content_type :json rescue JSON::ParserError end data end head '/recipe/:source/:x/:id.:fmt' do |source,x,id,fmt| src = Kuiristo.source(source) row = DB[:recipes].select(:updated) .first(:source => src::ID, :id => id.to_i) not_found if row.nil? # Ensure data is found! not_found if ![ 'xml', 'html' ].include?(fmt) last_modified row[:updated] end get '/recipe/:source/:x/:id.:fmt' do |source,x,id,fmt| src = Kuiristo.source(source) row = DB[:recipes].select(:zxml, :updated) .first(:source => src::ID, :id => id.to_i) not_found if row.nil? # Ensure data is found! xmltxt = Zlib::Inflate.inflate(row[:zxml]) last_modified row[:updated] case fmt when 'xml' content_type :xml xmltxt when 'html' # Recipe recipe = Kuiristo::Recipe.from_xml(xmltxt) # Recipe profil iprofils = DB[:recipe_ingredient] .left_join(:ingredients, :id => :ingredient) .where(:source => src::ID, :recipe => id.to_i) .select(:profil) .map(:profil) profil = VEGPROFILS.find(proc {[ 'unknown', 'Inconnu' ]}) {|k, v| iprofils.include?(k) } profil = [ 'ambiguous', 'Ambigu' ] if profil[0].nil? # Recipe categories tags = DB[:recipe_category] .left_join(:categories_for_recipes, :id => :category) .where(:source => src::ID, :recipe => id) .select(:id, :group, :name) .all # Render title recipe.name erb :recipe, :locals => { :recipe => recipe, :profil => profil, :tags => tags, } else not_found end end end
sdalu/kuiristo
app/recipe.rb
Ruby
gpl-3.0
3,314
OJ.importCss('nw.components.NwTray'); OJ.extendComponent( 'NwTray', [OjComponent], { '_props_' : { 'actuator' : null, 'allowSlide' : false, 'tray' : null }, '_template' : 'nw.components.NwTray', '_is_open' : false, // '_tray_anim' : null, '_constructor' : function(/*actuator, allowSlide = false unless native and mobile*/){ this._super(OjComponent, '_constructor', []); this._processArguments(arguments, { 'actuator' : undefined, 'allowSlide' : OJ.is_mobile && NW.isNative }); }, '_startTrayAnim' : function(tray_amount, content_amount){ var easing = OjEasing.STRONG_OUT, dir = OjMove.X; this._stopTrayAnim(); this._tray_anim = new OjTweenSet( new OjMove(this.panel, dir, tray_amount, 250, easing), new OjMove(this.container, dir, content_amount, 250, easing) ); this._tray_anim.addEventListener(OjTweenEvent.COMPLETE, this, '_onAnimComplete'); this._tray_anim.start(); }, '_stopTrayAnim' : function(){ this._unset('_tray_anim'); }, '_updateActuatorListeners' : function(action){ if(this._actuator){ this._actuator[action + 'EventListener'](OjUiEvent.PRESS, this, '_onActuatorClick'); } }, '_updateContainerListeners' : function(action){ this.container[action + 'EventListener'](OjUiEvent.DOWN, this, '_onTrayBlur'); }, '_updateDragListeners' : function(action){ if(this._actuator){ this._actuator[action + 'EventListener'](OjDragEvent.START, this, '_onActuatorDragStart'); this._actuator[action + 'EventListener'](OjDragEvent.MOVE, this, '_onActuatorDragMove'); } }, '_onActuatorClick' : function(evt){ this.toggleTray(); }, '_onActuatorDragMove' : function(evt){ }, '_onActuatorDragStart' : function(evt){ }, '_onAnimComplete' : function(evt){ this._stopTrayAnim(); if(this._callback){ this._callback(); this._callback = null; } }, '_onTrayBlur' : function(evt){ this.hideTray(); }, 'hideTray' : function(callback){ if(!this._is_open){ if(callback){ callback(); } return; } this._callback = callback; this._startTrayAnim(this.width * -.6, 0); this._updateContainerListeners(OjActionable.REMOVE); this._is_open = false; }, 'showTray' : function(callback){ if(this._is_open){ if(callback){ callback(); } return; } this._callback = callback; var w = this.width * .6; this.panel.width = w; this.panel.x = -1 * w; this._startTrayAnim(0, w); this._is_open = true; }, 'toggleTray' : function(/*val*/){ if(this._is_open){ this.hideTray(); } else{ this.showTray(); } }, '=actuator' : function(val){ if(this._actuator == val){ return; } this._updateActuatorListeners(OjActionable.REMOVE); this._updateDragListeners(OjActionable.REMOVE); this._actuator = val; this._updateActuatorListeners(OjActionable.ADD); if(this._allowSlide){ this._updateDragListeners(OjActionable.ADD); } }, '=allowSlide' : function(val){ if(this._allowSlide == val){ return; } this._updateDragListeners((this._allowSlide = val) ? OjActionable.ADD : OjActionable.REMOVE); }, '=tray' : function(val){ this.panel.removeAllChildren(); if(this._tray = val){ this.panel.appendChild(val); } }, '.trayPosition' : function(){ return this.container.x; }, '=trayPosition' : function(val){ var w = this.width * .6; this.panel.x = Math.max(Math.min(val - w, 0), -(w)); this.container.x = Math.min(Math.max(val, 0), w); // this._updateContainerListeners(OjActionable.ADD); } }, { '_TAGS' : ['tray'] } );
NuAge-Solutions/NW
src/js/components/NwTray.js
JavaScript
gpl-3.0
4,779
<?php include ('config.php'); include ('init.php'); include ('include.php'); $eventId = $_GET['eventId']; //get quantity of stations from event $query = 'SELECT stations FROM shootevent WHERE id='. $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $stations = $row['stations']; ?> <!DOCTYPE html> <html> <head> <title>Event Report</title> <?php include 'header.php'; ?> <style> td{ padding: 0px 3px; text-align:center; } td.firstName{ text-align:right; } td.lastName{ text-align:left; } tr:nth-child(even) { background: #DDD; } </style> </head> <body> <h1>Event Report</h1> <?php //put if event exists statement here /*echo '<h2> Editing Shooters in the '; $query = 'SELECT eventType FROM shootevent WHERE id='. $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $eventType = $row['eventType']; echo $eventType; echo ' Event of the '; */ $query = 'SELECT shootevent.eventType, registeredshoot.nscaShootId, registeredshoot.shootName, club.clubName FROM registeredshoot JOIN shootevent ON registeredshoot.id=shootevent.shootId JOIN club ON registeredshoot.clubId=club.id WHERE shootevent.id = ' . $eventId; $result = dbquery($query); $row = mysqli_fetch_array($result); $clubName = $row['clubName']; $shootName = $row['shootName']; $eventType = $row['eventType']; echo $clubName . '</br>'; echo $shootName; if($row['nscaShootId']){ echo ' - ' . $row['nscaShootId'] . '</br>'; }else{ echo '</br>'; } echo $eventType . ' Event </br>'; ?> <?php //total event Shooters $query = 'SELECT COUNT(*) AS numberOfShooters FROM eventshooter WHERE shooteventid =' . $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $totalShooters = $row['numberOfShooters'] . ' Shooters </br>'; $query = 'SELECT * FROM shooter JOIN eventshooter ON eventshooter.shooterId = shooter.id WHERE eventshooter.shootEventId =' . $eventId . ' ORDER BY shooter.lastName ASC'; $result = dbquery($query); //table all BY LASTNAME ASC echo '<table border=\'1\'><thead><td>NSCA ID</td><td></td><td></td><td></td><td>Score</td></thead>'; while ($row = mysqli_fetch_array($result)){ echo '<tr>'; echo '<td class=\'nscaId\'>' . $row['nscaId'] . '</td>'; echo '<td class=\'firstName\'>' . $row['firstName'] . '</td>'; echo '<td class=\'lastName\'>' . $row['lastName'] . ' ' . $row['suffix'] . '</td>'; echo '<td class=\'class\'>' . $row['class'] . '</td>'; echo'</td>'; //get score $query2 = 'SELECT SUM(targetsBroken) AS totalScore FROM shootereventstationscore WHERE eventShooterId=' . $row['id']; $result2 = dbquery($query2); $row2 = mysqli_fetch_assoc($result2); echo '<td class=\'score\'>' . $row2['totalScore'] . '</td>'; } echo '</table>'; $scoreReportData = array(); function makeTable ($eventId,$searchBy,$searchParameter/*,$headersArray*/){ //this is shit drawTable( mergeshooterArrayAwards( giveAwards( getShooters($eventId, $searchBy, $searchParameter), $searchBy, $searchParameter), $searchParameter), $searchBy, $searchParameter); } //end makeTable function getShooters($eventId, $searchBy, $searchParameter){ //number of shooters by searchBy if ($searchBy == 'class' || $searchBy == 'concurrent'){ $whereClause = 'WHERE eventshooter.' . $searchBy . '=\'' . $searchParameter . '\''; }else if ($searchBy == 'concurrentLady'){ $whereClause = 'WHERE shooter.nscaConcurrentLady =\'' . $searchParameter . '\''; } $query = 'SELECT COUNT(*) AS numberOfShooters FROM shooter JOIN eventshooter ON eventshooter.shooterId = shooter.id ' . $whereClause . ' AND eventshooter.shootEventId =' . $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $shooterCount = $row['numberOfShooters']; //get shooters by searchBy $query = 'SELECT * FROM shooter JOIN eventshooter ON eventshooter.shooterId = shooter.id ' . $whereClause . ' AND eventshooter.shootEventId =' . $eventId; $result = dbquery($query); $shooterArray = array(); $i = 0; while ($row = mysqli_fetch_array($result)){ //ust add score to array instead of creating new array? $shooterArray[$i]['firstName'] = $row['firstName']; $shooterArray[$i]['lastName'] = $row['lastName'] . ' ' . $row['suffix']; $shooterArray[$i]['nscaId'] = $row['nscaId']; //merged into nsca report $shooterArray[$i]['state'] = $row['state']; //merged into nsca report $shooterArray[$i]['shooterId'] = $row['shooterId'];//merged into nsca report //get scores $query2 = 'SELECT SUM(targetsBroken) AS totalScore FROM shootereventstationscore WHERE eventShooterId=' . $row['id']; $result2 = dbquery($query2); $row2 = mysqli_fetch_assoc($result2); $shooterArray[$i]['score'] = $row2['totalScore']; $i++; } $getShootersReturn = array($shooterArray,$shooterCount); return $getShootersReturn; } //end getShooters function giveAwards($getShooterReturn,$searchBy,$searchParameter){ //might be possible to do this with a strategic db query //sort by scores DESC $shooterArray = $getShooterReturn[0]; $shooterCount = $getShooterReturn[1]; if ($shooterCount > 0){ foreach ($shooterArray as $shooter){ $tmp[] = $shooter['score']; } array_multisort($tmp, SORT_DESC, $shooterArray); //put one of each score in array in descending order $scoreList = array(); $last = 10000; foreach ($shooterArray as $shooter){ $current = $shooter['score']; if ($current < $last){ $scoreList[] = $current; $last = $current; } } } if($searchBy == 'class'){ //determine punches/award based on amount of shooters if ($shooterCount >= 0 && $shooterCount <= 2){ $punches = array(); } if ($shooterCount >= 3 && $shooterCount <= 9){ $punches = array(1); } if ($shooterCount >= 10 && $shooterCount <= 14){ $punches = array(2,1); } if ($shooterCount >= 15 && $shooterCount <= 29){ $punches = array(4,2,1); } if ($shooterCount >= 30 && $shooterCount <= 44){ $punches = array(4,4,2,1); } if ($shooterCount >= 45){ $punches = array(4,4,4,3,2,1); } $i = 0; //location in punches and scoreList $j = 0; //location in shooter table while ($i < sizeof($punches)){ if ($shooterArray[$j]['score'] == $scoreList[$i]){ $shooterArray[$j]['awardClass'] = $searchParameter . strval($i+1); $shooterArray[$j]['punches'] = $punches[$i]; $j++; }else { $i++; } } while ($i >= sizeof($punches) && $j < $shooterCount){ $shooterArray[$j]['awardClass'] = $shooterArray[$j]['punches'] = '-'; $j++; }; }else if($searchBy == 'concurrent' || $searchBy == 'concurrentLady'){ //this will be more complicated when I implement points system, but for now this will do. //add shooter count conditions here for concurrent points $concurrentPoints = array(4,3,2,1); $i = 0; //location in punches and scoreList $j = 0; //location in shooter table while ($i < sizeof($concurrentPoints)){ if (isset($shooterArray[$j]['score']) && $shooterArray[$j]['score'] == $scoreList[$i]){ $shooterArray[$j]['awardConcurrent'] = $searchParameter . strval($i+1); $shooterArray[$j]['concurrentPoints'] = $concurrentPoints[$i]; $j++; }else { $i++; } } while ($i >= sizeof($concurrentPoints) && $j < $shooterCount){ $shooterArray[$j]['awardConcurrent'] = $shooterArray[$j]['concurrentPoints'] = '-'; $j++; }; }//else if($searchBy == 'concurrentLady'){ //append award instead of settign award //} return array($shooterArray,$shooterCount); } //end giveAwards function mergeshooterArrayAwards($shooterArrayAndShooterCount){ // $mergeshooterArrayAwards = array($mergedData, $shooterArray) //return $mergeshooterArrayAwardsReturn; return $shooterArrayAndShooterCount; }//end mergeshooterArrayAwards function drawTable($shooterArrayAndShooterCount, $searchBy, $searchParameter){ $shooterArray = $shooterArrayAndShooterCount[0]; $shooterCount = $shooterArrayAndShooterCount[1]; //dump shooterArray into scoreReport array //global $scoreReportData; //$scoreReportData = array_merge($scoreReportData, $shooterArray); //draw table if ($shooterCount > 0){ if ($searchBy == 'M'){ $searchBy = 'Master'; } $shooterCountString = $shooterCount; if ($shooterCountString == 1){ $shooterCountString .= ' Shooter'; }else{ $shooterCountString .= ' Shooters'; } if ($searchBy == 'class'){ echo '<table border=\'1\'><thead><td colspan=\'3\'>' . $searchParameter . ' Class - ' . $shooterCountString . '</td><td>Award</td><td>Punches</td></thead>'; for ($k = 0; $k < $shooterCount ; $k++){ echo '<tr>'; echo '<td class=\'firstName\'>' . $shooterArray[$k]['firstName'] . '</td>'; echo '<td class=\'lastName\'>' . $shooterArray[$k]['lastName'] . '</td>'; echo '<td class=\'score\'>' . $shooterArray[$k]['score'] . '</td>'; echo '<td class=\'awardClass\'>' . $shooterArray[$k]['awardClass'] . '</td>'; echo '<td class=\'punches\'>' . $shooterArray[$k]['punches'] . '</td>'; echo '</tr>'; } echo '</table>'; }else if ($searchBy == 'concurrent' || $searchBy == 'concurrentLady' ){ if ($searchBy == 'concurrentLady'){ $searchParameter = 'LY'; } echo '<table border=\'1\'><thead><td colspan=\'3\'>' . $searchParameter . ' Concurrent - ' . $shooterCountString . '</td><td>Award</td></thead>'; for ($k = 0; $k < $shooterCount ; $k++){ echo '<tr>'; echo '<td class=\'firstName\'>' . $shooterArray[$k]['firstName'] . '</td>'; echo '<td class=\'lastName\'>' . $shooterArray[$k]['lastName'] . '</td>'; echo '<td class=\'score\'>' . $shooterArray[$k]['score'] . '</td>'; echo '<td class=\'awardClass\'>' . $shooterArray[$k]['awardConcurrent'] . '</td>'; echo '</tr>'; } } } //return $shooterArray; } //end drawTable //end function makeClassTableh /*makeTable($eventId,'class','M'); makeTable($eventId,'class','AA'); makeTable($eventId,'class','A'); makeTable($eventId,'class','B'); makeTable($eventId,'class','C'); makeTable($eventId,'class','D'); makeTable($eventId,'class','E'); makeTable($eventId,'concurrent','SJ'); makeTable($eventId,'concurrent','JR'); makeTable($eventId,'concurrent','VT'); makeTable($eventId,'concurrent','SV'); makeTable($eventId,'concurrent','SSV'); makeTable($eventId,'concurrentLady','1'); //makeTable($eventId,'concurrent',''); //open concurrency - to calculate All-X points */ //HOA //get shooters with hoa //find highest score //calculate percentage winnings //calculate money winnings //HIC //get shooters with hic per class //same as above //lewis //get shooters with lewis //get shooterCount with lewis //get lewis groups //order shooters by score ascending **important // //Lewis Calculation // //these queries should be moved to getShooters $query = ' SELECT lewisGroups FROM shootevent WHERE id=' . $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $lewisGroups = $row['lewisGroups']; if(!isset($lewisGroups) || $lewisGroups == 0){ echo 'Lewis Groups not set'; } else{ $searchBy = 'lewisOption'; $searchParameter = 1; $whereClause = 'WHERE eventshooter.' . $searchBy . '=\'' . $searchParameter . '\''; $query = 'SELECT COUNT(*) AS numberOfShooters FROM shooter JOIN eventshooter ON eventshooter.shooterId = shooter.id ' . $whereClause . ' AND eventshooter.shootEventId =' . $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $shooterCount = $row['numberOfShooters']; //get shooters by searchBy $query = 'SELECT * FROM shooter JOIN eventshooter ON eventshooter.shooterId = shooter.id ' . $whereClause . ' AND eventshooter.shootEventId =' . $eventId; $result = dbquery($query); $i = 0; while ($row = mysqli_fetch_array($result)){ $shooterArray[$i]['firstName'] = $row['firstName']; $shooterArray[$i]['lastName'] = $row['lastName'] . ' ' . $row['suffix']; //get scores $query2 = 'SELECT SUM(targetsBroken) AS totalScore FROM shootereventstationscore WHERE eventShooterId=' . $row['id']; $result2 = dbquery($query2); $row2 = mysqli_fetch_assoc($result2); $shooterArray[$i]['score'] = $row2['totalScore']; $i++; } foreach ($shooterArray as $val){ $tmp[] = $val['score']; } array_multisort($tmp, SORT_ASC, $shooterArray); $shooterCountModular = $shooterCount % $lewisGroups; //left over shooters if broken into even groups $groupShooterCount = ( $shooterCount - $shooterCountModular ) / $lewisGroups; //Lewis group size if evenly divisible $groupCounts = array(); //size of each Lewis group from lowest score to highest $x = 1; //$x - group number while ($x <= $lewisGroups){ if ($shooterCountModular > 0){ $groupCounts[$x] = $groupShooterCount + 1; $shooterCountModular -= 1; }else { $groupCounts[$x] = $groupShooterCount; } $x++; } //end while //assign groupings $x = 0; $y = $lewisGroups; //look at each value in the $lewisGroupShooterCount array foreach ($groupCounts as $shootersLeftInGroup){ //set shooters' group while ($shootersLeftInGroup > 0 ){ $shooterArray[$x]['lewisGroup'] = $y; $shootersLeftInGroup -= 1; $x += 1; } $y -= 1; } //groupings for $originalGroup = $lastGroup = $shooterArray[0]['lewisGroup']; $lastScore = $currentGroup = -1; //set to impossible $scoresBelowLine = $scoresAboveLine = 0; foreach ($shooterArray as $shooter){ $currentScore = $shooter['score']; $currentGroup = $shooter['lewisGroup']; //echo $lastScore; if ($currentScore == $lastScore){ if ($scoresBelowLine == 0 && $scoresAboveLine == 0){ $originalGroup = $lastGroup; } if ($currentGroup == $originalGroup){ $scoresBelowLine += 1; }else{ $scoresAboveLine += 1; $highestGroup = $currentGroup; } }else { //if scores are not the same if ($scoresBelowLine == 0 && $scoresBelowLine == 0){ //capture case, no ties before this, skip to next score }else if ($scoresBelowLine >= $scoresAboveLine){ $lewisTies[$lastScore] = $originalGroup; // echo ' v'; }else { $lewisTies[lastScore] = $lastGroup; // echo ' ^'; $scoresAboveLine = $scoresBelowLine = 0; } $scoresAboveLine = $scoresBelowLine = 0; } $lastScore = $currentScore; $lastGroup = $currentGroup; //echo ' --- ' . $currentScore . ' - ' . $currentGroup . ' - ' . $originalGroup . ' - ' . $lastGroup . ' - ' . $scoresBelowLine . ' - ' . $scoresAboveLine; //echo '</br>'; } //end outer foreach //changing groups foreach ($shooterArray as &$shooter){ foreach ($lewisTies as $score => $newGroup){ if ($shooter['score'] == $score ){ $shooter['lewisGroup'] = $newGroup; break; } } } //end changing groups unset($shooter); $query = 'SELECT lewisCost FROM shootevent WHERE id =' . $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $lewisCost = $row['lewisCost']; $totalLewisMoney = $lewisCost * $shooterCount; $groupLewisMoney = $totalLewisMoney / $lewisGroups; $x = 1; while ($x <= $lewisGroups){ $highestScore = 0; $awardSplit = 0; foreach ($shooterArray as $shooter){ //the last score meeting the if statement should always be highest else there's a problem if($shooter['lewisGroup'] == $x){ $highestScore = $shooter['score']; } } foreach ($shooterArray as $shooter){ if ($shooter['score'] == $highestScore){ $awardSplit++; } } //convert lewis group number to letter (NSCA practice) $lewisClassLetter = chr($x + 64); foreach ($shooterArray as &$shooter){ if($shooter['lewisGroup'] == $x){ if ($shooter['score'] == $highestScore){ $shooter['lewisPercentage'] = round((1 / $awardSplit), 3, PHP_ROUND_HALF_UP) * 100; $shooter['lewisMoney'] = round(((1 / $awardSplit) * $groupLewisMoney),2,PHP_ROUND_HALF_UP); }else { $shooter['lewisPercentage'] = $shooter['lewisMoney'] = '0'; } } } unset($shooter); echo '<table border="1">'; echo '<thead><td colspan="5">Lewis Class ' . $lewisClassLetter . '</thead>'; echo '<thead>'; echo '<td colspan="2"></td>'; //firstName lastName echo '<td>Score</td>'; echo '<td>Win %</td>'; echo '<td class="private">Money</td>'; echo '</thead>'; $shooterArrayDesc = array_reverse($shooterArray); foreach ($shooterArrayDesc as $shooter){ if($shooter['lewisGroup'] == $x){ echo '<tr>'; echo '<td class="firstName">' . $shooter['firstName'] . '</td>'; echo '<td class="lastName">' . $shooter['lastName'] . '</td>'; echo '<td>' . $shooter['score'] . '</td>'; echo '<td>' . $shooter['lewisPercentage'] . '%</td>'; echo '<td class="private">$' . $shooter['lewisMoney'] . '</td>'; echo '</tr>'; } } echo '</table>'; $x++; }//end while } // //end Lewis Calculation // ?> </body> <?php include 'footer.php'; ?> <script type="text/javascript"> $(document).ready(function(){ }); </script> </html>
peteritism/ShootReportSystem
eventReport.php
PHP
gpl-3.0
17,554
/** * @file Column.cpp * @ingroup SQLiteCpp * @brief Encapsulation of a Column in a row of the result pointed by the prepared SQLite::Statement. * * Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <SQLiteCpp/Column.h> #include <iostream> namespace SQLite { // Encapsulation of a Column in a row of the result pointed by the prepared Statement. Column::Column(Statement::Ptr& aStmtPtr, int aIndex) noexcept : // nothrow mStmtPtr(aStmtPtr), mIndex(aIndex) { } // Finalize and unregister the SQL query from the SQLite Database Connection. Column::~Column() noexcept // nothrow { // the finalization will be done by the destructor of the last shared pointer } // Return the named assigned to this result column (potentially aliased) const char* Column::getName() const noexcept // nothrow { return sqlite3_column_name(mStmtPtr, mIndex); } #ifdef SQLITE_ENABLE_COLUMN_METADATA // Return the name of the table column that is the origin of this result column const char* Column::getOriginName() const noexcept // nothrow { return sqlite3_column_origin_name(mStmtPtr, mIndex); } #endif // Return the integer value of the column specified by its index starting at 0 int Column::getInt() const noexcept // nothrow { return sqlite3_column_int(mStmtPtr, mIndex); } // Return the 64bits integer value of the column specified by its index starting at 0 sqlite3_int64 Column::getInt64() const noexcept // nothrow { return sqlite3_column_int64(mStmtPtr, mIndex); } // Return the double value of the column specified by its index starting at 0 double Column::getDouble() const noexcept // nothrow { return sqlite3_column_double(mStmtPtr, mIndex); } // Return a pointer to the text value (NULL terminated string) of the column specified by its index starting at 0 const char* Column::getText(const char* apDefaultValue /* = "" */) const noexcept // nothrow { const char* pText = (const char*)sqlite3_column_text(mStmtPtr, mIndex); return (pText?pText:apDefaultValue); } // Return a pointer to the text value (NULL terminated string) of the column specified by its index starting at 0 const void* Column::getBlob() const noexcept // nothrow { return sqlite3_column_blob(mStmtPtr, mIndex); } // Return the type of the value of the column int Column::getType() const noexcept // nothrow { return sqlite3_column_type(mStmtPtr, mIndex); } // Return the number of bytes used by the text value of the column int Column::getBytes() const noexcept // nothrow { return sqlite3_column_bytes(mStmtPtr, mIndex); } // Standard std::ostream inserter std::ostream& operator<<(std::ostream& aStream, const Column& aColumn) { aStream << aColumn.getText(); return aStream; } } // namespace SQLite
edlund/fabl-ng
vendor/sources/sqlitecpp-1.1/src/Column.cpp
C++
gpl-3.0
2,919
<?php /** * Single Post template file * * This file is the single template file, used on single blog posts, per * the {@link http://codex.wordpress.org/Template_Hierarchy Template Hierarchy}. * * @link http://codex.wordpress.org/Function_Reference/comments_open comments_open() * @link http://codex.wordpress.org/Function_Reference/comments_template comments_template() * @link http://codex.wordpress.org/Function_Reference/get_header get_header() * @link http://codex.wordpress.org/Function_Reference/get_footer get_footer() * @link http://codex.wordpress.org/Function_Reference/have_posts have_posts() * @link http://codex.wordpress.org/Function_Reference/post_password_required post_password_required() * @link http://codex.wordpress.org/Function_Reference/the_content the_content() * @link http://codex.wordpress.org/Function_Reference/the_ID the_ID() * @link http://codex.wordpress.org/Function_Reference/the_post the_post() * @link http://codex.wordpress.org/Function_Reference/wp_link_pages wp_link_pages() * * @uses apptheme_no_posts() Defined in /functions.php * * @package App Theme * @copyright Copyright (c) 2010, UpThemes * @license license.txt GNU General Public License, v3 * @since AppTheme 1.0 */ /** * Include the header template part file * * MUST come first. * Calls the header PHP file. * Used in all primary template pages * * @see {@link: http://codex.wordpress.org/Function_Reference/get_header get_header} * * Child Themes can replace this template part file globally, via "header.php", or in * a specific context only, via "header-single.php" */ get_header(); ?> <div id="content"> <div class="row"> <div class="column six"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h1><?php the_title(); ?></h1> <div id="post-<?php the_ID(); ?>" <?php post_class('postwrapper'); ?>> <?php the_content(); ?> <?php wp_link_pages(); ?> </div><!-- /.postwrapper --> <?php if ( comments_open() && ! post_password_required() ) { /** * Include the comments template * * Includes the comments.php template part file */ comments_template(); } ?> <?php endwhile; ?> <?php else : ?> <?php /** * Output no-post content */ apptheme_no_posts(); ?> <?php endif; ?> </div><!-- .column.six --> </div><!-- .row --> </div><!-- #content --> <?php /** * Include the footer template part file * * MUST come last. * Calls the footer PHP file. * Used in all primary template pages * * Codex reference: {@link http://codex.wordpress.org/Function_Reference/get_footer get_footer} * * Child Themes can replace this template part file globally, via "footer.php", or in * a specific context only, via "footer-single.php" */ get_footer(); ?>
UpThemes/AppTheme
single.php
PHP
gpl-3.0
2,893
// This file has been generated by Py++. #include "stdafx.h" #include "pypluspluscommon.h" #include "boost/python.hpp" #include "__call_policies.pypp.hpp" #include "xmlmanager.h" #include "httpurl.h" #include "xmldocument.h" #include "xmlmanager.pypp.hpp" namespace bp = boost::python; struct XMLManager_wrapper : ::osiris::XMLManager, ::osiris::PythonWrapper< ::osiris::XMLManager > { XMLManager_wrapper( ) : ::osiris::XMLManager( ) , ::osiris::PythonWrapper< ::osiris::XMLManager >(){ // null constructor } static boost::python::object parseBuffer( ::osiris::XMLManager & inst, ::osiris::Buffer const & buffer, ::osiris::IXMLHandler * handler, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr), ::osiris::String const & encoding=("UTF-8") ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseBuffer(buffer, handler, schema, encoding); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object parseFile( ::osiris::XMLManager & inst, ::osiris::String const & filename, ::osiris::IXMLHandler * handler, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseFile(filename, handler, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object parseString( ::osiris::XMLManager & inst, ::osiris::String const & str, ::osiris::IXMLHandler * handler, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseString(str, handler, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object parseStringUTF8( ::osiris::XMLManager & inst, ::std::string const & str, ::osiris::IXMLHandler * handler, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseStringUTF8(str, handler, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object parseStream( ::osiris::XMLManager & inst, ::boost::shared_ptr< osiris::IStream > stream, ::osiris::IXMLHandler * handler, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr), ::osiris::String const & encoding=("UTF-8") ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseStream(stream, handler, schema, encoding); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object parseUrl( ::osiris::XMLManager & inst, ::osiris::HttpUrl const & url, ::osiris::IXMLHandler * handler, ::osiris::String const & userAgent, ::boost::shared_ptr< boost::asio::io_service > service, ::boost::shared_ptr< osiris::TCPSocket > socket, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseUrl(url, handler, userAgent, service, socket, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object writeBuffer( ::osiris::XMLManager const & inst, ::osiris::XMLDocument const & document, ::osiris::Buffer & buffer, ::osiris::String const & encoding=("UTF-8") ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.writeBuffer(document, buffer, encoding); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object writeFile( ::osiris::XMLManager const & inst, ::osiris::XMLDocument const & document, ::osiris::String const & filename, ::osiris::String const & encoding=("UTF-8") ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.writeFile(document, filename, encoding); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object writeString( ::osiris::XMLManager const & inst, ::osiris::XMLDocument const & document, ::osiris::String & str ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.writeString(document, str); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object writeStringUTF8( ::osiris::XMLManager const & inst, ::osiris::XMLDocument const & document, ::std::string & str ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.writeStringUTF8(document, str); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object writeStream( ::osiris::XMLManager const & inst, ::osiris::XMLDocument const & document, ::boost::shared_ptr< osiris::IStream > stream, ::osiris::String const & encoding=("UTF-8") ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.writeStream(document, stream, encoding); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object validateBuffer( ::osiris::XMLManager const & inst, ::osiris::Buffer const & buffer, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.validateBuffer(buffer, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object validateFile( ::osiris::XMLManager const & inst, ::osiris::String const & filename, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.validateFile(filename, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object validateString( ::osiris::XMLManager const & inst, ::osiris::String const & str, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.validateString(str, schema); __pythreadSaver.restore(); return boost::python::object( result ); } }; void register_XMLManager_class(){ ::boost::python::class_< XMLManager_wrapper, ::boost::python::bases< ::osiris::StaticSingleton< osiris::XMLManager, true > >, ::boost::noncopyable >( "XMLManager", ::boost::python::no_init ) .def( ::boost::python::init< >() ) .def( "parseBuffer" , (boost::python::object (*)( ::osiris::XMLManager &,::osiris::Buffer const &,::osiris::IXMLHandler *,::boost::shared_ptr<osiris::XMLSchema>,::osiris::String const & ))( &XMLManager_wrapper::parseBuffer ) , ( ::boost::python::arg("inst"), ::boost::python::arg("buffer"), ::boost::python::arg("handler"), ::boost::python::arg("schema")=(nullptr), ::boost::python::arg("encoding")=("UTF-8") ) ) .def( "parseFile" , (boost::python::object (*)( ::osiris::XMLManager &,::osiris::String const &,::osiris::IXMLHandler *,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::parseFile ) , ( ::boost::python::arg("inst"), ::boost::python::arg("filename"), ::boost::python::arg("handler"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "parseString" , (boost::python::object (*)( ::osiris::XMLManager &,::osiris::String const &,::osiris::IXMLHandler *,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::parseString ) , ( ::boost::python::arg("inst"), ::boost::python::arg("str"), ::boost::python::arg("handler"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "parseStringUTF8" , (boost::python::object (*)( ::osiris::XMLManager &,::std::string const &,::osiris::IXMLHandler *,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::parseStringUTF8 ) , ( ::boost::python::arg("inst"), ::boost::python::arg("str"), ::boost::python::arg("handler"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "parseStream" , (boost::python::object (*)( ::osiris::XMLManager &,::boost::shared_ptr<osiris::IStream>,::osiris::IXMLHandler *,::boost::shared_ptr<osiris::XMLSchema>,::osiris::String const & ))( &XMLManager_wrapper::parseStream ) , ( ::boost::python::arg("inst"), ::boost::python::arg("stream"), ::boost::python::arg("handler"), ::boost::python::arg("schema")=(nullptr), ::boost::python::arg("encoding")=("UTF-8") ) ) .def( "parseUrl" , (boost::python::object (*)( ::osiris::XMLManager &,::osiris::HttpUrl const &,::osiris::IXMLHandler *,::osiris::String const &,::boost::shared_ptr<boost::asio::io_service>,::boost::shared_ptr<osiris::TCPSocket>,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::parseUrl ) , ( ::boost::python::arg("inst"), ::boost::python::arg("url"), ::boost::python::arg("handler"), ::boost::python::arg("userAgent"), ::boost::python::arg("service"), ::boost::python::arg("socket"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "writeBuffer" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::XMLDocument const &,::osiris::Buffer &,::osiris::String const & ))( &XMLManager_wrapper::writeBuffer ) , ( ::boost::python::arg("inst"), ::boost::python::arg("document"), ::boost::python::arg("buffer"), ::boost::python::arg("encoding")=("UTF-8") ) ) .def( "writeFile" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::XMLDocument const &,::osiris::String const &,::osiris::String const & ))( &XMLManager_wrapper::writeFile ) , ( ::boost::python::arg("inst"), ::boost::python::arg("document"), ::boost::python::arg("filename"), ::boost::python::arg("encoding")=("UTF-8") ) ) .def( "writeString" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::XMLDocument const &,::osiris::String & ))( &XMLManager_wrapper::writeString ) , ( ::boost::python::arg("inst"), ::boost::python::arg("document"), ::boost::python::arg("str") ) ) .def( "writeStringUTF8" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::XMLDocument const &,::std::string & ))( &XMLManager_wrapper::writeStringUTF8 ) , ( ::boost::python::arg("inst"), ::boost::python::arg("document"), ::boost::python::arg("str") ) ) .def( "writeStream" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::XMLDocument const &,::boost::shared_ptr<osiris::IStream>,::osiris::String const & ))( &XMLManager_wrapper::writeStream ) , ( ::boost::python::arg("inst"), ::boost::python::arg("document"), ::boost::python::arg("stream"), ::boost::python::arg("encoding")=("UTF-8") ) ) .def( "validateBuffer" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::Buffer const &,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::validateBuffer ) , ( ::boost::python::arg("inst"), ::boost::python::arg("buffer"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "validateFile" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::String const &,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::validateFile ) , ( ::boost::python::arg("inst"), ::boost::python::arg("filename"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "validateString" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::String const &,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::validateString ) , ( ::boost::python::arg("inst"), ::boost::python::arg("str"), ::boost::python::arg("schema")=(nullptr) ) ); }
OsirisSPS/osiris-sps
client/src/plugins/python/wrappers/xmlmanager.pypp.cpp
C++
gpl-3.0
12,206
package models; import java.sql.ResultSet; import java.sql.SQLException; /** * Classe qui permet de gérer les informations des utilisateurs déjà inscris. * @author BURC Pierre, DUPLOUY Olivier, KISIALIOVA Katsiaryna, SEGUIN Tristan * */ public class UserInformation { private User infoUser; private static String quoteCharacter="'"; /** * Constructeur vide. */ public UserInformation(){ } /** * <p>Méthode qui permet de récupérer l'ensemble des informations d'un utilisateur en * interrogeant la BDD.</p> * @param pseudo Le pseudo pour lequel on souhaite récupérer les informations. * @throws SQLException Problème SQL. */ public void retrieveInformation(String pseudo) throws SQLException{ ConnectionBase.open(); ResultSet res=ConnectionBase.requete("SELECT * FROM \"UserInfo\" " + "WHERE pseudo="+quoteCharacter+pseudo+quoteCharacter); if (!res.first()){ this.infoUser=new User("guest"); }else{ res.first(); this.infoUser=new User( res.getString("pseudo"), res.getString("nom"), res.getString("prenom"), res.getString("mdp"), res.getString("email")); } ConnectionBase.close(); } /*public void profil(String pseudo) throws SQLException{ ConnectionBase.open(); ResultSet res=ConnectionBase.requete("SELECT * FROM \"UserInfo\" " + "WHERE pseudo="+quoteCharacter+pseudo+quoteCharacter); res.first(); this.infoUser=new User( res.getString("pseudo"), res.getString("mdp"), res.getString("nom"), res.getString("prenom"), res.getString("email")); ConnectionBase.close(); }*/ /** * * @param pseudo * @return vrai s'il y a déjà un pseudo égal au paramètre. Sinon faux * @throws SQLException */ public boolean pseudoAlreadyExists(String pseudo) throws SQLException{ ConnectionBase.open(); ResultSet res=ConnectionBase.requete("SELECT pseudo FROM \"UserInfo\" " + "WHERE pseudo="+quoteCharacter+pseudo+quoteCharacter); boolean retour=res.first(); ConnectionBase.close(); return retour; } /** * * @param pseudo * @param mdp * @return vrai si l'utilisateur est autorisé à se connecter. Sinon faux * @throws SQLException */ public boolean connectionAllowed(String pseudo,String mdp) throws SQLException{ ConnectionBase.open(); ResultSet res=ConnectionBase.requete("SELECT pseudo,mdp " + "FROM \"UserInfo\" " + "WHERE pseudo='"+pseudo+"'"+ "AND mdp='"+mdp+"'"); boolean retour=res.first(); ConnectionBase.close(); return retour; } /** * Getter permettant de récupérer un objet User contenant les informations d'un utilisateur. * @return */ public User getInfoUser() { return infoUser; } }
lodacom/UpYourMood
app/models/UserInformation.java
Java
gpl-3.0
2,698
#include <iostream> #include "argument.h" using namespace std; using namespace command; #define VALUE "-1234567890" typedef int ArgumentType; ArgumentType test; void _function(ArgumentType value) { test = value; } int main() { Argument<ArgumentType> argument("Argument as negative int", _function); if (argument.understand(VALUE)) { argument.handle(); } else { cout << "Argument class do not understand negative int values\n"; return 1; } if (test == std::stoi(VALUE)) { cout << "Argument class handles negative int values\n"; return 0; } cout << "Argument class do not handle negative int values\n"; return 1; }
quayle/command
tests/argument/handles_negative_int_value.cpp
C++
gpl-3.0
704
/* Neutrino-GUI - DBoxII-Project Copyright (C) 2001 Steffen Hehn 'McClean' Homepage: http://dbox.cyberphoria.org/ Copyright (C) 2012-2013 Stefan Seyfried License: GPL This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "infoviewer_bb.h" #include <algorithm> #include <sys/types.h> #include <sys/stat.h> #include <sys/sysinfo.h> #include <sys/vfs.h> #include <sys/timeb.h> #include <sys/param.h> #include <time.h> #include <fcntl.h> #include <unistd.h> #include <global.h> #include <neutrino.h> #include <gui/infoviewer.h> #include <gui/bouquetlist.h> #include <gui/widget/icons.h> #include <gui/widget/hintbox.h> #include <gui/customcolor.h> #include <gui/pictureviewer.h> #include <gui/movieplayer.h> #include <system/helpers.h> #include <system/hddstat.h> #include <daemonc/remotecontrol.h> #include <driver/radiotext.h> #include <driver/volume.h> #include <zapit/femanager.h> #include <zapit/zapit.h> #include <video.h> extern CRemoteControl *g_RemoteControl; /* neutrino.cpp */ extern cVideo * videoDecoder; #define COL_INFOBAR_BUTTONS_BACKGROUND (COL_INFOBAR_SHADOW_PLUS_1) CInfoViewerBB::CInfoViewerBB() { frameBuffer = CFrameBuffer::getInstance(); is_visible = false; scrambledErr = false; scrambledErrSave = false; scrambledNoSig = false; scrambledNoSigSave = false; scrambledT = 0; #if 0 if(!scrambledT) { pthread_create(&scrambledT, NULL, scrambledThread, (void*) this) ; pthread_detach(scrambledT); } #endif hddscale = NULL; sysscale = NULL; bbIconInfo[0].x = 0; bbIconInfo[0].h = 0; BBarY = 0; BBarFontY = 0; hddscale = NULL; sysscale = NULL; Init(); } void CInfoViewerBB::Init() { hddwidth = 0; bbIconMaxH = 0; bbButtonMaxH = 0; bbIconMinX = 0; bbButtonMaxX = 0; fta = true; minX = 0; for (int i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { tmp_bbButtonInfoText[i] = ""; bbButtonInfo[i].x = -1; } InfoHeightY_Info = g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->getHeight() + 5; setBBOffset(); changePB(); } CInfoViewerBB::~CInfoViewerBB() { if(scrambledT) { pthread_cancel(scrambledT); scrambledT = 0; } if (hddscale) delete hddscale; if (sysscale) delete sysscale; } CInfoViewerBB* CInfoViewerBB::getInstance() { static CInfoViewerBB* InfoViewerBB = NULL; if(!InfoViewerBB) { InfoViewerBB = new CInfoViewerBB(); } return InfoViewerBB; } bool CInfoViewerBB::checkBBIcon(const char * const icon, int *w, int *h) { frameBuffer->getIconSize(icon, w, h); if ((*w != 0) && (*h != 0)) return true; return false; } void CInfoViewerBB::getBBIconInfo() { bbIconMaxH = 0; BBarY = g_InfoViewer->BoxEndY + bottom_bar_offset; BBarFontY = BBarY + InfoHeightY_Info - (InfoHeightY_Info - g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->getHeight()) / 2; /* center in buttonbar */ bbIconMinX = g_InfoViewer->BoxEndX - 8; //should be 10px, but 2px will be reduced for each icon CNeutrinoApp* neutrino = CNeutrinoApp::getInstance(); for (int i = 0; i < CInfoViewerBB::ICON_MAX; i++) { int w = 0, h = 0; bool iconView = false; switch (i) { case CInfoViewerBB::ICON_SUBT: //no radio if (neutrino->getMode() != NeutrinoMessages::mode_radio) iconView = checkBBIcon(NEUTRINO_ICON_SUBT, &w, &h); break; case CInfoViewerBB::ICON_VTXT: //no radio if (neutrino->getMode() != NeutrinoMessages::mode_radio) iconView = checkBBIcon(NEUTRINO_ICON_VTXT, &w, &h); break; case CInfoViewerBB::ICON_RT: if ((neutrino->getMode() == NeutrinoMessages::mode_radio) && g_settings.radiotext_enable) iconView = checkBBIcon(NEUTRINO_ICON_RADIOTEXTGET, &w, &h); break; case CInfoViewerBB::ICON_DD: if( g_settings.infobar_show_dd_available ) iconView = checkBBIcon(NEUTRINO_ICON_DD, &w, &h); break; case CInfoViewerBB::ICON_16_9: //no radio if (neutrino->getMode() != NeutrinoMessages::mode_radio) iconView = checkBBIcon(NEUTRINO_ICON_16_9, &w, &h); break; case CInfoViewerBB::ICON_RES: //no radio if ((g_settings.infobar_show_res < 2) && (neutrino->getMode() != NeutrinoMessages::mode_radio)) iconView = checkBBIcon(NEUTRINO_ICON_RESOLUTION_1280, &w, &h); break; case CInfoViewerBB::ICON_CA: if (g_settings.casystem_display == 2) iconView = checkBBIcon(NEUTRINO_ICON_SCRAMBLED2, &w, &h); break; case CInfoViewerBB::ICON_TUNER: if (CFEManager::getInstance()->getEnabledCount() > 1 && g_settings.infobar_show_tuner == 1) iconView = checkBBIcon(NEUTRINO_ICON_TUNER_1, &w, &h); break; default: break; } if (iconView) { bbIconMinX -= w + 2; bbIconInfo[i].x = bbIconMinX; bbIconInfo[i].h = h; } else bbIconInfo[i].x = -1; } for (int i = 0; i < CInfoViewerBB::ICON_MAX; i++) { if (bbIconInfo[i].x != -1) bbIconMaxH = std::max(bbIconMaxH, bbIconInfo[i].h); } if (g_settings.infobar_show_sysfs_hdd) bbIconMinX -= hddwidth + 2; } void CInfoViewerBB::getBBButtonInfo() { bbButtonMaxH = 0; bbButtonMaxX = g_InfoViewer->ChanInfoX; int bbButtonMaxW = 0; int mode = NeutrinoMessages::mode_unknown; for (int i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { int w = 0, h = 0; bool active; std::string text, icon; switch (i) { case CInfoViewerBB::BUTTON_EPG: icon = NEUTRINO_ICON_BUTTON_RED; frameBuffer->getIconSize(icon.c_str(), &w, &h); text = CUserMenu::getUserMenuButtonName(0, active); if (!text.empty()) break; text = g_settings.usermenu[SNeutrinoSettings::BUTTON_RED]->title; if (text.empty()) text = g_Locale->getText(LOCALE_INFOVIEWER_EVENTLIST); break; case CInfoViewerBB::BUTTON_AUDIO: icon = NEUTRINO_ICON_BUTTON_GREEN; frameBuffer->getIconSize(icon.c_str(), &w, &h); text = CUserMenu::getUserMenuButtonName(1, active); mode = CNeutrinoApp::getInstance()->getMode(); if (!text.empty() && mode < NeutrinoMessages::mode_audio) break; text = g_settings.usermenu[SNeutrinoSettings::BUTTON_GREEN]->title; if (text == g_Locale->getText(LOCALE_AUDIOSELECTMENUE_HEAD)) text = ""; if ((mode == NeutrinoMessages::mode_ts || mode == NeutrinoMessages::mode_webtv || mode == NeutrinoMessages::mode_audio) && !CMoviePlayerGui::getInstance().timeshift) { text = CMoviePlayerGui::getInstance().CurrentAudioName(); } else if (!g_RemoteControl->current_PIDs.APIDs.empty()) { int selected = g_RemoteControl->current_PIDs.PIDs.selected_apid; if (text.empty()){ text = g_RemoteControl->current_PIDs.APIDs[selected].desc; } } break; case CInfoViewerBB::BUTTON_SUBS: icon = NEUTRINO_ICON_BUTTON_YELLOW; frameBuffer->getIconSize(icon.c_str(), &w, &h); text = CUserMenu::getUserMenuButtonName(2, active); if (!text.empty()) break; text = g_settings.usermenu[SNeutrinoSettings::BUTTON_YELLOW]->title; if (text.empty()) text = g_Locale->getText((g_RemoteControl->are_subchannels) ? LOCALE_INFOVIEWER_SUBSERVICE : LOCALE_INFOVIEWER_SELECTTIME); break; case CInfoViewerBB::BUTTON_FEAT: icon = NEUTRINO_ICON_BUTTON_BLUE; frameBuffer->getIconSize(icon.c_str(), &w, &h); text = CUserMenu::getUserMenuButtonName(3, active); if (!text.empty()) break; text = g_settings.usermenu[SNeutrinoSettings::BUTTON_BLUE]->title; if (text.empty()) text = g_Locale->getText(LOCALE_INFOVIEWER_STREAMINFO); break; default: break; } bbButtonInfo[i].w = g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->getRenderWidth(text) + w + 10; bbButtonInfo[i].cx = w + 5; bbButtonInfo[i].h = h; bbButtonInfo[i].text = text; bbButtonInfo[i].icon = icon; bbButtonInfo[i].active = active; } // Calculate position/size of buttons minX = std::min(bbIconMinX, g_InfoViewer->ChanInfoX + (((g_InfoViewer->BoxEndX - g_InfoViewer->ChanInfoX) * 75) / 100)); int MaxBr = minX - (g_InfoViewer->ChanInfoX + 10); bbButtonMaxX = g_InfoViewer->ChanInfoX + 10; int br = 0, count = 0; for (int i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { if ((i == CInfoViewerBB::BUTTON_SUBS) && (g_RemoteControl->subChannels.empty())) { // no subchannels bbButtonInfo[i].paint = false; // bbButtonInfo[i].x = -1; // continue; } else { count++; bbButtonInfo[i].paint = true; br += bbButtonInfo[i].w; bbButtonInfo[i].x = bbButtonMaxX; bbButtonMaxX += bbButtonInfo[i].w; bbButtonMaxW = std::max(bbButtonMaxW, bbButtonInfo[i].w); } } if (br > MaxBr) printf("[infoviewer_bb:%s#%d] width br (%d) > MaxBr (%d) count %d\n", __func__, __LINE__, br, MaxBr, count); #if 0 int Btns = 0; // counting buttons for (int i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { if (bbButtonInfo[i].x != -1) { Btns++; } } bbButtonMaxX = g_InfoViewer->ChanInfoX + 10; bbButtonInfo[CInfoViewerBB::BUTTON_EPG].x = bbButtonMaxX; bbButtonInfo[CInfoViewerBB::BUTTON_FEAT].x = minX - bbButtonInfo[CInfoViewerBB::BUTTON_FEAT].w; int x1 = bbButtonInfo[CInfoViewerBB::BUTTON_EPG].x + bbButtonInfo[CInfoViewerBB::BUTTON_EPG].w; int rest = bbButtonInfo[CInfoViewerBB::BUTTON_FEAT].x - x1; if (Btns < 4) { rest -= bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].w; bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].x = x1 + rest / 2; } else { rest -= bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].w + bbButtonInfo[CInfoViewerBB::BUTTON_SUBS].w; rest = rest / 3; bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].x = x1 + rest; bbButtonInfo[CInfoViewerBB::BUTTON_SUBS].x = bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].x + bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].w + rest; } #endif bbButtonMaxX = g_InfoViewer->ChanInfoX + 10; int step = MaxBr / 4; if (count > 0) { /* avoid div-by-zero :-) */ step = MaxBr / count; count = 0; for (int i = 0; i < BUTTON_MAX; i++) { if (!bbButtonInfo[i].paint) continue; bbButtonInfo[i].x = bbButtonMaxX + step * count; // printf("%s: i = %d count = %d b.x = %d\n", __func__, i, count, bbButtonInfo[i].x); count++; } } else { printf("[infoviewer_bb:%s#%d: count <= 0???\n", __func__, __LINE__); bbButtonInfo[BUTTON_EPG].x = bbButtonMaxX; bbButtonInfo[BUTTON_AUDIO].x = bbButtonMaxX + step; bbButtonInfo[BUTTON_SUBS].x = bbButtonMaxX + 2*step; bbButtonInfo[BUTTON_FEAT].x = bbButtonMaxX + 3*step; } } void CInfoViewerBB::showBBButtons(const int modus) { if (!is_visible) return; int i; bool paint = false; if (g_settings.volume_pos == CVolumeBar::VOLUMEBAR_POS_BOTTOM_LEFT || g_settings.volume_pos == CVolumeBar::VOLUMEBAR_POS_BOTTOM_RIGHT || g_settings.volume_pos == CVolumeBar::VOLUMEBAR_POS_BOTTOM_CENTER || g_settings.volume_pos == CVolumeBar::VOLUMEBAR_POS_HIGHER_CENTER) g_InfoViewer->isVolscale = CVolume::getInstance()->hideVolscale(); else g_InfoViewer->isVolscale = false; getBBButtonInfo(); for (i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { if (tmp_bbButtonInfoText[i] != bbButtonInfo[i].text) { paint = true; break; } } if (paint) { int last_x = minX; frameBuffer->paintBoxRel(g_InfoViewer->ChanInfoX, BBarY, minX - g_InfoViewer->ChanInfoX, InfoHeightY_Info, COL_INFOBAR_BUTTONS_BACKGROUND, RADIUS_LARGE, CORNER_BOTTOM); //round for (i = BUTTON_MAX; i > 0;) { --i; if ((bbButtonInfo[i].x <= g_InfoViewer->ChanInfoX) || (bbButtonInfo[i].x >= g_InfoViewer->BoxEndX) || (!bbButtonInfo[i].paint)) continue; if (bbButtonInfo[i].x > 0) { if (bbButtonInfo[i].x + bbButtonInfo[i].w > last_x) /* text too long */ bbButtonInfo[i].w = last_x - bbButtonInfo[i].x; last_x = bbButtonInfo[i].x; if (bbButtonInfo[i].w - bbButtonInfo[i].cx <= 0) { printf("[infoviewer_bb:%d cannot paint icon %d (not enough space)\n", __LINE__, i); continue; } if (bbButtonInfo[i].active) { frameBuffer->paintIcon(bbButtonInfo[i].icon, bbButtonInfo[i].x, BBarY, InfoHeightY_Info); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(bbButtonInfo[i].x + bbButtonInfo[i].cx, BBarFontY, bbButtonInfo[i].w - bbButtonInfo[i].cx, bbButtonInfo[i].text, COL_INFOBAR_TEXT); } } } if (modus == CInfoViewerBB::BUTTON_AUDIO) showIcon_DD(); for (i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { tmp_bbButtonInfoText[i] = bbButtonInfo[i].text; } } if (g_InfoViewer->isVolscale) CVolume::getInstance()->showVolscale(); } void CInfoViewerBB::showBBIcons(const int modus, const std::string & icon) { if ((bbIconInfo[modus].x <= g_InfoViewer->ChanInfoX) || (bbIconInfo[modus].x >= g_InfoViewer->BoxEndX)) return; if ((modus >= CInfoViewerBB::ICON_SUBT) && (modus < CInfoViewerBB::ICON_MAX) && (bbIconInfo[modus].x != -1) && (is_visible)) { frameBuffer->paintIcon(icon, bbIconInfo[modus].x, BBarY, InfoHeightY_Info, 1, true, !g_settings.gradiant, COL_INFOBAR_BUTTONS_BACKGROUND); } } void CInfoViewerBB::paintshowButtonBar() { if (!is_visible) return; getBBIconInfo(); for (int i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { tmp_bbButtonInfoText[i] = ""; } g_InfoViewer->sec_timer_id = g_RCInput->addTimer(1*1000*1000, false); if (g_settings.casystem_display < 2) paintCA_bar(0,0); frameBuffer->paintBoxRel(g_InfoViewer->ChanInfoX, BBarY, g_InfoViewer->BoxEndX - g_InfoViewer->ChanInfoX, InfoHeightY_Info, COL_INFOBAR_BUTTONS_BACKGROUND, RADIUS_LARGE, CORNER_BOTTOM); //round g_InfoViewer->showSNR(); // Buttons showBBButtons(); // Icons, starting from right showIcon_SubT(); showIcon_VTXT(); showIcon_DD(); showIcon_16_9(); #if 0 scrambledCheck(true); #endif showIcon_CA_Status(0); showIcon_Resolution(); showIcon_Tuner(); showSysfsHdd(); } void CInfoViewerBB::showIcon_SubT() { if (!is_visible) return; bool have_sub = false; CZapitChannel * cc = CNeutrinoApp::getInstance()->channelList->getChannel(CNeutrinoApp::getInstance()->channelList->getActiveChannelNumber()); if (cc && cc->getSubtitleCount()) have_sub = true; showBBIcons(CInfoViewerBB::ICON_SUBT, (have_sub) ? NEUTRINO_ICON_SUBT : NEUTRINO_ICON_SUBT_GREY); } void CInfoViewerBB::showIcon_VTXT() { if (!is_visible) return; showBBIcons(CInfoViewerBB::ICON_VTXT, (g_RemoteControl->current_PIDs.PIDs.vtxtpid != 0) ? NEUTRINO_ICON_VTXT : NEUTRINO_ICON_VTXT_GREY); } void CInfoViewerBB::showIcon_DD() { if (!is_visible || !g_settings.infobar_show_dd_available) return; std::string dd_icon; if ((g_RemoteControl->current_PIDs.PIDs.selected_apid < g_RemoteControl->current_PIDs.APIDs.size()) && (g_RemoteControl->current_PIDs.APIDs[g_RemoteControl->current_PIDs.PIDs.selected_apid].is_ac3)) dd_icon = NEUTRINO_ICON_DD; else dd_icon = g_RemoteControl->has_ac3 ? NEUTRINO_ICON_DD_AVAIL : NEUTRINO_ICON_DD_GREY; showBBIcons(CInfoViewerBB::ICON_DD, dd_icon); } void CInfoViewerBB::showIcon_RadioText(bool rt_available) { if (!is_visible || !g_settings.radiotext_enable) return; std::string rt_icon; if (rt_available) rt_icon = (g_Radiotext->S_RtOsd) ? NEUTRINO_ICON_RADIOTEXTGET : NEUTRINO_ICON_RADIOTEXTWAIT; else rt_icon = NEUTRINO_ICON_RADIOTEXTOFF; showBBIcons(CInfoViewerBB::ICON_RT, rt_icon); } void CInfoViewerBB::showIcon_16_9() { if (!is_visible) return; if ((g_InfoViewer->aspectRatio == 0) || ( g_RemoteControl->current_PIDs.PIDs.vpid == 0 ) || (g_InfoViewer->aspectRatio != videoDecoder->getAspectRatio())) { if (g_InfoViewer->chanready && g_RemoteControl->current_PIDs.PIDs.vpid > 0 ) { g_InfoViewer->aspectRatio = videoDecoder->getAspectRatio(); } else g_InfoViewer->aspectRatio = 0; showBBIcons(CInfoViewerBB::ICON_16_9, (g_InfoViewer->aspectRatio > 2) ? NEUTRINO_ICON_16_9 : NEUTRINO_ICON_16_9_GREY); } } void CInfoViewerBB::showIcon_Resolution() { if ((!is_visible) || (g_settings.infobar_show_res == 2)) //show resolution icon is off return; if (CNeutrinoApp::getInstance()->getMode() == NeutrinoMessages::mode_radio) return; const char *icon_name = NULL; #if 0 if ((scrambledNoSig) || ((!fta) && (scrambledErr))) #else #if BOXMODEL_UFS910 if (!g_InfoViewer->chanready) #else if (!g_InfoViewer->chanready || videoDecoder->getBlank()) #endif #endif { icon_name = NEUTRINO_ICON_RESOLUTION_000; } else { int xres, yres, framerate; if (g_settings.infobar_show_res == 0) {//show resolution icon on infobar videoDecoder->getPictureInfo(xres, yres, framerate); switch (yres) { case 1920: icon_name = NEUTRINO_ICON_RESOLUTION_1920; break; case 1080: case 1088: icon_name = NEUTRINO_ICON_RESOLUTION_1080; break; case 1440: icon_name = NEUTRINO_ICON_RESOLUTION_1440; break; case 1280: icon_name = NEUTRINO_ICON_RESOLUTION_1280; break; case 720: icon_name = NEUTRINO_ICON_RESOLUTION_720; break; case 704: icon_name = NEUTRINO_ICON_RESOLUTION_704; break; case 576: icon_name = NEUTRINO_ICON_RESOLUTION_576; break; case 544: icon_name = NEUTRINO_ICON_RESOLUTION_544; break; case 528: icon_name = NEUTRINO_ICON_RESOLUTION_528; break; case 480: icon_name = NEUTRINO_ICON_RESOLUTION_480; break; case 382: icon_name = NEUTRINO_ICON_RESOLUTION_382; break; case 352: icon_name = NEUTRINO_ICON_RESOLUTION_352; break; case 288: icon_name = NEUTRINO_ICON_RESOLUTION_288; break; default: icon_name = NEUTRINO_ICON_RESOLUTION_000; break; } } if (g_settings.infobar_show_res == 1) {//show simple resolution icon on infobar videoDecoder->getPictureInfo(xres, yres, framerate); if (yres > 704) icon_name = NEUTRINO_ICON_RESOLUTION_HD; else if (yres >= 288) icon_name = NEUTRINO_ICON_RESOLUTION_SD; else icon_name = NEUTRINO_ICON_RESOLUTION_000; } } showBBIcons(CInfoViewerBB::ICON_RES, icon_name); } void CInfoViewerBB::showOne_CAIcon() { std::string sIcon = ""; #if 0 if (CNeutrinoApp::getInstance()->getMode() != NeutrinoMessages::mode_radio) { if (scrambledNoSig) sIcon = NEUTRINO_ICON_SCRAMBLED2_BLANK; else { if (fta) sIcon = NEUTRINO_ICON_SCRAMBLED2_GREY; else sIcon = (scrambledErr) ? NEUTRINO_ICON_SCRAMBLED2_RED : NEUTRINO_ICON_SCRAMBLED2; } } else #endif sIcon = (fta) ? NEUTRINO_ICON_SCRAMBLED2_GREY : NEUTRINO_ICON_SCRAMBLED2; showBBIcons(CInfoViewerBB::ICON_CA, sIcon); } void CInfoViewerBB::showIcon_Tuner() { if (CFEManager::getInstance()->getEnabledCount() <= 1 || !g_settings.infobar_show_tuner) return; std::string icon_name; switch (CFEManager::getInstance()->getLiveFE()->getNumber()) { case 1: icon_name = NEUTRINO_ICON_TUNER_2; break; case 2: icon_name = NEUTRINO_ICON_TUNER_3; break; case 3: icon_name = NEUTRINO_ICON_TUNER_4; break; case 0: default: icon_name = NEUTRINO_ICON_TUNER_1; break; } showBBIcons(CInfoViewerBB::ICON_TUNER, icon_name); } void CInfoViewerBB::showSysfsHdd() { if (g_settings.infobar_show_sysfs_hdd) { //sysFS info int percent = 0; uint64_t t, u; #if HAVE_SPARK_HARDWARE || HAVE_DUCKBOX_HARDWARE if (get_fs_usage("/var", t, u)) #else if (get_fs_usage("/", t, u)) #endif percent = (int)((u * 100ULL) / t); showBarSys(percent); showBarHdd(cHddStat::getInstance()->getPercent()); } } void CInfoViewerBB::showBarSys(int percent) { if (is_visible){ sysscale->setDimensionsAll(bbIconMinX, BBarY + InfoHeightY_Info / 2 - 2 - 6, hddwidth, 6); sysscale->setValues(percent, 100); sysscale->paint(); } } void CInfoViewerBB::showBarHdd(int percent) { if (is_visible) { if (percent >= 0){ hddscale->setDimensionsAll(bbIconMinX, BBarY + InfoHeightY_Info / 2 + 2 + 0, hddwidth, 6); hddscale->setValues(percent, 100); hddscale->paint(); }else { frameBuffer->paintBoxRel(bbIconMinX, BBarY + InfoHeightY_Info / 2 + 2 + 0, hddwidth, 6, COL_INFOBAR_BUTTONS_BACKGROUND); hddscale->reset(); } } } void CInfoViewerBB::paint_ca_icons(int caid, const char *icon, int &icon_space_offset) { char buf[20]; int endx = g_InfoViewer->BoxEndX - 10; int py = g_InfoViewer->BoxEndY + 2; /* hand-crafted, should be automatic */ int px = 0; static map<int, std::pair<int,const char*> > icon_map; const int icon_space = 5, icon_number = 10; static int icon_offset[icon_number] = {0,0,0,0,0,0,0,0,0,0}; static int icon_sizeW [icon_number] = {0,0,0,0,0,0,0,0,0,0}; static bool init_flag = false; if (!init_flag) { init_flag = true; int icon_sizeH = 0, index = 0; map<int, std::pair<int,const char*> >::const_iterator it; icon_map[0x0E00] = std::make_pair(index++,"powervu"); icon_map[0x4A00] = std::make_pair(index++,"d"); icon_map[0x2600] = std::make_pair(index++,"biss"); icon_map[0x0600] = std::make_pair(index++,"ird"); icon_map[0x0100] = std::make_pair(index++,"seca"); icon_map[0x0500] = std::make_pair(index++,"via"); icon_map[0x1800] = std::make_pair(index++,"nagra"); icon_map[0x0B00] = std::make_pair(index++,"conax"); icon_map[0x0D00] = std::make_pair(index++,"cw"); icon_map[0x0900] = std::make_pair(index ,"nds"); for (it=icon_map.begin(); it!=icon_map.end(); ++it) { snprintf(buf, sizeof(buf), "%s_%s", (*it).second.second, icon); frameBuffer->getIconSize(buf, &icon_sizeW[(*it).second.first], &icon_sizeH); } for (int j = 0; j < icon_number; j++) { for (int i = j; i < icon_number; i++) { icon_offset[j] += icon_sizeW[i] + icon_space; } } } caid &= 0xFF00; if (icon_offset[icon_map[caid].first] == 0) return; if (g_settings.casystem_display == 0) { px = endx - (icon_offset[icon_map[caid].first] - icon_space ); } else { icon_space_offset += icon_sizeW[icon_map[caid].first]; px = endx - icon_space_offset; icon_space_offset += 4; } if (px) { snprintf(buf, sizeof(buf), "%s_%s", icon_map[caid].second, icon); if ((px >= (endx-8)) || (px <= 0)) printf("#####[%s:%d] Error paint icon %s, px: %d, py: %d, endx: %d, icon_offset: %d\n", __FUNCTION__, __LINE__, buf, px, py, endx, icon_offset[icon_map[caid].first]); else frameBuffer->paintIcon(buf, px, py); } } void CInfoViewerBB::showIcon_CA_Status(int /*notfirst*/) { if (!is_visible) return; if (g_settings.casystem_display == 3) return; if(NeutrinoMessages::mode_ts == CNeutrinoApp::getInstance()->getMode() && !CMoviePlayerGui::getInstance().timeshift){ if (g_settings.casystem_display == 2) { fta = true; showOne_CAIcon(); } return; } int caids[] = { 0x900, 0xD00, 0xB00, 0x1800, 0x0500, 0x0100, 0x600, 0x2600, 0x4a00, 0x0E00 }; const char *white = "white"; const char *yellow = "yellow"; const char *green = "green"; int icon_space_offset = 0; const char *ecm_info_f = "/tmp/ecm.info"; if(!g_InfoViewer->chanready) { if (g_settings.infoviewer_ecm_info == 1) frameBuffer->paintBackgroundBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-185, 225, g_InfoViewer->ChanHeight+105); else if (g_settings.infoviewer_ecm_info == 2) frameBuffer->paintBackgroundBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-185, 225, g_InfoViewer->ChanHeight+105); unlink(ecm_info_f); if (g_settings.casystem_display == 2) { fta = true; showOne_CAIcon(); } else if(g_settings.casystem_display == 0) { for (int i = 0; i < (int)(sizeof(caids)/sizeof(int)); i++) { paint_ca_icons(caids[i], white, icon_space_offset); } } return; } CZapitChannel * channel = CZapit::getInstance()->GetCurrentChannel(); if(!channel) return; if (g_settings.casystem_display == 2) { fta = channel->camap.empty(); showOne_CAIcon(); return; } emu = 0; if(file_exists("/var/etc/.mgcamd")) emu = 1; else if(file_exists("/var/etc/.gbox")) emu = 2; else if(file_exists("/var/etc/.oscam")) emu = 3; else if(file_exists("/var/etc/.osemu")) emu = 4; else if(file_exists("/var/etc/.wicard")) emu = 5; else if(file_exists("/var/etc/.camd3")) emu = 6; if ( (file_exists(ecm_info_f)) && ((g_settings.infoviewer_ecm_info == 1) || (g_settings.infoviewer_ecm_info == 2)) ) paintECM(); if ((g_settings.casystem_display == 0) || (g_settings.casystem_display == 1)) { FILE* fd = fopen (ecm_info_f, "r"); int ecm_caid = 0; int decMode = 0; bool mgcamd_emu = emu==1 ? true:false; char ecm_pid[16] = {0}; if (fd) { char *buffer = NULL, *card = NULL; size_t len = 0; ssize_t read; char decode[16] = {0}; while ((read = getline(&buffer, &len, fd)) != -1) { if ((sscanf(buffer, "=%*[^9-0]%x", &ecm_caid) == 1) || (sscanf(buffer, "caid: %x", &ecm_caid) == 1)) { if (mgcamd_emu && ((ecm_caid & 0xFF00) == 0x1700)){ sscanf(buffer, "=%*[^','], pid %6s",ecm_pid); } continue; } else if ((sscanf(buffer, "decode:%15s", decode) == 1) || (sscanf(buffer, "source:%15s", decode) == 2) || (sscanf(buffer, "from: %15s", decode) == 3)) { card = strstr(buffer, "127.0.0.1"); break; } } fclose (fd); if (buffer) free (buffer); if (strncasecmp(decode, "net", 3) == 0) decMode = (card == NULL) ? 1 : 3; // net == 1, card == 3 else if ((strncasecmp(decode, "emu", 3) == 0) || (strncasecmp(decode, "Net", 1) == 0) || (strncasecmp(decode, "int", 3) == 0) || (sscanf(decode, "protocol: char*", 3) == 0) || (sscanf(decode, "from: char*", 3) == 0) || (strncasecmp(decode, "cache", 5) == 0) || (strstr(decode, "/" ) != NULL)) decMode = 2; //emu else if ((strncasecmp(decode, "com", 3) == 0) || (strncasecmp(decode, "slot", 4) == 0) || (strncasecmp(decode, "local", 5) == 0)) decMode = 3; //card } if (mgcamd_emu && ((ecm_caid & 0xFF00) == 0x1700)) { const char *pid_info_f = "/tmp/pid.info"; FILE* pidinfo = fopen (pid_info_f, "r"); if (pidinfo){ char *buf_mg = NULL; size_t mg_len = 0; ssize_t mg_read; while ((mg_read = getline(&buf_mg, &mg_len, pidinfo)) != -1){ if(strcasestr(buf_mg, ecm_pid)){ int pidnagra = 0; sscanf(buf_mg, "%*[^':']: CaID: %x *", &pidnagra); ecm_caid = pidnagra; } } fclose (pidinfo); if (buf_mg) free (buf_mg); } } if ((ecm_caid & 0xFF00) == 0x1700 ) { bool nagra_found = false; bool beta_found = false; for(casys_map_iterator_t it = channel->camap.begin(); it != channel->camap.end(); ++it) { int caid = (*it) & 0xFF00; if(caid == 0x1800) nagra_found = true; if (caid == 0x1700) beta_found = true; } if(beta_found) ecm_caid = 0x600; else if(!beta_found && nagra_found) ecm_caid = 0x1800; } paintEmuIcons(decMode); for (int i = 0; i < (int)(sizeof(caids)/sizeof(int)); i++) { bool found = false; for(casys_map_iterator_t it = channel->camap.begin(); it != channel->camap.end(); ++it) { int caid = (*it) & 0xFF00; if (caid == 0x1700) caid = 0x0600; if((found = (caid == caids[i]))) break; } if(g_settings.casystem_display == 0) paint_ca_icons(caids[i], (found ? (caids[i] == (ecm_caid & 0xFF00) ? green : yellow) : white), icon_space_offset); else if(found) paint_ca_icons(caids[i], (caids[i] == (ecm_caid & 0xFF00) ? green : yellow), icon_space_offset); } } } void CInfoViewerBB::paintCA_bar(int left, int right) { int xcnt = (g_InfoViewer->BoxEndX - g_InfoViewer->ChanInfoX) / 4; int ycnt = bottom_bar_offset / 4; if (right) right = xcnt - ((right/4)+1); if (left) left = xcnt - ((left/4)-1); frameBuffer->paintBox(g_InfoViewer->ChanInfoX + (right*4), g_InfoViewer->BoxEndY, g_InfoViewer->BoxEndX - (left*4), g_InfoViewer->BoxEndY + bottom_bar_offset, (g_settings.dotmatrix == 1) ? COL_BLACK : COL_INFOBAR_PLUS_0); if (g_settings.dotmatrix == 1) { if (left) left -= 1; for (int i = 0 + right; i < xcnt - left; i++) { for (int j = 0; j < ycnt; j++) { frameBuffer->paintBoxRel((g_InfoViewer->ChanInfoX + 2) + i*4, g_InfoViewer->BoxEndY + 2 + j*4, 2, 2, COL_INFOBAR_PLUS_1); } } } } void CInfoViewerBB::changePB() { hddwidth = frameBuffer->getScreenWidth(true) * ((g_settings.screen_preset == 1) ? 10 : 8) / 128; /* 80(CRT)/100(LCD) pix if screen is 1280 wide */ if (!hddscale) { hddscale = new CProgressBar(); hddscale->setType(CProgressBar::PB_REDRIGHT); } if (!sysscale) { sysscale = new CProgressBar(); sysscale->setType(CProgressBar::PB_REDRIGHT); } } void CInfoViewerBB::reset_allScala() { hddscale->reset(); sysscale->reset(); //lasthdd = lastsys = -1; } void CInfoViewerBB::setBBOffset() { bottom_bar_offset = (g_settings.casystem_display < 2) ? 22 : 0; } void* CInfoViewerBB::scrambledThread(void *arg) { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); CInfoViewerBB *infoViewerBB = static_cast<CInfoViewerBB*>(arg); while(1) { if (infoViewerBB->is_visible) infoViewerBB->scrambledCheck(); usleep(500*1000); } return 0; } void CInfoViewerBB::scrambledCheck(bool force) { scrambledErr = false; scrambledNoSig = false; if (videoDecoder->getBlank()) { if (videoDecoder->getPlayState()) scrambledErr = true; else scrambledNoSig = true; } if ((scrambledErr != scrambledErrSave) || (scrambledNoSig != scrambledNoSigSave) || force) { showIcon_CA_Status(0); showIcon_Resolution(); scrambledErrSave = scrambledErr; scrambledNoSigSave = scrambledNoSig; } } void CInfoViewerBB::paintEmuIcons(int decMode) { char buf[20]; int py = g_InfoViewer->BoxEndY + 2; /* hand-crafted, should be automatic */ const char emu_green[] = "green"; const char emu_gray[] = "white"; const char emu_yellow[] = "yellow"; enum E{ GBOX,MGCAMD,OSCAM,OSEMU,WICARD,CAMD3,NET,EMU,CARD }; static int emus_icon_sizeW[CARD+1] = {0}; const char *icon_emu[CARD+1] = {"gbox", "mgcamd", "oscam", "osemu", "wicard", "camd3", "net", "emu", "card"}; int icon_sizeH = 0; static int ga = g_InfoViewer->ChanInfoX+30+16; if (emus_icon_sizeW[GBOX] == 0) { for (E e=GBOX; e <= CARD; e = E(e+1)) { snprintf(buf, sizeof(buf), "%s_%s", icon_emu[e], emu_green); frameBuffer->getIconSize(buf, &emus_icon_sizeW[e], &icon_sizeH); ga+=emus_icon_sizeW[e]; } } struct stat sb; int icon_emuX = g_InfoViewer->ChanInfoX ; static int icon_offset = 0; int icon_flag = 0; // gray = 0, yellow = 1, green = 2 if ((g_settings.casystem_display == 1) && (icon_offset)) { paintCA_bar(icon_offset, 0); icon_offset = 0; } for (E e = GBOX; e <= CARD; e = E(e+1)) { switch (e) { case GBOX: case MGCAMD: case OSCAM: case OSEMU: case CAMD3: case WICARD: snprintf(buf, sizeof(buf), "/var/etc/.%s", icon_emu[e]); icon_flag = (stat(buf, &sb) == -1) ? 0 : decMode ? 2 : 1; break; case NET: icon_flag = (decMode == 1) ? 2 : 0; break; case EMU: icon_flag = (decMode == 2) ? 2 : 0; break; case CARD: icon_flag = (decMode == 3) ? 2 : 0; break; default: break; } if (!((g_settings.casystem_display == 1) && (icon_flag == 0))) { snprintf(buf, sizeof(buf), "%s_%s", icon_emu[e], (icon_flag == 0) ? emu_gray : (icon_flag == 1) ? emu_yellow : emu_green); frameBuffer->paintIcon(buf, icon_emuX, py); if (g_settings.casystem_display == 1) { icon_offset += emus_icon_sizeW[e] + ((g_settings.casystem_display == 1) ? 2 : 2); icon_emuX += icon_offset; } else if (e == 4) icon_emuX += emus_icon_sizeW[e] + 15 + ((g_settings.casystem_display == 1) ? 2 : 2); else icon_emuX += emus_icon_sizeW[e] + ((g_settings.casystem_display == 1) ? 2 : 2); } } } void CInfoViewerBB::painttECMInfo(int xa, const char *info, char *caid, char *decode, char *response, char *prov) { frameBuffer->paintBoxRel(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-120, 220, g_InfoViewer->ChanHeight+40, COL_INFOBAR_SHADOW_PLUS_0, g_settings.rounded_corners ? CORNER_RADIUS_MID : 0); frameBuffer->paintBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-125, 220, g_InfoViewer->ChanHeight+40, COL_INFOBAR_PLUS_0, g_settings.rounded_corners ? CORNER_RADIUS_MID : 0); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-190, g_InfoViewer->BoxStartY-100, xa, info, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-80, 80, "CaID:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-80, 130, caid, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-60, 80, "Decode:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-60, 70, decode, COL_INFOBAR_TEXT, 0, true); if(response[0] != 0 ) { g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-90, g_InfoViewer->BoxStartY-60, 15, "in", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-70, g_InfoViewer->BoxStartY-60, 45, response, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-25, g_InfoViewer->BoxStartY-60, 10, "s", COL_INFOBAR_TEXT, 0, true); } g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-40, 80, "Provider:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-40, 130, prov, COL_INFOBAR_TEXT, 0, true); } void CInfoViewerBB::paintECM() { char caid1[5] = {0}; char pid1[5] = {0}; char net[8] = {0}; char cw0_[8][3]; char cw1_[8][3]; char source1[30] = {0}; char caid2[5] = {0}; char pid2[5] = {0}; char provider1[3] = {0}; char prov1[8] = {0}; char prov2[16] = {0}; char decode1[9] = {0}; char from1[9] = {0}; char response1[10] = {0}; char reader[20] = {0}; char protocol[20] = {0}; char tmp; const char *ecm_info = "/tmp/ecm.info"; FILE* ecminfo = fopen (ecm_info, "r"); bool ecmInfoEmpty = true; if (ecminfo) { char *buffer = NULL; size_t len = 0; ssize_t read; while ((read = getline(&buffer, &len, ecminfo)) != -1) { ecmInfoEmpty = false; if(emu == 1 || emu == 2){ sscanf(buffer, "%*s %*s ECM on CaID 0x%4s, pid 0x%4s", caid1, pid1); // gbox, mgcamd sscanf(buffer, "prov: %06[^',',(]", prov1); // gbox, mgcamd sscanf(buffer, "caid: 0x%4s", caid2); // oscam sscanf(buffer, "pid: 0x%4s", pid2); // oscam sscanf(buffer, "provider: %s", provider1); // gbox sscanf(buffer, "prov: 0x%6s", prov1); // oscam sscanf(buffer, "prov: 0x%s", prov2); // oscam sscanf(buffer, "decode:%15s", decode1); // gbox sscanf(buffer, "from: %29s", net); // oscam sscanf(buffer, "from: %29s", source1); // oscam sscanf(buffer, "from: %s", from1); // oscam } if(emu == 2){ sscanf(buffer, "decode:%8s", source1); // gbox sscanf(buffer, "response:%05s", response1); // gbox sscanf(buffer, "provider: %02s", prov1); // gbox } if(emu == 1) sscanf(buffer, "source: %08s", source1); // mgcamd sscanf(buffer, "caid: 0x%4s", caid1); // oscam sscanf(buffer, "pid: 0x%4s", pid1); // oscam sscanf(buffer, "from: %29s", source1); // oscam sscanf(buffer, "prov: 0x%6s", prov1); // oscam sscanf(buffer, "ecm time: %9s",response1); // oscam sscanf(buffer, "reader: %18s", reader); // oscam sscanf(buffer, "protocol: %18s", protocol); // oscam if(emu == 3){ sscanf(buffer, "source: %08s", source1); // osca, sscanf(buffer, "caid: 0x%4s", caid1); // oscam sscanf(buffer, "pid: 0x%4s", pid1); // oscam sscanf(buffer, "from: %29s", source1); // oscam sscanf(buffer, "prov: 0x%6s", prov1); // oscam sscanf(buffer, "ecm time: %9s",response1); // oscam sscanf(buffer, "reader: %18s", reader); // oscam sscanf(buffer, "protocol: %18s", protocol); // oscam } sscanf(buffer, "%c%c0: %02s %02s %02s %02s %02s %02s %02s %02s",&tmp,&tmp, cw0_[0], cw0_[1], cw0_[2], cw0_[3], cw0_[4], cw0_[5], cw0_[6], cw0_[7]); // gbox, mgcamd oscam sscanf(buffer, "%c%c1: %02s %02s %02s %02s %02s %02s %02s %02s",&tmp,&tmp, cw1_[0], cw1_[1], cw1_[2], cw1_[3], cw1_[4], cw1_[5], cw1_[6], cw1_[7]); // gbox, mgcamd oscam sscanf(buffer, "%*s %*s ECM on CaID 0x%4s, pid 0x%4s", caid1, pid1); // gbox, mgcamd sscanf(buffer, "caid: 0x%4s", caid2); // oscam sscanf(buffer, "pid: 0x%4s", pid2); // oscam sscanf(buffer, "provider: %s", provider1); // gbox sscanf(buffer, "prov: %[^',']", prov1); // gbox, mgcamd sscanf(buffer, "prov: 0x%s", prov2); // oscam sscanf(buffer, "decode:%15s", decode1); // gbox sscanf(buffer, "source: %s", source1); // mgcamd sscanf(buffer, "from: %s", from1); // oscam } fclose (ecminfo); if (buffer) free (buffer); if(ecmInfoEmpty) return; if(emu == 3){ std::string kname = source1; size_t pos1 = kname.find_last_of("/")+1; size_t pos2 = kname.find_last_of("."); if(pos2>pos1) kname=kname.substr(pos1, pos2-pos1); snprintf(source1,sizeof(source1),"%s",kname.c_str()); } if(emu == 2 && response1[0] != 0){ char tmp_res[10] = ""; memcpy(tmp_res,response1,sizeof(tmp_res)); if(response1[3] != 0){ snprintf(response1,sizeof(response1),"%c.%s",tmp_res[0],&tmp_res[1]); } else snprintf(response1,sizeof(response1),"0.%s",tmp_res); } // tmp_cw0=(cw0_[0][0]<<8)+cw0_[0][1]; // tmp_cw1=(cw1_[0][0]<<8)+cw1_[0][1]; // if((tmp_cw0+tmp_cw1) != (cw0+cw1)){ // cw0=tmp_cw0; // cw1=tmp_cw1; // } } else { if (g_settings.infoviewer_ecm_info == 1) frameBuffer->paintBackgroundBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-185, 225, g_InfoViewer->ChanHeight+105); else frameBuffer->paintBackgroundBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-185, 225, g_InfoViewer->ChanHeight+105); return; } if (prov1[strlen(prov1)-1] == '\n') prov1[strlen(prov1)-1] = '\0'; char share_at[32] = {0}; char share_card[5] = {0}; char share_id[5] = {0}; int share_net = 0; const char *share_info = "/tmp/share.info"; FILE* shareinfo = fopen (share_info, "r"); if (shareinfo) { char *buffer = NULL; size_t len = 0; ssize_t read; while ((read = getline(&buffer, &len, shareinfo)) != -1) { sscanf(buffer, "CardID %*s at %s Card %s Sl:%*s Lev:%*s dist:%*s id:%s", share_at, share_card, share_id); if ((strncmp(caid1, share_card, 4) == 0) && (strncmp(prov1, share_id, 4) == 0)) { share_net = 1; break; } } fclose (shareinfo); if (buffer) free (buffer); } const char *gbox_info = "<< Gbox-ECM-Info >>"; const char *mgcamd_info = "<< Mgcamd-ECM-Info >>"; const char *oscam_info = "<< OScam-ECM-Info >>"; if (g_settings.infoviewer_ecm_info == 1) { if (emu == 2) { painttECMInfo(160, gbox_info, caid1, source1, response1, prov1); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-20, 80, "From:", COL_INFOBAR_TEXT, 0, true); if (strstr(source1, "Net" ) != NULL) { if (share_net == 1) g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-20, 130, share_at, COL_INFOBAR_TEXT, 0, true); else g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-20, 130, "N/A", COL_INFOBAR_TEXT, 0, true); } else g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-20, 130, "127.0.0.1", COL_INFOBAR_TEXT, 0, true); } else if ((emu == 1) || (emu == 3)) { painttECMInfo((emu == 1) ?180:190,(emu == 1)? mgcamd_info:oscam_info, caid1, source1, response1, prov1); if(emu == 3){ g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-20, 80, "Reader:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-20, 130, reader, COL_INFOBAR_TEXT, 0, true); } } } if (g_settings.infoviewer_ecm_info == 2) { bool gboxECM = false; int gboxoffset = 0,i=0; if (emu == 2){ gboxECM = true; gboxoffset = 20; } frameBuffer->paintBoxRel(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-180, 220, g_InfoViewer->ChanHeight+80+gboxoffset, COL_INFOBAR_SHADOW_PLUS_0, g_settings.rounded_corners ? CORNER_RADIUS_MID : 0); frameBuffer->paintBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-185, 220, g_InfoViewer->ChanHeight+80+gboxoffset, COL_INFOBAR_PLUS_0, g_settings.rounded_corners ? CORNER_RADIUS_MID : 0); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-140, 80, "CaID:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-120, 80, "PID:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-100, 80, "Decode:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-80, 80, "Provider:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-60, 42, "CW0:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-40, 42, "CW1:", COL_INFOBAR_TEXT, 0, true); for(i=0;i<8;i++){ g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-(173-(i*21)), g_InfoViewer->BoxStartY-60, 21, cw0_[i], COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-(173-(i*21)), g_InfoViewer->BoxStartY-40, 21, cw1_[i], COL_INFOBAR_TEXT, 0, true); } if (gboxECM) { g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-190, g_InfoViewer->BoxStartY-160, 160, gbox_info, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-140, 80, caid1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-120, 80, pid1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-100, 70, source1, COL_INFOBAR_TEXT, 0, true); if(response1[0] != 0) { g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-90, g_InfoViewer->BoxStartY-100, 15, "in", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-70, g_InfoViewer->BoxStartY-100, 45, response1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-25, g_InfoViewer->BoxStartY-100, 10, "s", COL_INFOBAR_TEXT, 0, true); } g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-80, 130, prov1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-20, 50, "From:", COL_INFOBAR_TEXT, 0, true); if (strstr(source1, "Net") != NULL) { if (share_net == 1) g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-173, g_InfoViewer->BoxStartY-20, 160, share_at, COL_INFOBAR_TEXT, 0, true); else g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-173, g_InfoViewer->BoxStartY-20, 160, "N/A", COL_INFOBAR_TEXT, 0, true); } else g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-173, g_InfoViewer->BoxStartY-20, 160, "127.0.0.1", COL_INFOBAR_TEXT, 0, true); } else if ((emu == 1) || (emu == 3)) { g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-200, g_InfoViewer->BoxStartY-160, 190,(emu == 1)? mgcamd_info:oscam_info, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-140, 80, caid1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-120, 80, pid1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-100, 70, source1, COL_INFOBAR_TEXT, 0, true); //g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-70, g_InfoViewer->BoxStartY-100, 20, "", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-55, g_InfoViewer->BoxStartY-100, 70, response1, COL_INFOBAR_TEXT, 0, true); //g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-25, g_InfoViewer->BoxStartY-100, 20, "", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-80, 130, prov1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-140, 80, "CaID:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-140, 130, caid2, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-120, 80, "PID:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-120, 130, pid2, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-100, 80, "Decode:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-100, 130, from1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-80, 80, "Provider:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-80, 130, prov2, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-60, 42, "CW0:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-40, 42, "CW1:", COL_INFOBAR_TEXT, 0, true); } } }
FFTEAM/FFTEAM-MP3-Martii
src/gui/infoviewer_bb.cpp
C++
gpl-3.0
47,910
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.batik.dom.svg; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import org.apache.batik.css.engine.SVGCSSEngine; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.svg.SVGElement; import org.w3c.dom.svg.SVGException; import org.w3c.dom.svg.SVGFitToViewBox; import org.w3c.dom.svg.SVGMatrix; import org.w3c.dom.svg.SVGRect; /** * This class provides support for the SVGLocatable interface. * * @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a> * @version $Id$ */ public class SVGLocatableSupport { /** * Creates a new SVGLocatable element. */ public SVGLocatableSupport() { } /** * To implement {@link * org.w3c.dom.svg.SVGLocatable#getNearestViewportElement()}. */ public static SVGElement getNearestViewportElement(Element e) { Element elt = e; while (elt != null) { elt = SVGCSSEngine.getParentCSSStylableElement(elt); if (elt instanceof SVGFitToViewBox) { break; } } return (SVGElement)elt; } /** * To implement {@link * org.w3c.dom.svg.SVGLocatable#getFarthestViewportElement()}. */ public static SVGElement getFarthestViewportElement(Element elt) { return (SVGElement)elt.getOwnerDocument().getDocumentElement(); } /** * To implement {@link org.w3c.dom.svg.SVGLocatable#getBBox()}. */ public static SVGRect getBBox(Element elt) { final SVGOMElement svgelt = (SVGOMElement)elt; SVGContext svgctx = svgelt.getSVGContext(); if (svgctx == null) return null; if (svgctx.getBBox() == null) return null; return new SVGRect() { public float getX() { return (float)svgelt.getSVGContext().getBBox().getX(); } public void setX(float x) throws DOMException { throw svgelt.createDOMException (DOMException.NO_MODIFICATION_ALLOWED_ERR, "readonly.rect", null); } public float getY() { return (float)svgelt.getSVGContext().getBBox().getY(); } public void setY(float y) throws DOMException { throw svgelt.createDOMException (DOMException.NO_MODIFICATION_ALLOWED_ERR, "readonly.rect", null); } public float getWidth() { return (float)svgelt.getSVGContext().getBBox().getWidth(); } public void setWidth(float width) throws DOMException { throw svgelt.createDOMException (DOMException.NO_MODIFICATION_ALLOWED_ERR, "readonly.rect", null); } public float getHeight() { return (float)svgelt.getSVGContext().getBBox().getHeight(); } public void setHeight(float height) throws DOMException { throw svgelt.createDOMException (DOMException.NO_MODIFICATION_ALLOWED_ERR, "readonly.rect", null); } }; } /** * To implement {@link org.w3c.dom.svg.SVGLocatable#getCTM()}. */ public static SVGMatrix getCTM(Element elt) { final SVGOMElement svgelt = (SVGOMElement)elt; return new AbstractSVGMatrix() { protected AffineTransform getAffineTransform() { return svgelt.getSVGContext().getCTM(); } }; } /** * To implement {@link org.w3c.dom.svg.SVGLocatable#getScreenCTM()}. */ public static SVGMatrix getScreenCTM(Element elt) { final SVGOMElement svgelt = (SVGOMElement)elt; return new AbstractSVGMatrix() { protected AffineTransform getAffineTransform() { SVGContext context = svgelt.getSVGContext(); AffineTransform ret = context.getGlobalTransform(); AffineTransform scrnTrans = context.getScreenTransform(); if (scrnTrans != null) ret.preConcatenate(scrnTrans); return ret; } }; } /** * To implement {@link * org.w3c.dom.svg.SVGLocatable#getTransformToElement(SVGElement)}. */ public static SVGMatrix getTransformToElement(Element elt, SVGElement element) throws SVGException { final SVGOMElement currentElt = (SVGOMElement)elt; final SVGOMElement targetElt = (SVGOMElement)element; return new AbstractSVGMatrix() { protected AffineTransform getAffineTransform() { AffineTransform cat = currentElt.getSVGContext().getGlobalTransform(); if (cat == null) { cat = new AffineTransform(); } AffineTransform tat = targetElt.getSVGContext().getGlobalTransform(); if (tat == null) { tat = new AffineTransform(); } AffineTransform at = new AffineTransform(cat); try { at.preConcatenate(tat.createInverse()); return at; } catch (NoninvertibleTransformException ex) { throw currentElt.createSVGException (SVGException.SVG_MATRIX_NOT_INVERTABLE, "noninvertiblematrix", null); } } }; } }
srnsw/xena
plugins/image/ext/src/batik-1.7/sources/org/apache/batik/dom/svg/SVGLocatableSupport.java
Java
gpl-3.0
6,739
/* * Copyright (C) 2012 Timo Vesalainen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.vesalainen.bcc; import java.io.IOException; import java.util.Map; /** * * @author Timo Vesalainen <timo.vesalainen@iki.fi> */ public class LongASM extends Assembler implements TypeASM { LongASM(CodeDataOutput out, Map<String, Label> labels) { super(out, labels); } public void tadd() throws IOException { out.writeByte(LADD); } public void taload() throws IOException { out.writeByte(LALOAD); } public void tand() throws IOException { out.writeByte(LAND); } public void tastore() throws IOException { out.writeByte(LASTORE); } public void tcmp() throws IOException { out.writeByte(LCMP); } public void tconst(int i) throws IOException { switch (i) { case 0: tconst_0(); break; case 1: tconst_1(); break; default: throw new UnsupportedOperationException("Not supported yet."); } } public void tconst_0() throws IOException { out.writeByte(LCONST_0); } public void tconst_1() throws IOException { out.writeByte(LCONST_1); } public void tdiv() throws IOException { out.writeByte(LDIV); } public void tload(int index) throws IOException { switch (index) { case 0: out.writeByte(LLOAD_0); break; case 1: out.writeByte(LLOAD_1); break; case 2: out.writeByte(LLOAD_2); break; case 3: out.writeByte(LLOAD_3); break; default: if (index < 256) { out.writeByte(LLOAD); out.writeByte(index); } else { out.writeByte(WIDE); out.writeByte(LLOAD); out.writeShort(index); } break; } } public void tmul() throws IOException { out.writeByte(LMUL); } public void tneg() throws IOException { out.writeByte(LNEG); } public void tor() throws IOException { out.writeByte(LOR); } public void trem() throws IOException { out.writeByte(LREM); } public void treturn() throws IOException { out.writeByte(LRETURN); } public void tshl() throws IOException { out.writeByte(LSHL); } public void tshr() throws IOException { out.writeByte(LSHR); } public void tstore(int index) throws IOException { switch (index) { case 0: out.writeByte(LSTORE_0); break; case 1: out.writeByte(LSTORE_1); break; case 2: out.writeByte(LSTORE_2); break; case 3: out.writeByte(LSTORE_3); break; default: if (index < 256) { out.writeByte(LSTORE); out.writeByte(index); } else { out.writeByte(WIDE); out.writeByte(LSTORE); out.writeShort(index); } break; } } public void tsub() throws IOException { out.writeByte(LSUB); } public void tushr() throws IOException { out.writeByte(LUSHR); } public void txor() throws IOException { out.writeByte(LXOR); } public void i2t() throws IOException { out.writeByte(I2L); } public void f2t() throws IOException { out.writeByte(F2L); } public void d2t() throws IOException { out.writeByte(D2L); } public void tipush(int b) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void tinc(int index, int con) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void l2t() throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpeq(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpne(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmplt(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpge(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpgt(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmple(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void tcmpl() throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void tcmpg() throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void tconst_null() throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpeq(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpne(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmplt(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpge(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpgt(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmple(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } }
tvesalainen/bcc
src/main/java/org/vesalainen/bcc/LongASM.java
Java
gpl-3.0
7,297
/* * stereographic projection * * Copyright 2010 dan collins <danc@badbytes.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ from numpy import * def Convert(channelpnts): #assuming a half ~sphere, we rad = max(chan['lpnt'][:,1]) - min(chan['lpnt'][:,1])
badbytes/pymeg
meg/stereographicprojection.py
Python
gpl-3.0
1,056
<?php // Activate session session_start(); // Start output buffer ob_start(); // Include utility files require_once 'include/config.php'; require_once BUSINESS_DIR . 'error_handler.php'; // Set the error handler ErrorHandler::SetHandler(); // Load the application page template require_once PRESENTATION_DIR . 'application.php'; require_once PRESENTATION_DIR . 'link.php'; // Load the database handler require_once BUSINESS_DIR . 'database_handler.php'; // Load Business Tier require_once BUSINESS_DIR . 'catalog.php'; require_once BUSINESS_DIR . 'shopping_cart.php'; require_once BUSINESS_DIR . 'orders.php'; require_once BUSINESS_DIR . 'symmetric_crypt.php'; require_once BUSINESS_DIR . 'secure_card.php'; require_once BUSINESS_DIR . 'customer.php'; require_once BUSINESS_DIR . 'i_pipeline_section.php'; require_once BUSINESS_DIR . 'order_processor.php'; require_once BUSINESS_DIR . 'ps_initial_notification.php'; require_once BUSINESS_DIR . 'ps_check_funds.php'; require_once BUSINESS_DIR . 'ps_check_stock.php'; require_once BUSINESS_DIR . 'ps_stock_ok.php'; require_once BUSINESS_DIR . 'ps_take_payment.php'; require_once BUSINESS_DIR . 'ps_ship_goods.php'; require_once BUSINESS_DIR . 'ps_ship_ok.php'; require_once BUSINESS_DIR . 'ps_final_notification.php'; // Load Smarty template file $application = new Application(); // Display the page $application->display('store_admin.tpl'); // Close database connection DatabaseHandler::Close(); // Output content from the buffer flush(); ob_flush(); ob_end_clean(); ?>
ray1919/zsq3p1_db
admin.php
PHP
gpl-3.0
1,583
/******************************************************************************\ * _ ___ ____ __ _ * * | | | \ \___/ / \/ | ___ __ _ ___| |_ * * | |_| |\ /| |\/| |/ __/ _` / __| __| * * | _ | \ - / | | | | (_| (_| \__ \ |_ * * |_| |_| \_/ |_| |_|\___\__,_|___/\__| * * * * This file is part of the HAMcast project. * * * * HAMcast 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. * * * * HAMcast 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 HAMcast. If not, see <http://www.gnu.org/licenses/>. * * * * Contact: HAMcast support <hamcast-support@informatik.haw-hamburg.de> * \******************************************************************************/ #include <boost/thread.hpp> #include "hamcast/uri.hpp" #include "hamcast/multicast_packet.hpp" #include "hamcast/interface_property.hpp" #include "hamcast/ipc/message.hpp" #include "hamcast/util/serialization.hpp" namespace { const size_t max_cache_size = 50; typedef std::map<std::string, hamcast::uri> uri_cache; boost::thread_specific_ptr<uri_cache> m_uri_cache; // check if @p uri_str is cached // if @p uri_str is cached then set storage to the cached uri object // otherwise put a new instance to the cache and set storage afterwards void uri_lookup(const std::string& uri_str, hamcast::uri& storage) { uri_cache* cache = m_uri_cache.get(); if (!cache) { cache = new uri_cache; m_uri_cache.reset(cache); } uri_cache::const_iterator i(cache->find(uri_str)); if (i != cache->end()) { storage = i->second; } else { storage = hamcast::uri(uri_str); // purge the cache if full if (cache->size() >= max_cache_size) { cache->clear(); } cache->insert(uri_cache::value_type(uri_str, storage)); } } } // namespace <anonymous> namespace hamcast { namespace util { /****************************************************************************** * integers * ******************************************************************************/ deserializer& operator>>(deserializer& d, bool& storage) { boost::uint8_t tmp; d >> tmp; storage = (tmp != 0); return d; } /****************************************************************************** * HAMcast types * ******************************************************************************/ serializer& operator<<(serializer& s, const uri& what) { return (s << what.str()); } deserializer& operator>>(deserializer& d, uri& storage) { std::string str; d >> str; uri_lookup(str, storage); return d; } serializer& operator<<(serializer& s, const multicast_packet& mp) { s << mp.from() << mp.size(); if (mp.size() > 0) { s.write(mp.size(), mp.data()); } return s; } deserializer& operator>>(deserializer& d, multicast_packet& mp) { uri mp_from; boost::uint32_t mp_size; d >> mp_from >> mp_size; char* mp_data = 0; if (mp_size > 0) { mp_data = new char[mp_size]; d.read(mp_size, mp_data); } multicast_packet tmp(mp_from, mp_size, mp_data); mp = tmp; return d; } serializer& operator<<(serializer& s, const interface_property& ip) { return (s << ip.id << ip.name << ip.address << ip.technology); } deserializer& operator>>(deserializer& d, interface_property& ip) { return (d >> ip.id >> ip.name >> ip.address >> ip.technology); } serializer& operator<<(serializer& s, const ipc::message& what) { return ipc::message::serialize(s, what); } deserializer& operator>>(deserializer& d, ipc::message::ptr& mptr) { return ipc::message::deserialize(d, mptr); } /****************************************************************************** * standard template library types * ******************************************************************************/ serializer& operator<<(serializer& s, const std::string& what) { s << static_cast<boost::uint32_t>(what.size()); s.write(what.size(), what.c_str()); return s; } deserializer& operator>>(deserializer& d, std::string& storage) { boost::uint32_t str_size; d >> str_size; storage.reserve(str_size); // read string in 128 byte chunks char chunk[129]; while (str_size > 0) { size_t rd_size = std::min<size_t>(128, str_size); d.read(rd_size, chunk); chunk[rd_size] = '\0'; storage += chunk; str_size -= rd_size; } return d; } } } // namespace hamcast::util
HAMcast/HAMcast
libhamcast/src/serialization.cpp
C++
gpl-3.0
5,912
/* * This file is part of the L2J Global project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jglobal.gameserver.model.conditions; import com.l2jglobal.gameserver.model.actor.L2Character; import com.l2jglobal.gameserver.model.items.L2Item; import com.l2jglobal.gameserver.model.skills.Skill; /** * The Class ConditionPlayerHp. * @author mr */ public class ConditionPlayerHp extends Condition { private final int _hp; /** * Instantiates a new condition player hp. * @param hp the hp */ public ConditionPlayerHp(int hp) { _hp = hp; } @Override public boolean testImpl(L2Character effector, L2Character effected, Skill skill, L2Item item) { return (effector != null) && (((effector.getCurrentHp() * 100) / effector.getMaxHp()) <= _hp); } }
rubenswagner/L2J-Global
java/com/l2jglobal/gameserver/model/conditions/ConditionPlayerHp.java
Java
gpl-3.0
1,390
#!/usr/bin/env python import asyncio import json from bson import json_util from pymongo import MongoClient from .search import Query from .crawl import Spider class ClientSpider(Spider): """ Indexes the client website and saves all pages to a mongodb collection """ def __init__(self, client): self.client = client uri = client.website super().__init__(uri) async def save_pages(self): """Save pages to mongodb""" pages = await self.crawl() mongo_client = MongoClient('localhost', 27017) database = mongo_client.pages collection = database[self.client.name] collection.delete_many({}) # delete previous pages collection.insert_many(pages) # insert new pages # Dump loaded BSON to valid JSON string and reload it as dict pages_sanitised = json.loads(json_util.dumps(pages)) return pages_sanitised class ClientQuery(Query): """ Query a client """ def __init__(self, client, query): self.client = client pages = client.get_pages(client.name) query = query super().__init__(pages, query) def modify_search(self): """Modify search with client settings""" pages = self.search() # Dump loaded BSON to valid JSON string and reload it as dict pages_sanitised = json.loads(json_util.dumps(pages)) return pages_sanitised if __name__ == "__main__": import doctest doctest.testmod()
apt-helion/viperidae
api/developer.py
Python
gpl-3.0
1,525
# -*- coding: utf-8 -*- # * Authors: # * TJEBBES Gaston <g.t@majerti.fr> # * Arezki Feth <f.a@majerti.fr>; # * Miotte Julien <j.m@majerti.fr>; import os from autonomie.models.user.userdatas import ( ZoneOption, ZoneQualificationOption, StudyLevelOption, SocialStatusOption, ActivityTypeOption, PcsOption, PrescripteurOption, NonAdmissionOption, ParcoursStatusOption, SocialDocTypeOption, CaeSituationOption, AntenneOption, ) from autonomie.models.career_path import ( TypeContratOption, EmployeeQualityOption, TypeSortieOption, MotifSortieOption, ) from autonomie.views.admin.tools import ( get_model_admin_view, ) from autonomie.views.admin.userdatas import ( USERDATAS_URL, UserDatasIndexView, ) def includeme(config): """ Configure route and views for userdatas management """ for model in ( CaeSituationOption, AntenneOption, ZoneOption, ZoneQualificationOption, StudyLevelOption, SocialStatusOption, EmployeeQualityOption, ActivityTypeOption, PcsOption, PrescripteurOption, NonAdmissionOption, ParcoursStatusOption, MotifSortieOption, SocialDocTypeOption, TypeSortieOption, TypeContratOption, ): view = get_model_admin_view(model, r_path=USERDATAS_URL) config.add_route(view.route_name, view.route_name) config.add_admin_view(view, parent=UserDatasIndexView)
CroissanceCommune/autonomie
autonomie/views/admin/userdatas/options.py
Python
gpl-3.0
1,533
# -*- coding: utf8 -*- """Configuration params for sherlock.""" import os basedir = os.path.abspath(os.path.dirname(__file__)) CORS_HEADER = 'Content-Type' TOKEN_TIMEOUT = 9999 SECRET_KEY = os.urandom(25) SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') SQLALCHEMY_TRACK_MODIFICATIONS = True
leoGalani/sherlock
config.py
Python
gpl-3.0
309
# ############################################################################# # # buckshot.py - given a set of numbers and a marker name, make sarsoft markers # corresponding to all three lat-lon coordinate systems # # # developed for Nevada County Sheriff's Search and Rescue # Copyright (c) 2015 Tom Grundy # # http://ncssarradiologsoftware.sourceforge.net # # Contact the author at nccaves@yahoo.com # Attribution, feedback, bug reports and feature requests are appreciated # # REVISION HISTORY #----------------------------------------------------------------------------- # DATE | AUTHOR | NOTES #----------------------------------------------------------------------------- # 5-29-16 TMG optionally write a GPX file, with color and symbol data; # skip the URL export step if the URL field is blank; # rearrange GUI accordingly # 3-3-17 TMG bug fixes and cleanup (fixes github issues 6,7,8,9) # 3-11-17 TMG fix issue 10 (crash when URL is other than localhost) # 4-16-17 TMG fix issue 3 (mark the best match) - don't attempt an # algorithm - just let the user select one possibility # as the best match; this required changing the fields # to QListWidgets; make sure the best match is exported # to sarsoft with appropriate text, and to gpx with # appropriate icon for Locus Map (android app). Can # investigate best icons for other apps/programs later. # 1-21-18 TMG fix issue 12 (integrate with search-in-progress) by # creating a new sartopo folder each time, and placing # all newly created buckshot markers in that folder # 8-29-18 TMG fix #14 (work with either API version) by using external # module sartopo_python (see separate GitHub project # by that name) # 10-7-18 TMG overhaul to work with significant api changes in v4151 # of sar.jar - probably not backwards compatible - required # changes to sartopo_python also; allow URL on network # other than localhost # # ############################################################################# # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # See included file LICENSE.txt for full license terms, also # available at http://opensource.org/licenses/gpl-3.0.html # # ############################################################################ # # Originally written and tested on Windows Vista Home Basic 32-bit # with PyQt 5.4 and Python 3.4.2; should run for Windows Vista and higher # # Note, this file must be encoded as UTF-8, to preserve degree signs in the code # # ############################################################################ from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import xml.dom.minidom import regex as re from parse import * import sys import requests import json import os from sartopo_python import SartopoSession from buckshot_ui import Ui_buckshot # valid delimiters: space, period, X, x, D, d, M, m, ', S, s, " # 'best match' = all correct delimiters in all the correct places # 'close match' = some delimieter in all the correct places # first, define exactly what will qualify as an 'exact match'; # then, relax that definition some to define a 'close match' # make a canonical form of the input string; # make a canonical form of each possibility; # if they are identical, it is an exact match # i string actual coordinates should this be a match? # 1. 39d120d 39.0dN -120.0dW exact # 2. 39.0d120.0d exact # 3. 39d-120d exact # 4. 39120 close # 5. 3901200 close # 4. 39d12m120d12m 39d12.0mN -120d12.0mW exact # # preprocess the input string: # 1. remove minus sign(s) # 2. convert to lowercase # 3. replace ' with m # 4. replace " with s # 5. replace all letters other than [dmsx] with <space> # 6. replace all multiple-spaces with just one space # 7. do some work to find the lat/lon break ('x'): # 7a. for each known delimiter [dms]: if the next delimiter is d, then insert # 'x' immediately after the current delimiter # preprocessed input string characteristics (i.e. canonical form): # - no minus signs # - unknown delimiters are represented by a <space> # - known delimiters are [.dmsx] # criteria for exact match: # delimiterRegEx="[ .XxDdMm'Ss\"]" bestMatchLabelPrefix="*" closeMatchLabelPrefix="+" class MyWindow(QDialog,Ui_buckshot): def __init__(self,parent): QDialog.__init__(self) self.setWindowFlags(self.windowFlags()|Qt.WindowMinMaxButtonsHint) self.parent=parent self.ui=Ui_buckshot() self.ui.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) self.coordDdStringList=[] self.coordDMmStringList=[] self.coordDMSsStringList=[] # default gpx dir: ~\Documents if it exists, ~ otherwise self.gpxDefaultDir=os.path.expanduser("~") docDir=self.gpxDefaultDir+"\\Documents" if os.path.isdir(docDir): self.gpxDefaultDir=docDir self.ui.gpxFileNameField.setText(self.gpxDefaultDir+"\\buckshot_blank.gpx") self.bestMatch="" def markerNameChanged(self): print("markerNameChanged called") markerName=self.ui.markerNameField.text() fileName=self.ui.gpxFileNameField.text() idx=fileName.find("buckshot_") if idx > -1: self.ui.gpxFileNameField.setText(fileName[0:idx]+"buckshot_"+markerName+".gpx") def gpxSetFileName(self): markerName=self.ui.markerNameField.text() initVal=self.ui.gpxFileNameField.text() if initVal=="": initVal=self.gpxDefaultDir+"\\buckshot_"+markerName+".gpx" gpxFileName=QFileDialog.getSaveFileName(self,"GPX filename",initVal,filter="gpx (*.gpx)") # cancel from file dialog returns a real array with a blank filename; # prevent this from blanking out the filename field if gpxFileName[0]!="": self.ui.gpxFileNameField.setText(gpxFileName[0]) def writeGPX(self,markerList): gpxFileName=self.ui.gpxFileNameField.text() print("Writing GPX file "+gpxFileName) # make sure the file is writable; if not, return False here gpxFile=self.fnameValidate(gpxFileName) if not gpxFile: return False doc=xml.dom.minidom.Document() gpx=doc.createElement("gpx") gpx.setAttribute("creator","BUCKSHOT") gpx.setAttribute("version","1.1") gpx.setAttribute("xmlns","http://www.topografix.com/GPX/1/1") # each element in markerList will result in a gpx wpt token. # markerList element syntax = [name,lat,lon,color] # <desc> CDATA contains SARSoft marker and color # <sym> CDATA contains Locus marker, parsed from marker name # some relevant Locus markers: # z-ico01 = red down arrow # z-ico02 = red x # z-ico03 = red donut # z-ico04 = red dot # z-ico05 = red down triangle # same sequence as above: 06-10 = cyan; 11-15=green; 16-20=yellow # misc-sunny = large green star bubble for marker in markerList: ## print("marker:"+str(marker)+"\n") [title,lat,lon,color,symbol]=marker description="" if title.startswith(bestMatchLabelPrefix): description="User-selected best match!" if title.startswith(closeMatchLabelPrefix): description="CLOSE match for specified coordinates" wpt=doc.createElement("wpt") wpt.setAttribute("lat",str(lat)) wpt.setAttribute("lon",str(lon)) name=doc.createElement("name") desc=doc.createElement("desc") sym=doc.createElement("sym") # descCDATAStr="comments=&url=%23"+marker[3][1:] descCDATAStr=description descCDATA=doc.createCDATASection(descCDATAStr) if "_Dd" in title: # red if title.startswith(bestMatchLabelPrefix): symCDATAStr="z-ico01" else: symCDATAStr="z-ico04" elif "_DMm" in title: # cyan if title.startswith(bestMatchLabelPrefix): symCDATAStr="z-ico06" else: symCDATAStr="z-ico09" elif "_DMSs" in title: # yellow if title.startswith(bestMatchLabelPrefix): symCDATAStr="z-ico16" else: symCDATAStr="z-ico19" else: if title.startswith(bestMatchLabelPrefix): symCDATAStr="z-ico11" else: symCDATAStr="z-ico14" name.appendChild(doc.createTextNode(title)) desc.appendChild(descCDATA) symCDATA=doc.createCDATASection(symCDATAStr) sym.appendChild(symCDATA) wpt.appendChild(name) wpt.appendChild(desc) wpt.appendChild(sym) gpx.appendChild(wpt) doc.appendChild(gpx) gpxFile.write(doc.toprettyxml()) gpxFile.close() return True # calcLatLon - make guesses about actual coordinates based on a string of numbers # called from textChanged of coordsField # assumptions: # - Degrees Latitude is a two-digit number starting with 2, 3, or 4 # - Degrees Longitude is a three-digit number starting with one, second digit # either 0, 1, or 2 # - space or minus sign is a known delimiter and assumed to be correct def calcLatLon(self): ### code to get overlapping matches (i.e. each possible longitude whole number) and their indices: ##import regex as re ##matches=re.finditer("1[012][0123456789]",numbers,overlapped=True) ##[match.span() for match in matches] coordString=self.ui.coordsField.text() # shortCoordString = the 'canonical' form that the possibilities will # be compared to, to check for close or exact matches. Same as # coordString, with standardized D/M/S delimiters; cannot eliminate all # spaces at this point since they may or may not be important delimiters; # therefore, will need to insert a space into the shortCoordString before # longitude for each possibility on the fly during parsing; this ensures # that original coordString with NO spaces at all can still make an # best match. shortCoordString=coordString.lower() shortCoordString=re.sub(r'[Xx]',' ',shortCoordString) # replace X or x with space for canonical form shortCoordString=re.sub(r'\s+',' ',shortCoordString) # get rid of duplicate spaces shortCoordString=re.sub(r'\'','m',shortCoordString) shortCoordString=re.sub(r'"','s',shortCoordString) print("Short coordinate string for comparison:"+shortCoordString+"\n") # different approach: # make a list of the indeces and kinds of delimiters; # if the indeces all match, it is a 'close' match; # if the indeces all match AND each one is of the same kind, it is an 'best' match delimIter=re.finditer(r'[ .dDmMsS\'"-]+',coordString) ## numbers=re.sub(r'[ .dDmMsS\'"-]','',coordString) numbers=re.sub(r'\D','',coordString) print("Raw Numbers:"+numbers+"\n") ## numbers=self.ui.numbersField.text() self.coordDdStringList=[] self.coordDMmStringList=[] self.coordDMSsStringList=[] latDegIndex=0 lonDegIndex=-1 pattern=re.compile('1[012][0123456789]') # assume longitude 100-129 west matches=pattern.finditer(numbers,2,overlapped=True) ## print(str([match.span() for match in matches])) for lonDegMobj in matches: print(str(lonDegMobj.span())) ## lonDegMobj=pattern.search(numbers,2) # skip the first two characters ## if lonDegMobj!=None: lonDegIndex=lonDegMobj.start() lonDeg=lonDegMobj.group() print("lonDegIndex: '"+str(lonDegIndex)+"'") print("Longitude Degrees: '"+lonDeg+"'") lonRestIndex=lonDegIndex+3 lonRest=numbers[lonRestIndex:] print("Longitude rest: '"+lonRest+"'") if int(numbers[0])>1 and int(numbers[0])<5: #assume latitude 20-49 north latDeg=numbers[0:2] latRest=numbers[2:lonDegIndex] print("Latitude degrees: '"+latDeg+"'") print("Latitude rest: '"+latRest+"'") # initialize whole minutes and seconds to unrealizable values # for use in the 'possible' section below latMin1="99" latMin2="99" latSec11="99" latSec12="99" latSec21="99" latSec22="99" lonMin1="99" lonMin2="99" lonSec11="99" lonSec12="99" lonSec21="99" lonSec22="99" # initialize "rest" arguments to blank strings latMin1Rest="" latMin2Rest="" latSec11Rest="" latSec12Rest="" latSec21Rest="" latSec22Rest="" lonMin1Rest="" lonMin2Rest="" lonSec11Rest="" lonSec12Rest="" lonSec21Rest="" lonSec22Rest="" # parse minutes and seconds from the rest of the string # whole minutes and whole seconds could be one digit or two digits if len(latRest)>0: print("t1") latMin1=latRest[0] if len(latRest)>1: print("t2") latMin1Rest=latRest[1:] latMin2=latRest[0:2] if len(latRest)>2: print("t2.5") latMin2Rest=latRest[2:] if len(latMin1Rest)>0: print("t3") latSec1=latMin1Rest[0:] if len(latSec1)>0: print("t4") latSec11=latSec1[0] if len(latSec1)>1: print("t5") latSec11Rest=latSec1[1:] latSec12=latSec1[0:2] if len(latSec1)>2: print("t5.5") latSec12Rest=latSec1[2:] if len(latMin2Rest)>0: print("t6") latSec2=latMin2Rest[0:] if len(latSec2)>0: print("t7") latSec21=latSec2[0] if len(latSec2)>1: print("t8") latSec21Rest=latSec2[1:] latSec22=latSec2[0:2] if len(latSec2)>2: print("t9") latSec22Rest=latSec2[2:] else: latSec2="0" # account for implied zero seconds latSec21="0" else: latSec1="0" # account for implied zero seconds latSec11="0" if len(lonRest)>0: lonMin1=lonRest[0] if len(lonRest)>1: lonMin1Rest=lonRest[1:] lonMin2=lonRest[0:2] if len(lonRest)>2: lonMin2Rest=lonRest[2:] if len(lonMin1Rest)>0: lonSec1=lonMin1Rest[0:] if len(lonSec1)>0: lonSec11=lonSec1[0] if len(lonSec1)>1: lonSec11Rest=lonSec1[1:] lonSec12=lonSec1[0:2] if len(lonSec1)>2: lonSec12Rest=lonSec1[2:] if len(lonMin2Rest)>0: lonSec2=lonMin2Rest[0:] if len(lonSec2)>0: lonSec21=lonSec2[0] if len(lonSec2)>1: lonSec21Rest=lonSec2[1:] lonSec22=lonSec2[0:2] if len(lonSec2)>2: lonSec22Rest=lonSec2[2:] else: lonSec2="0" # account for implied zero seconds lonSec21="0" else: lonSec1="0" # account for implied zero seconds lonSec11="0" # set flags as to which ones are possible # (whole min/sec <60 (2-digit) or <10 (1-digit)) latMin1Possible=int(latMin1)<10 latMin2Possible=int(latMin2)>9 and int(latMin2)<60 latSec11Possible=int(latSec11)<10 latSec12Possible=int(latSec12)<60 latSec21Possible=int(latSec21)<10 latSec22Possible=int(latSec22)<60 lonMin1Possible=int(lonMin1)<10 lonMin2Possible=int(lonMin2)>9 and int(lonMin2)<60 lonSec11Possible=int(lonSec11)<10 lonSec12Possible=int(lonSec12)<60 lonSec21Possible=int(lonSec21)<10 lonSec22Possible=int(lonSec22)<60 print("latMin1Possible:"+str(latMin1Possible)+":"+latMin1+":"+latMin1Rest) print("latMin2Possible:"+str(latMin2Possible)+":"+latMin2+":"+latMin2Rest) print("latSec11Possible:"+str(latSec11Possible)+":"+latSec11+":"+latSec11Rest) print("latSec12Possible:"+str(latSec12Possible)+":"+latSec12+":"+latSec12Rest) print("latSec21Possible:"+str(latSec21Possible)+":"+latSec21+":"+latSec21Rest) print("latSec22Possible:"+str(latSec22Possible)+":"+latSec22+":"+latSec22Rest) print("lonMin1Possible:"+str(lonMin1Possible)+":"+lonMin1+":"+lonMin1Rest) print("lonMin2Possible:"+str(lonMin2Possible)+":"+lonMin2+":"+lonMin2Rest) print("lonSec11Possible:"+str(lonSec11Possible)+":"+lonSec11+":"+lonSec11Rest) print("lonSec12Possible:"+str(lonSec12Possible)+":"+lonSec12+":"+lonSec12Rest) print("lonSec21Possible:"+str(lonSec21Possible)+":"+lonSec21+":"+lonSec21Rest) print("lonSec22Possible:"+str(lonSec22Possible)+":"+lonSec22+":"+lonSec22Rest) # zero-pad right-of-decimal if needed, i.e. no blank strings right-of-decimal latRest=latRest or "0" lonRest=lonRest or "0" latMin1Rest=latMin1Rest or "0" latMin2Rest=latMin2Rest or "0" lonMin1Rest=lonMin1Rest or "0" lonMin2Rest=lonMin2Rest or "0" latSec11Rest=latSec11Rest or "0" latSec12Rest=latSec12Rest or "0" latSec21Rest=latSec21Rest or "0" latSec22Rest=latSec22Rest or "0" lonSec11Rest=lonSec11Rest or "0" lonSec12Rest=lonSec12Rest or "0" lonSec21Rest=lonSec21Rest or "0" lonSec22Rest=lonSec22Rest or "0" # build the lists of possible coordinate strings for each coordinate system # (if only one of lat/lon per pair is possible, then the pair is # not possible) self.coordDdStringList.append(str(latDeg+"."+latRest+"deg N x "+lonDeg+"."+lonRest+"deg W")) if latMin1Possible and lonMin1Possible: self.coordDMmStringList.append(str(latDeg+"deg "+latMin1+"."+latMin1Rest+"min N x "+lonDeg+"deg "+lonMin1+"."+lonMin1Rest+"min W")) if latMin1Possible and lonMin2Possible: self.coordDMmStringList.append(str(latDeg+"deg "+latMin1+"."+latMin1Rest+"min N x "+lonDeg+"deg "+lonMin2+"."+lonMin2Rest+"min W")) if latMin2Possible and lonMin1Possible: self.coordDMmStringList.append(str(latDeg+"deg "+latMin2+"."+latMin2Rest+"min N x "+lonDeg+"deg "+lonMin1+"."+lonMin1Rest+"min W")) if latMin2Possible and lonMin2Possible: self.coordDMmStringList.append(str(latDeg+"deg "+latMin2+"."+latMin2Rest+"min N x "+lonDeg+"deg "+lonMin2+"."+lonMin2Rest+"min W")) if latSec11Possible and lonSec11Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec11+"."+latSec11Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec11+"."+lonSec11Rest+"sec W")) if latSec11Possible and lonSec12Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec11+"."+latSec11Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec12+"."+lonSec12Rest+"sec W")) if latSec11Possible and lonSec21Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec11+"."+latSec11Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec21+"."+lonSec21Rest+"sec W")) if latSec11Possible and lonSec22Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec11+"."+latSec11Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec22+"."+lonSec22Rest+"sec W")) if latSec12Possible and lonSec11Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec12+"."+latSec12Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec11+"."+lonSec11Rest+"sec W")) if latSec12Possible and lonSec12Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec12+"."+latSec12Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec12+"."+lonSec12Rest+"sec W")) if latSec12Possible and lonSec21Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec12+"."+latSec12Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec21+"."+lonSec21Rest+"sec W")) if latSec12Possible and lonSec22Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec12+"."+latSec12Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec22+"."+lonSec22Rest+"sec W")) if latSec21Possible and lonSec11Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec21+"."+latSec21Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec11+"."+lonSec11Rest+"sec W")) if latSec21Possible and lonSec12Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec21+"."+latSec21Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec12+"."+lonSec12Rest+"sec W")) if latSec21Possible and lonSec21Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec21+"."+latSec21Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec21+"."+lonSec21Rest+"sec W")) if latSec21Possible and lonSec22Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec21+"."+latSec21Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec22+"."+lonSec22Rest+"sec W")) if latSec22Possible and lonSec11Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec22+"."+latSec22Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec11+"."+lonSec11Rest+"sec W")) if latSec22Possible and lonSec12Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec22+"."+latSec22Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec12+"."+lonSec12Rest+"sec W")) if latSec22Possible and lonSec21Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec22+"."+latSec22Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec21+"."+lonSec21Rest+"sec W")) if latSec22Possible and lonSec22Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec22+"."+latSec22Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec22+"."+lonSec22Rest+"sec W")) else: print("Latitiude not found.") else: print("Longitude not found.") # self.ui.DdField.setPlainText("\n".join(self.coordDdStringList)) # self.ui.DMmField.setPlainText("\n".join(self.coordDMmStringList)) # self.ui.DMSsField.setPlainText("\n".join(self.coordDMSsStringList)) self.ui.DdField.clear() self.ui.DdField.addItems(self.coordDdStringList) self.ui.DMmField.clear() self.ui.DMmField.addItems(self.coordDMmStringList) self.ui.DMSsField.clear() self.ui.DMSsField.addItems(self.coordDMSsStringList) print("Possible Dd coordinates:\n"+str(self.coordDdStringList)) print("Possible DMm coordinates:\n"+str(self.coordDMmStringList)) print("Possible DMSs coordinates:\n"+str(self.coordDMSsStringList)) # now find the 'short' string corresponding to each possibility, and # see how close of a match it is to the originally entered string # (highlight the row in the GUI, and change the marker name and symbol) for n,DdString in enumerate(self.coordDdStringList): DdShort=DdString.replace("deg ","d") DdShort=DdShort.replace("N x "," ") DdShort=DdShort.replace("W","") print("DdShort:"+DdShort) if DdShort==shortCoordString: print(" EXACT MATCH!") self.coordDdStringList[n]=bestMatchLabelPrefix+DdString # self.ui.DdField.setPlainText("\n".join(self.coordDdStringList)) self.ui.DdField.clear() self.ui.DdField.addItems(self.coordDdStringList) for n,DMmString in enumerate(self.coordDMmStringList): DMmShort=DMmString.replace("deg ","d") DMmShort=DMmShort.replace("min ","m") DMmShort=DMmShort.replace("N x "," ") DMmShort=DMmShort.replace("W","") print("DMmShort:"+DMmShort) if DMmShort==shortCoordString: print(" EXACT MATCH!") self.coordDMmStringList[n]=bestMatchLabelPrefix+DMmString # self.ui.DMmField.setPlainText("\n".join(self.coordDMmStringList)) self.ui.DMmField.clear() self.ui.DMmField.addItems(self.coordDMmStringList) for n,DMSsString in enumerate(self.coordDMSsStringList): DMSsShort=DMSsString.replace("deg ","d") DMSsShort=DMSsShort.replace("min ","m") DMSsShort=DMSsShort.replace("sec ","s") DMSsShort=DMSsShort.replace("N x "," ") DMSsShort=DMSsShort.replace("W","") print("DMSsShort:"+DMSsShort) if DMSsShort==shortCoordString: print(" EXACT MATCH!") self.coordDMSsStringList[n]=bestMatchLabelPrefix+DMSsString # self.ui.DMSsField.setPlainText("\n".join(self.coordDMSsStringList)) self.ui.DMSsField.clear() self.ui.DMSsField.addItems(self.coordDMSsStringList) # possibilityClicked: when any row is clicked, unhighlight / unselect any # highlighted/selected rows in the other two coordinate system list widgets, # and use the selected row as the 'best match' possibility def possibilityDdClicked(self): clicked=self.ui.DdField.selectedItems()[0].text() if clicked==self.bestMatch: self.bestMatch="" self.ui.DdField.clearSelection() else: self.bestMatch=clicked print(self.bestMatch) self.ui.DMmField.clearSelection() self.ui.DMSsField.clearSelection() def possibilityDMmClicked(self): clicked=self.ui.DMmField.selectedItems()[0].text() if clicked==self.bestMatch: self.bestMatch="" self.ui.DMmField.clearSelection() else: self.bestMatch=clicked print(self.bestMatch) self.ui.DdField.clearSelection() self.ui.DMSsField.clearSelection() def possibilityDMSsClicked(self): clicked=self.ui.DMSsField.selectedItems()[0].text() if clicked==self.bestMatch: self.bestMatch="" self.ui.DMSsField.clearSelection() else: self.bestMatch=clicked print(self.bestMatch) self.ui.DdField.clearSelection() self.ui.DMmField.clearSelection() #fnameValidate: try writing a test file to the specified filename; # return the filehandle if valid, or print the error message and return False # if invalid for whatever reason def fnameValidate(self,filename): try: f=open(filename,"w") except (IOError,FileNotFoundError) as err: QMessageBox.warning(self,"Invalid Filename","GPX filename is not valid:\n\n"+str(err)+"\n\nNo markers written to GPX or URL. Fix or blank out the filename, and try again.") return False else: return f def createMarkers(self): print("createMarkers called") # if a gpx filename is specified, validate it first; if invalid, force # the user to fix it or blank it out before generating any URL markers if not self.fnameValidate(self.ui.gpxFileNameField.text()): return DdIdx=0 DMmIdx=0 DMSsIdx=0 DdIdxFlag=len(self.coordDdStringList)>1 DMmIdxFlag=len(self.coordDMmStringList)>1 DMSsIdxFlag=len(self.coordDMSsStringList)>1 markerName=self.ui.markerNameField.text() if markerName=="": markerName="X" # for best match, use a ring with center dot # for close match, use a hollow ring # appropriate prefixes were determined from decoding json POST request # of a live header when creating each type of marker by hand # final URL values: # simple dot: "#<hex_color>" # target: "c:target,<hex_color>" (notice, no pound sign) # ring: "c:ring,<hex_color>" (notice, no pound sign) bestMatchSymbol="c:target" closeMatchSymbol="c:ring" # build a list of markers; each marker is a list: # [markerName,lat,lon,color] markerList=[] for DdString in self.coordDdStringList: DdIdx=DdIdx+1 labelPrefix="" symbol="point" # if DdString.startswith(bestMatchLabelPrefix): if DdString==self.bestMatch: DdString=DdString.replace(bestMatchLabelPrefix,"") labelPrefix=bestMatchLabelPrefix symbol=bestMatchSymbol if DdString.startswith(closeMatchLabelPrefix): DdString=DdString.replace(closeMatchLabelPrefix,"") labelPrefix=closeMatchLabelPrefix symbol=closeMatchSymbol print(" Dd : '"+DdString+"'") r=parse("{:g}deg N x {:g}deg W",DdString) print(r) if DdIdxFlag: idx=str(DdIdx) else: idx="" markerList.append([labelPrefix+markerName+"_Dd"+idx,r[0],-r[1],"FF0000",symbol]) for DMmString in self.coordDMmStringList: DMmIdx=DMmIdx+1 labelPrefix="" symbol="point" # if DMmString.startswith(bestMatchLabelPrefix): if DMmString==self.bestMatch: DMmString=DMmString.replace(bestMatchLabelPrefix,"") labelPrefix=bestMatchLabelPrefix symbol=bestMatchSymbol if DMmString.startswith(closeMatchLabelPrefix): DMmString=DMmString.replace(closeMatchLabelPrefix,"") labelPrefix=closeMatchLabelPrefix symbol=closeMatchSymbol print(" DMm : "+DMmString) r=parse("{:g}deg {:g}min N x {:g}deg {:g}min W",DMmString) print(r) if DMmIdxFlag: idx=str(DMmIdx) else: idx="" markerList.append([labelPrefix+markerName+"_DMm"+idx,r[0]+r[1]/60.0,-(r[2]+r[3]/60.0),"FF00FF",symbol]) for DMSsString in self.coordDMSsStringList: DMSsIdx=DMSsIdx+1 labelPrefix="" symbol="point" # if DMSsString.startswith(bestMatchLabelPrefix): if DMSsString==self.bestMatch: DMSsString=DMSsString.replace(bestMatchLabelPrefix,"") labelPrefix=bestMatchLabelPrefix symbol=bestMatchSymbol if DMSsString.startswith(closeMatchLabelPrefix): DMSsString=DMSsString.replace(closeMatchLabelPrefix,"") labelPrefix=closeMatchLabelPrefix symbol=closeMatchSymbol print(" DMSs: "+DMSsString) r=parse("{:g}deg {:g}min {:g}sec N x {:g}deg {:g}min {:g}sec W",DMSsString) print(r) if DMSsIdxFlag: idx=str(DMSsIdx) else: idx="" markerList.append([labelPrefix+markerName+"_DMSs"+idx,r[0]+r[1]/60.0+r[2]/3600.0,-(r[3]+r[4]/60.0+r[5]/3600.0),"0000FF",symbol]) print("Final marker list:") print(str(markerList)) if self.writeGPX(markerList): infoStr="\nWrote GPX? YES" else: infoStr="\nWrote GPX? NO" if self.ui.URLField.text(): url=self.ui.URLField.text() p=url.lower().replace("http://","").split("/") domainAndPort=p[0] mapID=p[-1] print("domainAndPort: "+domainAndPort) print("map ID: "+mapID) sts=SartopoSession(domainAndPort=domainAndPort,mapID=mapID) fid=sts.addFolder("Buckshot") print(" folder id="+str(fid)) for marker in markerList: [title,lat,lon,color,symbol]=marker description="" if title.startswith(bestMatchLabelPrefix): description="User-selected best match!" if title.startswith(closeMatchLabelPrefix): description="CLOSE match for specified coordinates" sts.addMarker(lat,lon,title,description,color,symbol,None,fid) infoStr+="\nWrote URL? YES" else: infoStr+="\nWrote URL? NO" print("No URL specified; skipping URL export.") QMessageBox.information(self,"Markers Created","Markers created successfully.\n"+infoStr) def main(): app = QApplication(sys.argv) w = MyWindow(app) w.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
ncssar/buckshot
buckshot.py
Python
gpl-3.0
30,547
/******************************************************************************* * Copyright (c) 2011-2014 SirSengir. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.txt * * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ package forestry.core.genetics; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import forestry.api.core.EnumHumidity; import forestry.api.genetics.IAllele; import forestry.api.genetics.IGenome; import forestry.api.genetics.IMutationCondition; public class MutationConditionHumidity implements IMutationCondition { private final EnumHumidity minHumidity; private final EnumHumidity maxHumidity; public MutationConditionHumidity(EnumHumidity minHumidity, EnumHumidity maxHumidity) { this.minHumidity = minHumidity; this.maxHumidity = maxHumidity; } @Override public float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1) { BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(x, z); EnumHumidity biomeHumidity = EnumHumidity.getFromValue(biome.rainfall); if (biomeHumidity.ordinal() < minHumidity.ordinal() || biomeHumidity.ordinal() > maxHumidity.ordinal()) { return 0; } return 1; } @Override public String getDescription() { if (minHumidity != maxHumidity) { return String.format("Humidity between %s and %s.", minHumidity, maxHumidity); } else { return String.format("Humidity %s required.", minHumidity); } } }
ThiagoGarciaAlves/ForestryMC
src/main/java/forestry/core/genetics/MutationConditionHumidity.java
Java
gpl-3.0
1,896
package io.renren.modules.api.controller; import io.renren.common.utils.R; import io.renren.modules.api.annotation.AuthIgnore; import io.renren.modules.api.annotation.LoginUser; import io.renren.modules.api.entity.TokenEntity; import io.renren.modules.api.entity.UserEntity; import org.springframework.web.bind.annotation.*; /** * API测试接口 * * @author chenshun * @email sunlightcs@gmail.com * @date 2017-03-23 15:47 */ @RestController @RequestMapping("/api") public class ApiTestController { /** * 获取用户信息 */ @GetMapping("userInfo") public R userInfo(@LoginUser UserEntity user){ return R.ok().put("user", user); } /** * 忽略Token验证测试 */ @AuthIgnore @GetMapping("notToken") public R notToken(){ return R.ok().put("msg", "无需token也能访问。。。"); } /** * 接收JSON数据 */ @PostMapping("jsonData") public R jsonData(@LoginUser UserEntity user, @RequestBody TokenEntity token){ return R.ok().put("user", user).put("token", token); } }
qqq490010553/springboot-basis
src/main/java/io/renren/modules/api/controller/ApiTestController.java
Java
gpl-3.0
1,092
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/i18n/icu_util.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include <string> #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "unicode/putil.h" #include "unicode/udata.h" #if defined(OS_MACOSX) #include "base/mac/foundation_util.h" #endif #define ICU_UTIL_DATA_FILE 0 #define ICU_UTIL_DATA_SHARED 1 #define ICU_UTIL_DATA_STATIC 2 #ifndef ICU_UTIL_DATA_IMPL #if defined(OS_WIN) #define ICU_UTIL_DATA_IMPL ICU_UTIL_DATA_SHARED #else #define ICU_UTIL_DATA_IMPL ICU_UTIL_DATA_STATIC #endif #endif // ICU_UTIL_DATA_IMPL #if ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE #define ICU_UTIL_DATA_FILE_NAME "icudt" U_ICU_VERSION_SHORT "l.dat" #elif ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_SHARED #define ICU_UTIL_DATA_SYMBOL "icudt" U_ICU_VERSION_SHORT "_dat" #if defined(OS_WIN) #define ICU_UTIL_DATA_SHARED_MODULE_NAME "icudt.dll" #endif #endif namespace icu_util { bool Initialize() { #ifndef NDEBUG // Assert that we are not called more than once. Even though calling this // function isn't harmful (ICU can handle it), being called twice probably // indicates a programming error. static bool called_once = false; DCHECK(!called_once); called_once = true; #endif #if (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_SHARED) // We expect to find the ICU data module alongside the current module. FilePath data_path; PathService::Get(base::DIR_MODULE, &data_path); data_path = data_path.AppendASCII(ICU_UTIL_DATA_SHARED_MODULE_NAME); HMODULE module = LoadLibrary(data_path.value().c_str()); if (!module) { DLOG(ERROR) << "Failed to load " << ICU_UTIL_DATA_SHARED_MODULE_NAME; return false; } FARPROC addr = GetProcAddress(module, ICU_UTIL_DATA_SYMBOL); if (!addr) { DLOG(ERROR) << ICU_UTIL_DATA_SYMBOL << ": not found in " << ICU_UTIL_DATA_SHARED_MODULE_NAME; return false; } UErrorCode err = U_ZERO_ERROR; udata_setCommonData(reinterpret_cast<void*>(addr), &err); return err == U_ZERO_ERROR; #elif (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_STATIC) // Mac/Linux bundle the ICU data in. return true; #elif (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE) #if !defined(OS_MACOSX) // For now, expect the data file to be alongside the executable. // This is sufficient while we work on unit tests, but will eventually // likely live in a data directory. FilePath data_path; bool path_ok = PathService::Get(base::DIR_EXE, &data_path); DCHECK(path_ok); u_setDataDirectory(data_path.value().c_str()); // Only look for the packaged data file; // the default behavior is to look for individual files. UErrorCode err = U_ZERO_ERROR; udata_setFileAccess(UDATA_ONLY_PACKAGES, &err); return err == U_ZERO_ERROR; #else // If the ICU data directory is set, ICU won't actually load the data until // it is needed. This can fail if the process is sandboxed at that time. // Instead, Mac maps the file in and hands off the data so the sandbox won't // cause any problems. // Chrome doesn't normally shut down ICU, so the mapped data shouldn't ever // be released. static file_util::MemoryMappedFile mapped_file; if (!mapped_file.IsValid()) { // Assume it is in the MainBundle's Resources directory. FilePath data_path = base::mac::PathForMainAppBundleResource(CFSTR(ICU_UTIL_DATA_FILE_NAME)); if (data_path.empty()) { DLOG(ERROR) << ICU_UTIL_DATA_FILE_NAME << " not found in bundle"; return false; } if (!mapped_file.Initialize(data_path)) { DLOG(ERROR) << "Couldn't mmap " << data_path.value(); return false; } } UErrorCode err = U_ZERO_ERROR; udata_setCommonData(const_cast<uint8*>(mapped_file.data()), &err); return err == U_ZERO_ERROR; #endif // OS check #endif } } // namespace icu_util
tierney/cryptagram-cc
src/base/i18n/icu_util.cc
C++
gpl-3.0
4,102
/* * Created on 16-dic-2004 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ /* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana * * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA. * * For more information, contact: * * Generalitat Valenciana * Conselleria d'Infraestructures i Transport * Av. Blasco Ibáñez, 50 * 46010 VALENCIA * SPAIN * * +34 963862235 * gvsig@gva.es * www.gvsig.gva.es * * or * * IVER T.I. S.A * Salamanca 50 * 46005 Valencia * Spain * * +34 963163400 * dac@iver.es */ package com.iver.cit.gvsig.fmap.layers; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import javax.print.attribute.PrintRequestAttributeSet; import org.geotools.data.FeatureSource; import org.geotools.map.DefaultMapContext; import org.geotools.map.MapContext; import org.geotools.map.MapLayer; import org.geotools.renderer.lite.LiteRenderer2; import com.hardcode.gdbms.driver.exceptions.ReadDriverException; import com.iver.cit.gvsig.fmap.ViewPort; import com.iver.utiles.swing.threads.Cancellable; import com.vividsolutions.jts.geom.Envelope; /** * @author FJP * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ // TODO: Cuando no sea para pruebas, habrá que ponerla privada public class FLyrGT2_old extends FLyrDefault { private MapLayer m_lyrGT2; private LiteRenderer2 liteR2; private MapContext mapContextGT2; public FLyrGT2_old(MapLayer lyrGT2) { m_lyrGT2 = lyrGT2; setName(lyrGT2.getTitle()); mapContextGT2 = new DefaultMapContext(); mapContextGT2.addLayer(lyrGT2); liteR2 = new LiteRenderer2(mapContextGT2); } /* (non-Javadoc) * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent() */ public Rectangle2D getFullExtent() { FeatureSource fs = m_lyrGT2.getFeatureSource(); Envelope bounds = null; try { bounds = fs.getBounds(); if (bounds == null) { bounds = fs.getFeatures().getBounds(); } } catch (IOException e) { e.printStackTrace(); } return new Rectangle2D.Double(bounds.getMinX(), bounds.getMinY(), bounds.getWidth(), bounds.getHeight()); } /* (non-Javadoc) * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage, java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort, com.iver.cit.gvsig.fmap.operations.Cancellable) */ public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale) throws ReadDriverException { try { if (isWithinScale(scale)){ // mapExtent = this.context.getAreaOfInterest(); m_lyrGT2.setVisible(isVisible()); Envelope envelope = new Envelope(viewPort.getExtent().getMinX(), viewPort.getExtent().getMinY(), viewPort.getExtent().getMaxX(), viewPort.getExtent().getMaxY()); mapContextGT2.setAreaOfInterest(envelope); /* FeatureResults results = queryLayer(m_lyrGT2, envelope, destinationCrs); // extract the feature type stylers from the style object // and process them processStylers(g, results, m_lyrGT2.getStyle().getFeatureTypeStyles(), viewPort.getAffineTransform(), mapContextGT2.getCoordinateReferenceSystem()); */ Rectangle r = new Rectangle(viewPort.getImageSize()); long t1 = System.currentTimeMillis(); liteR2.paint(g,r, viewPort.getAffineTransform()); long t2 = System.currentTimeMillis(); System.out.println("Tiempo en pintar capa " + getName() + " de GT2:" + (t2- t1) + " milisegundos"); } } catch (Exception exception) { exception.printStackTrace(); } } /** * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort, com.iver.utiles.swing.threads.Cancellable) */ public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale, PrintRequestAttributeSet properties) throws ReadDriverException { } }
iCarto/siga
libFMap/src/com/iver/cit/gvsig/fmap/layers/FLyrGT2_old.java
Java
gpl-3.0
5,013
namespace _08.Custom_Comparator { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main() { int[] numbers = Console.ReadLine() .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); Array.Sort(numbers, (x, y) => { if (IsEven(x) && !IsEven(y)) { return -1; } if (!IsEven(x) && IsEven(y)) { return 1; } if (x < y) { return -1; } if (x > y) { return 1; } return 0; }); Console.WriteLine(string.Join(" ",numbers)); } static bool IsEven(int i) { return i % 2 == 0; } } }
PlamenHP/Softuni
Advanced C#/Functional Programming - Exercises/08. Custom Comparator/Startup.cs
C#
gpl-3.0
1,086
#include <fstream> #include <iostream> #include "df3volume.h" #ifdef _WIN32 # define LITTLE_ENDIAN #endif #ifdef LITTLE_ENDIAN #define SWAP_2(x) ( (((x) & 0xff) << 8) | ((unsigned short)(x) >> 8) ) #define SWAP_4(x) ( ((x) << 24) | \ (((x) << 8) & 0x00ff0000) | \ (((x) >> 8) & 0x0000ff00) | \ ((x) >> 24) ) #define FIX_SHORT(x) (*(unsigned short *)&(x) = SWAP_2(*(unsigned short *)&(x))) #define FIX_INT(x) (*(unsigned int *)&(x) = SWAP_4(*(unsigned int *)&(x))) #else #define FIX_SHORT(x) (x) #define FIX_INT(x) (x) #endif using namespace std; bool df3volume::load(const char * file) { ifstream ffile; ffile.open(file, ios_base::binary | ios_base::in); if( ffile.fail() ) { cerr << "ERROR: Could not read input volume file '" << file << "' ! " << endl; return false; } ffile.read((char*)&width, sizeof(short)); ffile.read((char*)&height, sizeof(short)); ffile.read((char*)&depth, sizeof(short)); width = FIX_SHORT(width); height = FIX_SHORT(height); depth = FIX_SHORT(depth); size_t size = width * height * depth; data.resize(size); ffile.read((char*)&data[0], size); if( ffile.fail() ) { cerr << "Failed to read from volume file !" << endl; ffile.close(); return false; } ffile.close(); #ifdef _DEBUG cout << "Volume " << file << " size = " << size << " bytes" << endl; #endif return true; } bool df3volume::load_raw(uint16 _width, uint16 _height, uint16 _depth, const char * file) { ifstream ffile; ffile.open(file, ios_base::binary | ios_base::in); if( ffile.fail() ) { cerr << "Could not read input volume file '" << file << "' ! " << endl; return false; } size_t size = _width * _height * _depth; data.resize(size); ffile.read((char*)&data[0], size); if( ffile.fail() ) { cerr << "Failed to read from volume file " << file << endl; ffile.close(); return false; } width = _width; height = _height; depth = _depth; #ifdef _DEBUG cout << "Volume " << file << " size = " << size << " bytes" << endl; #endif return true; } bool df3volume::save(const char* file) { ofstream df3(file, ios::out | ios::binary); if( df3.fail() ) { cerr << "Could not open file " << file << " for writing !" << endl; return false; } uint16 _width = FIX_SHORT(width); uint16 _height = FIX_SHORT(height); uint16 _depth = FIX_SHORT(depth); df3.write((const char*)&_width, sizeof(uint16)); df3.write((const char*)&_height, sizeof(uint16)); df3.write((const char*)&_depth, sizeof(uint16)); df3.write((const char*)&data[0], data.size()); if( df3.fail() ) { cerr << "Failed to save df3 volume to output file " << file << endl; df3.close(); return false; } df3.close(); return true; }
mihaipopescu/VEGA
tools/df3volume.cpp
C++
gpl-3.0
3,022
// Copyright (c) 2005 - 2015 Settlers Freaks (sf-team at siedler25.org) // // This file is part of Return To The Roots. // // Return To The Roots is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // Return To The Roots 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 Return To The Roots. If not, see <http://www.gnu.org/licenses/>. /////////////////////////////////////////////////////////////////////////////// // Header #include "defines.h" #include "iwEndgame.h" #include "Loader.h" #include "GameManager.h" #include "desktops/dskMainMenu.h" #include "iwSave.h" #include "WindowManager.h" #include "GameClient.h" /////////////////////////////////////////////////////////////////////////////// // Makros / Defines #if defined _WIN32 && defined _DEBUG && defined _MSC_VER #define new new(_NORMAL_BLOCK, THIS_FILE, __LINE__) #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////////// /** * Konstruktor von @p iwEndgame. * * @author OLiver */ iwEndgame::iwEndgame(void) : IngameWindow(CGI_ENDGAME, 0xFFFF, 0xFFFF, 240, 100, _("End game?"), LOADER.GetImageN("resource", 41)) { // Ok AddImageButton(0, 16, 24, 71, 57, TC_GREEN2, LOADER.GetImageN("io", 32)); //-V525 // Abbrechen AddImageButton(1, 88, 24, 71, 57, TC_RED1, LOADER.GetImageN("io", 40)); // Ok + Speichern AddImageButton(2, 160, 24, 65, 57, TC_GREY, LOADER.GetImageN("io", 47)); } void iwEndgame::Msg_ButtonClick(const unsigned int ctrl_id) { switch(ctrl_id) { case 0: // OK { GAMEMANAGER.ShowMenu(); GAMECLIENT.ExitGame(); } break; case 1: // Abbrechen { Close(); } break; case 2: // OK + Speichern { WINDOWMANAGER.Show(new iwSave()); } break; } }
ikharbeq/s25client
src/ingameWindows/iwEndgame.cpp
C++
gpl-3.0
2,321
package dotest.module.frame.debug; import android.app.Activity; import core.interfaces.DoIPageViewFactory; public class DoPageViewFactory implements DoIPageViewFactory { private Activity currentActivity; @Override public Activity getAppContext() { // TODO Auto-generated method stub return currentActivity; } @Override public void openPage(String arg0, String arg1, String arg2, String arg3, String arg4, String arg5, String arg6, String arg7) { // TODO Auto-generated method stub } public void setCurrentActivity(Activity currentActivity) { this.currentActivity = currentActivity; } @Override public void closePage(String _animationType, String _data, int _continue) { // TODO Auto-generated method stub } }
do-android/do_BaiduMapView
doExt_do_BaiduMapView/src/dotest/module/frame/debug/DoPageViewFactory.java
Java
gpl-3.0
748
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-01-09 11:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tmv_app', '0072_runstats_dyn_win_threshold'), ] operations = [ migrations.AlterField( model_name='runstats', name='dyn_win_threshold', field=models.FloatField(default=0.1), ), ]
mcallaghan/tmv
BasicBrowser/tmv_app/migrations/0073_auto_20180109_1124.py
Python
gpl-3.0
471
#include "SQLParserResult.h" namespace hsql { SQLParserResult::SQLParserResult() : isValid_(true), errorMsg_(NULL) {}; SQLParserResult::SQLParserResult(SQLStatement* stmt) : isValid_(true), errorMsg_(NULL) { addStatement(stmt); }; SQLParserResult::~SQLParserResult() { for (SQLStatement* statement : statements_) { delete statement; } free(errorMsg_); } void SQLParserResult::addStatement(SQLStatement* stmt) { statements_.push_back(stmt); } const SQLStatement* SQLParserResult::getStatement(int index) const { return statements_[index]; } SQLStatement* SQLParserResult::getMutableStatement(int index) { return statements_[index]; } size_t SQLParserResult::size() const { return statements_.size(); } bool SQLParserResult::isValid() const { return isValid_; } const char* SQLParserResult::errorMsg() const { return errorMsg_; } int SQLParserResult::errorLine() const { return errorLine_; } int SQLParserResult::errorColumn() const { return errorColumn_; } void SQLParserResult::setIsValid(bool isValid) { isValid_ = isValid; } void SQLParserResult::setErrorDetails(char* errorMsg, int errorLine, int errorColumn) { errorMsg_ = errorMsg; errorLine_ = errorLine; errorColumn_ = errorColumn; } } // namespace hsql
msdeep14/DeepDataBase
sql-parser/src/SQLParserResult.cpp
C++
gpl-3.0
1,363
namespace _6.Customers_Migration { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class StoreLocation { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public StoreLocation() { Sales = new HashSet<Sale>(); } public int Id { get; set; } public string LocationName { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Sale> Sales { get; set; } } }
PlamenHP/Softuni
Entity Framework/Entity Framework Code First/6. Customers Migration/StoreLocation.cs
C#
gpl-3.0
782
# smallest number 2^500500 divisors , modulo 500500507 # 单调递减 # (2^a0)(2^a1)(2^a2) = 2^500500 # (2^ai)(2^aj) -> (2^{ai-1})(2^{aj+1}) : p_j^(2^{aj})/p_i^(2^{ai-1}) < 1 , (a > b) # (2^aj)ln(p_j) < (2^{ai-1})ln(p_i) # if 2^{a_i-a_j-1} > ln(p_j)/ln(p_i), then a_i-=1,a_j-=1 # # i < j # p_j^(2^(a_j-1)) < p_i^(2^a_i) # p_i^(2^(a_i-1)) < p_j^(2^a_j) # # (n-log(log(p_i)/log(p_j)/2)/log(2))/2 > ai > (n-log(2*log(p_i)/log(p_j))/log(2))/2 # # n = a_i+a_j # a_i = floor( # ( # n + 1 - (log( # log(p_i)/log(p_j) # )/log(2)) # )/2 # ) import math N = 9_000_000 MOD = 500500507 def mypow(v, mi): r = 1 while mi > 0: if mi % 2 == 1: r *= v r %= MOD v *= v v %= MOD mi //= 2 return r def prepare(): p = [0 for i in range(N+10)] ps = [] for i in range(2,N+1): if p[i] != 0: continue; ps.append(i) j = i*i while j <= N: p[j] = i j+=i print("prime count:",len(ps),",max prime:",ps[-1]) logij = [0 for i in range(500500)] for i in range(500500): logij[i] = math.log(math.log(ps[i])/math.log(ps[i+1])/2)/math.log(4) print("logij finished") # p[i] = i is prime # ps : prime s # logij : adjacent # sum 以外的部分 return p,ps,logij # dst 幂次 , p 质数校验数组, ps质数数组, 预先运算 sum以外部分 def main(dst,p,ps,logij): ans = [0 for i in range(500500)] ans[0] = dst maxi = 1 # ans 长度 loop = True while loop: loop = False i = 0 # for range not work when i want modify i while i+1 < len(ans) and ans[i] > 0: cnt = ans[i]+ans[i+1] dstai = math.floor(cnt/2 - logij[i]) if dstai != ans[i]: ans[i] = dstai; ans[i+1] = cnt - dstai # just from last start if i > 0: i -= 1 continue i+=1 if i >= maxi and ans[i] > 0: maxi = i+1 print(f"len[{maxi}]\tfirst[{ans[0]}]\tlast[{ans[i]}]", flush=True) assert(i+1 < len(ans)) assert(ans[maxi] == 0) # print("arr:",ans[:maxi]) print(f"fixlen [{maxi}]\tfirst[{ans[0]}]\tlast[{ans[maxi-1]}]", flush=True) # check movable first and last # if math.log(math.log(ps[maxi])/math.log(2)) < math.log(2)*(ans[0]-1): newans0 = math.floor((ans[0]+1-math.log(math.log(2)/math.log(ps[maxi]))/math.log(2))/2) if newans0 != ans[0]: ans[maxi] = ans[0] - newans0 ans[0] = newans0 assert(ans[0] > 0) assert(ans[maxi] > 0) loop = True output = 1 for i in range(len(ans)): output *= mypow(ps[i],2**ans[i] - 1); output %= MOD print("ans:", output, flush=True) p,ps,logij = prepare() main(4,p,ps,logij) main(500500,p,ps,logij) # len[206803] first[5] last[1] # fixlen [206803] first[5] last[1] # ans: 287659177 # 跑了3个小时 , 没有所有位满足最小
CroMarmot/MyOICode
ProjectEuler/unsolved/p500.py
Python
gpl-3.0
3,132
# -*- coding: utf-8 -*- """ Created on Sun Mar 29 18:02:06 2015 """ ##################################################################################################### # Groupe d'Étude pour la Traduction/le Traitement Automatique des Langues et de la Parole (GETALP) # Homepage: http://getalp.imag.fr # # Author: Tien LE (ngoc-tien.le@imag.fr) # Advisors: Laurent Besacier & Benjamin Lecouteux # URL: tienhuong.weebly.com ##################################################################################################### import os import sys import datetime #when import module/class in other directory sys.path.append(os.path.join(os.path.dirname(__file__), '..'))#in order to test with line by line on the server from feature.common_functions import * from config.configuration import * #**************************************************************************# def get_duration(datetime_start, datetime_end): dt1 = datetime.datetime.strptime(datetime_start, '%Y-%m-%d %H:%M:%S.%f') dt2 = datetime.datetime.strptime(datetime_end, '%Y-%m-%d %H:%M:%S.%f') duration = dt2-dt1 return duration #**************************************************************************# """ noruego NOUN de OTHER """ def count_num_of_words_for_polysemy_count_target(file_input_path): if not os.path.exists(file_input_path): raise TypeError('Not Existed file corpus input with format - column') #end if #for reading: file_input_path file_reader = open(file_input_path, mode = 'r', encoding = 'utf-8') num_of_words_all = 0 num_of_words_other = 0 str_other = "OTHER" for line in file_reader: line = line.strip() if len(line) == 0: continue #end if num_of_words_all += 1 items = split_string_to_list_delimeter_tab(line) if items[1].strip() == str_other: num_of_words_other += 1 #end if #end for #close file file_reader.close() num_of_words_result = num_of_words_all - num_of_words_other print("num_of_words_all = %d" %num_of_words_all) print("num_of_words_result = %d" %num_of_words_result) #**************************************************************************# def convert_from_second_to_format_h_m_s(num_of_second): m, s = divmod(num_of_second, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) print("d:h:m:s = %d:%d:%02d:%02d" % (d, h, m, s)) #**************************************************************************# #**************************************************************************# #**************************************************************************# #**************************************************************************# if __name__ == "__main__": #Test case: current_config = load_configuration() datetime_start="2015-03-31 20:09:23.282432" datetime_end="2015-04-01 00:25:42.996360" dt = get_duration(datetime_start, datetime_end) print(dt) file_input_path = current_config.BABEL_NET_CORPUS_ES count_num_of_words_for_polysemy_count_target(file_input_path) convert_from_second_to_format_h_m_s(449369) print ('OK')
besacier/WCE-LIG
wce_system/preprocessing/measure_performance_system.py
Python
gpl-3.0
3,171
using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_ParticleSystem_CollisionModule : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule o; o=new UnityEngine.ParticleSystem.CollisionModule(); pushValue(l,true); pushValue(l,o); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetPlane(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); System.Int32 a1; checkType(l,2,out a1); UnityEngine.Transform a2; checkType(l,3,out a2); self.SetPlane(a1,a2); pushValue(l,true); setBack(l,self); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetPlane(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); System.Int32 a1; checkType(l,2,out a1); var ret=self.GetPlane(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_enabled(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.enabled); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_enabled(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.enabled=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_type(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushEnum(l,(int)self.type); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_type(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystemCollisionType v; checkEnum(l,2,out v); self.type=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_mode(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushEnum(l,(int)self.mode); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_mode(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystemCollisionMode v; checkEnum(l,2,out v); self.mode=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_dampen(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.dampen); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_dampen(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystem.MinMaxCurve v; checkValueType(l,2,out v); self.dampen=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_bounce(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.bounce); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_bounce(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystem.MinMaxCurve v; checkValueType(l,2,out v); self.bounce=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_lifetimeLoss(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.lifetimeLoss); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_lifetimeLoss(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystem.MinMaxCurve v; checkValueType(l,2,out v); self.lifetimeLoss=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_minKillSpeed(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.minKillSpeed); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_minKillSpeed(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.minKillSpeed=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_maxKillSpeed(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.maxKillSpeed); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_maxKillSpeed(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.maxKillSpeed=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_collidesWith(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.collidesWith); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_collidesWith(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.LayerMask v; checkValueType(l,2,out v); self.collidesWith=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_enableDynamicColliders(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.enableDynamicColliders); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_enableDynamicColliders(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.enableDynamicColliders=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_enableInteriorCollisions(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.enableInteriorCollisions); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_enableInteriorCollisions(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.enableInteriorCollisions=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_maxCollisionShapes(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.maxCollisionShapes); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_maxCollisionShapes(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); int v; checkType(l,2,out v); self.maxCollisionShapes=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_quality(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushEnum(l,(int)self.quality); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_quality(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystemCollisionQuality v; checkEnum(l,2,out v); self.quality=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_voxelSize(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.voxelSize); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_voxelSize(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.voxelSize=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_radiusScale(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.radiusScale); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_radiusScale(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.radiusScale=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_sendCollisionMessages(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.sendCollisionMessages); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_sendCollisionMessages(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.sendCollisionMessages=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_maxPlaneCount(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.maxPlaneCount); return 2; } catch(Exception e) { return error(l,e); } } static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.ParticleSystem.CollisionModule"); addMember(l,SetPlane); addMember(l,GetPlane); addMember(l,"enabled",get_enabled,set_enabled,true); addMember(l,"type",get_type,set_type,true); addMember(l,"mode",get_mode,set_mode,true); addMember(l,"dampen",get_dampen,set_dampen,true); addMember(l,"bounce",get_bounce,set_bounce,true); addMember(l,"lifetimeLoss",get_lifetimeLoss,set_lifetimeLoss,true); addMember(l,"minKillSpeed",get_minKillSpeed,set_minKillSpeed,true); addMember(l,"maxKillSpeed",get_maxKillSpeed,set_maxKillSpeed,true); addMember(l,"collidesWith",get_collidesWith,set_collidesWith,true); addMember(l,"enableDynamicColliders",get_enableDynamicColliders,set_enableDynamicColliders,true); addMember(l,"enableInteriorCollisions",get_enableInteriorCollisions,set_enableInteriorCollisions,true); addMember(l,"maxCollisionShapes",get_maxCollisionShapes,set_maxCollisionShapes,true); addMember(l,"quality",get_quality,set_quality,true); addMember(l,"voxelSize",get_voxelSize,set_voxelSize,true); addMember(l,"radiusScale",get_radiusScale,set_radiusScale,true); addMember(l,"sendCollisionMessages",get_sendCollisionMessages,set_sendCollisionMessages,true); addMember(l,"maxPlaneCount",get_maxPlaneCount,null,true); createTypeMetatable(l,constructor, typeof(UnityEngine.ParticleSystem.CollisionModule),typeof(System.ValueType)); } }
yongkangchen/poker-client
Assets/Runtime/Slua/LuaObject/Unity/Lua_UnityEngine_ParticleSystem_CollisionModule.cs
C#
gpl-3.0
14,303
package tensor2go type Scalar struct { *Tensor } func NewScalar(val interface{}) (v *Scalar){ v = &Scalar{NewTensor()} v.Tensor.tensorRoot = v.Tensor.graph.CreateVertex("root",val) return } func (s *Scalar) Val() interface{} { return s.Tensor.tensorRoot.Properties() } func (s *Scalar) Multiply(val interface{})(r interface{}){ m, ok := s.Val().(Multiplier) if !ok { panic("Value is not a multiplier") } if v, ok := val.(*Scalar); ok { r = m.Multiply(v.Val()) } return }
joernweissenborn/tensor2go
scalar.go
GO
gpl-3.0
491
/************************************************************************************************** * This file is part of Connect X. * * Connect X 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. * * Connect X 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 Connect X. If not, see <https://www.gnu.org/licenses/>. * *************************************************************************************************/ /**********************************************************************************************//** * @file GameBoard.cpp * @date 2020 * *************************************************************************************************/ #include <algorithm> #include <gdkmm/display.h> #include <cxinv/include/assertion.h> #include <cxmodel/include/Disc.h> #include <Board.h> #include <DiscChip.h> #include <IGameViewController.h> #include <IGameViewPresenter.h> constexpr bool FULLY_HANDLED = true; constexpr bool PROPAGATE = false; namespace { // Computes the best chip dimension so that the game view, when the board is present with all // chips drawn, is entirely viewable on the user's screen. int ComputeMinimumChipSize(const cxgui::Board& p_board, size_t p_nbRows, size_t p_nbColumns) { // Get screen containing the widget: const Glib::RefPtr<const Gdk::Screen> screen = p_board.get_screen(); IF_CONDITION_NOT_MET_DO(bool(screen), return -1;); // Get the screen dimensions: const int fullScreenHeight = screen->get_height(); const int fullScreenWidth = screen->get_width(); // Get minimum screen dimension: const int minFullScreenDimension = std::min(fullScreenHeight, fullScreenWidth); // First, we check if the chips can use their default size: int nbRows = static_cast<int>(p_nbRows); int nbColumns = static_cast<int>(p_nbColumns); if(nbRows * cxgui::DEFAULT_CHIP_SIZE < (2 * fullScreenHeight) / 3) { if(nbColumns * cxgui::DEFAULT_CHIP_SIZE < (2 * fullScreenWidth) / 3) { return cxgui::DEFAULT_CHIP_SIZE; } } // The the biggest board dimension: const int maxBoardDimension = std::max(nbRows, nbColumns); // From this, the max chip dimension (dimension at which together, chips from the board would fill the // entire screen in its smallest dimension) is computed: const int maxChipDimension = (minFullScreenDimension / maxBoardDimension); // We take two thirds from this value for the board (leaving the remaining to the rest of the // game view): return (maxChipDimension * 2) / 3; } } // namespace cxgui::Board::Board(const IGameViewPresenter& p_presenter, IGameViewController& p_controller) : m_presenter{p_presenter} , m_controller{p_controller} , m_currentDiscPosition{0u} { set_orientation(Gtk::Orientation::ORIENTATION_VERTICAL); InitializeNextDiscArea(m_presenter.GetGameViewBoardWidth()); InitializeBoard(m_presenter.GetGameViewBoardHeight(), m_presenter.GetGameViewBoardWidth()); pack1(m_nextDiscAreaLayout, true, false); pack2(m_boardLayout, true, false); } void cxgui::Board::DropChip() { Chip* chip = GetChip(m_nextDiscAreaLayout, m_currentDiscPosition, 0); IF_CONDITION_NOT_MET_DO(chip, return;); m_controller.OnDown(chip->GetColor(), m_currentDiscPosition); } void cxgui::Board::MoveLeft() { Move(Side::Left); } void cxgui::Board::MoveRight() { Move(Side::Right); } void cxgui::Board::Update(Context p_context) { switch(p_context) { case Context::CHIP_DROPPED: { MoveCurrentDiscAtFirstRow(); RefreshBoardArea(); break; } case Context::GAME_WON: { ClearNextDiscArea(); RefreshBoardArea(); break; } case Context::GAME_REINITIALIZED: { MoveCurrentDiscAtFirstRow(); ClearBoardArea(); break; } } } cxgui::Chip* cxgui::Board::GetChip(Gtk::Grid& p_discArea, int p_left, int p_top) { Widget* child = p_discArea.get_child_at(p_left, p_top); IF_CONDITION_NOT_MET_DO(child, return nullptr;); Chip* chip = dynamic_cast<Chip*>(child); IF_CONDITION_NOT_MET_DO(child, return nullptr;); return chip; } void cxgui::Board::Move(Side p_side) { ChangeCurrentDisc(cxmodel::MakeTransparent()); UpdateNextDiscPosition(p_side); ChangeCurrentDisc(m_presenter.GetGameViewActivePlayerChipColor()); } void cxgui::Board::ChangeCurrentDisc(const cxmodel::ChipColor& p_newColor) { Chip* chip = GetChip(m_nextDiscAreaLayout, m_currentDiscPosition, 0); IF_CONDITION_NOT_MET_DO(chip, return;); chip->ChangeColor(p_newColor); } void cxgui::Board::UpdateNextDiscPosition(Side p_side) { if(p_side == Side::Left) { if(m_currentDiscPosition > 0) { --m_currentDiscPosition; } else { m_currentDiscPosition = m_presenter.GetGameViewBoardWidth() - 1; } } else { if(m_currentDiscPosition < m_presenter.GetGameViewBoardWidth() - 1) { ++m_currentDiscPosition; } else { m_currentDiscPosition = 0u; } } } void cxgui::Board::InitializeNextDiscArea(size_t p_width) { const int chipDimension = ComputeMinimumChipSize(*this, m_presenter.GetGameViewBoardHeight(), m_presenter.GetGameViewBoardWidth()); m_nextDiscAreaLayout.set_row_homogeneous(true); m_nextDiscAreaLayout.set_column_homogeneous(true); Chip* activePlayerChip = Gtk::manage(new DiscChip{m_presenter.GetGameViewActivePlayerChipColor(), cxmodel::MakeTransparent(), chipDimension}); activePlayerChip->set_vexpand(true); activePlayerChip->set_hexpand(true); m_nextDiscAreaLayout.attach(*activePlayerChip, 0, 0, 1, 1); for(size_t i = 1; i < p_width; ++i) { Chip* noChip = Gtk::manage(new DiscChip{cxmodel::MakeTransparent(), cxmodel::MakeTransparent(), chipDimension}); noChip->set_vexpand(true); noChip->set_hexpand(true); m_nextDiscAreaLayout.attach(*noChip, i, 0, 1, 1); } } void cxgui::Board::InitializeBoard(size_t p_height, size_t p_width) { const int chipDimension = ComputeMinimumChipSize(*this, m_presenter.GetGameViewBoardHeight(), m_presenter.GetGameViewBoardWidth()); m_boardLayout.set_row_homogeneous(true); m_boardLayout.set_column_homogeneous(true); for(size_t i = 0; i < p_height; ++i) { for(size_t j = 0; j < p_width; ++j) { Chip* noChip = Gtk::manage(new DiscChip{cxmodel::MakeTransparent(), cxmodel::MakeBlue(), chipDimension}); noChip->set_vexpand(true); noChip->set_hexpand(true); m_boardLayout.attach(*noChip, j, i, 1, 1); } } } void cxgui::Board::MoveCurrentDiscAtFirstRow() { Chip* currentChip = GetChip(m_nextDiscAreaLayout, m_currentDiscPosition, 0); IF_CONDITION_NOT_MET_DO(currentChip, return;); currentChip->ChangeColor(cxmodel::MakeTransparent()); m_currentDiscPosition = 0u; Chip* startChip = GetChip(m_nextDiscAreaLayout, m_currentDiscPosition, 0); IF_CONDITION_NOT_MET_DO(startChip, return;); startChip->ChangeColor(m_presenter.GetGameViewActivePlayerChipColor()); } void cxgui::Board::RefreshBoardArea() { const cxgui::IGameViewPresenter::ChipColors& chipColors = m_presenter.GetGameViewChipColors(); for(size_t row = 0u; row < m_presenter.GetGameViewBoardHeight(); ++row) { for(size_t column = 0u; column < m_presenter.GetGameViewBoardWidth(); ++column) { Chip* chip = GetChip(m_boardLayout, column, row); IF_CONDITION_NOT_MET_DO(chip, return;); chip->ChangeColor(chipColors[row][column]); } } } void cxgui::Board::ClearNextDiscArea() { for(size_t column = 0u; column < m_presenter.GetGameViewBoardWidth(); ++column) { Chip* chip = GetChip(m_nextDiscAreaLayout, column, 0u); IF_CONDITION_NOT_MET_DO(chip, return;); chip->ChangeColor(cxmodel::MakeTransparent()); } } void cxgui::Board::ClearBoardArea() { for(size_t row = 0u; row < m_presenter.GetGameViewBoardHeight(); ++row) { for(size_t column = 0u; column < m_presenter.GetGameViewBoardWidth(); ++column) { Chip* chip = GetChip(m_boardLayout, column, row); IF_CONDITION_NOT_MET_DO(chip, return;); chip->ChangeColor(cxmodel::MakeTransparent()); } } }
BobMorane22/ConnectX
cxgui/src/Board.cpp
C++
gpl-3.0
8,959
using CatalokoSite.Models; using CatalokoSite.Models.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CatalokoSite.Controllers { public class MarketController : Controller { [Route("~/market")] public ActionResult Noticias() { var model = new OpenGraph { title = "Market", description = "Compre e venda no Catáloko", image = "" }; return View(Config.ResolveMasterView(this.HttpContext), model); } } }
albertoroque/cataloko
site/CatalokoSite/Controllers/MarketController.cs
C#
gpl-3.0
642
// This file is part of LEDStick_TFT. // // LEDStick_TFT 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. // // LEDStick_TFT 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 LEDStick_TFT.If not, see <http://www.gnu.org/licenses/>. #include "RGBController.h" #include "RGBBitmap.h" #define RGB_SCALE 10 void RGBController::create_interface_components(StickHardware hardware, uint32_t x, uint32_t y) { m_hardware = hardware; m_xmin = x; m_xmax = (COLOR_PICKER_WIDTH * RGB_SCALE) + x; m_ymin = y; m_ymax = (COLOR_PICKER_HEIGHT * RGB_SCALE) + y; hardware.pTft->drawBitmap(x, y, COLOR_PICKER_WIDTH, COLOR_PICKER_HEIGHT, (unsigned int*)color_picker_bmp, RGB_SCALE); } void RGBController::check_point(uint32_t x, uint32_t y, RGB &rgb, boolean has_changed) { if (x < m_xmin || y < m_ymin || x > m_xmax || y > m_ymax) { has_changed = false; return; } m_hardware.pTft->setColor(255, 0, 0); uint32_t point_in_bitmap_x = (x - m_xmin) / RGB_SCALE; uint32_t point_in_bitmap_y = (y - m_ymin) / RGB_SCALE; uint32_t color = pgm_read_word(color_picker_bmp + (point_in_bitmap_y * COLOR_PICKER_WIDTH) + point_in_bitmap_x); rgb.red = ((((color >> 11) & 0x1F) * 527) + 23) >> 6; rgb.green = ((((color >> 5) & 0x3F) * 259) + 33) >> 6; rgb.blue = (((color & 0x1F) * 527) + 23) >> 6; has_changed = true; }
dipsylala/LEDStick_TFT
RGBController.cpp
C++
gpl-3.0
1,772
package GUI; import Logic.AI; import Logic.Board; import Logic.Player; import Logic.SpecialCoord; import Pieces.Coordinate; import Pieces.MasterPiece; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.SnapshotParameters; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.PixelReader; import javafx.scene.image.WritableImage; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Modality; import javafx.stage.Stage; import sun.java2d.loops.GraphicsPrimitive; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; import java.util.Stack; import java.util.concurrent.Exchanger; /*** * Controller Class * This class is responsible for managing the logic behind the GUI. * Intensive logic processes should be run in a separate thread as they will cause the GUI to freeze. * * @author Patrick Shinn * @version 10/28/16 */ public class Controller { // FXML Objects @FXML Label statusLbl = new Label(); @FXML Pane gamePane = new Pane(); @FXML Button undoButton = new Button(); @FXML Button redoButton = new Button(); @FXML ImageView boardStateView = new ImageView(); @FXML Label stateLbl = new Label(); @FXML Canvas canvas = new Canvas(); // Board Shit and such private Board board; // the board for the game. private GraphicsContext graphics; // for drawing private boolean clicked = false; private boolean game = false; private Coordinate[] currentMoveSet = null; // for making moves private Coordinate currentPiece = null; // for making moves private Stack<Board> undoBoard = new Stack<>(); // undo, redo stacks private Stack<Image> undoImage = new Stack<>(); private Stack<Board> redoBoard = new Stack<>(); private Stack<Image> redoImage = new Stack<>(); private String boardTheme = "RedBrown"; // theme info private String tableImage = "wooden"; private String pieceTheme = "default"; private boolean AI = false; // AI info private int oldMouseX = 0; private int oldMouseY = 0; // pieces private Image whitePawn = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whitePawn.png")); private Image whiteKnight = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whiteKnight.png")); private Image whiteRook = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whiteRook.png")); private Image whiteBishop = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whiteBishop.png")); private Image whiteQueen = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whiteQueen.png")); private Image whiteKing = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whiteKing.png")); private Image blackPawn = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackPawn.png")); private Image blackKnight = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackKnight.png")); private Image blackRook = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackRook.png")); private Image blackBishop = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackBishop.png")); private Image blackQueen = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackQueen.png")); private Image blackKing = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackKing.png")); // this will initialize the change listeners and such at when the game is started. public void initialize() { try { // try to apply the users settings from the last game. Scanner settingsReader = new Scanner(new File("Settings.txt")); boardTheme = settingsReader.nextLine(); // read the first line of the settings file and apply it to the board theme tableImage = settingsReader.nextLine(); // second line is the table image pieceTheme = settingsReader.nextLine(); // third is piece theme. settingsReader.close(); }catch (FileNotFoundException e){ // ignore, the game has never been played before or the default settings have never been changed. } // update the status label statusLbl.setText("No game."); // get the ability to draw on it graphics = canvas.getGraphicsContext2D(); // painting on the table top and the empty board. Image table = new Image(getClass().getResourceAsStream("/Graphics/Images/Tables/"+tableImage+"TableTop.png")); graphics.drawImage(table, 0, 0); // draws from the top part of the canvas. freshBoard(); } // settings dialogue public void settings() { new SettingsWindow(); } // shows the instructions on how to play public void info(){new DirectionsWindow();} // opens the about dialogue public void about() { new AboutWindow("About", "Wahjudi’s Highly Advanced Chess", "1.0", "This is an insane version of chess!", "Can't Trump This", "https://github.com/shinn16/Chess"); } // creates a new game public void newGame() { new NewGameWindow(); } // undo the last move. public void undo() { // this stuff is heavily try catched so the popping of one does not interfere with the other. if (!undoBoard.empty() && AI) { // if we are playing against an AI and the stack is not empty try { redoBoard.push(board.copyOf()); // skips the AI turn board = undoBoard.pop(); // gets the last state of the board } catch (Exception e) { // ignore } try { redoImage.push(boardStateView.getImage()); boardStateView.setImage(undoImage.pop()); boardStateView.autosize(); } catch (Exception e) { // ignore } freshBoard(); drawPieces(); redoButton.setDisable(false); if (undoBoard.empty()) undoButton.setDisable(true); // if we have emptied the stack, disable undo // correcting the turn if we need to. int correctTurn = 0; for (Player player: board.getPlayers()){ if (!player.getType().equals("AI")) board.setTurnCounter(correctTurn); else correctTurn ++; } }else{ // we disable the buttons undoButton.setDisable(true); redoButton.setDisable(true); } } // redo the last move public void redo(){ if (!redoBoard.empty() && AI) { try { undoBoard.push(board.copyOf()); // pushing current board then skipping AI moves board = redoBoard.pop(); // gets the last state of the board } catch (Exception e) { // ignore } try { undoImage.push(redoImage.peek()); boardStateView.setImage(redoImage.pop()); // sets the old state image boardStateView.autosize(); } catch (Exception e) { // ignore } freshBoard(); drawPieces(); undoButton.setDisable(false); if (redoBoard.empty()) redoButton.setDisable(true); // correcting the turn if we need to. int correctTurn = 0; for (Player player: board.getPlayers()){ if (!player.getType().equals("AI")) board.setTurnCounter(correctTurn); else correctTurn ++; } }else redoButton.setDisable(true); } // draws the background table private void drawTable(){ graphics.drawImage(new Image(getClass().getResourceAsStream("/Graphics/Images/Tables/"+tableImage+"TableTop.png")), 0, 0); } // redraws board private void freshBoard(){ // draw the new board for the new game. graphics.setStroke(Color.BLACK); // settings up to draw a black border for the board. graphics.setLineWidth(5); // sets the weight of the line for the border graphics.strokeRect(150, 50, 500, 500); // draws rectangle if (boardTheme.equals("glass")){ graphics.setGlobalAlpha(.60); // reduce the opacity if we are painting on the glass. drawTable(); // redraw the table on top so we don't lose our opacity due to us drawing over it multiple times. } // draws the board. for (int y = 0; y < 5; y ++){ // for the y for (int x = 0; x < 5; x ++){ // for the x if ((x+y)%2 == 0){ // tells us which images to use for this spot on the board. graphics.drawImage(new Image(getClass().getResourceAsStream("/Graphics/Images/"+boardTheme+"/blackSpot.png")), (x * 100) + 150, (y * 100) +50); // draws a 100X100 black spot centered }else { graphics.drawImage(new Image(getClass().getResourceAsStream("/Graphics/Images/"+boardTheme+"/whiteSpot.png")), (x * 100) + 150, (y * 100) + 50); // draws a 100X100 white spot centered } } } graphics.setGlobalAlpha(1); graphics.setStroke(Color.AQUA); // new highlight color graphics.setLineWidth(2); // new line width. } // redraws pieces private void drawPieces(){ // draw the pieces on the board // black side if (game){ // if there is a game on, we will draw the pieces at their given coordinates. for (Player player: board.getPlayers()){ for (MasterPiece[] row: board.getBoard()){ for (MasterPiece piece: row){ if (piece != null){ if (piece.getPlayerID() == 0){ try { if (piece.toString().contains("King")) graphics.drawImage(blackKing, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 -50); else if (piece.toString().contains("Queen")) graphics.drawImage(blackQueen, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 -50); else if (piece.toString().contains("Rook")) graphics.drawImage(blackRook, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 - 50); else if (piece.toString().contains("Knight")) graphics.drawImage(blackKnight, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 -50); else if (piece.toString().contains("Bishop")) graphics.drawImage(blackBishop, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 - 50); else if (piece.toString().contains("Pawn")) graphics.drawImage(blackPawn, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 - 50); }catch (NullPointerException e) { // ignore } }else { try{ if (piece.toString().contains("King"))graphics.drawImage(whiteKing, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); else if (piece.toString().contains("Queen")) graphics.drawImage(whiteQueen, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); else if (piece.toString().contains("Rook")) graphics.drawImage(whiteRook, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); else if (piece.toString().contains("Knight")) graphics.drawImage(whiteKnight, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); else if (piece.toString().contains("Bishop")) graphics.drawImage(whiteBishop, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); else if (piece.toString().contains("Pawn")) graphics.drawImage(whitePawn, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); }catch (NullPointerException e) { // ignore } } } } } } }else { // fresh set of pieces graphics.drawImage(blackKing, 150, 50); graphics.drawImage(blackQueen, 250, 50); graphics.drawImage(blackBishop, 350, 50); graphics.drawImage(blackKnight, 450, 50); graphics.drawImage(blackRook, 550, 50); for (int i = 1; i < 6; i++) graphics.drawImage(blackPawn, i * 100 + 50, 150); // white side graphics.drawImage(whiteRook, 150, 450); graphics.drawImage(whiteKnight, 250, 450); graphics.drawImage(whiteBishop, 350, 450); graphics.drawImage(whiteQueen, 450, 450); graphics.drawImage(whiteKing, 550, 450); for (int i = 1; i < 6; i++) graphics.drawImage(whitePawn, i * 100 + 50, 350); // reset the stroke color to be used for highlighting. graphics.setStroke(Color.AQUA); } } // updates the side pane image private void updateLastMoveImage(){ //takes a snap shot to be used as last state image WritableImage state = new WritableImage(700, 700); state = canvas.snapshot(new SnapshotParameters(), state); // cropping state PixelReader reader =state.getPixelReader(); WritableImage currentState = new WritableImage(reader, 150, 50, 500, 500); // shrinking image and displaying it, and adding it to the stack for undo if (game) { if (!board.getCurrentPlayer().getType().equals("AI"))undoImage.push(currentState); boardStateView.setImage(currentState); boardStateView.autosize(); } } // checks for winners private void checkWinner(){ if (!board.gameOver()) { String winner = null; Image winnerKing = null; // this portion determines the winner int whitePlayerPieces = 0; int blackPlayerPieces = 0; for (MasterPiece[] row: board.getBoard()){ for (MasterPiece piece: row){ if (piece != null){ if (piece.getPlayerID() == 0) whitePlayerPieces ++; else blackPlayerPieces ++; } } } if (whitePlayerPieces < blackPlayerPieces){ winner = "Black wins!"; winnerKing = blackKing; } else if (whitePlayerPieces > blackPlayerPieces){ winner = "White wins!"; winnerKing = whiteKing; } else{ winner = "Draw!"; winnerKing = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/draw.png")); } new EndOfGameWindow(winner, winnerKing); statusLbl.setText("Game over."); board.setLocked(true); game = false; redoButton.setDisable(true); undoButton.setDisable(true); } else { if (board.getCurrentPlayer().getPlayerNumber() == 0) statusLbl.setText("White's Turn"); else statusLbl.setText("Black's turn."); if (AI) undoButton.setDisable(false); board.nextTurn(); // advances to the next turn. // now we check to see if the next turn is an AI, if so, let it run AICheck(); } } // checks to see if an AI call is needed private void AICheck(){ if (board.gameOver()){ // if we are still playing a game. if (board.getCurrentPlayer().getType().equals("AI")){ board.setLocked(true); // locks the board so the user can't touch it. for (Player player: board.getPlayers()){ // this will invert the players so the AI plays with the correct player if (!player.equals(board.getCurrentPlayer())) new AIThread(player, board).run(); } } } } // gets the current mouse location public void getMouseHover(MouseEvent event) { try { if (game){ // if we are currently in a game int mouse_x = (int) event.getSceneX(); int mouse_y = (int) event.getSceneY(); // this will give us the index of the board position. mouse_x = (mouse_x - 50) / 100 - 1; mouse_y = (mouse_y + 20) / 100 - 1; if (!board.isLocked()){ // if the board is not locked if (!clicked) { // if the user has not already selected a piece to play with if (board.getPiece(mouse_y, mouse_x).getPlayerID() == board.getTurnCounter() && mouse_x == oldMouseX && mouse_y == oldMouseY){ // if the current piece belongs to the player and this is the most recent spot we have been to graphics.strokeRect((mouse_x + 1) * 100 + 52, (mouse_y + 1) * 100 - 48, 98, 98);// highlight the piece tile in blue }else { oldMouseX = mouse_x; oldMouseY = mouse_y; freshBoard(); drawPieces(); } } } } }catch (Exception e){ // ignore } } //gets the current location of the mouse click and does the appropriate actions public void getMouseClick(MouseEvent event) { try { int mouse_x = (int) event.getSceneX(); int mouse_y = (int) event.getSceneY(); // this will give us the index of the board position. mouse_x = (mouse_x - 50) / 100 - 1; mouse_y = (mouse_y + 20) / 100 - 1; // now we try to get a piece at these coordinates. // ensures we are on the board, otherwise resets all graphics in current state. if (board.isLocked()) new WarningWindow("Game Over!", "The game is over or the AI is thinking, either make a \nnew game or be patient."); else { if (mouse_x < 0 || mouse_y < 0 || mouse_x > 4 || mouse_y > 4) { if (game) { freshBoard(); drawPieces(); } if (clicked) undoBoard.pop(); clicked = false; currentMoveSet = null; currentPiece = null; }else if (clicked && currentPiece.equals(new Coordinate(mouse_x, mouse_y))){ // for some reason this case needs to appear. Logically it shouldn't, but this is a quick fix. clicked = false; freshBoard(); // update the board. drawPieces(); }else if (clicked) { // if we have already selected a piece if (currentMoveSet.length == 0) { // if we have no moves, clear the board of move options. clicked = false; freshBoard(); drawPieces(); } else { for (Coordinate move : currentMoveSet) { if (mouse_x == move.getX() && mouse_y == move.getY()) { // if the current click is in the move set, make the move. if (board.getPiece(move.getY(), move.getX()) != null) { // if there is an enemy piece at this point int pieceAttacked = board.getPiece(move.getY(), move.getX()).getArrayIndex(); // gets the index of the piece board.getPlayers()[board.getTurnCounter()].capturePiece(pieceAttacked); // remove the piece from the opponents list of pieces } board.makeMove(board.getPiece(currentPiece.getY(), currentPiece.getX()), mouse_y, mouse_x); // move the piece redoBoard = new Stack<>(); // dump the redo stack redoImage = new Stack<>(); // dump the redo images redoButton.setDisable(true); // disable the redo button because the stack is now empty updateLastMoveImage(); freshBoard(); // update the board. drawPieces(); clicked = false; // reset click checkWinner(); } else { // else, clear the stuff. clicked = false; freshBoard(); drawPieces(); } } } // if we have not already selected a piece and there is a piece at the current position, we also enforce turns here. } else if (board.getPiece(mouse_y, mouse_x) != null && board.getTurnCounter() == board.getPiece(mouse_y, mouse_x).getPlayerID()) { // if we have picked a piece of the current player. graphics.strokeRect((mouse_x + 1) * 100 + 52, (mouse_y + 1) * 100 - 48, 98, 98);// highlight the piece tile in blue if (board.hasAttack()) { // if the current player has an attack if (board.getPiece(mouse_y, mouse_x).hasAttack(board)) { // if the selected piece has an attack currentPiece = board.getPiece(mouse_y, mouse_x).getCoords(); // store this piece for the next run currentMoveSet = board.getPiece(mouse_y, mouse_x).getMoves(board); // store the moveset for the next run for (Coordinate coordinate : currentMoveSet) { //for every move in the move set, highlight the spots. graphics.setStroke(Color.RED); graphics.strokeRect((coordinate.getX() + 1) * 100 + 52, (coordinate.getY() + 1) * 100 - 48, 96, 96); } } } else { // if there are no attacks to be made, so any piece can move currentPiece = board.getPiece(mouse_y, mouse_x).getCoords(); // store this piece for the next run currentMoveSet = board.getPiece(mouse_y, mouse_x).getMoves(board); // store the moveset for the next run for (Coordinate coordinate : currentMoveSet) { //for every move in the move set, highlight the spots. // highlight it yellow. graphics.setStroke(Color.YELLOW); // set to yellow to highlight the moves graphics.strokeRect((coordinate.getX() + 1) * 100 + 52, (coordinate.getY() + 1) * 100 - 48, 96, 96); } } graphics.setStroke(Color.AQUA); // reset color undoBoard.push(board.copyOf()); clicked = true; // we have clicked a piece } } }catch (NullPointerException e){ // ignore } } // ------------------------------ Private internal classes ------------------------------ private class AboutWindow { private String windowName, developer, version, appName, website, aboutApp; private Stage window; private AboutWindow(String windowName, String appName, String version, String aboutApp, String developer, String website) { this.windowName = windowName; this.appName = appName; this.version = version; this.aboutApp = aboutApp; this.developer = developer; this.website = website; display(); } private void display() { // Stage setup window = new Stage(); window.setTitle(windowName); window.initModality(Modality.APPLICATION_MODAL); // means that while this window is open, you can't interact with the main program. // buttons Button closeBtn = new Button("Close"); closeBtn.setOnAction(e -> window.close()); // Labels Label appNameLabel = new Label(appName); Label websiteLabel = new Label("Website: " + website); Label aboutAppLabel = new Label(aboutApp); aboutAppLabel.setAlignment(Pos.CENTER); Label developerLabel = new Label("Developers: " + developer); Label versionLabel = new Label("Version: " + version); // Images ImageView imageView = new ImageView(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); // Layout type VBox layout = new VBox(10); HBox closeBox = new HBox(); closeBox.getChildren().addAll(closeBtn); closeBox.setAlignment(Pos.CENTER_RIGHT); closeBox.setPadding(new Insets(5, 5, 5, 5)); layout.getChildren().addAll(imageView, appNameLabel, developerLabel, versionLabel, aboutAppLabel, websiteLabel, closeBox); layout.setAlignment(Pos.CENTER); // Building scene and displaying. Scene scene = new Scene(layout); scene.getStylesheets().addAll("/Graphics/CSS/StyleSheet.css"); window.setScene(scene); window.setHeight(400); window.setWidth(550); window.setResizable(false); window.getIcons().add(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); window.show(); } } private class WarningWindow { // a warning window for when the user does something wrong. private String windowTitle; private String warning; WarningWindow(String windowTitle, String warning) { this.windowTitle = windowTitle; this.warning = warning; display(); } private void display() { // displays the window Stage window = new Stage(); window.setTitle(windowTitle); window.initModality(Modality.APPLICATION_MODAL); // means that while this window is open, you can't interact with the main program. // buttons Button closeBtn = new Button("Close"); closeBtn.setOnAction(e -> window.close()); // labels Label warningLabel = new Label(warning); // images ImageView warningImage = new ImageView(new Image(getClass().getResourceAsStream("/Graphics/Images/warning.png"))); // Building the window VBox layout = new VBox(10); HBox closeBox = new HBox(); closeBox.getChildren().addAll(closeBtn); closeBox.setAlignment(Pos.CENTER_RIGHT); closeBox.setPadding(new Insets(5, 5, 5, 5)); HBox hBox = new HBox(10); hBox.getChildren().addAll(warningImage, warningLabel); hBox.setAlignment(Pos.CENTER); layout.getChildren().addAll(hBox, closeBox); layout.setAlignment(Pos.CENTER); // Showing the window Scene scene = new Scene(layout); scene.getStylesheets().addAll("Graphics/CSS/StyleSheet.css"); window.setScene(scene); window.setHeight(200.00); window.setWidth(550.00); window.getIcons().add(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); window.show(); } } private class NewGameWindow { private Stage primaryStage = new Stage(); private Button playBtn = new Button("Play"); private Button closeBtn = new Button("Cancel"); private Label whiteLbl = new Label("White"); private Label blackLbl = new Label("Black"); private ComboBox<String> whiteOptions = new ComboBox<>(); private ComboBox<String> blackOptions = new ComboBox<>(); private ComboBox<String> firstPlayer = new ComboBox<>(); private Label goesFirst = new Label("Goes First"); private NewGameWindow() { statusLbl.setText("Setting up new game."); display(); } private void display() { // builds and displays the window. // setting up the buttons closeBtn.setOnAction(e -> cancelMethod()); playBtn.setOnAction(e -> playBtnMethod()); //settings up player options whiteOptions.getItems().addAll("Human", "AI"); blackOptions.getItems().addAll("Human", "AI"); firstPlayer.getItems().addAll("White" , "Black"); firstPlayer.setValue("White"); // layout setup VBox layout = new VBox(10); // white options section HBox whiteSection = new HBox(10); whiteOptions.setValue("None"); // value whiteSection.getChildren().addAll(whiteLbl, whiteOptions); whiteSection.setAlignment(Pos.CENTER); // black section options HBox blackSection = new HBox(10); blackOptions.setValue("None"); // initial value blackSection.getChildren().addAll(blackLbl, blackOptions); blackSection.setAlignment(Pos.CENTER); // button section HBox buttonsSection = new HBox(10); buttonsSection.setAlignment(Pos.CENTER_RIGHT); buttonsSection.getChildren().addAll(closeBtn, playBtn); buttonsSection.setPadding(new Insets(5, 5, 5, 5)); // setting spacing around the Hbox // building main layout layout.getChildren().addAll(whiteSection, blackSection, goesFirst, firstPlayer, buttonsSection); layout.setAlignment(Pos.CENTER); // building window Scene scene = new Scene(layout); scene.getStylesheets().addAll("/Graphics/CSS/StyleSheet.css"); // sets the style sheet. primaryStage.setScene(scene); primaryStage.setTitle("New Game"); primaryStage.initModality(Modality.APPLICATION_MODAL); // sets the window to be modal, meaning the underlying window cannot be used until this one is closed. primaryStage.setWidth(245); primaryStage.setHeight(210); primaryStage.setResizable(false); // this window cannot be resized. primaryStage.show(); // displays the window } private void cancelMethod(){ primaryStage.close(); statusLbl.setText("No game."); } private void playBtnMethod() { String playerOneType = whiteOptions.getValue(); String playerTwoType = blackOptions.getValue(); if (playerOneType.equals("None") || playerTwoType.equals("None"))// if the player failed to set one of the players properly new WarningWindow("Looks like there is something wrong with your settings...", "You have to apply settings for both players!"); else { // if the player has set up the right options for the game stateLbl.setOpacity(1); // makes this visible Player white = new Player(playerTwoType, 0); // set the player types Player black = new Player(playerOneType, 1); board = new Board(white, black); // set the board up with white going first. if (firstPlayer.getValue().equals("White")) statusLbl.setText("White's turn."); // sets the status label to who's turn it is else { board.setTurnCounter(0); statusLbl.setText("Black's turn."); } // dump the stacks from last run undoBoard = new Stack<>(); undoImage = new Stack<>(); redoBoard = new Stack<>(); redoImage = new Stack<>(); game = true; // we are now playing a game. freshBoard(); // draw board and pieces, then update last board state drawPieces(); updateLastMoveImage(); if ((playerOneType.equals("AI") || playerTwoType.equals("AI")) && (!(playerOneType.equals("AI") && playerTwoType.equals("AI")))) AI = true; AICheck(); primaryStage.close(); } } } private class EndOfGameWindow { private double width = 400; private Stage primaryStage = new Stage(); private Label messageLabel = new Label(); private Button okayButton = new Button("Okay"); private Image fireworks = new Image(getClass().getResourceAsStream("/Graphics/Images/fireworks.gif")); private ImageView leftWorks = new ImageView(fireworks); private ImageView rightWorks = new ImageView(fireworks); private ImageView winnerKingView = new ImageView(); private EndOfGameWindow(String message, Image winnerKing) { winnerKingView.setImage(winnerKing); messageLabel.setText(message); okayButton.setOnAction(e -> primaryStage.close()); if (message.equals("Draw!"))width = 500; // we need a bigger window to accommodate the draw image. // vbox VBox vertical = new VBox(20); vertical.getChildren().addAll(winnerKingView, messageLabel, okayButton); vertical.setPadding(new Insets(5, 5, 5, 5)); vertical.setAlignment(Pos.CENTER); // main layout HBox layout = new HBox(5); layout.getChildren().addAll(leftWorks, vertical, rightWorks); layout.setAlignment(Pos.CENTER); Scene scene = new Scene(layout); scene.getStylesheets().addAll("/Graphics/CSS/StyleSheet.css"); primaryStage.setScene(scene); primaryStage.initModality(Modality.APPLICATION_MODAL); // sets the window to be modal, meaning the underlying window cannot be used until this one is closed. primaryStage.setWidth(width); primaryStage.setHeight(250); primaryStage.setResizable(false); // this window cannot be resized.\ primaryStage.setTitle("End of Game"); // window title primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); // window icon primaryStage.show(); // displays the window } } private class SettingsWindow { private Stage primaryStage = new Stage(); // stages are basically windows private ComboBox<String> tableThemes = new ComboBox<>(); // allows the user to pick the theme of choice private ComboBox<String> boardThemes = new ComboBox<>(); private Label tableLabel = new Label("Table Themes"); private Label boardLabel = new Label("Board Themes"); private Button closeBtn = new Button("Close"); SettingsWindow(){ display(); } private void display(){ // sets the action for the button (close the window) closeBtn.setOnAction(e -> primaryStage.close()); closeBtn.setPadding(new Insets(2, 5, 5 ,5)); // adding objects to the comboBoxs, setting action of the box. tableThemes.getItems().addAll("wooden", "marble", "space", "secret"); // add all elements of the box here :) boardThemes.getItems().addAll("Grey and White", "Red and Brown", "Glass"); // setting up tableTheme box tableThemes.setValue(tableImage); // sets the current value to the currently selected theme. tableThemes.setPrefSize(125, 25); tableThemes.setOnAction(event -> tableThemeMethod()); // setting up boardTheme board if (boardTheme.equals("RedBrown")) boardThemes.setValue("Red and Brown"); else if (boardTheme.equals("default"))boardThemes.setValue("Grey and White"); else boardThemes.setValue("Glass"); boardThemes.setPrefSize(125, 25); boardThemes.setOnAction(e -> boardThemeMethod()); // building the layout of the scene VBox layout = new VBox(25); // main layout, will contain the others // sub layouts for object placement HBox labels = new HBox(23); labels.getChildren().addAll(tableLabel, boardLabel); labels.setAlignment(Pos.CENTER); HBox combos = new HBox(10); combos.getChildren().addAll(tableThemes, boardThemes); combos.setAlignment(Pos.CENTER); // building the layout layout.getChildren().addAll(labels, combos, closeBtn); layout.setAlignment(Pos.CENTER); layout.setMargin(labels, new Insets(0,0,0 -20,0)); // building and displaying the window (primaryStage) Scene scene = new Scene(layout); scene.getStylesheets().addAll("/Graphics/CSS/StyleSheet.css"); primaryStage.setScene(scene); primaryStage.initModality(Modality.APPLICATION_MODAL); // sets the window to be modal, meaning the underlying window cannot be used until this one is closed. primaryStage.setWidth(300); primaryStage.setHeight(200); primaryStage.setResizable(false); // this window cannot be resized.\ primaryStage.setTitle("Settings"); // window title primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); // window icon primaryStage.show(); // displays the window } private void tableThemeMethod(){ // updates the table value, then redraws board. tableImage = tableThemes.getValue(); System.out.println(); drawTable(); freshBoard(); if (game) drawPieces(); // if there is a game on, draw the pieces. try { // save the user's settings PrintWriter settingsWriter = new PrintWriter(new File("Settings.txt")); settingsWriter.print(boardTheme + "\n" + tableImage + "\n" + pieceTheme); settingsWriter.close(); }catch (FileNotFoundException e) { // ignore } } private void boardThemeMethod(){ if (boardThemes.getValue().equals("Red and Brown")) boardTheme = "RedBrown"; else if (boardThemes.getValue().equals("Grey and White"))boardTheme = "default"; else boardTheme = "glass"; drawTable(); freshBoard(); if (game) drawPieces(); updateLastMoveImage(); try { // save the user's settings PrintWriter settingsWriter = new PrintWriter(new File("Settings.txt")); settingsWriter.print(boardTheme + "\n" + tableImage + "\n" + pieceTheme); settingsWriter.close(); }catch (FileNotFoundException e) { // ignore } } } private class DirectionsWindow{ private Stage primaryStage = new Stage(); private Button closeButton = new Button("Close"); private VBox layout = new VBox(10); private Label howTOPlay = new Label("How to Play"); private Text text = new Text(); private DirectionsWindow(){ display(); text.setText("This game is pretty much chess, but turned inside out... the rules are as follows:\n" + "1. The board size is now 5 x 5.\n" + "2. Each player will have five pawns, a rook, a knight, a bishop, a queen and a king.\n" + "\t Piece movements are the same as the are in normal chess except the pawn can only advance one square at a time.\n" + "3. Each chess piece follows the same movement/pattern as regular chess.\n" + "4. Capturing is compulsory. When more than one capture is available, the player may choose.\n" + "5. The king has no royal power and accordingly:\n" + "\tIt may be captured like any other piece.\n" + "\tThere is no check or checkmate.\n" + "\tThere is no castling.\n" + "6. A pawn will be promoted to a King when it reached the other side of the board.\n" + "7. A player wins by losing all his pieces\n" + "8. If a player cannot make a move, the winner is the player with the least number of piece (regardless of the piece).\n" + "9. The game is also a stalemate when a win is impossible\n" + "\tA player cannot make a move and there is the same number of piece for both players.\n" + "10. The side to make the first move is determined prior to the start of a game.\n\n" + "Board Rules:\n" + "Undo and Redo buttons can only be used if you play against the AI. If someone outsmarts you in one on one,\n" + " you don't deserve a redo :P.\n\n" + "Final Thoughts: Enjoy the game! :)"); text.setFont(Font.font("Arial")); } private void display(){ // setting up close button function closeButton.setOnAction(e -> primaryStage.close()); // building the layout layout.getChildren().addAll(howTOPlay, text, closeButton); layout.setAlignment(Pos.CENTER); //setting up the window Scene scene = new Scene(layout); primaryStage.setScene(scene); primaryStage.setTitle("Learn to Play!"); primaryStage.getIcons().addAll(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); primaryStage.setResizable(false); primaryStage.setWidth(800); primaryStage.setHeight(500); primaryStage.show(); } } // ------------------------------ Threading classes ------------------------------------- private class AIThread implements Runnable{ private AI watson; private AIThread(Player player, Board board){ this.watson = new AI(player, board); Thread Watson = Thread.currentThread(); Watson.setName("AI Thread"); // Names this thead } @Override public void run() { SpecialCoord specialCoord = watson.play(board); Platform.runLater(new Runnable() { // this will run the needed operations in the FX thread. @Override public void run() { board.setLocked(false); // after the AI plays, unlock the board so the player can play // updating the graphic elements if (specialCoord == null) checkWinner(); else { // now we highlight the piece at its move for the last state image graphics.strokeRect((specialCoord.getPiece().getCoords().getX() + 1) * 100 + 52, (specialCoord.getPiece().getCoords().getY() + 1) * 100 - 48, 98, 98);// highlight the piece tile in blue if (board.getPiece(specialCoord.getY(), specialCoord.getX()) == null){ // if the space we are going to is empty graphics.setStroke(Color.YELLOW); graphics.strokeRect((specialCoord.getX() + 1) * 100 + 52, (specialCoord.getY() + 1) * 100 - 48, 98, 98);// highlight the move yellow }else{ // if the space we are going to is an attack graphics.setStroke(Color.RED); graphics.strokeRect((specialCoord.getX() + 1) * 100 + 52, (specialCoord.getY() + 1) * 100 - 48, 98, 98);// highlight the move red } graphics.setStroke(Color.AQUA); // reset color for next piece highlighting board.makeMove(board.getPiece(specialCoord.getPiece().getCoords().getY(), specialCoord.getPiece().getCoords().getX()), specialCoord.getY(), specialCoord.getX()); updateLastMoveImage(); freshBoard(); drawPieces(); checkWinner(); if (board.getCurrentPlayer().getPlayerNumber() == 0) statusLbl.setText("Black's Turn"); else statusLbl.setText("White's turn."); } } }); } } }
shinn16/Chess
src/GUI/Controller.java
Java
gpl-3.0
46,008
/* * Copyright 2016 Nathan Howard * * This file is part of OpenGrave * * OpenGrave 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. * * OpenGrave 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 OpenGrave. If not, see <http://www.gnu.org/licenses/>. */ package com.opengrave.common; import java.util.ArrayList; import java.util.HashMap; import java.util.UUID; import com.opengrave.common.inventory.ItemMaterial; import com.opengrave.common.inventory.ItemType; import com.opengrave.common.world.CommonObject; import com.opengrave.common.world.CommonProcess; import com.opengrave.common.world.CommonWorld; import com.opengrave.common.world.ProcessProvision; public class ModSession { boolean loadFinished = false; ArrayList<ItemMaterial> materialList = new ArrayList<ItemMaterial>(); ArrayList<ItemType> itemTypes = new ArrayList<ItemType>(); ArrayList<CommonWorld> worldList = new ArrayList<CommonWorld>(); ArrayList<CommonProcess> processList = new ArrayList<CommonProcess>(); HashMap<UUID, ArrayList<ProcessProvision>> processHash = new HashMap<UUID, ArrayList<ProcessProvision>>(); ObjectStorage objectList = new ObjectStorage(); public CommonProcess addProcess(String processName, ArrayList<String> vars) { CommonProcess process = new CommonProcess(processName, vars); synchronized (processList) { if (!processList.contains(process)) { processList.add(process); } } return process; } public CommonProcess getProcess(String processName) { synchronized (processList) { for (CommonProcess proc : processList) { if (proc.getProcessName().equalsIgnoreCase(processName)) { return proc; } } } return null; } public void addObjectProcess(UUID id, CommonProcess proc, ArrayList<Float> vars) { CommonObject obj = getObjectStorage().getObject(id); if (proc == null) { System.out.println("No process : '" + proc + "'"); return; } if (obj == null) { System.out.println("No object with id " + id.toString()); return; } if (vars.size() != proc.getVariables().size()) { System.out.println("Variables for process don't match."); return; } synchronized (processHash) { if (!processHash.containsKey(id)) { processHash.put(id, new ArrayList<ProcessProvision>()); } ProcessProvision pp = new ProcessProvision(proc, vars); processHash.get(id).add(pp); } } public ArrayList<ProcessProvision> getProcessObject(UUID id) { ArrayList<ProcessProvision> copyList = new ArrayList<ProcessProvision>(); synchronized (processHash) { if (processHash.containsKey(id)) { for (ProcessProvision prov : processHash.get(id)) { copyList.add(prov); } } } return copyList; } public void add(ItemMaterial im) { if (loadFinished) { throw new RuntimeException("Can not add new materials after mods finish loading"); } synchronized (materialList) { materialList.add(im); } } public void add(ItemType itemType) { if (loadFinished) { throw new RuntimeException("Can not add new item types after mods finish loading"); } synchronized (itemTypes) { itemTypes.add(itemType); } } public ItemType getItemType(String id) { synchronized (itemTypes) { for (ItemType it : itemTypes) { if (id.equalsIgnoreCase(it.getID())) { return it; } } } return null; } public ArrayList<ItemMaterial> getMaterials() { ArrayList<ItemMaterial> nM = new ArrayList<ItemMaterial>(); synchronized (materialList) { for (ItemMaterial iM : materialList) { nM.add(iM); } } return nM; } public ArrayList<ItemType> getItemTypes() { ArrayList<ItemType> iT = new ArrayList<ItemType>(); synchronized (itemTypes) { for (ItemType it : itemTypes) { iT.add(it); } } return iT; } public CommonWorld addWorld(String string) { if (loadFinished) { throw new RuntimeException("Can not add new worlds after mods finish loading"); } CommonWorld world = new CommonWorld(string); synchronized (worldList) { worldList.add(world); } world.loadInThread(this); return world; } public ArrayList<CommonWorld> getWorlds() { ArrayList<CommonWorld> newList = new ArrayList<CommonWorld>(); synchronized (worldList) { for (CommonWorld world : worldList) { newList.add(world); } } return newList; } public ObjectStorage getObjectStorage() { return objectList; } }
AperiStudios/OpenGrave
src/main/java/com/opengrave/common/ModSession.java
Java
gpl-3.0
4,818
package net.lomeli.magiks.api.machines; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.item.ItemStack; public class OreCrusherManager { private static final OreCrusherManager instance = new OreCrusherManager(); @SuppressWarnings("rawtypes") private Map crushableOre = new HashMap(); private HashMap<List<Integer>, ItemStack> metaCrushableOre = new HashMap<List<Integer>, ItemStack>(); public static final OreCrusherManager getInstance() { return instance; } private OreCrusherManager() { } @SuppressWarnings("unchecked") public void addCrushRecipe(int itemID, ItemStack itemStack) { this.crushableOre.put(Integer.valueOf(itemID), itemStack); } public void addCrushRecipe(int itemID, ItemStack itemStack, int metadata) { this.metaCrushableOre.put(Arrays.asList(itemID, metadata), itemStack); } public ItemStack getCrushResult(ItemStack item) { if(item == null) return null; ItemStack ret = metaCrushableOre.get(Arrays.asList(item.itemID, item.getItemDamage())); if(ret != null) return ret; return (ItemStack)crushableOre.get(Integer.valueOf(item.itemID)); } @SuppressWarnings("rawtypes") public Map getCrushableList() { return this.crushableOre; } }
Lomeli12/MechroMagiks
common/net/lomeli/magiks/api/machines/OreCrusherManager.java
Java
gpl-3.0
1,412
/* * Copyright (C) 2013-2022 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre (contact@b3dgs.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.b3dgs.lionheart.object.feature; import com.b3dgs.lionengine.Animation; import com.b3dgs.lionengine.LionEngineException; import com.b3dgs.lionengine.Medias; import com.b3dgs.lionengine.Mirror; import com.b3dgs.lionengine.Tick; import com.b3dgs.lionengine.Updatable; import com.b3dgs.lionengine.UtilMath; import com.b3dgs.lionengine.game.AnimationConfig; import com.b3dgs.lionengine.game.FeatureProvider; import com.b3dgs.lionengine.game.feature.Animatable; import com.b3dgs.lionengine.game.feature.FeatureGet; import com.b3dgs.lionengine.game.feature.FeatureInterface; import com.b3dgs.lionengine.game.feature.FeatureModel; import com.b3dgs.lionengine.game.feature.Identifiable; import com.b3dgs.lionengine.game.feature.Mirrorable; import com.b3dgs.lionengine.game.feature.Recyclable; import com.b3dgs.lionengine.game.feature.Routine; import com.b3dgs.lionengine.game.feature.Services; import com.b3dgs.lionengine.game.feature.Setup; import com.b3dgs.lionengine.game.feature.Spawner; import com.b3dgs.lionengine.game.feature.Transformable; import com.b3dgs.lionengine.game.feature.launchable.Launcher; import com.b3dgs.lionengine.game.feature.rasterable.Rasterable; import com.b3dgs.lionengine.graphic.engine.SourceResolutionProvider; import com.b3dgs.lionheart.Music; import com.b3dgs.lionheart.MusicPlayer; import com.b3dgs.lionheart.RasterType; import com.b3dgs.lionheart.ScreenShaker; import com.b3dgs.lionheart.Settings; import com.b3dgs.lionheart.WorldType; import com.b3dgs.lionheart.constant.Anim; import com.b3dgs.lionheart.constant.Folder; import com.b3dgs.lionheart.landscape.ForegroundWater; /** * Boss Underworld feature implementation. * <ol> * <li>Spawn from hole.</li> * <li>Track player horizontally.</li> * <li>Attack player.</li> * <li>Move down.</li> * <li>Spawn turtles.</li> * <li>Rise.</li> * </ol> */ @FeatureInterface public final class BossUnderworld extends FeatureModel implements Routine, Recyclable { private static final int SPAWN_DELAY_MS = 6_000; private static final int ATTACK_DELAY_MS = 10_000; private static final int DOWN_DELAY_MS = 3_000; private static final double RAISE_SPEED = 0.5; private static final double RAISE_MAX = -8; private static final double RAISE_MIN = -80; private static final double EFFECT_SPEED = 4.0; private static final double EFFECT_AMPLITUDE = 4.0; private final Trackable target = services.get(Trackable.class); private final SourceResolutionProvider source = services.get(SourceResolutionProvider.class); private final MusicPlayer music = services.get(MusicPlayer.class); private final ScreenShaker shaker = services.get(ScreenShaker.class); private final Spawner spawner = services.get(Spawner.class); private final ForegroundWater water = services.get(ForegroundWater.class); private final Tick tick = new Tick(); private final Animation idle; private Updatable updater; private boolean attack; private double effectY; @FeatureGet private Transformable transformable; @FeatureGet private Mirrorable mirrorable; @FeatureGet private Animatable animatable; @FeatureGet private Launcher launcher; @FeatureGet private Rasterable rasterable; @FeatureGet private Identifiable identifiable; @FeatureGet private Stats stats; /** * Create feature. * * @param services The services reference (must not be <code>null</code>). * @param setup The setup reference (must not be <code>null</code>). * @throws LionEngineException If invalid arguments. */ public BossUnderworld(Services services, Setup setup) { super(services, setup); idle = AnimationConfig.imports(setup).getAnimation(Anim.IDLE); } /** * Update spawn delay. * * @param extrp The extrapolation value. */ private void updateSpawn(double extrp) { tick.update(extrp); if (tick.elapsedTime(source.getRate(), SPAWN_DELAY_MS)) { updater = this::updateRaise; shaker.start(); attack = false; } } /** * Update raise phase until max. * * @param extrp The extrapolation value. */ private void updateRaise(double extrp) { transformable.moveLocationY(extrp, RAISE_SPEED); if (transformable.getY() > RAISE_MAX) { transformable.teleportY(RAISE_MAX); updater = this::updateAttack; launcher.setLevel(attack ? 2 : 1); launcher.fire(); tick.restart(); } } /** * Update attack phase. * * @param extrp The extrapolation value. */ private void updateAttack(double extrp) { transformable.setLocationY(RAISE_MAX + UtilMath.sin(effectY) * EFFECT_AMPLITUDE); effectY = UtilMath.wrapAngleDouble(effectY + EFFECT_SPEED); tick.update(extrp); if (tick.elapsedTime(source.getRate(), ATTACK_DELAY_MS)) { updater = this::updateMoveDown; shaker.start(); } } /** * Update move down phase. * * @param extrp The extrapolation value. */ private void updateMoveDown(double extrp) { transformable.moveLocationY(extrp, -RAISE_SPEED); if (transformable.getY() < RAISE_MIN) { transformable.teleportY(RAISE_MIN); updater = this::updateAttackDown; launcher.setLevel(0); launcher.fire(); tick.restart(); } } /** * Update attack once moved down. * * @param extrp The extrapolation value. */ private void updateAttackDown(double extrp) { tick.update(extrp); if (tick.elapsedTime(source.getRate(), DOWN_DELAY_MS)) { updater = this::updateRaise; attack = !attack; shaker.start(); tick.restart(); } } /** * Update mirror depending on player location. */ private void updateMirror() { if (transformable.getX() > target.getX()) { mirrorable.mirror(Mirror.NONE); } else { mirrorable.mirror(Mirror.HORIZONTAL); } } @Override public void prepare(FeatureProvider provider) { super.prepare(provider); if (RasterType.CACHE == Settings.getInstance().getRaster()) { launcher.addListener(l -> l.ifIs(Underwater.class, u -> u.loadRaster("raster/underworld/underworld/"))); } identifiable.addListener(id -> music.playMusic(Music.BOSS_WIN)); stats.addListener(new StatsListener() { @Override public void notifyNextSword(int level) { // Nothing to do } @Override public void notifyDead() { water.stopRaise(); spawner.spawn(Medias.create(Folder.ENTITY, WorldType.UNDERWORLD.getFolder(), "Floater3.xml"), 208, 4); spawner.spawn(Medias.create(Folder.ENTITY, WorldType.UNDERWORLD.getFolder(), "Floater3.xml"), 240, 4); } }); } @Override public void update(double extrp) { updater.update(extrp); updateMirror(); } @Override public void recycle() { updater = this::updateSpawn; animatable.play(idle); effectY = 0.0; tick.restart(); } }
b3dgs/lionheart-remake
lionheart-game/src/main/java/com/b3dgs/lionheart/object/feature/BossUnderworld.java
Java
gpl-3.0
8,280
from setuptools import setup setup(name="waterworks", version="0.0.0", description="Message agregation daemon.", url="https://github.com/Aeva/waterworks", author="Aeva Palecek", author_email="aeva.ntsc@gmail.com", license="GPLv3", packages=["waterworks"], zip_safe=False, entry_points = { "console_scripts" : [ "waterworks=waterworks.waterworks:start_daemon", ], }, install_requires = [ ])
Aeva/waterworks
setup.py
Python
gpl-3.0
508
/** * This file is part of BP generator. * * BP generator 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. * * BP generator 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 * BP generator. If not, see <http://www.gnu.org/licenses/>. * * @link https://github.com/dsx75/bp-gen * @copyright (C) Dominik Smatana 2014 */ package eu.bp.gen1.pages; import eu.bp.data.Data; /** * * @author Dominik Smatana <dominik.smatana@gmail.com> */ public class SkLedS2720 extends BasePage implements Page { public SkLedS2720() { this.url = "sk/produkty/SMD5630_LED_ziarovka_E27_tepla/"; this.language = "sk"; this.title = "SMD5630 LED žiarovka E27 (teplá biela)"; this.h1 = "SMD5630 LED žiarovka E27 (teplá biela)"; this.product = Data.createProduct(13); } }
dsx75/bp-gen
src/eu/bp/gen1/pages/SkLedS2720.java
Java
gpl-3.0
1,263
#!/usr/bin/env ruby # # This plugin provides integration with OpenVAS. Written by kost and # averagesecurityguy. # # Distributed under MIT license: # http://www.opensource.org/licenses/mit-license.php # require 'socket' require 'timeout' require 'openssl' require 'rexml/document' require 'rexml/text' require 'base64' # OpenVASOMP module # # Usage: require 'openvas-omp' module OpenVASOMP #------------------------------ # Error Classes #------------------------------ class OMPError < :: RuntimeError attr_accessor :reason def initialize(reason = '') self.reason = reason end def to_s "OpenVAS OMP: #{self.reason}" end end class OMPConnectionError < OMPError def initialize self.reason = "Could not connect to server" end end class OMPResponseError < OMPError def initialize self.reason = "Error in OMP request/response" end end class OMPAuthError < OMPError def initialize self.reason = "Authentication failed" end end class XMLParsingError < OMPError def initialize self.reason = "XML parsing failed" end end #------------------------------ # Connection Class #------------------------------ class OpenVASConnection attr_accessor :socket, :bufsize, :debug def initialize(host="127.0.0.1", port=9390, debug=false) @host = host @port = port @socket = nil @bufsize = 16384 @debug = debug end def connect if @debug then puts "Connecting to server #{@host} on port #{@port}" end plain_socket = TCPSocket.open(@host, @port) ssl_context = OpenSSL::SSL::SSLContext.new() @socket = OpenSSL::SSL::SSLSocket.new(plain_socket, ssl_context) @socket.sync_close = true @socket.connect end def disconnect if @debug then puts "Closing connection to server #{@host} on port #{@port}" end if @socket then @socket.close end end def sendrecv(data) # Send the data if @debug then puts "Preparing to send data" end if not @socket then connect end if @debug then puts "SENDING: " + data end @socket.puts(data) # Receive the response resp = '' size = 0 begin begin timeout(@read_timeout) { a = @socket.sysread(@bufsize) size = a.length resp << a } rescue Timeout::Error size = 0 rescue EOFError raise OMPResponseError end end while size >= @bufsize if @debug then puts "RECEIVED: " + resp end return resp end end #------------------------------ # OpenVASOMP class #------------------------------ class OpenVASOMP # initialize object: try to connect to OpenVAS using URL, user and password attr_reader :targets, :tasks, :configs, :formats, :reports def initialize(user="openvas", pass="openvas", host="localhost", port=9392, debug=false) @debug = debug @token = '' @server = OpenVASConnection.new(host, port, debug) @server.connect login(user, pass) @configs = nil @tasks = nil @targets = nil @formats = nil @reports = nil config_get_all task_get_all target_get_all format_get_all report_get_all end #-------------------------- # Low level commands. Only # used by OpenVASOMP class. #-------------------------- # Nests a string inside an XML tag specified by root def xml_str(root, str) return "<#{root}>#{str}</#{root}>" end # Creates an XML root with child elements specified by a hash def xml_elems(root, elems) xml = REXML::Element.new(root) elems.each do |key, val| e = xml.add_element(key) e.text = val end return xml.to_s end # Creates and XML element with attributes specified by a hash def xml_attrs(elem, attribs) xml = REXML::Element.new(elem) attribs.each do |key, val| xml.attributes[key] = val end return xml.to_s end # Send authentication string and return an XML object (authentication token) def auth_request_xml(request) if @debug puts "Sending Request: #{request}" end resp = @server.sendrecv(request) begin docxml = REXML::Document.new(resp) status = docxml.root.attributes['status'].to_i status_text = docxml.root.attributes['status_text'] if @debug puts "Status: #{status}" puts "Status Text: #{status_text}" end rescue raise XMLParsingError end return status, status_text end # Send string request wrapped with authentication XML and return # an XML object def omp_request_xml(request) if @debug puts "Sending Request: #{request}" end resp = @server.sendrecv(@token + request) begin # Wrap the response in XML tags to use next_element properly. docxml = REXML::Document.new("<response>" + resp + "</response>") resp = docxml.root.elements['authenticate_response'].next_element status = resp.attributes['status'].to_i status_text = resp.attributes['status_text'] if @debug puts "Status: #{status}" puts "Status Text: #{status_text}" end rescue raise XMLParsingError end return status, status_text, resp end #-------------------------- # Class API methods. #-------------------------- # Sets debug level def debug(value) if value == 0 @debug = false @server.debug = false return "Debug is deactivated." else @debug = true @server.debug = true return "Debug is activated." end end # get OMP version (you don't need to be authenticated) def get_version status, status_text, resp = omp_request_xml("<get_version/>") begin version = resp.elements['version'].text return version rescue raise XMLParsingError end end # login to OpenVAS server. # if successful returns authentication XML for further usage # if unsuccessful returns empty string def login(user, pass) creds = xml_elems("credentials", {"username"=> user, "password" => pass}) req = xml_str("authenticate", creds) status, status_text = auth_request_xml(req) if status == 200 @token = req else raise OMPAuthError end end # Logout by disconnecting from the server and deleting the # authentication string. There are no sessions in OMP, must # send the credentials every time. def logout @server.disconnect() @token = '' end #------------------------------ # Target Functions #------------------------------ # OMP - Get all targets for scanning and returns array of hashes # with following keys: id,name,comment,hosts,max_hosts,in_use # # Usage: # array_of_hashes = target_get_all() # def target_get_all() begin status, status_text, resp = omp_request_xml("<get_targets/>") list = Array.new resp.elements.each('//get_targets_response/target') do |target| td = Hash.new td["id"] = target.attributes["id"] td["name"] = target.elements["name"].text td["comment"] = target.elements["comment"].text td["hosts"] = target.elements["hosts"].text td["max_hosts"] = target.elements["max_hosts"].text td["in_use"] = target.elements["in_use"].text list.push td end @targets = list return list rescue raise OMPResponseError end end # OMP - Create target for scanning # # Usage: # # target_id = ov.target_create("name"=>"localhost", # "hosts"=>"127.0.0.1","comment"=>"yes") # def target_create(name, hosts, comment) req = xml_elems("create_target", {"name"=>name, "hosts"=>hosts, "comment"=>comment}) begin status, status_text, resp = omp_request_xml(req) target_get_all return "#{status_text}: #{resp.attributes['id']}" rescue raise OMPResponseError end end # OMP - Delete target # # Usage: # # ov.target_delete(target_id) # def target_delete(id) target = @targets[id.to_i] if not target raise OMPError.new("Invalid target id.") end req = xml_attrs("delete_target",{"target_id" => target["id"]}) begin status, status_text, resp = omp_request_xml(req) target_get_all return status_text rescue raise OMPResponseError end end #-------------------------- # Task Functions #-------------------------- # In short: Create a task. # # The client uses the create_task command to create a new task. # def task_create(name, comment, config_id, target_id) config = @configs[config_id.to_i] target = @targets[target_id.to_i] config = xml_attrs("config", {"id"=>config["id"]}) target = xml_attrs("target", {"id"=>target["id"]}) namestr = xml_str("name", name) commstr = xml_str("comment", comment) req = xml_str("create_task", namestr + commstr + config + target) begin status, status_text, resp = omp_request_xml(req) task_get_all return "#{status_text}: #{resp.attributes['id']}" rescue raise OMPResponseError end end # In short: Delete a task. # # The client uses the delete_task command to delete an existing task, # including all reports associated with the task. # def task_delete(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("delete_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) task_get_all return status_text rescue raise OMPResponseError end end # In short: Get all tasks. # # The client uses the get_tasks command to get task information. # def task_get_all() begin status, status_text, resp = omp_request_xml("<get_tasks/>") list = Array.new resp.elements.each('//get_tasks_response/task') do |task| td = Hash.new td["id"] = task.attributes["id"] td["name"] = task.elements["name"].text td["comment"] = task.elements["comment"].text td["status"] = task.elements["status"].text td["progress"] = task.elements["progress"].text list.push td end @tasks = list return list rescue raise OMPResponseError end end # In short: Manually start an existing task. # # The client uses the start_task command to manually start an existing # task. # def task_start(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("start_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) return status_text rescue raise OMPResponseError end end # In short: Stop a running task. # # The client uses the stop_task command to manually stop a running # task. # def task_stop(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("stop_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) return status_text rescue raise OMPResponseError end end # In short: Pause a running task. # # The client uses the pause_task command to manually pause a running # task. # def task_pause(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("pause_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) return status_text rescue raise OMPResponseError end end # In short: Resume task if stopped, else start task. # # The client uses the resume_or_start_task command to manually start # an existing task, ensuring that the task will resume from its # previous position if the task is in the Stopped state. # def task_resume_or_start(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("resume_or_start_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) return status_text rescue raise OMPResponseError end end # In short: Resume a puased task # # The client uses the resume_paused_task command to manually resume # a paused task. # def task_resume_paused(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("resume_paused_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) return status_text rescue raise OMPResponseError end end #-------------------------- # Config Functions #-------------------------- # OMP - get configs and returns hash as response # hash[config_id]=config_name # # Usage: # # array_of_hashes=ov.config_get_all() # def config_get_all() begin status, status_text, resp = omp_request_xml("<get_configs/>") list = Array.new resp.elements.each('//get_configs_response/config') do |config| c = Hash.new c["id"] = config.attributes["id"] c["name"] = config.elements["name"].text list.push c end @configs = list return list rescue raise OMPResponseError end end #-------------------------- # Format Functions #-------------------------- # Get a list of report formats def format_get_all() begin status, status_text, resp = omp_request_xml("<get_report_formats/>") if @debug then print resp end list = Array.new resp.elements.each('//get_report_formats_response/report_format') do |report| td = Hash.new td["id"] = report.attributes["id"] td["name"] = report.elements["name"].text td["extension"] = report.elements["extension"].text td["summary"] = report.elements["summary"].text list.push td end @formats = list return list rescue raise OMPResponseError end end #-------------------------- # Report Functions #-------------------------- # Get a list of reports def report_get_all() begin status, status_text, resp = omp_request_xml("<get_reports/>") list = Array.new resp.elements.each('//get_reports_response/report') do |report| td = Hash.new td["id"] = report.attributes["id"] td["task"] = report.elements["report/task/name"].text td["start_time"] = report.elements["report/scan_start"].text td["stop_time"] = report.elements["report/scan_end"].text list.push td end @reports = list return list rescue raise OMPResponseError end end def report_delete(report_id) report = @reports[report_id.to_i] if not report raise OMPError.new("Invalid report id.") end req = xml_attrs("delete_report",{"report_id" => report["id"]}) begin status, status_text, resp = omp_request_xml(req) report_get_all return status_text rescue raise OMPResponseError end end # Get a report by id. Must also specify the format_id def report_get_by_id(report_id, format_id) report = @reports[report_id.to_i] if not report raise OMPError.new("Invalid report id.") end format = @formats[format_id.to_i] if not format raise OMPError.new("Invalid format id.") end req = xml_attrs("get_reports", {"report_id"=>report["id"], "format_id"=>format["id"]}) begin status, status_text, resp = omp_request_xml(req) rescue raise OMPResponseError end if status == "404" raise OMPError.new(status_text) end content_type = resp.elements["report"].attributes["content_type"] report = resp.elements["report"].to_s if report == nil raise OMPError.new("The report is empty.") end # XML reports are in XML format, everything else is base64 encoded. if content_type == "text/xml" return report else return Base64.decode64(report) end end end end
cSploit/android.MSF
lib/openvas/openvas-omp.rb
Ruby
gpl-3.0
17,262
/* CPU_X86_32.cpp Copyright (C) 2008 Stephen Torri This file is part of Libreverse. Libreverse 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, or (at your option) any later version. Libreverse is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "CPU_X86_32.h" #include "errors/IO_Exception.h" namespace reverse { namespace mach_module { string CPU_X86_32::get_Register_Name ( uint32_t index ) { // Bouml preserved body begin 0001F437 if ( index > GS ) { throw errors::IO_Exception ( errors::IO_Exception::INVALID_INDEX ); } std::string name = ""; switch ( index ) { case EAX: name = "EAX"; break; case EBX: name = "EBX"; break; case ECX: name = "ECX"; break; case EDX: name = "EDX"; break; case EDI: name = "EDI"; break; case ESI: name = "ESI"; break; case EBP: name = "EBP"; break; case ESP: name = "ESP"; break; case SS: name = "SS"; break; case EFLAGS: name = "EFLAGS"; break; case EIP: name = "EIP"; break; case DS: name = "DS"; break; case ES: name = "ES"; break; case FS: name = "FS"; break; case GS: name = "GS"; break; } return name; // Bouml preserved body end 0001F437 } } /* namespace mach_module */ } /* namespace reverse */
storri/libreverse
reverse/io/input/file_readers/mac_mach/cpu_x86_32.cpp
C++
gpl-3.0
2,043
/** Copyright 2012 John Cummens (aka Shadowmage, Shadowmage4513) This software is distributed under the terms of the GNU General Public License. Please see COPYING for precise license information. This file is part of Ancient Warfare. Ancient Warfare 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. Ancient Warfare 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 Ancient Warfare. If not, see <http://www.gnu.org/licenses/>. */ package shadowmage.ancient_warfare.common.item; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import shadowmage.ancient_warfare.common.research.IResearchGoal; import shadowmage.ancient_warfare.common.research.ResearchGoal; import shadowmage.ancient_warfare.common.tracker.ResearchTracker; import shadowmage.ancient_warfare.common.utils.BlockPosition; public class ItemResearchNote extends AWItemClickable { /** * @param itemID * @param hasSubTypes */ public ItemResearchNote(int itemID) { super(itemID, true); this.hasLeftClick = false; this.setCreativeTab(CreativeTabAW.researchTab); this.maxStackSize = 1; } @Override public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean par4) { super.addInformation(stack, player, list, par4); list.add("Right Click to learn research."); } @Override public boolean onUsedFinal(World world, EntityPlayer player, ItemStack stack, BlockPosition hit, int side) { IResearchGoal goal = ResearchGoal.getGoalByID(stack.getItemDamage()); if(world.isRemote) { player.addChatMessage("Learning research from notes: " + StatCollector.translateToLocal(goal.getDisplayName())); return true; } if(goal!=null && !ResearchTracker.instance().getEntryFor(player).hasDoneResearch(goal)) { ResearchTracker.instance().addResearchToPlayer(world, player.getEntityName(), goal.getGlobalResearchNum()); if(!player.capabilities.isCreativeMode) { stack.stackSize--; if(stack.stackSize<=0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, null); } return true; } } return true; } @Override public boolean onUsedFinalLeft(World world, EntityPlayer player, ItemStack stack, BlockPosition hit, int side) { return false; } }
shadowmage45/AncientWarfare
AncientWarfare/src/shadowmage/ancient_warfare/common/item/ItemResearchNote.java
Java
gpl-3.0
2,960
'use strict'; var async = require('async'); var rss = require('rss'); var nconf = require('nconf'); var validator = require('validator'); var posts = require('../posts'); var topics = require('../topics'); var user = require('../user'); var categories = require('../categories'); var meta = require('../meta'); var helpers = require('../controllers/helpers'); var privileges = require('../privileges'); var db = require('../database'); var utils = require('../utils'); var controllers404 = require('../controllers/404.js'); var terms = { daily: 'day', weekly: 'week', monthly: 'month', alltime: 'alltime', }; module.exports = function (app, middleware) { app.get('/topic/:topic_id.rss', middleware.maintenanceMode, generateForTopic); app.get('/category/:category_id.rss', middleware.maintenanceMode, generateForCategory); app.get('/recent.rss', middleware.maintenanceMode, generateForRecent); app.get('/top.rss', middleware.maintenanceMode, generateForTop); app.get('/top/:term.rss', middleware.maintenanceMode, generateForTop); app.get('/popular.rss', middleware.maintenanceMode, generateForPopular); app.get('/popular/:term.rss', middleware.maintenanceMode, generateForPopular); app.get('/recentposts.rss', middleware.maintenanceMode, generateForRecentPosts); app.get('/category/:category_id/recentposts.rss', middleware.maintenanceMode, generateForCategoryRecentPosts); app.get('/user/:userslug/topics.rss', middleware.maintenanceMode, generateForUserTopics); app.get('/tags/:tag.rss', middleware.maintenanceMode, generateForTag); }; function validateTokenIfRequiresLogin(requiresLogin, cid, req, res, callback) { var uid = req.query.uid; var token = req.query.token; if (!requiresLogin) { return callback(); } if (!uid || !token) { return helpers.notAllowed(req, res); } async.waterfall([ function (next) { db.getObjectField('user:' + uid, 'rss_token', next); }, function (_token, next) { if (token === _token) { async.waterfall([ function (next) { privileges.categories.get(cid, uid, next); }, function (privileges, next) { if (!privileges.read) { return helpers.notAllowed(req, res); } next(); }, ], callback); return; } user.auth.logAttempt(uid, req.ip, next); }, function () { helpers.notAllowed(req, res); }, ], callback); } function generateForTopic(req, res, callback) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var tid = req.params.topic_id; var userPrivileges; var topic; async.waterfall([ function (next) { async.parallel({ privileges: function (next) { privileges.topics.get(tid, req.uid, next); }, topic: function (next) { topics.getTopicData(tid, next); }, }, next); }, function (results, next) { if (!results.topic || (parseInt(results.topic.deleted, 10) && !results.privileges.view_deleted)) { return controllers404.send404(req, res); } userPrivileges = results.privileges; topic = results.topic; validateTokenIfRequiresLogin(!results.privileges['topics:read'], results.topic.cid, req, res, next); }, function (next) { topics.getTopicWithPosts(topic, 'tid:' + tid + ':posts', req.uid || req.query.uid || 0, 0, 25, false, next); }, function (topicData) { topics.modifyPostsByPrivilege(topicData, userPrivileges); var description = topicData.posts.length ? topicData.posts[0].content : ''; var image_url = topicData.posts.length ? topicData.posts[0].picture : ''; var author = topicData.posts.length ? topicData.posts[0].username : ''; var feed = new rss({ title: utils.stripHTMLTags(topicData.title, utils.tags), description: description, feed_url: nconf.get('url') + '/topic/' + tid + '.rss', site_url: nconf.get('url') + '/topic/' + topicData.slug, image_url: image_url, author: author, ttl: 60, }); var dateStamp; if (topicData.posts.length > 0) { feed.pubDate = new Date(parseInt(topicData.posts[0].timestamp, 10)).toUTCString(); } topicData.posts.forEach(function (postData) { if (!postData.deleted) { dateStamp = new Date(parseInt(parseInt(postData.edited, 10) === 0 ? postData.timestamp : postData.edited, 10)).toUTCString(); feed.item({ title: 'Reply to ' + utils.stripHTMLTags(topicData.title, utils.tags) + ' on ' + dateStamp, description: postData.content, url: nconf.get('url') + '/post/' + postData.pid, author: postData.user ? postData.user.username : '', date: dateStamp, }); } }); sendFeed(feed, res); }, ], callback); } function generateForCategory(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var cid = req.params.category_id; var category; async.waterfall([ function (next) { async.parallel({ privileges: function (next) { privileges.categories.get(cid, req.uid, next); }, category: function (next) { categories.getCategoryById({ cid: cid, set: 'cid:' + cid + ':tids', reverse: true, start: 0, stop: 25, uid: req.uid || req.query.uid || 0, }, next); }, }, next); }, function (results, next) { category = results.category; validateTokenIfRequiresLogin(!results.privileges.read, cid, req, res, next); }, function (next) { generateTopicsFeed({ uid: req.uid || req.query.uid || 0, title: category.name, description: category.description, feed_url: '/category/' + cid + '.rss', site_url: '/category/' + category.cid, }, category.topics, next); }, function (feed) { sendFeed(feed, res); }, ], next); } function generateForRecent(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } async.waterfall([ function (next) { if (req.query.token && req.query.uid) { db.getObjectField('user:' + req.query.uid, 'rss_token', next); } else { next(null, null); } }, function (token, next) { generateForTopics({ uid: token && token === req.query.token ? req.query.uid : req.uid, title: 'Recently Active Topics', description: 'A list of topics that have been active within the past 24 hours', feed_url: '/recent.rss', site_url: '/recent', }, 'topics:recent', req, res, next); }, ], next); } function generateForTop(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var term = terms[req.params.term] || 'day'; var uid; async.waterfall([ function (next) { if (req.query.token && req.query.uid) { db.getObjectField('user:' + req.query.uid, 'rss_token', next); } else { next(null, null); } }, function (token, next) { uid = token && token === req.query.token ? req.query.uid : req.uid; topics.getSortedTopics({ uid: uid, start: 0, stop: 19, term: term, sort: 'votes', }, next); }, function (result, next) { generateTopicsFeed({ uid: uid, title: 'Top Voted Topics', description: 'A list of topics that have received the most votes', feed_url: '/top/' + (req.params.term || 'daily') + '.rss', site_url: '/top/' + (req.params.term || 'daily'), }, result.topics, next); }, function (feed) { sendFeed(feed, res); }, ], next); } function generateForPopular(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var term = terms[req.params.term] || 'day'; var uid; async.waterfall([ function (next) { if (req.query.token && req.query.uid) { db.getObjectField('user:' + req.query.uid, 'rss_token', next); } else { next(null, null); } }, function (token, next) { uid = token && token === req.query.token ? req.query.uid : req.uid; topics.getSortedTopics({ uid: uid, start: 0, stop: 19, term: term, sort: 'posts', }, next); }, function (result, next) { generateTopicsFeed({ uid: uid, title: 'Popular Topics', description: 'A list of topics that are sorted by post count', feed_url: '/popular/' + (req.params.term || 'daily') + '.rss', site_url: '/popular/' + (req.params.term || 'daily'), }, result.topics, next); }, function (feed) { sendFeed(feed, res); }, ], next); } function generateForTopics(options, set, req, res, next) { var start = options.hasOwnProperty('start') ? options.start : 0; var stop = options.hasOwnProperty('stop') ? options.stop : 19; async.waterfall([ function (next) { topics.getTopicsFromSet(set, options.uid, start, stop, next); }, function (data, next) { generateTopicsFeed(options, data.topics, next); }, function (feed) { sendFeed(feed, res); }, ], next); } function generateTopicsFeed(feedOptions, feedTopics, callback) { feedOptions.ttl = 60; feedOptions.feed_url = nconf.get('url') + feedOptions.feed_url; feedOptions.site_url = nconf.get('url') + feedOptions.site_url; feedTopics = feedTopics.filter(Boolean); var feed = new rss(feedOptions); if (feedTopics.length > 0) { feed.pubDate = new Date(parseInt(feedTopics[0].lastposttime, 10)).toUTCString(); } async.each(feedTopics, function (topicData, next) { var feedItem = { title: utils.stripHTMLTags(topicData.title, utils.tags), url: nconf.get('url') + '/topic/' + topicData.slug, date: new Date(parseInt(topicData.lastposttime, 10)).toUTCString(), }; if (topicData.teaser && topicData.teaser.user) { feedItem.description = topicData.teaser.content; feedItem.author = topicData.teaser.user.username; feed.item(feedItem); return next(); } topics.getMainPost(topicData.tid, feedOptions.uid, function (err, mainPost) { if (err) { return next(err); } if (!mainPost) { feed.item(feedItem); return next(); } feedItem.description = mainPost.content; feedItem.author = mainPost.user.username; feed.item(feedItem); next(); }); }, function (err) { callback(err, feed); }); } function generateForRecentPosts(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } async.waterfall([ function (next) { posts.getRecentPosts(req.uid, 0, 19, 'month', next); }, function (posts) { var feed = generateForPostsFeed({ title: 'Recent Posts', description: 'A list of recent posts', feed_url: '/recentposts.rss', site_url: '/recentposts', }, posts); sendFeed(feed, res); }, ], next); } function generateForCategoryRecentPosts(req, res, callback) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var cid = req.params.category_id; var category; var posts; async.waterfall([ function (next) { async.parallel({ privileges: function (next) { privileges.categories.get(cid, req.uid, next); }, category: function (next) { categories.getCategoryData(cid, next); }, posts: function (next) { categories.getRecentReplies(cid, req.uid || req.query.uid || 0, 20, next); }, }, next); }, function (results, next) { if (!results.category) { return controllers404.send404(req, res); } category = results.category; posts = results.posts; validateTokenIfRequiresLogin(!results.privileges.read, cid, req, res, next); }, function () { var feed = generateForPostsFeed({ title: category.name + ' Recent Posts', description: 'A list of recent posts from ' + category.name, feed_url: '/category/' + cid + '/recentposts.rss', site_url: '/category/' + cid + '/recentposts', }, posts); sendFeed(feed, res); }, ], callback); } function generateForPostsFeed(feedOptions, posts) { feedOptions.ttl = 60; feedOptions.feed_url = nconf.get('url') + feedOptions.feed_url; feedOptions.site_url = nconf.get('url') + feedOptions.site_url; var feed = new rss(feedOptions); if (posts.length > 0) { feed.pubDate = new Date(parseInt(posts[0].timestamp, 10)).toUTCString(); } posts.forEach(function (postData) { feed.item({ title: postData.topic ? postData.topic.title : '', description: postData.content, url: nconf.get('url') + '/post/' + postData.pid, author: postData.user ? postData.user.username : '', date: new Date(parseInt(postData.timestamp, 10)).toUTCString(), }); }); return feed; } function generateForUserTopics(req, res, callback) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var userslug = req.params.userslug; async.waterfall([ function (next) { user.getUidByUserslug(userslug, next); }, function (uid, next) { if (!uid) { return callback(); } user.getUserFields(uid, ['uid', 'username'], next); }, function (userData, next) { generateForTopics({ uid: req.uid, title: 'Topics by ' + userData.username, description: 'A list of topics that are posted by ' + userData.username, feed_url: '/user/' + userslug + '/topics.rss', site_url: '/user/' + userslug + '/topics', }, 'uid:' + userData.uid + ':topics', req, res, next); }, ], callback); } function generateForTag(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var tag = validator.escape(String(req.params.tag)); var page = parseInt(req.query.page, 10) || 1; var topicsPerPage = meta.config.topicsPerPage || 20; var start = Math.max(0, (page - 1) * topicsPerPage); var stop = start + topicsPerPage - 1; generateForTopics({ uid: req.uid, title: 'Topics tagged with ' + tag, description: 'A list of topics that have been tagged with ' + tag, feed_url: '/tags/' + tag + '.rss', site_url: '/tags/' + tag, start: start, stop: stop, }, 'tag:' + tag + ':topics', req, res, next); } function sendFeed(feed, res) { var xml = feed.xml(); res.type('xml').set('Content-Length', Buffer.byteLength(xml)).send(xml); }
BenLubar/NodeBB
src/routes/feeds.js
JavaScript
gpl-3.0
14,110
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root: return root.left, root.right = root.right, root.left self.invertTree(root.left) self.invertTree(root.right) return root
zqfan/leetcode
algorithms/226. Invert Binary Tree/solution.py
Python
gpl-3.0
490
# Copyright (C) 2011 Pierre de Buyl # This file is part of pyMPCD # pyMPCD 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. # pyMPCD 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 pyMPCD. If not, see <http://www.gnu.org/licenses/>. """ MPCD.py - This file contains the base class to perform MPCD simulations: MPCD_system. """ ## \namespace pyMPCD::MPCD # \brief MPCD.py - This file contains the base class to perform MPCD simulations: MPCD_system. # # MPCD methods define the basic import numpy as np from scipy.misc import factorial from MPCD_f import mpcd_mod ## Defines all variables for a MPCD system # # A simulation box is either declared via MPCD_system or through one test_case or from a file. # # \b Example # \code #import pyMPCD # import the pyMPCD package #box = pyMPCD.MPCD_system( (8,8,8), 10, 1.0) # Create a PBC system of 8x8x8 cells, density 10 and cell size 1.0 # \endcode class MPCD_system(): """ The MPCD_system class contains all variables relevant for MPCD simulations: box information, periodic boundaries, particles positions, ... """ ## Initializes a MPCD_system # # \param N_cells a 3 elements list or tuple that contains the number of cells in each dimension. # \param density an integer number that define the average number of particles per cell. # \param a the linear cell size. # \param N_species The number of solvent species to consider. def __init__( self, N_cells , density , a , N_species = 1): """ Defines a MPCD_system with periodic boundary conditions. N_cells is the number of cells in the 3 dimensions. density is the reference density for initialization and for filling cells with virtual particles. a is the linear cell size. """ ## Number of physical cells for the simulation. self.N_cells = np.array( N_cells , dtype=np.int32) # Check the input for N_cells if (len(self.N_cells) != 3): raise Exception ## The number of actual binning cells. Is higher than N_cells to allow for non-periodic systems. self.N_grid = self.N_cells + 1 ## The average density (number of particles per cell). self.density = int(density) ## The total number of MPCD particles. self.so_N = np.prod( self.N_cells ) * self.density ## The linear cell size. self.a = float(a) ## The number of solvent species self.N_species = N_species # Check that N_species is valid if (N_species < 1): raise Exception ## The shift applied to the system. self.shift = np.zeros( (3,) , dtype=np.float64 ) ## NumPy array for the position of the MPCD solvent. self.so_r = np.zeros( (self.so_N , 3) , dtype=np.float64 ) ## A view to so_r in Fortran order. self.so_r_f = self.so_r.T ## NumPy array for the velocity of the MPCD solvent. self.so_v = np.zeros( (self.so_N , 3) , dtype=np.float64 ) ## A view to so_v in Fortran order. self.so_v_f = self.so_v.T ## The local temperature in the cells. self.cells_temperature = np.zeros( (self.N_grid[0], self.N_grid[1], self.N_grid[2]), dtype=np.float64 ) ## NumPy array for the species. self.so_species = np.zeros( (self.so_N, ), dtype=np.int32) ## NumPy array holding the mass of each species. self.so_mass = np.ones( (self.N_species, ), dtype=np.float64) ## The size of the box. self.L = self.N_cells*self.a ## The MPCD time step, used for streaming. self.tau = float(0.) ## The number of particles in each cell. self.cells = np.zeros( self.N_grid, dtype=np.int32 ) ## A view to cells in Fortran order. self.cells_f = self.cells.T ## The list of particles, per cell. self.par_list = np.zeros( (self.N_grid[0], self.N_grid[1], self.N_grid[2], 64), dtype=np.int32 ) ## A view to par_list in Fortran order. self.par_list_f = self.par_list.T ## The cell-wise center-of-mass velocity. self.v_com = np.zeros( (self.N_grid[0], self.N_grid[1], self.N_grid[2], 3), dtype=np.float64 ) ## The origin of the grid. self.root = np.zeros( (3,), dtype=np.float64) ## Boundary conditions, in the three directions. 0 = PBC , 1 = elastic collision with virtual particles. self.BC = np.zeros( (3,) , dtype=np.int32 ) ## Wall velocity, on each wall. indices = wall dir (x,y,z) , wall low/high , v. self.wall_v0 = np.zeros( (3, 2, 3) , dtype=np.float64 ) ## Wall temperature for the virtual particles on each wall side. indices = wall dir (x,y,z), wall low/high. self.wall_temp = np.zeros( (3, 2) , dtype=np.float64 ) ## Magnitude of the acceleration provided by gravity, if applicable. self.gravity = float(0.) ## Number of chemical reactions to consider. self.N_reactions = 0 ## Kind of chemical reaction. self.reaction_kind = [] ## Rates for the chemical reactions. self.rates = [] ## Stoechiometry for reactants. self.reactants = [] ## Stoechiometry for products. self.products = [] def __str__(self): return str(type(self))+' size '+str(self.N_cells)+' , '+str(self.so_N)+' solvent particles' def add_reaction(self, rate, reactants, products): if ( not (len(reactants) == len(products) == self.N_species) ): print("Bad input for add_reaction") return if ( (min(reactants)<0) or (min(products)<0) ): print("Bad input for add_reaction") return N_reactants = np.sum(reactants) N_products = np.sum(products) if ( (N_reactants==1) and (N_products==1) ): kind = 0 elif ( reactants[0]==1 and reactants[1]==2 and products[1]==3): kind = 1 else: print("reaction type not supported in add_reaction") return self.N_reactions += 1 self.reaction_kind.append(kind) self.rates.append(rate) self.reactants.append(reactants) self.products.append(products) def close_reaction(self): if (self.N_reactions > 0): self.rates = np.array(self.rates) self.reactants = np.array(self.reactants,ndmin=2) self.products = np.array(self.products,ndmin=2) ## Initializes the particles according to a normal or flat velocity profile. # \param temp Initial temperature of the system. # \param boltz if True or unset, use a normal velocity profile of temperature T. # Else, use a flat profile. def init_v(self, temp, boltz=True): """ Initializes the particles according to a normal distribution of temperature temp and resets the total velocity of the system. If boltz is set to False, a uniform distribution is used instead """ if boltz: self.so_v[:,:] = np.random.randn( self.so_v.shape[0], self.so_v.shape[1] ) * np.sqrt(temp) self.so_v /= np.sqrt(self.so_mass[self.so_species]).reshape( (self.so_N, 1) ) else: self.so_v[:,:] = np.random.rand( self.so_v.shape[0], self.so_v.shape[1] ) self.so_v[:,:] -= 0.5 self.so_v[:,:] *= 2.*np.sqrt(6.*temp/2.) tot_v = np.sum( self.so_v*(self.so_mass[self.so_species]).reshape( (self.so_N, 1) ) , axis=0 ) / self.so_mass[self.so_species].sum() tot_v = tot_v.reshape( ( 1 , tot_v.shape[0] ) ) self.so_v -= tot_v ## Places particles in the simulation box at random according to a uniform distribution. def init_r(self): """ Places particles in the simulation box at random according to a uniform distribution. """ self.so_r[:,:] = np.random.rand( self.so_r.shape[0], self.so_r.shape[1] ) self.so_r *= (self.a*self.N_cells).reshape( ( 1 , self.so_r.shape[1] ) ) ## Advances the particles according to their velocities. def stream(self): """Advances the particles according to their velocities.""" self.so_r[:] += self.so_v*self.tau ## Advances the particles according to their velocities by calling a Fortran routine. def stream_f(self): """"Advances the particles according to their velocities by calling a Fortran routine.""" mpcd_mod.stream(self.so_r_f, self.so_v_f, self.tau) ## Advances the particles according to their velocities and a constant acceleration in the z direction. # Also updates the velocities to take into account the acceleration. def accel(self): """ Advances the particles according to their velocities and a constant acceleration in the z direction. Also updates the velocities to take into account the acceleration. """ self.so_r[:] += self.so_v*self.tau + np.array( [0., 0., self.gravity] ).reshape( (1, 3) )*0.5*self.tau**2 self.so_v[:] += np.array( [0., 0., self.gravity] ).reshape( (1, 3) )*self.tau ## Corrects particles positions and velocities to take into account the boundary conditions. def boundaries(self): """ Corrects particles positions and velocities to take into account the boundary conditions. PBC keep the particles in the box by sending them to their periodic in-box location. Elastic walls reflect particles and reverse the velocities. """ for i in range(3): # take each dim if (self.BC[i] == 0): # if PBC, simply appy x = mod( x , L ) to keep particles in the box self.so_r[:,i] = np.remainder( self.so_r[:,i] , self.L[i] ) elif (self.BC[i] == 1): # if elastic wall, reflect "too high" particles around L and "too low" particles around 0 j_out = ( self.so_r[:,i] > self.L[i] ) self.so_r[j_out,i] = 2.*self.L[i] - self.so_r[j_out,i] self.so_v[j_out,i] = - self.so_v[j_out,i] j_out = ( self.so_r[:,i] < 0 ) self.so_r[j_out,i] = - self.so_r[j_out,i] self.so_v[j_out,i] = - self.so_v[j_out,i] else: print "unknown boundary condition ", self.BC[i] raise Exception def check_in_box(self): """ A test routine to check that all particles are actually in the box [0:L] """ r_min = self.so_r.min(axis=0) t_min = ( r_min >= 0. ).min() r_max = self.so_r.max(axis=0) t_max = ( r_max < self.L ).min() if ( t_min and t_max ): return True else: return False def print_check_in_box(self): if (self.check_in_box()): print "All particles inside the box" else: print "Some particles outside the box" def null_shift(self): """ Resets the shift to zero. """ self.shift[:] = 0. self.root[:] = self.shift[:] - self.a def rand_shift(self): """ Applies a random shift in [0:a[ to the system. """ self.shift[:] = np.random.random( self.shift.shape[0] )*self.a self.root[:] = self.shift[:] - self.a def idx(self, i , cijk): """ Returns in cijk the three cell indices for particle i. """ np.floor( (self.so_r[i,:] - self.root) / self.a , cijk ) for j in range(3): my_n = self.N_cells[j] if (self.BC[j] == 0): if ( cijk[j] >= my_n ): cijk[j] -= my_n ## Bins the particles into the MPCD cells. def fill_box(self): """ Bins the particles into the MPCD cells. """ cijk = np.zeros( (3,) , dtype=np.int32 ) self.cells[:] = 0 self.par_list[:] = 0 for i in range(self.so_N): self.idx( i , cijk ) my_n = self.cells[ cijk[0] , cijk[1] , cijk[2] ] self.par_list[ cijk[0] , cijk[1] , cijk[2] , my_n ] = i self.cells[ cijk[0] , cijk[1] , cijk[2] ] = my_n + 1 ## Bins the particles into the MPCD cells by calling a Fortran routine. def fill_box_f(self): """"Bins the particles into the MPCD cells by calling a Fortran routine.""" mpcd_mod.fill_box(self.so_r_f, self.cells_f, self.par_list_f, self.a, self.root) ## Computes the center of mass velocity for all the cells in the system. # \param self A MPCD_system instance. def compute_v_com(self): """ Computes the c.o.m. velocity for all cells. """ self.v_com[:] = 0 for ci in range(self.N_grid[0]): for cj in range(self.N_grid[1]): for ck in range(self.N_grid[2]): mass_local = 0. v_local = np.zeros( (3, ) , dtype=np.float64) n_local = self.cells[ci,cj,ck] for i in range( n_local ): part = self.par_list[ci,cj,ck,i] v_local += self.so_v[part,:]*self.so_mass[self.so_species[part]] mass_local += self.so_mass[self.so_species[part]] if (n_local > 0): self.v_com[ci,cj,ck,:] = v_local/mass_local ## Computes the temperature of the cells. # The temperature is computed as \f$ \frac{ \sum_{i=1}^{N^\xi} m_i (v_i-v_0) ^2 }{N^\xi-1} \f$ # where \f$ v_0 \f$ is the center of mass velocity of the cell. # \param self A MPCD_system instance. def compute_cells_temperature(self): for ci in range(self.N_grid[0]): for cj in range(self.N_grid[1]): for ck in range(self.N_grid[2]): v_local = self.v_com[ci,cj,ck,:] T_local = 0. n_local = self.cells[ci,cj,ck] for i in range(n_local): part = self.par_list[ci,cj,ck,i] T_local += self.so_mass[self.so_species[part]]*((self.so_v[part,:]-v_local)**2).sum() if (n_local>1): T_local /= 3.*(n_local-1) self.cells_temperature[ci,cj,ck] = T_local def MPCD_step_axis(self): """ Performs a MPCD collision step where the axis is one of x, y or z, chosen at random. """ v_therm = np.zeros((3,)) nn = self.N_cells.copy() nn += self.BC is_wall = False v_wall = np.zeros( (3,) ) local_N = np.zeros( (self.N_species,) , dtype=np.int32) amu = np.zeros( (self.N_reactions,), dtype=np.float64) for ci in range(nn[0]): for cj in range(nn[1]): for ck in range(nn[2]): # Choose an axis to perform the rotation rand_axis = np.random.randint(0,3) axis1 = ( rand_axis + 1 ) % 3 axis2 = ( rand_axis + 2 ) % 3 if (np.random.randint(2)==0): r_sign = 1 else: r_sign = -1 # test if is a wall is_wall = False local_i = [ ci , cj , ck ] for i in range(3): if (self.BC[i]==1): if ( (local_i[i]==0) or (local_i[i]==nn[i]-1) ): is_wall=True v_wall[:] = self.wall_v0[ i , min( local_i[i], 1 ) , : ] v_temp = float(self.wall_temp[ i , min( local_i[i] , 1 ) ]) # number of particles in the cell local_n = self.cells[ci,cj,ck] # c.o.m. velocity in the cell local_v = self.v_com[ci,cj,ck,:].copy() # if cell is a wall, add virtual particles if (is_wall): if (local_n < self.density): local_v = ( (np.random.randn(3) * np.sqrt(v_temp * (self.density - local_n) ) ) + v_wall*(self.density - local_n) + local_v * local_n ) / self.density v_therm +=local_v # perform cell-wise collisions local_N *= 0 for i in range(local_n): part = self.par_list[ci,cj,ck,i] self.so_v[part,:] -= local_v temp = self.so_v[part,axis2] self.so_v[part,axis2] = r_sign*self.so_v[part,axis1] self.so_v[part,axis1] = -r_sign*temp self.so_v[part,:] += local_v local_N[self.so_species[part]] += 1 # evaluate reaction probability a0 = 0. for i in range(self.N_reactions): amu[i] = self.combi( i, local_N )*self.rates[i] a0 += amu[i] P_something = a0*self.tau reac = -1 if (np.random.rand() < P_something): amu /= a0 amu = np.cumsum(amu) x = np.random.rand() for i in range(self.N_reactions): if (x < amu[i]): reac = i break # apply reaction reac if (reac>=0): if (self.reaction_kind[reac]==0): reac_s = np.where(self.reactants[i]==1)[0][0] prod_s = np.where(self.products[i]==1)[0][0] for i in range(local_n): part = self.par_list[ci,cj,ck,i] if (self.so_species[part]==reac_s): self.so_species[part] = prod_s break elif (self.reaction_kind[reac]==1): reac_s = np.where(self.reactants[i]==1)[0][0] prod_s = np.where(self.products[i]==3)[0][0] for i in range(local_n): part = self.par_list[ci,cj,ck,i] if (self.so_species[part]==reac_s): self.so_species[part] = prod_s break else: raise Exception def combi(self, reac, N): R = self.reactants[reac] P = self.products[reac] r = 1.0 for i in range(self.N_species): if ( N[i] < R[i] ): return 0 r *= factorial(N[i],exact=1) r /= factorial(N[i]-R[i],exact=1) return r ## Exchanges the positions, momenta and species of two solvent particles. # \param i index of the first particle to be exchanged. # \param j index of the second particle to be exchanged. def exchange_solvent(self,i,j): """ Exchanges the positions, momenta and species of two solvent particles. """ tmp_copy = self.so_r[i,:].copy() self.so_r[i,:] = self.so_r[j,:] self.so_r[j,:] = tmp_copy tmp_copy = self.so_v[i,:].copy() self.so_v[i,:] = self.so_v[j,:] self.so_v[j,:] = tmp_copy tmp_copy = self.so_species[i].copy() self.so_species[i] = self.so_species[j] self.so_species[j] = tmp_copy ## Sorts the solvent in the x,y,z cell order. def sort_solvent(self): """ Sorts the solvent in the x,y,z cell order. """ nn = self.N_cells.copy() nn += self.BC array_idx = 0 for ci in range(nn[0]): for cj in range(nn[1]): for ck in range(nn[2]): local_n = self.cells[ci,cj,ck] for i in range(local_n): self.exchange_solvent(self.par_list[ci,cj,ck,i],array_idx) array_idx += 1 def one_full_step(self): """ Performs a full step of MPCD without gravitation, including the streaming, taking into account the boundary conditions and the MPCD collision step. """ self.stream() self.boundaries() self.rand_shift() self.fill_box() self.compute_v_com() self.MPCD_step_axis() def one_full_accel(self): """ Performs a full step of MPCD with gravitation, including the streaming, taking into account the boundary conditions and the MPCD collision step. """ self.accel() self.boundaries() self.rand_shift() self.fill_box() self.compute_v_com() self.MPCD_step_axis() def one_full_step_f(self): """ Performs a full step of MPCD without gravitation, including the streaming, taking into account the boundary conditions and the MPCD collision step. The streaming and binning steps are performed in Fortran. """ self.stream_f() self.boundaries() self.rand_shift() self.fill_box_f() self.compute_v_com() self.MPCD_step_axis()
pdebuyl/pyMPCD
pyMPCD/MPCD.py
Python
gpl-3.0
21,970
<?php namespace Tests\PhpCmplr\Core\Reflection; use PhpCmplr\Core\Container; use PhpCmplr\Core\FileStoreInterface; use PhpCmplr\Core\SourceFile\SourceFile; use PhpCmplr\Core\Parser\Parser; use PhpCmplr\Core\DocComment\DocCommentParser; use PhpCmplr\Core\NameResolver\NameResolver; use PhpCmplr\Core\Reflection\FileReflection; use PhpCmplr\Core\Reflection\LocatorReflection; use PhpCmplr\Core\Reflection\LocatorInterface; use PhpCmplr\Core\Reflection\Element\Class_; use PhpCmplr\Core\Reflection\Element\ClassLike; use PhpCmplr\Core\Reflection\Element\Function_; use PhpCmplr\Core\Reflection\Element\Interface_; use PhpCmplr\Core\Reflection\Element\Trait_; use PhpCmplr\Util\FileIOInterface; use PhpCmplr\Core\Parser\PositionsReconstructor; /** * @covers \PhpCmplr\Core\Reflection\LocatorReflection */ class LocatorReflectionTest extends \PHPUnit_Framework_TestCase { protected function loadFile($contents, $path = 'qaz.php') { $container = new Container(); $container->set('file', new SourceFile($container, $path, $contents)); $container->set('parser', new Parser($container)); $container->set('parser.positions_reconstructor', new PositionsReconstructor($container)); $container->set('doc_comment', new DocCommentParser($container)); $container->set('name_resolver', new NameResolver($container)); $container->set('reflection.file', new FileReflection($container)); return $container; } public function test_findClass() { $cont1 = $this->loadFile('<?php class CC { public function f() {} }', '/qaz.php'); $cont2 = $this->loadFile('<?php ;', '/wsx.php'); $fileStore = $this->getMockForAbstractClass(FileStoreInterface::class); $fileStore->expects($this->exactly(1)) ->method('getFile') ->with($this->equalTo('/qaz.php')) ->willReturn($cont1); $cont2->set('file_store', $fileStore); $locator = $this->getMockForAbstractClass(LocatorInterface::class); $locator->expects($this->once()) ->method('getPathsForClass') ->with($this->equalTo('\\CC')) ->willReturn(['/qaz.php']); $cont2->set('locator', $locator, ['reflection.locator']); $io = $this->getMockForAbstractClass(FileIOInterface::class); $cont2->set('io', $io); $refl = new LocatorReflection($cont2); $classes = $refl->findClass('\\CC'); $this->assertCount(1, $classes); $this->assertSame('\\CC', $classes[0]->getName()); $this->assertSame('f', $classes[0]->getMethods()[0]->getName()); $classesCaseInsensitive = $refl->findClass('\\cC'); $this->assertSame($classes, $classesCaseInsensitive); } public function test_findFunction() { $cont1 = $this->loadFile('<?php function fff() {}', '/qaz.php'); $cont2 = $this->loadFile('<?php ;', '/wsx.php'); $fileStore = $this->getMockForAbstractClass(FileStoreInterface::class); $fileStore->expects($this->exactly(1)) ->method('getFile') ->with($this->equalTo('/qaz.php')) ->willReturn($cont1); $cont2->set('file_store', $fileStore); $locator = $this->getMockForAbstractClass(LocatorInterface::class); $locator->expects($this->once()) ->method('getPathsForFunction') ->with($this->equalTo('\\fff')) ->willReturn(['/qaz.php']); $cont2->set('locator', $locator, ['reflection.locator']); $io = $this->getMockForAbstractClass(FileIOInterface::class); $cont2->set('io', $io); $refl = new LocatorReflection($cont2); $functions = $refl->findFunction('\\fff'); $this->assertCount(1, $functions); $this->assertSame('\\fff', $functions[0]->getName()); $functionsCaseInsensitive = $refl->findFunction('\\fFf'); $this->assertSame($functions, $functionsCaseInsensitive); } public function test_findConst() { $cont1 = $this->loadFile('<?php const ZZ = 7;', '/qaz.php'); $cont2 = $this->loadFile('<?php ;', '/wsx.php'); $fileStore = $this->getMockForAbstractClass(FileStoreInterface::class); $fileStore->expects($this->exactly(1)) ->method('getFile') ->with($this->equalTo('/qaz.php')) ->willReturn($cont1); $cont2->set('file_store', $fileStore); $locator = $this->getMockForAbstractClass(LocatorInterface::class); $locator->expects($this->exactly(2)) ->method('getPathsForConst') ->withConsecutive([$this->equalTo('\\ZZ')], [$this->equalTo('\\zZ')]) ->will($this->onConsecutiveCalls(['/qaz.php'], [])); $cont2->set('locator', $locator, ['reflection.locator']); $io = $this->getMockForAbstractClass(FileIOInterface::class); $cont2->set('io', $io); $refl = new LocatorReflection($cont2); $consts = $refl->findConst('\\ZZ'); $this->assertCount(1, $consts); $this->assertSame('\\ZZ', $consts[0]->getName()); $constsCaseSensitive = $refl->findConst('\\zZ'); $this->assertCount(0, $constsCaseSensitive); } }
tsufeki/phpcmplr
tests/PhpCmplr/Core/Reflection/LocatorReflectionTest.php
PHP
gpl-3.0
5,229
var Gpio = function (physicalPin, wiringPiPin, name) { this.id = physicalPin; this.physicalPin = physicalPin; this.wiringPiPin = wiringPiPin; this.name = name; } Gpio.fromGpioDefinition = function (definition) { return new Gpio(definition.physicalPin, definition.wiringPiPin, definition.name); } module.exports = Gpio;
jvandervelden/rasp-train
src/node/models/gpio.js
JavaScript
gpl-3.0
340
#include "Granulizer.h" #include <iostream> Granulizer::Granulizer() : grainIdx_(0), straightIdx_(0), grainLen_(0.0f), generator(std::chrono::system_clock::now().time_since_epoch().count()) { } bool Granulizer::loadLoop(char* filename) { grainIdx_ = 0; grainLen_ = 0; SNDFILE* sfFile = sf_open(filename, SFM_READ, &sfInfo_); if (sfFile) { sf_command(sfFile, SFC_SET_NORM_FLOAT, NULL, SF_TRUE); loop_.resize(sfInfo_.frames * sfInfo_.channels); sf_read_float(sfFile, loop_.data(), sfInfo_.frames * sfInfo_.channels); sf_close(sfFile); std::cout << "Successfully loaded " << filename << "." << std::endl; grainLen_ = float(sfInfo_.frames) / sfInfo_.samplerate * 1000.0f; return true; } else { std::cerr << "Error: cannot open " << filename << "." << std::endl; } return false; } const Granulizer::Frame& Granulizer::grainedFrame() { Frame frame; frame.first = loop_[(grainStart_ + grainIdx_) % loop_.size()]; frame.second = loop_[(grainStart_ + grainIdx_ + 1) % loop_.size()]; grainIdx_ += 2; if (grainIdx_ > grainLen_ * sfInfo_.samplerate) { newGrain(); } return frame; } const Granulizer::Frame& Granulizer::straightFrame() { Frame frame; frame.first = loop_[straightIdx_++]; frame.second = loop_[straightIdx_++]; straightIdx_ %= loop_.size(); return frame; } void Granulizer::newGrain() { grainIdx_ = 0; grainStart_ = (generator() % int(sfInfo_.frames * 0.5 * sfInfo_.channels)) * 2; }
vooku/Generate-festival-music-demo
src/Granulizer.cpp
C++
gpl-3.0
1,629
package org.remipassmoilesel.bookme.services; import org.remipassmoilesel.bookme.utils.Utils; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.util.Objects; /** * Created by remipassmoilesel on 30/01/17. */ public class MerchantServiceForm { @NotNull @Min(0) private double totalPrice; @NotNull private long id = -1; @NotNull @Size(max = 2000) private String comment; @NotNull @Size(min = 2, max = 50) private String customerFirstname; @NotNull @Size(min = 2, max = 50) private String customerLastname; @NotNull @Size(min = 2, max = 50) @Pattern(regexp = "\\+?[0-9]+") private String customerPhonenumber; @NotNull private Long customerId = -1l; @NotNull @Pattern(regexp = "([0-9]{2}/[0-9]{2}/[0-9]{4} [0-9]{2}:[0-9]{2})?") private String executionDate; @NotNull private Long serviceType = -1l; @NotNull private Boolean paid = false; @NotNull private Boolean scheduled = false; @NotNull private Long token; public MerchantServiceForm() { } /** * Load a service in form * * @param service */ public void load(MerchantService service) { if (service == null) { return; } setTotalPrice(service.getTotalPrice()); setId(service.getId()); if (service.getCustomer() != null) { setCustomerId(service.getCustomer().getId()); setCustomerFirstname(service.getCustomer().getFirstname()); setCustomerLastname(service.getCustomer().getLastname()); setCustomerPhonenumber(service.getCustomer().getPhonenumber()); } if (service.getExecutionDate() != null) { setExecutionDate(Utils.dateToString(service.getExecutionDate(), "dd/MM/YYYY HH:mm")); } if (service.getServiceType() != null) { setServiceType(service.getServiceType().getId()); } setComment(service.getComment()); setPaid(service.isPaid()); setScheduled(service.isScheduled()); } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getCustomerFirstname() { return customerFirstname; } public void setCustomerFirstname(String customerFirstname) { this.customerFirstname = customerFirstname; } public String getCustomerLastname() { return customerLastname; } public void setCustomerLastname(String customerLastname) { this.customerLastname = customerLastname; } public String getCustomerPhonenumber() { return customerPhonenumber; } public void setCustomerPhonenumber(String customerPhonenumber) { this.customerPhonenumber = customerPhonenumber; } public long getCustomerId() { return customerId; } public void setCustomerId(long customerId) { this.customerId = customerId; } public String getExecutionDate() { return executionDate; } public void setExecutionDate(String executionDate) { this.executionDate = executionDate; } public long getServiceType() { return serviceType; } public void setServiceType(long serviceType) { this.serviceType = serviceType; } public boolean isPaid() { return paid; } public void setPaid(boolean paid) { this.paid = paid; } public boolean isScheduled() { return scheduled; } public void setScheduled(boolean scheduled) { this.scheduled = scheduled; } public Long getToken() { return token; } public void setToken(Long token) { this.token = token; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MerchantServiceForm that = (MerchantServiceForm) o; return totalPrice == that.totalPrice && id == that.id && customerId == that.customerId && serviceType == that.serviceType && paid == that.paid && scheduled == that.scheduled && Objects.equals(comment, that.comment) && Objects.equals(customerFirstname, that.customerFirstname) && Objects.equals(customerLastname, that.customerLastname) && Objects.equals(customerPhonenumber, that.customerPhonenumber) && Objects.equals(executionDate, that.executionDate) && Objects.equals(token, that.token); } @Override public int hashCode() { return Objects.hash(totalPrice, id, comment, customerFirstname, customerLastname, customerPhonenumber, customerId, executionDate, serviceType, paid, scheduled, token); } }
remipassmoilesel/simple-hostel-management
src/main/java/org/remipassmoilesel/bookme/services/MerchantServiceForm.java
Java
gpl-3.0
5,356
# Monkey-patch OpenSSL to skip checking the hostname of the remote certificate. # We need to enable VERIFY_PEER in order to get hands on the remote certificate # to check the fingerprint. But we don't care for the matching of the # hostnames. Unfortunately this patch is apparently the only way to achieve # that. module OpenSSL module SSL def self.verify_certificate_identity(peer_cert, hostname) Rails.logger.debug "Ignoring check for hostname (verify_certificate_identity())." true end end end
schleuder/schleuder-web
lib/openssl_ssl_patch.rb
Ruby
gpl-3.0
521
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MECS.Core.Engraving { public class EngraverPosition { public int X { get; set; } public int Y { get; set; } } }
Mr-Alicates/MECS
MECS/MECS.Core/Engraving/EngraverPosition.cs
C#
gpl-3.0
270
#include "chessgame.h" #include <QUrl> #include <QQmlContext> #include <QDebug> #include "validator/pawnvalidator.h" #include "validator/rookvalidator.h" #include "validator/knightvalidator.h" #include "validator/bishopvalidator.h" #include "validator/queenvalidator.h" #include "validator/kingvalidator.h" #define HISTORY_MARKER 0xDADA ChessGame::ChessGame(QObject *parent) : QObject(parent) , m_screenId(Screen_1) , m_pEngine(nullptr) , m_pChessboard(nullptr) , m_lastMovedIdx(0) {} void ChessGame::initialize(QQmlApplicationEngine *pEngine) { m_pEngine = pEngine; m_pChessboard = pEngine->rootObjects().first()->findChild<QQuickItem *>("chessboard"); foreach (QQuickItem *pItem, m_pChessboard->findChildren<QQuickItem *>(QRegExp("chesspiece\\d\\d?"))) setValidatorByIdx(pItem); } void ChessGame::start() { m_history.clear(); QMetaObject::invokeMethod(m_pChessboard, "init", Q_ARG(QVariant, true)); m_field.resetField(m_pChessboard); m_lastMovedIdx = 0; setScreenId(Screen_2); qDebug("The Game is STARTED"); } void ChessGame::stop() { QMetaObject::invokeMethod(m_pChessboard, "clear"); setScreenId(Screen_1); qDebug("The Game is STOPPED"); } void ChessGame::load(const QUrl &filepath) { QString name = filepath.toLocalFile(); QFile f(name); if (!f.open(QFile::ReadOnly)) { qDebug() << "Can't open file:" << name; return; } QDataStream s(&f); quint16 marker; s >> marker; if (static_cast<quint16>(HISTORY_MARKER) == marker) { s >> m_history; QMetaObject::invokeMethod(m_pChessboard, "init", Q_ARG(QVariant, false)); setScreenId(Screen_3); qDebug() << "LOADED:" << name; } } void ChessGame::save(const QUrl &filepath) { QString name = filepath.toLocalFile(); QFile f(name); if (!f.open(QFile::WriteOnly)) { qDebug() << "Can't open file:" << name; return; } QDataStream s(&f); s << static_cast<quint16>(HISTORY_MARKER) << m_history; qDebug() << "SAVED:" << name; } bool ChessGame::prev() { Move *pMove = m_history.getPrev(); if (pMove) { QQuickItem *pItem = getChessPieceByIdx(pMove->getMovedIdx()); QMetaObject::invokeMethod(pItem, "moveToCell", Q_ARG(QVariant, pMove->getBefore())); if (pMove->getDeletedIdx()) { QQuickItem *pDelItem = getChessPieceByIdx(pMove->getDeletedIdx()); pDelItem->setProperty("visible", true); } qDebug() << "PREV:" << pMove->getMovedIdx() << pMove->getBefore() << pMove->getAfter() << pMove->getDeletedIdx(); } return pMove; } bool ChessGame::next() { Move *pMove = m_history.getNext(); if (pMove) { QQuickItem *pItem = getChessPieceByIdx(pMove->getMovedIdx()); QMetaObject::invokeMethod(pItem, "moveToCell", Q_ARG(QVariant, pMove->getAfter())); if (pMove->getDeletedIdx()) { QQuickItem *pDelItem = getChessPieceByIdx(pMove->getDeletedIdx()); pDelItem->setProperty("visible", false); } qDebug() << "NEXT:" << pMove->getMovedIdx() << pMove->getBefore() << pMove->getAfter() << pMove->getDeletedIdx(); } return pMove; } bool ChessGame::move(int sIdx, int sCell, int dCell) { bool isValidColor = (m_lastMovedIdx <= 16 && sIdx > 16) || (m_lastMovedIdx > 16 && sIdx <= 16); int deletedIdx = 0; if (isValidColor && m_field.makeMove(sCell, dCell, &deletedIdx)) { m_history.addStep(Move(sIdx, sCell, dCell, deletedIdx)); m_lastMovedIdx = sIdx; return true; } return false; } void ChessGame::setValidatorByIdx(QQuickItem *pChessPiece) { static IValidator *pPawnValidator = new PawnValidator(&m_field, m_pChessboard); static IValidator *pRookValidator = new RookValidator(&m_field, m_pChessboard); static IValidator *pKnightValidator = new KnightValidator(&m_field, m_pChessboard); static IValidator *pBishopValidator = new BishopValidator(&m_field, m_pChessboard); static IValidator *pQueenValidator = new QueenValidator(&m_field, m_pChessboard); static IValidator *pKingValidator = new KingValidator(&m_field, m_pChessboard); int idx = pChessPiece->property("idx").toInt(); if ((idx >= 9 && idx <= 16) || (idx >= 49 && idx <= 56)) { pChessPiece->setProperty("validator", QVariant::fromValue(pPawnValidator)); } else { switch (idx) { case 1: case 8: case 57: case 64: pChessPiece->setProperty("validator", QVariant::fromValue(pRookValidator)); break; case 2: case 7: case 58: case 63: pChessPiece->setProperty("validator", QVariant::fromValue(pKnightValidator)); break; case 3: case 6: case 59: case 62: pChessPiece->setProperty("validator", QVariant::fromValue(pBishopValidator)); break; case 4: case 60: pChessPiece->setProperty("validator", QVariant::fromValue(pQueenValidator)); break; case 5: case 61: pChessPiece->setProperty("validator", QVariant::fromValue(pKingValidator)); break; } } } QQuickItem *ChessGame::getChessPieceByIdx(int idx) { return m_pChessboard->findChild<QQuickItem *>(QString("chesspiece%1").arg(idx)); }
remico/dai-chess
src/chessgame.cpp
C++
gpl-3.0
5,364
<?php /** * Dashboard - Products * * @package FrozrCoreLibrary * @subpackage FrozrmarketTemplates */ if ( ! defined( 'ABSPATH' ) ) exit; /* Exit if accessed directly*/ frozr_redirect_login(); frozr_redirect_if_not_seller(); $action = isset( $_GET['action'] ) ? wc_clean($_GET['action']) : 'listing'; if ( $action == 'edit' ) { frozr_get_template( FROZR_WOO_TMP . '/dish-edit.php'); } else { frozr_get_template( FROZR_WOO_TMP . '/dishes-listing.php'); }
MahmudHamid/LazyEater
templates/dishes.php
PHP
gpl-3.0
471
window.saveData = function (key, data) { if(!localStorage.savedData) localStorage.savedData = JSON.stringify({}); var savedData = JSON.parse(localStorage.savedData) var type = typeof data; savedData[key] = { type: type, data: (type === 'object') ? JSON.stringify(data) : data }; localStorage.savedData = JSON.stringify(savedData); } window.getData = function (key) { var savedData = JSON.parse(localStorage.savedData) if(savedData[key] !== undefined) { var value = savedData[key]; if(value.type === 'number') { return parseFloat(value.data) } else if (value.type === 'string') { return value.data; } else if (value.type === 'object') { return JSON.parse(value.data); } } else { throw (new Error(key + " does not exist in saved data.")) } }
zrispo/wick
lib/localstoragewrapper.js
JavaScript
gpl-3.0
780
// This file is part of BOINC. // http://boinc.berkeley.edu // Copyright (C) 2008 University of California // // BOINC 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. // // BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>. // SCHED_SHMEM is the structure of a chunk of memory shared between // the feeder (which reads from the database) // and instances of the scheduling server #include "config.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <vector> using std::vector; #include "boinc_db.h" #include "error_numbers.h" #ifdef _USING_FCGI_ #include "boinc_fcgi.h" #endif #include "sched_config.h" #include "sched_msgs.h" #include "sched_types.h" #include "sched_util.h" #include "sched_shmem.h" void SCHED_SHMEM::init(int nwu_results) { int size = sizeof(SCHED_SHMEM) + nwu_results*sizeof(WU_RESULT); memset(this, 0, size); ss_size = size; platform_size = sizeof(PLATFORM); app_size = sizeof(APP); app_version_size = sizeof(APP_VERSION); assignment_size = sizeof(ASSIGNMENT); wu_result_size = sizeof(WU_RESULT); max_platforms = MAX_PLATFORMS; max_apps = MAX_APPS; max_app_versions = MAX_APP_VERSIONS; max_assignments = MAX_ASSIGNMENTS; max_wu_results = nwu_results; } static int error_return(const char* p) { fprintf(stderr, "Error in structure: %s\n", p); return ERR_SCHED_SHMEM; } int SCHED_SHMEM::verify() { int size = sizeof(SCHED_SHMEM) + max_wu_results*sizeof(WU_RESULT); if (ss_size != size) return error_return("shmem"); if (platform_size != sizeof(PLATFORM)) return error_return("platform"); if (app_size != sizeof(APP)) return error_return("app"); if (app_version_size != sizeof(APP_VERSION)) return error_return("app_version"); if (assignment_size != sizeof(ASSIGNMENT)) return error_return("assignment"); if (wu_result_size != sizeof(WU_RESULT)) return error_return("wu_result"); if (max_platforms != MAX_PLATFORMS) return error_return("max platform"); if (max_apps != MAX_APPS) return error_return("max apps"); if (max_app_versions != MAX_APP_VERSIONS) return error_return("max app versions"); if (max_assignments != MAX_ASSIGNMENTS) return error_return("max assignments"); return 0; } static void overflow(const char* table, const char* param_name) { log_messages.printf(MSG_CRITICAL, "The SCHED_SHMEM structure is too small for the %s table.\n" "Either increase the %s parameter in sched_shmem.h and recompile,\n" "or prune old rows from the table.\n" "Then restart the project.\n", table, param_name ); exit(1); } int SCHED_SHMEM::scan_tables() { DB_PLATFORM platform; DB_APP app; DB_APP_VERSION app_version; DB_ASSIGNMENT assignment; int i, j, n; n = 0; while (!platform.enumerate()) { if (platform.deprecated) continue; platforms[n++] = platform; if (n == MAX_PLATFORMS) { overflow("platforms", "MAX_PLATFORMS"); } } nplatforms = n; n = 0; app_weight_sum = 0; while (!app.enumerate()) { if (app.deprecated) continue; apps[n++] = app; if (n == MAX_APPS) { overflow("apps", "MAX_APPS"); } app_weight_sum += app.weight; if (app.locality_scheduling == LOCALITY_SCHED_LITE) { locality_sched_lite = true; } if (app.non_cpu_intensive) { have_nci_app = true; } if (config.non_cpu_intensive) { have_nci_app = true; app.non_cpu_intensive = true; } } napps = n; n = 0; // for each (app, platform) pair, // get all versions with numbers maximal in their plan class. // for (i=0; i<nplatforms; i++) { PLATFORM& splatform = platforms[i]; for (j=0; j<napps; j++) { APP& sapp = apps[j]; vector<APP_VERSION> avs; char query[1024]; sprintf(query, "where appid=%d and platformid=%d and deprecated=0", sapp.id, splatform.id ); while (!app_version.enumerate(query)) { avs.push_back(app_version); } for (unsigned int k=0; k<avs.size(); k++) { APP_VERSION& av1 = avs[k]; for (unsigned int kk=0; kk<avs.size(); kk++) { if (k == kk) continue; APP_VERSION& av2 = avs[kk]; if (!strcmp(av1.plan_class, av2.plan_class) && av1.version_num > av2.version_num) { av2.deprecated = 1; } } } for (unsigned int k=0; k<avs.size(); k++) { APP_VERSION& av1 = avs[k]; if (av1.deprecated) continue; if (av1.min_core_version && av1.min_core_version < 10000) { fprintf(stderr, "min core version too small - multiplying by 100\n"); av1.min_core_version *= 100; } if (av1.max_core_version && av1.max_core_version < 10000) { fprintf(stderr, "max core version too small - multiplying by 100\n"); av1.max_core_version *= 100; } app_versions[n++] = av1; if (n == MAX_APP_VERSIONS) { overflow("app_versions", "MAX_APP_VERSIONS"); } } } } napp_versions = n; // see which resources we have app versions for // for (i=0; i<NPROC_TYPES; i++) { have_apps_for_proc_type[i] = false; } for (i=0; i<napp_versions; i++) { APP_VERSION& av = app_versions[i]; if (strstr(av.plan_class, "cuda") || strstr(av.plan_class, "nvidia")) { have_apps_for_proc_type[PROC_TYPE_NVIDIA_GPU] = true; } else if (strstr(av.plan_class, "ati")) { have_apps_for_proc_type[PROC_TYPE_AMD_GPU] = true; } else if (strstr(av.plan_class, "intel_gpu")) { have_apps_for_proc_type[PROC_TYPE_INTEL_GPU] = true; } else { have_apps_for_proc_type[PROC_TYPE_CPU] = true; } } n = 0; while (!assignment.enumerate("where multi <> 0")) { assignments[n++] = assignment; if (n == MAX_ASSIGNMENTS) { overflow("assignments", "MAX_ASSIGNMENTS"); } } nassignments = n; return 0; } PLATFORM* SCHED_SHMEM::lookup_platform(char* name) { for (int i=0; i<nplatforms; i++) { if (!strcmp(platforms[i].name, name)) { return &platforms[i]; } } return NULL; } PLATFORM* SCHED_SHMEM::lookup_platform_id(int id) { for (int i=0; i<nplatforms; i++) { if (platforms[i].id == id) return &platforms[i]; } return NULL; } APP* SCHED_SHMEM::lookup_app(int id) { for (int i=0; i<napps; i++) { if (apps[i].id == id) return &apps[i]; } return NULL; } APP* SCHED_SHMEM::lookup_app_name(char* name) { for (int i=0; i<napps; i++) { if (!strcmp(name, apps[i].name)) return &apps[i]; } return NULL; } APP_VERSION* SCHED_SHMEM::lookup_app_version(int id) { APP_VERSION* avp; for (int i=0; i<napp_versions; i++) { avp = &app_versions[i]; if (avp->id == id) { return avp; } } return NULL; } APP_VERSION* SCHED_SHMEM::lookup_app_version_platform_plan_class( int platformid, char* plan_class ) { APP_VERSION* avp; for (int i=0; i<napp_versions; i++) { avp = &app_versions[i]; if (avp->platformid == platformid && !strcmp(avp->plan_class, plan_class)) { return avp; } } return NULL; } // see if there's any work. // If there is, reserve it for this process // (if we don't do this, there's a race condition where lots // of servers try to get a single work item) // bool SCHED_SHMEM::no_work(int pid) { if (!ready) return true; for (int i=0; i<max_wu_results; i++) { if (wu_results[i].state == WR_STATE_PRESENT) { wu_results[i].state = pid; return false; } } return true; } void SCHED_SHMEM::restore_work(int pid) { for (int i=0; i<max_wu_results; i++) { if (wu_results[i].state == pid) { wu_results[i].state = WR_STATE_PRESENT; return; } } } void SCHED_SHMEM::show(FILE* f) { fprintf(f, "app versions:\n"); for (int i=0; i<napp_versions; i++) { APP_VERSION av = app_versions[i]; fprintf(f, "appid: %d platformid: %d version_num: %d plan_class: %s\n", av.appid, av.platformid, av.version_num, av.plan_class ); } for (int i=0; i<NPROC_TYPES; i++) { fprintf(f, "have %s apps: %s\n", proc_type_name(i), have_apps_for_proc_type[i]?"yes":"no" ); } fprintf(f, "Jobs; key:\n" "ap: app ID\n" "ic: infeasible count\n" "wu: workunit ID\n" "rs: result ID\n" "hr: HR class\n" "nr: need reliable\n" ); fprintf(f, "host fpops mean %f stddev %f\n", perf_info.host_fpops_mean, perf_info.host_fpops_stddev ); fprintf(f, "host fpops 50th pctile %f 95th pctile %f\n", perf_info.host_fpops_50_percentile, perf_info.host_fpops_95_percentile ); fprintf(f, "ready: %d\n", ready); fprintf(f, "max_wu_results: %d\n", max_wu_results); for (int i=0; i<max_wu_results; i++) { if (i%24 == 0) { fprintf(f, "%4s %12s %10s %10s %10s %8s %10s %8s %12s %12s %9s\n", "slot", "app", "WU ID", "result ID", "batch", "HR class", "priority", "in shmem", "size (stdev)", "need reliable", "inf count" ); } WU_RESULT& wu_result = wu_results[i]; APP* app; const char* appname; int delta_t; switch(wu_result.state) { case WR_STATE_PRESENT: app = lookup_app(wu_result.workunit.appid); appname = app?app->name:"missing"; delta_t = dtime() - wu_result.time_added_to_shared_memory; fprintf(f, "%4d %12.12s %10d %10d %10d %8d %10d %7ds %12f %12s %9d\n", i, appname, wu_result.workunit.id, wu_result.resultid, wu_result.workunit.batch, wu_result.workunit.hr_class, wu_result.res_priority, delta_t, wu_result.fpops_size, wu_result.need_reliable?"yes":"no", wu_result.infeasible_count ); break; case WR_STATE_EMPTY: fprintf(f, "%4d: ---\n", i); break; default: fprintf(f, "%4d: PID %d: result %u\n", i, wu_result.state, wu_result.resultid); } } } const char *BOINC_RCSID_e548c94703 = "$Id$";
MestreLion/boinc-debian
sched/sched_shmem.cpp
C++
gpl-3.0
11,690
import request from '@/utils/request' export function fetchCommon() { return request({ url: '/setting/common/cron/', method: 'get' }) } export function editCommon(formData) { const data = formData return request({ url: '/setting/common/cron/', method: 'put', data }) } export function fetchBotedu() { return request({ url: '/setting/botedu/cron/', method: 'get' }) } export function editBotedu(formData) { const data = formData return request({ url: '/setting/botedu/cron/', method: 'put', data }) } export function fetchStats() { return request({ url: '/setting/stats/cron/', method: 'get' }) } export function editStats(formData) { const data = formData return request({ url: '/setting/stats/cron/', method: 'put', data }) }
wdxtub/Patriots
frontend/src/api/setting.js
JavaScript
gpl-3.0
823
package net.BukkitPE.item.enchantment.bow; import net.BukkitPE.item.enchantment.Enchantment; /** * BukkitPE Project */ public class EnchantmentBowInfinity extends EnchantmentBow { public EnchantmentBowInfinity() { super(Enchantment.ID_BOW_INFINITY, "arrowInfinite", 1); } @Override public int getMinEnchantAbility(int level) { return 20; } @Override public int getMaxEnchantAbility(int level) { return 50; } @Override public int getMaxLevel() { return 1; } }
BukkitPE/BukkitPE
src/main/java/net/BukkitPE/item/enchantment/bow/EnchantmentBowInfinity.java
Java
gpl-3.0
542
class AddStatusToUsers < ActiveRecord::Migration def self.up add_column :users, :status, :string, :default => "U" remove_column :users, :approved end def self.down remove_column :users, :status add_column :users, :approved, :boolean, :default => false end end
IntersectAustralia/nedb
db/migrate/20101015032903_add_status_to_users.rb
Ruby
gpl-3.0
285
#include <stdlib.h> #include <iostream> #include "boats/FloatingObject.hpp" using namespace std; // Quelques conseils avant de commencer... // * N'oubliez pas de tracer (cout << ...) tous les constructeurs et le destructeur !!! Ca, c'est pas un conseil, // c'est obligatoire :-) // * N'essayez pas de compiler ce programme entierement immediatement. Mettez tout en commentaires // sauf le point (1) et creez votre classe (dans ce fichier pour commencer) afin de compiler et tester // le point (1). Une fois que cela fonctionne, decommentez le point (2) et modifier votre classe en // consequence. Vous developpez, compilez et testez donc etape par etape. N'attendez pas d'avoir encode // 300 lignes pour compiler... // * Une fois que tout le programme compile et fonctionne correctement, creez le .h contenant la declaration // de la classe, le .cxx contenant la definition des methodes, et ensuite le makefile permettant de compiler // le tout grace a la commande make int main() { cout << endl << "(1) ***** Test constructeur par defaut + affiche *****" << endl; { FloatingObject objetFlottant; objetFlottant.display(); } // La presence des accolades assure que le destructeur de avion sera appele --> a tracer ! cout << endl << "(2) ***** Test des setters et getters *****" << endl; { FloatingObject objetFlottant; objetFlottant.setIdentifier("HC-1716"); objetFlottant.setModel("HobieCat16Easy"); objetFlottant.display(); cout << "Identifiant = " << objetFlottant.getIdentifier() << endl; cout << "Modele = " << objetFlottant.getModel() << endl; } cout << endl << "(3) ***** Test du constructeur d'initialisation *****" << endl; { FloatingObject objetFlottant("HC-1821","HobieCat21Hard"); objetFlottant.display(); } cout << endl << "(4) ***** Test du constructeur de copie *****" << endl; { FloatingObject objetFlottant1("HC-2110","HobieCat10Easy"); cout << "objetFlottant1 (AVANT) :" << endl; objetFlottant1.display(); { FloatingObject objetFlottant2(objetFlottant1); cout << "objetFlottant2 :" << endl; objetFlottant2.display(); objetFlottant2.setIdentifier("HC-2112"); objetFlottant2.display(); } // de nouveau, les {} assurent que objetFlottant2 sera detruit avant la suite cout << "objetFlottant1 (APRES) :" << endl; objetFlottant1.display(); } cout << endl << "(5) ***** Test d'allocation dynamique (constructeur par defaut) *****" << endl; { FloatingObject *p = new FloatingObject(); p->setIdentifier("BI-4115"); p->setModel("BicCat15Easy"); p->display(); cout << "Le modele de cet objet flottant est : " << p->getModel() << endl; delete p; } cout << endl << "(6) ***** Test d'allocation dynamique (constructeur de copie) *****" << endl; { FloatingObject objetFlottant1("BI-7415","BicCat21Hard"); cout << "objetFlottant1 (AVANT) :" << endl; objetFlottant1.display(); FloatingObject* p = new FloatingObject(objetFlottant1); cout << "La copie :" << endl; p->display(); cout << "Destruction de la copie..." << endl; delete p; cout << "objetFlottant1 (APRES) :" << endl; objetFlottant1.display(); } return 0; }
bendem/SchoolBoats
Test1.cpp
C++
gpl-3.0
3,245
package com.creativemd.opf.gui; import java.util.ArrayList; import com.creativemd.creativecore.common.gui.GuiRenderHelper; import com.creativemd.creativecore.common.gui.client.style.ColoredDisplayStyle; import com.creativemd.creativecore.common.gui.client.style.Style; import com.creativemd.creativecore.common.gui.controls.gui.GuiTextfield; import com.creativemd.opf.OPFrame; import com.google.common.collect.Lists; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.translation.I18n; public class GuiUrlTextfield extends GuiTextfield { public static final Style DISABLED = new Style("disabled", new ColoredDisplayStyle(50, 0, 0), new ColoredDisplayStyle(150, 90, 90), new ColoredDisplayStyle(180, 100, 100), new ColoredDisplayStyle(220, 198, 198), new ColoredDisplayStyle(50, 0, 0, 100)); public static final Style WARNING = new Style("warning", new ColoredDisplayStyle(50, 50, 0), new ColoredDisplayStyle(150, 150, 90), new ColoredDisplayStyle(180, 180, 100), new ColoredDisplayStyle(220, 220, 198), new ColoredDisplayStyle(50, 50, 0, 100)); private SubGuiPic gui; public GuiUrlTextfield(SubGuiPic gui, String name, String text, int x, int y, int width, int height) { super(name, text, x, y, width, height); this.gui = gui; } @Override protected void renderBackground(GuiRenderHelper helper, Style style) { if (!canUse(true)) { style = OPFrame.CONFIG.whitelistEnabled ? DISABLED : WARNING; } super.renderBackground(helper, style); } @Override public boolean onKeyPressed(char character, int key) { boolean pressed = super.onKeyPressed(character, key); gui.save.setEnabled(canUse(false)); return pressed; } @Override public ArrayList<String> getTooltip() { if (!canUse(false)) { return Lists.newArrayList(TextFormatting.RED.toString() + TextFormatting.BOLD.toString() + I18n.translateToLocal("label.opframe.not_whitelisted.name")); } else if (!canUse(true)) { return Lists.newArrayList(TextFormatting.GOLD + I18n.translateToLocal("label.opframe.whitelist_warning.name")); } return Lists.newArrayList(); } protected boolean canUse(boolean ignoreToggle) { return OPFrame.CONFIG.canUse(mc.player, text, ignoreToggle); } }
CreativeMD/OnlinePictureFrame
src/main/java/com/creativemd/opf/gui/GuiUrlTextfield.java
Java
gpl-3.0
2,213
const errorHandler = require('../../../src/controllers/middlewares/error') describe('Error Handler', () => { describe('with generic error', () => { const error = { code: '007', stack: 'StackTrace', } const req = { id: 'request_id' } const res = { locals: {}, } const next = () => {} errorHandler(error, req, res, next) test('should include standard error payload on `res.locals`', () => { expect(res.locals.payload).toMatchObject({ type: 'error', statusCode: 500, data: [{ message: 'Internal server error', type: 'internal_server_error', code: '007', }], }) }) }) describe('with custom made error', () => { const error = { type: 'fake_error', statusCode: 418, message: 'I\'m a teapot', code: '007', stack: 'StackTrace', } const req = { id: 'request_id' } const res = { locals: {}, } const next = () => {} errorHandler(error, req, res, next) test('should include standard error payload on `res.locals`', () => { expect(res.locals.payload).toMatchObject({ type: 'error', statusCode: 418, data: [{ message: 'I\'m a teapot', type: 'fake_error', code: '007', }], }) }) }) describe('with validation error', () => { const error = { type: 'validation', statusCode: 400, fields: [{ type: 'invalid_field', message: 'This field is invalid', field: 'fake_field', }], stack: 'StackTrace', } const req = { id: 'request_id' } const res = { locals: {}, } const next = () => {} errorHandler(error, req, res, next) test('should include standard error payload on `res.locals`', () => { expect(res.locals.payload).toMatchObject({ type: 'error', statusCode: 400, data: [{ message: 'This field is invalid', type: 'invalid_field', field: 'fake_field', }], }) }) }) })
hails/tane
tests/unit/middlewares/error.test.js
JavaScript
gpl-3.0
2,113
<?php echo file_get_contents(HERE."install".DS."install-header.html"); if (URI == "install") { inc("install".DS."install"); } else { inc("install".DS."must-install"); } ?>
mkg20001/website-cms
sys/install/index.php
PHP
gpl-3.0
174
package com.mycompany.control; import com.mycompany.entidades.Demanda; import com.mycompany.control.util.JsfUtil; import com.mycompany.control.util.PaginationHelper; import com.mycompany.facade.DemandaFacade; import java.io.Serializable; import java.util.ResourceBundle; import javax.ejb.EJB; import javax.inject.Named; import javax.enterprise.context.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; @Named("demandaController") @SessionScoped public class DemandaController implements Serializable { private Demanda current; private DataModel items = null; @EJB private com.mycompany.facade.DemandaFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; public DemandaController() { } public Demanda getSelected() { if (current == null) { current = new Demanda(); selectedItemIndex = -1; } return current; } private DemandaFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { pagination = new PaginationHelper(10) { @Override public int getItemsCount() { return getFacade().count(); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()})); } }; } return pagination; } public String prepareList() { recreateModel(); return "List"; } public String prepareView() { current = (Demanda) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Demanda(); selectedItemIndex = -1; return "Create"; } public String create() { try { getFacade().create(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("DemandaCreated")); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String prepareEdit() { current = (Demanda) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "Edit"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("DemandaUpdated")); return "View"; } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); return null; } } public String destroy() { current = (Demanda) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreatePagination(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("DemandaDeleted")); } catch (Exception e) { JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } private void recreatePagination() { pagination = null; } public String next() { getPagination().nextPage(); recreateModel(); return "List"; } public String previous() { getPagination().previousPage(); recreateModel(); return "List"; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } public Demanda getDemanda(java.lang.Integer id) { return ejbFacade.find(id); } @FacesConverter(forClass = Demanda.class) public static class DemandaControllerConverter implements Converter { @Override public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } DemandaController controller = (DemandaController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "demandaController"); return controller.getDemanda(getKey(value)); } java.lang.Integer getKey(String value) { java.lang.Integer key; key = Integer.valueOf(value); return key; } String getStringKey(java.lang.Integer value) { StringBuilder sb = new StringBuilder(); sb.append(value); return sb.toString(); } @Override public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Demanda) { Demanda o = (Demanda) object; return getStringKey(o.getIdDemanda()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Demanda.class.getName()); } } } }
OscarMiticanoy/NuestraPLaza-java
NuestraPlaza/src/main/java/com/mycompany/control/DemandaController.java
Java
gpl-3.0
7,210
/********************* * status_screen.cpp * *********************/ /**************************************************************************** * Written By Mark Pelletier 2017 - Aleph Objects, Inc. * * Written By Marcio Teixeira 2018 - Aleph Objects, Inc. * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * To view a copy of the GNU General Public License, go to the following * * location: <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "../config.h" #if ENABLED(TOUCH_UI_FTDI_EVE) && DISABLED(TOUCH_UI_LULZBOT_BIO) && DISABLED(TOUCH_UI_COCOA_PRESS) #include "screens.h" #include "screen_data.h" #include "../archim2-flash/flash_storage.h" using namespace FTDI; using namespace Theme; #ifdef TOUCH_UI_PORTRAIT #define GRID_ROWS 8 #else #define GRID_ROWS 8 #endif void StatusScreen::draw_axis_position(draw_mode_t what) { CommandProcessor cmd; #define GRID_COLS 3 if (what & BACKGROUND) { cmd.tag(6) #ifdef TOUCH_UI_PORTRAIT .fgcolor(Theme::axis_label) .font(Theme::font_large) .button( BTN_POS(1,5), BTN_SIZE(2,1), F(""), OPT_FLAT) .button( BTN_POS(1,6), BTN_SIZE(2,1), F(""), OPT_FLAT) .button( BTN_POS(1,7), BTN_SIZE(2,1), F(""), OPT_FLAT) .font(Theme::font_small) .text ( BTN_POS(1,5), BTN_SIZE(1,1), GET_TEXT_F(MSG_AXIS_X)) .text ( BTN_POS(1,6), BTN_SIZE(1,1), GET_TEXT_F(MSG_AXIS_Y)) .text ( BTN_POS(1,7), BTN_SIZE(1,1), GET_TEXT_F(MSG_AXIS_Z)) .font(Theme::font_medium) .fgcolor(Theme::x_axis) .button( BTN_POS(2,5), BTN_SIZE(2,1), F(""), OPT_FLAT) .fgcolor(Theme::y_axis) .button( BTN_POS(2,6), BTN_SIZE(2,1), F(""), OPT_FLAT) .fgcolor(Theme::z_axis) .button( BTN_POS(2,7), BTN_SIZE(2,1), F(""), OPT_FLAT); #else .fgcolor(Theme::axis_label) .font(Theme::font_large) .button( BTN_POS(1,5), BTN_SIZE(1,2), F(""), OPT_FLAT) .button( BTN_POS(2,5), BTN_SIZE(1,2), F(""), OPT_FLAT) .button( BTN_POS(3,5), BTN_SIZE(1,2), F(""), OPT_FLAT) .font(Theme::font_small) .text ( BTN_POS(1,5), BTN_SIZE(1,1), GET_TEXT_F(MSG_AXIS_X)) .text ( BTN_POS(2,5), BTN_SIZE(1,1), GET_TEXT_F(MSG_AXIS_Y)) .text ( BTN_POS(3,5), BTN_SIZE(1,1), GET_TEXT_F(MSG_AXIS_Z)) .font(Theme::font_medium) .fgcolor(Theme::x_axis) .button( BTN_POS(1,6), BTN_SIZE(1,1), F(""), OPT_FLAT) .fgcolor(Theme::y_axis) .button( BTN_POS(2,6), BTN_SIZE(1,1), F(""), OPT_FLAT) .fgcolor(Theme::z_axis) .button( BTN_POS(3,6), BTN_SIZE(1,1), F(""), OPT_FLAT); #endif } if (what & FOREGROUND) { using namespace ExtUI; char x_str[15]; char y_str[15]; char z_str[15]; if (isAxisPositionKnown(X)) format_position(x_str, getAxisPosition_mm(X)); else strcpy_P(x_str, PSTR("?")); if (isAxisPositionKnown(Y)) format_position(y_str, getAxisPosition_mm(Y)); else strcpy_P(y_str, PSTR("?")); if (isAxisPositionKnown(Z)) format_position(z_str, getAxisPosition_mm(Z)); else strcpy_P(z_str, PSTR("?")); cmd.tag(6).font(Theme::font_medium) #ifdef TOUCH_UI_PORTRAIT .text ( BTN_POS(2,5), BTN_SIZE(2,1), x_str) .text ( BTN_POS(2,6), BTN_SIZE(2,1), y_str) .text ( BTN_POS(2,7), BTN_SIZE(2,1), z_str); #else .text ( BTN_POS(1,6), BTN_SIZE(1,1), x_str) .text ( BTN_POS(2,6), BTN_SIZE(1,1), y_str) .text ( BTN_POS(3,6), BTN_SIZE(1,1), z_str); #endif } #undef GRID_COLS } #ifdef TOUCH_UI_PORTRAIT #define GRID_COLS 8 #else #define GRID_COLS 12 #endif void StatusScreen::draw_temperature(draw_mode_t what) { using namespace Theme; CommandProcessor cmd; if (what & BACKGROUND) { cmd.font(Theme::font_small) #ifdef TOUCH_UI_PORTRAIT .tag(5) .fgcolor(temp) .button( BTN_POS(1,1), BTN_SIZE(4,2), F(""), OPT_FLAT) .button( BTN_POS(1,1), BTN_SIZE(8,1), F(""), OPT_FLAT) .fgcolor(fan_speed) .button( BTN_POS(5,2), BTN_SIZE(4,1), F(""), OPT_FLAT) .tag(0) .fgcolor(progress) .button( BTN_POS(1,3), BTN_SIZE(4,1), F(""), OPT_FLAT) .button( BTN_POS(5,3), BTN_SIZE(4,1), F(""), OPT_FLAT); #else .tag(5) .fgcolor(temp) .button( BTN_POS(1,1), BTN_SIZE(4,2), F(""), OPT_FLAT) .button( BTN_POS(1,1), BTN_SIZE(8,1), F(""), OPT_FLAT) .fgcolor(fan_speed) .button( BTN_POS(5,2), BTN_SIZE(4,1), F(""), OPT_FLAT) .tag(0) .fgcolor(progress) .button( BTN_POS(9,1), BTN_SIZE(4,1), F(""), OPT_FLAT) .button( BTN_POS(9,2), BTN_SIZE(4,1), F(""), OPT_FLAT); #endif // Draw Extruder Bitmap on Extruder Temperature Button cmd.tag(5) .cmd(BITMAP_SOURCE(Extruder_Icon_Info)) .cmd(BITMAP_LAYOUT(Extruder_Icon_Info)) .cmd(BITMAP_SIZE (Extruder_Icon_Info)) .icon (BTN_POS(1,1), BTN_SIZE(1,1), Extruder_Icon_Info, icon_scale) .icon (BTN_POS(5,1), BTN_SIZE(1,1), Extruder_Icon_Info, icon_scale); // Draw Bed Heat Bitmap on Bed Heat Button cmd.cmd(BITMAP_SOURCE(Bed_Heat_Icon_Info)) .cmd(BITMAP_LAYOUT(Bed_Heat_Icon_Info)) .cmd(BITMAP_SIZE (Bed_Heat_Icon_Info)) .icon (BTN_POS(1,2), BTN_SIZE(1,1), Bed_Heat_Icon_Info, icon_scale); // Draw Fan Percent Bitmap on Bed Heat Button cmd.cmd(BITMAP_SOURCE(Fan_Icon_Info)) .cmd(BITMAP_LAYOUT(Fan_Icon_Info)) .cmd(BITMAP_SIZE (Fan_Icon_Info)) .icon (BTN_POS(5,2), BTN_SIZE(1,1), Fan_Icon_Info, icon_scale); #ifdef TOUCH_UI_USE_UTF8 load_utf8_bitmaps(cmd); // Restore font bitmap handles #endif } if (what & FOREGROUND) { using namespace ExtUI; char e0_str[20]; char e1_str[20]; char bed_str[20]; char fan_str[20]; sprintf_P( fan_str, PSTR("%-3d %%"), int8_t(getActualFan_percent(FAN0)) ); if (isHeaterIdle(BED)) format_temp_and_idle(bed_str, getActualTemp_celsius(BED)); else format_temp_and_temp(bed_str, getActualTemp_celsius(BED), getTargetTemp_celsius(BED)); if (isHeaterIdle(H0)) format_temp_and_idle(e0_str, getActualTemp_celsius(H0)); else format_temp_and_temp(e0_str, getActualTemp_celsius(H0), getTargetTemp_celsius(H0)); #if EXTRUDERS == 2 if (isHeaterIdle(H1)) format_temp_and_idle(e1_str, getActualTemp_celsius(H1)); else format_temp_and_temp(e1_str, getActualTemp_celsius(H1), getTargetTemp_celsius(H1)); #else strcpy_P( e1_str, PSTR("-") ); #endif cmd.tag(5) .font(font_medium) .text(BTN_POS(2,1), BTN_SIZE(3,1), e0_str) .text(BTN_POS(6,1), BTN_SIZE(3,1), e1_str) .text(BTN_POS(2,2), BTN_SIZE(3,1), bed_str) .text(BTN_POS(6,2), BTN_SIZE(3,1), fan_str); } } void StatusScreen::draw_progress(draw_mode_t what) { using namespace ExtUI; using namespace Theme; CommandProcessor cmd; if (what & BACKGROUND) { cmd.tag(0).font(font_medium) #ifdef TOUCH_UI_PORTRAIT .fgcolor(progress) .button(BTN_POS(1,3), BTN_SIZE(4,1), F(""), OPT_FLAT) .button(BTN_POS(5,3), BTN_SIZE(4,1), F(""), OPT_FLAT); #else .fgcolor(progress) .button(BTN_POS(9,1), BTN_SIZE(4,1), F(""), OPT_FLAT) .button(BTN_POS(9,2), BTN_SIZE(4,1), F(""), OPT_FLAT); #endif } if (what & FOREGROUND) { const uint32_t elapsed = getProgress_seconds_elapsed(); const uint8_t hrs = elapsed/3600; const uint8_t min = (elapsed/60)%60; char time_str[10]; char progress_str[10]; sprintf_P(time_str, PSTR(" %02d : %02d"), hrs, min); sprintf_P(progress_str, PSTR("%-3d %%"), getProgress_percent() ); cmd.font(font_medium) #ifdef TOUCH_UI_PORTRAIT .tag(0).text(BTN_POS(1,3), BTN_SIZE(4,1), time_str) .text(BTN_POS(5,3), BTN_SIZE(4,1), progress_str); #else .tag(0).text(BTN_POS(9,1), BTN_SIZE(4,1), time_str) .text(BTN_POS(9,2), BTN_SIZE(4,1), progress_str); #endif } } #undef GRID_COLS void StatusScreen::draw_interaction_buttons(draw_mode_t what) { #define GRID_COLS 4 if (what & FOREGROUND) { using namespace ExtUI; const bool has_media = isMediaInserted() && !isPrintingFromMedia(); CommandProcessor cmd; cmd.colors(normal_btn) .font(Theme::font_medium) .enabled(has_media) .colors(has_media ? action_btn : normal_btn) .tag(3).button( #ifdef TOUCH_UI_PORTRAIT BTN_POS(1,8), BTN_SIZE(2,1), #else BTN_POS(1,7), BTN_SIZE(2,2), #endif isPrintingFromMedia() ? GET_TEXT_F(MSG_PRINTING) : GET_TEXT_F(MSG_BUTTON_MEDIA) ).colors(!has_media ? action_btn : normal_btn) #ifdef TOUCH_UI_PORTRAIT .tag(4).button( BTN_POS(3,8), BTN_SIZE(2,1), GET_TEXT_F(MSG_BUTTON_MENU)); #else .tag(4).button( BTN_POS(3,7), BTN_SIZE(2,2), GET_TEXT_F(MSG_BUTTON_MENU)); #endif } #undef GRID_COLS } void StatusScreen::draw_status_message(draw_mode_t what, const char* message) { #define GRID_COLS 1 if (what & BACKGROUND) { CommandProcessor cmd; cmd.fgcolor(Theme::status_msg) .tag(0) #ifdef TOUCH_UI_PORTRAIT .button( BTN_POS(1,4), BTN_SIZE(1,1), F(""), OPT_FLAT); #else .button( BTN_POS(1,3), BTN_SIZE(1,2), F(""), OPT_FLAT); #endif draw_text_box(cmd, #ifdef TOUCH_UI_PORTRAIT BTN_POS(1,4), BTN_SIZE(1,1), #else BTN_POS(1,3), BTN_SIZE(1,2), #endif message, OPT_CENTER, font_large); } #undef GRID_COLS } void StatusScreen::setStatusMessage(progmem_str message) { char buff[strlen_P((const char * const)message)+1]; strcpy_P(buff, (const char * const) message); setStatusMessage((const char *) buff); } void StatusScreen::setStatusMessage(const char* message) { CommandProcessor cmd; cmd.cmd(CMD_DLSTART) .cmd(CLEAR_COLOR_RGB(Theme::bg_color)) .cmd(CLEAR(true,true,true)); draw_temperature(BACKGROUND); draw_progress(BACKGROUND); draw_axis_position(BACKGROUND); draw_status_message(BACKGROUND, message); draw_interaction_buttons(BACKGROUND); storeBackground(); #if ENABLED(TOUCH_UI_DEBUG) SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("New status message: ", message); #endif if (AT_SCREEN(StatusScreen)) { current_screen.onRefresh(); } } void StatusScreen::loadBitmaps() { // Load the bitmaps for the status screen using namespace Theme; constexpr uint32_t base = ftdi_memory_map::RAM_G; CLCD::mem_write_pgm(base + TD_Icon_Info.RAMG_offset, TD_Icon, sizeof(TD_Icon)); CLCD::mem_write_pgm(base + Extruder_Icon_Info.RAMG_offset, Extruder_Icon, sizeof(Extruder_Icon)); CLCD::mem_write_pgm(base + Bed_Heat_Icon_Info.RAMG_offset, Bed_Heat_Icon, sizeof(Bed_Heat_Icon)); CLCD::mem_write_pgm(base + Fan_Icon_Info.RAMG_offset, Fan_Icon, sizeof(Fan_Icon)); // Load fonts for internationalization #ifdef TOUCH_UI_USE_UTF8 load_utf8_data(base + UTF8_FONT_OFFSET); #endif } void StatusScreen::onStartup() { UIFlashStorage::initialize(); } void StatusScreen::onRedraw(draw_mode_t what) { if (what & FOREGROUND) { draw_temperature(FOREGROUND); draw_progress(FOREGROUND); draw_axis_position(FOREGROUND); draw_interaction_buttons(FOREGROUND); } } void StatusScreen::onEntry() { onRefresh(); } void StatusScreen::onIdle() { if (refresh_timer.elapsed(STATUS_UPDATE_INTERVAL)) { onRefresh(); refresh_timer.start(); } BaseScreen::onIdle(); } bool StatusScreen::onTouchEnd(uint8_t tag) { using namespace ExtUI; switch (tag) { case 3: GOTO_SCREEN(FilesScreen); break; case 4: if (isPrinting()) { GOTO_SCREEN(TuneMenu); } else { GOTO_SCREEN(MainMenu); } break; case 5: GOTO_SCREEN(TemperatureScreen); break; case 6: if (!isPrinting()) { GOTO_SCREEN(MoveAxisScreen); } break; default: return true; } // If a passcode is enabled, the LockScreen will prevent the // user from proceeding. LockScreen::check_passcode(); return true; } #endif // TOUCH_UI_FTDI_EVE
petrzjunior/Marlin
Marlin/src/lcd/extensible_ui/lib/ftdi_eve_touch_ui/screens/status_screen.cpp
C++
gpl-3.0
13,488
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.internal.dsl; import com.android.annotations.NonNull; import com.google.common.collect.Sets; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /** * DSL object for configuring per-language splits options. * <p> * <p>See <a href="http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits">APK Splits</a>. */ public class LanguageSplitOptions { private boolean enable = false; private boolean auto = false; private Set<String> include; /** * Collection of include patterns. */ public Set<String> getInclude() { return include; } public void setInclude(@NonNull List<String> list) { include = Sets.newHashSet(list); } /** * Adds an include pattern. */ public void include(@NonNull String... includes) { if (include == null) { include = Sets.newHashSet(includes); return; } include.addAll(Arrays.asList(includes)); } @NonNull public Set<String> getApplicationFilters() { return include == null || !enable ? new HashSet<String>() : include; } /** * Returns true if splits should be generated for languages. */ public boolean isEnable() { return enable; } /** * enables or disables splits for language */ public void setEnable(boolean enable) { this.enable = enable; } /** * Returns whether to use the automatic discovery mechanism for supported languages (true) or * the manual include list (false). * * @return true for automatic, false for manual mode. */ public boolean isAuto() { return auto; } /** * Sets whether the build system should determine the splits based on the "language-*" folders * in the resources. If the auto mode is set to true, the include list will be ignored. * * @param auto true to automatically set the splits list based on the folders presence, false * to use the include list. */ public void setAuto(boolean auto) { this.auto = auto; } }
tranleduy2000/javaide
aosp/gradle/src/main/java/com/android/build/gradle/internal/dsl/LanguageSplitOptions.java
Java
gpl-3.0
2,810
using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UIKeyBinding : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int IsBound_s(IntPtr l) { try { UnityEngine.KeyCode a1; checkEnum(l,1,out a1); var ret=UIKeyBinding.IsBound(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetKeyCode_s(IntPtr l) { try { System.String a1; checkType(l,1,out a1); UnityEngine.KeyCode a2; UIKeyBinding.Modifier a3; var ret=UIKeyBinding.GetKeyCode(a1,out a2,out a3); pushValue(l,true); pushValue(l,ret); pushValue(l,a2); pushValue(l,a3); return 4; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_keyCode(IntPtr l) { try { UIKeyBinding self=(UIKeyBinding)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.keyCode); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_keyCode(IntPtr l) { try { UIKeyBinding self=(UIKeyBinding)checkSelf(l); UnityEngine.KeyCode v; checkEnum(l,2,out v); self.keyCode=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_modifier(IntPtr l) { try { UIKeyBinding self=(UIKeyBinding)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.modifier); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_modifier(IntPtr l) { try { UIKeyBinding self=(UIKeyBinding)checkSelf(l); UIKeyBinding.Modifier v; checkEnum(l,2,out v); self.modifier=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_action(IntPtr l) { try { UIKeyBinding self=(UIKeyBinding)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.action); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_action(IntPtr l) { try { UIKeyBinding self=(UIKeyBinding)checkSelf(l); UIKeyBinding.Action v; checkEnum(l,2,out v); self.action=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_captionText(IntPtr l) { try { UIKeyBinding self=(UIKeyBinding)checkSelf(l); pushValue(l,true); pushValue(l,self.captionText); return 2; } catch(Exception e) { return error(l,e); } } static public void reg(IntPtr l) { getTypeTable(l,"UIKeyBinding"); addMember(l,IsBound_s); addMember(l,GetKeyCode_s); addMember(l,"keyCode",get_keyCode,set_keyCode,true); addMember(l,"modifier",get_modifier,set_modifier,true); addMember(l,"action",get_action,set_action,true); addMember(l,"captionText",get_captionText,null,true); createTypeMetatable(l,null, typeof(UIKeyBinding),typeof(UnityEngine.MonoBehaviour)); } }
yongkangchen/poker-client
Assets/Runtime/Slua/LuaObject/Dll/Lua_UIKeyBinding.cs
C#
gpl-3.0
3,361
using System; using System.Collections.Generic; using Server; using Server.Events; using Server.Buff.Icons; using Server.Items; namespace Server.Spells.Bard { public class Inspire : AreaSpellsong { public static void Initialize() { EventSink.BeforeDamage += new BeforeDamageEventHandler( EventSink_BeforeDamage ); } private static void EventSink_BeforeDamage( BeforeDamageEventArgs e ) { if ( e.From == null ) return; Inspire spellsong = Spellsong.GetEffectSpellsong<Inspire>( e.From ); if ( spellsong != null ) e.Amount = (int) ( e.Amount * ( 100 + spellsong.DamageModifier ) / 100 ); } private static SpellInfo m_Info = new SpellInfo( "Inspire", "Uus Por", -1, 9002 ); public override BardMastery RequiredMastery { get { return BardMastery.Provocation; } } public override TimeSpan CastDelayBase { get { return TimeSpan.FromSeconds( 1.25 ); } } public override int RequiredMana { get { return 16; } } public override int UpkeepCost { get { return 5; } } public override BuffIcon BuffIcon { get { return BuffIcon.Inspire; } } // You feel inspired by the bard's spellsong. public override int StartEffectMessage { get { return 1115736; } } public Inspire( Mobile caster, Item scroll ) : base( caster, scroll, m_Info ) { } public int DamageModifier { get; private set; } protected override void AddMods(/*ISet<AosAttribute> mods,*/ ISet<StatMod> statMods) { int music, peace, provo, disco; GetSkillBonus( out music, out peace, out provo, out disco ); int weaponDamage = 10 + 5 * ( music + provo ) + 3 * ( peace + disco ); //mods.Add( new AttributeMod(AosAttribute.WeaponDamage, weaponDamage)); int spellDamage = 4 + 2 * ( music + provo ) + peace + disco; //mods.Add( new AttributeMod( MagicalAttribute.SpellDamage, spellDamage ) ); int attackChance = 4 + 2 * ( music + provo ) + peace + disco; //mods.Add( new AttributeMod( MagicalAttribute.AttackChance, attackChance ) ); int damageModifier = Math.Max( 1, music * provo + Math.Max( music, provo ) + ( disco + peace ) / 2 ); this.DamageModifier = damageModifier; this.BuffInfo = new BuffInfo( this.BuffIcon, 1115612, 1151951, String.Format( "{0}\t{1}\t{2}\t{3}", weaponDamage, spellDamage, attackChance, DamageModifier ), false ); } } }
GenerationOfWorlds/GOW
Scripts/Core/Stygian Abyss/Magic/Bard Masteries/Inspire.cs
C#
gpl-3.0
2,339
import DS from 'ember-data'; export default DS.LSAdapter.extend({ namespace: 'bateria_namespace' });
hugoruscitti/bateria
app/adapters/application.js
JavaScript
gpl-3.0
105
'use strict' const config = { development: './env/dev', production: './env/prod', test: './env/test' } const { NODE_ENV = 'development' } = process.env module.exports = require(config[NODE_ENV])
calebgregory/node-testing-with-mocha-chai
config/index.js
JavaScript
gpl-3.0
204
/* * QuarkPlayer, a Phonon media player * Copyright (C) 2008-2011 Tanguy Krotoff <tkrotoff@gmail.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, see <http://www.gnu.org/licenses/>. */ #include "WebBrowser.h" #include "TkTextBrowser.h" #include "WebBrowserLogger.h" #include <TkUtil/LanguageChangeEventFilter.h> #ifdef WEBKIT #include <QtWebKit/QtWebKit> #endif //WEBKIT #include <QtGui/QtGui> #include <QtCore/QCoreApplication> #include <QtCore/QUrl> /** Detects if _homeHtml should be used or not inside WebBrowser::home(). */ static const char * HOME_HTML_INVALID = "INVALID"; WebBrowser::WebBrowser(QWidget * parent) : QWidget(parent) { populateActionCollection(); QVBoxLayout * layout = new QVBoxLayout(); setLayout(layout); layout->setMargin(0); layout->setSpacing(0); _toolBar = new QToolBar(); _toolBar->setIconSize(QSize(16, 16)); _toolBar->addAction(_actions["WebBrowser.Backward"]); _toolBar->addAction(_actions["WebBrowser.Forward"]); _toolBar->addAction(_actions["WebBrowser.Reload"]); _toolBar->addAction(_actions["WebBrowser.Stop"]); _toolBar->addAction(_actions["WebBrowser.Home"]); layout->addWidget(_toolBar); _urlLineEdit = new QLineEdit(); _toolBar->addWidget(_urlLineEdit); //Do not use QLineEdit::editingFinished() since it will trigger go() //even with QLineEdit::setText() connect(_urlLineEdit, SIGNAL(returnPressed()), SLOT(go())); _toolBar->addAction(_actions["WebBrowser.Go"]); connect(_actions["WebBrowser.Go"], SIGNAL(triggered()), SLOT(go())); _toolBar->addAction(_actions["WebBrowser.OpenBrowser"]); connect(_actions["WebBrowser.OpenBrowser"], SIGNAL(triggered()), SLOT(openExternalWebBrowser())); #ifdef WEBKIT _webView = new QWebView(); layout->addWidget(_webView); connect(_webView, SIGNAL(urlChanged(const QUrl &)), SLOT(urlChanged(const QUrl &))); connect(_webView, SIGNAL(urlChanged(const QUrl &)), SLOT(historyChanged())); connect(_actions["WebBrowser.Backward"], SIGNAL(triggered()), _webView, SLOT(back())); connect(_actions["WebBrowser.Forward"], SIGNAL(triggered()), _webView, SLOT(forward())); connect(_actions["WebBrowser.Reload"], SIGNAL(triggered()), _webView, SLOT(reload())); connect(_actions["WebBrowser.Home"], SIGNAL(triggered()), SLOT(home())); connect(_actions["WebBrowser.Stop"], SIGNAL(triggered()), _webView, SLOT(stop())); #else _textBrowser = new TkTextBrowser(); layout->addWidget(_textBrowser); connect(_textBrowser, SIGNAL(sourceChanged(const QUrl &)), SLOT(urlChanged(const QUrl &))); connect(_textBrowser, SIGNAL(historyChanged()), SLOT(historyChanged())); connect(_actions["WebBrowser.Backward"], SIGNAL(triggered()), _textBrowser, SLOT(backward())); connect(_actions["WebBrowser.Forward"], SIGNAL(triggered()), _textBrowser, SLOT(forward())); connect(_actions["WebBrowser.Reload"], SIGNAL(triggered()), _textBrowser, SLOT(reload())); connect(_actions["WebBrowser.Home"], SIGNAL(triggered()), SLOT(home())); //QTextBrowser cannot stops current rendering, multithreaded? //connect(_actions["WebBrowser.Stop"], SIGNAL(triggered()), _textBrowser, SLOT(stop())); _actions["WebBrowser.Stop"]->setEnabled(false); #endif //WEBKIT //Initializes the backward and forward QAction setBackActionToolTip(); setForwardActionToolTip(); RETRANSLATE(this); retranslate(); } WebBrowser::~WebBrowser() { } void WebBrowser::populateActionCollection() { QCoreApplication * app = QApplication::instance(); Q_ASSERT(app); _actions.add("WebBrowser.Backward", new QAction(app)); _actions.add("WebBrowser.Forward", new QAction(app)); _actions.add("WebBrowser.Reload", new QAction(app)); _actions.add("WebBrowser.Stop", new QAction(app)); _actions.add("WebBrowser.Home", new QAction(app)); _actions.add("WebBrowser.Go", new QAction(app)); _actions.add("WebBrowser.OpenBrowser", new QAction(app)); } void WebBrowser::retranslate() { _actions["WebBrowser.Backward"]->setText(tr("Back")); _actions["WebBrowser.Backward"]->setIcon(QIcon::fromTheme("go-previous")); _actions["WebBrowser.Forward"]->setText(tr("Forward")); _actions["WebBrowser.Forward"]->setIcon(QIcon::fromTheme("go-next")); _actions["WebBrowser.Reload"]->setText(tr("Reload")); _actions["WebBrowser.Reload"]->setIcon(QIcon::fromTheme("view-refresh")); _actions["WebBrowser.Stop"]->setText(tr("Stop")); _actions["WebBrowser.Stop"]->setIcon(QIcon::fromTheme("process-stop")); _actions["WebBrowser.Home"]->setText(tr("Home")); _actions["WebBrowser.Home"]->setIcon(QIcon::fromTheme("go-home")); _actions["WebBrowser.Go"]->setText(tr("Go")); _actions["WebBrowser.Go"]->setIcon(QIcon::fromTheme("go-jump-locationbar")); _actions["WebBrowser.OpenBrowser"]->setText(tr("Open External Browser")); _actions["WebBrowser.OpenBrowser"]->setIcon(QIcon::fromTheme("internet-web-browser")); } void WebBrowser::setHtml(const QString & html) { if (_homeHtml.isEmpty()) { _homeHtml = html; } #ifdef WEBKIT _webView->setHtml(html); #else _textBrowser->setHtml(html); #endif //WEBKIT } void WebBrowser::setUrl(const QUrl & url) { if (_homeUrl.isEmpty()) { _homeUrl = url.toString(); _actions["WebBrowser.Home"]->setToolTip(_homeUrl); _homeHtml = HOME_HTML_INVALID; } #ifdef WEBKIT _webView->setUrl(url); #else _textBrowser->setSource(url); #endif //WEBKIT } void WebBrowser::setUrlLineEdit(const QString & url) { if (_homeUrl.isEmpty()) { _homeUrl = url; _actions["WebBrowser.Home"]->setToolTip(_homeUrl); } _urlLineEdit->setText(url); } void WebBrowser::clear() { setUrl(QString()); setHtml(QString()); } void WebBrowser::go() { QString url(_urlLineEdit->text()); /*Don't do that: url line edit can contain a simple text that is not a URL if (!url.contains("http://") && !url.contains("file://") && !url.contains("://")) { url.prepend("http://"); }*/ setUrl(url); } void WebBrowser::setBackActionToolTip() { QString title; #ifdef WEBKIT title = _webView->history()->backItem().title(); #else title = _textBrowser->historyTitle(-1); #endif //WEBKIT _actions["WebBrowser.Backward"]->setEnabled(!title.isEmpty()); _actions["WebBrowser.Backward"]->setToolTip(title); } void WebBrowser::setForwardActionToolTip() { QString title; #ifdef WEBKIT title = _webView->history()->forwardItem().title(); #else title = _textBrowser->historyTitle(+1); #endif //WEBKIT _actions["WebBrowser.Forward"]->setEnabled(!title.isEmpty()); _actions["WebBrowser.Forward"]->setToolTip(title); } void WebBrowser::urlChanged(const QUrl & url) { _urlLineEdit->setText(url.toString()); } void WebBrowser::historyChanged() { setBackActionToolTip(); setForwardActionToolTip(); } void WebBrowser::openExternalWebBrowser() { QDesktopServices::openUrl(QUrl::fromPercentEncoding(_urlLineEdit->text().toAscii())); } void WebBrowser::home() { if (_homeHtml == HOME_HTML_INVALID) { setUrl(_homeUrl); } else { setUrlLineEdit(_homeUrl); setHtml(_homeHtml); } }
tkrotoff/QuarkPlayer
libs/WebBrowser/WebBrowser.cpp
C++
gpl-3.0
7,469
/* Copyright (C) 2016 PencilBlue, LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ //dependencies var url = require('url'); var https = require('https'); module.exports = function SlideShareMediaRendererModule(pb) { //pb dependencies var util = pb.util; var BaseMediaRenderer = pb.media.renderers.BaseMediaRenderer; /** * * @class SlideShareMediaRenderer * @constructor */ function SlideShareMediaRenderer(){} /** * The media type supported by the provider * @private * @static * @property TYPE * @type {String} */ var TYPE = 'slideshare'; /** * Provides the styles used by each type of view * @private * @static * @property STYLES * @type {Object} */ var STYLES = Object.freeze({ view: { width: "100%" }, editor: { width: "427px", height: "356px" }, post: { width: "427px", height: "356px" } }); /** * Retrieves the supported extension types for the renderer. * @static * @method getSupportedExtensions * @return {Array} */ SlideShareMediaRenderer.getSupportedExtensions = function() { return []; }; /** * Retrieves the style for the specified type of view * @static * @method getStyle * @param {String} viewType The view type calling for a styling * @return {Object} a hash of style properties */ SlideShareMediaRenderer.getStyle = function(viewType) { return STYLES[viewType] || STYLES.view; }; /** * Retrieves the supported media types as a hash. * @static * @method getSupportedTypes * @return {Object} */ SlideShareMediaRenderer.getSupportedTypes = function() { var types = {}; types[TYPE] = true; return types; }; /** * Retrieves the name of the renderer. * @static * @method getName * @return {String} */ SlideShareMediaRenderer.getName = function() { return 'SlideShareMediaRenderer'; }; /** * Determines if the URL to a media object is supported by this renderer * @static * @method isSupported * @param {String} urlStr * @return {Boolean} TRUE if the URL is supported by the renderer, FALSE if not */ SlideShareMediaRenderer.isSupported = function(urlStr) { var details = url.parse(urlStr, true, true); return SlideShareMediaRenderer.isFullSite(details); }; /** * Indicates if the passed URL to a media resource points to the main website * that provides the media represented by this media renderer * @static * @method isFullSite * @param {Object|String} parsedUrl The URL string or URL object * @return {Boolean} TRUE if URL points to the main domain and media resource, FALSE if not */ SlideShareMediaRenderer.isFullSite = function(parsedUrl) { if (util.isString(parsedUrl)) { parsedUrl = url.parse(urlStr, true, true); } return parsedUrl.host && (parsedUrl.host.indexOf('slideshare.com') >= 0 || parsedUrl.host.indexOf('slideshare.net') >= 0) && parsedUrl.pathname.indexOf('/') >= 0; }; /** * Gets the specific type of the media resource represented by the provided URL * @static * @method getType * @param {String} urlStr * @return {String} */ SlideShareMediaRenderer.getType = function(urlStr) { return SlideShareMediaRenderer.isSupported(urlStr) ? TYPE : null; } /** * Retrieves the Font Awesome icon class. It is safe to assume that the type * provided will be a supported type by the renderer. * @static * @method getIcon * @param {String} type * @return {String} */ SlideShareMediaRenderer.getIcon = function(type) { return 'list-alt'; }; /** * Renders the media resource via the raw URL to the resource * @static * @method renderByUrl * @param {String} urlStr * @param {Object} [options] * @param {Object} [options.attrs] A hash of all attributes (excluding style) * that will be applied to the element generated by the rendering * @param {Object} [options.style] A hash of all attributes that will be * applied to the style of the element generated by the rendering. * @param {Function} cb A callback where the first parameter is an Error if * occurred and the second is the rendering of the media resource as a HTML * formatted string */ SlideShareMediaRenderer.renderByUrl = function(urlStr, options, cb) { SlideShareMediaRenderer.getMediaId(urlStr, function(err, mediaId) { if (util.isError(err)) { return cb(err); } SlideShareMediaRenderer.render({location: mediaId}, options, cb); }); }; /** * Renders the media resource via the media descriptor object. It is only * guaranteed that the "location" property will be available at the time of * rendering. * @static * @method render * @param {Object} media * @param {String} media.location The unique resource identifier (only to the * media type) for the media resource * @param {Object} [options] * @param {Object} [options.attrs] A hash of all attributes (excluding style) * that will be applied to the element generated by the rendering * @param {Object} [options.style] A hash of all attributes that will be * applied to the style of the element generated by the rendering. * @param {Function} cb A callback where the first parameter is an Error if * occurred and the second is the rendering of the media resource as a HTML * formatted string */ SlideShareMediaRenderer.render = function(media, options, cb) { if (util.isFunction(options)) { cb = options; options = {}; } var embedUrl = SlideShareMediaRenderer.getEmbedUrl(media.location); cb(null, BaseMediaRenderer.renderIFrameEmbed(embedUrl, options.attrs, options.style)); }; /** * Retrieves the source URI that will be used when generating the rendering * @static * @method getEmbedUrl * @param {String} mediaId The unique (only to the type) media identifier * @return {String} A properly formatted URI string that points to the resource * represented by the media Id */ SlideShareMediaRenderer.getEmbedUrl = function(mediaId) { return '//www.slideshare.net/slideshow/embed_code/' + mediaId; }; /** * Retrieves the unique identifier from the URL provided. The value should * distinguish the media resource from the others of this type and provide * insight on how to generate the embed URL. * @static * @method getMediaId */ SlideShareMediaRenderer.getMediaId = function(urlStr, cb) { SlideShareMediaRenderer.getDetails(urlStr, function(err, details) { if (util.isError(err)) { return cb(err); } cb(null, details.slideshow_id); }); }; /** * Retrieves any meta data about the media represented by the URL. * @static * @method getMeta * @param {String} urlStr * @param {Boolean} isFile indicates if the URL points to a file that was * uploaded to the PB server * @param {Function} cb A callback that provides an Error if occurred and an * Object if meta was collected. NULL if no meta was collected */ SlideShareMediaRenderer.getMeta = function(urlStr, isFile, cb) { var details = url.parse(urlStr, true, true); var meta = details.query; cb(null, meta); }; /** * Retrieves a URI to a thumbnail for the media resource * @static * @method getThumbnail * @param {String} urlStr * @param {Function} cb A callback where the first parameter is an Error if * occurred and the second is the URI string to the thumbnail. Empty string or * NULL if no thumbnail is available */ SlideShareMediaRenderer.getThumbnail = function(urlStr, cb) { SlideShareMediaRenderer.getDetails(urlStr, function(err, details) { if (util.isError(err)) { return cb(err); } cb(null, details.thumbnail); }); }; /** * Retrieves the native URL for the media resource. This can be the raw page * where it was found or a direct link to the content. * @static * @method getNativeUrl */ SlideShareMediaRenderer.getNativeUrl = function(media) { return 'http://slideshare.net/slideshow/embed_code/' + media.location; }; /** * Retrieves details about the media resource via SlideShare's API because they * are inconsistent about how they reference things. * @static * @method getDetails * @param {String} urlStr * @param {Function} cb Provides two parameters. First is an Error if occurred * and the second is an object with the data returned by the SlideShare API */ SlideShareMediaRenderer.getDetails = function(urlStr, cb) { var options = { host: 'www.slideshare.net', path: '/api/oembed/2?url=' + encodeURIComponent(urlStr) + '&format=jsonp&callback=?' }; var callback = function(response) { var str = ''; //another chunk of data has been recieved, so append it to `str` response.once('error', cb); response.on('data', function (chunk) { str += chunk; }); //the whole response has been recieved, so we just print it out here response.on('end', function () { try { var data = JSON.parse(str); cb(null, data); } catch(err) { cb(err); } }); }; https.request(options, callback).end(); }; //exports return SlideShareMediaRenderer; };
Whatsit2yaa/vast-tundra-84597
include/service/media/renderers/slideshare_media_renderer.js
JavaScript
gpl-3.0
10,832
package net.BukkitPE.block; import net.BukkitPE.item.Item; import net.BukkitPE.item.ItemTool; import net.BukkitPE.level.Level; import net.BukkitPE.math.AxisAlignedBB; import net.BukkitPE.math.Vector3; import net.BukkitPE.utils.BlockColor; /** * Created on 2015/12/2 by xtypr. * Package net.BukkitPE.block in project BukkitPE . */ public class BlockFarmland extends BlockTransparent { public BlockFarmland() { this(0); } public BlockFarmland(int meta) { super(meta); } @Override public String getName() { return "Farmland"; } @Override public int getId() { return FARMLAND; } @Override public double getResistance() { return 3; } @Override public double getHardness() { return 0.6; } @Override public int getToolType() { return ItemTool.TYPE_SHOVEL; } @Override protected AxisAlignedBB recalculateBoundingBox() { return new AxisAlignedBB( this.x, this.y, this.z, this.x + 1, this.y + 0.9375, this.z + 1 ); } @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_RANDOM) { boolean found = false; Vector3 v = new Vector3(); for (int x = (int) this.x - 1; x <= this.x + 1; x++) { for (int z = (int) this.z - 1; z <= this.z + 1; z++) { if (z == this.z && x == this.x) { continue; } Block block = this.level.getBlock(v.setComponents(x, this.y, z)); if (block instanceof BlockWater) { found = true; break; } } } Block block = this.level.getBlock(v.setComponents(x, y - 1, z)); if (found || block instanceof BlockWater) { return Level.BLOCK_UPDATE_RANDOM; } this.level.setBlock(this, new BlockDirt(), true, true); return Level.BLOCK_UPDATE_RANDOM; } return 0; } @Override public int[][] getDrops(Item item) { return new int[][]{ {Item.DIRT, 0, 1} }; } @Override public BlockColor getColor() { return BlockColor.DIRT_BLOCK_COLOR; } }
BukkitPE/BukkitPE
src/main/java/net/BukkitPE/block/BlockFarmland.java
Java
gpl-3.0
2,452
# -*- test-case-name: twisted.web.test.test_web -*- # Copyright (c) 2001-2009 Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.web.static}. """ import os, re, StringIO from zope.interface.verify import verifyObject from twisted.internet import abstract, interfaces from twisted.python.compat import set from twisted.python.runtime import platform from twisted.python.filepath import FilePath from twisted.python import log from twisted.trial.unittest import TestCase from twisted.web import static, http, script, resource from twisted.web.test.test_web import DummyRequest from twisted.web.test._util import _render class StaticFileTests(TestCase): """ Tests for the basic behavior of L{File}. """ def _render(self, resource, request): return _render(resource, request) def test_notFound(self): """ If a request is made which encounters a L{File} before a final segment which does not correspond to any file in the path the L{File} was created with, a not found response is sent. """ base = FilePath(self.mktemp()) base.makedirs() file = static.File(base.path) request = DummyRequest(['foobar']) child = resource.getChildForRequest(file, request) d = self._render(child, request) def cbRendered(ignored): self.assertEqual(request.responseCode, 404) d.addCallback(cbRendered) return d def test_emptyChild(self): """ The C{''} child of a L{File} which corresponds to a directory in the filesystem is a L{DirectoryLister}. """ base = FilePath(self.mktemp()) base.makedirs() file = static.File(base.path) request = DummyRequest(['']) child = resource.getChildForRequest(file, request) self.assertIsInstance(child, static.DirectoryLister) self.assertEqual(child.path, base.path) def test_securityViolationNotFound(self): """ If a request is made which encounters a L{File} before a final segment which cannot be looked up in the filesystem due to security considerations, a not found response is sent. """ base = FilePath(self.mktemp()) base.makedirs() file = static.File(base.path) request = DummyRequest(['..']) child = resource.getChildForRequest(file, request) d = self._render(child, request) def cbRendered(ignored): self.assertEqual(request.responseCode, 404) d.addCallback(cbRendered) return d def test_forbiddenResource(self): """ If the file in the filesystem which would satisfy a request cannot be read, L{File.render} sets the HTTP response code to I{FORBIDDEN}. """ base = FilePath(self.mktemp()) base.setContent('') # Make sure we can delete the file later. self.addCleanup(base.chmod, 0700) # Get rid of our own read permission. base.chmod(0) file = static.File(base.path) request = DummyRequest(['']) d = self._render(file, request) def cbRendered(ignored): self.assertEqual(request.responseCode, 403) d.addCallback(cbRendered) return d if platform.isWindows(): test_forbiddenResource.skip = "Cannot remove read permission on Windows" def test_indexNames(self): """ If a request is made which encounters a L{File} before a final empty segment, a file in the L{File} instance's C{indexNames} list which exists in the path the L{File} was created with is served as the response to the request. """ base = FilePath(self.mktemp()) base.makedirs() base.child("foo.bar").setContent("baz") file = static.File(base.path) file.indexNames = ['foo.bar'] request = DummyRequest(['']) child = resource.getChildForRequest(file, request) d = self._render(child, request) def cbRendered(ignored): self.assertEqual(''.join(request.written), 'baz') self.assertEqual(request.outgoingHeaders['content-length'], '3') d.addCallback(cbRendered) return d def test_staticFile(self): """ If a request is made which encounters a L{File} before a final segment which names a file in the path the L{File} was created with, that file is served as the response to the request. """ base = FilePath(self.mktemp()) base.makedirs() base.child("foo.bar").setContent("baz") file = static.File(base.path) request = DummyRequest(['foo.bar']) child = resource.getChildForRequest(file, request) d = self._render(child, request) def cbRendered(ignored): self.assertEqual(''.join(request.written), 'baz') self.assertEqual(request.outgoingHeaders['content-length'], '3') d.addCallback(cbRendered) return d def test_staticFileDeletedGetChild(self): """ A L{static.File} created for a directory which does not exist should return childNotFound from L{static.File.getChild}. """ staticFile = static.File(self.mktemp()) request = DummyRequest(['foo.bar']) child = staticFile.getChild("foo.bar", request) self.assertEquals(child, staticFile.childNotFound) def test_staticFileDeletedRender(self): """ A L{static.File} created for a file which does not exist should render its C{childNotFound} page. """ staticFile = static.File(self.mktemp()) request = DummyRequest(['foo.bar']) request2 = DummyRequest(['foo.bar']) d = self._render(staticFile, request) d2 = self._render(staticFile.childNotFound, request2) def cbRendered2(ignored): def cbRendered(ignored): self.assertEquals(''.join(request.written), ''.join(request2.written)) d.addCallback(cbRendered) return d d2.addCallback(cbRendered2) return d2 def test_processors(self): """ If a request is made which encounters a L{File} before a final segment which names a file with an extension which is in the L{File}'s C{processors} mapping, the processor associated with that extension is used to serve the response to the request. """ base = FilePath(self.mktemp()) base.makedirs() base.child("foo.bar").setContent( "from twisted.web.static import Data\n" "resource = Data('dynamic world','text/plain')\n") file = static.File(base.path) file.processors = {'.bar': script.ResourceScript} request = DummyRequest(["foo.bar"]) child = resource.getChildForRequest(file, request) d = self._render(child, request) def cbRendered(ignored): self.assertEqual(''.join(request.written), 'dynamic world') self.assertEqual(request.outgoingHeaders['content-length'], '13') d.addCallback(cbRendered) return d def test_ignoreExt(self): """ The list of ignored extensions can be set by passing a value to L{File.__init__} or by calling L{File.ignoreExt} later. """ file = static.File(".") self.assertEqual(file.ignoredExts, []) file.ignoreExt(".foo") file.ignoreExt(".bar") self.assertEqual(file.ignoredExts, [".foo", ".bar"]) file = static.File(".", ignoredExts=(".bar", ".baz")) self.assertEqual(file.ignoredExts, [".bar", ".baz"]) def test_ignoredExtensionsIgnored(self): """ A request for the I{base} child of a L{File} succeeds with a resource for the I{base<extension>} file in the path the L{File} was created with if such a file exists and the L{File} has been configured to ignore the I{<extension>} extension. """ base = FilePath(self.mktemp()) base.makedirs() base.child('foo.bar').setContent('baz') base.child('foo.quux').setContent('foobar') file = static.File(base.path, ignoredExts=(".bar",)) request = DummyRequest(["foo"]) child = resource.getChildForRequest(file, request) d = self._render(child, request) def cbRendered(ignored): self.assertEqual(''.join(request.written), 'baz') d.addCallback(cbRendered) return d def test_createPickleChild(self): """ L{static.File.createPickleChild} is deprecated. """ path = FilePath(self.mktemp()) path.makedirs() static.File(path.path).createPickleChild("foo", None) warnings = self.flushWarnings([self.test_createPickleChild]) self.assertEqual(warnings[0]['category'], DeprecationWarning) self.assertEqual( warnings[0]['message'], "File.createPickleChild is deprecated since Twisted 9.0. " "Resource persistence is beyond the scope of Twisted Web.") self.assertEqual(len(warnings), 1) class StaticMakeProducerTests(TestCase): """ Tests for L{File.makeProducer}. """ def makeResourceWithContent(self, content, type=None, encoding=None): """ Make a L{static.File} resource that has C{content} for its content. @param content: The bytes to use as the contents of the resource. @param type: Optional value for the content type of the resource. """ fileName = self.mktemp() fileObject = open(fileName, 'w') fileObject.write(content) fileObject.close() resource = static.File(fileName) resource.encoding = encoding resource.type = type return resource def contentHeaders(self, request): """ Extract the content-* headers from the L{DummyRequest} C{request}. This returns the subset of C{request.outgoingHeaders} of headers that start with 'content-'. """ contentHeaders = {} for k, v in request.outgoingHeaders.iteritems(): if k.startswith('content-'): contentHeaders[k] = v return contentHeaders def test_noRangeHeaderGivesNoRangeStaticProducer(self): """ makeProducer when no Range header is set returns an instance of NoRangeStaticProducer. """ resource = self.makeResourceWithContent('') request = DummyRequest([]) producer = resource.makeProducer(request, resource.openForReading()) self.assertIsInstance(producer, static.NoRangeStaticProducer) def test_noRangeHeaderSets200OK(self): """ makeProducer when no Range header is set sets the responseCode on the request to 'OK'. """ resource = self.makeResourceWithContent('') request = DummyRequest([]) resource.makeProducer(request, resource.openForReading()) self.assertEqual(http.OK, request.responseCode) def test_noRangeHeaderSetsContentHeaders(self): """ makeProducer when no Range header is set sets the Content-* headers for the response. """ length = 123 contentType = "text/plain" contentEncoding = 'gzip' resource = self.makeResourceWithContent( 'a'*length, type=contentType, encoding=contentEncoding) request = DummyRequest([]) resource.makeProducer(request, resource.openForReading()) self.assertEqual( {'content-type': contentType, 'content-length': str(length), 'content-encoding': contentEncoding}, self.contentHeaders(request)) def test_singleRangeGivesSingleRangeStaticProducer(self): """ makeProducer when the Range header requests a single byte range returns an instance of SingleRangeStaticProducer. """ request = DummyRequest([]) request.headers['range'] = 'bytes=1-3' resource = self.makeResourceWithContent('abcdef') producer = resource.makeProducer(request, resource.openForReading()) self.assertIsInstance(producer, static.SingleRangeStaticProducer) def test_singleRangeSets206PartialContent(self): """ makeProducer when the Range header requests a single, satisfiable byte range sets the response code on the request to 'Partial Content'. """ request = DummyRequest([]) request.headers['range'] = 'bytes=1-3' resource = self.makeResourceWithContent('abcdef') resource.makeProducer(request, resource.openForReading()) self.assertEqual( http.PARTIAL_CONTENT, request.responseCode) def test_singleRangeSetsContentHeaders(self): """ makeProducer when the Range header requests a single, satisfiable byte range sets the Content-* headers appropriately. """ request = DummyRequest([]) request.headers['range'] = 'bytes=1-3' contentType = "text/plain" contentEncoding = 'gzip' resource = self.makeResourceWithContent('abcdef', type=contentType, encoding=contentEncoding) resource.makeProducer(request, resource.openForReading()) self.assertEqual( {'content-type': contentType, 'content-encoding': contentEncoding, 'content-range': 'bytes 1-3/6', 'content-length': '3'}, self.contentHeaders(request)) def test_singleUnsatisfiableRangeReturnsSingleRangeStaticProducer(self): """ makeProducer still returns an instance of L{SingleRangeStaticProducer} when the Range header requests a single unsatisfiable byte range. """ request = DummyRequest([]) request.headers['range'] = 'bytes=4-10' resource = self.makeResourceWithContent('abc') producer = resource.makeProducer(request, resource.openForReading()) self.assertIsInstance(producer, static.SingleRangeStaticProducer) def test_singleUnsatisfiableRangeSets416ReqestedRangeNotSatisfiable(self): """ makeProducer sets the response code of the request to of 'Requested Range Not Satisfiable' when the Range header requests a single unsatisfiable byte range. """ request = DummyRequest([]) request.headers['range'] = 'bytes=4-10' resource = self.makeResourceWithContent('abc') resource.makeProducer(request, resource.openForReading()) self.assertEqual( http.REQUESTED_RANGE_NOT_SATISFIABLE, request.responseCode) def test_singleUnsatisfiableRangeSetsContentHeaders(self): """ makeProducer when the Range header requests a single, unsatisfiable byte range sets the Content-* headers appropriately. """ request = DummyRequest([]) request.headers['range'] = 'bytes=4-10' contentType = "text/plain" resource = self.makeResourceWithContent('abc', type=contentType) resource.makeProducer(request, resource.openForReading()) self.assertEqual( {'content-type': 'text/plain', 'content-length': '0', 'content-range': 'bytes */3'}, self.contentHeaders(request)) def test_singlePartiallyOverlappingRangeSetsContentHeaders(self): """ makeProducer when the Range header requests a single byte range that partly overlaps the resource sets the Content-* headers appropriately. """ request = DummyRequest([]) request.headers['range'] = 'bytes=2-10' contentType = "text/plain" resource = self.makeResourceWithContent('abc', type=contentType) resource.makeProducer(request, resource.openForReading()) self.assertEqual( {'content-type': 'text/plain', 'content-length': '1', 'content-range': 'bytes 2-2/3'}, self.contentHeaders(request)) def test_multipleRangeGivesMultipleRangeStaticProducer(self): """ makeProducer when the Range header requests a single byte range returns an instance of MultipleRangeStaticProducer. """ request = DummyRequest([]) request.headers['range'] = 'bytes=1-3,5-6' resource = self.makeResourceWithContent('abcdef') producer = resource.makeProducer(request, resource.openForReading()) self.assertIsInstance(producer, static.MultipleRangeStaticProducer) def test_multipleRangeSets206PartialContent(self): """ makeProducer when the Range header requests a multiple satisfiable byte ranges sets the response code on the request to 'Partial Content'. """ request = DummyRequest([]) request.headers['range'] = 'bytes=1-3,5-6' resource = self.makeResourceWithContent('abcdef') resource.makeProducer(request, resource.openForReading()) self.assertEqual( http.PARTIAL_CONTENT, request.responseCode) def test_mutipleRangeSetsContentHeaders(self): """ makeProducer when the Range header requests a single, satisfiable byte range sets the Content-* headers appropriately. """ request = DummyRequest([]) request.headers['range'] = 'bytes=1-3,5-6' resource = self.makeResourceWithContent( 'abcdefghijkl', encoding='gzip') producer = resource.makeProducer(request, resource.openForReading()) contentHeaders = self.contentHeaders(request) # The only content-* headers set are content-type and content-length. self.assertEqual( set(['content-length', 'content-type']), set(contentHeaders.keys())) # The content-length depends on the boundary used in the response. expectedLength = 5 for boundary, offset, size in producer.rangeInfo: expectedLength += len(boundary) self.assertEqual(expectedLength, contentHeaders['content-length']) # Content-type should be set to a value indicating a multipart # response and the boundary used to separate the parts. self.assertIn('content-type', contentHeaders) contentType = contentHeaders['content-type'] self.assertNotIdentical( None, re.match( 'multipart/byteranges; boundary="[^"]*"\Z', contentType)) # Content-encoding is not set in the response to a multiple range # response, which is a bit wussy but works well enough with the way # static.File does content-encodings... self.assertNotIn('content-encoding', contentHeaders) def test_multipleUnsatisfiableRangesReturnsMultipleRangeStaticProducer(self): """ makeProducer still returns an instance of L{SingleRangeStaticProducer} when the Range header requests multiple ranges, none of which are satisfiable. """ request = DummyRequest([]) request.headers['range'] = 'bytes=10-12,15-20' resource = self.makeResourceWithContent('abc') producer = resource.makeProducer(request, resource.openForReading()) self.assertIsInstance(producer, static.MultipleRangeStaticProducer) def test_multipleUnsatisfiableRangesSets416ReqestedRangeNotSatisfiable(self): """ makeProducer sets the response code of the request to of 'Requested Range Not Satisfiable' when the Range header requests multiple ranges, none of which are satisfiable. """ request = DummyRequest([]) request.headers['range'] = 'bytes=10-12,15-20' resource = self.makeResourceWithContent('abc') resource.makeProducer(request, resource.openForReading()) self.assertEqual( http.REQUESTED_RANGE_NOT_SATISFIABLE, request.responseCode) def test_multipleUnsatisfiableRangeSetsContentHeaders(self): """ makeProducer when the Range header requests multiple ranges, none of which are satisfiable, sets the Content-* headers appropriately. """ request = DummyRequest([]) request.headers['range'] = 'bytes=4-10' contentType = "text/plain" request.headers['range'] = 'bytes=10-12,15-20' resource = self.makeResourceWithContent('abc', type=contentType) resource.makeProducer(request, resource.openForReading()) self.assertEqual( {'content-length': '0', 'content-range': 'bytes */3'}, self.contentHeaders(request)) def test_oneSatisfiableRangeIsEnough(self): """ makeProducer when the Range header requests multiple ranges, at least one of which matches, sets the response code to 'Partial Content'. """ request = DummyRequest([]) request.headers['range'] = 'bytes=1-3,100-200' resource = self.makeResourceWithContent('abcdef') resource.makeProducer(request, resource.openForReading()) self.assertEqual( http.PARTIAL_CONTENT, request.responseCode) class StaticProducerTests(TestCase): """ Tests for the abstract L{StaticProducer}. """ def test_stopProducingClosesFile(self): """ L{StaticProducer.stopProducing} closes the file object the producer is producing data from. """ fileObject = StringIO.StringIO() producer = static.StaticProducer(None, fileObject) producer.stopProducing() self.assertTrue(fileObject.closed) def test_stopProducingSetsRequestToNone(self): """ L{StaticProducer.stopProducing} sets the request instance variable to None, which indicates to subclasses' resumeProducing methods that no more data should be produced. """ fileObject = StringIO.StringIO() producer = static.StaticProducer(DummyRequest([]), fileObject) producer.stopProducing() self.assertIdentical(None, producer.request) class NoRangeStaticProducerTests(TestCase): """ Tests for L{NoRangeStaticProducer}. """ def test_implementsIPullProducer(self): """ L{NoRangeStaticProducer} implements L{IPullProducer}. """ verifyObject( interfaces.IPullProducer, static.NoRangeStaticProducer(None, None)) def test_resumeProducingProducesContent(self): """ L{NoRangeStaticProducer.resumeProducing} writes content from the resource to the request. """ request = DummyRequest([]) content = 'abcdef' producer = static.NoRangeStaticProducer( request, StringIO.StringIO(content)) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() self.assertEqual(content, ''.join(request.written)) def test_resumeProducingBuffersOutput(self): """ L{NoRangeStaticProducer.start} writes at most C{abstract.FileDescriptor.bufferSize} bytes of content from the resource to the request at once. """ request = DummyRequest([]) bufferSize = abstract.FileDescriptor.bufferSize content = 'a' * (2*bufferSize + 1) producer = static.NoRangeStaticProducer( request, StringIO.StringIO(content)) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() expected = [ content[0:bufferSize], content[bufferSize:2*bufferSize], content[2*bufferSize:] ] self.assertEqual(expected, request.written) def test_finishCalledWhenDone(self): """ L{NoRangeStaticProducer.resumeProducing} calls finish() on the request after it is done producing content. """ request = DummyRequest([]) finishDeferred = request.notifyFinish() callbackList = [] finishDeferred.addCallback(callbackList.append) producer = static.NoRangeStaticProducer( request, StringIO.StringIO('abcdef')) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() self.assertEqual([None], callbackList) class SingleRangeStaticProducerTests(TestCase): """ Tests for L{SingleRangeStaticProducer}. """ def test_implementsIPullProducer(self): """ L{SingleRangeStaticProducer} implements L{IPullProducer}. """ verifyObject( interfaces.IPullProducer, static.SingleRangeStaticProducer(None, None, None, None)) def test_resumeProducingProducesContent(self): """ L{SingleRangeStaticProducer.resumeProducing} writes the given amount of content, starting at the given offset, from the resource to the request. """ request = DummyRequest([]) content = 'abcdef' producer = static.SingleRangeStaticProducer( request, StringIO.StringIO(content), 1, 3) # DummyRequest.registerProducer pulls all output from the producer, so # we just need to call start. producer.start() self.assertEqual(content[1:4], ''.join(request.written)) def test_resumeProducingBuffersOutput(self): """ L{SingleRangeStaticProducer.start} writes at most C{abstract.FileDescriptor.bufferSize} bytes of content from the resource to the request at once. """ request = DummyRequest([]) bufferSize = abstract.FileDescriptor.bufferSize content = 'abc' * bufferSize producer = static.SingleRangeStaticProducer( request, StringIO.StringIO(content), 1, bufferSize+10) # DummyRequest.registerProducer pulls all output from the producer, so # we just need to call start. producer.start() expected = [ content[1:bufferSize+1], content[bufferSize+1:bufferSize+11], ] self.assertEqual(expected, request.written) def test_finishCalledWhenDone(self): """ L{SingleRangeStaticProducer.resumeProducing} calls finish() on the request after it is done producing content. """ request = DummyRequest([]) finishDeferred = request.notifyFinish() callbackList = [] finishDeferred.addCallback(callbackList.append) producer = static.SingleRangeStaticProducer( request, StringIO.StringIO('abcdef'), 1, 1) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() self.assertEqual([None], callbackList) class MultipleRangeStaticProducerTests(TestCase): """ Tests for L{MultipleRangeStaticProducer}. """ def test_implementsIPullProducer(self): """ L{MultipleRangeStaticProducer} implements L{IPullProducer}. """ verifyObject( interfaces.IPullProducer, static.MultipleRangeStaticProducer(None, None, None)) def test_resumeProducingProducesContent(self): """ L{MultipleRangeStaticProducer.resumeProducing} writes the requested chunks of content from the resource to the request, with the supplied boundaries in between each chunk. """ request = DummyRequest([]) content = 'abcdef' producer = static.MultipleRangeStaticProducer( request, StringIO.StringIO(content), [('1', 1, 3), ('2', 5, 1)]) # DummyRequest.registerProducer pulls all output from the producer, so # we just need to call start. producer.start() self.assertEqual('1bcd2f', ''.join(request.written)) def test_resumeProducingBuffersOutput(self): """ L{MultipleRangeStaticProducer.start} writes about C{abstract.FileDescriptor.bufferSize} bytes of content from the resource to the request at once. To be specific about the 'about' above: it can write slightly more, for example in the case where the first boundary plus the first chunk is less than C{bufferSize} but first boundary plus the first chunk plus the second boundary is more, but this is unimportant as in practice the boundaries are fairly small. On the other side, it is important for performance to bundle up several small chunks into one call to request.write. """ request = DummyRequest([]) content = '0123456789' * 2 producer = static.MultipleRangeStaticProducer( request, StringIO.StringIO(content), [('a', 0, 2), ('b', 5, 10), ('c', 0, 0)]) producer.bufferSize = 10 # DummyRequest.registerProducer pulls all output from the producer, so # we just need to call start. producer.start() expected = [ 'a' + content[0:2] + 'b' + content[5:11], content[11:15] + 'c', ] self.assertEqual(expected, request.written) def test_finishCalledWhenDone(self): """ L{MultipleRangeStaticProducer.resumeProducing} calls finish() on the request after it is done producing content. """ request = DummyRequest([]) finishDeferred = request.notifyFinish() callbackList = [] finishDeferred.addCallback(callbackList.append) producer = static.MultipleRangeStaticProducer( request, StringIO.StringIO('abcdef'), [('', 1, 2)]) # start calls registerProducer on the DummyRequest, which pulls all # output from the producer and so we just need this one call. producer.start() self.assertEqual([None], callbackList) class RangeTests(TestCase): """ Tests for I{Range-Header} support in L{twisted.web.static.File}. @type file: L{file} @ivar file: Temporary (binary) file containing the content to be served. @type resource: L{static.File} @ivar resource: A leaf web resource using C{file} as content. @type request: L{DummyRequest} @ivar request: A fake request, requesting C{resource}. @type catcher: L{list} @ivar catcher: List which gathers all log information. """ def setUp(self): """ Create a temporary file with a fixed payload of 64 bytes. Create a resource for that file and create a request which will be for that resource. Each test can set a different range header to test different aspects of the implementation. """ path = FilePath(self.mktemp()) # This is just a jumble of random stuff. It's supposed to be a good # set of data for this test, particularly in order to avoid # accidentally seeing the right result by having a byte sequence # repeated at different locations or by having byte values which are # somehow correlated with their position in the string. self.payload = ('\xf8u\xf3E\x8c7\xce\x00\x9e\xb6a0y0S\xf0\xef\xac\xb7' '\xbe\xb5\x17M\x1e\x136k{\x1e\xbe\x0c\x07\x07\t\xd0' '\xbckY\xf5I\x0b\xb8\x88oZ\x1d\x85b\x1a\xcdk\xf2\x1d' '&\xfd%\xdd\x82q/A\x10Y\x8b') path.setContent(self.payload) self.file = path.open() self.resource = static.File(self.file.name) self.resource.isLeaf = 1 self.request = DummyRequest(['']) self.request.uri = self.file.name self.catcher = [] log.addObserver(self.catcher.append) def tearDown(self): """ Clean up the resource file and the log observer. """ self.file.close() log.removeObserver(self.catcher.append) def _assertLogged(self, expected): """ Asserts that a given log message occurred with an expected message. """ logItem = self.catcher.pop() self.assertEquals(logItem["message"][0], expected) self.assertEqual( self.catcher, [], "An additional log occured: %r" % (logItem,)) def test_invalidRanges(self): """ L{File._parseRangeHeader} raises L{ValueError} when passed syntactically invalid byte ranges. """ f = self.resource._parseRangeHeader # there's no = self.assertRaises(ValueError, f, 'bytes') # unknown isn't a valid Bytes-Unit self.assertRaises(ValueError, f, 'unknown=1-2') # there's no - in =stuff self.assertRaises(ValueError, f, 'bytes=3') # both start and end are empty self.assertRaises(ValueError, f, 'bytes=-') # start isn't an integer self.assertRaises(ValueError, f, 'bytes=foo-') # end isn't an integer self.assertRaises(ValueError, f, 'bytes=-foo') # end isn't equal to or greater than start self.assertRaises(ValueError, f, 'bytes=5-4') def test_rangeMissingStop(self): """ A single bytes range without an explicit stop position is parsed into a two-tuple giving the start position and C{None}. """ self.assertEqual( self.resource._parseRangeHeader('bytes=0-'), [(0, None)]) def test_rangeMissingStart(self): """ A single bytes range without an explicit start position is parsed into a two-tuple of C{None} and the end position. """ self.assertEqual( self.resource._parseRangeHeader('bytes=-3'), [(None, 3)]) def test_range(self): """ A single bytes range with explicit start and stop positions is parsed into a two-tuple of those positions. """ self.assertEqual( self.resource._parseRangeHeader('bytes=2-5'), [(2, 5)]) def test_rangeWithSpace(self): """ A single bytes range with whitespace in allowed places is parsed in the same way as it would be without the whitespace. """ self.assertEqual( self.resource._parseRangeHeader(' bytes=1-2 '), [(1, 2)]) self.assertEqual( self.resource._parseRangeHeader('bytes =1-2 '), [(1, 2)]) self.assertEqual( self.resource._parseRangeHeader('bytes= 1-2'), [(1, 2)]) self.assertEqual( self.resource._parseRangeHeader('bytes=1 -2'), [(1, 2)]) self.assertEqual( self.resource._parseRangeHeader('bytes=1- 2'), [(1, 2)]) self.assertEqual( self.resource._parseRangeHeader('bytes=1-2 '), [(1, 2)]) def test_nullRangeElements(self): """ If there are multiple byte ranges but only one is non-null, the non-null range is parsed and its start and stop returned. """ self.assertEqual( self.resource._parseRangeHeader('bytes=1-2,\r\n, ,\t'), [(1, 2)]) def test_multipleRanges(self): """ If multiple byte ranges are specified their starts and stops are returned. """ self.assertEqual( self.resource._parseRangeHeader('bytes=1-2,3-4'), [(1, 2), (3, 4)]) def test_bodyLength(self): """ A correct response to a range request is as long as the length of the requested range. """ self.request.headers['range'] = 'bytes=0-43' self.resource.render(self.request) self.assertEquals(len(''.join(self.request.written)), 44) def test_invalidRangeRequest(self): """ An incorrect range request (RFC 2616 defines a correct range request as a Bytes-Unit followed by a '=' character followed by a specific range. Only 'bytes' is defined) results in the range header value being logged and a normal 200 response being sent. """ self.request.headers['range'] = range = 'foobar=0-43' self.resource.render(self.request) expected = "Ignoring malformed Range header %r" % (range,) self._assertLogged(expected) self.assertEquals(''.join(self.request.written), self.payload) self.assertEquals(self.request.responseCode, http.OK) self.assertEquals( self.request.outgoingHeaders['content-length'], str(len(self.payload))) def parseMultipartBody(self, body, boundary): """ Parse C{body} as a multipart MIME response separated by C{boundary}. Note that this with fail the calling test on certain syntactic problems. """ sep = "\r\n--" + boundary parts = ''.join(body).split(sep) self.assertEquals('', parts[0]) self.assertEquals('--\r\n', parts[-1]) parsed_parts = [] for part in parts[1:-1]: before, header1, header2, blank, partBody = part.split('\r\n', 4) headers = header1 + '\n' + header2 self.assertEqual('', before) self.assertEqual('', blank) partContentTypeValue = re.search( '^content-type: (.*)$', headers, re.I|re.M).group(1) start, end, size = re.search( '^content-range: bytes ([0-9]+)-([0-9]+)/([0-9]+)$', headers, re.I|re.M).groups() parsed_parts.append( {'contentType': partContentTypeValue, 'contentRange': (start, end, size), 'body': partBody}) return parsed_parts def test_multipleRangeRequest(self): """ The response to a request for multipe bytes ranges is a MIME-ish multipart response. """ startEnds = [(0, 2), (20, 30), (40, 50)] rangeHeaderValue = ','.join(["%s-%s"%(s,e) for (s, e) in startEnds]) self.request.headers['range'] = 'bytes=' + rangeHeaderValue self.resource.render(self.request) self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT) boundary = re.match( '^multipart/byteranges; boundary="(.*)"$', self.request.outgoingHeaders['content-type']).group(1) parts = self.parseMultipartBody(''.join(self.request.written), boundary) self.assertEquals(len(startEnds), len(parts)) for part, (s, e) in zip(parts, startEnds): self.assertEqual(self.resource.type, part['contentType']) start, end, size = part['contentRange'] self.assertEqual(int(start), s) self.assertEqual(int(end), e) self.assertEqual(int(size), self.resource.getFileSize()) self.assertEqual(self.payload[s:e+1], part['body']) def test_multipleRangeRequestWithRangeOverlappingEnd(self): """ The response to a request for multipe bytes ranges is a MIME-ish multipart response, even when one of the ranged falls off the end of the resource. """ startEnds = [(0, 2), (40, len(self.payload) + 10)] rangeHeaderValue = ','.join(["%s-%s"%(s,e) for (s, e) in startEnds]) self.request.headers['range'] = 'bytes=' + rangeHeaderValue self.resource.render(self.request) self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT) boundary = re.match( '^multipart/byteranges; boundary="(.*)"$', self.request.outgoingHeaders['content-type']).group(1) parts = self.parseMultipartBody(''.join(self.request.written), boundary) self.assertEquals(len(startEnds), len(parts)) for part, (s, e) in zip(parts, startEnds): self.assertEqual(self.resource.type, part['contentType']) start, end, size = part['contentRange'] self.assertEqual(int(start), s) self.assertEqual(int(end), min(e, self.resource.getFileSize()-1)) self.assertEqual(int(size), self.resource.getFileSize()) self.assertEqual(self.payload[s:e+1], part['body']) def test_implicitEnd(self): """ If the end byte position is omitted, then it is treated as if the length of the resource was specified by the end byte position. """ self.request.headers['range'] = 'bytes=23-' self.resource.render(self.request) self.assertEquals(''.join(self.request.written), self.payload[23:]) self.assertEquals(len(''.join(self.request.written)), 41) self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT) self.assertEquals( self.request.outgoingHeaders['content-range'], 'bytes 23-63/64') self.assertEquals(self.request.outgoingHeaders['content-length'], '41') def test_implicitStart(self): """ If the start byte position is omitted but the end byte position is supplied, then the range is treated as requesting the last -N bytes of the resource, where N is the end byte position. """ self.request.headers['range'] = 'bytes=-17' self.resource.render(self.request) self.assertEquals(''.join(self.request.written), self.payload[-17:]) self.assertEquals(len(''.join(self.request.written)), 17) self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT) self.assertEquals( self.request.outgoingHeaders['content-range'], 'bytes 47-63/64') self.assertEquals(self.request.outgoingHeaders['content-length'], '17') def test_explicitRange(self): """ A correct response to a bytes range header request from A to B starts with the A'th byte and ends with (including) the B'th byte. The first byte of a page is numbered with 0. """ self.request.headers['range'] = 'bytes=3-43' self.resource.render(self.request) written = ''.join(self.request.written) self.assertEquals(written, self.payload[3:44]) self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT) self.assertEquals( self.request.outgoingHeaders['content-range'], 'bytes 3-43/64') self.assertEquals( str(len(written)), self.request.outgoingHeaders['content-length']) def test_explicitRangeOverlappingEnd(self): """ A correct response to a bytes range header request from A to B when B is past the end of the resource starts with the A'th byte and ends with the last byte of the resource. The first byte of a page is numbered with 0. """ self.request.headers['range'] = 'bytes=40-100' self.resource.render(self.request) written = ''.join(self.request.written) self.assertEquals(written, self.payload[40:]) self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT) self.assertEquals( self.request.outgoingHeaders['content-range'], 'bytes 40-63/64') self.assertEquals( str(len(written)), self.request.outgoingHeaders['content-length']) def test_statusCodeRequestedRangeNotSatisfiable(self): """ If a range is syntactically invalid due to the start being greater than the end, the range header is ignored (the request is responded to as if it were not present). """ self.request.headers['range'] = 'bytes=20-13' self.resource.render(self.request) self.assertEquals(self.request.responseCode, http.OK) self.assertEquals(''.join(self.request.written), self.payload) self.assertEquals( self.request.outgoingHeaders['content-length'], str(len(self.payload))) def test_invalidStartBytePos(self): """ If a range is unsatisfiable due to the start not being less than the length of the resource, the response is 416 (Requested range not satisfiable) and no data is written to the response body (RFC 2616, section 14.35.1). """ self.request.headers['range'] = 'bytes=67-108' self.resource.render(self.request) self.assertEquals( self.request.responseCode, http.REQUESTED_RANGE_NOT_SATISFIABLE) self.assertEquals(''.join(self.request.written), '') self.assertEquals(self.request.outgoingHeaders['content-length'], '0') # Sections 10.4.17 and 14.16 self.assertEquals( self.request.outgoingHeaders['content-range'], 'bytes */%d' % (len(self.payload),)) class DirectoryListerTest(TestCase): """ Tests for L{static.DirectoryLister}. """ def _request(self, uri): request = DummyRequest(['']) request.uri = uri return request def test_renderHeader(self): """ L{static.DirectoryLister} prints the request uri as header of the rendered content. """ path = FilePath(self.mktemp()) path.makedirs() lister = static.DirectoryLister(path.path) data = lister.render(self._request('foo')) self.assertIn("<h1>Directory listing for foo</h1>", data) self.assertIn("<title>Directory listing for foo</title>", data) def test_renderUnquoteHeader(self): """ L{static.DirectoryLister} unquote the request uri before printing it. """ path = FilePath(self.mktemp()) path.makedirs() lister = static.DirectoryLister(path.path) data = lister.render(self._request('foo%20bar')) self.assertIn("<h1>Directory listing for foo bar</h1>", data) self.assertIn("<title>Directory listing for foo bar</title>", data) def test_escapeHeader(self): """ L{static.DirectoryLister} escape "&", "<" and ">" after unquoting the request uri. """ path = FilePath(self.mktemp()) path.makedirs() lister = static.DirectoryLister(path.path) data = lister.render(self._request('foo%26bar')) self.assertIn("<h1>Directory listing for foo&amp;bar</h1>", data) self.assertIn("<title>Directory listing for foo&amp;bar</title>", data) def test_renderFiles(self): """ L{static.DirectoryLister} is able to list all the files inside a directory. """ path = FilePath(self.mktemp()) path.makedirs() path.child('file1').setContent("content1") path.child('file2').setContent("content2" * 1000) lister = static.DirectoryLister(path.path) data = lister.render(self._request('foo')) body = """<tr class="odd"> <td><a href="file1">file1</a></td> <td>8B</td> <td>[text/html]</td> <td></td> </tr> <tr class="even"> <td><a href="file2">file2</a></td> <td>7K</td> <td>[text/html]</td> <td></td> </tr>""" self.assertIn(body, data) def test_renderDirectories(self): """ L{static.DirectoryLister} is able to list all the directories inside a directory. """ path = FilePath(self.mktemp()) path.makedirs() path.child('dir1').makedirs() path.child('dir2 & 3').makedirs() lister = static.DirectoryLister(path.path) data = lister.render(self._request('foo')) body = """<tr class="odd"> <td><a href="dir1/">dir1/</a></td> <td></td> <td>[Directory]</td> <td></td> </tr> <tr class="even"> <td><a href="dir2%20%26%203/">dir2 &amp; 3/</a></td> <td></td> <td>[Directory]</td> <td></td> </tr>""" self.assertIn(body, data) def test_renderFiltered(self): """ L{static.DirectoryLister} takes a optional C{dirs} argument that filter out the list of of directories and files printed. """ path = FilePath(self.mktemp()) path.makedirs() path.child('dir1').makedirs() path.child('dir2').makedirs() path.child('dir3').makedirs() lister = static.DirectoryLister(path.path, dirs=["dir1", "dir3"]) data = lister.render(self._request('foo')) body = """<tr class="odd"> <td><a href="dir1/">dir1/</a></td> <td></td> <td>[Directory]</td> <td></td> </tr> <tr class="even"> <td><a href="dir3/">dir3/</a></td> <td></td> <td>[Directory]</td> <td></td> </tr>""" self.assertIn(body, data) def test_oddAndEven(self): """ L{static.DirectoryLister} gives an alternate class for each odd and even rows in the table. """ lister = static.DirectoryLister(None) elements = [{"href": "", "text": "", "size": "", "type": "", "encoding": ""} for i in xrange(5)] content = lister._buildTableContent(elements) self.assertEquals(len(content), 5) self.assertTrue(content[0].startswith('<tr class="odd">')) self.assertTrue(content[1].startswith('<tr class="even">')) self.assertTrue(content[2].startswith('<tr class="odd">')) self.assertTrue(content[3].startswith('<tr class="even">')) self.assertTrue(content[4].startswith('<tr class="odd">')) def test_mimeTypeAndEncodings(self): """ L{static.DirectoryLister} is able to detect mimetype and encoding of listed files. """ path = FilePath(self.mktemp()) path.makedirs() path.child('file1.txt').setContent("file1") path.child('file2.py').setContent("python") path.child('file3.conf.gz').setContent("conf compressed") path.child('file4.diff.bz2').setContent("diff compressed") directory = os.listdir(path.path) directory.sort() contentTypes = { ".txt": "text/plain", ".py": "text/python", ".conf": "text/configuration", ".diff": "text/diff" } lister = static.DirectoryLister(path.path, contentTypes=contentTypes) dirs, files = lister._getFilesAndDirectories(directory) self.assertEquals(dirs, []) self.assertEquals(files, [ {'encoding': '', 'href': 'file1.txt', 'size': '5B', 'text': 'file1.txt', 'type': '[text/plain]'}, {'encoding': '', 'href': 'file2.py', 'size': '6B', 'text': 'file2.py', 'type': '[text/python]'}, {'encoding': '[gzip]', 'href': 'file3.conf.gz', 'size': '15B', 'text': 'file3.conf.gz', 'type': '[text/configuration]'}, {'encoding': '[bzip2]', 'href': 'file4.diff.bz2', 'size': '15B', 'text': 'file4.diff.bz2', 'type': '[text/diff]'}]) def test_brokenSymlink(self): """ If on the file in the listing points to a broken symlink, it should not be returned by L{static.DirectoryLister._getFilesAndDirectories}. """ path = FilePath(self.mktemp()) path.makedirs() file1 = path.child('file1') file1.setContent("file1") file1.linkTo(path.child("file2")) file1.remove() lister = static.DirectoryLister(path.path) directory = os.listdir(path.path) directory.sort() dirs, files = lister._getFilesAndDirectories(directory) self.assertEquals(dirs, []) self.assertEquals(files, []) if getattr(os, "symlink", None) is None: test_brokenSymlink.skip = "No symlink support" def test_childrenNotFound(self): """ Any child resource of L{static.DirectoryLister} renders an HTTP I{NOT FOUND} response code. """ path = FilePath(self.mktemp()) path.makedirs() lister = static.DirectoryLister(path.path) request = self._request('') child = resource.getChildForRequest(lister, request) result = _render(child, request) def cbRendered(ignored): self.assertEquals(request.responseCode, http.NOT_FOUND) result.addCallback(cbRendered) return result def test_repr(self): """ L{static.DirectoryLister.__repr__} gives the path of the lister. """ path = FilePath(self.mktemp()) lister = static.DirectoryLister(path.path) self.assertEquals(repr(lister), "<DirectoryLister of %r>" % (path.path,)) self.assertEquals(str(lister), "<DirectoryLister of %r>" % (path.path,)) def test_formatFileSize(self): """ L{static.formatFileSize} format an amount of bytes into a more readable format. """ self.assertEquals(static.formatFileSize(0), "0B") self.assertEquals(static.formatFileSize(123), "123B") self.assertEquals(static.formatFileSize(4567), "4K") self.assertEquals(static.formatFileSize(8900000), "8M") self.assertEquals(static.formatFileSize(1234000000), "1G") self.assertEquals(static.formatFileSize(1234567890000), "1149G") class TestFileTransferDeprecated(TestCase): """ L{static.FileTransfer} is deprecated. """ def test_deprecation(self): """ Instantiation of L{FileTransfer} produces a deprecation warning. """ static.FileTransfer(StringIO.StringIO(), 0, DummyRequest([])) warnings = self.flushWarnings([self.test_deprecation]) self.assertEqual(len(warnings), 1) self.assertEqual(warnings[0]['category'], DeprecationWarning) self.assertEqual( warnings[0]['message'], 'FileTransfer is deprecated since Twisted 9.0. ' 'Use a subclass of StaticProducer instead.')
Donkyhotay/MoonPy
twisted/web/test/test_static.py
Python
gpl-3.0
53,951
package com.mirrorlabs.filebrowser; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.app.ActivityManager; import android.app.AlertDialog; import android.app.ActivityManager.MemoryInfo; import android.app.ActivityManager.RunningAppProcessInfo; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Debug; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.CompoundButton.OnCheckedChangeListener; import com.markupartist.android.widget.ActionBar; import com.markupartist.android.widget.ActionBar.IntentAction; import com.mirrorlabs.filebrowser.FilebrowserULTRAActivity.Fonts; import com.mirrorlabs.menupopup.MenuItem; import com.mirrorlabs.menupopup.PopupMenu; import com.mirrorlabs.menupopup.PopupMenu.OnItemSelectedListener; import com.mirrorlabs.quickaction.ActionItem; import com.mirrorlabs.quickaction.QuickAction; public class ProcessManager extends ListActivity { private final int CONVERT = 1024; private static final String STAR_STATES = "mylist:star_states"; private boolean[] mStarStates=null; private static final String[] Q = new String[]{"B", "KB", "MB", "GB", "T", "P", "E"}; private static PackageManager pk; private static List<RunningAppProcessInfo> display_process; private static ActivityManager activity_man; private static TextView availMem_label, numProc_label; private static ListView mylist; private ApplicationInfo appinfo = null; private PackageInfo pkginfo = null; private static final int ID_LAUNCH = 1; private static final int ID_DETAILS = 2; private static final int ID_INFO = 3; private static final int ID_UNINSTAL = 4; private static final int ID_KILL = 5; public static int[] pidvalue; private static List<String> multiSelectData=null; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.manage_layout); //Toast.makeText(ProcessManager.this," allocated size = " + getAsString(Debug.getNativeHeapAllocatedSize()), 1).show(); pk = getPackageManager(); availMem_label = (TextView)findViewById(R.id.available_mem_label); availMem_label.setTypeface(Fonts.ICS); numProc_label = (TextView)findViewById(R.id.num_processes_label); numProc_label.setTypeface(Fonts.ICS); Button killall_button = (Button)findViewById(R.id.killall_button); killall_button.setTypeface(Fonts.ICS); Button cancel_button = (Button)findViewById(R.id.cancel_button); cancel_button.setTypeface(Fonts.ICS); activity_man = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); display_process = new ArrayList<RunningAppProcessInfo>(); //setup ActionBar final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar); actionBar.setTitle("Process Manager"); actionBar.setHomeAction(new IntentAction(this, FilebrowserULTRAActivity.createIntent(this), R.drawable.ic_title_home_default)); actionBar.setDisplayHomeAsUpEnabled(true); final AsyncTask loadAppsTask = new AsyncTask<String[], Long, Long>(){ @Override protected Long doInBackground(String[]... params) { update_list(); return null; } protected void onPreExecute() { actionBar.setProgressBarVisibility(View.VISIBLE); availMem_label.setText("calculating..."); numProc_label.setText("Listing Processes..."); } @Override protected void onProgressUpdate(Long... updatedSize){ } @Override protected void onPostExecute(Long result){ actionBar.setProgressBarVisibility(View.GONE); setListAdapter(new MyListAdapter()); if (savedInstanceState != null) { mStarStates = savedInstanceState.getBooleanArray(STAR_STATES); } else { mStarStates = new boolean[display_process.size()]; } update_labels(); } }.execute(); mylist = getListView(); mylist.setFastScrollEnabled(true); mylist.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> av, View v, final int position , long id) { // TODO Auto-generated method stub getoptions(position,v); return false; } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBooleanArray(STAR_STATES, mStarStates); } public void getoptions(final int position , View view){ String processname = display_process.get(position).processName.toString(); PopupMenu menu = new PopupMenu(ProcessManager.this); menu.setHeaderTitle("Process Options"); menu.setHeaderIcon(getProcessIcon(processname)); // Set Listener menu.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case ID_LAUNCH: Intent i = pk.getLaunchIntentForPackage(display_process.get(position).processName); if(i != null) startActivity(i); else Toast.makeText(ProcessManager.this, "Could not launch", Toast.LENGTH_SHORT).show(); break; case ID_KILL: try { killProcess(ProcessManager.this, display_process.get(position).pid, display_process.get(position).processName); } catch (Exception e) { // TODO: handle exception Toast.makeText(ProcessManager.this, "couldn't kill the process ",Toast.LENGTH_SHORT).show(); } @SuppressWarnings("unchecked") final ArrayAdapter<RunningAppProcessInfo> adapter = (ArrayAdapter<RunningAppProcessInfo>) getListAdapter(); Toast.makeText(ProcessManager.this,display_process.get(position).processName + " was killed !", Toast.LENGTH_SHORT).show(); adapter.remove(display_process.get(position)); update_labels(); break; case ID_DETAILS: final int apiLevel = Build.VERSION.SDK_INT; Intent intent = new Intent(); if (apiLevel >= 9) { //TODO get working on gb //Toast.makeText(SDMove.this, "Gingerbread Not Currently Supported", Toast.LENGTH_LONG).show(); startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + display_process.get(position).processName))); } else { final String appPkgName = (apiLevel == 8 ? "pkg" : "com.android.settings.ApplicationPkgName"); intent.setAction(Intent.ACTION_VIEW); intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); intent.putExtra(appPkgName, display_process.get(position).processName); startActivity(intent); } break; case ID_UNINSTAL: try{ Intent uninstall_intent= new Intent(Intent.ACTION_DELETE); uninstall_intent.setData(Uri.parse("package:"+display_process.get(position).processName)); startActivity(uninstall_intent); } catch (Exception e) { // TODO: handle exception Toast.makeText(ProcessManager.this,"Can't Uninstall" , Toast.LENGTH_SHORT).show(); } break; case ID_INFO: //Toast.makeText(ProcessManager.this, "Process : "+display_process.get(position).processName +" lru : " +display_process.get(position).lru + " Pid : " +display_process.get(position).pid, Toast.LENGTH_SHORT).show(); final AlertDialog alert1 = new AlertDialog.Builder(ProcessManager.this).create(); alert1.setTitle("Process Info"); alert1.setIcon(getProcessIcon(display_process.get(position).processName)); alert1.setMessage("Process : "+display_process.get(position).processName+ " \nlru : "+display_process.get(position).lru + "\nPid : " +display_process.get(position).pid ); alert1.show(); } } }); // Add Menu (Android menu like style) menu.add(ID_LAUNCH, R.string.launch).setIcon( getResources().getDrawable(R.drawable.install)); menu.add(ID_DETAILS, R.string.details).setIcon( getResources().getDrawable(R.drawable.advancedsettings)); menu.add(ID_INFO, R.string.info).setIcon( getResources().getDrawable(R.drawable.info)); // menu.add(ID_UNINSTAL, R.string.uninstall).setIcon( // getResources().getDrawable(R.drawable.uninstall)); menu.add(ID_KILL, R.string.kill).setIcon( getResources().getDrawable(R.drawable.delete)); menu.show(view); } @Override protected void onPause() { super.onPause(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); System.gc(); } @Override protected void onResume() { super.onResume(); } public void onClick(View view){ switch (view.getId()) { case R.id.cancel_button : finish(); break; case R.id.killall_button: //i hate this method it doesn't work...but still. //have to change it and write another code.. List<RunningAppProcessInfo> total_process = activity_man.getRunningAppProcesses(); int len; len = total_process.size(); int count=0; for (int i = 0; i < len; i++){ if(total_process.get(i).importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND && total_process.get(i).importance != RunningAppProcessInfo.IMPORTANCE_SERVICE){ count++; } } for (int i = 0;i<count;i++){ try { killProcess(ProcessManager.this, display_process.get(i).pid, display_process.get(i).processName); @SuppressWarnings("unchecked") final ArrayAdapter<RunningAppProcessInfo> adapter = (ArrayAdapter<RunningAppProcessInfo>) getListAdapter(); adapter.remove(display_process.get(i)); } catch (Exception e) { e.printStackTrace(); } } update_labels(); Toast.makeText(ProcessManager.this, count + " processes were killed !", Toast.LENGTH_SHORT).show(); break; } } @Override protected void onListItemClick(ListView mylist, View view, final int position, long id) { ActionItem killItem = new ActionItem(ID_KILL, "Kill this", getResources().getDrawable(R.drawable.delete)); ActionItem launchItem = new ActionItem(ID_LAUNCH, "Launch", getResources().getDrawable(R.drawable.install)); ActionItem unisntallItem = new ActionItem(ID_UNINSTAL, "Uninstall", getResources().getDrawable(R.drawable.uninstall)); ActionItem infoItem = new ActionItem(ID_INFO, "Info", getResources().getDrawable(R.drawable.info)); ActionItem detailsItem = new ActionItem(ID_DETAILS, "Manage", getResources().getDrawable(R.drawable.advancedsettings)); final QuickAction quickAction = new QuickAction(this); //add action items into QuickAction quickAction.addActionItem(launchItem); quickAction.addActionItem(detailsItem); //quickAction.addActionItem(searchItem); quickAction.addActionItem(infoItem); // quickAction.addActionItem(unisntallItem); //quickAction.addActionItem(eraseItem); quickAction.addActionItem(killItem); //Set listener for action item clicked quickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() { public void onItemClick(QuickAction source, int pos, int actionId) { //here we can filter which action item was clicked with pos or actionId parameter ActionItem actionItem = quickAction.getActionItem(pos); switch (actionId) { case ID_KILL: try { killProcess(ProcessManager.this, display_process.get(position).pid, display_process.get(position).processName); } catch (Exception e) { // TODO: handle exception Toast.makeText(ProcessManager.this, "couldn't kill the process ",Toast.LENGTH_SHORT).show(); } @SuppressWarnings("unchecked") final ArrayAdapter<RunningAppProcessInfo> adapter = (ArrayAdapter<RunningAppProcessInfo>) getListAdapter(); Toast.makeText(ProcessManager.this,display_process.get(position).processName + " was killed !", Toast.LENGTH_SHORT).show(); adapter.remove(display_process.get(position)); update_labels(); break; case ID_DETAILS: final int apiLevel = Build.VERSION.SDK_INT; Intent intent = new Intent(); if (apiLevel >= 9) { //TODO get working on gb //Toast.makeText(SDMove.this, "Gingerbread Not Currently Supported", Toast.LENGTH_LONG).show(); startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + display_process.get(position).processName))); } else { final String appPkgName = (apiLevel == 8 ? "pkg" : "com.android.settings.ApplicationPkgName"); intent.setAction(Intent.ACTION_VIEW); intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); intent.putExtra(appPkgName, display_process.get(position).processName); startActivity(intent); } break; case ID_LAUNCH: Intent i = pk.getLaunchIntentForPackage(display_process.get(position).processName); if(i != null) startActivity(i); else Toast.makeText(ProcessManager.this, "Could not launch", Toast.LENGTH_SHORT).show(); break; case ID_UNINSTAL: try{ Intent uninstall_intent= new Intent(Intent.ACTION_DELETE); uninstall_intent.setData(Uri.parse("package:"+display_process.get(position).processName)); startActivity(uninstall_intent); } catch (Exception e) { // TODO: handle exception Toast.makeText(ProcessManager.this,"Can't Uninstall" , Toast.LENGTH_SHORT).show(); } break; case ID_INFO: //Toast.makeText(ProcessManager.this, "Process : "+display_process.get(position).processName +" lru : " +display_process.get(position).lru + " Pid : " +display_process.get(position).pid, Toast.LENGTH_SHORT).show(); final AlertDialog alert1 = new AlertDialog.Builder(ProcessManager.this).create(); alert1.setTitle("Process Info"); alert1.setIcon(getProcessIcon(display_process.get(position).processName)); alert1.setMessage("Process : "+display_process.get(position).processName+ " \nlru : "+display_process.get(position).lru + "\nPid : " +display_process.get(position).pid ); alert1.show(); break; default: Toast.makeText(ProcessManager.this, actionItem.getTitle() + " selected", Toast.LENGTH_SHORT).show(); break; } } }); //set listnener for on dismiss event, this listener will be called only if QuickAction dialog was dismissed //by clicking the area outside the dialog. quickAction.setOnDismissListener(new QuickAction.OnDismissListener() { public void onDismiss() { } }); quickAction.show(view); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)){ //Back key pressed finish(); return true; } return super.onKeyDown(keyCode, event); } public boolean killProcess(Context context, int pid, String packageName) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); if (pid <= 0) { return false; } if (pid == android.os.Process.myPid()) { System.out.println("Killing own process"); android.os.Process.killProcess(pid); return true; } Method method = null; try { // Since API_LEVEL 8 : v2.2 method = manager.getClass().getMethod("killBackgroundProcesses", new Class[] { String.class}); } catch (NoSuchMethodException e) { // less than 2.2 try { method = manager.getClass().getMethod("restartPackage", new Class[] { String.class }); } catch (NoSuchMethodException ee) { ee.printStackTrace(); } } if (method != null) { try { method.invoke(manager, packageName); System.out.println("kill method " + method.getName()+ " invoked " + packageName); } catch (Exception e) { e.printStackTrace(); } } android.os.Process.killProcess(pid); return true; } private void update_labels() { MemoryInfo mem_info; double mem_size; mem_info = new ActivityManager.MemoryInfo(); activity_man.getMemoryInfo(mem_info); mem_size = (mem_info.availMem / (CONVERT * CONVERT)); availMem_label.setText(String.format("Available memory:\t %.2f Mb", mem_size)); numProc_label.setText("Number of processes:\t " + display_process.size()); } public Drawable getProcessIcon(String pkg_name){ try { return pk.getApplicationIcon(pkg_name); }catch (Exception e) { // TODO: handle exception return getResources().getDrawable(R.drawable.apk_file); } } private void update_list() { List<RunningAppProcessInfo> total_process = activity_man.getRunningAppProcesses(); int len; total_process = activity_man.getRunningAppProcesses(); len = total_process.size(); for (int i = 0; i < len; i++){ if(total_process.get(i).importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND && total_process.get(i).importance != RunningAppProcessInfo.IMPORTANCE_SERVICE) display_process.add(total_process.get(i)); } } public String getAsString(long bytes) { for (int i = 6; i > 0; i--) { double step = Math.pow(1024, i); if (bytes > step) return String.format("%3.1f %s", bytes / step, Q[i]); } return Long.toString(bytes); } class ViewHolder { public ImageView image=null; public TextView name=null; public CheckBox select=null; public TextView version =null; public TextView state=null; ViewHolder(View row){ name = (TextView)row.findViewById(R.id.app_name); name.setTypeface(Fonts.ICS); select = (CheckBox)row.findViewById(R.id.select_icon); select.setVisibility(View.GONE); version = (TextView)row.findViewById(R.id.version); version.setTypeface(Fonts.ICS); state = (TextView)row.findViewById(R.id.installdate); state.setTypeface(Fonts.ICS); image = (ImageView)row.findViewById(R.id.icon); } void populateFrom(String s) { name.setText(s); } } private class MyListAdapter extends ArrayAdapter<RunningAppProcessInfo> { public MyListAdapter() { super(ProcessManager.this, R.layout.app_row, display_process); } public String parse_name(String pkgName) { String[] items = pkgName.split("\\."); String name = ""; int len = items.length; for (int i = 0; i < len; i++){ if(!items[i].equalsIgnoreCase("com") && !items[i].equalsIgnoreCase("android") && !items[i].equalsIgnoreCase("google") && !items[i].equalsIgnoreCase("process") && !items[i].equalsIgnoreCase("htc") && !items[i].equalsIgnoreCase("coremobility")) name = items[i]; } return name; } @Override public View getView(int position,View convertView, ViewGroup parent) { ViewHolder holder; String pkg_name = display_process.get(position).processName; CharSequence processName; try { appinfo = pk.getApplicationInfo(pkg_name, 0); processName = appinfo.loadLabel(pk); } catch (NameNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); processName = parse_name(pkg_name); } if(convertView == null) { LayoutInflater inflater = getLayoutInflater(); convertView = inflater.inflate(R.layout.app_row, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.select.setOnCheckedChangeListener(null); holder.select.setChecked(mStarStates[position]); holder.select.setOnCheckedChangeListener(mStarCheckedChanceChangeListener); holder.name.setText(processName); holder.version.setText(String.format("%s", display_process.get(position).processName)); if(display_process.get(position).importance==RunningAppProcessInfo.IMPORTANCE_FOREGROUND){ holder.state.setText("Foreground"); } else if(display_process.get(position).importance==RunningAppProcessInfo.IMPORTANCE_BACKGROUND) { holder.state.setText("Background"); } else if(display_process.get(position).importance==RunningAppProcessInfo.IMPORTANCE_VISIBLE) { holder.state.setText("Visible"); } else if(display_process.get(position).importance==RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE) { holder.state.setText("Perceptible"); } try { holder.image.setImageDrawable(pk.getApplicationIcon(pkg_name)); } catch (NameNotFoundException e) { holder.image.setImageResource(R.drawable.apk_file); } return convertView; } } private OnCheckedChangeListener mStarCheckedChanceChangeListener = new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { final int position = getListView().getPositionForView(buttonView); if (position != ListView.INVALID_POSITION) { mStarStates[position] = isChecked; } } }; }
kshark27/UltraExplorer
filebrowserULTRA/src/com/mirrorlabs/filebrowser/ProcessManager.java
Java
gpl-3.0
24,569
<?php if (_DEBUGMODE) { $creation_time = getmt() - script_start_time; echo sprintf("<p/><hr/><p>Script took %1.0f ms for generation\n</p>", $creation_time); } ?> </body> </html>
stefaweb/XAMS-0.3.x
gui/footer.php
PHP
gpl-3.0
206
#include <string> #include <vector> #include "TProfesor.h" TProfesor::TProfesor(std::string _strNombre, int _intCodigo) { intCodigo = _intCodigo; strNombre = _strNombre; } TProfesor::TProfesor(const char* _pchrNombre, int _intCodigo) { intCodigo = _intCodigo; strNombre = _pchrNombre; } void TProfesor::PutCostAsigProf (TCostAsigProf CostAsigProf) { LCostAsigProf.push_back(CostAsigProf); } unsigned TProfesor::FindAsigPos(int intSearchTerm){ unsigned uintIndex=0; for (unsigned i=0; i<LCostAsigProf.size(); i++) { if (LCostAsigProf[i].GetCodAsig() == intSearchTerm) { uintIndex=i; return uintIndex; } } return (unsigned) 0; } std::string TProfesor::GetSummary() { std::string strTemp="Profesor: " + strNombre + "\n"; for (unsigned i=0; i<LCostAsigProf.size(); i++) { strTemp+=LCostAsigProf[i].Show()+"\n"; } return strTemp; } int TProfesor::GetCodProf() { return intCodigo; } std::string TProfesor::GetNombre() { return strNombre; } unsigned TProfesor::EscogeHorarioDisplonibleDeAsignatura(unsigned pos) { return LCostAsigProf[pos].ChooseHorario(); } TCostHoraProf *TProfesor::EscogeCostHoraProf(unsigned pos) { return LCostAsigProf[pos].ChooseCostHoraProf(); }
KarlHeitmann/PlanificacionHorarios
src/ae/eda/TProfesor.cpp
C++
gpl-3.0
1,195
<?php /** * All law firms and agents have been assigned. Now a lifespan must be negotiated. */ class DisputeOpened extends DisputeDefaults implements DisputeStateInterface { public function getStateDescription() { return 'Negotiating lifespan.'; } public function canOpenDispute() { return false; } public function canAssignDisputeToAgent() { return false; } }
ChrisBAshton/smartresolution
webapp/core/model/dispute_states/DisputeStateDisputeOpened.php
PHP
gpl-3.0
416
/* * Copyright 2018 <copyright holder> <email> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <dsr/gui/viewers/graph_viewer/graph_node.h> //#include <dsr/gui/viewers/graph_viewer/node_colors.h> #include <dsr/gui/viewers/graph_viewer/graph_colors.h> #include <dsr/gui/viewers/graph_viewer/graph_node_laser_widget.h> #include <dsr/gui/viewers/graph_viewer/graph_node_widget.h> #include <dsr/gui/viewers/graph_viewer/graph_node_rgbd_widget.h> #include <dsr/gui/viewers/graph_viewer/graph_node_person_widget.h> GraphNode::GraphNode(const std::shared_ptr<DSR::GraphViewer>& graph_viewer_):QGraphicsEllipseItem(0,0,DEFAULT_DIAMETER,DEFAULT_DIAMETER), graph_viewer(graph_viewer_) { auto flags = ItemIsMovable | ItemIsSelectable | ItemSendsGeometryChanges | ItemUsesExtendedStyleOption | ItemIsFocusable; setFlags(flags); setCacheMode(DeviceCoordinateCache); setAcceptHoverEvents(true); setZValue(-1); node_brush.setStyle(Qt::SolidPattern); animation = new QPropertyAnimation(this, "node_color"); animation->setDuration(animation_time); animation->setStartValue(plain_color); animation->setEndValue(dark_color); animation->setLoopCount(ANIMATION_REPEAT); QObject::connect(graph_viewer_->getGraph().get(), &DSR::DSRGraph::update_node_attr_signal, this, &GraphNode::update_node_attr_slot, Qt::QueuedConnection); } void GraphNode::setTag(const std::string &tag_) { QString c = QString::fromStdString(tag_); tag = new QGraphicsSimpleTextItem(c, this); tag->setX(DEFAULT_DIAMETER); tag->setY(-10); } void GraphNode::setType(const std::string &type_) { type = type_; if(type == "laser" or type == "rgbd" or type == "person") { contextMenu = new QMenu(); QAction *table_action = new QAction("View table"); contextMenu->addAction(table_action); connect(table_action, &QAction::triggered, this, [this](){ this->show_node_widget("table");}); QAction *stuff_action = new QAction("View data"); contextMenu->addAction(stuff_action); connect(stuff_action, &QAction::triggered, this, [this, type_](){ this->show_node_widget(type_);}); } auto color = GraphColors<DSR::Node>()[type]; set_color(color); } void GraphNode::addEdge(GraphEdge *edge) { qDebug()<<"===================================="; int same_count = 0; int bend_factor = 0; // look for edges with the same dest qDebug()<<__FUNCTION__ <<"Checking edges for node: "<<this->id_in_graph; for (auto old_edge: edgeList) { if(old_edge == edge) throw std::runtime_error("Trying to add an already existing edge " + std::to_string(edge->sourceNode()->id_in_graph)+"--"+std::to_string(edge->destNode()->id_in_graph)); // qDebug()<<__FUNCTION__ <<"\tExisting EDGE: "<<edge->sourceNode()->id_in_graph<<edge->destNode()->id_in_graph<<"OTHER: "<<old_edge->sourceNode()->id_in_graph<<old_edge->destNode()->id_in_graph; qDebug()<<"\t"<<__FUNCTION__ <<"Existing EDGE: "<<old_edge->sourceNode()->id_in_graph<<"--"<<old_edge->destNode()->id_in_graph; qDebug()<<"\t"<<__FUNCTION__ <<" New EDGE: "<<edge->sourceNode()->id_in_graph<<"--"<<edge->destNode()->id_in_graph; if((edge->sourceNode()->id_in_graph==old_edge->sourceNode()->id_in_graph or edge->sourceNode()->id_in_graph==old_edge->destNode()->id_in_graph) and (edge->destNode()->id_in_graph==old_edge->sourceNode()->id_in_graph or edge->destNode()->id_in_graph==old_edge->destNode()->id_in_graph)) { same_count++; qDebug()<<"\t\t"<<__FUNCTION__ <<"SAME EDGE"<<same_count; } } // https://www.wolframalpha.com/input/?i=0%2C+1%2C+-1%2C+2%2C+-2%2C+3%2C+-3 bend_factor = (pow(-1,same_count)*(-1 + pow(-1,same_count) - 2*same_count))/4; qDebug()<<__FUNCTION__ <<__LINE__<<"ID: "<<id_in_graph<<"SAME: "<<same_count<<"FACTOR: "<<bend_factor; edge->set_bend_factor(bend_factor); edgeList << edge; edge->adjust(); qDebug()<<"===================================="; } void GraphNode::deleteEdge(GraphEdge *edge) { edgeList.removeAll(edge); } QList<GraphEdge *> GraphNode::edges() const { return edgeList; } void GraphNode::calculateForces() { if (!scene() || scene()->mouseGrabberItem() == this) { newPos = pos(); return; } // Sum up all forces pushing this item away qreal xvel = 0; qreal yvel = 0; //foreach (QGraphicsItem *item, scene()->items()) for( auto &[k,node] : graph_viewer->getGMap()) { //GraphNode *node = qgraphicsitem_cast<GraphNode *>(item); //if (!node) // continue; (void)k; QPointF vec = mapToItem(node, 0, 0); qreal dx = vec.x(); qreal dy = vec.y(); double l = 2.0 * (dx * dx + dy * dy); if (l > 0) { xvel += (dx * force_velocity_factor) / l; yvel += (dy * force_velocity_factor) / l; } } // Now subtract all forces pulling items together double weight = (edgeList.size() + 1) * EDGE_PULL_FACTOR; foreach (GraphEdge *edge, edgeList) { QPointF vec; if (edge->sourceNode() == this) vec = mapToItem(edge->destNode(), 0, 0); else vec = mapToItem(edge->sourceNode(), 0, 0); xvel -= vec.x() / weight; yvel -= vec.y() / weight; } // Subtract force from central pos pulling item to the center of the image QPointF to_central_point = mapFromItem(graph_viewer->getCentralPoint(), 0, 0); xvel += to_central_point.x() / (weight/2) ; yvel += to_central_point.y() / (weight/2) ; // sludge if (qAbs(xvel) < 0.1 && qAbs(yvel) < 0.1) xvel = yvel = 0; QRectF sceneRect = scene()->sceneRect(); newPos = pos() + QPointF(xvel, yvel); newPos.setX(qMin(qMax(newPos.x(), sceneRect.left() + SCENE_MARGIN), sceneRect.right() - SCENE_MARGIN)); newPos.setY(qMin(qMax(newPos.y(), sceneRect.top() + SCENE_MARGIN), sceneRect.bottom() - SCENE_MARGIN)); } bool GraphNode::advancePosition() { if (newPos == pos()) return false; setPos(newPos); return true; } QRectF GraphNode::boundingRect() const { qreal adjust = 2; return QRectF( -DEFAULT_RADIUS - adjust, -DEFAULT_RADIUS - adjust, DEFAULT_DIAMETER + 3 + adjust, DEFAULT_DIAMETER + 3 + adjust ); } QPainterPath GraphNode::shape() const { QPainterPath path; path.addEllipse(-DEFAULT_RADIUS, -DEFAULT_RADIUS, DEFAULT_DIAMETER, DEFAULT_DIAMETER); return path; } void GraphNode::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) { painter->setPen(Qt::NoPen); painter->setBrush(SUNKEN_COLOR); // painter->drawEllipse(-7, -7, node_width, node_width); QRadialGradient gradient(-3, -3, 10); if (option->state & QStyle::State_Sunken) { gradient.setColorAt(0, QColor(Qt::darkGray).light(LUMINOSITY_FACTOR)); gradient.setColorAt(1, QColor(Qt::darkGray)); } else { gradient.setColorAt(0, node_brush.color()); gradient.setColorAt(1, QColor(node_brush.color().dark(LUMINOSITY_FACTOR))); } painter->setBrush(gradient); if(isSelected()) painter->setPen(QPen(Qt::green, 0, Qt::DashLine)); else painter->setPen(QPen(Qt::black, 0)); painter->drawEllipse(-DEFAULT_RADIUS, -DEFAULT_RADIUS, DEFAULT_DIAMETER, DEFAULT_DIAMETER); } QVariant GraphNode::itemChange(GraphicsItemChange change, const QVariant &value) { switch (change) { case ItemPositionHasChanged: { foreach (GraphEdge *edge, edgeList) edge->adjust(this, value.toPointF()); break; } default: break; } return QGraphicsItem::itemChange(change, value); } void GraphNode::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { //if (tag->text() != "") return; // Explota sin esto // animation->start(); if( event->button()== Qt::RightButton) { if (contextMenu != nullptr) contextMenu->exec(event->screenPos()); else show_node_widget("table"); } // update(); QGraphicsEllipseItem::mouseDoubleClickEvent(event); } void GraphNode::show_node_widget(const std::string &show_type) { //static std::unique_ptr<QWidget> do_stuff; const auto graph = graph_viewer->getGraph(); if(show_type=="laser") node_widget = std::make_unique<GraphNodeLaserWidget>(graph, id_in_graph); else if(show_type=="rgbd") node_widget = std::make_unique<GraphNodeRGBDWidget>(graph, id_in_graph); else if(show_type=="person") node_widget = std::make_unique<GraphNodePersonWidget>(graph, id_in_graph); else node_widget = std::make_unique<GraphNodeWidget>(graph, id_in_graph); } void GraphNode::change_detected() { animation->start(); } void GraphNode::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if( event->button()== Qt::LeftButton) { auto g = graph_viewer->getGraph(); qDebug() << __FILE__ <<":"<<__FUNCTION__<< " node id in graphnode: " << id_in_graph ; std::optional<Node> n = g->get_node(id_in_graph); if (n.has_value()) { // qDebug()<<"ScenePos X"<<(float) event->scenePos().x()<<" Width "<<(this->rect())<<" this "<<this->pos().x(); // qDebug()<<"ScenePos Y"<<(float) event->scenePos().y()<<" Height "<<(this->rect())<<" this "<<this->pos().y(); g->add_or_modify_attrib_local<pos_x_att>(n.value(), (float) this->pos().x()); g->add_or_modify_attrib_local<pos_y_att>(n.value(), (float) this->pos().y()); g->update_node(n.value()); } // this->dsr_to_graph_viewer->itemMoved(); } QGraphicsItem::mouseReleaseEvent(event); } QColor GraphNode::_node_color() { return this->brush().color(); } void GraphNode::set_node_color(const QColor& c) { node_brush.setColor(c); this->setBrush( node_brush ); } void GraphNode::set_color(const std::string &plain) { QString c = QString::fromStdString(plain); plain_color = c; dark_color = "dark" + c; set_node_color(QColor(c)); animation->setStartValue(QColor("green").lighter()); animation->setEndValue(c); } /////////////////////////////////////////////////////////////////////////////////////////7 //// ///////////////////////////////////////////////////////////////////////////////////////// void GraphNode::update_node_attr_slot(std::uint64_t node_id, const std::vector<std::string> &type) { if (node_id != this->id_in_graph) return; // if(std::find(type.begin(), type.end(), "color") != type.end()) // { // std::optional<Node> n = graph_viewer->getGraph()->get_node(node_id); // if (n.has_value()) { //// auto &attrs = n.value().attrs(); //// auto value = attrs.find("color"); //// if (value != attrs.end()) { //// this->setColor(value->second.str()); //// } // } // } } /* void GraphNode::NodeAttrsChangedSLOT(const DSR::IDType &node, const DSR::Attribs &attr) { std::cout << "do cool stuff" << std::endl; } */ // void GraphNode::hoverEnterEvent(QGraphicsSceneHoverEvent* event) // { // // label = new QTableWidget(graph); // //label->setText(tag->text().toStdString()); // //label->show(); // //label->exec(); // std::cout << "entering node: " << tag->text().toStdString() << std::endl; // update (boundingRect()); // } // void GraphNode::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) // { // // QDialog *label = new QDialog(graph); // // label->exec(); // //label->close(); // //lable->delete(); // std::cout << "exiting node: " << tag->text().toStdString() << std::endl; // update (boundingRect()); // }
robocomp/robocomp
libs/dsr/gui/viewers/graph_viewer/graph_node.cpp
C++
gpl-3.0
12,408
using System; using System.Drawing; using System.Windows.Forms; using GradeTracker.Data; namespace GradeTracker.Forms { public class CourseGradeableTasksForm : Form { Course course; #region Form elements private Button addNewTaskButton; private DataGridView tasksGrid; #endregion /// <summary> /// Maps the columns of the Tasks grid. /// </summary> private enum GradeableTasksGridColumn { Edit = 4, Delete = 5 }; public CourseGradeableTasksForm(Course course) { this.course = course; Text = String.Format("Course Tasks: {0}", this.course.Name); MinimumSize = new Size(600, 600); InitializeAddNewTaskButton(); InitializeTasksGrid(); Refresh(); } /// <summary> /// Initializes the Add New Task button. /// </summary> private void InitializeAddNewTaskButton() { addNewTaskButton = new Button() { Text = "Add New Task", Width = 200, Location = new Point(0, 10) }; addNewTaskButton.Click += new EventHandler(AddNewTaskButton_Click); Controls.Add(addNewTaskButton); } /// <summary> /// Handles the Add New Task button's click event. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void AddNewTaskButton_Click(object sender, EventArgs e) { new GradeableTaskForm(course).Show(); } /// <summary> /// Initializes the Tasks grid. /// </summary> private void InitializeTasksGrid() { tasksGrid = new DataGridView() { ReadOnly = true, AllowUserToAddRows = false, Location = new Point(addNewTaskButton.Left, addNewTaskButton.Height + addNewTaskButton.Top + 10), Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right }; tasksGrid.Columns.Add(new DataGridViewTextBoxColumn(){ HeaderText = "Task" }); tasksGrid.Columns.Add(new DataGridViewTextBoxColumn(){ HeaderText = "Due Date" }); tasksGrid.Columns.Add(new DataGridViewTextBoxColumn(){ HeaderText = "Marks" }); tasksGrid.Columns.Add(new DataGridViewTextBoxColumn(){ HeaderText = "Weight" }); tasksGrid.Columns.Add(new DataGridViewButtonColumn() { HeaderText = "Edit", Text = "Edit", UseColumnTextForButtonValue = true }); tasksGrid.Columns.Add(new DataGridViewButtonColumn() { HeaderText = "Delete", Text = "Delete", UseColumnTextForButtonValue = true }); tasksGrid.CellClick += TasksGrid_CellClick; Controls.Add(tasksGrid); } /// <summary> /// Handles the Task grid's click event. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="DataGridViewCellEventArgs"/> instance containing the event data.</param> private void TasksGrid_CellClick (object sender, DataGridViewCellEventArgs e) { DataGridViewRow row = tasksGrid.Rows[e.RowIndex]; GradeableTask task = (GradeableTask)row.Tag; switch (e.ColumnIndex) { case (int)GradeableTasksGridColumn.Edit: new GradeableTaskForm(task).Show(); break; case (int)GradeableTasksGridColumn.Delete: switch (MessageBox.Show(this, String.Format("Are you sure you want to delete {0}", task.Name), "Delete Task", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation)) { case DialogResult.OK: task.Delete(); break; default: break; } Refresh(); break; } } /// <summary> /// Refresh the form, and ensure the Tasks grid is up to date. /// </summary> public override void Refresh() { base.Refresh(); tasksGrid.Rows.Clear(); foreach(GradeableTask task in course.GetTasks()) { DataGridViewRow row = new DataGridViewRow(){ Tag = task }; row.Cells.Add(new DataGridViewTextBoxCell(){ Value = task.Name }); row.Cells.Add(new DataGridViewTextBoxCell(){ Value = task.DueDate.ToShortDateString() }); row.Cells.Add(new DataGridViewTextBoxCell(){ Value = task.PotentialMarks.ToString() }); row.Cells.Add(new DataGridViewTextBoxCell(){ Value = String.Format("{0}%", task.Weight.ToString()) }); tasksGrid.Rows.Add(row); } } } }
baconbum/GradeTracker
GradeTracker/Forms/CourseGradeableTasksForm.cs
C#
gpl-3.0
4,165
/** * \file * Copyright 2014-2015 Benjamin Worpitz * * This file is part of alpaka. * * alpaka 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. * * alpaka 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 alpaka. * If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <alpaka/core/Common.hpp> // ALPAKA_FN_HOST_ACC #if !defined(__CUDA_ARCH__) #include <boost/core/ignore_unused.hpp> // boost::ignore_unused #endif #if !(__cplusplus >= 201402L) #include <type_traits> // std::result_of #endif namespace alpaka { namespace core { //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TFnObj, typename T> ALPAKA_FN_HOST_ACC auto foldr( TFnObj const & f, T const & t) -> T { #if !defined(__CUDA_ARCH__) boost::ignore_unused(f); #endif return t; } #if __cplusplus >= 201402L //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TFnObj, typename T0, typename T1, typename... Ts> ALPAKA_FN_HOST_ACC auto foldr( TFnObj const & f, T0 const & t0, T1 const & t1, Ts const & ... ts) { return f(t0, foldr(f, t1, ts...)); } #else namespace detail { //############################################################################# //! //############################################################################# template< typename TFnObj, typename... T> struct TypeOfFold; //############################################################################# //! //############################################################################# template< typename TFnObj, typename T> struct TypeOfFold< TFnObj, T> { using type = T; }; //############################################################################# //! //############################################################################# template< typename TFnObj, typename T, typename... P> struct TypeOfFold< TFnObj, T, P...> { using type = typename std::result_of< TFnObj(T, typename TypeOfFold<TFnObj, P...>::type)>::type; }; } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TFnObj, typename T0, typename T1, typename... Ts> ALPAKA_FN_HOST_ACC auto foldr( TFnObj const & f, T0 const & t0, T1 const & t1, Ts const & ... ts) // NOTE: The following line is not allowed because the point of function declaration is after the trailing return type. // Thus the function itself is not available inside its return type declaration. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1433 // http://stackoverflow.com/questions/3744400/trailing-return-type-using-decltype-with-a-variadic-template-function // http://stackoverflow.com/questions/11596898/variadic-template-and-inferred-return-type-in-concat/11597196#11597196 //-> decltype(f(t0, foldr(f, t1, ts...))) -> typename detail::TypeOfFold<TFnObj, T0, T1, Ts...>::type { return f(t0, foldr(f, t1, ts...)); } #endif } }
erikzenker/alpaka-examples
alpaka/include/alpaka/core/Fold.hpp
C++
gpl-3.0
4,795
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using CheezeMod.NPCs; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace CheezeMod.Items.Weapons.Ratchet { public class LavaGun : ModItem { public override void SetDefaults() { item.damage = 5; item.ranged = true; item.width = 50; item.height = 30; item.scale = 0.875f; item.channel = true; item.useTime = 5; item.useAnimation = 10; item.useStyle = 5; item.channel = true; item.noMelee = true; //so the item's animation doesn't do damage item.knockBack = 1; item.value = 33000; item.rare = CheezeItem.ratchetRarity[0]; item.UseSound = mod.GetLegacySoundSlot(SoundType.Item, "Sounds/Item/LavaGun"); item.autoReuse = true; item.shoot = mod.ProjectileType("LavaGun"); item.shootSpeed = 0f; item.useAmmo = 931; } public override void SetStaticDefaults() { DisplayName.SetDefault("Lava Gun"); Tooltip.SetDefault("Uses Flares, now also made at the MegaCorp Vendor with Musket Balls.\nOriginally from Ratchet and Clank: Going Commando."); } public override bool Shoot(Player player, ref Microsoft.Xna.Framework.Vector2 position, ref float speedX, ref float speedY, ref int type, ref int damage, ref float knockBack) { type = mod.ProjectileType("LavaGun"); return true; } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(null, "MeteoriteBolt", 50); recipe.AddIngredient(ItemID.LavaBucket); recipe.AddTile(null, "MegaCorpVendor"); recipe.SetResult(this, 1); recipe.AddRecipe(); } public override void UpdateInventory(Player player) { CheezePlayer.sellFlare = true; base.UpdateInventory(player); } public override bool ConsumeAmmo(Player p) { return Main.rand.Next(10) < 1; // 90% not to consume ammo. } } }
Cheezegami/Mod-Sources-Cheezes-Content-Pack
CheezeMod/Items/Weapons/Ratchet/LavaGun.cs
C#
gpl-3.0
2,175
<?php use_helper('Date', 'Text', 'I18N', 'myWidgets', 'enMessageBox'); ?> <div class="page-header"> <h1><?php echo __('Usuários do sistema') ?></h1> </div> <?php if ($sf_request->hasParameter('name')) : ?> <div class="msg alert"><?php echo __('Procurando pelo termo') ?> <strong>"<?php echo $sf_request->getParameter('name')?>"</strong></div> <?php endif ?> <table class="table table-striped"> <thead> <tr> <?php $dir = ($dir == 'asc')?'desc':'asc'; ?> <th><?php echo link_to(__('Usuário'), 'users/index?order='.sfGuardUserPeer::USERNAME.'&dir='.$dir, array ('class' => ($order == sfGuardUserPeer::USERNAME ? $dir : ''))) ?></th> <th><?php echo link_to(__('Nome'), 'users/index?order='.sfGuardUserProfilePeer::NAME.'&dir='.$dir, array ('class' => ($order == sfGuardUserProfilePeer::NAME ? $dir : ''))) ?></th> <th><?php echo link_to(__('Ativo?'), 'users/index?order='.sfGuardUserPeer::IS_ACTIVE.'&dir='.$dir, array ('class' => ($order == sfGuardUserPeer::IS_ACTIVE ? $dir : ''))) ?></th> <th><?php echo link_to(__('Último acesso'), 'users/index?order='.sfGuardUserPeer::LAST_LOGIN.'&dir='.$dir, array ('class' => ($order == sfGuardUserPeer::LAST_LOGIN ? $dir : ''))) ?></th> <th><?php echo __('Ações') ?></th> </tr> </thead> <tbody> <?php foreach ($users->getResults() as $user) : ?> <tr> <td><?php echo $user[1] ?></td> <td><?php echo truncate_text($user[3]) ?></td> <td><?php echo ($user[5] ? '<i class="icon-ok-sign"></i>' : '<i class="icon-remove-sign"></i>') ?></td> <td><?php echo en_distance_of_time_in_words($user[4]) ?></td> <?php if ($sf_user->hasCredential('users')) : ?> <td class="ctrls"> <div class="btn-group"> <?php echo link_to('<i class="icon-pencil"></i> editar', 'users/edit?id=' . $user[0], array ('class' => 'btn btn-mini btn-info')) ?> <?php echo ($user[1] == 'admin') ? '' : link_to('<i class="icon-remove-sign"></i> excluir', 'users/delete?id=' . $user[0], array ('class' => 'btn btn-mini btn-danger')) ?> </div> </td> <?php else : ?> <td></td> <?php endif; ?> </tr> <?php endforeach; ?> <?php if (!$users->getNbResults()) : ?> <tr> <td colspan="5" class="emptyCell"><?php echo __('Nenhum usuário encontrado') ?></td> </tr> <?php endif; ?> </tbody> </table> <?php echo form_pager_display($users, "users/index?page="); ?>
jeffersonmolleri/sesra
apps/adm/modules/users/templates/_list.php
PHP
gpl-3.0
2,540
/** * This file is part of da2i-boggle. * * da2i-boggle 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. * * da2i-boggle 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 da2i-boggle. If not, see <http://www.gnu.org/licenses/>. * * @author Edouard CATTEZ <edouard.cattez@sfr.fr> (La 7 Production) */ package boggle.gui.decorateur; import javax.swing.JButton; /** * Ajoute une décoration sur un JButton. */ public class DecorateurBouton extends JButton { private static final long serialVersionUID = 772827254096143798L; public DecorateurBouton(JButton bouton) { super(bouton.getText()); } }
ecattez/da2i-boggle
sources/boggle/gui/decorateur/DecorateurBouton.java
Java
gpl-3.0
1,109
package de.metalcon.imageServer.protocol; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; import de.metalcon.imageStorageServer.protocol.ProtocolConstants; import de.metalcon.imageStorageServer.protocol.read.ReadResponse; import de.metalcon.imageStorageServer.protocol.read.ReadScaledRequest; import de.metalcon.utils.formItemList.FormItemList; public class ReadScaledRequestTest extends RequestTest { private ReadScaledRequest readScaledRequest; private void fillRequest( final String imageIdentifier, final String width, final String height) { FormItemList formItemList = new FormItemList(); if (imageIdentifier != null) { formItemList.addField( ProtocolConstants.Parameters.Read.IMAGE_IDENTIFIER, imageIdentifier); } if (width != null) { formItemList.addField( ProtocolConstants.Parameters.Read.IMAGE_WIDTH, width); } if (height != null) { formItemList.addField( ProtocolConstants.Parameters.Read.IMAGE_HEIGHT, height); } final ReadResponse readResponse = new ReadResponse(); readScaledRequest = ReadScaledRequest.checkRequest(formItemList, readResponse); extractJson(readResponse); } @Test public void testReadScaledRequest() { fillRequest(VALID_IDENTIFIER, ProtocolTestConstants.VALID_SCALING_WIDTH, ProtocolTestConstants.VALID_SCALING_HEIGHT); assertNotNull(readScaledRequest); assertEquals(VALID_IDENTIFIER, readScaledRequest.getImageIdentifier()); assertEquals(ProtocolTestConstants.VALID_SCALING_WIDTH, String.valueOf(readScaledRequest.getImageWidth())); assertEquals(ProtocolTestConstants.VALID_SCALING_HEIGHT, String.valueOf(readScaledRequest.getImageHeight())); } @Test public void testImageIdentifierMissing() { fillRequest(null, ProtocolTestConstants.VALID_SCALING_WIDTH, ProtocolTestConstants.VALID_SCALING_HEIGHT); checkForMissingParameterMessage(ProtocolConstants.Parameters.Read.IMAGE_IDENTIFIER); assertNull(readScaledRequest); } @Test public void testWidthMissing() { fillRequest(VALID_IDENTIFIER, null, ProtocolTestConstants.VALID_SCALING_HEIGHT); checkForMissingParameterMessage(ProtocolConstants.Parameters.Read.IMAGE_WIDTH); assertNull(readScaledRequest); } @Test public void testWidthMalformed() { fillRequest(VALID_IDENTIFIER, ProtocolTestConstants.MALFORMED_SCALING_VALUE, ProtocolTestConstants.VALID_SCALING_HEIGHT); checkForStatusMessage(ProtocolConstants.StatusMessage.Read.SCALING_WIDTH_MALFORMED); assertNull(readScaledRequest); } @Test public void testWidthInvalid() { fillRequest(VALID_IDENTIFIER, ProtocolTestConstants.INVALID_SCALING_WIDTH, ProtocolTestConstants.VALID_SCALING_HEIGHT); checkForStatusMessage(ProtocolConstants.StatusMessage.Read.SCALING_WIDTH_INVALID); assertNull(readScaledRequest); } @Test public void testHeightMissing() { fillRequest(VALID_IDENTIFIER, ProtocolTestConstants.VALID_SCALING_WIDTH, null); checkForMissingParameterMessage(ProtocolConstants.Parameters.Read.IMAGE_HEIGHT); assertNull(readScaledRequest); } @Test public void testHeightMalformed() { fillRequest(VALID_IDENTIFIER, ProtocolTestConstants.VALID_SCALING_WIDTH, ProtocolTestConstants.MALFORMED_SCALING_VALUE); checkForStatusMessage(ProtocolConstants.StatusMessage.Read.SCALING_HEIGHT_MALFORMED); assertNull(readScaledRequest); } @Test public void testHeightInvalid() { fillRequest(VALID_IDENTIFIER, ProtocolTestConstants.VALID_SCALING_WIDTH, ProtocolTestConstants.INVALID_SCALING_HEIGHT); checkForStatusMessage(ProtocolConstants.StatusMessage.Read.SCALING_HEIGHT_INVALID); assertNull(readScaledRequest); } }
Metalcon/imageStorageServer
src/test/java/de/metalcon/imageServer/protocol/ReadScaledRequestTest.java
Java
gpl-3.0
4,366
package tk.natallymp.ratingimages; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { private String url_image; private ImageView imageView1; private EditText edit_message1; private ImageButton imageButton2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edit_message1 = (EditText) findViewById(R.id.edit_message); WebView webView = (WebView) findViewById(R.id.web_view1); webView.loadUrl("http://ya.ru"); imageView1 = (ImageView) findViewById(R.id.imageView1); imageView1.setClickable(true); imageView1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toLink("https://mail.ru"); } }); } public void onClickGO(View v){ String url_image = edit_message1.getText().toString(); //вывод картинки в imageview Picasso .with(this) .load(url_image) .placeholder(R.drawable.errormessage) .error(R.drawable.errormessage) .into(imageView1); } public void onClick_go_url(View v) { String url_image = edit_message1.getText().toString(); toLink(url_image); } //перейти по ссылке рабочи код private void toLink(String url){ Uri address = Uri.parse(url); Intent openlinkIntent = new Intent(Intent.ACTION_VIEW, address); startActivity(openlinkIntent); } }
x2wing/android
RatingImages/app/src/main/java/tk/natallymp/ratingimages/MainActivity.java
Java
gpl-3.0
1,981
""" ============================ ``ctypes`` Utility Functions ============================ See Also --------- load_library : Load a C library. ndpointer : Array restype/argtype with verification. as_ctypes : Create a ctypes array from an ndarray. as_array : Create an ndarray from a ctypes array. References ---------- .. [1] "SciPy Cookbook: ctypes", http://www.scipy.org/Cookbook/Ctypes Examples -------- Load the C library: >>> _lib = np.ctypeslib.load_library('libmystuff', '.') #doctest: +SKIP Our result type, an ndarray that must be of type double, be 1-dimensional and is C-contiguous in memory: >>> array_1d_double = np.ctypeslib.ndpointer( ... dtype=np.double, ... ndim=1, flags='CONTIGUOUS') #doctest: +SKIP Our C-function typically takes an array and updates its values in-place. For example:: void foo_func(double* x, int length) { int i; for (i = 0; i < length; i++) { x[i] = i*i; } } We wrap it using: >>> _lib.foo_func.restype = None #doctest: +SKIP >>> _lib.foo_func.argtypes = [array_1d_double, c_int] #doctest: +SKIP Then, we're ready to call ``foo_func``: >>> out = np.empty(15, dtype=np.double) >>> _lib.foo_func(out, len(out)) #doctest: +SKIP """ from __future__ import division, absolute_import, print_function __all__ = ['load_library', 'ndpointer', 'test', 'ctypes_load_library', 'c_intp', 'as_ctypes', 'as_array'] import sys, os from numpy import integer, ndarray, dtype as _dtype, deprecate, array from numpy.core.multiarray import _flagdict, flagsobj try: import ctypes except ImportError: ctypes = None if ctypes is None: def _dummy(*args, **kwds): """ Dummy object that raises an ImportError if ctypes is not available. Raises ------ ImportError If ctypes is not available. """ raise ImportError("ctypes is not available.") ctypes_load_library = _dummy load_library = _dummy as_ctypes = _dummy as_array = _dummy from numpy import intp as c_intp _ndptr_base = object else: import numpy.core._internal as nic c_intp = nic._getintp_ctype() del nic _ndptr_base = ctypes.c_void_p # Adapted from Albert Strasheim def load_library(libname, loader_path): if ctypes.__version__ < '1.0.1': import warnings warnings.warn("All features of ctypes interface may not work " \ "with ctypes < 1.0.1") ext = os.path.splitext(libname)[1] if not ext: # Try to load library with platform-specific name, otherwise # default to libname.[so|pyd]. Sometimes, these files are built # erroneously on non-linux platforms. from numpy.distutils.misc_util import get_shared_lib_extension so_ext = get_shared_lib_extension() libname_ext = [libname + so_ext] # mac, windows and linux >= py3.2 shared library and loadable # module have different extensions so try both so_ext2 = get_shared_lib_extension(is_python_ext=True) if not so_ext2 == so_ext: libname_ext.insert(0, libname + so_ext2) try: import sysconfig so_ext3 = '.%s-%s.so' % (sysconfig.get_config_var('SOABI'), sysconfig.get_config_var('MULTIARCH')) libname_ext.insert(0, libname + so_ext3) except (KeyError, ImportError): pass else: libname_ext = [libname] loader_path = os.path.abspath(loader_path) if not os.path.isdir(loader_path): libdir = os.path.dirname(loader_path) else: libdir = loader_path for ln in libname_ext: libpath = os.path.join(libdir, ln) if os.path.exists(libpath): try: return ctypes.cdll[libpath] except OSError: ## defective lib file raise ## if no successful return in the libname_ext loop: raise OSError("no file with expected extension") ctypes_load_library = deprecate(load_library, 'ctypes_load_library', 'load_library') def _num_fromflags(flaglist): num = 0 for val in flaglist: num += _flagdict[val] return num _flagnames = ['C_CONTIGUOUS', 'F_CONTIGUOUS', 'ALIGNED', 'WRITEABLE', 'OWNDATA', 'UPDATEIFCOPY'] def _flags_fromnum(num): res = [] for key in _flagnames: value = _flagdict[key] if (num & value): res.append(key) return res class _ndptr(_ndptr_base): def _check_retval_(self): """This method is called when this class is used as the .restype asttribute for a shared-library function. It constructs a numpy array from a void pointer.""" return array(self) @property def __array_interface__(self): return {'descr': self._dtype_.descr, '__ref': self, 'strides': None, 'shape': self._shape_, 'version': 3, 'typestr': self._dtype_.descr[0][1], 'data': (self.value, False), } @classmethod def from_param(cls, obj): if not isinstance(obj, ndarray): raise TypeError("argument must be an ndarray") if cls._dtype_ is not None \ and obj.dtype != cls._dtype_: raise TypeError("array must have data type %s" % cls._dtype_) if cls._ndim_ is not None \ and obj.ndim != cls._ndim_: raise TypeError("array must have %d dimension(s)" % cls._ndim_) if cls._shape_ is not None \ and obj.shape != cls._shape_: raise TypeError("array must have shape %s" % str(cls._shape_)) if cls._flags_ is not None \ and ((obj.flags.num & cls._flags_) != cls._flags_): raise TypeError("array must have flags %s" % _flags_fromnum(cls._flags_)) return obj.ctypes # Factory for an array-checking class with from_param defined for # use with ctypes argtypes mechanism _pointer_type_cache = {} def ndpointer(dtype=None, ndim=None, shape=None, flags=None): """ Array-checking restype/argtypes. An ndpointer instance is used to describe an ndarray in restypes and argtypes specifications. This approach is more flexible than using, for example, ``POINTER(c_double)``, since several restrictions can be specified, which are verified upon calling the ctypes function. These include data type, number of dimensions, shape and flags. If a given array does not satisfy the specified restrictions, a ``TypeError`` is raised. Parameters ---------- dtype : data-type, optional Array data-type. ndim : int, optional Number of array dimensions. shape : tuple of ints, optional Array shape. flags : str or tuple of str Array flags; may be one or more of: - C_CONTIGUOUS / C / CONTIGUOUS - F_CONTIGUOUS / F / FORTRAN - OWNDATA / O - WRITEABLE / W - ALIGNED / A - UPDATEIFCOPY / U Returns ------- klass : ndpointer type object A type object, which is an ``_ndtpr`` instance containing dtype, ndim, shape and flags information. Raises ------ TypeError If a given array does not satisfy the specified restrictions. Examples -------- >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64, ... ndim=1, ... flags='C_CONTIGUOUS')] ... #doctest: +SKIP >>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64)) ... #doctest: +SKIP """ if dtype is not None: dtype = _dtype(dtype) num = None if flags is not None: if isinstance(flags, str): flags = flags.split(',') elif isinstance(flags, (int, integer)): num = flags flags = _flags_fromnum(num) elif isinstance(flags, flagsobj): num = flags.num flags = _flags_fromnum(num) if num is None: try: flags = [x.strip().upper() for x in flags] except: raise TypeError("invalid flags specification") num = _num_fromflags(flags) try: return _pointer_type_cache[(dtype, ndim, shape, num)] except KeyError: pass if dtype is None: name = 'any' elif dtype.names: name = str(id(dtype)) else: name = dtype.str if ndim is not None: name += "_%dd" % ndim if shape is not None: try: strshape = [str(x) for x in shape] except TypeError: strshape = [str(shape)] shape = (shape,) shape = tuple(shape) name += "_"+"x".join(strshape) if flags is not None: name += "_"+"_".join(flags) else: flags = [] klass = type("ndpointer_%s"%name, (_ndptr,), {"_dtype_": dtype, "_shape_" : shape, "_ndim_" : ndim, "_flags_" : num}) _pointer_type_cache[dtype] = klass return klass if ctypes is not None: ct = ctypes ################################################################ # simple types # maps the numpy typecodes like '<f8' to simple ctypes types like # c_double. Filled in by prep_simple. _typecodes = {} def prep_simple(simple_type, dtype): """Given a ctypes simple type, construct and attach an __array_interface__ property to it if it does not yet have one. """ try: simple_type.__array_interface__ except AttributeError: pass else: return typestr = _dtype(dtype).str _typecodes[typestr] = simple_type def __array_interface__(self): return {'descr': [('', typestr)], '__ref': self, 'strides': None, 'shape': (), 'version': 3, 'typestr': typestr, 'data': (ct.addressof(self), False), } simple_type.__array_interface__ = property(__array_interface__) simple_types = [ ((ct.c_byte, ct.c_short, ct.c_int, ct.c_long, ct.c_longlong), "i"), ((ct.c_ubyte, ct.c_ushort, ct.c_uint, ct.c_ulong, ct.c_ulonglong), "u"), ((ct.c_float, ct.c_double), "f"), ] # Prep that numerical ctypes types: for types, code in simple_types: for tp in types: prep_simple(tp, "%c%d" % (code, ct.sizeof(tp))) ################################################################ # array types _ARRAY_TYPE = type(ct.c_int * 1) def prep_array(array_type): """Given a ctypes array type, construct and attach an __array_interface__ property to it if it does not yet have one. """ try: array_type.__array_interface__ except AttributeError: pass else: return shape = [] ob = array_type while type(ob) is _ARRAY_TYPE: shape.append(ob._length_) ob = ob._type_ shape = tuple(shape) ai = ob().__array_interface__ descr = ai['descr'] typestr = ai['typestr'] def __array_interface__(self): return {'descr': descr, '__ref': self, 'strides': None, 'shape': shape, 'version': 3, 'typestr': typestr, 'data': (ct.addressof(self), False), } array_type.__array_interface__ = property(__array_interface__) def prep_pointer(pointer_obj, shape): """Given a ctypes pointer object, construct and attach an __array_interface__ property to it if it does not yet have one. """ try: pointer_obj.__array_interface__ except AttributeError: pass else: return contents = pointer_obj.contents dtype = _dtype(type(contents)) inter = {'version': 3, 'typestr': dtype.str, 'data': (ct.addressof(contents), False), 'shape': shape} pointer_obj.__array_interface__ = inter ################################################################ # public functions def as_array(obj, shape=None): """Create a numpy array from a ctypes array or a ctypes POINTER. The numpy array shares the memory with the ctypes object. The size parameter must be given if converting from a ctypes POINTER. The size parameter is ignored if converting from a ctypes array """ tp = type(obj) try: tp.__array_interface__ except AttributeError: if hasattr(obj, 'contents'): prep_pointer(obj, shape) else: prep_array(tp) return array(obj, copy=False) def as_ctypes(obj): """Create and return a ctypes object from a numpy array. Actually anything that exposes the __array_interface__ is accepted.""" ai = obj.__array_interface__ if ai["strides"]: raise TypeError("strided arrays not supported") if ai["version"] != 3: raise TypeError("only __array_interface__ version 3 supported") addr, readonly = ai["data"] if readonly: raise TypeError("readonly arrays unsupported") tp = _typecodes[ai["typestr"]] for dim in ai["shape"][::-1]: tp = tp * dim result = tp.from_address(addr) result.__keep = ai return result
ruibarreira/linuxtrail
usr/lib/python2.7/dist-packages/numpy/ctypeslib.py
Python
gpl-3.0
14,076
/* * Platformer Game Engine by Wohlstand, a free platform for game making * Copyright (c) 2014-2019 Vitaly Novichkov <admin@wohlnet.ru> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "engine_intproc.h" #include <PGE_File_Formats/file_formats.h> #include <common_features/main_window_ptr.h> #include <common_features/app_path.h> #include <common_features/logger.h> #include <QSharedPointer> static void base64_encode(QByteArray &out, const char *msg) { QByteArray ba(msg); out = ba.toBase64(); } static void base64_encode(QByteArray &out, QString &string) { QByteArray ba(string.toUtf8()); out = ba.toBase64(); } IntEngine::IntEngine() {} IntEngine::~IntEngine() {} void IntEngine::onData() { if(isWorking()) { QByteArray strdata = engine->readAllStandardOutput(); QByteArray msg = QByteArray::fromBase64(strdata); if(msg.startsWith("CMD:")) { char *msgP = msg.data() + 4; //"CMD:" LogDebug("ENGINE COMMAND: >>"); LogDebug(msgP); LogDebug("<<ENGINE COMMAND END"); if(strcmp(msgP, "CONNECT_TO_ENGINE") == 0) sendLevelBuffer(); else if(strcmp(msgP, "ENGINE_CLOSED") == 0) { MainWinConnect::pMainWin->show(); MainWinConnect::pMainWin->raise(); } } else emit engineInputMsg(QString::fromUtf8(msg)); } } LevelData IntEngine::testBuffer; QProcess *IntEngine::engine = nullptr; static QSharedPointer<IntEngine> IntEngine_helper(nullptr); void IntEngine::init(QProcess *engine_proc) { if(IntEngine_helper.isNull()) IntEngine_helper = QSharedPointer<IntEngine>(new IntEngine); if(!engine) { engine = engine_proc; engine->connect(engine, SIGNAL(readyReadStandardOutput()), &(*IntEngine_helper), SLOT(onData())); } } void IntEngine::quit() { FileFormats::CreateLevelData(testBuffer); if(engine) engine->close(); engine = nullptr; } bool IntEngine::isWorking() { return ((engine != nullptr) && (engine->state() == QProcess::Running)); } bool IntEngine::sendCheat(QString _args) { if(isWorking()) { if(_args.isEmpty()) return false; _args.replace('\n', "\\n"); QString out = QString("CHEAT: %1").arg(_args); return sendMessage(out); } else return false; } bool IntEngine::sendMessageBox(QString _args) { if(isWorking()) { if(_args.isEmpty()) return false; _args.replace('\n', "\\n"); QString out = QString("MSGBOX: %1").arg(_args); return sendMessage(out); } else return false; } bool IntEngine::sendItemPlacing(QString _args) { if(isWorking()) { LogDebug("ENGINE: Place item command: " + _args); QString out = QString("PLACEITEM: %1").arg(_args); bool ret = sendMessage(out); return ret; } return false; } void IntEngine::sendLevelBuffer() { if(isWorking()) { LogDebug("Attempt to send LVLX buffer"); QString output; FileFormats::WriteExtendedLvlFileRaw(testBuffer, output); QString sendLvlx; if(!testBuffer.meta.path.isEmpty()) sendLvlx = QString("SEND_LVLX: %1/%2\n") .arg(testBuffer.meta.path) .arg(testBuffer.meta.filename + ".lvlx"); else sendLvlx = QString("SEND_LVLX: %1/%2\n") .arg(ApplicationPath) .arg("_untitled.lvlx"); if(output.size() <= 0) output = "HEAD\nEMPTY:1\nHEAD_END\n"; //#ifdef DEBUG_BUILD // qDebug() << "Sent File data BEGIN >>>>>>>>>>>\n" << output << "\n<<<<<<<<<<<<Sent File data END"; //#endif sendMessage(sendLvlx); QByteArray output_e; base64_encode(output_e, output); output_e.append('\n'); engine->write(output_e); sendMessage("PARSE_LVLX"); LogDebug("LVLX buffer sent"); } } void IntEngine::setTestLvlBuffer(LevelData &buffer) { testBuffer = buffer; } bool IntEngine::sendMessage(const char *msg) { if(!isWorking()) return false; QByteArray output_e; base64_encode(output_e, msg); output_e.append('\n'); return (engine->write(output_e) > 0); } bool IntEngine::sendMessage(QString &msg) { if(!isWorking()) return false; QByteArray output_e; base64_encode(output_e, msg); output_e.append('\n'); return (engine->write(output_e) > 0); }
Wohlhabend-Networks/PGE-Project
Editor/networking/engine_intproc.cpp
C++
gpl-3.0
5,233
/* Copyright © 2018 Maksim Lukyanov This file is part of Cross++ Game Engine. Cross++ Game Engine 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. Cross++ 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 Cross++. If not, see <http://www.gnu.org/licenses/> */ #include "Cubemap.h" #include "Texture.h" #include "Internals/GraphicsGL.h" using namespace cross; Cubemap::Cubemap( const String& right, const String& left, const String& top, const String& bottom, const String& back, const String& front) { SAFE(glGenTextures(1, (GLuint*)&textureID)); SAFE(glActiveTexture(GL_TEXTURE0)); SAFE(glBindTexture(GL_TEXTURE_CUBE_MAP, (GLuint)textureID)); int width, height, channels; Byte* image; image = Texture::LoadRawData(right, width, height, channels); SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image)); //delete[] image; image = Texture::LoadRawData(left, width, height, channels); SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 1, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image)); //delete image; image = Texture::LoadRawData(top, width, height, channels); SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 2, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image)); //delete image; image = Texture::LoadRawData(bottom, width, height, channels); SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 3, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image)); //delete image; image = Texture::LoadRawData(back, width, height, channels); SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 4, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image)); //delete image; image = Texture::LoadRawData(front, width, height, channels); SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 5, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image)); //delete image; SAFE(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); SAFE(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); SAFE(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); SAFE(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); SAFE(glBindTexture(GL_TEXTURE_CUBE_MAP, 0)); } Cubemap::~Cubemap(){ SAFE(glDeleteTextures(1, (GLuint*)&textureID)); } U64 Cubemap::GetTextureID() const{ return textureID; }
maxon887/Cross
Sources/Utils/Cubemap.cpp
C++
gpl-3.0
2,855
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class enteventsEntityResize : redEvent { [Ordinal(0)] [RED("extents")] public Vector3 Extents { get; set; } public enteventsEntityResize(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/enteventsEntityResize.cs
C#
gpl-3.0
355
package com.ernstlustig.faeries.jei.FaeryProducts; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.IDrawable; import mezz.jei.api.gui.IGuiItemStackGroup; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.recipe.IRecipeCategory; import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import javax.annotation.Nonnull; import java.awt.*; import java.util.*; import java.util.List; public class FaeryProductsCategory implements IRecipeCategory<FaeryProductsWrapper> { @Nonnull private final IDrawable background; @Nonnull private final String localizedName; public FaeryProductsCategory(IGuiHelper guiHelper) { ResourceLocation location = new ResourceLocation( "faeries", "textures/gui/guifaeryhousejei.png" ); background = guiHelper.createDrawable( location, 0, 0, 163, 55, 0, 0, 0, 0 ); //guiHelper.createDrawable( location, 8, 5, 163, 55, 0, 0, 0, 0 ); localizedName = "Faery Products"; //Translate } @Nonnull @Override public IDrawable getBackground() { return background; } @Override public void drawExtras( @Nonnull Minecraft minecraft ) { } @Override public void drawAnimations( @Nonnull Minecraft minecraft ) { } @Nonnull @Override public String getUid() { return "faeries.products"; } @Nonnull @Override public String getTitle() { return localizedName; } @Override public void setRecipe( @Nonnull IRecipeLayout recipeLayout, @Nonnull FaeryProductsWrapper recipeWrapper ){ IGuiItemStackGroup itemStacks = recipeLayout.getItemStacks(); itemStacks.init( 0, true, 9, 0 ); itemStacks.setFromRecipe( 0, recipeWrapper.getInputs().get(0) ); int i = 0; for( ItemStack is : recipeWrapper.getOutputs() ){ i++; itemStacks.init( i, true, 65 + 20 * ( ( i - 1 ) % 5 ), 27 * ( ( i - 1 ) / 5 ) ); itemStacks.setFromRecipe( i, is ); } } }
davqvist/Faeries
src/main/java/com/ernstlustig/faeries/jei/FaeryProducts/FaeryProductsCategory.java
Java
gpl-3.0
2,053
using Aperture.Parser.HTML.Microsyntaxes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aperture.Parser.HTML { /// <summary> /// Case-sensitivity and string comparison. /// </summary> public static class StringComparisons // Must end with s to avoid ambiguity { // with System.StringComparison // HTML spec 2.3 Case-sensitivity and string comparisons public static bool CompareCaseSensitive(string str1, string str2) { return str1 == str2; } /// <summary> /// Compares strings, where A-Z == a-z. /// </summary> public static bool CompareASCIICaseInsensitive(string str1, string str2) { return ConvertToASCIILowercase(str1) == ConvertToASCIILowercase(str2); } /// <summary> /// Unicode string comparing, with no regard for capitalization. /// </summary> public static bool CompareCompatibilityCaseless(string str1, string str2) { // Unicode spec version 7.0, page 158, D146 // TODO: ToLowerInvariant() may not match the spec's toCasefold method exactly. return str1.Normalize(NormalizationForm.FormD) .ToLowerInvariant() .Normalize(NormalizationForm.FormKD) .ToLowerInvariant() .Normalize(NormalizationForm.FormKD) == str2.Normalize(NormalizationForm.FormD) .ToLowerInvariant() .Normalize(NormalizationForm.FormKD) .ToLowerInvariant() .Normalize(NormalizationForm.FormKD); } /// <summary> /// Converts a-z to A-Z. /// </summary> public static string ConvertToASCIIUppercase(string input) { char[] inputArr = input.ToCharArray(); for (int i = 0; i < inputArr.Length; i++) { if (ParserIdioms.LowercaseASCIILetters.Contains(inputArr[i])) { int charIndex = Array.IndexOf( ParserIdioms.LowercaseASCIILetters, inputArr[i]); inputArr[i] = ParserIdioms.UppercaseASCIILetters[charIndex]; } } return new string(inputArr); } /// <summary> /// Converts A-Z to a-z. /// </summary> public static string ConvertToASCIILowercase(string input) { char[] inputArr = input.ToCharArray(); for (int i = 0; i < inputArr.Length; i++) { if (ParserIdioms.UppercaseASCIILetters.Contains(inputArr[i])) { int charIndex = Array.IndexOf( ParserIdioms.UppercaseASCIILetters, inputArr[i]); inputArr[i] = ParserIdioms.LowercaseASCIILetters[charIndex]; } } return new string(inputArr); } } }
Pneumaticat/Aperture
Aperture.Parser/HTML/StringComparisons.cs
C#
gpl-3.0
3,096