repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
eaglgenes101/universalSmashSystem
engine/network.py
17430
import socket import json import select import random import pygame import settingsManager import time class NetworkEvt(object): pass#empty, for deserialising, attributes are added from json class NetworkUpdateMessage(object): def __init__(self): self.status = "u" self.json = "{}" self.type = 0 self.frame = 0 def toString(self): return self.status+"_"+str(self.type)+"_"+str(self.frame)+"_"+self.json def isValid(self,msg): return (len(msg)>1 and msg[0] == "u" and msg.count("_")==3) def isBlank(self): return self.type == 0 def fromString(self,msg): evt = NetworkEvt() evtSplit = msg.split("_") self.status = evtSplit[0] self.type = int(evtSplit[1]) self.frame = int(evtSplit[2]) self.json = evtSplit[3] evt.type = self.type jsondict = json.loads(self.json).items() for attr,val in jsondict: setattr(evt,attr,val) return evt def update(self,_type,_json,_frame): self.json = _json self.type = _type self.frame = _frame class NetworkTickMessage(object): def __init__(self): self.status = "t" self.json = "" self.tick = 0 def isValid(self,msg): return (len(msg)>1 and msg[0] == "t" and msg.count("_")==2) def fromString(self,msg): evtSplit = msg.split("_") self.status = evtSplit[0] self.tick = int(evtSplit[1]) self.json = evtSplit[2] return self class NetworkFighterMessage(object): def __init__(self): self.status = "f" self.frame = 0 self.json = "" def setFighter(self,_frame,_fighterAttrs): self.frame = _frame self.json = json.dumps(_fighterAttrs) def isValid(self,msg): return (len(msg)>1 and msg[0] == "f" and msg.count("|")==2) def toString(self): return self.status+"|"+str(self.frame)+"|"+self.json def fromString(self,msg): evtSplit = msg.split("|") self.status = evtSplit[0] self.frame = int(evtSplit[1]) self.json = evtSplit[2] return self class NetworkProgressMessage(object): def __init__(self): self.status = "p" self.frame = 0 def isValid(self,msg): return (len(msg)>1 and msg[0] == "p" and msg.count("_")==1) def toString(self): return self.status+"_"+str(self.frame) def fromString(self,msg): evtSplit = msg.split("_") self.status = evtSplit[0] self.frame = int(evtSplit[1]) return self class NetworkBufferEntry(object): def __init__(self): self.eventList = [] self.receivedFrom = {} def getEvents(self): self.eventList = [] for k,v in self.receivedFrom.items(): for e in v: self.eventList.append(e) return self.eventList class Network(object): def send(self,msg,target): if(self.connect_mode == self.SOCKET_MODE_UDP): self.conn.sendto(msg, target) if(self.connect_mode == self.SOCKET_MODE_TCP): if len(msg)<self.MESSAGE_SIZE:#fixed-width messages, could be made better by proper buffering msg='{message: <{fill}}'.format(message=msg, fill=self.MESSAGE_SIZE) else: print("message too long: "+str(len(msg))) self.conn.sendall(msg) #TODO: replace hard-coded ports/addresses/buffer/etc with configurable ones def __init__(self): self.settings = settingsManager.getSetting().setting #set to false to disable all networking and just run locally self.enabled = self.settings['networkEnabled'] if(self.enabled): self.MESSAGE_SIZE = 96 self.SOCKET_MODE_UDP = "udp" self.SOCKET_MODE_TCP = "tcp" self.connect_mode = self.settings['networkProtocol'] self.serveraddr = self.settings['networkServerIP'] self.serverport = self.settings['networkServerPort'] if(self.connect_mode == self.SOCKET_MODE_UDP): self.conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.conn.setblocking(0) self.clientport = random.randrange(self.settings['networkUDPClientPortMin'], self.settings['networkUDPClientPortMax']) self.conn.bind(("", self.clientport))#bind to everything. if(self.connect_mode == self.SOCKET_MODE_TCP): self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.conn.connect((self.serveraddr,self.serverport)) self.conn.setblocking(0) self.read_list = [self.conn] self.write_list = [] self.send("c", (self.serveraddr, self.serverport)) #count each frame with an id so that it can be identified when sent over the wire self.tick_count = 0 self.buffer_size = self.settings['networkBufferSize']#number of frames of latency to introduce locally (should be greater than the network latency) self.max_frame = self.buffer_size self.buffer = [NetworkBufferEntry() for x in range(self.buffer_size)] for x in self.buffer: x.receivedFrom['local']=[] self.fighter_buffer = [[] for x in range(self.buffer_size)] self.STATE_WAITING_FOR_OPPONENT = 0 self.STATE_PLAYING = 1 self.current_state = self.STATE_WAITING_FOR_OPPONENT self.playerno = 0 #TODO: on exit implement disconnect (message status "d" to server) #close TCP """ Creates a fake 'pipe' between the local event source (keyboard) and the network processing if networking is disabled, this method does nothing if networking is enabled, this method takes the local events and sends them over the network it also receives events from the network and appends them to the local queue Since this sends inputs per frame, if games are out of sync at the frame-level, this will diverge there is a number of frames as a buffer. Local input is pushed onto the end of the buffer at that stage the frame count is recorded and sent over the wire with the count when receiving inputs, insert them onto the buffer at the correct frame this assumes that latency never exceeds the number of frames in the buffer it also assumes the frame rate of each client is very close to being the same the game will be laggy to local input by the size of the buffer, but will be consistent ideally, the clients will be in sync as they would have the same frame rate. since this is unlikely in practice, each client sends to the server a request to progress to frame X where X = buffer_size when the server receives this from every player, it sends back an acknowldgeemnt that the client can progress if the client doesn't receive this, it stalls if the latency/frame rates of the clients never differs by more than buffer_size, then the games will play smoothly if one begins to get ahead by too much, the game will stutter. Sample code has been written to sync fighters in the case that the game diverges. This needs to be updated/enabled if it's needed. In theory syncing fighters would be a safety net to re-sync the state. (for example, in the case keyboard packets are lost over the network) In practice, this should be avoided if possible because it will cause fighters to jump around and it means tracking code changes to fighters in this class (making code slightly harder to maintain). Additioanlly it requires possible engine changes to allow state rollback/fast forward TODO: implement a translation layer between controls? player 1 keybindings on computer 1 should translate to player 2 keybindings on computer 2 """ def processEvents(self,events): if(not self.enabled): return events#not turned on, nothing to do #enqueue/dequeue from buffer bufferObj = NetworkBufferEntry() bufferObj.receivedFrom['local']=events self.buffer.insert(0,bufferObj)#enqueue event onto start of queue nextEventObj = self.buffer.pop()#dequeue the frame that's persisted the length of the queue nextEventList = nextEventObj.getEvents() self.sendBuffer() self.readFromNetwork() MAX_STALL_COUNT = 100#1 second max while(self.tick_count > self.max_frame and MAX_STALL_COUNT>=0): print("Stall at frame: "+str(self.tick_count)+" max: "+str(self.max_frame)) MAX_STALL_COUNT-=1 self.readFromNetwork() time.sleep(0.01)#wait 1/100th of a second before checking again. if(MAX_STALL_COUNT<0): print("Max stalls exceeded.") #TODO: lost connectivity? exit battle? if(self.current_state == self.STATE_WAITING_FOR_OPPONENT): return []#absorb events until players are ready #TODO: stop clock (game countdown timer) from progressing while waiting. self.tick_count += 1 return nextEventList def sendBuffer(self): bufferTicks = self.tick_count+(self.buffer_size) b = self.buffer[0] if('local' in b.receivedFrom): events = b.receivedFrom['local'] for e in events: #TODO: make this work for devices other than keyboard if e.type == pygame.locals.KEYDOWN or e.type == pygame.locals.KEYUP: #send input to others msgEvt = NetworkUpdateMessage() msgEvt.update(e.type,json.dumps(e.__dict__),bufferTicks) self.send(msgEvt.toString(), (self.serveraddr, self.serverport)) #print("sent input for frame: "+str(bufferTicks)+" current frame: "+str(self.tick_count)) #periodically send "progressing to frame X" if(self.tick_count % self.buffer_size == 0): msgProgress = NetworkProgressMessage() msgProgress.frame = self.tick_count + self.buffer_size self.send(msgProgress.toString(),(self.serveraddr, self.serverport)) def handleMessage(self, msg): msgEvt = NetworkUpdateMessage() msgTick = NetworkTickMessage() msgFighter = NetworkFighterMessage() msgProgress = NetworkProgressMessage() if(msgEvt.isValid(msg)): fromString = msgEvt.fromString(msg) receivedTime = msgEvt.frame #print("received input for frame: "+str(msgEvt.frame)+" current frame: "+str(self.tick_count)) frameDiff = self.buffer_size - (receivedTime - self.tick_count) if(frameDiff<self.buffer_size and frameDiff>=0): if(self.serveraddr not in self.buffer[frameDiff].receivedFrom):#initialise list self.buffer[frameDiff].receivedFrom[self.serveraddr] = [] if(not msgEvt.isBlank()): self.buffer[frameDiff].receivedFrom[self.serveraddr].append(fromString)#new entry, insert into buffer else: print("frame outside range"+str(msgEvt.frame)) if msgEvt.frame>=self.buffer_size: #Note: should never get here, it means frame rates are out of sync by a lot #but if we have hit this, try and re-sync frame count print(str(self.tick_count)+" adjusted to: "+str(msgEvt.frame-self.buffer_size+1)) self.tick_count = msgEvt.frame-self.buffer_size+1 if(msgTick.isValid(msg)): msgTick.fromString(msg) self.tick_count = msgTick.tick self.playerno = json.loads(msgTick.json)['playerno'] if(self.current_state == self.STATE_WAITING_FOR_OPPONENT): self.current_state = self.STATE_PLAYING print("starting") if(msgFighter.isValid(msg)): fromString = msgFighter.fromString(msg) receivedTime = msgFighter.frame frameDiff = receivedTime - self.tick_count if(frameDiff-1<self.buffer_size and frameDiff-1>-1): self.fighter_buffer[frameDiff-1].append(fromString)#insert into buffer if(msgProgress.isValid(msg)): fromString = msgProgress.fromString(msg) self.max_frame = fromString.frame def readFromNetwork(self): repeat = True while(repeat): repeat = False readable, writable, exceptional = ( select.select(self.read_list, self.write_list, [], 0) ) if self.connect_mode == self.SOCKET_MODE_UDP: for f in readable: if f is self.conn: msg,addr = f.recvfrom(self.MESSAGE_SIZE) repeat = True#may be more than 1 message waiting to be read, catch up by looping until select returns nothing self.handleMessage(msg) if self.connect_mode == self.SOCKET_MODE_TCP: for f in readable: if f is self.conn: msg,addr = f.recvfrom(self.MESSAGE_SIZE) msg = msg.strip() repeat = True self.handleMessage(msg) def processFighters(self,fighters): if(not self.enabled or not self.current_state == self.STATE_PLAYING or not self.tick_count%100 == 0): return None return None #TODO: enable by removing this statement. #NOTE: before this can be enabled, some work needs to be done on the frame counts #unlike the keyboard which can be predicted due to a local latency buffer #the fighter's position is only known at the current frame, #therefore by the time the opponent gets it the data is obsolete. #in theory the best way of handling this would be to roll state forward/back #the engine currently cannot do this #need to confirm minimal set params are that can capture fighter state #e.g. x,y, speed?, angle?, state?, gravity? friction? self.fighter_buffer.insert(0,[])#enqueue empty list to keep buffer the same size nextFighterList = self.fighter_buffer.pop()#dequeue the frame that's persisted the length of the queue if self.playerno == 1:#player 1 is authorotive - it will send, rest will receive for f in fighters: msg = NetworkFighterMessage() msg.setFighter(self.tick_count,{ 'rectX':f.rect.top, 'rectY':f.rect.left }) """ #'grounded' : f.grounded, #'back_walled' : f.back_walled, #'front_walled' : f.front_walled, #'ceilinged' : f.ceilinged, #'damage' : f.damage, #'landing_lag' : f.landing_lag, #'platform_phase' : f.platform_phase, #'tech_window' : f.tech_window, #'change_x' : f.change_x, #'change_y' : f.change_y, #'preferred_xspeed' : f.preferred_xspeed, #'preferred_yspeed' : f.preferred_yspeed, #'facing' : f.facing, #'no_flinch_hits' : f.no_flinch_hits, #'flinch_damage_threshold' : f.flinch_damage_threshold, #'flinch_knockback_threshold' : f.flinch_knockback_threshold, #'armor_damage_multiplier' : f.armor_damage_multiplier, #'invulnerable' : f.invulnerable, #'respawn_invulnerable' : f.respawn_invulnerable, #'shield' : f.shield, #'shield_integrity' : f.shield_integrity, #'hitstop' : f.hitstop, #'hitstop_vibration' : f.hitstop_vibration, #'hitstop_pos' : f.hitstop_pos, #'ledge_lock' : f.ledge_lock #jumps = var['jumps']#?? #airdodges = 1#?? #grabbing = None#?? #grabbed_by = None#?? #hit_tagged = None#??""" self.send(msg.toString(), (self.serveraddr, self.serverport)) for fighter_message in nextFighterList: fighter_data = json.loads(fighter_message.json).items() print("updating fighter"+str(fighter_data.frame)+" "+str(self.tick_count)) for f in fighters: for attr,val in fighter_data: if(attr == "rectX"): print("prev x was: "+str(f.rect.top)+" new: "+str(val)) f.rect.x = val continue if(attr == "rectY"): print("prev y was: "+str(f.rect.left)+" new: "+str(val)) f.rect.x = val continue setattr(f,attr,val)#currently completely broken
gpl-3.0
eraffxi/darkstar
scripts/globals/mobskills/airy_shield.lua
611
--------------------------------------------- -- Airy Shield -- -- Description: Ranged shield -- Type: Enhancing -- Utsusemi/Blink absorb: N/A -- Range: Self --------------------------------------------- require("scripts/globals/monstertpmoves"); require("scripts/globals/settings"); require("scripts/globals/status"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = dsp.effect.ARROW_SHIELD; skill:setMsg(MobBuffMove(mob, typeEffect, 1, 0, 60)); return typeEffect; end;
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c103950002.lua
2784
--Mecha Force: Delta function c103950002.initial_effect(c) --synchro summon aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1) c:EnableReviveLimit() --synchro summon success local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(103950002,1)) e1:SetCategory(CATEGORY_DRAW) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetCondition(c103950002.drcon) e1:SetTarget(c103950002.drtarg) e1:SetOperation(c103950002.drop) c:RegisterEffect(e1) --leaves field local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(103950002,2)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_LEAVE_FIELD) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e2:SetCondition(c103950002.spcon) e2:SetTarget(c103950002.sptg) e2:SetOperation(c103950002.spop) c:RegisterEffect(e2) end --Material group filter function c103950002.mgfilter(c) return c:IsRace(RACE_MACHINE) end --Drawing condition function c103950002.drcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:GetSummonType()~=SUMMON_TYPE_SYNCHRO or c:GetMaterialCount()<=0 then return false end local mg=c:GetMaterial() return mg:IsExists(c103950002.mgfilter,1,nil) end --Drawing target function c103950002.drtarg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end --Drawing function c103950002.drop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Draw(p,d,REASON_EFFECT) end --Special Summon condition function c103950002.spcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:GetSummonType()==SUMMON_TYPE_SYNCHRO and c:IsPreviousPosition(POS_FACEUP) and not c:IsLocation(LOCATION_DECK) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,103950003,0,0x4011,800,800,2,RACE_MACHINE,ATTRIBUTE_EARTH) end --Special Summon target function c103950002.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,2,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,0,0) end --Special Summon operation function c103950002.spop(e,tp,eg,ep,ev,re,r,rp) local token=Duel.CreateToken(tp,103950003) Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP_DEFENSE) if Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then if Duel.SelectYesNo(tp,aux.Stringid(103950002,5)) then local token2=Duel.CreateToken(tp,103950003) Duel.SpecialSummonStep(token2,0,tp,tp,false,false,POS_FACEUP_DEFENSE) end end Duel.SpecialSummonComplete() end
gpl-3.0
karrtikr/ete
ete3/parser/phylip.py
8131
from __future__ import absolute_import from __future__ import print_function # #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://etetoolkit.org # # ETE 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. # # ETE 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 ETE. If not, see <http://www.gnu.org/licenses/>. # # # ABOUT THE ETE PACKAGE # ===================== # # ETE is distributed under the GPL copyleft license (2008-2015). # # If you make use of ETE in published work, please cite: # # Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. # ETE: a python Environment for Tree Exploration. Jaime BMC # Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 # # Note that extra references to the specific methods implemented in # the toolkit may be available in the documentation. # # More info at http://etetoolkit.org. Contact: huerta@embl.de # # # #END_LICENSE############################################################# import os import re from sys import stderr as STDERR import six from six.moves import range def read_phylip(source, interleaved=True, obj=None, relaxed=False, fix_duplicates=True): if obj is None: from ..coretype import SeqGroup SG = SeqGroup() else: SG = obj # Prepares handle from which read sequences if os.path.isfile(source): if source.endswith('.gz'): import gzip _source = gzip.open(source) else: _source = open(source, "rU") else: _source = iter(source.split("\n")) nchar, ntax = None, None counter = 0 id_counter = 0 for line in _source: line = line.strip("\n") # Passes comments and blank lines if not line or line[0] == "#": continue # Reads head if not nchar or not ntax: m = re.match("^\s*(\d+)\s+(\d+)",line) if m: ntax = int (m.groups()[0]) nchar = int (m.groups()[1]) else: raise Exception("A first line with the alignment dimension is required") # Reads sequences else: if not interleaved: # Reads names and sequences if SG.id2name.get(id_counter, None) is None: if relaxed: m = re.match("^([^ ]+)(.+)", line) else: m = re.match("^(.{10})(.+)", line) if m: name = m.groups()[0].strip() if fix_duplicates and name in SG.name2id: tag = str(len([k for k in list(SG.name2id.keys()) \ if k.endswith(name)])) old_name = name # Tag is in the beginning to avoid being # cut it by the 10 chars limit name = tag+"_"+name print("Duplicated entry [%s] was renamed to [%s]" %\ (old_name, name), file=STDERR) SG.id2name[id_counter] = name SG.name2id[name] = id_counter SG.id2seq[id_counter] = "" line = m.groups()[1] else: raise Exception("Wrong phylip sequencial format.") SG.id2seq[id_counter] += re.sub("\s","", line) if len(SG.id2seq[id_counter]) == nchar: id_counter += 1 name = None elif len(SG.id2seq[id_counter]) > nchar: raise Exception("Unexpected length of sequence [%s] [%s]." %(name,SG.id2seq[id_counter])) else: if len(SG)<ntax: if relaxed: m = re.match("^([^ ]+)(.+)", line) else: m = re.match("^(.{10})(.+)",line) if m: name = m.groups()[0].strip() seq = re.sub("\s","",m.groups()[1]) SG.id2seq[id_counter] = seq SG.id2name[id_counter] = name if fix_duplicates and name in SG.name2id: tag = str(len([k for k in list(SG.name2id.keys()) \ if k.endswith(name)])) old_name = name name = tag+"_"+name print("Duplicated entry [%s] was renamed to [%s]" %\ (old_name, name), file=STDERR) SG.name2id[name] = id_counter id_counter += 1 else: raise Exception("Unexpected number of sequences.") else: seq = re.sub("\s", "", line) if id_counter == len(SG): id_counter = 0 SG.id2seq[id_counter] += seq id_counter += 1 if len(SG) != ntax: raise Exception("Unexpected number of sequences.") # Check lenght of all seqs for i in list(SG.id2seq.keys()): if len(SG.id2seq[i]) != nchar: raise Exception("Unexpected lenght of sequence [%s]" %SG.id2name[i]) return SG def write_phylip(aln, outfile=None, interleaved=True, relaxed=False): width = 60 seq_visited = set([]) show_name_warning = False lenghts = set((len(seq) for seq in list(aln.id2seq.values()))) if len(lenghts) >1: raise Exception("Phylip format requires sequences of equal lenght.") seqlength = lenghts.pop() if not relaxed: name_fix = 10 else: name_fix = max([len(name) for name in list(aln.id2name.values())]) alg_lines = [] alg_text = " %d %d" %(len(aln), seqlength) alg_lines.append(alg_text) if interleaved: visited = set([]) for i in range(0, seqlength, width): for j in six.iterkeys(aln.id2name): #xrange(len(aln)): name = aln.id2name[j] if not relaxed and len(name)>name_fix: name = name[:name_fix] show_name_warning = True seq = aln.id2seq[j][i:i+width] if j not in visited: name_str = "%s " %name.ljust(name_fix) visited.add(j) else: name_str = "".ljust(name_fix+3) seq_str = ' '.join([seq[k:k+10] for k in range(0, len(seq), 10)]) line_str = "%s%s" %(name_str, seq_str) alg_lines.append(line_str) alg_lines.append("") else: for name, seq, comments in aln.iter_entries(): if not relaxed and len(name)>10: name = name[:name_fix] show_name_warning = True line_str = "%s %s\n%s" %\ (name.ljust(name_fix), seq[0:width-name_fix-3], '\n'.join([seq[k:k+width] \ for k in range(width-name_fix-3, len(seq), width)])) alg_lines.append(line_str) alg_lines.append("") if show_name_warning: print("Warning! Some sequence names were cut to 10 characters!!", file=STDERR) alg_text = '\n'.join(alg_lines) if outfile is not None: OUT = open(outfile, "w") OUT.write(alg_text) OUT.close() else: return alg_text
gpl-3.0
hubert667/AIR
build/celery/celery/tests/app/test_app.py
23154
from __future__ import absolute_import import gc import os import itertools from copy import deepcopy from pickle import loads, dumps from amqp import promise from kombu import Exchange from celery import shared_task, current_app from celery import app as _app from celery import _state from celery.app import base as _appbase from celery.app import defaults from celery.exceptions import ImproperlyConfigured from celery.five import items from celery.loaders.base import BaseLoader from celery.platforms import pyimplementation from celery.utils.serialization import pickle from celery.tests.case import ( CELERY_TEST_CONFIG, AppCase, Mock, depends_on_current_app, mask_modules, patch, platform_pyimp, sys_platform, pypy_version, with_environ, ) from celery.utils import uuid from celery.utils.mail import ErrorMail THIS_IS_A_KEY = 'this is a value' class ObjectConfig(object): FOO = 1 BAR = 2 object_config = ObjectConfig() dict_config = dict(FOO=10, BAR=20) class ObjectConfig2(object): LEAVE_FOR_WORK = True MOMENT_TO_STOP = True CALL_ME_BACK = 123456789 WANT_ME_TO = False UNDERSTAND_ME = True class Object(object): def __init__(self, **kwargs): for key, value in items(kwargs): setattr(self, key, value) def _get_test_config(): return deepcopy(CELERY_TEST_CONFIG) test_config = _get_test_config() class test_module(AppCase): def test_default_app(self): self.assertEqual(_app.default_app, _state.default_app) def test_bugreport(self): self.assertTrue(_app.bugreport(app=self.app)) class test_App(AppCase): def setup(self): self.app.add_defaults(test_config) def test_task_autofinalize_disabled(self): with self.Celery('xyzibari', autofinalize=False) as app: @app.task def ttafd(): return 42 with self.assertRaises(RuntimeError): ttafd() with self.Celery('xyzibari', autofinalize=False) as app: @app.task def ttafd2(): return 42 app.finalize() self.assertEqual(ttafd2(), 42) def test_registry_autofinalize_disabled(self): with self.Celery('xyzibari', autofinalize=False) as app: with self.assertRaises(RuntimeError): app.tasks['celery.chain'] app.finalize() self.assertTrue(app.tasks['celery.chain']) def test_task(self): with self.Celery('foozibari') as app: def fun(): pass fun.__module__ = '__main__' task = app.task(fun) self.assertEqual(task.name, app.main + '.fun') def test_with_config_source(self): with self.Celery(config_source=ObjectConfig) as app: self.assertEqual(app.conf.FOO, 1) self.assertEqual(app.conf.BAR, 2) @depends_on_current_app def test_task_windows_execv(self): prev, _appbase._EXECV = _appbase._EXECV, True try: @self.app.task(shared=False) def foo(): pass self.assertTrue(foo._get_current_object()) # is proxy finally: _appbase._EXECV = prev assert not _appbase._EXECV def test_task_takes_no_args(self): with self.assertRaises(TypeError): @self.app.task(1) def foo(): pass def test_add_defaults(self): self.assertFalse(self.app.configured) _conf = {'FOO': 300} conf = lambda: _conf self.app.add_defaults(conf) self.assertIn(conf, self.app._pending_defaults) self.assertFalse(self.app.configured) self.assertEqual(self.app.conf.FOO, 300) self.assertTrue(self.app.configured) self.assertFalse(self.app._pending_defaults) # defaults not pickled appr = loads(dumps(self.app)) with self.assertRaises(AttributeError): appr.conf.FOO # add more defaults after configured conf2 = {'FOO': 'BAR'} self.app.add_defaults(conf2) self.assertEqual(self.app.conf.FOO, 'BAR') self.assertIn(_conf, self.app.conf.defaults) self.assertIn(conf2, self.app.conf.defaults) def test_connection_or_acquire(self): with self.app.connection_or_acquire(block=True): self.assertTrue(self.app.pool._dirty) with self.app.connection_or_acquire(pool=False): self.assertFalse(self.app.pool._dirty) def test_maybe_close_pool(self): cpool = self.app._pool = Mock() amqp = self.app.__dict__['amqp'] = Mock() ppool = amqp._producer_pool self.app._maybe_close_pool() cpool.force_close_all.assert_called_with() ppool.force_close_all.assert_called_with() self.assertIsNone(self.app._pool) self.assertIsNone(self.app.__dict__['amqp']._producer_pool) self.app._pool = Mock() self.app._maybe_close_pool() self.app._maybe_close_pool() def test_using_v1_reduce(self): self.app._using_v1_reduce = True self.assertTrue(loads(dumps(self.app))) def test_autodiscover_tasks_force(self): self.app.loader.autodiscover_tasks = Mock() self.app.autodiscover_tasks(['proj.A', 'proj.B'], force=True) self.app.loader.autodiscover_tasks.assert_called_with( ['proj.A', 'proj.B'], 'tasks', ) self.app.loader.autodiscover_tasks = Mock() self.app.autodiscover_tasks( lambda: ['proj.A', 'proj.B'], related_name='george', force=True, ) self.app.loader.autodiscover_tasks.assert_called_with( ['proj.A', 'proj.B'], 'george', ) def test_autodiscover_tasks_lazy(self): with patch('celery.signals.import_modules') as import_modules: packages = lambda: [1, 2, 3] self.app.autodiscover_tasks(packages) self.assertTrue(import_modules.connect.called) prom = import_modules.connect.call_args[0][0] self.assertIsInstance(prom, promise) self.assertEqual(prom.fun, self.app._autodiscover_tasks) self.assertEqual(prom.args[0](), [1, 2, 3]) @with_environ('CELERY_BROKER_URL', '') def test_with_broker(self): with self.Celery(broker='foo://baribaz') as app: self.assertEqual(app.conf.BROKER_URL, 'foo://baribaz') def test_repr(self): self.assertTrue(repr(self.app)) def test_custom_task_registry(self): with self.Celery(tasks=self.app.tasks) as app2: self.assertIs(app2.tasks, self.app.tasks) def test_include_argument(self): with self.Celery(include=('foo', 'bar.foo')) as app: self.assertEqual(app.conf.CELERY_IMPORTS, ('foo', 'bar.foo')) def test_set_as_current(self): current = _state._tls.current_app try: app = self.Celery(set_as_current=True) self.assertIs(_state._tls.current_app, app) finally: _state._tls.current_app = current def test_current_task(self): @self.app.task def foo(shared=False): pass _state._task_stack.push(foo) try: self.assertEqual(self.app.current_task.name, foo.name) finally: _state._task_stack.pop() def test_task_not_shared(self): with patch('celery.app.base.shared_task') as sh: @self.app.task(shared=False) def foo(): pass self.assertFalse(sh.called) def test_task_compat_with_filter(self): with self.Celery(accept_magic_kwargs=True) as app: check = Mock() def filter(task): check(task) return task @app.task(filter=filter, shared=False) def foo(): pass check.assert_called_with(foo) def test_task_with_filter(self): with self.Celery(accept_magic_kwargs=False) as app: check = Mock() def filter(task): check(task) return task assert not _appbase._EXECV @app.task(filter=filter, shared=False) def foo(): pass check.assert_called_with(foo) def test_task_sets_main_name_MP_MAIN_FILE(self): from celery import utils as _utils _utils.MP_MAIN_FILE = __file__ try: with self.Celery('xuzzy') as app: @app.task def foo(): pass self.assertEqual(foo.name, 'xuzzy.foo') finally: _utils.MP_MAIN_FILE = None def test_annotate_decorator(self): from celery.app.task import Task class adX(Task): abstract = True def run(self, y, z, x): return y, z, x check = Mock() def deco(fun): def _inner(*args, **kwargs): check(*args, **kwargs) return fun(*args, **kwargs) return _inner self.app.conf.CELERY_ANNOTATIONS = { adX.name: {'@__call__': deco} } adX.bind(self.app) self.assertIs(adX.app, self.app) i = adX() i(2, 4, x=3) check.assert_called_with(i, 2, 4, x=3) i.annotate() i.annotate() def test_apply_async_has__self__(self): @self.app.task(__self__='hello', shared=False) def aawsX(): pass with patch('celery.app.amqp.TaskProducer.publish_task') as dt: aawsX.apply_async((4, 5)) args = dt.call_args[0][1] self.assertEqual(args, ('hello', 4, 5)) def test_apply_async_adds_children(self): from celery._state import _task_stack @self.app.task(shared=False) def a3cX1(self): pass @self.app.task(shared=False) def a3cX2(self): pass _task_stack.push(a3cX1) try: a3cX1.push_request(called_directly=False) try: res = a3cX2.apply_async(add_to_parent=True) self.assertIn(res, a3cX1.request.children) finally: a3cX1.pop_request() finally: _task_stack.pop() def test_pickle_app(self): changes = dict(THE_FOO_BAR='bars', THE_MII_MAR='jars') self.app.conf.update(changes) saved = pickle.dumps(self.app) self.assertLess(len(saved), 2048) restored = pickle.loads(saved) self.assertDictContainsSubset(changes, restored.conf) def test_worker_main(self): from celery.bin import worker as worker_bin class worker(worker_bin.worker): def execute_from_commandline(self, argv): return argv prev, worker_bin.worker = worker_bin.worker, worker try: ret = self.app.worker_main(argv=['--version']) self.assertListEqual(ret, ['--version']) finally: worker_bin.worker = prev def test_config_from_envvar(self): os.environ['CELERYTEST_CONFIG_OBJECT'] = 'celery.tests.app.test_app' self.app.config_from_envvar('CELERYTEST_CONFIG_OBJECT') self.assertEqual(self.app.conf.THIS_IS_A_KEY, 'this is a value') def assert_config2(self): self.assertTrue(self.app.conf.LEAVE_FOR_WORK) self.assertTrue(self.app.conf.MOMENT_TO_STOP) self.assertEqual(self.app.conf.CALL_ME_BACK, 123456789) self.assertFalse(self.app.conf.WANT_ME_TO) self.assertTrue(self.app.conf.UNDERSTAND_ME) def test_config_from_object__lazy(self): conf = ObjectConfig2() self.app.config_from_object(conf) self.assertFalse(self.app.loader._conf) self.assertIs(self.app._config_source, conf) self.assert_config2() def test_config_from_object__force(self): self.app.config_from_object(ObjectConfig2(), force=True) self.assertTrue(self.app.loader._conf) self.assert_config2() def test_config_from_cmdline(self): cmdline = ['.always_eager=no', '.result_backend=/dev/null', 'celeryd.prefetch_multiplier=368', '.foobarstring=(string)300', '.foobarint=(int)300', '.result_engine_options=(dict){"foo": "bar"}'] self.app.config_from_cmdline(cmdline, namespace='celery') self.assertFalse(self.app.conf.CELERY_ALWAYS_EAGER) self.assertEqual(self.app.conf.CELERY_RESULT_BACKEND, '/dev/null') self.assertEqual(self.app.conf.CELERYD_PREFETCH_MULTIPLIER, 368) self.assertEqual(self.app.conf.CELERY_FOOBARSTRING, '300') self.assertEqual(self.app.conf.CELERY_FOOBARINT, 300) self.assertDictEqual(self.app.conf.CELERY_RESULT_ENGINE_OPTIONS, {'foo': 'bar'}) def test_compat_setting_CELERY_BACKEND(self): self.app.config_from_object(Object(CELERY_BACKEND='set_by_us')) self.assertEqual(self.app.conf.CELERY_RESULT_BACKEND, 'set_by_us') def test_setting_BROKER_TRANSPORT_OPTIONS(self): _args = {'foo': 'bar', 'spam': 'baz'} self.app.config_from_object(Object()) self.assertEqual(self.app.conf.BROKER_TRANSPORT_OPTIONS, {}) self.app.config_from_object(Object(BROKER_TRANSPORT_OPTIONS=_args)) self.assertEqual(self.app.conf.BROKER_TRANSPORT_OPTIONS, _args) def test_Windows_log_color_disabled(self): self.app.IS_WINDOWS = True self.assertFalse(self.app.log.supports_color(True)) def test_compat_setting_CARROT_BACKEND(self): self.app.config_from_object(Object(CARROT_BACKEND='set_by_us')) self.assertEqual(self.app.conf.BROKER_TRANSPORT, 'set_by_us') def test_WorkController(self): x = self.app.WorkController self.assertIs(x.app, self.app) def test_Worker(self): x = self.app.Worker self.assertIs(x.app, self.app) @depends_on_current_app def test_AsyncResult(self): x = self.app.AsyncResult('1') self.assertIs(x.app, self.app) r = loads(dumps(x)) # not set as current, so ends up as default app after reduce self.assertIs(r.app, current_app._get_current_object()) def test_get_active_apps(self): self.assertTrue(list(_state._get_active_apps())) app1 = self.Celery() appid = id(app1) self.assertIn(app1, _state._get_active_apps()) app1.close() del(app1) gc.collect() # weakref removed from list when app goes out of scope. with self.assertRaises(StopIteration): next(app for app in _state._get_active_apps() if id(app) == appid) def test_config_from_envvar_more(self, key='CELERY_HARNESS_CFG1'): self.assertFalse( self.app.config_from_envvar( 'HDSAJIHWIQHEWQU', force=True, silent=True), ) with self.assertRaises(ImproperlyConfigured): self.app.config_from_envvar( 'HDSAJIHWIQHEWQU', force=True, silent=False, ) os.environ[key] = __name__ + '.object_config' self.assertTrue(self.app.config_from_envvar(key, force=True)) self.assertEqual(self.app.conf['FOO'], 1) self.assertEqual(self.app.conf['BAR'], 2) os.environ[key] = 'unknown_asdwqe.asdwqewqe' with self.assertRaises(ImportError): self.app.config_from_envvar(key, silent=False) self.assertFalse( self.app.config_from_envvar(key, force=True, silent=True), ) os.environ[key] = __name__ + '.dict_config' self.assertTrue(self.app.config_from_envvar(key, force=True)) self.assertEqual(self.app.conf['FOO'], 10) self.assertEqual(self.app.conf['BAR'], 20) @patch('celery.bin.celery.CeleryCommand.execute_from_commandline') def test_start(self, execute): self.app.start() self.assertTrue(execute.called) def test_mail_admins(self): class Loader(BaseLoader): def mail_admins(*args, **kwargs): return args, kwargs self.app.loader = Loader(app=self.app) self.app.conf.ADMINS = None self.assertFalse(self.app.mail_admins('Subject', 'Body')) self.app.conf.ADMINS = [('George Costanza', 'george@vandelay.com')] self.assertTrue(self.app.mail_admins('Subject', 'Body')) def test_amqp_get_broker_info(self): self.assertDictContainsSubset( {'hostname': 'localhost', 'userid': 'guest', 'password': 'guest', 'virtual_host': '/'}, self.app.connection('pyamqp://').info(), ) self.app.conf.BROKER_PORT = 1978 self.app.conf.BROKER_VHOST = 'foo' self.assertDictContainsSubset( {'port': 1978, 'virtual_host': 'foo'}, self.app.connection('pyamqp://:1978/foo').info(), ) conn = self.app.connection('pyamqp:////value') self.assertDictContainsSubset({'virtual_host': '/value'}, conn.info()) def test_amqp_failover_strategy_selection(self): # Test passing in a string and make sure the string # gets there untouched self.app.conf.BROKER_FAILOVER_STRATEGY = 'foo-bar' self.assertEquals( self.app.connection('amqp:////value').failover_strategy, 'foo-bar', ) # Try passing in None self.app.conf.BROKER_FAILOVER_STRATEGY = None self.assertEquals( self.app.connection('amqp:////value').failover_strategy, itertools.cycle, ) # Test passing in a method def my_failover_strategy(it): yield True self.app.conf.BROKER_FAILOVER_STRATEGY = my_failover_strategy self.assertEquals( self.app.connection('amqp:////value').failover_strategy, my_failover_strategy, ) def test_BROKER_BACKEND_alias(self): self.assertEqual(self.app.conf.BROKER_BACKEND, self.app.conf.BROKER_TRANSPORT) def test_after_fork(self): p = self.app._pool = Mock() self.app._after_fork(self.app) p.force_close_all.assert_called_with() self.assertIsNone(self.app._pool) self.app._after_fork(self.app) def test_pool_no_multiprocessing(self): with mask_modules('multiprocessing.util'): pool = self.app.pool self.assertIs(pool, self.app._pool) def test_bugreport(self): self.assertTrue(self.app.bugreport()) def test_send_task_sent_event(self): class Dispatcher(object): sent = [] def publish(self, type, fields, *args, **kwargs): self.sent.append((type, fields)) conn = self.app.connection() chan = conn.channel() try: for e in ('foo_exchange', 'moo_exchange', 'bar_exchange'): chan.exchange_declare(e, 'direct', durable=True) chan.queue_declare(e, durable=True) chan.queue_bind(e, e, e) finally: chan.close() assert conn.transport_cls == 'memory' prod = self.app.amqp.TaskProducer( conn, exchange=Exchange('foo_exchange'), send_sent_event=True, ) dispatcher = Dispatcher() self.assertTrue(prod.publish_task('footask', (), {}, exchange='moo_exchange', routing_key='moo_exchange', event_dispatcher=dispatcher)) self.assertTrue(dispatcher.sent) self.assertEqual(dispatcher.sent[0][0], 'task-sent') self.assertTrue(prod.publish_task('footask', (), {}, event_dispatcher=dispatcher, exchange='bar_exchange', routing_key='bar_exchange')) def test_error_mail_sender(self): x = ErrorMail.subject % {'name': 'task_name', 'id': uuid(), 'exc': 'FOOBARBAZ', 'hostname': 'lana'} self.assertTrue(x) def test_error_mail_disabled(self): task = Mock() x = ErrorMail(task) x.should_send = Mock() x.should_send.return_value = False x.send(Mock(), Mock()) self.assertFalse(task.app.mail_admins.called) class test_defaults(AppCase): def test_str_to_bool(self): for s in ('false', 'no', '0'): self.assertFalse(defaults.strtobool(s)) for s in ('true', 'yes', '1'): self.assertTrue(defaults.strtobool(s)) with self.assertRaises(TypeError): defaults.strtobool('unsure') class test_debugging_utils(AppCase): def test_enable_disable_trace(self): try: _app.enable_trace() self.assertEqual(_app.app_or_default, _app._app_or_default_trace) _app.disable_trace() self.assertEqual(_app.app_or_default, _app._app_or_default) finally: _app.disable_trace() class test_pyimplementation(AppCase): def test_platform_python_implementation(self): with platform_pyimp(lambda: 'Xython'): self.assertEqual(pyimplementation(), 'Xython') def test_platform_jython(self): with platform_pyimp(): with sys_platform('java 1.6.51'): self.assertIn('Jython', pyimplementation()) def test_platform_pypy(self): with platform_pyimp(): with sys_platform('darwin'): with pypy_version((1, 4, 3)): self.assertIn('PyPy', pyimplementation()) with pypy_version((1, 4, 3, 'a4')): self.assertIn('PyPy', pyimplementation()) def test_platform_fallback(self): with platform_pyimp(): with sys_platform('darwin'): with pypy_version(): self.assertEqual('CPython', pyimplementation()) class test_shared_task(AppCase): def test_registers_to_all_apps(self): with self.Celery('xproj', set_as_current=True) as xproj: xproj.finalize() @shared_task def foo(): return 42 @shared_task() def bar(): return 84 self.assertIs(foo.app, xproj) self.assertIs(bar.app, xproj) self.assertTrue(foo._get_current_object()) with self.Celery('yproj', set_as_current=True) as yproj: self.assertIs(foo.app, yproj) self.assertIs(bar.app, yproj) @shared_task() def baz(): return 168 self.assertIs(baz.app, yproj)
gpl-3.0
mudrd8mz/moodle
lib/tests/behat/behat_general.php
87564
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * General use steps definitions. * * @package core * @category test * @copyright 2012 David Monllaó * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ // NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php. require_once(__DIR__ . '/../../behat/behat_base.php'); use Behat\Gherkin\Node\TableNode as TableNode; use Behat\Mink\Exception\DriverException as DriverException; use Behat\Mink\Exception\ElementNotFoundException as ElementNotFoundException; use Behat\Mink\Exception\ExpectationException as ExpectationException; use WebDriver\Exception\NoSuchElement as NoSuchElement; use WebDriver\Exception\StaleElementReference as StaleElementReference; /** * Cross component steps definitions. * * Basic web application definitions from MinkExtension and * BehatchExtension. Definitions modified according to our needs * when necessary and including only the ones we need to avoid * overlapping and confusion. * * @package core * @category test * @copyright 2012 David Monllaó * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class behat_general extends behat_base { /** * @var string used by {@link switch_to_window()} and * {@link switch_to_the_main_window()} to work-around a Chrome browser issue. */ const MAIN_WINDOW_NAME = '__moodle_behat_main_window_name'; /** * @var string when we want to check whether or not a new page has loaded, * we first write this unique string into the page. Then later, by checking * whether it is still there, we can tell if a new page has been loaded. */ const PAGE_LOAD_DETECTION_STRING = 'new_page_not_loaded_since_behat_started_watching'; /** * @var $pageloaddetectionrunning boolean Used to ensure that page load detection was started before a page reload * was checked for. */ private $pageloaddetectionrunning = false; /** * Opens Moodle homepage. * * @Given /^I am on homepage$/ */ public function i_am_on_homepage() { $this->execute('behat_general::i_visit', ['/']); } /** * Opens Moodle site homepage. * * @Given /^I am on site homepage$/ */ public function i_am_on_site_homepage() { $this->execute('behat_general::i_visit', ['/?redirect=0']); } /** * Opens course index page. * * @Given /^I am on course index$/ */ public function i_am_on_course_index() { $this->execute('behat_general::i_visit', ['/course/index.php']); } /** * Reloads the current page. * * @Given /^I reload the page$/ */ public function reload() { $this->getSession()->reload(); } /** * Follows the page redirection. Use this step after any action that shows a message and waits for a redirection * * @Given /^I wait to be redirected$/ */ public function i_wait_to_be_redirected() { // Xpath and processes based on core_renderer::redirect_message(), core_renderer::$metarefreshtag and // moodle_page::$periodicrefreshdelay possible values. if (!$metarefresh = $this->getSession()->getPage()->find('xpath', "//head/descendant::meta[@http-equiv='refresh']")) { // We don't fail the scenario if no redirection with message is found to avoid race condition false failures. return true; } // Wrapped in try & catch in case the redirection has already been executed. try { $content = $metarefresh->getAttribute('content'); } catch (NoSuchElement $e) { return true; } catch (StaleElementReference $e) { return true; } // Getting the refresh time and the url if present. if (strstr($content, 'url') != false) { list($waittime, $url) = explode(';', $content); // Cleaning the URL value. $url = trim(substr($url, strpos($url, 'http'))); } else { // Just wait then. $waittime = $content; } // Wait until the URL change is executed. if ($this->running_javascript()) { $this->getSession()->wait($waittime * 1000); } else if (!empty($url)) { // We redirect directly as we can not wait for an automatic redirection. $this->getSession()->getDriver()->getClient()->request('get', $url); } else { // Reload the page if no URL was provided. $this->getSession()->getDriver()->reload(); } } /** * Switches to the specified iframe. * * @Given /^I switch to "(?P<iframe_name_string>(?:[^"]|\\")*)" iframe$/ * @param string $iframename */ public function switch_to_iframe($iframename) { // We spin to give time to the iframe to be loaded. // Using extended timeout as we don't know about which // kind of iframe will be loaded. $this->spin( function($context, $iframename) { $context->getSession()->switchToIFrame($iframename); // If no exception we are done. return true; }, $iframename, behat_base::get_extended_timeout() ); } /** * Switches to the iframe containing specified class. * * @Given /^I switch to "(?P<iframe_name_string>(?:[^"]|\\")*)" class iframe$/ * @param string $classname */ public function switch_to_class_iframe($classname) { // We spin to give time to the iframe to be loaded. // Using extended timeout as we don't know about which // kind of iframe will be loaded. $this->spin( function($context, $classname) { $iframe = $this->find('iframe', $classname); if (!empty($iframe->getAttribute('id'))) { $iframename = $iframe->getAttribute('id'); } else { $iframename = $iframe->getAttribute('name'); } $context->getSession()->switchToIFrame($iframename); // If no exception we are done. return true; }, $classname, behat_base::get_extended_timeout() ); } /** * Switches to the main Moodle frame. * * @Given /^I switch to the main frame$/ */ public function switch_to_the_main_frame() { $this->getSession()->switchToIFrame(); } /** * Switches to the specified window. Useful when interacting with popup windows. * * @Given /^I switch to "(?P<window_name_string>(?:[^"]|\\")*)" window$/ * @param string $windowname */ public function switch_to_window($windowname) { // In Behat, some browsers (e.g. Chrome) are unable to switch to a // window without a name, and by default the main browser window does // not have a name. To work-around this, when we switch away from an // unnamed window (presumably the main window) to some other named // window, then we first set the main window name to a conventional // value that we can later use this name to switch back. $this->execute_script('if (window.name == "") window.name = "' . self::MAIN_WINDOW_NAME . '"'); $this->getSession()->switchToWindow($windowname); } /** * Switches to the main Moodle window. Useful when you finish interacting with popup windows. * * @Given /^I switch to the main window$/ */ public function switch_to_the_main_window() { $this->getSession()->switchToWindow(self::MAIN_WINDOW_NAME); } /** * Closes all extra windows opened during the navigation. * * This assumes all popups are opened by the main tab and you will now get back. * * @Given /^I close all opened windows$/ * @throws DriverException If there aren't exactly 1 tabs open when finish or no javascript running */ public function i_close_all_opened_windows() { if (!$this->running_javascript()) { throw new DriverException('Closing windows steps require javascript'); } $names = $this->getSession()->getWindowNames(); for ($index = 1; $index < count($names); $index ++) { $this->getSession()->switchToWindow($names[$index]); $this->execute_script("window.open('', '_self').close();"); } $names = $this->getSession()->getWindowNames(); if (count($names) !== 1) { throw new DriverException('Expected to see 1 tabs open, not ' . count($names)); } $this->getSession()->switchToWindow($names[0]); } /** * Accepts the currently displayed alert dialog. This step does not work in all the browsers, consider it experimental. * @Given /^I accept the currently displayed dialog$/ */ public function accept_currently_displayed_alert_dialog() { $this->getSession()->getDriver()->getWebDriverSession()->accept_alert(); } /** * Dismisses the currently displayed alert dialog. This step does not work in all the browsers, consider it experimental. * @Given /^I dismiss the currently displayed dialog$/ */ public function dismiss_currently_displayed_alert_dialog() { $this->getSession()->getDriver()->getWebDriverSession()->dismiss_alert(); } /** * Clicks link with specified id|title|alt|text. * * @When /^I follow "(?P<link_string>(?:[^"]|\\")*)"$/ * @throws ElementNotFoundException Thrown by behat_base::find * @param string $link */ public function click_link($link) { $linknode = $this->find_link($link); $this->ensure_node_is_visible($linknode); $linknode->click(); } /** * Waits X seconds. Required after an action that requires data from an AJAX request. * * @Then /^I wait "(?P<seconds_number>\d+)" seconds$/ * @param int $seconds */ public function i_wait_seconds($seconds) { if ($this->running_javascript()) { $this->getSession()->wait($seconds * 1000); } else { sleep($seconds); } } /** * Waits until the page is completely loaded. This step is auto-executed after every step. * * @Given /^I wait until the page is ready$/ */ public function wait_until_the_page_is_ready() { // No need to wait if not running JS. if (!$this->running_javascript()) { return; } $this->getSession()->wait(self::get_timeout() * 1000, self::PAGE_READY_JS); } /** * Waits until the provided element selector exists in the DOM * * Using the protected method as this method will be usually * called by other methods which are not returning a set of * steps and performs the actions directly, so it would not * be executed if it returns another step. * @Given /^I wait until "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" exists$/ * @param string $element * @param string $selector * @return void */ public function wait_until_exists($element, $selectortype) { $this->ensure_element_exists($element, $selectortype); } /** * Waits until the provided element does not exist in the DOM * * Using the protected method as this method will be usually * called by other methods which are not returning a set of * steps and performs the actions directly, so it would not * be executed if it returns another step. * @Given /^I wait until "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" does not exist$/ * @param string $element * @param string $selector * @return void */ public function wait_until_does_not_exists($element, $selectortype) { $this->ensure_element_does_not_exist($element, $selectortype); } /** * Generic mouse over action. Mouse over a element of the specified type. * * @When /^I hover "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)"$/ * @param string $element Element we look for * @param string $selectortype The type of what we look for */ public function i_hover($element, $selectortype) { // Gets the node based on the requested selector type and locator. $node = $this->get_selected_node($selectortype, $element); $node->mouseOver(); } /** * Generic click action. Click on the element of the specified type. * * @When /^I click on "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)"$/ * @param string $element Element we look for * @param string $selectortype The type of what we look for */ public function i_click_on($element, $selectortype) { // Gets the node based on the requested selector type and locator. $node = $this->get_selected_node($selectortype, $element); $this->ensure_node_is_visible($node); $node->click(); } /** * Sets the focus and takes away the focus from an element, generating blur JS event. * * @When /^I take focus off "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)"$/ * @param string $element Element we look for * @param string $selectortype The type of what we look for */ public function i_take_focus_off_field($element, $selectortype) { if (!$this->running_javascript()) { throw new ExpectationException('Can\'t take focus off from "' . $element . '" in non-js mode', $this->getSession()); } // Gets the node based on the requested selector type and locator. $node = $this->get_selected_node($selectortype, $element); $this->ensure_node_is_visible($node); // Ensure element is focused before taking it off. $node->focus(); $node->blur(); } /** * Clicks the specified element and confirms the expected dialogue. * * @When /^I click on "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" confirming the dialogue$/ * @throws ElementNotFoundException Thrown by behat_base::find * @param string $element Element we look for * @param string $selectortype The type of what we look for */ public function i_click_on_confirming_the_dialogue($element, $selectortype) { $this->i_click_on($element, $selectortype); $this->accept_currently_displayed_alert_dialog(); } /** * Clicks the specified element and dismissing the expected dialogue. * * @When /^I click on "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" dismissing the dialogue$/ * @throws ElementNotFoundException Thrown by behat_base::find * @param string $element Element we look for * @param string $selectortype The type of what we look for */ public function i_click_on_dismissing_the_dialogue($element, $selectortype) { $this->i_click_on($element, $selectortype); $this->dismiss_currently_displayed_alert_dialog(); } /** * Click on the element of the specified type which is located inside the second element. * * @When /^I click on "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" in the "(?P<element_container_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)"$/ * @param string $element Element we look for * @param string $selectortype The type of what we look for * @param string $nodeelement Element we look in * @param string $nodeselectortype The type of selector where we look in */ public function i_click_on_in_the($element, $selectortype, $nodeelement, $nodeselectortype) { $node = $this->get_node_in_container($selectortype, $element, $nodeselectortype, $nodeelement); $this->ensure_node_is_visible($node); $node->click(); } /** * Drags and drops the specified element to the specified container. This step does not work in all the browsers, consider it experimental. * * The steps definitions calling this step as part of them should * manage the wait times by themselves as the times and when the * waits should be done depends on what is being dragged & dropper. * * @Given /^I drag "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector1_string>(?:[^"]|\\")*)" and I drop it in "(?P<container_element_string>(?:[^"]|\\")*)" "(?P<selector2_string>(?:[^"]|\\")*)"$/ * @param string $element * @param string $selectortype * @param string $containerelement * @param string $containerselectortype */ public function i_drag_and_i_drop_it_in($source, $sourcetype, $target, $targettype) { if (!$this->running_javascript()) { throw new DriverException('Drag and drop steps require javascript'); } $source = $this->find($sourcetype, $source); $target = $this->find($targettype, $target); if (!$source->isVisible()) { throw new ExpectationException("'{$source}' '{$sourcetype}' is not visible", $this->getSession()); } if (!$target->isVisible()) { throw new ExpectationException("'{$target}' '{$targettype}' is not visible", $this->getSession()); } $this->getSession()->getDriver()->dragTo($source->getXpath(), $target->getXpath()); } /** * Checks, that the specified element is visible. Only available in tests using Javascript. * * @Then /^"(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>(?:[^"]|\\")*)" should be visible$/ * @throws ElementNotFoundException * @throws ExpectationException * @throws DriverException * @param string $element * @param string $selectortype * @return void */ public function should_be_visible($element, $selectortype) { if (!$this->running_javascript()) { throw new DriverException('Visible checks are disabled in scenarios without Javascript support'); } $node = $this->get_selected_node($selectortype, $element); if (!$node->isVisible()) { throw new ExpectationException('"' . $element . '" "' . $selectortype . '" is not visible', $this->getSession()); } } /** * Checks, that the existing element is not visible. Only available in tests using Javascript. * * As a "not" method, it's performance could not be good, but in this * case the performance is good because the element must exist, * otherwise there would be a ElementNotFoundException, also here we are * not spinning until the element is visible. * * @Then /^"(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>(?:[^"]|\\")*)" should not be visible$/ * @throws ElementNotFoundException * @throws ExpectationException * @param string $element * @param string $selectortype * @return void */ public function should_not_be_visible($element, $selectortype) { try { $this->should_be_visible($element, $selectortype); } catch (ExpectationException $e) { // All as expected. return; } throw new ExpectationException('"' . $element . '" "' . $selectortype . '" is visible', $this->getSession()); } /** * Checks, that the specified element is visible inside the specified container. Only available in tests using Javascript. * * @Then /^"(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" in the "(?P<element_container_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)" should be visible$/ * @throws ElementNotFoundException * @throws DriverException * @throws ExpectationException * @param string $element Element we look for * @param string $selectortype The type of what we look for * @param string $nodeelement Element we look in * @param string $nodeselectortype The type of selector where we look in */ public function in_the_should_be_visible($element, $selectortype, $nodeelement, $nodeselectortype) { if (!$this->running_javascript()) { throw new DriverException('Visible checks are disabled in scenarios without Javascript support'); } $node = $this->get_node_in_container($selectortype, $element, $nodeselectortype, $nodeelement); if (!$node->isVisible()) { throw new ExpectationException( '"' . $element . '" "' . $selectortype . '" in the "' . $nodeelement . '" "' . $nodeselectortype . '" is not visible', $this->getSession() ); } } /** * Checks, that the existing element is not visible inside the existing container. Only available in tests using Javascript. * * As a "not" method, it's performance could not be good, but in this * case the performance is good because the element must exist, * otherwise there would be a ElementNotFoundException, also here we are * not spinning until the element is visible. * * @Then /^"(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" in the "(?P<element_container_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)" should not be visible$/ * @throws ElementNotFoundException * @throws ExpectationException * @param string $element Element we look for * @param string $selectortype The type of what we look for * @param string $nodeelement Element we look in * @param string $nodeselectortype The type of selector where we look in */ public function in_the_should_not_be_visible($element, $selectortype, $nodeelement, $nodeselectortype) { try { $this->in_the_should_be_visible($element, $selectortype, $nodeelement, $nodeselectortype); } catch (ExpectationException $e) { // All as expected. return; } throw new ExpectationException( '"' . $element . '" "' . $selectortype . '" in the "' . $nodeelement . '" "' . $nodeselectortype . '" is visible', $this->getSession() ); } /** * Checks, that page contains specified text. It also checks if the text is visible when running Javascript tests. * * @Then /^I should see "(?P<text_string>(?:[^"]|\\")*)"$/ * @throws ExpectationException * @param string $text */ public function assert_page_contains_text($text) { // Looking for all the matching nodes without any other descendant matching the // same xpath (we are using contains(., ....). $xpathliteral = behat_context_helper::escape($text); $xpath = "/descendant-or-self::*[contains(., $xpathliteral)]" . "[count(descendant::*[contains(., $xpathliteral)]) = 0]"; try { $nodes = $this->find_all('xpath', $xpath); } catch (ElementNotFoundException $e) { throw new ExpectationException('"' . $text . '" text was not found in the page', $this->getSession()); } // If we are not running javascript we have enough with the // element existing as we can't check if it is visible. if (!$this->running_javascript()) { return; } // We spin as we don't have enough checking that the element is there, we // should also ensure that the element is visible. Using microsleep as this // is a repeated step and global performance is important. $this->spin( function($context, $args) { foreach ($args['nodes'] as $node) { if ($node->isVisible()) { return true; } } // If non of the nodes is visible we loop again. throw new ExpectationException('"' . $args['text'] . '" text was found but was not visible', $context->getSession()); }, array('nodes' => $nodes, 'text' => $text), false, false, true ); } /** * Checks, that page doesn't contain specified text. When running Javascript tests it also considers that texts may be hidden. * * @Then /^I should not see "(?P<text_string>(?:[^"]|\\")*)"$/ * @throws ExpectationException * @param string $text */ public function assert_page_not_contains_text($text) { // Looking for all the matching nodes without any other descendant matching the // same xpath (we are using contains(., ....). $xpathliteral = behat_context_helper::escape($text); $xpath = "/descendant-or-self::*[contains(., $xpathliteral)]" . "[count(descendant::*[contains(., $xpathliteral)]) = 0]"; // We should wait a while to ensure that the page is not still loading elements. // Waiting less than self::get_timeout() as we already waited for the DOM to be ready and // all JS to be executed. try { $nodes = $this->find_all('xpath', $xpath, false, false, self::get_reduced_timeout()); } catch (ElementNotFoundException $e) { // All ok. return; } // If we are not running javascript we have enough with the // element existing as we can't check if it is hidden. if (!$this->running_javascript()) { throw new ExpectationException('"' . $text . '" text was found in the page', $this->getSession()); } // If the element is there we should be sure that it is not visible. $this->spin( function($context, $args) { foreach ($args['nodes'] as $node) { // If element is removed from dom, then just exit. try { // If element is visible then throw exception, so we keep spinning. if ($node->isVisible()) { throw new ExpectationException('"' . $args['text'] . '" text was found in the page', $context->getSession()); } } catch (WebDriver\Exception\NoSuchElement $e) { // Do nothing just return, as element is no more on page. return true; } catch (ElementNotFoundException $e) { // Do nothing just return, as element is no more on page. return true; } } // If non of the found nodes is visible we consider that the text is not visible. return true; }, array('nodes' => $nodes, 'text' => $text), behat_base::get_reduced_timeout(), false, true ); } /** * Checks, that the specified element contains the specified text. When running Javascript tests it also considers that texts may be hidden. * * @Then /^I should see "(?P<text_string>(?:[^"]|\\")*)" in the "(?P<element_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)"$/ * @throws ElementNotFoundException * @throws ExpectationException * @param string $text * @param string $element Element we look in. * @param string $selectortype The type of element where we are looking in. */ public function assert_element_contains_text($text, $element, $selectortype) { // Getting the container where the text should be found. $container = $this->get_selected_node($selectortype, $element); // Looking for all the matching nodes without any other descendant matching the // same xpath (we are using contains(., ....). $xpathliteral = behat_context_helper::escape($text); $xpath = "/descendant-or-self::*[contains(., $xpathliteral)]" . "[count(descendant::*[contains(., $xpathliteral)]) = 0]"; // Wait until it finds the text inside the container, otherwise custom exception. try { $nodes = $this->find_all('xpath', $xpath, false, $container); } catch (ElementNotFoundException $e) { throw new ExpectationException('"' . $text . '" text was not found in the "' . $element . '" element', $this->getSession()); } // If we are not running javascript we have enough with the // element existing as we can't check if it is visible. if (!$this->running_javascript()) { return; } // We also check the element visibility when running JS tests. Using microsleep as this // is a repeated step and global performance is important. $this->spin( function($context, $args) { foreach ($args['nodes'] as $node) { if ($node->isVisible()) { return true; } } throw new ExpectationException('"' . $args['text'] . '" text was found in the "' . $args['element'] . '" element but was not visible', $context->getSession()); }, array('nodes' => $nodes, 'text' => $text, 'element' => $element), false, false, true ); } /** * Checks, that the specified element does not contain the specified text. When running Javascript tests it also considers that texts may be hidden. * * @Then /^I should not see "(?P<text_string>(?:[^"]|\\")*)" in the "(?P<element_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)"$/ * @throws ElementNotFoundException * @throws ExpectationException * @param string $text * @param string $element Element we look in. * @param string $selectortype The type of element where we are looking in. */ public function assert_element_not_contains_text($text, $element, $selectortype) { // Getting the container where the text should be found. $container = $this->get_selected_node($selectortype, $element); // Looking for all the matching nodes without any other descendant matching the // same xpath (we are using contains(., ....). $xpathliteral = behat_context_helper::escape($text); $xpath = "/descendant-or-self::*[contains(., $xpathliteral)]" . "[count(descendant::*[contains(., $xpathliteral)]) = 0]"; // We should wait a while to ensure that the page is not still loading elements. // Giving preference to the reliability of the results rather than to the performance. try { $nodes = $this->find_all('xpath', $xpath, false, $container, self::get_reduced_timeout()); } catch (ElementNotFoundException $e) { // All ok. return; } // If we are not running javascript we have enough with the // element not being found as we can't check if it is visible. if (!$this->running_javascript()) { throw new ExpectationException('"' . $text . '" text was found in the "' . $element . '" element', $this->getSession()); } // We need to ensure all the found nodes are hidden. $this->spin( function($context, $args) { foreach ($args['nodes'] as $node) { if ($node->isVisible()) { throw new ExpectationException('"' . $args['text'] . '" text was found in the "' . $args['element'] . '" element', $context->getSession()); } } // If all the found nodes are hidden we are happy. return true; }, array('nodes' => $nodes, 'text' => $text, 'element' => $element), behat_base::get_reduced_timeout(), false, true ); } /** * Checks, that the first specified element appears before the second one. * * @Then :preelement :preselectortype should appear before :postelement :postselectortype * @Then :preelement :preselectortype should appear before :postelement :postselectortype in the :containerelement :containerselectortype * @throws ExpectationException * @param string $preelement The locator of the preceding element * @param string $preselectortype The selector type of the preceding element * @param string $postelement The locator of the latest element * @param string $postselectortype The selector type of the latest element * @param string $containerelement * @param string $containerselectortype */ public function should_appear_before( string $preelement, string $preselectortype, string $postelement, string $postselectortype, ?string $containerelement = null, ?string $containerselectortype = null ) { $msg = "'{$preelement}' '{$preselectortype}' does not appear before '{$postelement}' '{$postselectortype}'"; $this->check_element_order( $containerelement, $containerselectortype, $preelement, $preselectortype, $postelement, $postselectortype, $msg ); } /** * Checks, that the first specified element appears after the second one. * * @Then :postelement :postselectortype should appear after :preelement :preselectortype * @Then :postelement :postselectortype should appear after :preelement :preselectortype in the :containerelement :containerselectortype * @throws ExpectationException * @param string $postelement The locator of the latest element * @param string $postselectortype The selector type of the latest element * @param string $preelement The locator of the preceding element * @param string $preselectortype The selector type of the preceding element * @param string $containerelement * @param string $containerselectortype */ public function should_appear_after( string $postelement, string $postselectortype, string $preelement, string $preselectortype, ?string $containerelement = null, ?string $containerselectortype = null ) { $msg = "'{$postelement}' '{$postselectortype}' does not appear after '{$preelement}' '{$preselectortype}'"; $this->check_element_order( $containerelement, $containerselectortype, $preelement, $preselectortype, $postelement, $postselectortype, $msg ); } /** * Shared code to check whether an element is before or after another one. * * @param string $containerelement * @param string $containerselectortype * @param string $preelement The locator of the preceding element * @param string $preselectortype The locator of the preceding element * @param string $postelement The locator of the following element * @param string $postselectortype The selector type of the following element * @param string $msg Message to output if this fails */ protected function check_element_order( ?string $containerelement, ?string $containerselectortype, string $preelement, string $preselectortype, string $postelement, string $postselectortype, string $msg ) { $containernode = false; if ($containerselectortype && $containerelement) { // Get the container node. $containernode = $this->get_selected_node($containerselectortype, $containerelement); $msg .= " in the '{$containerelement}' '{$containerselectortype}'"; } list($preselector, $prelocator) = $this->transform_selector($preselectortype, $preelement); list($postselector, $postlocator) = $this->transform_selector($postselectortype, $postelement); $newlines = [ "\r\n", "\r", "\n", ]; $prexpath = str_replace($newlines, ' ', $this->find($preselector, $prelocator, false, $containernode)->getXpath()); $postxpath = str_replace($newlines, ' ', $this->find($postselector, $postlocator, false, $containernode)->getXpath()); if ($this->running_javascript()) { // The xpath to do this was running really slowly on certain Chrome versions so we are using // this DOM method instead. $js = <<<EOF (function() { var a = document.evaluate("{$prexpath}", document, null, XPathResult.ANY_TYPE, null).iterateNext(); var b = document.evaluate("{$postxpath}", document, null, XPathResult.ANY_TYPE, null).iterateNext(); return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING; })() EOF; $ok = $this->evaluate_script($js); } else { // Using following xpath axe to find it. $xpath = "{$prexpath}/following::*[contains(., {$postxpath})]"; $ok = $this->getSession()->getDriver()->find($xpath); } if (!$ok) { throw new ExpectationException($msg, $this->getSession()); } } /** * Checks, that element of specified type is disabled. * * @Then /^the "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should be disabled$/ * @throws ExpectationException Thrown by behat_base::find * @param string $element Element we look in * @param string $selectortype The type of element where we are looking in. */ public function the_element_should_be_disabled($element, $selectortype) { // Transforming from steps definitions selector/locator format to Mink format and getting the NodeElement. $node = $this->get_selected_node($selectortype, $element); if (!$node->hasAttribute('disabled')) { throw new ExpectationException('The element "' . $element . '" is not disabled', $this->getSession()); } } /** * Checks, that element of specified type is enabled. * * @Then /^the "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should be enabled$/ * @throws ExpectationException Thrown by behat_base::find * @param string $element Element we look on * @param string $selectortype The type of where we look */ public function the_element_should_be_enabled($element, $selectortype) { // Transforming from steps definitions selector/locator format to mink format and getting the NodeElement. $node = $this->get_selected_node($selectortype, $element); if ($node->hasAttribute('disabled')) { throw new ExpectationException('The element "' . $element . '" is not enabled', $this->getSession()); } } /** * Checks the provided element and selector type are readonly on the current page. * * @Then /^the "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should be readonly$/ * @throws ExpectationException Thrown by behat_base::find * @param string $element Element we look in * @param string $selectortype The type of element where we are looking in. */ public function the_element_should_be_readonly($element, $selectortype) { // Transforming from steps definitions selector/locator format to Mink format and getting the NodeElement. $node = $this->get_selected_node($selectortype, $element); if (!$node->hasAttribute('readonly')) { throw new ExpectationException('The element "' . $element . '" is not readonly', $this->getSession()); } } /** * Checks the provided element and selector type are not readonly on the current page. * * @Then /^the "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should not be readonly$/ * @throws ExpectationException Thrown by behat_base::find * @param string $element Element we look in * @param string $selectortype The type of element where we are looking in. */ public function the_element_should_not_be_readonly($element, $selectortype) { // Transforming from steps definitions selector/locator format to Mink format and getting the NodeElement. $node = $this->get_selected_node($selectortype, $element); if ($node->hasAttribute('readonly')) { throw new ExpectationException('The element "' . $element . '" is readonly', $this->getSession()); } } /** * Checks the provided element and selector type exists in the current page. * * This step is for advanced users, use it if you don't find anything else suitable for what you need. * * @Then /^"(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should exist$/ * @throws ElementNotFoundException Thrown by behat_base::find * @param string $element The locator of the specified selector * @param string $selectortype The selector type */ public function should_exist($element, $selectortype) { // Will throw an ElementNotFoundException if it does not exist. $this->find($selectortype, $element); } /** * Checks that the provided element and selector type not exists in the current page. * * This step is for advanced users, use it if you don't find anything else suitable for what you need. * * @Then /^"(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should not exist$/ * @throws ExpectationException * @param string $element The locator of the specified selector * @param string $selectortype The selector type */ public function should_not_exist($element, $selectortype) { // Will throw an ElementNotFoundException if it does not exist, but, actually it should not exist, so we try & // catch it. try { // The exception does not really matter as we will catch it and will never "explode". $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $element); // Using the spin method as we want a reduced timeout but there is no need for a 0.1 seconds interval // because in the optimistic case we will timeout. // If all goes good it will throw an ElementNotFoundExceptionn that we will catch. return $this->find($selectortype, $element, $exception, false, behat_base::get_reduced_timeout()); } catch (ElementNotFoundException $e) { // We expect the element to not be found. return; } // The element was found and should not have been. Throw an exception. throw new ExpectationException("The '{$element}' '{$selectortype}' exists in the current page", $this->getSession()); } /** * This step triggers cron like a user would do going to admin/cron.php. * * @Given /^I trigger cron$/ */ public function i_trigger_cron() { $this->execute('behat_general::i_visit', ['/admin/cron.php']); } /** * Runs a scheduled task immediately, given full class name. * * This is faster and more reliable than running cron (running cron won't * work more than once in the same test, for instance). However it is * a little less 'realistic'. * * While the task is running, we suppress mtrace output because it makes * the Behat result look ugly. * * Note: Most of the code relating to running a task is based on * admin/tool/task/cli/schedule_task.php. * * @Given /^I run the scheduled task "(?P<task_name>[^"]+)"$/ * @param string $taskname Name of task e.g. 'mod_whatever\task\do_something' */ public function i_run_the_scheduled_task($taskname) { global $CFG; require_once("{$CFG->libdir}/cronlib.php"); $task = \core\task\manager::get_scheduled_task($taskname); if (!$task) { throw new DriverException('The "' . $taskname . '" scheduled task does not exist'); } // Do setup for cron task. raise_memory_limit(MEMORY_EXTRA); cron_setup_user(); // Get lock. $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron'); if (!$cronlock = $cronlockfactory->get_lock('core_cron', 10)) { throw new DriverException('Unable to obtain core_cron lock for scheduled task'); } if (!$lock = $cronlockfactory->get_lock('\\' . get_class($task), 10)) { $cronlock->release(); throw new DriverException('Unable to obtain task lock for scheduled task'); } $task->set_lock($lock); if (!$task->is_blocking()) { $cronlock->release(); } else { $task->set_cron_lock($cronlock); } try { // Prepare the renderer. cron_prepare_core_renderer(); // Discard task output as not appropriate for Behat output! ob_start(); $task->execute(); ob_end_clean(); // Restore the previous renderer. cron_prepare_core_renderer(true); // Mark task complete. \core\task\manager::scheduled_task_complete($task); } catch (Exception $e) { // Restore the previous renderer. cron_prepare_core_renderer(true); // Mark task failed and throw exception. \core\task\manager::scheduled_task_failed($task); throw new DriverException('The "' . $taskname . '" scheduled task failed', 0, $e); } } /** * Runs all ad-hoc tasks in the queue. * * This is faster and more reliable than running cron (running cron won't * work more than once in the same test, for instance). However it is * a little less 'realistic'. * * While the task is running, we suppress mtrace output because it makes * the Behat result look ugly. * * @Given /^I run all adhoc tasks$/ * @throws DriverException */ public function i_run_all_adhoc_tasks() { global $CFG, $DB; require_once("{$CFG->libdir}/cronlib.php"); // Do setup for cron task. cron_setup_user(); // Discard task output as not appropriate for Behat output! ob_start(); // Run all tasks which have a scheduled runtime of before now. $timenow = time(); while (!\core\task\manager::static_caches_cleared_since($timenow) && $task = \core\task\manager::get_next_adhoc_task($timenow)) { // Clean the output buffer between tasks. ob_clean(); // Run the task. cron_run_inner_adhoc_task($task); // Check whether the task record still exists. // If a task was successful it will be removed. // If it failed then it will still exist. if ($DB->record_exists('task_adhoc', ['id' => $task->get_id()])) { // End ouptut buffering and flush the current buffer. // This should be from just the current task. ob_end_flush(); throw new DriverException('An adhoc task failed', 0); } } ob_end_clean(); } /** * Checks that an element and selector type exists in another element and selector type on the current page. * * This step is for advanced users, use it if you don't find anything else suitable for what you need. * * @Then /^"(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should exist in the "(?P<element2_string>(?:[^"]|\\")*)" "(?P<selector2_string>[^"]*)"$/ * @throws ElementNotFoundException Thrown by behat_base::find * @param string $element The locator of the specified selector * @param string $selectortype The selector type * @param string $containerelement The container selector type * @param string $containerselectortype The container locator */ public function should_exist_in_the($element, $selectortype, $containerelement, $containerselectortype) { // Get the container node. $containernode = $this->find($containerselectortype, $containerelement); // Specific exception giving info about where can't we find the element. $locatorexceptionmsg = "{$element} in the {$containerelement} {$containerselectortype}"; $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg); // Looks for the requested node inside the container node. $this->find($selectortype, $element, $exception, $containernode); } /** * Checks that an element and selector type does not exist in another element and selector type on the current page. * * This step is for advanced users, use it if you don't find anything else suitable for what you need. * * @Then /^"(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should not exist in the "(?P<element2_string>(?:[^"]|\\")*)" "(?P<selector2_string>[^"]*)"$/ * @throws ExpectationException * @param string $element The locator of the specified selector * @param string $selectortype The selector type * @param string $containerelement The container selector type * @param string $containerselectortype The container locator */ public function should_not_exist_in_the($element, $selectortype, $containerelement, $containerselectortype) { // Get the container node. $containernode = $this->find($containerselectortype, $containerelement); // Will throw an ElementNotFoundException if it does not exist, but, actually it should not exist, so we try & // catch it. try { // Looks for the requested node inside the container node. $this->find($selectortype, $element, false, $containernode, behat_base::get_reduced_timeout()); } catch (ElementNotFoundException $e) { // We expect the element to not be found. return; } // The element was found and should not have been. Throw an exception. throw new ExpectationException( "The '{$element}' '{$selectortype}' exists in the '{$containerelement}' '{$containerselectortype}'", $this->getSession() ); } /** * Change browser window size small: 640x480, medium: 1024x768, large: 2560x1600, custom: widthxheight * * Example: I change window size to "small" or I change window size to "1024x768" * or I change viewport size to "800x600". The viewport option is useful to guarantee that the * browser window has same viewport size even when you run Behat on multiple operating systems. * * @throws ExpectationException * @Then /^I change (window|viewport) size to "(small|medium|large|\d+x\d+)"$/ * @Then /^I change the (window|viewport) size to "(small|medium|large|\d+x\d+)"$/ * @param string $windowsize size of the window (small|medium|large|wxh). */ public function i_change_window_size_to($windowviewport, $windowsize) { $this->resize_window($windowsize, $windowviewport === 'viewport'); } /** * Checks whether there is an attribute on the given element that contains the specified text. * * @Then /^the "(?P<attribute_string>[^"]*)" attribute of "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should contain "(?P<text_string>(?:[^"]|\\")*)"$/ * @throws ExpectationException * @param string $attribute Name of attribute * @param string $element The locator of the specified selector * @param string $selectortype The selector type * @param string $text Expected substring */ public function the_attribute_of_should_contain($attribute, $element, $selectortype, $text) { // Get the container node (exception if it doesn't exist). $containernode = $this->get_selected_node($selectortype, $element); $value = $containernode->getAttribute($attribute); if ($value == null) { throw new ExpectationException('The attribute "' . $attribute. '" does not exist', $this->getSession()); } else if (strpos($value, $text) === false) { throw new ExpectationException('The attribute "' . $attribute . '" does not contain "' . $text . '" (actual value: "' . $value . '")', $this->getSession()); } } /** * Checks that the attribute on the given element does not contain the specified text. * * @Then /^the "(?P<attribute_string>[^"]*)" attribute of "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should not contain "(?P<text_string>(?:[^"]|\\")*)"$/ * @throws ExpectationException * @param string $attribute Name of attribute * @param string $element The locator of the specified selector * @param string $selectortype The selector type * @param string $text Expected substring */ public function the_attribute_of_should_not_contain($attribute, $element, $selectortype, $text) { // Get the container node (exception if it doesn't exist). $containernode = $this->get_selected_node($selectortype, $element); $value = $containernode->getAttribute($attribute); if ($value == null) { throw new ExpectationException('The attribute "' . $attribute. '" does not exist', $this->getSession()); } else if (strpos($value, $text) !== false) { throw new ExpectationException('The attribute "' . $attribute . '" contains "' . $text . '" (value: "' . $value . '")', $this->getSession()); } } /** * Checks the provided value exists in specific row/column of table. * * @Then /^"(?P<row_string>[^"]*)" row "(?P<column_string>[^"]*)" column of "(?P<table_string>[^"]*)" table should contain "(?P<value_string>[^"]*)"$/ * @throws ElementNotFoundException * @param string $row row text which will be looked in. * @param string $column column text to search (or numeric value for the column position) * @param string $table table id/class/caption * @param string $value text to check. */ public function row_column_of_table_should_contain($row, $column, $table, $value) { $tablenode = $this->get_selected_node('table', $table); $tablexpath = $tablenode->getXpath(); $rowliteral = behat_context_helper::escape($row); $valueliteral = behat_context_helper::escape($value); $columnliteral = behat_context_helper::escape($column); if (preg_match('/^-?(\d+)-?$/', $column, $columnasnumber)) { // Column indicated as a number, just use it as position of the column. $columnpositionxpath = "/child::*[position() = {$columnasnumber[1]}]"; } else { // Header can be in thead or tbody (first row), following xpath should work. $theadheaderxpath = "thead/tr[1]/th[(normalize-space(.)=" . $columnliteral . " or a[normalize-space(text())=" . $columnliteral . "] or div[normalize-space(text())=" . $columnliteral . "])]"; $tbodyheaderxpath = "tbody/tr[1]/td[(normalize-space(.)=" . $columnliteral . " or a[normalize-space(text())=" . $columnliteral . "] or div[normalize-space(text())=" . $columnliteral . "])]"; // Check if column exists. $columnheaderxpath = $tablexpath . "[" . $theadheaderxpath . " | " . $tbodyheaderxpath . "]"; $columnheader = $this->getSession()->getDriver()->find($columnheaderxpath); if (empty($columnheader)) { $columnexceptionmsg = $column . '" in table "' . $table . '"'; throw new ElementNotFoundException($this->getSession(), "\n$columnheaderxpath\n\n".'Column', null, $columnexceptionmsg); } // Following conditions were considered before finding column count. // 1. Table header can be in thead/tr/th or tbody/tr/td[1]. // 2. First column can have th (Gradebook -> user report), so having lenient sibling check. $columnpositionxpath = "/child::*[position() = count(" . $tablexpath . "/" . $theadheaderxpath . "/preceding-sibling::*) + 1]"; } // Check if value exists in specific row/column. // Get row xpath. // GoutteDriver uses DomCrawler\Crawler and it is making XPath relative to the current context, so use descendant. $rowxpath = $tablexpath."/tbody/tr[descendant::th[normalize-space(.)=" . $rowliteral . "] | descendant::td[normalize-space(.)=" . $rowliteral . "]]"; $columnvaluexpath = $rowxpath . $columnpositionxpath . "[contains(normalize-space(.)," . $valueliteral . ")]"; // Looks for the requested node inside the container node. $coumnnode = $this->getSession()->getDriver()->find($columnvaluexpath); if (empty($coumnnode)) { $locatorexceptionmsg = $value . '" in "' . $row . '" row with column "' . $column; throw new ElementNotFoundException($this->getSession(), "\n$columnvaluexpath\n\n".'Column value', null, $locatorexceptionmsg); } } /** * Checks the provided value should not exist in specific row/column of table. * * @Then /^"(?P<row_string>[^"]*)" row "(?P<column_string>[^"]*)" column of "(?P<table_string>[^"]*)" table should not contain "(?P<value_string>[^"]*)"$/ * @throws ElementNotFoundException * @param string $row row text which will be looked in. * @param string $column column text to search * @param string $table table id/class/caption * @param string $value text to check. */ public function row_column_of_table_should_not_contain($row, $column, $table, $value) { try { $this->row_column_of_table_should_contain($row, $column, $table, $value); } catch (ElementNotFoundException $e) { // Table row/column doesn't contain this value. Nothing to do. return; } // Throw exception if found. throw new ExpectationException( '"' . $column . '" with value "' . $value . '" is present in "' . $row . '" row for table "' . $table . '"', $this->getSession() ); } /** * Checks that the provided value exist in table. * * First row may contain column headers or numeric indexes of the columns * (syntax -1- is also considered to be column index). Column indexes are * useful in case of multirow headers and/or presence of cells with colspan. * * @Then /^the following should exist in the "(?P<table_string>[^"]*)" table:$/ * @throws ExpectationException * @param string $table name of table * @param TableNode $data table with first row as header and following values * | Header 1 | Header 2 | Header 3 | * | Value 1 | Value 2 | Value 3| */ public function following_should_exist_in_the_table($table, TableNode $data) { $datahash = $data->getHash(); foreach ($datahash as $row) { $firstcell = null; foreach ($row as $column => $value) { if ($firstcell === null) { $firstcell = $value; } else { $this->row_column_of_table_should_contain($firstcell, $column, $table, $value); } } } } /** * Checks that the provided values do not exist in a table. * * @Then /^the following should not exist in the "(?P<table_string>[^"]*)" table:$/ * @throws ExpectationException * @param string $table name of table * @param TableNode $data table with first row as header and following values * | Header 1 | Header 2 | Header 3 | * | Value 1 | Value 2 | Value 3| */ public function following_should_not_exist_in_the_table($table, TableNode $data) { $datahash = $data->getHash(); foreach ($datahash as $value) { $row = array_shift($value); foreach ($value as $column => $value) { try { $this->row_column_of_table_should_contain($row, $column, $table, $value); // Throw exception if found. } catch (ElementNotFoundException $e) { // Table row/column doesn't contain this value. Nothing to do. continue; } throw new ExpectationException('"' . $column . '" with value "' . $value . '" is present in "' . $row . '" row for table "' . $table . '"', $this->getSession() ); } } } /** * Given the text of a link, download the linked file and return the contents. * * This is a helper method used by {@link following_should_download_bytes()} * and {@link following_should_download_between_and_bytes()} * * @param string $link the text of the link. * @return string the content of the downloaded file. */ public function download_file_from_link($link) { // Find the link. $linknode = $this->find_link($link); $this->ensure_node_is_visible($linknode); // Get the href and check it. $url = $linknode->getAttribute('href'); if (!$url) { throw new ExpectationException('Download link does not have href attribute', $this->getSession()); } if (!preg_match('~^https?://~', $url)) { throw new ExpectationException('Download link not an absolute URL: ' . $url, $this->getSession()); } // Download the URL and check the size. $session = $this->getSession()->getCookie('MoodleSession'); return download_file_content($url, array('Cookie' => 'MoodleSession=' . $session)); } /** * Downloads the file from a link on the page and checks the size. * * Only works if the link has an href attribute. Javascript downloads are * not supported. Currently, the href must be an absolute URL. * * @Then /^following "(?P<link_string>[^"]*)" should download "(?P<expected_bytes>\d+)" bytes$/ * @throws ExpectationException * @param string $link the text of the link. * @param number $expectedsize the expected file size in bytes. */ public function following_should_download_bytes($link, $expectedsize) { $exception = new ExpectationException('Error while downloading data from ' . $link, $this->getSession()); // It will stop spinning once file is downloaded or time out. $result = $this->spin( function($context, $args) { $link = $args['link']; return $this->download_file_from_link($link); }, array('link' => $link), behat_base::get_extended_timeout(), $exception ); // Check download size. $actualsize = (int)strlen($result); if ($actualsize !== (int)$expectedsize) { throw new ExpectationException('Downloaded data was ' . $actualsize . ' bytes, expecting ' . $expectedsize, $this->getSession()); } } /** * Downloads the file from a link on the page and checks the size is in a given range. * * Only works if the link has an href attribute. Javascript downloads are * not supported. Currently, the href must be an absolute URL. * * The range includes the endpoints. That is, a 10 byte file in considered to * be between "5" and "10" bytes, and between "10" and "20" bytes. * * @Then /^following "(?P<link_string>[^"]*)" should download between "(?P<min_bytes>\d+)" and "(?P<max_bytes>\d+)" bytes$/ * @throws ExpectationException * @param string $link the text of the link. * @param number $minexpectedsize the minimum expected file size in bytes. * @param number $maxexpectedsize the maximum expected file size in bytes. */ public function following_should_download_between_and_bytes($link, $minexpectedsize, $maxexpectedsize) { // If the minimum is greater than the maximum then swap the values. if ((int)$minexpectedsize > (int)$maxexpectedsize) { list($minexpectedsize, $maxexpectedsize) = array($maxexpectedsize, $minexpectedsize); } $exception = new ExpectationException('Error while downloading data from ' . $link, $this->getSession()); // It will stop spinning once file is downloaded or time out. $result = $this->spin( function($context, $args) { $link = $args['link']; return $this->download_file_from_link($link); }, array('link' => $link), behat_base::get_extended_timeout(), $exception ); // Check download size. $actualsize = (int)strlen($result); if ($actualsize < $minexpectedsize || $actualsize > $maxexpectedsize) { throw new ExpectationException('Downloaded data was ' . $actualsize . ' bytes, expecting between ' . $minexpectedsize . ' and ' . $maxexpectedsize, $this->getSession()); } } /** * Checks that the image on the page is the same as one of the fixture files * * @Then /^the image at "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" should be identical to "(?P<filepath_string>(?:[^"]|\\")*)"$/ * @throws ExpectationException * @param string $element The locator of the image * @param string $selectortype The selector type * @param string $filepath path to the fixture file */ public function the_image_at_should_be_identical_to($element, $selectortype, $filepath) { global $CFG; // Get the container node (exception if it doesn't exist). $containernode = $this->get_selected_node($selectortype, $element); $url = $containernode->getAttribute('src'); if ($url == null) { throw new ExpectationException('Element does not have src attribute', $this->getSession()); } $session = $this->getSession()->getCookie('MoodleSession'); $content = download_file_content($url, array('Cookie' => 'MoodleSession=' . $session)); // Get the content of the fixture file. // Replace 'admin/' if it is in start of path with $CFG->admin . if (substr($filepath, 0, 6) === 'admin/') { $filepath = $CFG->admin . DIRECTORY_SEPARATOR . substr($filepath, 6); } $filepath = str_replace('/', DIRECTORY_SEPARATOR, $filepath); $filepath = $CFG->dirroot . DIRECTORY_SEPARATOR . $filepath; if (!is_readable($filepath)) { throw new ExpectationException('The file to compare to does not exist.', $this->getSession()); } $expectedcontent = file_get_contents($filepath); if ($content !== $expectedcontent) { throw new ExpectationException('Image is not identical to the fixture. Received ' . strlen($content) . ' bytes and expected ' . strlen($expectedcontent) . ' bytes'); } } /** * Prepare to detect whether or not a new page has loaded (or the same page reloaded) some time in the future. * * @Given /^I start watching to see if a new page loads$/ */ public function i_start_watching_to_see_if_a_new_page_loads() { if (!$this->running_javascript()) { throw new DriverException('Page load detection requires JavaScript.'); } $session = $this->getSession(); if ($this->pageloaddetectionrunning || $session->getPage()->find('xpath', $this->get_page_load_xpath())) { // If we find this node at this point we are already watching for a reload and the behat steps // are out of order. We will treat this as an error - really it needs to be fixed as it indicates a problem. throw new ExpectationException( 'Page load expectation error: page reloads are already been watched for.', $session); } $this->pageloaddetectionrunning = true; $this->execute_script( 'var span = document.createElement("span"); span.setAttribute("data-rel", "' . self::PAGE_LOAD_DETECTION_STRING . '"); span.setAttribute("style", "display: none;"); document.body.appendChild(span);' ); } /** * Verify that a new page has loaded (or the same page has reloaded) since the * last "I start watching to see if a new page loads" step. * * @Given /^a new page should have loaded since I started watching$/ */ public function a_new_page_should_have_loaded_since_i_started_watching() { $session = $this->getSession(); // Make sure page load tracking was started. if (!$this->pageloaddetectionrunning) { throw new ExpectationException( 'Page load expectation error: page load tracking was not started.', $session); } // As the node is inserted by code above it is either there or not, and we do not need spin and it is safe // to use the native API here which is great as exception handling (the alternative is slow). if ($session->getPage()->find('xpath', $this->get_page_load_xpath())) { // We don't want to find this node, if we do we have an error. throw new ExpectationException( 'Page load expectation error: a new page has not been loaded when it should have been.', $session); } // Cancel the tracking of pageloaddetectionrunning. $this->pageloaddetectionrunning = false; } /** * Verify that a new page has not loaded (or the same page has reloaded) since the * last "I start watching to see if a new page loads" step. * * @Given /^a new page should not have loaded since I started watching$/ */ public function a_new_page_should_not_have_loaded_since_i_started_watching() { $session = $this->getSession(); // Make sure page load tracking was started. if (!$this->pageloaddetectionrunning) { throw new ExpectationException( 'Page load expectation error: page load tracking was not started.', $session); } // We use our API here as we can use the exception handling provided by it. $this->find( 'xpath', $this->get_page_load_xpath(), new ExpectationException( 'Page load expectation error: A new page has been loaded when it should not have been.', $this->getSession() ) ); } /** * Helper used by {@link a_new_page_should_have_loaded_since_i_started_watching} * and {@link a_new_page_should_not_have_loaded_since_i_started_watching} * @return string xpath expression. */ protected function get_page_load_xpath() { return "//span[@data-rel = '" . self::PAGE_LOAD_DETECTION_STRING . "']"; } /** * Wait unit user press Enter/Return key. Useful when debugging a scenario. * * @Then /^(?:|I )pause(?:| scenario execution)$/ */ public function i_pause_scenario_execution() { $message = "<colour:lightYellow>Paused. Press <colour:lightRed>Enter/Return<colour:lightYellow> to continue."; behat_util::pause($this->getSession(), $message); } /** * Presses a given button in the browser. * NOTE: Phantomjs and goutte driver reloads page while navigating back and forward. * * @Then /^I press the "(back|forward|reload)" button in the browser$/ * @param string $button the button to press. * @throws ExpectationException */ public function i_press_in_the_browser($button) { $session = $this->getSession(); if ($button == 'back') { $session->back(); } else if ($button == 'forward') { $session->forward(); } else if ($button == 'reload') { $session->reload(); } else { throw new ExpectationException('Unknown browser button.', $session); } } /** * Send key presses to the browser without first changing focusing, or applying the key presses to a specific * element. * * Example usage of this step: * When I type "Penguin" * * @When I type :keys * @param string $keys The key, or list of keys, to type */ public function i_type(string $keys): void { behat_base::type_keys($this->getSession(), str_split($keys)); } /** * Press a named key with an optional set of modifiers. * * Supported named keys are: * - up * - down * - left * - right * - pageup|page_up * - pagedown|page_down * - home * - end * - insert * - delete * - backspace * - escape * - enter * - tab * * Supported moderators are: * - shift * - ctrl * - alt * - meta * * Example usage of this new step: * When I press the up key * When I press the space key * When I press the shift tab key * * Multiple moderator keys can be combined using the '+' operator, for example: * When I press the ctrl+shift enter key * When I press the ctrl + shift enter key * * @When /^I press the (?P<modifiers_string>.* )?(?P<key_string>.*) key$/ * @param string $modifiers A list of keyboard modifiers, separated by the `+` character * @param string $key The name of the key to press */ public function i_press_named_key(string $modifiers, string $key): void { behat_base::require_javascript_in_session($this->getSession()); $keys = []; foreach (explode('+', $modifiers) as $modifier) { switch (strtoupper(trim($modifier))) { case '': break; case 'SHIFT': $keys[] = behat_keys::SHIFT; break; case 'CTRL': $keys[] = behat_keys::CONTROL; break; case 'ALT': $keys[] = behat_keys::ALT; break; case 'META': $keys[] = behat_keys::META; break; default: throw new \coding_exception("Unknown modifier key '$modifier'}"); } } $modifier = trim($key); switch (strtoupper($key)) { case 'UP': $keys[] = behat_keys::UP_ARROW; break; case 'DOWN': $keys[] = behat_keys::DOWN_ARROW; break; case 'LEFT': $keys[] = behat_keys::LEFT_ARROW; break; case 'RIGHT': $keys[] = behat_keys::RIGHT_ARROW; break; case 'HOME': $keys[] = behat_keys::HOME; break; case 'END': $keys[] = behat_keys::END; break; case 'INSERT': $keys[] = behat_keys::INSERT; break; case 'BACKSPACE': $keys[] = behat_keys::BACKSPACE; break; case 'DELETE': $keys[] = behat_keys::DELETE; break; case 'PAGEUP': case 'PAGE_UP': $keys[] = behat_keys::PAGE_UP; break; case 'PAGEDOWN': case 'PAGE_DOWN': $keys[] = behat_keys::PAGE_DOWN; break; case 'ESCAPE': $keys[] = behat_keys::ESCAPE; break; case 'ENTER': $keys[] = behat_keys::ENTER; break; case 'TAB': $keys[] = behat_keys::TAB; break; case 'SPACE': $keys[] = behat_keys::SPACE; break; default: throw new \coding_exception("Unknown key '$key'}"); } // Always send the NULL key as the last key. $keys[] = behat_keys::NULL_KEY; behat_base::type_keys($this->getSession(), $keys); } /** * Trigger a keydown event for a key on a specific element. * * @When /^I press key "(?P<key_string>(?:[^"]|\\")*)" in "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)"$/ * @param string $key either char-code or character itself, * may optionally be prefixed with ctrl-, alt-, shift- or meta- * @param string $element Element we look for * @param string $selectortype The type of what we look for * @throws DriverException * @throws ExpectationException */ public function i_press_key_in_element($key, $element, $selectortype) { if (!$this->running_javascript()) { throw new DriverException('Key down step is not available with Javascript disabled'); } // Gets the node based on the requested selector type and locator. $node = $this->get_selected_node($selectortype, $element); $modifier = null; $validmodifiers = array('ctrl', 'alt', 'shift', 'meta'); $char = $key; if (strpos($key, '-')) { list($modifier, $char) = preg_split('/-/', $key, 2); $modifier = strtolower($modifier); if (!in_array($modifier, $validmodifiers)) { throw new ExpectationException(sprintf('Unknown key modifier: %s.', $modifier)); } } if (is_numeric($char)) { $char = (int)$char; } $node->keyDown($char, $modifier); $node->keyPress($char, $modifier); $node->keyUp($char, $modifier); } /** * Press tab key on a specific element. * * @When /^I press tab key in "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)"$/ * @param string $element Element we look for * @param string $selectortype The type of what we look for * @throws DriverException * @throws ExpectationException */ public function i_post_tab_key_in_element($element, $selectortype) { if (!$this->running_javascript()) { throw new DriverException('Tab press step is not available with Javascript disabled'); } // Gets the node based on the requested selector type and locator. $node = $this->get_selected_node($selectortype, $element); $this->execute('behat_general::i_click_on', [$node, 'NodeElement']); $this->execute('behat_general::i_press_named_key', ['', 'tab']); } /** * Checks if database family used is using one of the specified, else skip. (mysql, postgres, mssql, oracle, etc.) * * @Given /^database family used is one of the following:$/ * @param TableNode $databasefamilies list of database. * @return void. * @throws \Moodle\BehatExtension\Exception\SkippedException */ public function database_family_used_is_one_of_the_following(TableNode $databasefamilies) { global $DB; $dbfamily = $DB->get_dbfamily(); // Check if used db family is one of the specified ones. If yes then return. foreach ($databasefamilies->getRows() as $dbfamilytocheck) { if ($dbfamilytocheck[0] == $dbfamily) { return; } } throw new \Moodle\BehatExtension\Exception\SkippedException(); } /** * Checks focus is with the given element. * * @Then /^the focused element is( not)? "(?P<node_string>(?:[^"]|\\")*)" "(?P<node_selector_string>[^"]*)"$/ * @param string $not optional step verifier * @param string $nodeelement Element identifier * @param string $nodeselectortype Element type * @throws DriverException If not using JavaScript * @throws ExpectationException */ public function the_focused_element_is($not, $nodeelement, $nodeselectortype) { if (!$this->running_javascript()) { throw new DriverException('Checking focus on an element requires JavaScript'); } $element = $this->find($nodeselectortype, $nodeelement); $xpath = addslashes_js($element->getXpath()); $script = 'return (function() { return document.activeElement === document.evaluate("' . $xpath . '", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; })(); '; $targetisfocused = $this->evaluate_script($script); if ($not == ' not') { if ($targetisfocused) { throw new ExpectationException("$nodeelement $nodeselectortype is focused", $this->getSession()); } } else { if (!$targetisfocused) { throw new ExpectationException("$nodeelement $nodeselectortype is not focused", $this->getSession()); } } } /** * Checks focus is with the given element. * * @Then /^the focused element is( not)? "(?P<n>(?:[^"]|\\")*)" "(?P<ns>[^"]*)" in the "(?P<c>(?:[^"]|\\")*)" "(?P<cs>[^"]*)"$/ * @param string $not string optional step verifier * @param string $element Element identifier * @param string $selectortype Element type * @param string $nodeelement Element we look in * @param string $nodeselectortype The type of selector where we look in * @throws DriverException If not using JavaScript * @throws ExpectationException */ public function the_focused_element_is_in_the($not, $element, $selectortype, $nodeelement, $nodeselectortype) { if (!$this->running_javascript()) { throw new DriverException('Checking focus on an element requires JavaScript'); } $element = $this->get_node_in_container($selectortype, $element, $nodeselectortype, $nodeelement); $xpath = addslashes_js($element->getXpath()); $script = 'return (function() { return document.activeElement === document.evaluate("' . $xpath . '", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; })(); '; $targetisfocused = $this->evaluate_script($script); if ($not == ' not') { if ($targetisfocused) { throw new ExpectationException("$nodeelement $nodeselectortype is focused", $this->getSession()); } } else { if (!$targetisfocused) { throw new ExpectationException("$nodeelement $nodeselectortype is not focused", $this->getSession()); } } } /** * Manually press tab key. * * @When /^I press( shift)? tab$/ * @param string $shift string optional step verifier * @throws DriverException */ public function i_manually_press_tab($shift = '') { if (empty($shift)) { $this->execute('behat_general::i_press_named_key', ['', 'tab']); } else { $this->execute('behat_general::i_press_named_key', ['shift', 'tab']); } } /** * Trigger click on node via javascript instead of actually clicking on it via pointer. * This function resolves the issue of nested elements. * * @When /^I click on "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" skipping visibility check$/ * @param string $element * @param string $selectortype */ public function i_click_on_skipping_visibility_check($element, $selectortype) { // Gets the node based on the requested selector type and locator. $node = $this->get_selected_node($selectortype, $element); $this->js_trigger_click($node); } /** * Checks, that the specified element contains the specified text a certain amount of times. * When running Javascript tests it also considers that texts may be hidden. * * @Then /^I should see "(?P<elementscount_number>\d+)" occurrences of "(?P<text_string>(?:[^"]|\\")*)" in the "(?P<element_string>(?:[^"]|\\")*)" "(?P<text_selector_string>[^"]*)"$/ * @throws ElementNotFoundException * @throws ExpectationException * @param int $elementscount How many occurrences of the element we look for. * @param string $text * @param string $element Element we look in. * @param string $selectortype The type of element where we are looking in. */ public function i_should_see_occurrences_of_in_element($elementscount, $text, $element, $selectortype) { // Getting the container where the text should be found. $container = $this->get_selected_node($selectortype, $element); // Looking for all the matching nodes without any other descendant matching the // same xpath (we are using contains(., ....). $xpathliteral = behat_context_helper::escape($text); $xpath = "/descendant-or-self::*[contains(., $xpathliteral)]" . "[count(descendant::*[contains(., $xpathliteral)]) = 0]"; $nodes = $this->find_all('xpath', $xpath, false, $container); if ($this->running_javascript()) { $nodes = array_filter($nodes, function($node) { return $node->isVisible(); }); } if ($elementscount != count($nodes)) { throw new ExpectationException('Found '.count($nodes).' elements in column. Expected '.$elementscount, $this->getSession()); } } /** * Manually press enter key. * * @When /^I press enter/ * @throws DriverException */ public function i_manually_press_enter() { $this->execute('behat_general::i_press_named_key', ['', 'enter']); } /** * Visit a local URL relative to the behat root. * * @When I visit :localurl * * @param string|moodle_url $localurl The URL relative to the behat_wwwroot to visit. */ public function i_visit($localurl): void { $localurl = new moodle_url($localurl); $this->getSession()->visit($this->locate_path($localurl->out_as_local_url(false))); } }
gpl-3.0
pressbooks/pressbooks
assets/src/scripts/login.js
865
/* global PB_Login */ const h1 = document.querySelector( 'h1' ); const login = document.querySelector( 'div#login' ); let subtitle = document.createElement( 'p' ); subtitle.classList.add( 'subtitle' ); if ( document.body.classList.contains( 'login-action-login' ) ) { subtitle.textContent = PB_Login.logInTitle; } else if ( document.body.classList.contains( 'login-action-lostpassword' ) ) { subtitle.textContent = PB_Login.lostPasswordTitle; } else if ( document.body.classList.contains( 'login-action-rp' ) ) { subtitle.textContent = PB_Login.resetPasswordTitle; } else if ( document.body.classList.contains( 'login-action-resetpass' ) ) { subtitle.textContent = PB_Login.passwordResetTitle; } else { subtitle.textContent = PB_Login.logInTitle; } document.body.insertBefore( h1, document.body.firstChild ); login.insertBefore( subtitle, login.firstChild );
gpl-3.0
google-code-export/webical
webical-core/src/main/java/org/webical/web/component/event/EventFormPanel.java
3191
/* * Webical - http://www.webical.org * Copyright (C) 2007 Func. Internet Integration * * This file is part of Webical. * * $Id$ * * 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.webical.web.component.event; import java.util.GregorianCalendar; import org.apache.wicket.markup.repeater.RepeatingView; import org.apache.wicket.model.IModel; import org.webical.Event; import org.webical.util.CalendarUtils; import org.webical.web.action.IAction; import org.webical.web.component.AbstractBasePanel; import org.webical.web.component.behavior.FormComponentValidationStyleBehavior; import org.webical.web.event.ExtensionPoint; /** * Creates an add/edit for for an event depending on whether a Event is provided or null * @author jochem * @author Mattijs Hoitink */ public abstract class EventFormPanel extends AbstractBasePanel { private static final long serialVersionUID = 1L; public static final String FORM_EXTENSIONS_MARKUP_ID = "formExtensions"; private static final String EVENT_ADD_EDIT_FORM_MARKUP_ID = "eventForm"; private GregorianCalendar date = null; private Event editEvent; private IModel eventModel; /** * Constructor * @param markupId The ID used in the markup * @param event The Event to be edited or null when a new event is edited * @param date */ public EventFormPanel(String markupId, Event editEvent, GregorianCalendar date) { super(markupId, EventFormPanel.class); // set variables needed the form this.editEvent = editEvent; this.date = CalendarUtils.duplicateCalendar(date); } public void setupCommonComponents() { // Create a new EventForm EventForm eventForm = new EventForm(EVENT_ADD_EDIT_FORM_MARKUP_ID, editEvent, this.date) { private static final long serialVersionUID = 1L; @Override public void onAction(IAction action) { EventFormPanel.this.onAction(action); } }; eventForm.add(new FormComponentValidationStyleBehavior()); //Create and register a new extensionpoint for plugins RepeatingView extensionPoint = new RepeatingView(FORM_EXTENSIONS_MARKUP_ID); getExtensionPoints().put(FORM_EXTENSIONS_MARKUP_ID, new ExtensionPoint(extensionPoint, eventModel)); //Add the components eventForm.add(extensionPoint); addOrReplace(eventForm); } public void setupAccessibleComponents() { // NOT IMPLEMENTED } public void setupNonAccessibleComponents() { // NOT IMPLEMENTED } /** * Handle actions generated by this panel * @param action The action to handle */ public abstract void onAction(IAction action); }
gpl-3.0
Fatalerror66/ffxi-a
scripts/globals/items/fire_feather.lua
681
----------------------------------------- -- ID: 5256 -- Item: Fire Feather -- Effect: Enfire ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) if(target:addStatusEffect(EFFECT_ENFIRE,25,0,90)) then target:messageBasic(205); else target:messageBasic(423); -- no effect end end;
gpl-3.0
mrtenda/CoilSnake
coilsnake/modules/eb/StaffModule.py
8738
import logging from coilsnake.exceptions.common.exceptions import CoilSnakeError, InvalidUserDataError from coilsnake.modules.eb.EbModule import EbModule from coilsnake.util.common.assets import open_asset from coilsnake.util.common.yml import yml_load from coilsnake.util.eb.pointer import from_snes_address, to_snes_address log = logging.getLogger(__name__) STAFF_TEXT_POINTER_OFFSET = 0x4f253 LENGTH_OFFSETS = [0x4f583, 0x4f58c, 0x4f66f] MODE_CONTROL = 0 MODE_SMALL = 1 MODE_BIG = 2 MODE_SPACE = 3 HEIGHT_SMALL = 8 HEIGHT_BIG = 16 CONTROL_END_OF_LINE = 0x00 CONTROL_SMALL = 0x01 CONTROL_BIG = 0x02 CONTROL_SPACE = 0x03 CONTROL_PLAYER_NAME = 0x04 CONTROL_END_OF_STAFF = 0xff MAX_ROW = 0xf - 0x4 MAX_COL = 0xf SCREEN_WIDTH_IN_TILES = 32 ENTRY_TYPE = 'Type' ENTRY_ROW = 'Row' ENTRY_COL = 'Column' ENTRY_CHAR = 'Character' STAFF_CHARS_FILE_NAME = 'Staff/staff_chars' STAFF_TEXT_FILE_NAME = 'Staff/staff_text' KEYWORD_BYTE_HEIGHT = { 'player_name': (CONTROL_PLAYER_NAME, HEIGHT_BIG) } class StaffModule(EbModule): NAME = 'Staff' FREE_RANGES = [(0x21413f, 0x214de7)] def __init__(self): self.big = {} self.small = {} self.data = [] self.height = 0 @staticmethod def check_row_col_error(name, val, max_val): if val > max_val: raise InvalidUserDataError( 'Invalid \'{}\'={} - should be between 0 and {}.'.format( name, val, max_val ) ) def read_staff_chars(self, yml_data): log.debug('Reading staff character-to-code mapping') for k, v in yml_data.items(): vrow = v[ENTRY_ROW] vcol = v[ENTRY_COL] self.check_row_col_error(ENTRY_ROW, vrow, MAX_ROW) self.check_row_col_error(ENTRY_COL, vcol, MAX_COL) vtile = (vrow << 4) | vcol vtype = v[ENTRY_TYPE] vchar = v[ENTRY_CHAR] if vtype == 'big': self.big[str(vchar)] = vtile + 0x40 elif vtype == 'small': self.small[str(vchar)] = vtile + 0x40 else: raise InvalidUserDataError( 'Invalid \'{}\' for entry with \'{}\'={}, \'{}\'={} and \'{}\'={}.'.format( ENTRY_TYPE, ENTRY_ROW, vrow, ENTRY_COL, vcol, ENTRY_CHAR, vchar ) ) def read_staff_chars_from_assets(self): with open_asset('structures', 'eb_staff_chars.yml') as f: yml_data = yml_load(f) self.read_staff_chars(yml_data) def read_staff_chars_from_project(self, resource_open): with resource_open(STAFF_CHARS_FILE_NAME, 'yml', True) as f: yml_data = yml_load(f) self.read_staff_chars(yml_data) def read_text_line_from_project(self, byte, line, mapping, height): self.data.append(byte) if not line: line = ' ' for char in line: self.data.append(mapping[char]) self.data.append(CONTROL_END_OF_LINE) self.height += height def read_small_line_from_project(self, line): self.read_text_line_from_project(CONTROL_SMALL, line, self.small, HEIGHT_SMALL) def read_big_line_from_project(self, line): self.read_text_line_from_project(CONTROL_BIG, line, self.big, HEIGHT_BIG) def read_space_from_project(self, how_much): if how_much == 0: # Ignore zero-sized space return self.data.append(CONTROL_SPACE) self.data.append(how_much) self.height += HEIGHT_SMALL * how_much def read_keyword_from_project(self, keyword): if keyword not in KEYWORD_BYTE_HEIGHT: raise InvalidUserDataError( 'Invalid keyword={} in {}.yml - should be one of {}.'.format( keyword, name, KEYWORD_BYTE_HEIGHT.keys() ) ) byte, height = KEYWORD_BYTE_HEIGHT[keyword] self.data.append(byte) self.height += height def read_staff_text_from_project(self, resource_open): with resource_open(STAFF_TEXT_FILE_NAME, 'md', True) as f: line = f.readline() while line: line = line.strip() if not line: line = f.readline() continue text = line[1:].lstrip() mark = line[0] line = f.readline() if mark == '>': self.read_space_from_project(int(text)) elif mark not in ['#', '-']: self.read_keyword_from_project(mark + text) elif len(text) > SCREEN_WIDTH_IN_TILES: raise InvalidUserDataError( 'Text \'{}\' is too long - must have at most {} characters'.format( text, SCREEN_WIDTH_IN_TILES ) ) elif mark == '#': self.read_small_line_from_project(text) else: self.read_big_line_from_project(text) self.data.append(CONTROL_END_OF_STAFF) def print_keyword(self, f, byte): for item in KEYWORD_BYTE_HEIGHT.items(): keyword, v = item b, h = v if byte == b: f.write('{}\n'.format(keyword)) return MODE_CONTROL else: raise CoilSnakeError('Unknown control byte 0x{:X}'.format(byte)) def print_control(self, f, byte): if byte == CONTROL_SMALL: f.write('# ') return MODE_SMALL elif byte == CONTROL_BIG: f.write('- ') return MODE_BIG elif byte == CONTROL_SPACE: f.write('> ') return MODE_SPACE elif byte == CONTROL_END_OF_STAFF: return MODE_CONTROL else: return self.print_keyword(f, byte) def print_space(self, f, byte): f.write('{}\n\n'.format(byte)) return MODE_CONTROL def print_char(self, f, byte, mode, mapping_big, mapping_small): if byte == CONTROL_END_OF_LINE: f.write('\n') return MODE_CONTROL if mode == MODE_BIG: f.write(mapping_big[byte]) else: f.write(mapping_small[byte]) return mode def read_pointer_from_rom(self, rom): return ( (rom[STAFF_TEXT_POINTER_OFFSET + 6] << 16) | rom.read_multi(STAFF_TEXT_POINTER_OFFSET, 2) ) def write_pointer_to_rom(self, rom, pointer): rom[STAFF_TEXT_POINTER_OFFSET + 6] = pointer >> 16 rom.write_multi(STAFF_TEXT_POINTER_OFFSET, pointer & 0xFFFF, 2) def read_from_rom(self, rom): staff_text_offset = from_snes_address(self.read_pointer_from_rom(rom)) self.read_staff_chars_from_assets() log.debug('Reading staff text') i = 0 byte = 0x00 while byte != CONTROL_END_OF_STAFF: byte = rom[staff_text_offset + i] self.data.append(byte) i += 1 def write_to_rom(self, rom): offset = rom.allocate(size=len(self.data)) self.write_pointer_to_rom(rom, to_snes_address(offset)) log.debug('Writing staff text') rom[offset:offset + len(self.data)] = self.data for length_offset in LENGTH_OFFSETS: rom.write_multi(length_offset, self.height, 2) def read_from_project(self, resource_open): self.read_staff_chars_from_project(resource_open) log.debug('Reading staff text') self.read_staff_text_from_project(resource_open) def write_to_project(self, resource_open): mode = MODE_CONTROL invbig = {v: k for (k, v) in self.big.items()} invsmall = {v: k for (k, v) in self.small.items()} with open_asset('structures', 'eb_staff_chars.yml') as f: staff_chars = f.read() with resource_open(STAFF_CHARS_FILE_NAME, 'yml', True) as f: f.write(staff_chars) with resource_open(STAFF_TEXT_FILE_NAME, 'md', True) as f: for byte in self.data: if mode == MODE_CONTROL: mode = self.print_control(f, byte) elif mode == MODE_SPACE: mode = self.print_space(f, byte) else: mode = self.print_char(f, byte, mode, invbig, invsmall) def upgrade_project(self, old_version, new_version, rom, resource_open_r, resource_open_w, resource_delete): if old_version < 10: self.read_from_rom(rom) self.write_to_project(resource_open_w)
gpl-3.0
mpitid/pylabelme
shape.py
6219
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid. # # This file is part of Labelme. # # Labelme 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. # # Labelme 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 Labelme. If not, see <http://www.gnu.org/licenses/>. # from PyQt4.QtGui import * from PyQt4.QtCore import * from lib import distance # TODO: # - [opt] Store paths instead of creating new ones at each paint. DEFAULT_LINE_COLOR = QColor(0, 255, 0, 128) DEFAULT_FILL_COLOR = QColor(255, 0, 0, 128) DEFAULT_SELECT_LINE_COLOR = QColor(255, 255, 255) DEFAULT_SELECT_FILL_COLOR = QColor(0, 128, 255, 155) DEFAULT_VERTEX_FILL_COLOR = QColor(0, 255, 0, 255) DEFAULT_HVERTEX_FILL_COLOR = QColor(255, 0, 0) class Shape(object): P_SQUARE, P_ROUND = range(2) MOVE_VERTEX, NEAR_VERTEX = range(2) ## The following class variables influence the drawing ## of _all_ shape objects. line_color = DEFAULT_LINE_COLOR fill_color = DEFAULT_FILL_COLOR select_line_color = DEFAULT_SELECT_LINE_COLOR select_fill_color = DEFAULT_SELECT_FILL_COLOR vertex_fill_color = DEFAULT_VERTEX_FILL_COLOR hvertex_fill_color = DEFAULT_HVERTEX_FILL_COLOR point_type = P_ROUND point_size = 8 scale = 1.0 def __init__(self, label=None, line_color=None): self.label = label self.points = [] self.fill = False self.selected = False self._highlightIndex = None self._highlightMode = self.NEAR_VERTEX self._highlightSettings = { self.NEAR_VERTEX: (4, self.P_ROUND), self.MOVE_VERTEX: (1.5, self.P_SQUARE), } self._closed = False if line_color is not None: # Override the class line_color attribute # with an object attribute. Currently this # is used for drawing the pending line a different color. self.line_color = line_color def close(self): assert len(self.points) > 2 self._closed = True def addPoint(self, point): if self.points and point == self.points[0]: self.close() else: self.points.append(point) def popPoint(self): if self.points: return self.points.pop() return None def isClosed(self): return self._closed def setOpen(self): self._closed = False def paint(self, painter): if self.points: color = self.select_line_color if self.selected else self.line_color pen = QPen(color) # Try using integer sizes for smoother drawing(?) pen.setWidth(max(1, int(round(2.0 / self.scale)))) painter.setPen(pen) line_path = QPainterPath() vrtx_path = QPainterPath() line_path.moveTo(self.points[0]) # Uncommenting the following line will draw 2 paths # for the 1st vertex, and make it non-filled, which # may be desirable. #self.drawVertex(vrtx_path, 0) for i, p in enumerate(self.points): line_path.lineTo(p) self.drawVertex(vrtx_path, i) if self.isClosed(): line_path.lineTo(self.points[0]) painter.drawPath(line_path) painter.drawPath(vrtx_path) painter.fillPath(vrtx_path, self.vertex_fill_color) if self.fill: color = self.select_fill_color if self.selected else self.fill_color painter.fillPath(line_path, color) def drawVertex(self, path, i): d = self.point_size / self.scale shape = self.point_type point = self.points[i] if i == self._highlightIndex: size, shape = self._highlightSettings[self._highlightMode] d *= size if self._highlightIndex is not None: self.vertex_fill_color = self.hvertex_fill_color else: self.vertex_fill_color = Shape.vertex_fill_color if shape == self.P_SQUARE: path.addRect(point.x() - d/2, point.y() - d/2, d, d) elif shape == self.P_ROUND: path.addEllipse(point, d/2.0, d/2.0) else: assert False, "unsupported vertex shape" def nearestVertex(self, point, epsilon): for i, p in enumerate(self.points): if distance(p - point) <= epsilon: return i return None def containsPoint(self, point): return self.makePath().contains(point) def makePath(self): path = QPainterPath(self.points[0]) for p in self.points[1:]: path.lineTo(p) return path def boundingRect(self): return self.makePath().boundingRect() def moveBy(self, offset): self.points = [p + offset for p in self.points] def moveVertexBy(self, i, offset): self.points[i] = self.points[i] + offset def highlightVertex(self, i, action): self._highlightIndex = i self._highlightMode = action def highlightClear(self): self._highlightIndex = None def copy(self): shape = Shape("Copy of %s" % self.label ) shape.points= [p for p in self.points] shape.fill = self.fill shape.selected = self.selected shape._closed = self._closed if self.line_color != Shape.line_color: shape.line_color = self.line_color if self.fill_color != Shape.fill_color: shape.fill_color = self.fill_color return shape def __len__(self): return len(self.points) def __getitem__(self, key): return self.points[key] def __setitem__(self, key, value): self.points[key] = value
gpl-3.0
andforce/Beebo
app/src/main/java/org/zarroboogs/weibo/setting/SettingUtils.java
12435
package org.zarroboogs.weibo.setting; import org.zarroboogs.weibo.BeeboApplication; import org.zarroboogs.weibo.R; import org.zarroboogs.weibo.setting.activity.SettingActivity; import org.zarroboogs.weibo.support.utils.AppConfig; import org.zarroboogs.weibo.support.utils.Utility; import android.content.Context; public class SettingUtils { private static final String FIRSTSTART = "firststart"; private static final String LAST_FOUND_WEIBO_ACCOUNT_LINK = "last_found_weibo_account_link"; private static final String BLACK_MAGIC = "black_magic"; private static final String CLICK_TO_TOP_TIP = "click_to_top_tip"; private SettingUtils() { } public static boolean isDebug() { return false; } public static void setDefaultAccountId(String id) { SettingHelper.setEditor(getContext(), "id", id); } public static String getDefaultAccountId() { return SettingHelper.getSharedPreferences(getContext(), "id", ""); } private static Context getContext() { return BeeboApplication.getInstance(); } public static boolean firstStart() { boolean value = SettingHelper.getSharedPreferences(getContext(), FIRSTSTART, true); if (value) { SettingHelper.setEditor(getContext(), FIRSTSTART, false); } return value; } public static int getFontSize() { String value = SettingHelper.getSharedPreferences(getContext(), SettingActivity.FONT_SIZE, "15"); return Integer.valueOf(value); } public static int getAppTheme() { String value = SettingHelper.getSharedPreferences(getContext(), SettingActivity.THEME, "1"); switch (Integer.valueOf(value)) { // case 1: // return R.style.AppTheme_Light; // // case 2: // return R.style.AppTheme_Dark; default: return R.style.AppTheme_Light; } } public static void switchToAnotherTheme() { String value = SettingHelper.getSharedPreferences(getContext(), SettingActivity.THEME, "1"); switch (Integer.valueOf(value)) { case 1: SettingHelper.setEditor(getContext(), SettingActivity.THEME, "2"); break; case 2: SettingHelper.setEditor(getContext(), SettingActivity.THEME, "1"); break; default: SettingHelper.setEditor(getContext(), SettingActivity.THEME, "1"); break; } } public static int getHighPicMode() { String value = SettingHelper.getSharedPreferences(getContext(), SettingActivity.LIST_HIGH_PIC_MODE, "2"); return Integer.valueOf(value); } public static int getCommentRepostAvatar() { String value = SettingHelper.getSharedPreferences(getContext(), SettingActivity.COMMENT_REPOST_AVATAR, "1"); return Integer.valueOf(value); } public static int getListAvatarMode() { String value = SettingHelper.getSharedPreferences(getContext(), SettingActivity.LIST_AVATAR_MODE, "1"); return Integer.valueOf(value); } public static int getListPicMode() { String value = SettingHelper.getSharedPreferences(getContext(), SettingActivity.LIST_PIC_MODE, "3"); return Integer.valueOf(value); } public static void setEnableCommentRepostAvatar(boolean value) { SettingHelper.setEditor(getContext(), SettingActivity.SHOW_COMMENT_REPOST_AVATAR, value); } public static boolean getEnableCommentRepostListAvatar() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.SHOW_COMMENT_REPOST_AVATAR, true); } public static int getNotificationStyle() { String value = SettingHelper.getSharedPreferences(getContext(), SettingActivity.JBNOTIFICATION_STYLE, "1"); switch (Integer.valueOf(value)) { case 1: return 1; case 2: return 2; default: return 1; } } public static boolean isEnablePic() { return !SettingHelper.getSharedPreferences(getContext(), SettingActivity.DISABLE_DOWNLOAD_AVATAR_PIC, false); } public static boolean getEnableBigPic() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.SHOW_BIG_PIC, false); } public static boolean getEnableFetchMSG() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.ENABLE_FETCH_MSG, true); } // water mark setting public static boolean getEnableWaterMark() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.WATER_MARK_ENABLE, true); } /* * public static final String WATER_MARK_SCREEN_NAME = "water_mark_screen_name"; public static * final String WATER_MARK_WEIBO_ICON = "water_mark_weibo_icon"; public static final String * WATER_MARK_WEIBO_URL = "water_mark_weibo_url"; public static final String WATER_MARK_POS = * "water_mark_pos"; public static final String WATER_MARK_ENABLE = "water_mark_enable"; */ public static boolean isWaterMarkScreenNameShow() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.WATER_MARK_SCREEN_NAME, true); } public static boolean isWaterMarkWeiboICONShow() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.WATER_MARK_WEIBO_ICON, true); } public static boolean isWaterMarkWeiboURlShow() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.WATER_MARK_WEIBO_URL, true); } public static String getWaterMarkPos() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.WATER_MARK_POS, "1"); } // end water mark setting public static boolean getEnableAutoRefresh() { return false; // return SettingHelper.getSharedPreferences(getContext(), SettingActivity.AUTO_REFRESH, false); } public static boolean getEnableBigAvatar() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.SHOW_BIG_AVATAR, false); } public static boolean getEnableSound() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.SOUND_OF_PULL_TO_FRESH, true) && Utility.isSystemRinger(getContext()); } public static boolean disableFetchAtNight() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.DISABLE_FETCH_AT_NIGHT, true) && Utility.isSystemRinger(getContext()); } public static String getFrequency() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.FREQUENCY, "1"); } public static void setEnableBigPic(boolean value) { SettingHelper.setEditor(getContext(), SettingActivity.SHOW_BIG_PIC, value); } public static void setEnableBigAvatar(boolean value) { SettingHelper.setEditor(getContext(), SettingActivity.SHOW_BIG_AVATAR, value); } public static void setEnableFetchMSG(boolean value) { SettingHelper.setEditor(getContext(), SettingActivity.ENABLE_FETCH_MSG, value); } public static void setEnableWaterMark(boolean value) { SettingHelper.setEditor(getContext(), SettingActivity.WATER_MARK_ENABLE, value); } public static boolean allowVibrate() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.ENABLE_VIBRATE, false); } public static boolean allowLed() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.ENABLE_LED, false); } public static String getRingtone() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.ENABLE_RINGTONE, ""); } public static boolean allowFastScroll() { return false; // return SettingHelper // .getSharedPreferences(getContext(), SettingActivity.LIST_FAST_SCROLL, // true); } public static boolean allowMentionToMe() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.ENABLE_MENTION_TO_ME, true); } public static boolean allowCommentToMe() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.ENABLE_COMMENT_TO_ME, true); } public static boolean allowMentionCommentToMe() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.ENABLE_MENTION_COMMENT_TO_ME, true); } public static String getMsgCount() { // String value = SettingHelper.getSharedPreferences(getContext(), SettingActivity.MSG_COUNT, "3"); // // switch (Integer.valueOf(value)) { // case 1: // return String.valueOf(AppConfig.DEFAULT_MSG_COUNT_25); // // case 2: // return String.valueOf(AppConfig.DEFAULT_MSG_COUNT_50); // // case 3: // if (Utility.isConnected(getContext())) { // if (Utility.isWifi(getContext())) { // return String.valueOf(AppConfig.DEFAULT_MSG_COUNT_50); // } else { // return String.valueOf(AppConfig.DEFAULT_MSG_COUNT_25); // } // } // // } return String.valueOf(AppConfig.DEFAULT_MSG_COUNT_25); } public static boolean disableHardwareAccelerated() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.DISABLE_HARDWARE_ACCELERATED, false); } public static int getUploadQuality() { String result = SettingHelper.getSharedPreferences(getContext(), SettingActivity.UPLOAD_PIC_QUALITY, "2"); return Integer.valueOf(result); } public static void setDefaultSoftKeyBoardHeight(int height) { SettingHelper.setEditor(getContext(), "default_softkeyboard_height", height); } public static int getDefaultSoftKeyBoardHeight() { return SettingHelper.getSharedPreferences(getContext(), "default_softkeyboard_height", 400); } public static String getLastFoundWeiboAccountLink() { return SettingHelper.getSharedPreferences(getContext(), LAST_FOUND_WEIBO_ACCOUNT_LINK, ""); } public static void setLastFoundWeiboAccountLink(String url) { SettingHelper.setEditor(getContext(), LAST_FOUND_WEIBO_ACCOUNT_LINK, url); } public static boolean isReadStyleEqualWeibo() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.READ_STYLE, "1").equals("0"); } public static boolean isWifiUnlimitedMsgCount() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.WIFI_UNLIMITED_MSG_COUNT, true); } public static boolean isWifiAutoDownloadPic() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.WIFI_AUTO_DOWNLOAD_PIC, true); } public static boolean allowInternalWebBrowser() { return false;// SettingHelper.getSharedPreferences(getContext(), // SettingActivity.ENABLE_INTERNAL_WEB_BROWSER, true); } public static boolean allowClickToCloseGallery() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.ENABLE_CLICK_TO_CLOSE_GALLERY, true); } public static void setBlackMagicEnabled() { SettingHelper.setEditor(getContext(), BLACK_MAGIC, true); } public static boolean isClickToTopTipFirstShow() { boolean result = SettingHelper.getSharedPreferences(getContext(), CLICK_TO_TOP_TIP, true); SettingHelper.setEditor(getContext(), CLICK_TO_TOP_TIP, false); return result; } public static boolean isFilterSinaAd() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.FILTER_SINA_AD, false); } public static boolean isUploadBigPic() { return SettingHelper.getSharedPreferences(getContext(), SettingActivity.UPLOAD_BIG_PIC, true); } public static String[] getHotWeiboSelected() { return SettingHelper.getStringSetPreferences(getContext(), SettingActivity.HOT_WEIBO_LIST_KEY, R.array.hot_weibo_multi_select_value_def); } public static String[] getHotHuaTioSelected() { return SettingHelper.getStringSetPreferences(getContext(), SettingActivity.HOT_HUATI_LIST_KEY, R.array.hot_huati_multi_select_value_def); } }
gpl-3.0
marcelovilaca/DIRAC
StorageManagementSystem/Client/test/test_Client.py
2448
""" Test for StorageManagement clients """ import unittest import importlib from mock import MagicMock from DIRAC import S_OK from DIRAC.StorageManagementSystem.Client.StorageManagerClient import getFilesToStage class ClientsTestCase( unittest.TestCase ): """ Base class for the clients test cases """ def setUp( self ): from DIRAC import gLogger gLogger.setLevel( 'DEBUG' ) mockObjectDM = MagicMock() mockObjectDM.getActiveReplicas.return_value = S_OK( {'Successful': {'/a/lfn/1.txt':{'SE1':'/a/lfn/at/SE1.1.txt', 'SE2':'/a/lfn/at/SE2.1.txt'}, '/a/lfn/2.txt':{'SE1':'/a/lfn/at/SE1.1.txt'} }, 'Failed':{}} ) self.mockDM = MagicMock() self.mockDM.return_value = mockObjectDM mockObjectSE = MagicMock() mockObjectSE.getFileMetadata.return_value = S_OK( {'Successful':{'/a/lfn/1.txt':{'Cached':0}, '/a/lfn/2.txt':{'Cached':1}}, 'Failed':{}} ) self.mockSE = MagicMock() self.mockSE.return_value = mockObjectSE def tearDown( self ): pass ############################################################################# class StorageManagerSuccess( ClientsTestCase ): def test_getFilesToStage( self ): res = getFilesToStage( [] ) self.assert_( res['OK'] ) self.assertEqual( res['Value']['onlineLFNs'], [] ) self.assertEqual( res['Value']['offlineLFNs'], {} ) ourSMC = importlib.import_module( 'DIRAC.StorageManagementSystem.Client.StorageManagerClient' ) ourSMC.DataManager = self.mockDM ourSMC.StorageElement = self.mockSE res = getFilesToStage( ['/a/lfn/1.txt'] ) self.assert_( res['OK'] ) self.assertEqual( res['Value']['onlineLFNs'], ['/a/lfn/2.txt'] ) self.assert_( res['Value']['offlineLFNs'], {'SE1':['/a/lfn/1.txt']} or {'SE2':['/a/lfn/1.txt']} ) if __name__ == '__main__': suite = unittest.defaultTestLoader.loadTestsFromTestCase( ClientsTestCase ) suite.addTest( unittest.defaultTestLoader.loadTestsFromTestCase( StorageManagerSuccess ) ) testResult = unittest.TextTestRunner( verbosity = 2 ).run( suite )
gpl-3.0
DonLakeFlyer/ardupilot
libraries/AP_Proximity/AP_Proximity_Backend.cpp
14035
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <AP_Common/AP_Common.h> #include <AP_Common/Location.h> #include <AP_AHRS/AP_AHRS.h> #include <AP_HAL/AP_HAL.h> #include "AP_Proximity.h" #include "AP_Proximity_Backend.h" /* base class constructor. This incorporates initialisation as well. */ AP_Proximity_Backend::AP_Proximity_Backend(AP_Proximity &_frontend, AP_Proximity::Proximity_State &_state) : frontend(_frontend), state(_state) { // initialise sector edge vector used for building the boundary fence init_boundary(); } // get distance in meters in a particular direction in degrees (0 is forward, angles increase in the clockwise direction) bool AP_Proximity_Backend::get_horizontal_distance(float angle_deg, float &distance) const { uint8_t sector; if (convert_angle_to_sector(angle_deg, sector)) { if (_distance_valid[sector]) { distance = _distance[sector]; return true; } } return false; } // get distance and angle to closest object (used for pre-arm check) // returns true on success, false if no valid readings bool AP_Proximity_Backend::get_closest_object(float& angle_deg, float &distance) const { bool sector_found = false; uint8_t sector = 0; // check all sectors for shorter distance for (uint8_t i=0; i<_num_sectors; i++) { if (_distance_valid[i]) { if (!sector_found || (_distance[i] < _distance[sector])) { sector = i; sector_found = true; } } } if (sector_found) { angle_deg = _angle[sector]; distance = _distance[sector]; } return sector_found; } // get number of objects, used for non-GPS avoidance uint8_t AP_Proximity_Backend::get_object_count() const { return _num_sectors; } // get an object's angle and distance, used for non-GPS avoidance // returns false if no angle or distance could be returned for some reason bool AP_Proximity_Backend::get_object_angle_and_distance(uint8_t object_number, float& angle_deg, float &distance) const { if (object_number < _num_sectors && _distance_valid[object_number]) { angle_deg = _angle[object_number]; distance = _distance[object_number]; return true; } return false; } // get distances in PROXIMITY_MAX_DIRECTION directions. used for sending distances to ground station bool AP_Proximity_Backend::get_horizontal_distances(AP_Proximity::Proximity_Distance_Array &prx_dist_array) const { // exit immediately if we have no good ranges bool valid_distances = false; for (uint8_t i=0; i<_num_sectors; i++) { if (_distance_valid[i]) { valid_distances = true; break; } } if (!valid_distances) { return false; } // initialise orientations and directions // see MAV_SENSOR_ORIENTATION for orientations (0 = forward, 1 = 45 degree clockwise from north, etc) // distances initialised to maximum distances bool dist_set[PROXIMITY_MAX_DIRECTION]{}; for (uint8_t i=0; i<PROXIMITY_MAX_DIRECTION; i++) { prx_dist_array.orientation[i] = i; prx_dist_array.distance[i] = distance_max(); } // cycle through all sectors filling in distances for (uint8_t i=0; i<_num_sectors; i++) { if (_distance_valid[i]) { // convert angle to orientation int16_t orientation = static_cast<int16_t>(_angle[i] * (PROXIMITY_MAX_DIRECTION / 360.0f)); if ((orientation >= 0) && (orientation < PROXIMITY_MAX_DIRECTION) && (_distance[i] < prx_dist_array.distance[orientation])) { prx_dist_array.distance[orientation] = _distance[i]; dist_set[orientation] = true; } } } // fill in missing orientations with average of adjacent orientations if necessary and possible for (uint8_t i=0; i<PROXIMITY_MAX_DIRECTION; i++) { if (!dist_set[i]) { uint8_t orient_before = (i==0) ? (PROXIMITY_MAX_DIRECTION - 1) : (i-1); uint8_t orient_after = (i==(PROXIMITY_MAX_DIRECTION - 1)) ? 0 : (i+1); if (dist_set[orient_before] && dist_set[orient_after]) { prx_dist_array.distance[i] = (prx_dist_array.distance[orient_before] + prx_dist_array.distance[orient_after]) / 2.0f; } } } return true; } // get boundary points around vehicle for use by avoidance // returns nullptr and sets num_points to zero if no boundary can be returned const Vector2f* AP_Proximity_Backend::get_boundary_points(uint16_t& num_points) const { // high-level status check if (state.status != AP_Proximity::Proximity_Good) { num_points = 0; return nullptr; } // check at least one sector has valid data, if not, exit bool some_valid = false; for (uint8_t i=0; i<_num_sectors; i++) { if (_distance_valid[i]) { some_valid = true; break; } } if (!some_valid) { num_points = 0; return nullptr; } // return boundary points num_points = _num_sectors; return _boundary_point; } // initialise the boundary and sector_edge_vector array used for object avoidance // should be called if the sector_middle_deg or _setor_width_deg arrays are changed void AP_Proximity_Backend::init_boundary() { for (uint8_t sector=0; sector < _num_sectors; sector++) { float angle_rad = radians((float)_sector_middle_deg[sector]+(float)_sector_width_deg[sector]/2.0f); _sector_edge_vector[sector].x = cosf(angle_rad) * 100.0f; _sector_edge_vector[sector].y = sinf(angle_rad) * 100.0f; _boundary_point[sector] = _sector_edge_vector[sector] * PROXIMITY_BOUNDARY_DIST_DEFAULT; } update_locations(); } // update boundary points used for object avoidance based on a single sector's distance changing // the boundary points lie on the line between sectors meaning two boundary points may be updated based on a single sector's distance changing // the boundary point is set to the shortest distance found in the two adjacent sectors, this is a conservative boundary around the vehicle void AP_Proximity_Backend::update_boundary_for_sector(uint8_t sector) { // sanity check if (sector >= _num_sectors) { return; } // find adjacent sector (clockwise) uint8_t next_sector = sector + 1; if (next_sector >= _num_sectors) { next_sector = 0; } // boundary point lies on the line between the two sectors at the shorter distance found in the two sectors float shortest_distance = PROXIMITY_BOUNDARY_DIST_DEFAULT; if (_distance_valid[sector] && _distance_valid[next_sector]) { shortest_distance = MIN(_distance[sector], _distance[next_sector]); } else if (_distance_valid[sector]) { shortest_distance = _distance[sector]; } else if (_distance_valid[next_sector]) { shortest_distance = _distance[next_sector]; } if (shortest_distance < PROXIMITY_BOUNDARY_DIST_MIN) { shortest_distance = PROXIMITY_BOUNDARY_DIST_MIN; } _boundary_point[sector] = _sector_edge_vector[sector] * shortest_distance; // if the next sector (clockwise) has an invalid distance, set boundary to create a cup like boundary if (!_distance_valid[next_sector]) { _boundary_point[next_sector] = _sector_edge_vector[next_sector] * shortest_distance; } // repeat for edge between sector and previous sector uint8_t prev_sector = (sector == 0) ? _num_sectors-1 : sector-1; shortest_distance = PROXIMITY_BOUNDARY_DIST_DEFAULT; if (_distance_valid[prev_sector] && _distance_valid[sector]) { shortest_distance = MIN(_distance[prev_sector], _distance[sector]); } else if (_distance_valid[prev_sector]) { shortest_distance = _distance[prev_sector]; } else if (_distance_valid[sector]) { shortest_distance = _distance[sector]; } _boundary_point[prev_sector] = _sector_edge_vector[prev_sector] * shortest_distance; // if the sector counter-clockwise from the previous sector has an invalid distance, set boundary to create a cup like boundary uint8_t prev_sector_ccw = (prev_sector == 0) ? _num_sectors-1 : prev_sector-1; if (!_distance_valid[prev_sector_ccw]) { _boundary_point[prev_sector_ccw] = _sector_edge_vector[prev_sector_ccw] * shortest_distance; } update_locations(); } // copy location points around vehicle into a buffer owned by the caller // caller should provide the buff_size which is the maximum number of locations the buffer can hold (normally PROXIMITY_MAX_DIRECTION) // num_copied is updated with the number of locations copied into the buffer // returns true on success, false on failure which should only happen if buff is nullptr bool AP_Proximity_Backend::copy_locations(AP_Proximity::Proximity_Location* buff, uint16_t buff_size, uint16_t& num_copied) { // sanity check buffer if (buff == nullptr) { num_copied = 0; return false; } WITH_SEMAPHORE(_rsem); // copy locations into caller's buffer num_copied = MIN(_location_count, buff_size); memcpy(buff, _locations, num_copied * sizeof(AP_Proximity::Proximity_Location)); return true; } // set status and update valid count void AP_Proximity_Backend::set_status(AP_Proximity::Proximity_Status status) { state.status = status; } bool AP_Proximity_Backend::convert_angle_to_sector(float angle_degrees, uint8_t &sector) const { // sanity check angle if (angle_degrees > 360.0f || angle_degrees < -180.0f) { return false; } // convert to 0 ~ 360 if (angle_degrees < 0.0f) { angle_degrees += 360.0f; } bool closest_found = false; uint8_t closest_sector; float closest_angle; // search for which sector angle_degrees falls into for (uint8_t i = 0; i < _num_sectors; i++) { float angle_diff = fabsf(wrap_180(_sector_middle_deg[i] - angle_degrees)); // record if closest if (!closest_found || angle_diff < closest_angle) { closest_found = true; closest_sector = i; closest_angle = angle_diff; } if (fabsf(angle_diff) <= _sector_width_deg[i] / 2.0f) { sector = i; return true; } } // angle_degrees might have been within a gap between sectors if (closest_found) { sector = closest_sector; return true; } return false; } // get ignore area info uint8_t AP_Proximity_Backend::get_ignore_area_count() const { // count number of ignore sectors uint8_t count = 0; for (uint8_t i=0; i < PROXIMITY_MAX_IGNORE; i++) { if (frontend._ignore_width_deg[i] != 0) { count++; } } return count; } // get next ignore angle bool AP_Proximity_Backend::get_ignore_area(uint8_t index, uint16_t &angle_deg, uint8_t &width_deg) const { if (index >= PROXIMITY_MAX_IGNORE) { return false; } angle_deg = frontend._ignore_angle_deg[index]; width_deg = frontend._ignore_width_deg[index]; return true; } // retrieve start or end angle of next ignore area (i.e. closest ignore area higher than the start_angle) // start_or_end = 0 to get start, 1 to retrieve end bool AP_Proximity_Backend::get_next_ignore_start_or_end(uint8_t start_or_end, int16_t start_angle, int16_t &ignore_start) const { bool found = false; int16_t smallest_angle_diff = 0; int16_t smallest_angle_start = 0; for (uint8_t i=0; i < PROXIMITY_MAX_IGNORE; i++) { if (frontend._ignore_width_deg[i] != 0) { int16_t offset = start_or_end == 0 ? -frontend._ignore_width_deg[i] : +frontend._ignore_width_deg[i]; int16_t ignore_start_angle = wrap_360(frontend._ignore_angle_deg[i] + offset/2.0f); int16_t ang_diff = wrap_360(ignore_start_angle - start_angle); if (!found || ang_diff < smallest_angle_diff) { smallest_angle_diff = ang_diff; smallest_angle_start = ignore_start_angle; found = true; } } } if (found) { ignore_start = smallest_angle_start; } return found; } void AP_Proximity_Backend::update_locations() { WITH_SEMAPHORE(_rsem); // get number of objects, return early if none const uint8_t num_objects = get_object_count(); if (num_objects == 0) { _location_count = 0; return; } // get vehicle location and heading in degrees float veh_bearing; Location my_loc; { WITH_SEMAPHORE(AP::ahrs().get_semaphore()); if (!AP::ahrs().get_position(my_loc)) { return; } veh_bearing = AP::ahrs().yaw_sensor * 0.01f; } // convert offset from vehicle position to earth frame location const uint32_t now_ms = AP_HAL::millis(); _location_count = 0; for (uint8_t i=0; i<num_objects; i++) { float ang_deg, dist_m; if (get_object_angle_and_distance(i, ang_deg, dist_m)) { Location temp_loc = my_loc; temp_loc.offset_bearing(wrap_180(veh_bearing + ang_deg), dist_m); _locations[_location_count].loc = temp_loc; _locations[_location_count].radius_m = 1; _locations[_location_count].last_update_ms = now_ms; _location_count++; } } }
gpl-3.0
tectronics/magicgrove
source/Grove/Core/Effects/EachPlayerDiscardsHandAndDrawsGreatestDiscardedCount.cs
435
namespace Grove.Effects { using System; public class EachPlayerDiscardsHandAndDrawsGreatestDiscardedCount : Effect { protected override void ResolveEffect() { var maxCount = Math.Max(Players.Player1.Hand.Count, Players.Player2.Hand.Count); Players.Active.DiscardHand(); Players.Active.DrawCards(maxCount); Players.Passive.DiscardHand(); Players.Passive.DrawCards(maxCount); } } }
gpl-3.0
151706061/MacroMedicalSystem
ImageViewer/Tools/Standard/PresetVoiLuts/Operations/PresetVoiLutOperationsComponentContainer.cs
5720
#region License // Copyright (c) 2013, ClearCanvas Inc. // All rights reserved. // http://www.ClearCanvas.ca // // This file is part of the ClearCanvas RIS/PACS open source project. // // The ClearCanvas RIS/PACS open source project 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. // // The ClearCanvas RIS/PACS open source project 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 // the ClearCanvas RIS/PACS open source project. If not, see // <http://www.gnu.org/licenses/>. #endregion using System; using System.Collections.Generic; using Macro.Common; using Macro.Desktop; namespace Macro.ImageViewer.Tools.Standard.PresetVoiLuts.Operations { [ExtensionPoint] public sealed class PresetVoiLutOperationComponentContainerViewExtensionPoint : ExtensionPoint<IApplicationComponentView> { } [AssociateView(typeof(PresetVoiLutOperationComponentContainerViewExtensionPoint))] public sealed class PresetVoiLutOperationsComponentContainer : ApplicationComponentContainer { private sealed class PresetVoiLutOperationComponentHost : ApplicationComponentContainer.ContainedComponentHost { internal PresetVoiLutOperationComponentHost(PresetVoiLutOperationsComponentContainer owner, IPresetVoiLutOperationComponent hostedComponent) :base(owner, hostedComponent) { } public new IPresetVoiLutOperationComponent Component { get { return (IPresetVoiLutOperationComponent)base.Component; } } } private readonly PresetVoiLutOperationComponentHost _componentHost; private readonly List<KeyStrokeDescriptor> _availableKeyStrokes; private KeyStrokeDescriptor _selectedKeyStroke; public PresetVoiLutOperationsComponentContainer(IEnumerable<XKeys> availableKeyStrokes, IPresetVoiLutOperationComponent component) { Platform.CheckForNullReference(availableKeyStrokes, "availableKeyStrokes"); Platform.CheckForNullReference(component, "component"); _availableKeyStrokes = new List<KeyStrokeDescriptor>(); foreach (XKeys keyStroke in availableKeyStrokes) _availableKeyStrokes.Add(keyStroke); Platform.CheckPositive(_availableKeyStrokes.Count, "_availableKeyStrokes.Count"); _selectedKeyStroke = _availableKeyStrokes[0]; _componentHost = new PresetVoiLutOperationComponentHost(this, component); } private IPresetVoiLutOperationComponent ContainedComponent { get { return ((PresetVoiLutOperationComponentHost) ComponentHost).Component; } } public ApplicationComponentHost ComponentHost { get { return _componentHost; } } public IEnumerable<KeyStrokeDescriptor> AvailableKeyStrokes { get { return _availableKeyStrokes; } } public KeyStrokeDescriptor SelectedKeyStroke { get { return _selectedKeyStroke; } set { if (!_availableKeyStrokes.Contains(value)) throw new ArgumentException(SR.ExceptionSelectedKeystrokeMustBeOneOfAvailable); if (_selectedKeyStroke.Equals(value)) return; _selectedKeyStroke = value; Modified = true; NotifyPropertyChanged("SelectedKeyStroke"); } } public bool AcceptEnabled { get { if (!ContainedComponent.Valid) return false; switch (ContainedComponent.EditContext) { case EditContext.Edit: return this.Modified; default: return true; } } } public override bool Modified { get { return base.Modified || ComponentHost.Component.Modified; } protected set { base.Modified = value; NotifyPropertyChanged("AcceptEnabled"); } } internal PresetVoiLut GetPresetVoiLut() { PresetVoiLut preset = new PresetVoiLut(ContainedComponent.GetOperation()); preset.KeyStroke = _selectedKeyStroke.KeyStroke; return preset; } public void OK() { this.Exit(ApplicationComponentExitCode.Accepted); } public void Cancel() { this.Exit(ApplicationComponentExitCode.None); } public override void Start() { base.Modified = false; base.Start(); ContainedComponent.PropertyChanged += ComponentPropertyChanged; ComponentHost.StartComponent(); this.ExitCode = ApplicationComponentExitCode.None; } public override void Stop() { ComponentHost.StopComponent(); ContainedComponent.PropertyChanged -= ComponentPropertyChanged; base.Stop(); } #region ApplicationComponentContainer overrides public override IEnumerable<IApplicationComponent> ContainedComponents { get { yield return ComponentHost.Component; } } public override IEnumerable<IApplicationComponent> VisibleComponents { get { return this.ContainedComponents; } } public override void EnsureVisible(IApplicationComponent component) { if (!this.IsStarted) throw new InvalidOperationException("The container was never started."); // nothing to do, since the hosted components are started by default } public override void EnsureStarted(IApplicationComponent component) { if (!this.IsStarted) throw new InvalidOperationException("The container was never started."); // nothing to do, since the hosted components are visible by default } #endregion private void ComponentPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { this.NotifyPropertyChanged("AcceptEnabled"); } } }
gpl-3.0
eriklotin/lotin.cms
web/core/class/breadcrumbs.php
1229
<? # Erik. 03/03/2013 class Breadcrumbs { public $crumbs = array(); public $displayed = array(); public function push($name='', $url=''){ return array_unshift($this->crumbs, array('url'=>$url, 'header'=>$name)); } public function from_path_map(){ $node = node_by_path_arr(Gl::$path->path_map); while($node){ $this->crumbs[] = array("url"=>Gl::$path->base.Gl::$path->langpath.path_by_id($node['id']),"header"=>$node['header']); $node = node_by_id($node['pid']); } } public function display($template=null, $template_name="breadcrumbs", $force=false){ if(!empty($this->displayed[$template_name]) && $force==false){ return false; } if(empty($template)){ if(Gl::$page){ $template = Gl::$page; } else { return false; } } if(!empty($this->crumbs)){ $breadcrumbs = $template->create($template_name); $breadcrumbs->set($this->crumbs[0]); for($i=count($this->crumbs)-1; $i>0; $i--){ $parentCrumb = $breadcrumbs->create('parentCrumb'); $parentCrumb->set($this->crumbs[$i]); } $this->displayed[$template_name] = true; } else { return false; } } } ?>
gpl-3.0
saurabh947/MoodleLearning
question/type/edit_question_form.php
28366
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * A base class for question editing forms. * * @package moodlecore * @subpackage questiontypes * @copyright 2006 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU Public License */ defined('MOODLE_INTERNAL') || die(); global $CFG; require_once($CFG->libdir.'/formslib.php'); abstract class question_wizard_form extends moodleform { /** * Add all the hidden form fields used by question/question.php. */ protected function add_hidden_fields() { $mform = $this->_form; $mform->addElement('hidden', 'id'); $mform->setType('id', PARAM_INT); $mform->addElement('hidden', 'inpopup'); $mform->setType('inpopup', PARAM_INT); $mform->addElement('hidden', 'cmid'); $mform->setType('cmid', PARAM_INT); $mform->addElement('hidden', 'courseid'); $mform->setType('courseid', PARAM_INT); $mform->addElement('hidden', 'returnurl'); $mform->setType('returnurl', PARAM_LOCALURL); $mform->addElement('hidden', 'scrollpos'); $mform->setType('scrollpos', PARAM_INT); $mform->addElement('hidden', 'appendqnumstring'); $mform->setType('appendqnumstring', PARAM_ALPHA); } } /** * Form definition base class. This defines the common fields that * all question types need. Question types should define their own * class that inherits from this one, and implements the definition_inner() * method. * * @copyright 2006 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU Public License */ abstract class question_edit_form extends question_wizard_form { const DEFAULT_NUM_HINTS = 2; /** * Question object with options and answers already loaded by get_question_options * Be careful how you use this it is needed sometimes to set up the structure of the * form in definition_inner but data is always loaded into the form with set_data. * @var object */ protected $question; protected $contexts; protected $category; protected $categorycontext; /** @var object current context */ public $context; /** @var array html editor options */ public $editoroptions; /** @var array options to preapre draft area */ public $fileoptions; /** @var object instance of question type */ public $instance; public function __construct($submiturl, $question, $category, $contexts, $formeditable = true) { global $DB; $this->question = $question; $this->contexts = $contexts; $record = $DB->get_record('question_categories', array('id' => $question->category), 'contextid'); $this->context = get_context_instance_by_id($record->contextid); $this->editoroptions = array('subdirs' => 1, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'context' => $this->context); $this->fileoptions = array('subdirs' => 1, 'maxfiles' => -1, 'maxbytes' => -1); $this->category = $category; $this->categorycontext = get_context_instance_by_id($category->contextid); parent::__construct($submiturl, null, 'post', '', null, $formeditable); } /** * Build the form definition. * * This adds all the form fields that the default question type supports. * If your question type does not support all these fields, then you can * override this method and remove the ones you don't want with $mform->removeElement(). */ protected function definition() { global $COURSE, $CFG, $DB; $qtype = $this->qtype(); $langfile = "qtype_$qtype"; $mform = $this->_form; // Standard fields at the start of the form. $mform->addElement('header', 'generalheader', get_string("general", 'form')); if (!isset($this->question->id)) { if (!empty($this->question->formoptions->mustbeusable)) { $contexts = $this->contexts->having_add_and_use(); } else { $contexts = $this->contexts->having_cap('moodle/question:add'); } // Adding question $mform->addElement('questioncategory', 'category', get_string('category', 'question'), array('contexts' => $contexts)); } else if (!($this->question->formoptions->canmove || $this->question->formoptions->cansaveasnew)) { // Editing question with no permission to move from category. $mform->addElement('questioncategory', 'category', get_string('category', 'question'), array('contexts' => array($this->categorycontext))); } else if ($this->question->formoptions->movecontext) { // Moving question to another context. $mform->addElement('questioncategory', 'categorymoveto', get_string('category', 'question'), array('contexts' => $this->contexts->having_cap('moodle/question:add'))); } else { // Editing question with permission to move from category or save as new q $currentgrp = array(); $currentgrp[0] = $mform->createElement('questioncategory', 'category', get_string('categorycurrent', 'question'), array('contexts' => array($this->categorycontext))); if ($this->question->formoptions->canedit || $this->question->formoptions->cansaveasnew) { //not move only form $currentgrp[1] = $mform->createElement('checkbox', 'usecurrentcat', '', get_string('categorycurrentuse', 'question')); $mform->setDefault('usecurrentcat', 1); } $currentgrp[0]->freeze(); $currentgrp[0]->setPersistantFreeze(false); $mform->addGroup($currentgrp, 'currentgrp', get_string('categorycurrent', 'question'), null, false); $mform->addElement('questioncategory', 'categorymoveto', get_string('categorymoveto', 'question'), array('contexts' => array($this->categorycontext))); if ($this->question->formoptions->canedit || $this->question->formoptions->cansaveasnew) { //not move only form $mform->disabledIf('categorymoveto', 'usecurrentcat', 'checked'); } } $mform->addElement('text', 'name', get_string('questionname', 'question'), array('size' => 50)); $mform->setType('name', PARAM_TEXT); $mform->addRule('name', null, 'required', null, 'client'); $mform->addElement('editor', 'questiontext', get_string('questiontext', 'question'), array('rows' => 15), $this->editoroptions); $mform->setType('questiontext', PARAM_RAW); $mform->addElement('text', 'defaultmark', get_string('defaultmark', 'question'), array('size' => 7)); $mform->setType('defaultmark', PARAM_FLOAT); $mform->setDefault('defaultmark', 1); $mform->addRule('defaultmark', null, 'required', null, 'client'); $mform->addElement('editor', 'generalfeedback', get_string('generalfeedback', 'question'), array('rows' => 10), $this->editoroptions); $mform->setType('generalfeedback', PARAM_RAW); $mform->addHelpButton('generalfeedback', 'generalfeedback', 'question'); // Any questiontype specific fields. $this->definition_inner($mform); if (!empty($CFG->usetags)) { $mform->addElement('header', 'tagsheader', get_string('tags')); $mform->addElement('tags', 'tags', get_string('tags')); } if (!empty($this->question->id)) { $mform->addElement('header', 'createdmodifiedheader', get_string('createdmodifiedheader', 'question')); $a = new stdClass(); if (!empty($this->question->createdby)) { $a->time = userdate($this->question->timecreated); $a->user = fullname($DB->get_record( 'user', array('id' => $this->question->createdby))); } else { $a->time = get_string('unknown', 'question'); $a->user = get_string('unknown', 'question'); } $mform->addElement('static', 'created', get_string('created', 'question'), get_string('byandon', 'question', $a)); if (!empty($this->question->modifiedby)) { $a = new stdClass(); $a->time = userdate($this->question->timemodified); $a->user = fullname($DB->get_record( 'user', array('id' => $this->question->modifiedby))); $mform->addElement('static', 'modified', get_string('modified', 'question'), get_string('byandon', 'question', $a)); } } $this->add_hidden_fields(); $mform->addElement('hidden', 'movecontext'); $mform->setType('movecontext', PARAM_BOOL); $mform->addElement('hidden', 'qtype'); $mform->setType('qtype', PARAM_ALPHA); $buttonarray = array(); if (!empty($this->question->id)) { // Editing / moving question if ($this->question->formoptions->movecontext) { $buttonarray[] = $mform->createElement('submit', 'submitbutton', get_string('moveq', 'question')); } else if ($this->question->formoptions->canedit) { $buttonarray[] = $mform->createElement('submit', 'submitbutton', get_string('savechanges')); } if ($this->question->formoptions->cansaveasnew) { $buttonarray[] = $mform->createElement('submit', 'makecopy', get_string('makecopy', 'question')); } $buttonarray[] = $mform->createElement('cancel'); } else { // Adding new question $buttonarray[] = $mform->createElement('submit', 'submitbutton', get_string('savechanges')); $buttonarray[] = $mform->createElement('cancel'); } $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false); $mform->closeHeaderBefore('buttonar'); if ($this->question->formoptions->movecontext) { $mform->hardFreezeAllVisibleExcept(array('categorymoveto', 'buttonar')); } else if ((!empty($this->question->id)) && (!($this->question->formoptions->canedit || $this->question->formoptions->cansaveasnew))) { $mform->hardFreezeAllVisibleExcept(array('categorymoveto', 'buttonar', 'currentgrp')); } } /** * Add any question-type specific form fields. * * @param object $mform the form being built. */ protected function definition_inner($mform) { // By default, do nothing. } /** * Get the list of form elements to repeat, one for each answer. * @param object $mform the form being built. * @param $label the label to use for each option. * @param $gradeoptions the possible grades for each answer. * @param $repeatedoptions reference to array of repeated options to fill * @param $answersoption reference to return the name of $question->options * field holding an array of answers * @return array of form fields. */ protected function get_per_answer_fields($mform, $label, $gradeoptions, &$repeatedoptions, &$answersoption) { $repeated = array(); $repeated[] = $mform->createElement('header', 'answerhdr', $label); $repeated[] = $mform->createElement('text', 'answer', get_string('answer', 'question'), array('size' => 80)); $repeated[] = $mform->createElement('select', 'fraction', get_string('grade'), $gradeoptions); $repeated[] = $mform->createElement('editor', 'feedback', get_string('feedback', 'question'), array('rows' => 5), $this->editoroptions); $repeatedoptions['answer']['type'] = PARAM_RAW; $repeatedoptions['fraction']['default'] = 0; $answersoption = 'answers'; return $repeated; } /** * Add a set of form fields, obtained from get_per_answer_fields, to the form, * one for each existing answer, with some blanks for some new ones. * @param object $mform the form being built. * @param $label the label to use for each option. * @param $gradeoptions the possible grades for each answer. * @param $minoptions the minimum number of answer blanks to display. * Default QUESTION_NUMANS_START. * @param $addoptions the number of answer blanks to add. Default QUESTION_NUMANS_ADD. */ protected function add_per_answer_fields(&$mform, $label, $gradeoptions, $minoptions = QUESTION_NUMANS_START, $addoptions = QUESTION_NUMANS_ADD) { $answersoption = ''; $repeatedoptions = array(); $repeated = $this->get_per_answer_fields($mform, $label, $gradeoptions, $repeatedoptions, $answersoption); if (isset($this->question->options)) { $countanswers = count($this->question->options->$answersoption); } else { $countanswers = 0; } if ($this->question->formoptions->repeatelements) { $repeatsatstart = max($minoptions, $countanswers + $addoptions); } else { $repeatsatstart = $countanswers; } $this->repeat_elements($repeated, $repeatsatstart, $repeatedoptions, 'noanswers', 'addanswers', $addoptions, get_string('addmorechoiceblanks', 'qtype_multichoice')); } protected function add_combined_feedback_fields($withshownumpartscorrect = false) { $mform = $this->_form; $mform->addElement('header', 'combinedfeedbackhdr', get_string('combinedfeedback', 'question')); $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback'); foreach ($fields as $feedbackname) { $mform->addElement('editor', $feedbackname, get_string($feedbackname, 'question'), array('rows' => 5), $this->editoroptions); $mform->setType($feedbackname, PARAM_RAW); if ($withshownumpartscorrect && $feedbackname == 'partiallycorrectfeedback') { $mform->addElement('advcheckbox', 'shownumcorrect', get_string('options', 'question'), get_string('shownumpartscorrectwhenfinished', 'question')); } } } protected function get_hint_fields($withclearwrong = false, $withshownumpartscorrect = false) { $mform = $this->_form; $repeated = array(); $repeated[] = $mform->createElement('header', 'hinthdr', get_string('hintn', 'question')); $repeated[] = $mform->createElement('editor', 'hint', get_string('hinttext', 'question'), array('rows' => 5), $this->editoroptions); $repeatedoptions['hint']['type'] = PARAM_RAW; if ($withclearwrong) { $repeated[] = $mform->createElement('advcheckbox', 'hintclearwrong', get_string('options', 'question'), get_string('clearwrongparts', 'question')); } if ($withshownumpartscorrect) { $repeated[] = $mform->createElement('advcheckbox', 'hintshownumcorrect', '', get_string('shownumpartscorrect', 'question')); } return array($repeated, $repeatedoptions); } protected function add_interactive_settings($withclearwrong = false, $withshownumpartscorrect = false) { $mform = $this->_form; $mform->addElement('header', 'multitriesheader', get_string('settingsformultipletries', 'question')); $penalties = array( 1.0000000, 0.5000000, 0.3333333, 0.2500000, 0.2000000, 0.1000000, 0.0000000 ); if (!empty($this->question->penalty) && !in_array($this->question->penalty, $penalties)) { $penalties[] = $this->question->penalty; sort($penalties); } $penaltyoptions = array(); foreach ($penalties as $penalty) { $penaltyoptions["$penalty"] = (100 * $penalty) . '%'; } $mform->addElement('select', 'penalty', get_string('penaltyforeachincorrecttry', 'question'), $penaltyoptions); $mform->addRule('penalty', null, 'required', null, 'client'); $mform->addHelpButton('penalty', 'penaltyforeachincorrecttry', 'question'); $mform->setDefault('penalty', 0.3333333); if (isset($this->question->hints)) { $counthints = count($this->question->hints); } else { $counthints = 0; } if ($this->question->formoptions->repeatelements) { $repeatsatstart = max(self::DEFAULT_NUM_HINTS, $counthints); } else { $repeatsatstart = $counthints; } list($repeated, $repeatedoptions) = $this->get_hint_fields( $withclearwrong, $withshownumpartscorrect); $this->repeat_elements($repeated, $repeatsatstart, $repeatedoptions, 'numhints', 'addhint', 1, get_string('addanotherhint', 'question')); } public function set_data($question) { question_bank::get_qtype($question->qtype)->set_default_options($question); // prepare question text $draftid = file_get_submitted_draft_itemid('questiontext'); if (!empty($question->questiontext)) { $questiontext = $question->questiontext; } else { $questiontext = $this->_form->getElement('questiontext')->getValue(); $questiontext = $questiontext['text']; } $questiontext = file_prepare_draft_area($draftid, $this->context->id, 'question', 'questiontext', empty($question->id) ? null : (int) $question->id, $this->fileoptions, $questiontext); $question->questiontext = array(); $question->questiontext['text'] = $questiontext; $question->questiontext['format'] = empty($question->questiontextformat) ? editors_get_preferred_format() : $question->questiontextformat; $question->questiontext['itemid'] = $draftid; // prepare general feedback $draftid = file_get_submitted_draft_itemid('generalfeedback'); if (empty($question->generalfeedback)) { $generalfeedback = $this->_form->getElement('generalfeedback')->getValue(); $question->generalfeedback = $generalfeedback['text']; } $feedback = file_prepare_draft_area($draftid, $this->context->id, 'question', 'generalfeedback', empty($question->id) ? null : (int) $question->id, $this->fileoptions, $question->generalfeedback); $question->generalfeedback = array(); $question->generalfeedback['text'] = $feedback; $question->generalfeedback['format'] = empty($question->generalfeedbackformat) ? editors_get_preferred_format() : $question->generalfeedbackformat; $question->generalfeedback['itemid'] = $draftid; // Remove unnecessary trailing 0s form grade fields. if (isset($question->defaultgrade)) { $question->defaultgrade = 0 + $question->defaultgrade; } if (isset($question->penalty)) { $question->penalty = 0 + $question->penalty; } // Set any options. $extraquestionfields = question_bank::get_qtype($question->qtype)->extra_question_fields(); if (is_array($extraquestionfields) && !empty($question->options)) { array_shift($extraquestionfields); foreach ($extraquestionfields as $field) { if (property_exists($question->options, $field)) { $question->$field = $question->options->$field; } } } // subclass adds data_preprocessing code here $question = $this->data_preprocessing($question); parent::set_data($question); } /** * Perform an preprocessing needed on the data passed to {@link set_data()} * before it is used to initialise the form. * @param object $question the data being passed to the form. * @return object $question the modified data. */ protected function data_preprocessing($question) { return $question; } /** * Perform the necessary preprocessing for the fields added by * {@link add_per_answer_fields()}. * @param object $question the data being passed to the form. * @return object $question the modified data. */ protected function data_preprocessing_answers($question, $withanswerfiles = false) { if (empty($question->options->answers)) { return $question; } $key = 0; foreach ($question->options->answers as $answer) { if ($withanswerfiles) { // Prepare the feedback editor to display files in draft area $draftitemid = file_get_submitted_draft_itemid('answer['.$key.']'); $question->answer[$key]['text'] = file_prepare_draft_area( $draftitemid, // draftid $this->context->id, // context 'question', // component 'answer', // filarea !empty($answer->id) ? (int) $answer->id : null, // itemid $this->fileoptions, // options $answer->answer // text ); $question->answer[$key]['itemid'] = $draftitemid; $question->answer[$key]['format'] = $answer->answerformat; } else { $question->answer[$key] = $answer->answer; } $question->fraction[$key] = 0 + $answer->fraction; $question->feedback[$key] = array(); // Evil hack alert. Formslib can store defaults in two ways for // repeat elements: // ->_defaultValues['fraction[0]'] and // ->_defaultValues['fraction'][0]. // The $repeatedoptions['fraction']['default'] = 0 bit above means // that ->_defaultValues['fraction[0]'] has already been set, but we // are using object notation here, so we will be setting // ->_defaultValues['fraction'][0]. That does not work, so we have // to unset ->_defaultValues['fraction[0]'] unset($this->_form->_defaultValues["fraction[$key]"]); // Prepare the feedback editor to display files in draft area $draftitemid = file_get_submitted_draft_itemid('feedback['.$key.']'); $question->feedback[$key]['text'] = file_prepare_draft_area( $draftitemid, // draftid $this->context->id, // context 'question', // component 'answerfeedback', // filarea !empty($answer->id) ? (int) $answer->id : null, // itemid $this->fileoptions, // options $answer->feedback // text ); $question->feedback[$key]['itemid'] = $draftitemid; $question->feedback[$key]['format'] = $answer->feedbackformat; $key++; } return $question; } /** * Perform the necessary preprocessing for the fields added by * {@link add_combined_feedback_fields()}. * @param object $question the data being passed to the form. * @return object $question the modified data. */ protected function data_preprocessing_combined_feedback($question, $withshownumcorrect = false) { if (empty($question->options)) { return $question; } $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback'); foreach ($fields as $feedbackname) { $draftid = file_get_submitted_draft_itemid($feedbackname); $feedback = array(); $feedback['text'] = file_prepare_draft_area( $draftid, // draftid $this->context->id, // context 'question', // component $feedbackname, // filarea !empty($question->id) ? (int) $question->id : null, // itemid $this->fileoptions, // options $question->options->$feedbackname // text ); $feedbackformat = $feedbackname . 'format'; $feedback['format'] = $question->options->$feedbackformat; $feedback['itemid'] = $draftid; $question->$feedbackname = $feedback; } if ($withshownumcorrect) { $question->shownumcorrect = $question->options->shownumcorrect; } return $question; } /** * Perform the necessary preprocessing for the hint fields. * @param object $question the data being passed to the form. * @return object $question the modified data. */ protected function data_preprocessing_hints($question, $withclearwrong = false, $withshownumpartscorrect = false) { if (empty($question->hints)) { return $question; } $key = 0; foreach ($question->hints as $hint) { $question->hint[$key] = array(); // prepare feedback editor to display files in draft area $draftitemid = file_get_submitted_draft_itemid('hint['.$key.']'); $question->hint[$key]['text'] = file_prepare_draft_area( $draftitemid, // draftid $this->context->id, // context 'question', // component 'hint', // filarea !empty($hint->id) ? (int) $hint->id : null, // itemid $this->fileoptions, // options $hint->hint // text ); $question->hint[$key]['itemid'] = $draftitemid; $question->hint[$key]['format'] = $hint->hintformat; $key++; if ($withclearwrong) { $question->hintclearwrong[] = $hint->clearwrong; } if ($withshownumpartscorrect) { $question->hintshownumcorrect[] = $hint->shownumcorrect; } } return $question; } public function validation($fromform, $files) { $errors = parent::validation($fromform, $files); if (empty($fromform['makecopy']) && isset($this->question->id) && ($this->question->formoptions->canedit || $this->question->formoptions->cansaveasnew) && empty($fromform['usecurrentcat']) && !$this->question->formoptions->canmove) { $errors['currentgrp'] = get_string('nopermissionmove', 'question'); } return $errors; } /** * Override this in the subclass to question type name. * @return the question type name, should be the same as the name() method * in the question type class. */ public abstract function qtype(); }
gpl-3.0
cirnoworks/fiscevm
fiscevm-runtime/src/main/java/java/lang/Runnable.java
879
/* 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 java.lang; public interface Runnable { public abstract void run(); }
gpl-3.0
manojdjoshi/dnSpy
Extensions/dnSpy.AsmEditor/Commands/DeletedPropertyUpdater.cs
1962
/* Copyright (C) 2014-2019 de4dot@gmail.com This file is part of dnSpy dnSpy 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. dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using dnlib.DotNet; using dnSpy.Contracts.Documents.TreeView; using dnSpy.Contracts.TreeView; namespace dnSpy.AsmEditor.Commands { sealed class DeletedPropertyUpdater { public IEnumerable<DocumentTreeNodeData> OriginalNodes { get { yield return ownerNode; } } readonly TreeNodeData parentNode; readonly PropertyNode ownerNode; readonly TypeDef ownerType; readonly PropertyDef property; int propertyIndex; public DeletedPropertyUpdater(ModuleDocumentNode modNode, PropertyDef originalProperty) { var node = modNode.Context.DocumentTreeView.FindNode(originalProperty); if (node is null) throw new InvalidOperationException(); ownerNode = node; parentNode = ownerNode.TreeNode.Parent!.Data; ownerType = originalProperty.DeclaringType; property = originalProperty; } public void Add() { if (!parentNode.TreeNode.Children.Remove(ownerNode.TreeNode)) throw new InvalidOperationException(); propertyIndex = ownerType.Properties.IndexOf(property); ownerType.Properties.RemoveAt(propertyIndex); } public void Remove() { ownerType.Properties.Insert(propertyIndex, property); parentNode.TreeNode.AddChild(ownerNode.TreeNode); } } }
gpl-3.0
IDS-UK/genderhub
wp-content/plugins/redirection/matches/login.php
912
<?php class Login_Match extends Red_Match { function name() { return __( 'URL and login status', 'redirection' ); } public function save( array $details, $no_target_url = false ) { if ( $no_target_url ) { return null; } return array( 'logged_in' => isset( $details['action_data_logged_in'] ) ? $this->sanitize_url( $details['action_data_logged_in'] ) : '', 'logged_out' => isset( $details['action_data_logged_out'] ) ? $this->sanitize_url( $details['action_data_logged_out'] ) : '', ); } function get_target( $url, $matched_url, $regex ) { $target = false; if ( is_user_logged_in() && $this->logged_in !== '' ) { $target = $this->logged_in; } else if ( ! is_user_logged_in() && $this->logged_out !== '' ) { $target = $this->logged_out; } if ( $regex && $target ) { $target = $this->get_target_regex_url( $matched_url, $target, $url ); } return $target; } }
gpl-3.0
OpenCFD/OpenFOAM-1.7.x
src/lagrangian/intermediate/submodels/Kinematic/InjectionModel/InjectionModel/InjectionModelI.H
2464
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "InjectionModel.H" template<class CloudType> const Foam::dictionary& Foam::InjectionModel<CloudType>::dict() const { return dict_; } template<class CloudType> const CloudType& Foam::InjectionModel<CloudType>::owner() const { return owner_; } template<class CloudType> CloudType& Foam::InjectionModel<CloudType>::owner() { return owner_; } template<class CloudType> const Foam::dictionary& Foam::InjectionModel<CloudType>::coeffDict() const { return coeffDict_; } template<class CloudType> Foam::scalar Foam::InjectionModel<CloudType>::timeStart() const { return SOI_; } template<class CloudType> Foam::scalar Foam::InjectionModel<CloudType>::volumeTotal() const { return volumeTotal_; } template<class CloudType> Foam::scalar Foam::InjectionModel<CloudType>::massTotal() const { return massTotal_; } template<class CloudType> Foam::scalar Foam::InjectionModel<CloudType>::massInjected() const { return massInjected_; } template<class CloudType> Foam::label Foam::InjectionModel<CloudType>::nInjections() const { return nInjections_; } template<class CloudType> Foam::label Foam::InjectionModel<CloudType>::parcelsAddedTotal() const { return parcelsAddedTotal_; } // ************************************************************************* //
gpl-3.0
will-bainbridge/OpenFOAM-dev
src/mesh/blockMesh/blockVertices/blockVertex/blockVertex.C
3821
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2016-2018 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "blockVertex.H" #include "pointVertex.H" #include "blockMeshTools.H" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace Foam { defineTypeNameAndDebug(blockVertex, 0); defineRunTimeSelectionTable(blockVertex, Istream); } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // Foam::blockVertex::blockVertex() {} Foam::autoPtr<Foam::blockVertex> Foam::blockVertex::clone() const { NotImplemented; return autoPtr<blockVertex>(nullptr); } Foam::autoPtr<Foam::blockVertex> Foam::blockVertex::New ( const dictionary& dict, const label index, const searchableSurfaces& geometry, Istream& is ) { if (debug) { InfoInFunction << "Constructing blockVertex" << endl; } token firstToken(is); if (firstToken.isPunctuation() && firstToken.pToken() == token::BEGIN_LIST) { // Putback the opening bracket is.putBack(firstToken); return autoPtr<blockVertex> ( new blockVertices::pointVertex(dict, index, geometry, is) ); } else if (firstToken.isWord()) { const word faceType(firstToken.wordToken()); IstreamConstructorTable::iterator cstrIter = IstreamConstructorTablePtr_->find(faceType); if (cstrIter == IstreamConstructorTablePtr_->end()) { FatalErrorInFunction << "Unknown blockVertex type " << faceType << nl << nl << "Valid blockVertex types are" << endl << IstreamConstructorTablePtr_->sortedToc() << abort(FatalError); } return autoPtr<blockVertex>(cstrIter()(dict, index, geometry, is)); } else { FatalIOErrorInFunction(is) << "incorrect first token, expected <word> or '(', found " << firstToken.info() << exit(FatalIOError); return autoPtr<blockVertex>(nullptr); } } Foam::label Foam::blockVertex::read(Istream& is, const dictionary& dict) { const dictionary* varDictPtr = dict.subDictPtr("namedVertices"); if (varDictPtr) { return blockMeshTools::read(is, *varDictPtr); } return readLabel(is); } void Foam::blockVertex::write ( Ostream& os, const label val, const dictionary& d ) { const dictionary* varDictPtr = d.subDictPtr("namedVertices"); if (varDictPtr) { blockMeshTools::write(os, val, *varDictPtr); } else { os << val; } } // ************************************************************************* //
gpl-3.0
Bitl/RBXLegacy-src
Cut/UPnP/src/main/java/org/chris/portmapper/router/dummy/DummyRouterFactory.java
1786
/** * UPnP PortMapper - A tool for managing port forwardings via UPnP * Copyright (C) 2015 Christoph Pirkl <christoph at users.sourceforge.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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.chris.portmapper.router.dummy; import java.util.LinkedList; import java.util.List; import org.chris.portmapper.PortMapperApp; import org.chris.portmapper.router.AbstractRouterFactory; import org.chris.portmapper.router.IRouter; import org.chris.portmapper.router.RouterException; /** * Router factory for testing without a real router. */ public class DummyRouterFactory extends AbstractRouterFactory { public DummyRouterFactory(final PortMapperApp app) { super(app, "Dummy library"); } @Override protected List<IRouter> findRoutersInternal() throws RouterException { final List<IRouter> routers = new LinkedList<>(); routers.add(new DummyRouter("DummyRouter1")); routers.add(new DummyRouter("DummyRouter2")); return routers; } @Override protected IRouter connect(final String locationUrl) throws RouterException { return new DummyRouter("DummyRouter @ " + locationUrl); } }
gpl-3.0
llbit/chunky
chunky/src/java/se/llbit/chunky/block/Furnace.java
608
package se.llbit.chunky.block; import se.llbit.chunky.resources.Texture; public class Furnace extends TopBottomOrientedTexturedBlock { private final boolean lit; private final String description; public Furnace(String facing, boolean lit) { super("furnace", facing, lit ? Texture.furnaceLitFront : Texture.furnaceUnlitFront, Texture.furnaceSide, Texture.furnaceTop); this.description = String.format("facing=%s, lit=%s", facing, lit); this.lit = lit; } public boolean isLit() { return lit; } @Override public String description() { return description; } }
gpl-3.0
ABrandau/OpenRA
OpenRA.Mods.Common/Traits/Armament.cs
13291
#region Copyright & License Information /* * Copyright 2007-2019 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you 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. For more * information, see COPYING. */ #endregion using System; using System.Collections.Generic; using System.Linq; using OpenRA.GameRules; using OpenRA.Primitives; using OpenRA.Traits; namespace OpenRA.Mods.Common.Traits { public class Barrel { public WVec Offset; public WAngle Yaw; } [Desc("Allows you to attach weapons to the unit (use @IdentifierSuffix for > 1)")] public class ArmamentInfo : PausableConditionalTraitInfo, Requires<AttackBaseInfo> { public readonly string Name = "primary"; [WeaponReference, FieldLoader.Require] [Desc("Has to be defined in weapons.yaml as well.")] public readonly string Weapon = null; [Desc("Which turret (if present) should this armament be assigned to.")] public readonly string Turret = "primary"; [Desc("Time (in frames) until the weapon can fire again.")] public readonly int FireDelay = 0; [Desc("Muzzle position relative to turret or body, (forward, right, up) triples.", "If weapon Burst = 1, it cycles through all listed offsets, otherwise the offset corresponding to current burst is used.")] public readonly WVec[] LocalOffset = { }; [Desc("Muzzle yaw relative to turret or body.")] public readonly WAngle[] LocalYaw = { }; [Desc("Move the turret backwards when firing.")] public readonly WDist Recoil = WDist.Zero; [Desc("Recoil recovery per-frame")] public readonly WDist RecoilRecovery = new WDist(9); [Desc("Muzzle flash sequence to render")] public readonly string MuzzleSequence = null; [Desc("Palette to render Muzzle flash sequence in")] [PaletteReference] public readonly string MuzzlePalette = "effect"; [Desc("Use multiple muzzle images if non-zero")] public readonly int MuzzleSplitFacings = 0; [GrantedConditionReference] [Desc("Condition to grant while reloading.")] public readonly string ReloadingCondition = null; public WeaponInfo WeaponInfo { get; private set; } public WDist ModifiedRange { get; private set; } public readonly Stance TargetStances = Stance.Enemy; public readonly Stance ForceTargetStances = Stance.Enemy | Stance.Neutral | Stance.Ally; // TODO: instead of having multiple Armaments and unique AttackBase, // an actor should be able to have multiple AttackBases with // a single corresponding Armament each public readonly string Cursor = "attack"; // TODO: same as above public readonly string OutsideRangeCursor = "attackoutsiderange"; public override object Create(ActorInitializer init) { return new Armament(init.Self, this); } public override void RulesetLoaded(Ruleset rules, ActorInfo ai) { WeaponInfo weaponInfo; var weaponToLower = Weapon.ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out weaponInfo)) throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); WeaponInfo = weaponInfo; ModifiedRange = new WDist(Util.ApplyPercentageModifiers( WeaponInfo.Range.Length, ai.TraitInfos<IRangeModifierInfo>().Select(m => m.GetRangeModifierDefault()))); if (WeaponInfo.Burst > 1 && WeaponInfo.BurstDelays.Length > 1 && (WeaponInfo.BurstDelays.Length != WeaponInfo.Burst - 1)) throw new YamlException("Weapon '{0}' has an invalid number of BurstDelays, must be single entry or Burst - 1.".F(weaponToLower)); base.RulesetLoaded(rules, ai); } } public class Armament : PausableConditionalTrait<ArmamentInfo>, ITick { public readonly WeaponInfo Weapon; public readonly Barrel[] Barrels; readonly Actor self; Turreted turret; BodyOrientation coords; INotifyBurstComplete[] notifyBurstComplete; INotifyAttack[] notifyAttacks; ConditionManager conditionManager; int conditionToken = ConditionManager.InvalidConditionToken; IEnumerable<int> rangeModifiers; IEnumerable<int> reloadModifiers; IEnumerable<int> damageModifiers; IEnumerable<int> inaccuracyModifiers; int ticksSinceLastShot; int currentBarrel; int barrelCount; List<Pair<int, Action>> delayedActions = new List<Pair<int, Action>>(); public WDist Recoil; public int FireDelay { get; protected set; } public int Burst { get; protected set; } public Armament(Actor self, ArmamentInfo info) : base(info) { this.self = self; Weapon = info.WeaponInfo; Burst = Weapon.Burst; var barrels = new List<Barrel>(); for (var i = 0; i < info.LocalOffset.Length; i++) { barrels.Add(new Barrel { Offset = info.LocalOffset[i], Yaw = info.LocalYaw.Length > i ? info.LocalYaw[i] : WAngle.Zero }); } if (barrels.Count == 0) barrels.Add(new Barrel { Offset = WVec.Zero, Yaw = WAngle.Zero }); barrelCount = barrels.Count; Barrels = barrels.ToArray(); } public virtual WDist MaxRange() { return new WDist(Util.ApplyPercentageModifiers(Weapon.Range.Length, rangeModifiers.ToArray())); } protected override void Created(Actor self) { turret = self.TraitsImplementing<Turreted>().FirstOrDefault(t => t.Name == Info.Turret); coords = self.Trait<BodyOrientation>(); notifyBurstComplete = self.TraitsImplementing<INotifyBurstComplete>().ToArray(); notifyAttacks = self.TraitsImplementing<INotifyAttack>().ToArray(); conditionManager = self.TraitOrDefault<ConditionManager>(); rangeModifiers = self.TraitsImplementing<IRangeModifier>().ToArray().Select(m => m.GetRangeModifier()); reloadModifiers = self.TraitsImplementing<IReloadModifier>().ToArray().Select(m => m.GetReloadModifier()); damageModifiers = self.TraitsImplementing<IFirepowerModifier>().ToArray().Select(m => m.GetFirepowerModifier()); inaccuracyModifiers = self.TraitsImplementing<IInaccuracyModifier>().ToArray().Select(m => m.GetInaccuracyModifier()); base.Created(self); } void UpdateCondition(Actor self) { if (string.IsNullOrEmpty(Info.ReloadingCondition) || conditionManager == null) return; var enabled = !IsTraitDisabled && IsReloading; if (enabled && conditionToken == ConditionManager.InvalidConditionToken) conditionToken = conditionManager.GrantCondition(self, Info.ReloadingCondition); else if (!enabled && conditionToken != ConditionManager.InvalidConditionToken) conditionToken = conditionManager.RevokeCondition(self, conditionToken); } protected virtual void Tick(Actor self) { // We need to disable conditions if IsTraitDisabled is true, so we have to update conditions before the return below. UpdateCondition(self); if (IsTraitDisabled) return; if (ticksSinceLastShot < Weapon.ReloadDelay) ++ticksSinceLastShot; if (FireDelay > 0) --FireDelay; Recoil = new WDist(Math.Max(0, Recoil.Length - Info.RecoilRecovery.Length)); for (var i = 0; i < delayedActions.Count; i++) { var x = delayedActions[i]; if (--x.First <= 0) x.Second(); delayedActions[i] = x; } delayedActions.RemoveAll(a => a.First <= 0); } void ITick.Tick(Actor self) { // Split into a protected method to allow subclassing Tick(self); } protected void ScheduleDelayedAction(int t, Action a) { if (t > 0) delayedActions.Add(Pair.New(t, a)); else a(); } protected virtual bool CanFire(Actor self, Target target) { if (IsReloading || IsTraitPaused) return false; if (turret != null && !turret.HasAchievedDesiredFacing) return false; if ((!target.IsInRange(self.CenterPosition, MaxRange())) || (Weapon.MinRange != WDist.Zero && target.IsInRange(self.CenterPosition, Weapon.MinRange))) return false; if (!Weapon.IsValidAgainst(target, self.World, self)) return false; return true; } // Note: facing is only used by the legacy positioning code // The world coordinate model uses Actor.Orientation public virtual Barrel CheckFire(Actor self, IFacing facing, Target target) { if (!CanFire(self, target)) return null; if (ticksSinceLastShot >= Weapon.ReloadDelay) Burst = Weapon.Burst; ticksSinceLastShot = 0; // If Weapon.Burst == 1, cycle through all LocalOffsets, otherwise use the offset corresponding to current Burst currentBarrel %= barrelCount; var barrel = Weapon.Burst == 1 ? Barrels[currentBarrel] : Barrels[Burst % Barrels.Length]; currentBarrel++; FireBarrel(self, facing, target, barrel); UpdateBurst(self, target); return barrel; } protected virtual void FireBarrel(Actor self, IFacing facing, Target target, Barrel barrel) { foreach (var na in notifyAttacks) na.PreparingAttack(self, target, this, barrel); Func<WPos> muzzlePosition = () => self.CenterPosition + MuzzleOffset(self, barrel); var legacyFacing = MuzzleOrientation(self, barrel).Yaw.Angle / 4; Func<int> legacyMuzzleFacing = () => MuzzleOrientation(self, barrel).Yaw.Angle / 4; var passiveTarget = Weapon.TargetActorCenter ? target.CenterPosition : target.Positions.PositionClosestTo(muzzlePosition()); var initialOffset = Weapon.FirstBurstTargetOffset; if (initialOffset != WVec.Zero) { // We want this to match Armament.LocalOffset, so we need to convert it to forward, right, up initialOffset = new WVec(initialOffset.Y, -initialOffset.X, initialOffset.Z); passiveTarget += initialOffset.Rotate(WRot.FromFacing(legacyFacing)); } var followingOffset = Weapon.FollowingBurstTargetOffset; if (followingOffset != WVec.Zero) { // We want this to match Armament.LocalOffset, so we need to convert it to forward, right, up followingOffset = new WVec(followingOffset.Y, -followingOffset.X, followingOffset.Z); passiveTarget += ((Weapon.Burst - Burst) * followingOffset).Rotate(WRot.FromFacing(legacyFacing)); } var args = new ProjectileArgs { Weapon = Weapon, Facing = legacyFacing, CurrentMuzzleFacing = legacyMuzzleFacing, DamageModifiers = damageModifiers.ToArray(), InaccuracyModifiers = inaccuracyModifiers.ToArray(), RangeModifiers = rangeModifiers.ToArray(), Source = muzzlePosition(), CurrentSource = muzzlePosition, SourceActor = self, PassiveTarget = passiveTarget, GuidedTarget = target }; ScheduleDelayedAction(Info.FireDelay, () => { if (args.Weapon.Projectile != null) { var projectile = args.Weapon.Projectile.Create(args); if (projectile != null) self.World.Add(projectile); if (args.Weapon.Report != null && args.Weapon.Report.Any()) Game.Sound.Play(SoundType.World, args.Weapon.Report.Random(self.World.SharedRandom), self.CenterPosition); if (Burst == args.Weapon.Burst && args.Weapon.StartBurstReport != null && args.Weapon.StartBurstReport.Any()) Game.Sound.Play(SoundType.World, args.Weapon.StartBurstReport.Random(self.World.SharedRandom), self.CenterPosition); foreach (var na in notifyAttacks) na.Attacking(self, target, this, barrel); Recoil = Info.Recoil; } }); } protected virtual void UpdateBurst(Actor self, Target target) { if (--Burst > 0) { if (Weapon.BurstDelays.Length == 1) FireDelay = Weapon.BurstDelays[0]; else FireDelay = Weapon.BurstDelays[Weapon.Burst - (Burst + 1)]; } else { var modifiers = reloadModifiers.ToArray(); FireDelay = Util.ApplyPercentageModifiers(Weapon.ReloadDelay, modifiers); Burst = Weapon.Burst; if (Weapon.AfterFireSound != null && Weapon.AfterFireSound.Any()) { ScheduleDelayedAction(Weapon.AfterFireSoundDelay, () => { Game.Sound.Play(SoundType.World, Weapon.AfterFireSound.Random(self.World.SharedRandom), self.CenterPosition); }); } foreach (var nbc in notifyBurstComplete) nbc.FiredBurst(self, target, this); } } public virtual bool IsReloading { get { return FireDelay > 0 || IsTraitDisabled; } } public WVec MuzzleOffset(Actor self, Barrel b) { return CalculateMuzzleOffset(self, b); } protected virtual WVec CalculateMuzzleOffset(Actor self, Barrel b) { var bodyOrientation = coords.QuantizeOrientation(self, self.Orientation); var localOffset = b.Offset + new WVec(-Recoil, WDist.Zero, WDist.Zero); if (turret != null) { // WorldOrientation is quantized to satisfy the *Fudges. // Need to then convert back to a pseudo-local coordinate space, apply offsets, // then rotate back at the end var turretOrientation = turret.WorldOrientation(self) - bodyOrientation; localOffset = localOffset.Rotate(turretOrientation); localOffset += turret.Offset; } return coords.LocalToWorld(localOffset.Rotate(bodyOrientation)); } public WRot MuzzleOrientation(Actor self, Barrel b) { return CalculateMuzzleOrientation(self, b); } protected virtual WRot CalculateMuzzleOrientation(Actor self, Barrel b) { var orientation = turret != null ? turret.WorldOrientation(self) : coords.QuantizeOrientation(self, self.Orientation); return orientation + WRot.FromYaw(b.Yaw); } public Actor Actor { get { return self; } } } }
gpl-3.0
andrewhancox/facetoface-2.0
cancelsignup.php
5506
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Copyright (C) 2007-2011 Catalyst IT (http://www.catalyst.net.nz) * Copyright (C) 2011-2013 Totara LMS (http://www.totaralms.com) * Copyright (C) 2014 onwards Catalyst IT (http://www.catalyst-eu.net) * * @package mod * @subpackage facetoface * @copyright 2014 onwards Catalyst IT <http://www.catalyst-eu.net> * @author Stacey Walker <stacey@catalyst-eu.net> * @author Alastair Munro <alastair.munro@totaralms.com> * @author Aaron Barnes <aaron.barnes@totaralms.com> * @author Francois Marier <francois@catalyst.net.nz> */ require_once(dirname(dirname(dirname(__FILE__))) . '/config.php'); require_once('lib.php'); $s = required_param('s', PARAM_INT); // Facetoface session ID. $confirm = optional_param('confirm', false, PARAM_BOOL); $backtoallsessions = optional_param('backtoallsessions', 0, PARAM_INT); if (!$session = facetoface_get_session($s)) { print_error('error:incorrectcoursemodulesession', 'facetoface'); } if (!$session->allowcancellations) { print_error('error:cancellationsnotallowed', 'facetoface'); } if (!$facetoface = $DB->get_record('facetoface', array('id' => $session->facetoface))) { print_error('error:incorrectfacetofaceid', 'facetoface'); } if (!$course = $DB->get_record('course', array('id' => $facetoface->course))) { print_error('error:coursemisconfigured', 'facetoface'); } if (!$cm = get_coursemodule_from_instance("facetoface", $facetoface->id, $course->id)) { print_error('error:incorrectcoursemoduleid', 'facetoface'); } require_course_login($course); $context = context_course::instance($course->id); $contextmodule = context_module::instance($cm->id); require_capability('mod/facetoface:view', $context); $returnurl = "$CFG->wwwroot/course/view.php?id=$course->id"; if ($backtoallsessions) { $returnurl = "$CFG->wwwroot/mod/facetoface/view.php?f=$backtoallsessions"; } $mform = new mod_facetoface_cancelsignup_form(null, compact('s', 'backtoallsessions')); if ($mform->is_cancelled()) { redirect($returnurl); } if ($fromform = $mform->get_data()) { // Form submitted. if (empty($fromform->submitbutton)) { print_error('error:unknownbuttonclicked', 'facetoface', $returnurl); } $timemessage = 4; $errorstr = ''; if (facetoface_user_cancel($session, false, false, $errorstr, $fromform->cancelreason)) { // Logging and events trigger. $params = array( 'context' => $contextmodule, 'objectid' => $session->id ); $event = \mod_facetoface\event\cancel_booking::create($params); $event->add_record_snapshot('facetoface_sessions', $session); $event->add_record_snapshot('facetoface', $facetoface); $event->trigger(); $message = get_string('bookingcancelled', 'facetoface'); if ($session->datetimeknown) { $error = facetoface_send_cancellation_notice($facetoface, $session, $USER->id); if (empty($error)) { if ($session->datetimeknown && $facetoface->cancellationinstrmngr) { $message .= html_writer::empty_tag('br') . html_writer::empty_tag('br') . get_string('cancellationsentmgr', 'facetoface'); } else { $message .= html_writer::empty_tag('br') . html_writer::empty_tag('br') . get_string('cancellationsent', 'facetoface'); } } else { print_error($error, 'facetoface'); } } redirect($returnurl, $message, $timemessage); } else { // Logging and events trigger. $params = array( 'context' => $contextmodule, 'objectid' => $session->id ); $event = \mod_facetoface\event\cancel_booking_failed::create($params); $event->add_record_snapshot('facetoface_sessions', $session); $event->add_record_snapshot('facetoface', $facetoface); $event->trigger(); redirect($returnurl, $errorstr, $timemessage); } redirect($returnurl); } $pagetitle = format_string($facetoface->name); $PAGE->set_cm($cm); $PAGE->set_url('/mod/facetoface/cancelsignup.php', array('s' => $s, 'backtoallsessions' => $backtoallsessions, 'confirm' => $confirm)); $PAGE->set_title($pagetitle); $PAGE->set_heading($course->fullname); echo $OUTPUT->header(); $heading = get_string('cancelbookingfor', 'facetoface', $facetoface->name); $viewattendees = has_capability('mod/facetoface:viewattendees', $context); $signedup = facetoface_check_signup($facetoface->id); echo $OUTPUT->box_start(); echo $OUTPUT->heading($heading); if ($signedup) { facetoface_print_session($session, $viewattendees); $mform->display(); } else { print_error('notsignedup', 'facetoface', $returnurl); } echo $OUTPUT->box_end(); echo $OUTPUT->footer($course);
gpl-3.0
craftercms/studio-test-suite
src/test/java/org/craftercms/studio/test/cases/apitestcases/GetUserActivityAPITest.java
2482
/* * Copyright (C) 2007-2019 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.craftercms.studio.test.cases.apitestcases; import org.craftercms.studio.test.api.objects.ActivityAPI; import org.craftercms.studio.test.api.objects.ContentAssetAPI; import org.craftercms.studio.test.api.objects.SecurityAPI; import org.craftercms.studio.test.api.objects.SiteManagementAPI; import org.craftercms.studio.test.utils.APIConnectionManager; import org.craftercms.studio.test.utils.JsonTester; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * @author chris lim * */ public class GetUserActivityAPITest { private SecurityAPI securityAPI; private SiteManagementAPI siteManagementAPI; private ActivityAPI activityAPI; private ContentAssetAPI contentAssetAPI; private String siteId = "getuseractivityapitest"; public GetUserActivityAPITest() { APIConnectionManager apiConnectionManager = new APIConnectionManager(); JsonTester api = new JsonTester(apiConnectionManager.getProtocol(), apiConnectionManager.getHost(), apiConnectionManager.getPort()); securityAPI = new SecurityAPI(api, apiConnectionManager); siteManagementAPI = new SiteManagementAPI(api, apiConnectionManager); activityAPI = new ActivityAPI(api, apiConnectionManager); contentAssetAPI = new ContentAssetAPI(api, apiConnectionManager); } @BeforeTest public void beforeTest() { securityAPI.logInIntoStudioUsingAPICall(); siteManagementAPI.testCreateSite(siteId); contentAssetAPI.testWriteContent(siteId); } @Test(priority = 1) public void testGetUserActicity() { activityAPI.testGetUserActivity(siteId); } @AfterTest public void afterTest() { siteManagementAPI.testDeleteSite(siteId); securityAPI.logOutFromStudioUsingAPICall(); } }
gpl-3.0
esdalmaijer/EyeTribe_test
experiment/pygaze/_eyetracker/pytribe.py
40918
# PyTribe: classes to communicate with EyeTribe eye trackers # # author: Edwin Dalmaijer # email: edwin.dalmaijer@psy.ox.ac.uk # # version 3 (11-Aug-2014) import os import copy import json import time import socket from threading import Thread, Lock from multiprocessing import Queue class EyeTribe: """class for eye tracking and data collection using an EyeTribe tracker """ def __init__(self, logfilename='default.txt'): """Initializes an EyeTribe instance keyword arguments logfilename -- string indicating the log file name, including a full path to it's location and an extension (default = 'default.txt') """ # initialize data collectors self._logfile = open('%s.tsv' % (logfilename), 'w') self._separator = '\t' self._log_header() self._queue = Queue() # initialize connection self._connection = connection(host='localhost',port=6555) self._tracker = tracker(self._connection) self._heartbeat = heartbeat(self._connection) # create a new Lock self._lock = Lock() # initialize heartbeat thread self._beating = True self._heartbeatinterval = self._tracker.get_heartbeatinterval() / 1000.0 self._hbthread = Thread(target=self._heartbeater, args=[self._heartbeatinterval]) self._hbthread.daemon = True self._hbthread.name = 'heartbeater' # initialize sample streamer self._streaming = True self._samplefreq = self._tracker.get_framerate() self._intsampletime = 1.0 / self._samplefreq self._ssthread = Thread(target=self._stream_samples, args=[self._queue]) self._ssthread.daemon = True self._ssthread.name = 'samplestreamer' # initialize data processer self._processing = True self._logdata = False self._currentsample = self._tracker.get_frame() self._dpthread = Thread(target=self._process_samples, args=[self._queue]) self._dpthread.daemon = True self._dpthread.name = 'dataprocessor' # start all threads self._hbthread.start() self._ssthread.start() self._dpthread.start() # initialize calibration self.calibration = calibration(self._connection) def start_recording(self): """Starts data recording """ # set self._logdata to True, so the data processing thread starts # writing samples to the log file if not self._logdata: self._logdata = True self.log_message("start_recording") def stop_recording(self): """Stops data recording """ # set self._logdata to False, so the data processing thread does not # write samples to the log file if self._logdata: self.log_message("stop_recording") self._logdata = False def log_message(self, message): """Logs a message to the logfile, time locked to the most recent sample """ # timestamp, based on the most recent sample if self._currentsample != None: ts = self._currentsample['timestamp'] t = self._currentsample['time'] else: ts = '' t = '' # assemble line line = self._separator.join(map(str,['MSG',ts,t,message])) # write message self._logfile.write(line + '\n') # to internal buffer self._logfile.flush() # internal buffer to RAM os.fsync(self._logfile.fileno()) # RAM file cache to disk def sample(self): """Returns the most recent point of regard (=gaze location on screen) coordinates (smoothed signal) arguments None returns gaze -- a (x,y) tuple indicating the point of regard """ if self._currentsample == None: return None, None else: return (self._currentsample['avgx'],self._currentsample['avgy']) def pupil_size(self): """Returns the most recent pupil size sample (an average of the size of both pupils) arguments None returns pupsize -- a float indicating the pupil size (in arbitrary units) """ if self._currentsample == None: return None else: return self._currentsample['psize'] def close(self): """Stops all data streaming, and closes both the connection to the tracker and the logfile """ # if we are currently recording, stop doing so if self._logdata: self.stop_recording() # signal all threads to halt self._beating = False self._streaming = False self._processing = False # close the log file self._logfile.close() # close the connection self._connection.close() def _wait_while_calibrating(self): """Waits until the tracker is not in the calibration state """ while self._tracker.get_iscalibrating(): pass return True def _heartbeater(self, heartbeatinterval): """Continuously sends heartbeats to the tracker, to let it know the connection is still alive (it seems to think we could die any moment now, and is very keen on reassurance of our good health; almost like my grandparents...) arguments heartbeatinterval -- float indicating the heartbeatinterval in seconds; note that this is different from the value that the EyeTribe tracker reports: that value is in milliseconds and should be recalculated to seconds here! """ # keep beating until it is signalled that we should stop while self._beating: # do not bother the tracker when it is calibrating #self._wait_while_calibrating() # wait for the Threading Lock to be released, then lock it self._lock.acquire(True) # send heartbeat self._heartbeat.beat() # release the Threading Lock self._lock.release() # wait for a bit time.sleep(heartbeatinterval) def _stream_samples(self, queue): """Continuously polls the device, and puts all new samples in a Queue instance arguments queue -- a multithreading.Queue instance, to put samples into """ # keep streaming until it is signalled that we should stop while self._streaming: # do not bother the tracker when it is calibrating #self._wait_while_calibrating() # wait for the Threading Lock to be released, then lock it self._lock.acquire(True) # get a new sample sample = self._tracker.get_frame() # put the sample in the Queue queue.put(sample) # release the Threading Lock self._lock.release() # pause for half the intersample time, to avoid an overflow # (but to make sure to not miss any samples) time.sleep(self._intsampletime/2) def _process_samples(self, queue): """Continuously processes samples, updating the most recent sample and writing data to a the log file when self._logdata is set to True arguments queue -- a multithreading.Queue instance, to read samples from """ # keep processing until it is signalled that we should stop while self._processing: # wait for the Threading Lock to be released, then lock it self._lock.acquire(True) # read new item from the queue if not queue.empty(): sample = queue.get() else: sample = None # release the Threading Lock self._lock.release() # update newest sample if sample != None: # check if the new sample is the same as the current sample if not self._currentsample['timestamp'] == sample['timestamp']: # update current sample self._currentsample = copy.deepcopy(sample) # write to file if data logging is on if self._logdata: self._log_sample(sample) def _log_sample(self, sample): """Writes a sample to the log file arguments sample -- a sample dict, as is returned by tracker.get_frame """ # assemble new line line = self._separator.join(map(str,[ sample['timestamp'], sample['time'], sample['fix'], sample['state'], sample['rawx'], sample['rawy'], sample['avgx'], sample['avgy'], sample['psize'], sample['Lrawx'], sample['Lrawy'], sample['Lavgx'], sample['Lavgy'], sample['Lpsize'], sample['Lpupilx'], sample['Lpupily'], sample['Rrawx'], sample['Rrawy'], sample['Ravgx'], sample['Ravgy'], sample['Rpsize'], sample['Rpupilx'], sample['Rpupily'] ])) # write line to log file self._logfile.write(line + '\n') # to internal buffer self._logfile.flush() # internal buffer to RAM os.fsync(self._logfile.fileno()) # RAM file cache to disk def _log_header(self): """Logs a header to the data file """ # write a header to the data file header = self._separator.join(['timestamp','time','fix','state', 'rawx','rawy','avgx','avgy','psize', 'Lrawx','Lrawy','Lavgx','Lavgy','Lpsize','Lpupilx','Lpupily', 'Rrawx','Rrawy','Ravgx','Ravgy','Rpsize','Rpupilx','Rpupily' ]) self._logfile.write(header + '\n') # to internal buffer self._logfile.flush() # internal buffer to RAM os.fsync(self._logfile.fileno()) # RAM file cache to disk self._firstlog = False # # # # # # low-level classes class connection: """class for connections with the EyeTribe tracker""" def __init__(self, host='localhost', port=6555): """Initializes the connection with the EyeTribe tracker keyword arguments host -- a string indicating the host IP, NOTE: currently only 'localhost' is supported (default = 'localhost') port -- an integer indicating the port number, NOTE: currently only 6555 is supported (default = 6555) """ # properties self.host = host self.port = port self.resplist = [] self.DEBUG = False # initialize a connection self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host,self.port)) # Create lock self._request_lock = Lock() def request(self, category, request, values): """Send a message over the connection arguments category -- string indicating the query category request -- string indicating the actual request of the message values -- dict or list containing parameters of the request """ # create a JSON formatted string msg = self.create_json(category, request, values) # send the message over the connection self._request_lock.acquire() self.sock.send(msg) # print request in DEBUG mode if self.DEBUG: print("REQUEST: '%s'" % msg) # give the tracker a wee bit of time to reply time.sleep(0.005) # get new responses success = self.get_response() self._request_lock.release() # return the appropriate response if success: for i in range(len(self.resplist)): # check if the category matches if self.resplist[i]['category'] == category: # if this is a heartbeat, return if self.resplist[i]['category'] == 'heartbeat': return self.resplist.pop(i) # if this is another category, check if the request # matches elif self.resplist[i]['request'] == request: return self.resplist.pop(i) # on a connection error, get_response returns False and a connection # error should be returned else: return self.parse_json('{"statuscode":901,"values":{"statusmessage":"connection error"}}') def get_response(self): """Asks for a response, and adds these to the list of all received responses (basically a very simple queue) """ # try to get a new response try: response = self.sock.recv(32768) # print reply in DEBUG mode if self.DEBUG: print("REPLY: '%s'" % response) # if it fails, revive the connection and return a connection error except socket.error: print("reviving connection") self.revive() response = '{"statuscode":901,"values":{"statusmessage":"connection error"}}' return False # split the responses (in case multiple came in) response = response.split('\n') # add parsed responses to the internal list for r in response: if r: self.resplist.append(self.parse_json(r)) return True def create_json(self, category, request, values): """Creates a new json message, in the format that is required by the EyeTribe tracker; these messages consist of a categort, a request and a (list of) value(s), which can be thought of as class.method.value (for more info, see: http://dev.theeyetribe.com/api/) arguments category -- query category (string), e.g. 'tracker', 'calibration', or 'heartbeat' request -- the request message (string), e.g. 'get' for the 'tracker' category values -- a dict of parameters and their values, e.g. {"push":True, "version":1} OR: a list of parameters, e.g. ['push','iscalibrated'] OR: None to pass no values at all keyword arguments None returns jsonmsg -- a string in json format, that can be directly sent to the EyeTribe tracker """ # check if 'values' is a dict if type(values) == dict: # create a value string valuestring = '''{\n''' # loop through all keys of the value dict for k in values.keys(): # add key and value valuestring += '\t\t"%s": %s,\n' % (k, values[k]) # omit final comma valuestring = valuestring[:-2] valuestring += '\n\t}' # check if 'values' is a tuple or a list elif type(values) in [list,tuple]: # create a value string valuestring = '''[ "''' # compose a string of all the values valuestring += '", "'.join(values) # append the list ending valuestring += '" ]' # check if there are no values elif values == None: pass # error if the values are anything other than a dict, tuple or list else: raise Exception("values should be dict, tuple or list, not '%s' (values = %s)" % (type(values),values)) # create the json message if request == None: jsonmsg = ''' { "category": "%s" }''' % (category) elif values == None: jsonmsg = ''' { "category": "%s", "request": "%s", }''' % (category, request) else: jsonmsg = ''' { "category": "%s", "request": "%s", "values": %s }''' % (category, request, valuestring) return jsonmsg def parse_json(self, jsonmsg): """Parses a json message as those that are usually returned by the EyeTribe tracker (for more info, see: http://dev.theeyetribe.com/api/) arguments jsonmsg -- a string in json format keyword arguments None returns msg -- a dict containing the information in the json message; this dict has the following content: { "category": "tracker", "request": "get", "statuscode": 200, "values": { "push":True, "iscalibrated":True } } """ # parse json message parsed = json.loads(jsonmsg) return parsed def revive(self): """Re-establishes a connection """ # close old connection self.close() # initialize a connection self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host,self.port)) def close(self): """Closes the connection to the EyeTribe tracker """ # close the socket connection self.sock.close() class tracker: """class for SDK Tracker state and information related requests""" def __init__(self, connection): """Initializes a tracker instance arguments connection -- a pytribe.connection instance for the currently attached EyeTribe tracker """ self.connection = connection self.push = True def set_connection(self, connection): """Set a new connection arguments connection -- a pytribe.connection instance for the currently attached EyeTribe tracker """ self.connection = connection def get_push(self): """Returns a Booleam reflecting the state: True for push mode, False for pull mode (Boolean) """ # send the request response = self.connection.request('tracker', 'get', ['push']) # return value or error if response['statuscode'] == 200: return response['values']['push'] == 'true' else: raise Exception("Error in tracker.get_push: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def get_heartbeatinterval(self): """Returns the expected heartbeat interval in milliseconds (integer) """ # send the request response = self.connection.request('tracker', 'get', ['heartbeatinterval']) # check if the tracker is in push mode if response['statuscode'] == 200: return response['values']['heartbeatinterval'] else: raise Exception("Error in tracker.get_heartbeatinterval: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def get_version(self): """Returns the version number (integer) """ # send the request response = self.connection.request('tracker', 'get', ['version']) # return value or error if response['statuscode'] == 200: return response['values']['version'] else: raise Exception("Error in tracker.get_version: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def get_trackerstate(self): """Returns the state of the physcial tracker (integer): 0: TRACKER_CONNECTED tracker is detected and working 1: TRACKER_NOT_CONNECTED tracker device is not connected 2: TRACKER_CONNECTED_BADFW tracker device is connected, but not working due to bad firmware 3: TRACKER_CONNECTED_NOUSB3 tracker device is connected, but not working due to unsupported USB host 4: TRACKER_CONNECTED_NOSTREAM tracker device is connected, but no stream could be received """ # send the request response = self.connection.request('tracker', 'get', ['trackerstate']) # return value of error if response['statuscode'] == 200: return response['values']['trackerstate'] else: raise Exception("Error in tracker.get_trackerstate: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def get_framerate(self): """Returns the frame rate that the tracker is running at (integer) """ # send the request response = self.connection.request('tracker', 'get', ['framerate']) # return value or error if response['statuscode'] == 200: return response['values']['framerate'] else: raise Exception("Error in tracker.get_framerate: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def get_iscalibrated(self): """Indicates whether there is a calibration (Boolean) """ # send the request response = self.connection.request('tracker', 'get', ['iscalibrated']) # return value or error if response['statuscode'] == 200: return response['values']['iscalibrated'] == 'true' else: raise Exception("Error in tracker.get_iscalibrated: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def get_iscalibrating(self): """Indicates whether the tracker is in calibration mode (Boolean) """ # send the request response = self.connection.request('tracker', 'get', ['iscalibrating']) # return value or error if response['statuscode'] == 200: return response['values']['iscalibrating'] == 'true' else: raise Exception("Error in tracker.get_iscalibrating: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def get_calibresult(self): """Gets the latest valid calibration result returns WITHOUT CALIBRATION: None WITH CALIBRATION: calibresults -- a dict containing the calibration results: { 'result': Boolean indicating whether the calibration was succesful 'deg': float indicating the average error in degrees of visual angle 'Ldeg': float indicating the left eye error in degrees of visual angle 'Rdeg': float indicating the right eye error in degrees of visual angle 'calibpoints': list, containing a dict for each calibration point: {'state': integer indicating the state of the calibration point (0 means no useful data has been obtained and the point should be resampled; 1 means the data is of questionable quality, consider resampling; 2 means the data is ok) 'cpx': x coordinate of the calibration point 'cpy': y coordinate of the calibration point 'mecpx': mean estimated x coordinate of the calibration point 'mecpy': mean estimated y coordinate of the calibration point 'acd': float indicating the accuracy in degrees of visual angle 'Lacd': float indicating the accuracy in degrees of visual angle (left eye) 'Racd': float indicating the accuracy in degrees of visual angle (right eye) 'mepix': mean error in pixels 'Lmepix': mean error in pixels (left eye) 'Rmepix': mean error in pixels (right eye) 'asdp': standard deviation in pixels 'Lasdp': standard deviation in pixels (left eye) 'Rasdp': standard deviation in pixels (right eye) } } """ # send the request response = self.connection.request('tracker', 'get', ['calibresult']) # return value or error if response['statuscode'] != 200: raise Exception("Error in tracker.get_calibresult: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) # return True if this was not the final calibration point if not 'calibpoints' in response['values']: return None # if this was the final calibration point, return the results else: # return calibration dict returndict = { 'result':response['values']['calibresult']['result'], 'deg':response['values']['calibresult']['deg'], 'Rdeg':response['values']['calibresult']['degl'], 'Ldeg':response['values']['calibresult']['degr'], 'calibpoints':[] } for pointdict in response['values']['calibresult']['calibpoints']: returndict['calibpoints'].append({ 'state':pointdict['state'], 'cpx':pointdict['cp']['x'], 'cpy':pointdict['cp']['y'], 'mecpx':pointdict['mecp']['x'], 'mecpy':pointdict['mecp']['y'], 'acd':pointdict['acd']['ad'], 'Lacd':pointdict['acd']['adl'], 'Racd':pointdict['acd']['adr'], 'mepix':pointdict['mepix']['mep'], 'Lmepix':pointdict['mepix']['mepl'], 'Rmepix':pointdict['mepix']['mepr'], 'asdp':pointdict['asdp']['asd'], 'Lasdp':pointdict['asdp']['asdl'], 'Rasdp':pointdict['asdp']['asdr'] }) return returndict def get_frame(self): """Returns the latest frame data (dict) { 'timestamp': string time representation, 'time': integer timestamp in milliseconds, 'fix': Boolean indicating whether there is a fixation, 'state': integer 32bit masked tracker state, 'rawx': integer raw x gaze coordinate in pixels, 'rawy': integer raw y gaze coordinate in pixels, 'avgx': integer smoothed x gaze coordinate in pixels, 'avgx': integer smoothed y gaze coordinate in pixels, 'psize': float average pupil size, 'Lrawx': integer raw x left eye gaze coordinate in pixels, 'Lrawy': integer raw y left eye gaze coordinate in pixels, 'Lavgx': integer smoothed x left eye gaze coordinate in pixels, 'Lavgx': integer smoothed y left eye gaze coordinate in pixels, 'Lpsize': float left eye pupil size, 'Lpupilx': integer raw left eye pupil centre x coordinate, 'Lpupily': integer raw left eye pupil centre y coordinate, 'Rrawx': integer raw x right eye gaze coordinate in pixels, 'Rrawy': integer raw y right eye gaze coordinate in pixels, 'Ravgx': integer smoothed x right eye gaze coordinate in pixels, 'Ravgx': integer smoothed y right eye gaze coordinate in pixels, 'Rpsize': float right eye pupil size, 'Rpupilx': integer raw right eye pupil centre x coordinate, 'Rpupily': integer raw right eye pupil centre y coordinate } """ # send the request response = self.connection.request('tracker', 'get', ['frame']) # raise error if needed if response['statuscode'] != 200: raise Exception("Error in tracker.get_frame: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) # parse response return { 'timestamp': response['values']['frame']['timestamp'], 'time': response['values']['frame']['time'], 'fix': response['values']['frame']['fix']=='true', 'state': response['values']['frame']['state'], 'rawx': response['values']['frame']['raw']['x'], 'rawy': response['values']['frame']['raw']['y'], 'avgx': response['values']['frame']['avg']['x'], 'avgy': response['values']['frame']['avg']['y'], 'psize': (response['values']['frame']['lefteye']['psize']+response['values']['frame']['righteye']['psize'])/2.0, 'Lrawx': response['values']['frame']['lefteye']['raw']['x'], 'Lrawy': response['values']['frame']['lefteye']['raw']['y'], 'Lavgx': response['values']['frame']['lefteye']['avg']['x'], 'Lavgy': response['values']['frame']['lefteye']['avg']['y'], 'Lpsize': response['values']['frame']['lefteye']['psize'], 'Lpupilx': response['values']['frame']['lefteye']['pcenter']['x'], 'Lpupily': response['values']['frame']['lefteye']['pcenter']['y'], 'Rrawx': response['values']['frame']['righteye']['raw']['x'], 'Rrawy': response['values']['frame']['righteye']['raw']['y'], 'Ravgx': response['values']['frame']['righteye']['avg']['x'], 'Ravgy': response['values']['frame']['righteye']['avg']['y'], 'Rpsize': response['values']['frame']['righteye']['psize'], 'Rpupilx': response['values']['frame']['righteye']['pcenter']['x'], 'Rpupily': response['values']['frame']['righteye']['pcenter']['y'] } def get_screenindex(self): """Returns the screen index number in a multi screen setup (integer) """ # send the request response = self.connection.request('tracker', 'get', ['screenindex']) # return value or error if response['statuscode'] == 200: return response['values']['screenindex'] else: raise Exception("Error in tracker.get_screenindex: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def get_screenresw(self): """Returns the screen resolution width in pixels (integer) """ # send the request response = self.connection.request('tracker', 'get', ['screenresw']) # return value or error if response['statuscode'] == 200: return response['values']['screenresw'] else: raise Exception("Error in tracker.get_screenresw: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def get_screenresh(self): """Returns the screen resolution height in pixels (integer) """ # send the request response = self.connection.request('tracker', 'get', ['screenresh']) # return value or error if response['statuscode'] == 200: return response['values']['screenresh'] else: raise Exception("Error in tracker.get_screenresh: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def get_screenpsyw(self): """Returns the physical screen width in meters (float) """ # send the request response = self.connection.request('tracker', 'get', ['screenpsyw']) # return value or error if response['statuscode'] == 200: return response['values']['screenpsyw'] else: raise Exception("Error in tracker.get_screenpsyw: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def get_screenpsyh(self): """Returns the physical screen height in meters (float) """ # send the request response = self.connection.request('tracker', 'get', ['screenpsyh']) # return value or error if response['statuscode'] == 200: return response['values']['screenpsyh'] else: raise Exception("Error in tracker.get_screenpsyh: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def set_push(self, push=None): """Toggles the push state, or sets the state to the passed value keyword arguments push -- Boolean indicating the state: True for push, False for pull None to toggle current returns state -- Boolean indicating the push state """ # check passed value if push == None: # toggle state self.push = self.push != True elif type(push) == bool: # set state to passed value self.push = push else: # error on anything other than None, True or False raise Exception("tracker.set_push: push keyword argument should be a Boolean or None, not '%s'" % push) # send the request response = self.connection.request('tracker', 'set', {'push':str(self.push).lower()}) # return value or error if response['statuscode'] == 200: return self.push else: raise Exception("Error in tracker.set_push: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def set_version(self, version): """Set the protocol version arguments version -- integer version number """ # send the request response = self.connection.request('tracker', 'set', {'version':version}) # return value or error if response['statuscode'] == 200: return version else: raise Exception("Error in tracker.set_version: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def set_screenindex(self, index): """Set the screen index arguments index -- integer value indicating the index number of the screen that is to be used with the tracker """ # send the request response = self.connection.request('tracker', 'set', {'screenindex':index}) # return value or error if response['statuscode'] == 200: return index else: raise Exception("Error in tracker.set_screenindex: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def set_screenresw(self, width): """Set the screen resolution width arguments width -- integer value indicating the screen resolution width in pixels """ # send the request response = self.connection.request('tracker', 'set', {'screenresw':width}) # return value or error if response['statuscode'] == 200: return width else: raise Exception("Error in tracker.set_screenresw: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def set_screenresh(self, height): """Set the screen resolution height arguments height -- integer value indicating the screen resolution height in pixels """ # send the request response = self.connection.request('tracker', 'set', {'screenresh':height}) # return value or error if response['statuscode'] == 200: return height else: raise Exception("Error in tracker.set_screenresh: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def set_screenpsyw(self, width): """Set the physical width of the screen arguments width -- float value indicating the physical screen width in metres """ # send the request response = self.connection.request('tracker', 'set', {'screenpsyw':width}) # return value or error if response['statuscode'] == 200: return width else: raise Exception("Error in tracker.set_screenpsyw: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def set_screenpsyh(self, height): """Set the physical height of the screen arguments width -- float value indicating the physical screen height in metres """ # send the request response = self.connection.request('tracker', 'set', {'screenpsyh':height}) # return value or error if response['statuscode'] == 200: return height else: raise Exception("Error in tracker.set_screenpsyh: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) class calibration: """class for calibration related requests""" def __init__(self, connection): """Initializes a calibration instance arguments connection -- a pytribe.connection instance for the currently attached EyeTribe tracker """ self.connection = connection def set_connection(self, connection): """Set a new connection arguments connection -- a pytribe.connection instance for the currently attached EyeTribe tracker """ self.connection = connection def start(self, pointcount=9): """Starts the calibration, using the passed number of calibration points keyword arguments pointcount -- integer value indicating the amount of calibration points that should be used, which should be at least 7 (default = 9) """ # send the request response = self.connection.request('calibration', 'start', {'pointcount':pointcount}) # return value or error if response['statuscode'] == 200: return True else: raise Exception("Error in calibration.start: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def pointstart(self, x, y): """Mark the beginning of a new calibration point for the tracker to process arguments x -- integer indicating the x coordinate of the calibration point y -- integer indicating the y coordinate of the calibration point returns success -- Boolean: True on success, False on a failure """ # send the request response = self.connection.request('calibration', 'pointstart', {'x':x,'y':y}) # return value or error if response['statuscode'] == 200: return True else: raise Exception("Error in calibration.pointstart: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def pointend(self): """Mark the end of processing a calibration point returns NORMALLY: success -- Boolean: True on success, False on failure AFTER FINAL POINT: calibresults -- a dict containing the calibration results: { 'result': Boolean indicating whether the calibration was succesful 'deg': float indicating the average error in degrees of visual angle 'Ldeg': float indicating the left eye error in degrees of visual angle 'Rdeg': float indicating the right eye error in degrees of visual angle 'calibpoints': list, containing a dict for each calibration point: {'state': integer indicating the state of the calibration point (0 means no useful data has been obtained and the point should be resampled; 1 means the data is of questionable quality, consider resampling; 2 means the data is ok) 'cpx': x coordinate of the calibration point 'cpy': y coordinate of the calibration point 'mecpx': mean estimated x coordinate of the calibration point 'mecpy': mean estimated y coordinate of the calibration point 'acd': float indicating the accuracy in degrees of visual angle 'Lacd': float indicating the accuracy in degrees of visual angle (left eye) 'Racd': float indicating the accuracy in degrees of visual angle (right eye) 'mepix': mean error in pixels 'Lmepix': mean error in pixels (left eye) 'Rmepix': mean error in pixels (right eye) 'asdp': standard deviation in pixels 'Lasdp': standard deviation in pixels (left eye) 'Rasdp': standard deviation in pixels (right eye) } } """ # send the request response = self.connection.request('calibration', 'pointend', None) # return value or error if response['statuscode'] != 200: raise Exception("Error in calibration.pointend: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) # return True if this was not the final calibration point if not 'calibresult' in response['values']: return True # if this was the final calibration point, return the results else: # return calibration dict returndict = { 'result':response['values']['calibresult']['result'], 'deg':response['values']['calibresult']['deg'], 'Rdeg':response['values']['calibresult']['degl'], 'Ldeg':response['values']['calibresult']['degr'], 'calibpoints':[] } for pointdict in response['values']['calibresult']['calibpoints']: returndict['calibpoints'].append({ 'state':pointdict['state'], 'cpx':pointdict['cp']['x'], 'cpy':pointdict['cp']['y'], 'mecpx':pointdict['mecp']['x'], 'mecpy':pointdict['mecp']['y'], 'acd':pointdict['acd']['ad'], 'Lacd':pointdict['acd']['adl'], 'Racd':pointdict['acd']['adr'], 'mepix':pointdict['mepix']['mep'], 'Lmepix':pointdict['mepix']['mepl'], 'Rmepix':pointdict['mepix']['mepr'], 'asdp':pointdict['asdp']['asd'], 'Lasdp':pointdict['asdp']['asdl'], 'Rasdp':pointdict['asdp']['asdr'] }) return returndict def abort(self): """Cancels the ongoing sequence and reinstates the previous calibration (only if there is one!) returns success -- Boolean: True on success, False on failure """ # send the request response = self.connection.request('calibration', 'abort', None) # return value or error if response['statuscode'] == 200: return True else: raise Exception("Error in calibration.abort: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) def clear(self): """Removes the current calibration from the tracker returns success -- Boolean: True on success, False on failure """ # send the request response = self.connection.request('calibration', 'clear', None) # return value or error if response['statuscode'] == 200: return True else: raise Exception("Error in calibration.clear: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) class heartbeat: """class for signalling heartbeats to the server""" def __init__(self, connection): """Initializes a heartbeat instance (not implemented in the SDK yet) arguments connection -- a pytribe.connection instance for the currently attached EyeTribe tracker """ self.connection = connection def set_connection(self, connection): """Set a new connection arguments connection -- a pytribe.connection instance for the currently attached EyeTribe tracker """ self.connection = connection def beat(self): """Sends a heartbeat to the device """ # send the request response = self.connection.request('heartbeat', None, None) # return value or error if response['statuscode'] == 200: return True else: raise Exception("Error in heartbeat.beat: %s (code %d)" % (response['values']['statusmessage'],response['statuscode'])) # # # # # # DEBUG # if __name__ == "__main__": test = EyeTribe() test.start_recording() time.sleep(10) test.stop_recording() test.close() # # # # #
gpl-3.0
aphexddb/agocontrol
devices/squeezeboxserver/agosqueezeboxserver.py
4265
# # Squeezebox client # # copyright (c) 2013 James Roberts <jimbob@jamesroberts.co.uk> # Using agoclient sample code as guidance! import agoclient import squeezeboxserver import threading import time client = agoclient.AgoConnection("squeezebox") # if you need to fetch any settings from config.ini, use the get_config_option call. The first parameter is the section name in the file (should be yor instance name) # the second one is the parameter name, and the third one is the default value for the case when nothing is set in the config.ini server = agoclient.get_config_option("squeezebox", "server", "127.0.0.1:9000") print "Server: " + server squeezebox = squeezeboxserver.SqueezeboxServer(server) # the messageHandler method will be called by the client library when a message comes in that is destined for one of the child devices you're handling # the first parameter is your internal id (all the mapping from ago control uuids to the internal ids is handled transparently for you) # the second parameter is a dict with the message content def messageHandler(internalid, content): if "command" in content: if content["command"] == "on": print "switching on: " + internalid squeezebox.power(internalid, content["command"]) client.emit_event(internalid, "event.device.statechanged", "255", "") if content["command"] == "off": print "switching off: " + internalid squeezebox.power(internalid, content["command"]) client.emit_event(internalid, "event.device.statechanged", "0", "") if content["command"] == "play": print "Play: " + internalid squeezebox.playlist(internalid, content["command"]) client.emit_event(internalid, "event.mediaplayer.statechanged", content["command"], "") if content["command"] == "pause": print "Pause: " + internalid squeezebox.playlist(internalid, content["command"]) client.emit_event(internalid, "event.mediaplayer.statechanged", content["command"], "") if content["command"] == "stop": print "Stop: " + internalid squeezebox.playlist(internalid, content["command"]) client.emit_event(internalid, "event.mediaplayer.statechanged", content["command"], "") # specify our message handler method client.add_handler(messageHandler) # of course you need to tell the client library about the devices you provide. The add_device call expects a internal id and a device type (you can find all valid types # in the schema.yaml configuration file). The internal id is whatever you're using in your code to distinct your devices. Or the pin number of some GPIO output. Or # the IP of a networked device. Whatever fits your device specific stuff. The persistent translation to a ago control uuid will be done by the client library. The # mapping is stored as a json file in CONFDIR/uuidmap/<instance name>.json # you don't need to worry at all about this, when the messageHandler is called, you'll be passed the internalid for the device that you did specifiy when using add_device() # Discover the devices connected players = squeezebox.players() for p in players: print ("MAC: %s" % p['playerid']) client.add_device(p['playerid'], "squeezebox") #client.add_device("MAC Address", "squeezebox") # then we add a background thread. This is not required and just shows how to send events from a separate thread. This might be handy when you have to poll something # in the background or need to handle some other communication. If you don't need one or if you want to keep things simple at the moment just skip this section. # Use this to create a thread to listen for events from clients - but how?? #class testEvent(threading.Thread): # def __init__(self,): # threading.Thread.__init__(self) # def run(self): # level = 0 # while (True): # client.emit_event("125", "event.security.sensortriggered", level, "") # if (level == 0): # level = 255 # else: # level = 0 # time.sleep (5) # #background = testEvent() #background.setDaemon(True) #background.start() # now you should have added all devices, set up all your internal and device specific stuff, started everything like listener threads or whatever. The call to run() # is blocking and will start the message handling client.run()
gpl-3.0
etherkit/OpenBeacon2
client/win/venv/Lib/site-packages/cmd2/argparse_custom.py
34936
# coding=utf-8 """ This module adds capabilities to argparse by patching a few of its functions. It also defines a parser class called Cmd2ArgumentParser which improves error and help output over normal argparse. All cmd2 code uses this parser and it is recommended that developers of cmd2-based apps either use it or write their own parser that inherits from it. This will give a consistent look-and-feel between the help/error output of built-in cmd2 commands and the app-specific commands. Since the new capabilities are added by patching at the argparse API level, they are available whether or not Cmd2ArgumentParser is used. However, the help and error output of Cmd2ArgumentParser is customized to notate nargs ranges whereas any other parser class won't be as explicit in their output. ############################################################################################################ # Added capabilities ############################################################################################################ Extends argparse nargs functionality by allowing tuples which specify a range (min, max). To specify a max value with no upper bound, use a 1-item tuple (min,) Example: # -f argument expects at least 3 values parser.add_argument('-f', nargs=(3,)) # -f argument expects 3 to 5 values parser.add_argument('-f', nargs=(3, 5)) Tab Completion: cmd2 uses its AutoCompleter class to enable argparse-based tab completion on all commands that use the @with_argparse wrappers. Out of the box you get tab completion of commands, subcommands, and flag names, as well as instructive hints about the current argument that print when tab is pressed. In addition, you can add tab completion for each argument's values using parameters passed to add_argument(). Below are the 5 add_argument() parameters for enabling tab completion of an argument's value. Only one can be used at a time. choices Pass a list of values to the choices parameter. Example: parser.add_argument('-o', '--options', choices=['An Option', 'SomeOtherOption']) parser.add_argument('-o', '--options', choices=my_list) choices_function Pass a function that returns choices. This is good in cases where the choice list is dynamically generated when the user hits tab. Example: def my_choices_function): ... return my_generated_list parser.add_argument('-o', '--options', choices_function=my_choices_function) choices_method This is exactly like choices_function, but the function needs to be an instance method of a cmd2-based class. When AutoCompleter calls the method, it will pass the app instance as the self argument. This is good in cases where the list of choices being generated relies on state data of the cmd2-based app Example: def my_choices_method(self): ... return my_generated_list completer_function Pass a tab-completion function that does custom completion. Since custom tab completion operations commonly need to modify cmd2's instance variables related to tab-completion, it will be rare to need a completer function. completer_method should be used in those cases. Example: def my_completer_function(text, line, begidx, endidx): ... return completions parser.add_argument('-o', '--options', completer_function=my_completer_function) completer_method This is exactly like completer_function, but the function needs to be an instance method of a cmd2-based class. When AutoCompleter calls the method, it will pass the app instance as the self argument. cmd2 provides a few completer methods for convenience (e.g., path_complete, delimiter_complete) Example: This adds file-path completion to an argument parser.add_argument('-o', '--options', completer_method=cmd2.Cmd.path_complete) You can use functools.partial() to prepopulate values of the underlying choices and completer functions/methods. Example: This says to call path_complete with a preset value for its path_filter argument. completer_method = functools.partial(path_complete, path_filter=lambda path: os.path.isdir(path)) parser.add_argument('-o', '--options', choices_method=completer_method) Of the 5 tab-completion parameters, choices is the only one where argparse validates user input against items in the choices list. This is because the other 4 parameters are meant to tab complete data sets that are viewed as dynamic. Therefore it is up to the developer to validate if the user has typed an acceptable value for these arguments. The following functions exist in cases where you may want to manually add choice providing function/methods to an existing argparse action. For instance, in __init__() of a custom action class. set_choices_function(action, func) set_choices_method(action, method) set_completer_function(action, func) set_completer_method(action, method) CompletionItem Class: This class was added to help in cases where uninformative data is being tab completed. For instance, tab completing ID numbers isn't very helpful to a user without context. Returning a list of CompletionItems instead of a regular string for completion results will signal the AutoCompleter to output the completion results in a table of completion tokens with descriptions instead of just a table of tokens. Instead of this: 1 2 3 The user sees this: ITEM_ID Item Name 1 My item 2 Another item 3 Yet another item The left-most column is the actual value being tab completed and its header is that value's name. The right column header is defined using the descriptive_header parameter of add_argument(). The right column values come from the CompletionItem.description value. Example: token = 1 token_description = "My Item" completion_item = CompletionItem(token, token_description) Since descriptive_header and CompletionItem.description are just strings, you can format them in such a way to have multiple columns. ITEM_ID Item Name Checked Out Due Date 1 My item True 02/02/2022 2 Another item False 3 Yet another item False To use CompletionItems, just return them from your choices or completer functions. To avoid printing a ton of information to the screen at once when a user presses tab, there is a maximum threshold for the number of CompletionItems that will be shown. It's value is defined in cmd2.Cmd.max_completion_items. It defaults to 50, but can be changed. If the number of completion suggestions exceeds this number, they will be displayed in the typical columnized format and will not include the description value of the CompletionItems. ############################################################################################################ # Patched argparse functions: ########################################################################################################### argparse._ActionsContainer.add_argument - adds arguments related to tab completion and enables nargs range parsing See _add_argument_wrapper for more details on these argument argparse.ArgumentParser._get_nargs_pattern - adds support to for nargs ranges See _get_nargs_pattern_wrapper for more details argparse.ArgumentParser._match_argument - adds support to for nargs ranges See _match_argument_wrapper for more details """ import argparse import re import sys # noinspection PyUnresolvedReferences,PyProtectedMember from argparse import ZERO_OR_MORE, ONE_OR_MORE, ArgumentError, _ from typing import Any, Callable, Iterable, List, Optional, Tuple, Union from .ansi import ansi_aware_write, style_error # Used in nargs ranges to signify there is no maximum INFINITY = float('inf') ############################################################################################################ # The following are names of custom argparse argument attributes added by cmd2 ############################################################################################################ # A tuple specifying nargs as a range (min, max) ATTR_NARGS_RANGE = 'nargs_range' # ChoicesCallable object that specifies the function to be called which provides choices to the argument ATTR_CHOICES_CALLABLE = 'choices_callable' # Pressing tab normally displays the help text for the argument if no choices are available # Setting this attribute to True will suppress these hints ATTR_SUPPRESS_TAB_HINT = 'suppress_tab_hint' # Descriptive header that prints when using CompletionItems ATTR_DESCRIPTIVE_COMPLETION_HEADER = 'desc_completion_header' def generate_range_error(range_min: int, range_max: Union[int, float]) -> str: """Generate an error message when the the number of arguments provided is not within the expected range""" err_str = "expected " if range_max == INFINITY: err_str += "at least {} argument".format(range_min) if range_min != 1: err_str += "s" else: if range_min == range_max: err_str += "{} argument".format(range_min) else: err_str += "{} to {} argument".format(range_min, range_max) if range_max != 1: err_str += "s" return err_str class CompletionItem(str): """ Completion item with descriptive text attached See header of this file for more information """ def __new__(cls, value: object, *args, **kwargs) -> str: return super().__new__(cls, value) # noinspection PyUnusedLocal def __init__(self, value: object, desc: str = '', *args, **kwargs) -> None: """ CompletionItem Initializer :param value: the value being tab completed :param desc: description text to display :param args: args for str __init__ :param kwargs: kwargs for str __init__ """ super().__init__(*args, **kwargs) self.description = desc ############################################################################################################ # Class and functions related to ChoicesCallable ############################################################################################################ class ChoicesCallable: """ Enables using a callable as the choices provider for an argparse argument. While argparse has the built-in choices attribute, it is limited to an iterable. """ def __init__(self, is_method: bool, is_completer: bool, to_call: Callable): """ Initializer :param is_method: True if to_call is an instance method of a cmd2 app. False if it is a function. :param is_completer: True if to_call is a tab completion routine which expects the args: text, line, begidx, endidx :param to_call: the callable object that will be called to provide choices for the argument """ self.is_method = is_method self.is_completer = is_completer self.to_call = to_call def _set_choices_callable(action: argparse.Action, choices_callable: ChoicesCallable) -> None: """ Set the choices_callable attribute of an argparse Action :param action: action being edited :param choices_callable: the ChoicesCallable instance to use :raises: TypeError if used on incompatible action type """ # Verify consistent use of parameters if action.choices is not None: err_msg = ("None of the following parameters can be used alongside a choices parameter:\n" "choices_function, choices_method, completer_function, completer_method") raise (TypeError(err_msg)) elif action.nargs == 0: err_msg = ("None of the following parameters can be used on an action that takes no arguments:\n" "choices_function, choices_method, completer_function, completer_method") raise (TypeError(err_msg)) setattr(action, ATTR_CHOICES_CALLABLE, choices_callable) def set_choices_function(action: argparse.Action, choices_function: Callable[[], Iterable[Any]]) -> None: """Set choices_function on an argparse action""" _set_choices_callable(action, ChoicesCallable(is_method=False, is_completer=False, to_call=choices_function)) def set_choices_method(action: argparse.Action, choices_method: Callable[[Any], Iterable[Any]]) -> None: """Set choices_method on an argparse action""" _set_choices_callable(action, ChoicesCallable(is_method=True, is_completer=False, to_call=choices_method)) def set_completer_function(action: argparse.Action, completer_function: Callable[[str, str, int, int], List[str]]) -> None: """Set completer_function on an argparse action""" _set_choices_callable(action, ChoicesCallable(is_method=False, is_completer=True, to_call=completer_function)) def set_completer_method(action: argparse.Action, completer_method: Callable[[Any, str, str, int, int], List[str]]) -> None: """Set completer_method on an argparse action""" _set_choices_callable(action, ChoicesCallable(is_method=True, is_completer=True, to_call=completer_method)) ############################################################################################################ # Patch _ActionsContainer.add_argument with our wrapper to support more arguments ############################################################################################################ # Save original _ActionsContainer.add_argument so we can call it in our wrapper # noinspection PyProtectedMember orig_actions_container_add_argument = argparse._ActionsContainer.add_argument def _add_argument_wrapper(self, *args, nargs: Union[int, str, Tuple[int], Tuple[int, int], None] = None, choices_function: Optional[Callable[[], Iterable[Any]]] = None, choices_method: Optional[Callable[[Any], Iterable[Any]]] = None, completer_function: Optional[Callable[[str, str, int, int], List[str]]] = None, completer_method: Optional[Callable[[Any, str, str, int, int], List[str]]] = None, suppress_tab_hint: bool = False, descriptive_header: Optional[str] = None, **kwargs) -> argparse.Action: """ Wrapper around _ActionsContainer.add_argument() which supports more settings used by cmd2 # Args from original function :param self: instance of the _ActionsContainer being added to :param args: arguments expected by argparse._ActionsContainer.add_argument # Customized arguments from original function :param nargs: extends argparse nargs functionality by allowing tuples which specify a range (min, max) to specify a max value with no upper bound, use a 1-item tuple (min,) # Added args used by AutoCompleter :param choices_function: function that provides choices for this argument :param choices_method: cmd2-app method that provides choices for this argument :param completer_function: tab-completion function that provides choices for this argument :param completer_method: cmd2-app tab-completion method that provides choices for this argument :param suppress_tab_hint: when AutoCompleter has no results to show during tab completion, it displays the current argument's help text as a hint. Set this to True to suppress the hint. If this argument's help text is set to argparse.SUPPRESS, then tab hints will not display regardless of the value passed for suppress_tab_hint. Defaults to False. :param descriptive_header: if the provided choices are CompletionItems, then this header will display during tab completion. Defaults to None. # Args from original function :param kwargs: keyword-arguments recognized by argparse._ActionsContainer.add_argument Note: You can only use 1 of the following in your argument: choices, choices_function, choices_method, completer_function, completer_method See the header of this file for more information :return: the created argument action :raises ValueError on incorrect parameter usage """ # Verify consistent use of arguments choices_callables = [choices_function, choices_method, completer_function, completer_method] num_params_set = len(choices_callables) - choices_callables.count(None) if num_params_set > 1: err_msg = ("Only one of the following parameters may be used at a time:\n" "choices_function, choices_method, completer_function, completer_method") raise (ValueError(err_msg)) # Pre-process special ranged nargs nargs_range = None if nargs is not None: # Check if nargs was given as a range if isinstance(nargs, tuple): # Handle 1-item tuple by setting max to INFINITY if len(nargs) == 1: nargs = (nargs[0], INFINITY) # Validate nargs tuple if len(nargs) != 2 or not isinstance(nargs[0], int) or \ not (isinstance(nargs[1], int) or nargs[1] == INFINITY): raise ValueError('Ranged values for nargs must be a tuple of 1 or 2 integers') if nargs[0] >= nargs[1]: raise ValueError('Invalid nargs range. The first value must be less than the second') if nargs[0] < 0: raise ValueError('Negative numbers are invalid for nargs range') # Save the nargs tuple as our range setting nargs_range = nargs range_min = nargs_range[0] range_max = nargs_range[1] # Convert nargs into a format argparse recognizes if range_min == 0: if range_max == 1: nargs_adjusted = argparse.OPTIONAL # No range needed since (0, 1) is just argparse.OPTIONAL nargs_range = None else: nargs_adjusted = argparse.ZERO_OR_MORE if range_max == INFINITY: # No range needed since (0, INFINITY) is just argparse.ZERO_OR_MORE nargs_range = None elif range_min == 1 and range_max == INFINITY: nargs_adjusted = argparse.ONE_OR_MORE # No range needed since (1, INFINITY) is just argparse.ONE_OR_MORE nargs_range = None else: nargs_adjusted = argparse.ONE_OR_MORE else: nargs_adjusted = nargs # Add the argparse-recognized version of nargs to kwargs kwargs['nargs'] = nargs_adjusted # Create the argument using the original add_argument function new_arg = orig_actions_container_add_argument(self, *args, **kwargs) # Set the custom attributes setattr(new_arg, ATTR_NARGS_RANGE, nargs_range) if choices_function: set_choices_function(new_arg, choices_function) elif choices_method: set_choices_method(new_arg, choices_method) elif completer_function: set_completer_function(new_arg, completer_function) elif completer_method: set_completer_method(new_arg, completer_method) setattr(new_arg, ATTR_SUPPRESS_TAB_HINT, suppress_tab_hint) setattr(new_arg, ATTR_DESCRIPTIVE_COMPLETION_HEADER, descriptive_header) return new_arg # Overwrite _ActionsContainer.add_argument with our wrapper # noinspection PyProtectedMember argparse._ActionsContainer.add_argument = _add_argument_wrapper ############################################################################################################ # Patch ArgumentParser._get_nargs_pattern with our wrapper to nargs ranges ############################################################################################################ # Save original ArgumentParser._get_nargs_pattern so we can call it in our wrapper # noinspection PyProtectedMember orig_argument_parser_get_nargs_pattern = argparse.ArgumentParser._get_nargs_pattern # noinspection PyProtectedMember def _get_nargs_pattern_wrapper(self, action) -> str: # Wrapper around ArgumentParser._get_nargs_pattern behavior to support nargs ranges nargs_range = getattr(action, ATTR_NARGS_RANGE, None) if nargs_range is not None: if nargs_range[1] == INFINITY: range_max = '' else: range_max = nargs_range[1] nargs_pattern = '(-*A{{{},{}}}-*)'.format(nargs_range[0], range_max) # if this is an optional action, -- is not allowed if action.option_strings: nargs_pattern = nargs_pattern.replace('-*', '') nargs_pattern = nargs_pattern.replace('-', '') return nargs_pattern return orig_argument_parser_get_nargs_pattern(self, action) # Overwrite ArgumentParser._get_nargs_pattern with our wrapper # noinspection PyProtectedMember argparse.ArgumentParser._get_nargs_pattern = _get_nargs_pattern_wrapper ############################################################################################################ # Patch ArgumentParser._match_argument with our wrapper to nargs ranges ############################################################################################################ # noinspection PyProtectedMember orig_argument_parser_match_argument = argparse.ArgumentParser._match_argument # noinspection PyProtectedMember def _match_argument_wrapper(self, action, arg_strings_pattern) -> int: # Wrapper around ArgumentParser._match_argument behavior to support nargs ranges nargs_pattern = self._get_nargs_pattern(action) match = re.match(nargs_pattern, arg_strings_pattern) # raise an exception if we weren't able to find a match if match is None: nargs_range = getattr(action, ATTR_NARGS_RANGE, None) if nargs_range is not None: raise ArgumentError(action, generate_range_error(nargs_range[0], nargs_range[1])) return orig_argument_parser_match_argument(self, action, arg_strings_pattern) # Overwrite ArgumentParser._match_argument with our wrapper # noinspection PyProtectedMember argparse.ArgumentParser._match_argument = _match_argument_wrapper ############################################################################################################ # Unless otherwise noted, everything below this point are copied from Python's # argparse implementation with minor tweaks to adjust output. # Changes are noted if it's buried in a block of copied code. Otherwise the # function will check for a special case and fall back to the parent function ############################################################################################################ # noinspection PyCompatibility,PyShadowingBuiltins,PyShadowingBuiltins class Cmd2HelpFormatter(argparse.RawTextHelpFormatter): """Custom help formatter to configure ordering of help text""" def _format_usage(self, usage, actions, groups, prefix) -> str: if prefix is None: prefix = _('Usage: ') # if usage is specified, use that if usage is not None: usage %= dict(prog=self._prog) # if no optionals or positionals are available, usage is just prog elif usage is None and not actions: usage = '%(prog)s' % dict(prog=self._prog) # if optionals and positionals are available, calculate usage elif usage is None: prog = '%(prog)s' % dict(prog=self._prog) # split optionals from positionals optionals = [] positionals = [] # Begin cmd2 customization (separates required and optional, applies to all changes in this function) required_options = [] for action in actions: if action.option_strings: if action.required: required_options.append(action) else: optionals.append(action) else: positionals.append(action) # End cmd2 customization # build full usage string format = self._format_actions_usage action_usage = format(required_options + optionals + positionals, groups) usage = ' '.join([s for s in [prog, action_usage] if s]) # wrap the usage parts if it's too long text_width = self._width - self._current_indent if len(prefix) + len(usage) > text_width: # Begin cmd2 customization # break usage into wrappable parts part_regexp = r'\(.*?\)+|\[.*?\]+|\S+' req_usage = format(required_options, groups) opt_usage = format(optionals, groups) pos_usage = format(positionals, groups) req_parts = re.findall(part_regexp, req_usage) opt_parts = re.findall(part_regexp, opt_usage) pos_parts = re.findall(part_regexp, pos_usage) assert ' '.join(req_parts) == req_usage assert ' '.join(opt_parts) == opt_usage assert ' '.join(pos_parts) == pos_usage # End cmd2 customization # helper for wrapping lines # noinspection PyMissingOrEmptyDocstring,PyShadowingNames def get_lines(parts, indent, prefix=None): lines = [] line = [] if prefix is not None: line_len = len(prefix) - 1 else: line_len = len(indent) - 1 for part in parts: if line_len + 1 + len(part) > text_width and line: lines.append(indent + ' '.join(line)) line = [] line_len = len(indent) - 1 line.append(part) line_len += len(part) + 1 if line: lines.append(indent + ' '.join(line)) if prefix is not None: lines[0] = lines[0][len(indent):] return lines # if prog is short, follow it with optionals or positionals if len(prefix) + len(prog) <= 0.75 * text_width: indent = ' ' * (len(prefix) + len(prog) + 1) # Begin cmd2 customization if req_parts: lines = get_lines([prog] + req_parts, indent, prefix) lines.extend(get_lines(opt_parts, indent)) lines.extend(get_lines(pos_parts, indent)) elif opt_parts: lines = get_lines([prog] + opt_parts, indent, prefix) lines.extend(get_lines(pos_parts, indent)) elif pos_parts: lines = get_lines([prog] + pos_parts, indent, prefix) else: lines = [prog] # End cmd2 customization # if prog is long, put it on its own line else: indent = ' ' * len(prefix) # Begin cmd2 customization parts = req_parts + opt_parts + pos_parts lines = get_lines(parts, indent) if len(lines) > 1: lines = [] lines.extend(get_lines(req_parts, indent)) lines.extend(get_lines(opt_parts, indent)) lines.extend(get_lines(pos_parts, indent)) # End cmd2 customization lines = [prog] + lines # join lines into usage usage = '\n'.join(lines) # prefix with 'Usage:' return '%s%s\n\n' % (prefix, usage) def _format_action_invocation(self, action) -> str: if not action.option_strings: default = self._get_default_metavar_for_positional(action) metavar, = self._metavar_formatter(action, default)(1) return metavar else: parts = [] # if the Optional doesn't take a value, format is: # -s, --long if action.nargs == 0: parts.extend(action.option_strings) return ', '.join(parts) # Begin cmd2 customization (less verbose) # if the Optional takes a value, format is: # -s, --long ARGS else: default = self._get_default_metavar_for_optional(action) args_string = self._format_args(action, default) return ', '.join(action.option_strings) + ' ' + args_string # End cmd2 customization def _metavar_formatter(self, action, default_metavar) -> Callable: if action.metavar is not None: result = action.metavar elif action.choices is not None: choice_strs = [str(choice) for choice in action.choices] # Begin cmd2 customization (added space after comma) result = '{%s}' % ', '.join(choice_strs) # End cmd2 customization else: result = default_metavar # noinspection PyMissingOrEmptyDocstring def format(tuple_size): if isinstance(result, tuple): return result else: return (result, ) * tuple_size return format # noinspection PyProtectedMember def _format_args(self, action, default_metavar) -> str: get_metavar = self._metavar_formatter(action, default_metavar) # Begin cmd2 customization (less verbose) nargs_range = getattr(action, ATTR_NARGS_RANGE, None) if nargs_range is not None: if nargs_range[1] == INFINITY: range_str = '{}+'.format(nargs_range[0]) else: range_str = '{}..{}'.format(nargs_range[0], nargs_range[1]) result = '{}{{{}}}'.format('%s' % get_metavar(1), range_str) elif action.nargs == ZERO_OR_MORE: result = '[%s [...]]' % get_metavar(1) elif action.nargs == ONE_OR_MORE: result = '%s [...]' % get_metavar(1) elif isinstance(action.nargs, int) and action.nargs > 1: result = '{}{{{}}}'.format('%s' % get_metavar(1), action.nargs) # End cmd2 customization else: result = super()._format_args(action, default_metavar) return result # noinspection PyCompatibility class Cmd2ArgumentParser(argparse.ArgumentParser): """Custom ArgumentParser class that improves error and help output""" def __init__(self, *args, **kwargs) -> None: if 'formatter_class' not in kwargs: kwargs['formatter_class'] = Cmd2HelpFormatter super().__init__(*args, **kwargs) def add_subparsers(self, **kwargs): """Custom override. Sets a default title if one was not given.""" if 'title' not in kwargs: kwargs['title'] = 'subcommands' return super().add_subparsers(**kwargs) def error(self, message: str) -> None: """Custom override that applies custom formatting to the error message""" lines = message.split('\n') linum = 0 formatted_message = '' for line in lines: if linum == 0: formatted_message = 'Error: ' + line else: formatted_message += '\n ' + line linum += 1 self.print_usage(sys.stderr) formatted_message = style_error(formatted_message) self.exit(2, '{}\n\n'.format(formatted_message)) # noinspection PyProtectedMember def format_help(self) -> str: """Copy of format_help() from argparse.ArgumentParser with tweaks to separately display required parameters""" formatter = self._get_formatter() # usage formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups) # description formatter.add_text(self.description) # Begin cmd2 customization (separate required and optional arguments) # positionals, optionals and user-defined groups for action_group in self._action_groups: if action_group.title == 'optional arguments': # check if the arguments are required, group accordingly req_args = [] opt_args = [] for action in action_group._group_actions: if action.required: req_args.append(action) else: opt_args.append(action) # separately display required arguments formatter.start_section('required arguments') formatter.add_text(action_group.description) formatter.add_arguments(req_args) formatter.end_section() # now display truly optional arguments formatter.start_section(action_group.title) formatter.add_text(action_group.description) formatter.add_arguments(opt_args) formatter.end_section() else: formatter.start_section(action_group.title) formatter.add_text(action_group.description) formatter.add_arguments(action_group._group_actions) formatter.end_section() # End cmd2 customization # epilog formatter.add_text(self.epilog) # determine help from format above return formatter.format_help() + '\n' def _print_message(self, message, file=None): # Override _print_message to use ansi_aware_write() since we use ANSI escape characters to support color if message: if file is None: file = sys.stderr ansi_aware_write(file, message)
gpl-3.0
JunkyBulgaria/Test
src/main/java/net/minecraft/server/BlockCactus.java
4044
package net.minecraft.server; import java.util.Iterator; import java.util.Random; import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit public class BlockCactus extends Block { public static final BlockStateInteger AGE = BlockStateInteger.of("age", 0, 15); protected BlockCactus() { super(Material.CACTUS); this.j(this.blockStateList.getBlockData().set(BlockCactus.AGE, Integer.valueOf(0))); this.a(true); this.a(CreativeModeTab.c); } public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { BlockPosition blockposition1 = blockposition.up(); if (world.isEmpty(blockposition1)) { int i; for (i = 1; world.getType(blockposition.down(i)).getBlock() == this; ++i) { ; } if (i < 3) { int j = ((Integer) iblockdata.get(BlockCactus.AGE)).intValue(); if (j >= (byte) range(3, (world.growthOdds / world.spigotConfig.cactusModifier * 15) + 0.5F, 15)) { // Spigot // world.setTypeUpdate(blockposition1, this.getBlockData()); // CraftBukkit IBlockData iblockdata1 = iblockdata.set(BlockCactus.AGE, Integer.valueOf(0)); CraftEventFactory.handleBlockGrowEvent(world, blockposition1.getX(), blockposition1.getY(), blockposition1.getZ(), this, 0); // CraftBukkit world.setTypeAndData(blockposition, iblockdata1, 4); this.doPhysics(world, blockposition1, iblockdata1, this); } else { world.setTypeAndData(blockposition, iblockdata.set(BlockCactus.AGE, Integer.valueOf(j + 1)), 4); } } } } public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { float f = 0.0625F; return new AxisAlignedBB((double) ((float) blockposition.getX() + f), (double) blockposition.getY(), (double) ((float) blockposition.getZ() + f), (double) ((float) (blockposition.getX() + 1) - f), (double) ((float) (blockposition.getY() + 1) - f), (double) ((float) (blockposition.getZ() + 1) - f)); } public boolean d() { return false; } public boolean c() { return false; } public boolean canPlace(World world, BlockPosition blockposition) { return super.canPlace(world, blockposition) ? this.e(world, blockposition) : false; } public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { if (!this.e(world, blockposition)) { world.setAir(blockposition, true); } } public boolean e(World world, BlockPosition blockposition) { Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); while (iterator.hasNext()) { EnumDirection enumdirection = (EnumDirection) iterator.next(); if (world.getType(blockposition.shift(enumdirection)).getBlock().getMaterial().isBuildable()) { return false; } } Block block = world.getType(blockposition.down()).getBlock(); return block == Blocks.CACTUS || block == Blocks.SAND; } public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { CraftEventFactory.blockDamage = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); // CraftBukkit entity.damageEntity(DamageSource.CACTUS, 1.0F); CraftEventFactory.blockDamage = null; // CraftBukkit } public IBlockData fromLegacyData(int i) { return this.getBlockData().set(BlockCactus.AGE, Integer.valueOf(i)); } public int toLegacyData(IBlockData iblockdata) { return ((Integer) iblockdata.get(BlockCactus.AGE)).intValue(); } protected BlockStateList getStateList() { return new BlockStateList(this, new IBlockState[] { BlockCactus.AGE}); } }
gpl-3.0
lightspeeddevelopment/lsx
assets/js/src/lsx.js
17894
/** * LSX Scripts * * @package lsx * @subpackage scripts */ var lsx = Object.create(null); (function($, window, document, undefined) { "use strict"; var $document = $(document), $window = $(window), windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight, windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; /** * Adds browser class to html tag. * * @package lsx * @subpackage scripts */ lsx.add_class_browser_to_html = function() { if ("undefined" !== typeof platform) { var platform_name = "chrome"; if (null !== platform.name) { platform_name = platform.name.toLowerCase(); } var platform_version = "69"; if (null !== platform.version) { platform_version = platform.version.toLowerCase(); } $("html") .addClass(platform_name) .addClass(platform_version); } }; /** * Test if the sidebar exists (if exists, add a class to the body). * * @package lsx * @subpackage scripts */ lsx.add_class_sidebar_to_body = function() { if ($("#secondary").length > 0) { $("body").addClass("has-sidebar"); } }; /** * Add Bootstrap class to WordPress tables. * * @package lsx * @subpackage scripts */ lsx.add_class_bootstrap_to_table = function() { var tables = $("table#wp-calendar"); if (tables.length > 0) { tables.addClass("table"); } }; /** * Add a class to identify when the mobile nav is open * * @package lsx * @subpackage scripts */ lsx.navbar_toggle_handler = function() { $(".navbar-toggle") .parent() .on("click", function() { var $parent = $(this); $parent.toggleClass("open"); $("#masthead").toggleClass("masthead-open"); }); }; /** * Fix Bootstrap menus (touchstart). * * @package lsx * @subpackage scripts */ // lsx.fix_bootstrap_menus_touchstart = function() { // $( '.dropdown-menu' ).on( 'touchstart.dropdown.data-api', function( e ) { // e.stopPropagation(); // } ); // }; /** * Fix Bootstrap menus (dropdown). * * @package lsx * @subpackage scripts */ lsx.fix_bootstrap_menus_dropdown = function() { $(".navbar-nav .dropdown, #top-menu .dropdown").on( "show.bs.dropdown", function() { if (windowWidth < 1200) { $(this) .siblings(".open") .removeClass("open") .find("a.dropdown-toggle") .attr("data-toggle", "dropdown"); $(this) .find("a.dropdown-toggle") .removeAttr("data-toggle"); } } ); if (windowWidth > 1199) { $(".navbar-nav li.dropdown a, #top-menu li.dropdown a").each( function() { $(this).removeClass("dropdown-toggle"); $(this).removeAttr("data-toggle"); } ); } $window.resize(function() { if (windowWidth > 1199) { $(".navbar-nav li.dropdown a, #top-menu li.dropdown a").each( function() { $(this).removeClass("dropdown-toggle"); $(this).removeAttr("data-toggle"); } ); } else { $(".navbar-nav li.dropdown a, #top-menu li.dropdown a").each( function() { $(this).addClass("dropdown-toggle"); $(this).attr("data-toggle", "dropdown"); } ); } }); }; /** * Remove tabs classnames of WC and adding custom lsx classnames * * @package lsx * @subpackage scripts */ lsx.replace_wc_classnames = function() { $(".wc-tabs") .removeClass("wc-tabs") .addClass("nav-tabs"); $(".tabs") .removeClass("tabs") .addClass("nav wc-tabs"); }; /** * Fix Bootstrap menus (dropdown inside dropdown - click). * * @package lsx * @subpackage scripts */ lsx.fix_bootstrap_menus_dropdown_click = function() { if (windowWidth < 1200) { $( ".navbar-nav .dropdown .dropdown > a, #top-menu .dropdown .dropdown > a" ).on("click", function(e) { if ( !$(this) .parent() .hasClass("open") ) { $(this) .parent() .addClass("open"); $(this) .next(".dropdown-menu") .dropdown("toggle"); e.stopPropagation(); e.preventDefault(); } }); $( ".navbar-nav .dropdown .dropdown .dropdown-menu a, #top-menu .dropdown .dropdown > a" ).on("click", function(e) { document.location.href = this.href; }); } }; /** * Fix LazyLoad on Envira * * @package lsx * @subpackage scripts */ lsx.fix_lazyload_envira_gallery = function() { if ($(".lazyload, .lazyloaded").length > 0) { if (typeof envira_isotopes == "object") { $window.scroll(function() { $(".envira-gallery-wrap").each(function() { var id = $(this).attr("id"); id = id.replace("envira-gallery-wrap-", ""); if (typeof envira_isotopes[id] == "object") { envira_isotopes[id].enviratope("layout"); } }); }); } } }; /** * Fixed main menu. * * @package lsx * @subpackage scripts */ lsx.set_main_menu_as_fixed = function() { var is_loaded = false; if (windowWidth > 1199) { if ($("body").hasClass("top-menu-fixed")) { $document.on("scroll", function(e) { if (false === is_loaded) { $(lsx_params.stickyMenuSelector).scrollToFixed({ marginTop: function() { var wpadminbar = $("#wpadminbar"); if (wpadminbar.length > 0) { return wpadminbar.outerHeight(); } return 0; }, minWidth: 768, preFixed: function() { $(this).addClass("scrolled"); }, preUnfixed: function() { $(this).removeClass("scrolled"); } }); is_loaded = true; } }); } } }; /** * Cover template header height. * * @package lsx * @subpackage scripts */ lsx.set_cover_template_header_height = function() { var mastheadHeight = 0; if ( $("body").hasClass("page-template-template-cover") || $("body").hasClass("post-template-template-cover") ) { mastheadHeight = $("#masthead").outerHeight(); //console.log(mastheadHeight); $("#masthead").css("margin-bottom", -Math.abs(mastheadHeight)); } }; /** * Search form effect (on mobile). * * @package lsx * @subpackage scripts */ lsx.set_search_form_effect_mobile = function() { $document.on( "click", "header.navbar #searchform button.search-submit", function(e) { if (windowWidth < 1200) { e.preventDefault(); var form = $(this).closest("form"); if (form.hasClass("hover")) { form.submit(); } else { form.addClass("hover"); form.find(".search-field").focus(); } } } ); $document.on( "blur", "header.navbar #searchform .search-field", function(e) { if (windowWidth < 1200) { var form = $(this).closest("form"); form.removeClass("hover"); } } ); }; /** * Search form effect (on mobile). * * @package lsx * @subpackage scripts */ lsx.search_form_prevent_empty_submissions = function() { $document.on("submit", "#searchform", function(e) { if ( "" === $(this) .find('input[name="s"]') .val() ) { e.preventDefault(); } }); $document.on( "blur", "header.navbar #searchform .search-field", function(e) { if (windowWidth < 1200) { var form = $(this).closest("form"); form.removeClass("hover"); } } ); }; /** * Slider Lightbox. * * @package lsx * @subpackage scripts */ lsx.build_slider_lightbox = function() { $("body:not(.single-tour-operator) .gallery").slickLightbox({ caption: function(element, info) { return $(element) .find("img") .attr("alt"); } }); }; /** * Init WooCommerce slider. * * @package lsx * @subpackage scripts */ lsx.init_wc_slider = function() { var $wcSlider = $(".lsx-woocommerce-slider"); $wcSlider.each(function(index, el) { var $self = $(this), _slidesToShow = 4, _slidesToScroll = 4, _slidesToShow_992 = 3, _slidesToScroll_992 = 3, _slidesToShow_768 = 1, _slidesToScroll_768 = 1; if ($self.find(".lsx-woocommerce-review-slot").length > 0) { _slidesToShow = 2; _slidesToScroll = 2; _slidesToShow_992 = 2; _slidesToScroll_992 = 2; } if ($self.closest("#secondary").length > 0) { _slidesToShow = 1; _slidesToScroll = 1; _slidesToShow_992 = 1; _slidesToScroll_992 = 1; } $self.on("init", function(event, slick) { if ( slick.options.arrows && slick.slideCount > slick.options.slidesToShow ) { $self.addClass("slick-has-arrows"); } }); $self.on("setPosition", function(event, slick) { if (!slick.options.arrows) { $self.removeClass("slick-has-arrows"); } else if (slick.slideCount > slick.options.slidesToShow) { $self.addClass("slick-has-arrows"); } }); $self.slick({ draggable: false, infinite: true, swipe: false, cssEase: "ease-out", dots: true, slidesToShow: _slidesToShow, slidesToScroll: _slidesToScroll, responsive: [ { breakpoint: 992, settings: { slidesToShow: _slidesToShow_992, slidesToScroll: _slidesToScroll_992, draggable: true, arrows: false, swipe: true } }, { breakpoint: 768, settings: { slidesToShow: _slidesToShow_768, slidesToScroll: _slidesToScroll_768, draggable: true, arrows: false, swipe: true } } ] }); }); if ($('a[href="#tab-bundled_products"]').length > 0) { $document.on("click", 'a[href="#tab-bundled_products"]', function( e ) { $("#tab-bundled_products .lsx-woocommerce-slider").slick( "setPosition" ); }); } }; /** * Remove gallery IMG width and height. * * @package lsx * @subpackage scripts */ lsx.remove_gallery_img_width_height = function() { $(".gallery-size-full img").each(function() { var $self = $(this); $self.removeAttr("height"); $self.removeAttr("width"); }); }; /** * Helper function to scroll to an element. * * @package lsx * @subpackage scripts */ lsx.do_scroll = function(_$el) { var _href = _$el.href.replace(/^[^#]*(#.+$)/gi, "$1"), _$to = $(_href), _top = parseInt(_$to.offset().top), _extra = -100; $("html, body").animate( { scrollTop: _top + _extra }, 800 ); }; /** * Fix WooCommerce API orders style/HTML. * Fix WooCommerce checkboxes style/HTML. * * @package lsx * @subpackage scripts */ lsx.fix_wc_elements = function(_$el) { $( ".woocommerce-MyAccount-content .api-manager-changelog, .woocommerce-MyAccount-content .api-manager-download" ).each(function() { var $this = $(this); $this.children("br:first-child").remove(); $this.children("hr:first-child").remove(); $this.children("hr:last-child").remove(); $this.children("br:last-child").remove(); }); $(".woocommerce-form__label-for-checkbox.checkbox").removeClass( "checkbox" ); $(document.body).on("updated_checkout", function() { $(".woocommerce-form__label-for-checkbox.checkbox").removeClass( "checkbox" ); }); }; /** * Fix Caldera Forms modal title. * * @package lsx * @subpackage scripts */ lsx.fix_caldera_form_modal_title = function() { $("[data-remodal-id]").each(function() { var $form = $(this), $button = $('[data-remodal-target="' + $form.attr("id") + '"]'), title = $button.text(); $form .find('[role="field"]') .first() .before("<div><h4>" + title + "</h4></div>"); }); }; /** * Open/close WC footer bar search. * * @package lsx * @subpackage scripts */ lsx.wc_footer_bar_toggle_handler = function() { $(".lsx-wc-footer-bar-link-toogle").on("click", function(event) { event.preventDefault(); $(".lsx-wc-footer-bar-form").slideToggle(); $(".lsx-wc-footer-bar").toggleClass("lsx-wc-footer-bar-search-on"); }); }; /** * Fix WC messages/notices visual. * * @package lsx * @subpackage scripts */ lsx.wc_fix_messages_visual = function() { $( ".woocommerce-message," + ".woocommerce-info:not(.wc_points_redeem_earn_points, .wc_points_rewards_earn_points)," + ".woocommerce-error," + ".woocommerce-noreviews," + ".woocommerce_message," + ".woocommerce_info:not(.wc_points_redeem_earn_points, .wc_points_rewards_earn_points)," + ".woocommerce_error," + ".woocommerce_noreviews," + "p.no-comments," + ".stock," + ".woocommerce-password-strength" ).each(function() { var _$this = $(this); if (0 === _$this.find(".button").length) { return; } _$this.wrapInner( '<div class="lsx-woocommerce-message-text"></div>' ); _$this.addClass("lsx-woocommerce-message-wrap"); _$this.find(".button").appendTo(_$this); }); }; /** * Fix WC subscrive to replies checkbox visual. * * @package lsx * @subpackage scripts */ lsx.wc_fix_subscribe_to_replies_checkbox = function() { $('input[name="subscribe_to_replies"]').removeClass("form-control"); }; /** * Add to the WC Quick View modal the close button. * * @package lsx * @subpackage scripts */ lsx.wc_add_quick_view_close_button = function() { $("body").on("quick-view-displayed", function(event) { if (0 === $(".pp_content_container").children(".close").length) { $(".pp_content_container").prepend( '<button type="button" class="close">&times;</button>' ); } }); $document.on("click", ".pp_content_container .close", function(e) { $.prettyPhoto.close(); }); }; /** * Fix WC subscriptions empty message. * * @package lsx * @subpackage scripts */ lsx.wc_fix_subscriptions_empty_message = function() { if ("" === $(".first-payment-date").text()) { $(".first-payment-date").remove(); } }; /** * Check if a courses thumbnail is empty on the archive page. * * @package lsx * @subpackage scripts */ lsx.sensei_courses_empty_thumbnail = function() { $(".course-thumbnail").each(function() { if (!$.trim($(this).html()).length) { $(this).addClass("course-thumbnail-empty"); } }); }; lsx.sensei_course_participants_widget_more = function() { if ($("body").hasClass("sensei")) { $(".sensei-course-participant").each(function() { if ($(this).hasClass("show")) { $(this).addClass("sensei-show"); $(this).removeClass("show"); } if ($(this).hasClass("hide")) { $(this).addClass("sensei-hide"); $(this).removeClass("hide"); } }); $(".sensei-view-all-participants a").on("click", function() { if ($(this).hasClass("clicked")) { $(this).removeClass("clicked"); } else { $(this).addClass("clicked"); } $(".sensei-course-participant.sensei-hide").each(function() { if ($(this).hasClass("sensei-clicked")) { $(this).removeClass("sensei-clicked"); } else { $(this).addClass("sensei-clicked"); } }); }); } }; lsx.detect_has_link_block = function() { $(".has-link-color").each(function() { $(this) .find("a") .each(function() { $(this).addClass("has-link-anchor"); }); }); }; //Toggle for woocommerce block filters. lsx.woocommerce_filters_mobile = function() { if ($("body").hasClass("woocommerce-js")) { $(".lsx-wc-filter-toggle").on("click", function() { $(this).toggleClass("lsx-wc-filter-toggle-open"); if ($(this).hasClass("lsx-wc-filter-toggle-open")) { $( '.lsx-wc-filter-block div[class^="wp-block-woocommerce-"][class$="-filter"]' ).each(function() { $(this).attr("id", "lsx-wc-filter-child-open"); }); $( ".lsx-wc-filter-block .wp-block-woocommerce-product-search" ).each(function() { $(this).attr("id", "lsx-wc-filter-child-open"); }); } else { $( '.lsx-wc-filter-block div[class^="wp-block-woocommerce-"][class$="-filter"]' ).each(function() { $(this).attr("id", "lsx-wc-filter-child-close"); }); $( ".lsx-wc-filter-block .wp-block-woocommerce-product-search" ).each(function() { $(this).attr("id", "lsx-wc-filter-child-close"); }); } }); } }; /** * On window resize. * * @package lsx * @subpackage scripts */ $window.resize(function() { windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; }); /** * On document ready. * * @package lsx * @subpackage scripts */ $document.ready(function() { lsx.navbar_toggle_handler(); // lsx.fix_bootstrap_menus_touchstart(); lsx.add_class_browser_to_html(); lsx.add_class_sidebar_to_body(); lsx.add_class_bootstrap_to_table(); lsx.set_main_menu_as_fixed(); lsx.search_form_prevent_empty_submissions(); lsx.remove_gallery_img_width_height(); lsx.replace_wc_classnames(); lsx.init_wc_slider(); lsx.fix_wc_elements(); lsx.fix_caldera_form_modal_title(); lsx.wc_footer_bar_toggle_handler(); lsx.wc_fix_messages_visual(); lsx.wc_fix_subscribe_to_replies_checkbox(); lsx.wc_add_quick_view_close_button(); lsx.wc_fix_subscriptions_empty_message(); lsx.sensei_courses_empty_thumbnail(); lsx.sensei_course_participants_widget_more(); lsx.woocommerce_filters_mobile(); lsx.detect_has_link_block(); }); /** * On window load. * * @package lsx * @subpackage scripts */ $(window).on('load', function () { lsx.fix_bootstrap_menus_dropdown(); lsx.fix_bootstrap_menus_dropdown_click(); lsx.fix_lazyload_envira_gallery(); lsx.set_search_form_effect_mobile(); lsx.build_slider_lightbox(); lsx.set_cover_template_header_height(); /* LAST CODE TO EXECUTE */ $("body.preloader-content-enable").addClass("html-loaded"); }); })(jQuery, window, document);
gpl-3.0
EyeSeeTea/dhis2
dhis-2/dhis-api/src/main/java/org/hisp/dhis/dataset/LockExceptionStore.java
2345
package org.hisp.dhis.dataset; /* * Copyright (c) 2004-2016, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.util.List; import org.hisp.dhis.common.GenericStore; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.period.Period; /** * @author Morten Olav Hansen <mortenoh@gmail.com> */ public interface LockExceptionStore extends GenericStore<LockException> { String ID = LockExceptionStore.class.getName(); List<LockException> getAllOrderedName( int first, int max ); List<LockException> getCombinations(); void deleteCombination( DataSet dataSet, Period period ); long getCount( DataElement dataElement, Period period, OrganisationUnit organisationUnit ); long getCount( DataSet dataSet, Period period, OrganisationUnit organisationUnit ); }
gpl-3.0
vith/qTox
src/widget/tool/screenshotgrabber.cpp
7832
/* Copyright © 2015 by The qTox Project This file is part of qTox, a Qt-based graphical interface for Tox. qTox is libre 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. qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>. */ #include "screenshotgrabber.h" #include <QApplication> #include <QDebug> #include <QDesktopWidget> #include <QGraphicsPixmapItem> #include <QGraphicsRectItem> #include <QGraphicsSceneMouseEvent> #include <QGraphicsView> #include <QMouseEvent> #include <QScreen> #include <QTimer> #include "screengrabberchooserrectitem.h" #include "screengrabberoverlayitem.h" #include "toolboxgraphicsitem.h" #include "src/widget/widget.h" ScreenshotGrabber::ScreenshotGrabber(QObject* parent) : QObject(parent) , mKeysBlocked(false) , scene(0) , mQToxVisible(true) { window = new QGraphicsView (scene); // Top-level widget window->setAttribute(Qt::WA_DeleteOnClose); window->setWindowFlags(Qt::FramelessWindowHint | Qt::BypassWindowManagerHint); window->setContentsMargins(0, 0, 0, 0); window->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); window->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); window->setFrameShape(QFrame::NoFrame); window->installEventFilter(this); #if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)) pixRatio = QApplication::primaryScreen()->devicePixelRatio(); #endif // Scale window down by devicePixelRatio to show full screen region window->scale(1 / pixRatio, 1 / pixRatio); setupScene(); } void ScreenshotGrabber::reInit() { window->resetCachedContent(); setupScene(); showGrabber(); mKeysBlocked = false; } ScreenshotGrabber::~ScreenshotGrabber() { delete scene; } bool ScreenshotGrabber::eventFilter(QObject* object, QEvent* event) { if (event->type() == QEvent::KeyPress) return handleKeyPress(static_cast<QKeyEvent*>(event)); return QObject::eventFilter(object, event); } void ScreenshotGrabber::showGrabber() { this->screenGrab = grabScreen(); this->screenGrabDisplay->setPixmap(this->screenGrab); this->window->show(); this->window->setFocus(); this->window->grabKeyboard(); QRect fullGrabbedRect = screenGrab.rect(); QRect rec = QApplication::primaryScreen()->virtualGeometry(); this->window->setGeometry(rec); this->scene->setSceneRect(fullGrabbedRect); this->overlay->setRect(fullGrabbedRect); adjustTooltipPosition(); } bool ScreenshotGrabber::handleKeyPress(QKeyEvent* event) { if (mKeysBlocked) return false; if (event->key() == Qt::Key_Escape) reject(); else if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) acceptRegion(); else if (event->key() == Qt::Key_Space) { mKeysBlocked = true; if (mQToxVisible) hideVisibleWindows(); else restoreHiddenWindows(); window->hide(); QTimer::singleShot(350, this, SLOT(reInit())); } else return false; return true; } void ScreenshotGrabber::acceptRegion() { QRect rect = this->chooserRect->chosenRect(); if (rect.width() < 1 || rect.height() < 1) return; qDebug() << "Screenshot accepted, chosen region" << rect; emit screenshotTaken(this->screenGrab.copy(rect)); this->window->close(); restoreHiddenWindows(); } void ScreenshotGrabber::setupScene() { delete scene; scene = new QGraphicsScene; window->setScene(scene); this->overlay = new ScreenGrabberOverlayItem(this); this->helperToolbox = new ToolBoxGraphicsItem; this->screenGrabDisplay = scene->addPixmap(this->screenGrab); this->helperTooltip = scene->addText(QString()); // Scale UI elements up by devicePixelRatio to compensate for window downscaling this->helperToolbox->setScale(pixRatio); this->helperTooltip->setScale(pixRatio); scene->addItem(this->overlay); this->chooserRect = new ScreenGrabberChooserRectItem(scene); scene->addItem(this->helperToolbox); this->helperToolbox->addToGroup(this->helperTooltip); this->helperTooltip->setDefaultTextColor(Qt::black); useNothingSelectedTooltip(); connect(this->chooserRect, &ScreenGrabberChooserRectItem::doubleClicked, this, &ScreenshotGrabber::acceptRegion); connect(this->chooserRect, &ScreenGrabberChooserRectItem::regionChosen, this, &ScreenshotGrabber::chooseHelperTooltipText); connect(this->chooserRect, &ScreenGrabberChooserRectItem::regionChosen, this->overlay, &ScreenGrabberOverlayItem::setChosenRect); } void ScreenshotGrabber::useNothingSelectedTooltip() { helperTooltip->setHtml(tr("Click and drag to select a region. Press <b>Space</b> to hide/show qTox window, or <b>Escape</b> to cancel.", "Help text shown when no region has been selected yet")); adjustTooltipPosition(); } void ScreenshotGrabber::useRegionSelectedTooltip() { helperTooltip->setHtml(tr("Press <b>Enter</b> to send a screenshot of the selection, <b>Space</b> to hide/show qTox window, or <b>Escape</b> to cancel.", "Help text shown when a region has been selected")); adjustTooltipPosition(); } void ScreenshotGrabber::chooseHelperTooltipText(QRect rect) { if (rect.size().isNull()) useNothingSelectedTooltip(); else useRegionSelectedTooltip(); } /** * @internal * * Align the tooltip centred at top of screen with the mouse cursor. */ void ScreenshotGrabber::adjustTooltipPosition() { QRect recGL = QGuiApplication::primaryScreen()->virtualGeometry(); QRect rec = qApp->desktop()->screenGeometry(QCursor::pos()); const QRectF ttRect = this->helperToolbox->childrenBoundingRect(); int x = abs(recGL.x()) + rec.x() + ((rec.width() - ttRect.width()) / 2); int y = abs(recGL.y()) + rec.y(); // Multiply by devicePixelRatio to get centered positions under scaling helperToolbox->setX(x * pixRatio); helperToolbox->setY(y * pixRatio); } void ScreenshotGrabber::reject() { qDebug() << "Rejected screenshot"; this->window->close(); restoreHiddenWindows(); } QPixmap ScreenshotGrabber::grabScreen() { QScreen* screen = QGuiApplication::primaryScreen(); QRect rec = screen->virtualGeometry(); // Multiply by devicePixelRatio to get actual desktop size return screen->grabWindow(QApplication::desktop()->winId(), rec.x() * pixRatio, rec.y() * pixRatio, rec.width() * pixRatio, rec.height() * pixRatio); } void ScreenshotGrabber::hideVisibleWindows() { foreach(QWidget* w, qApp->topLevelWidgets()) { if (w != window && w->isVisible()) { mHiddenWindows << w; w->setVisible(false); } } mQToxVisible = false; } void ScreenshotGrabber::restoreHiddenWindows() { foreach(QWidget* w, mHiddenWindows) { if (w) w->setVisible(true); } mHiddenWindows.clear(); mQToxVisible = true; } void ScreenshotGrabber::beginRectChooser(QGraphicsSceneMouseEvent* event) { QPointF pos = event->scenePos(); this->chooserRect->setX(pos.x()); this->chooserRect->setY(pos.y()); this->chooserRect->beginResize(event->scenePos()); }
gpl-3.0
causefx/Organizr
api/vendor/slim/psr7/src/Stream.php
9195
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim-Psr7/blob/master/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Psr7; use InvalidArgumentException; use Psr\Http\Message\StreamInterface; use RuntimeException; use function fclose; use function feof; use function fread; use function fseek; use function fstat; use function ftell; use function fwrite; use function is_array; use function is_resource; use function is_string; use function pclose; use function rewind; use function stream_get_contents; use function stream_get_meta_data; use function strstr; use const SEEK_SET; class Stream implements StreamInterface { /** * Bit mask to determine if the stream is a pipe * * This is octal as per header stat.h */ public const FSTAT_MODE_S_IFIFO = 0010000; /** * The underlying stream resource * * @var resource|null */ protected $stream; /** * @var array|null */ protected $meta; /** * @var bool|null */ protected $readable; /** * @var bool|null */ protected $writable; /** * @var bool|null */ protected $seekable; /** * @var null|int */ protected $size; /** * @var bool|null */ protected $isPipe; /** * @var bool */ protected $finished = false; /** * @var StreamInterface | null */ protected $cache; /** * @param resource $stream A PHP resource handle. * @param StreamInterface $cache A stream to cache $stream (useful for non-seekable streams) * * @throws InvalidArgumentException If argument is not a resource. */ public function __construct($stream, StreamInterface $cache = null) { $this->attach($stream); if ($cache && (!$cache->isSeekable() || !$cache->isWritable())) { throw new RuntimeException('Cache stream must be seekable and writable'); } $this->cache = $cache; } /** * {@inheritdoc} */ public function getMetadata($key = null) { if (!$this->stream) { return null; } $this->meta = stream_get_meta_data($this->stream); if (!$key) { return $this->meta; } return isset($this->meta[$key]) ? $this->meta[$key] : null; } /** * Attach new resource to this object. * * @internal This method is not part of the PSR-7 standard. * * @param resource $stream A PHP resource handle. * * @throws InvalidArgumentException If argument is not a valid PHP resource. * * @return void */ protected function attach($stream): void { if (!is_resource($stream)) { throw new InvalidArgumentException(__METHOD__ . ' argument must be a valid PHP resource'); } if ($this->stream) { $this->detach(); } $this->stream = $stream; } /** * {@inheritdoc} */ public function detach() { $oldResource = $this->stream; $this->stream = null; $this->meta = null; $this->readable = null; $this->writable = null; $this->seekable = null; $this->size = null; $this->isPipe = null; $this->cache = null; $this->finished = false; return $oldResource; } /** * {@inheritdoc} */ public function __toString(): string { if (!$this->stream) { return ''; } if ($this->cache && $this->finished) { $this->cache->rewind(); return $this->cache->getContents(); } if ($this->isSeekable()) { $this->rewind(); } return $this->getContents(); } /** * {@inheritdoc} */ public function close(): void { if ($this->stream) { if ($this->isPipe()) { pclose($this->stream); } else { fclose($this->stream); } } $this->detach(); } /** * {@inheritdoc} */ public function getSize(): ?int { if ($this->stream && !$this->size) { $stats = fstat($this->stream); if ($stats) { $this->size = isset($stats['size']) && !$this->isPipe() ? $stats['size'] : null; } } return $this->size; } /** * {@inheritdoc} */ public function tell(): int { $position = false; if ($this->stream) { $position = ftell($this->stream); } if ($position === false || $this->isPipe()) { throw new RuntimeException('Could not get the position of the pointer in stream.'); } return $position; } /** * {@inheritdoc} */ public function eof(): bool { return $this->stream ? feof($this->stream) : true; } /** * {@inheritdoc} */ public function isReadable(): bool { if ($this->readable === null) { if ($this->isPipe()) { $this->readable = true; } else { $this->readable = false; if ($this->stream) { $mode = $this->getMetadata('mode'); if (strstr($mode, 'r') !== false || strstr($mode, '+') !== false) { $this->readable = true; } } } } return $this->readable; } /** * {@inheritdoc} */ public function isWritable(): bool { if ($this->writable === null) { $this->writable = false; if ($this->stream) { $mode = $this->getMetadata('mode'); if (strstr($mode, 'w') !== false || strstr($mode, '+') !== false) { $this->writable = true; } } } return $this->writable; } /** * {@inheritdoc} */ public function isSeekable(): bool { if ($this->seekable === null) { $this->seekable = false; if ($this->stream) { $this->seekable = !$this->isPipe() && $this->getMetadata('seekable'); } } return $this->seekable; } /** * {@inheritdoc} */ public function seek($offset, $whence = SEEK_SET): void { if (!$this->isSeekable() || $this->stream && fseek($this->stream, $offset, $whence) === -1) { throw new RuntimeException('Could not seek in stream.'); } } /** * {@inheritdoc} */ public function rewind(): void { if (!$this->isSeekable() || $this->stream && rewind($this->stream) === false) { throw new RuntimeException('Could not rewind stream.'); } } /** * {@inheritdoc} */ public function read($length): string { $data = false; if ($this->isReadable() && $this->stream) { $data = fread($this->stream, $length); } if (is_string($data)) { if ($this->cache) { $this->cache->write($data); } if ($this->eof()) { $this->finished = true; } return $data; } throw new RuntimeException('Could not read from stream.'); } /** * {@inheritdoc} */ public function write($string) { $written = false; if ($this->isWritable() && $this->stream) { $written = fwrite($this->stream, $string); } if ($written !== false) { $this->size = null; return $written; } throw new RuntimeException('Could not write to stream.'); } /** * {@inheritdoc} */ public function getContents(): string { if ($this->cache && $this->finished) { $this->cache->rewind(); return $this->cache->getContents(); } $contents = false; if ($this->stream) { $contents = stream_get_contents($this->stream); } if (is_string($contents)) { if ($this->cache) { $this->cache->write($contents); } if ($this->eof()) { $this->finished = true; } return $contents; } throw new RuntimeException('Could not get contents of stream.'); } /** * Returns whether or not the stream is a pipe. * * @internal This method is not part of the PSR-7 standard. * * @return bool */ public function isPipe(): bool { if ($this->isPipe === null) { $this->isPipe = false; if ($this->stream) { $stats = fstat($this->stream); if (is_array($stats)) { $this->isPipe = isset($stats['mode']) && ($stats['mode'] & self::FSTAT_MODE_S_IFIFO) !== 0; } } } return $this->isPipe; } }
gpl-3.0
StevenLOL/aicyber_semeval_2016_ivector
System_2/utils/nnet/make_blstm_proto.py
3554
#!/usr/bin/env python # Copyright 2015 Brno University of Technology (author: Karel Vesely) # 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 # # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED # WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, # MERCHANTABLITY OR NON-INFRINGEMENT. # See the Apache 2 License for the specific language governing permissions and # limitations under the License. # Generated Nnet prototype, to be initialized by 'nnet-initialize'. import sys ### ### Parse options ### from optparse import OptionParser usage="%prog [options] <feat-dim> <num-leaves> >nnet-proto-file" parser = OptionParser(usage) # parser.add_option('--num-cells', dest='num_cells', type='int', default=800, help='Number of LSTM cells [default: %default]'); parser.add_option('--num-recurrent', dest='num_recurrent', type='int', default=512, help='Number of LSTM recurrent units [default: %default]'); parser.add_option('--num-layers', dest='num_layers', type='int', default=2, help='Number of LSTM layers [default: %default]'); parser.add_option('--lstm-stddev-factor', dest='lstm_stddev_factor', type='float', default=0.01, help='Standard deviation of initialization [default: %default]'); parser.add_option('--param-stddev-factor', dest='param_stddev_factor', type='float', default=0.04, help='Standard deviation in output layer [default: %default]'); parser.add_option('--clip-gradient', dest='clip_gradient', type='float', default=5.0, help='Clipping constant applied to gradients [default: %default]'); # (o,args) = parser.parse_args() if len(args) != 2 : parser.print_help() sys.exit(1) (feat_dim, num_leaves) = map(int,args); # Original prototype from Jiayu, #<NnetProto> #<Transmit> <InputDim> 40 <OutputDim> 40 #<LstmProjectedStreams> <InputDim> 40 <OutputDim> 512 <CellDim> 800 <ParamScale> 0.01 <NumStream> 4 #<AffineTransform> <InputDim> 512 <OutputDim> 8000 <BiasMean> 0.000000 <BiasRange> 0.000000 <ParamStddev> 0.04 #<Softmax> <InputDim> 8000 <OutputDim> 8000 #</NnetProto> print "<NnetProto>" # normally we won't use more than 2 layers of LSTM if o.num_layers == 1: print "<BLstmProjectedStreams> <InputDim> %d <OutputDim> %d <CellDim> %s <ParamScale> %f <ClipGradient> %f" % \ (feat_dim, 2*o.num_recurrent, o.num_cells, o.lstm_stddev_factor, o.clip_gradient) elif o.num_layers == 2: print "<BLstmProjectedStreams> <InputDim> %d <OutputDim> %d <CellDim> %s <ParamScale> %f <ClipGradient> %f" % \ (feat_dim, 2*o.num_recurrent, o.num_cells, o.lstm_stddev_factor, o.clip_gradient) print "<BLstmProjectedStreams> <InputDim> %d <OutputDim> %d <CellDim> %s <ParamScale> %f <ClipGradient> %f" % \ (2*o.num_recurrent, 2*o.num_recurrent, o.num_cells, o.lstm_stddev_factor, o.clip_gradient) else: sys.stderr.write("make_lstm_proto.py ERROR: more than 2 layers of LSTM, not supported yet.\n") sys.exit(1) print "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> 0.0 <BiasRange> 0.0 <ParamStddev> %f" % \ (2*o.num_recurrent, num_leaves, o.param_stddev_factor) print "<Softmax> <InputDim> %d <OutputDim> %d" % \ (num_leaves, num_leaves) print "</NnetProto>"
gpl-3.0
trezor/trezor-emu
trezor/transport_socket.py
3665
'''SocketTransport implements TCP socket interface for Transport.''' import socket from select import select from transport import Transport class FakeRead(object): # Because socket is the only transport which don't implement read() def __init__(self, socket): self.socket = socket def read(self, size): return self.socket.recv(size) class SocketTransportClient(Transport): def __init__(self, device, *args, **kwargs): device = device.split(':') if len(device) < 2: device = ('0.0.0.0', int(device[0])) else: device = (device[0], int(device[1])) self.socket = None super(SocketTransportClient, self).__init__(device, *args, **kwargs) def _open(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect(self.device) self.filelike = self.socket.makefile() def _close(self): self.socket.close() self.socket = None self.filelike = None def ready_to_read(self): rlist, _, _ = select([self.socket], [], [], 0) return len(rlist) > 0 def _write(self, msg): self.socket.sendall(msg) def _read(self): try: (msg_type, datalen) = self._read_headers(self.filelike) return (msg_type, self.filelike.read(datalen)) except socket.error: print "Failed to read from device" return None class SocketTransport(Transport): def __init__(self, device, *args, **kwargs): device = device.split(':') if len(device) < 2: device = ('0.0.0.0', int(device[0])) else: device = (device[0], int(device[1])) self.socket = None self.client = None self.filelike = None super(SocketTransport, self).__init__(device, *args, **kwargs) def _open(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #self.socket.setblocking(0) self.socket.bind(self.device) self.socket.listen(5) def _disconnect_client(self): print "Disconnecting client" if self.client is not None: self.client.close() self.client = None self.filelike = None def _close(self): self._disconnect_client() self.socket.close() self.socket = None def ready_to_read(self): if self.filelike: # Connected rlist, _, _ = select([self.client], [], [], 0) return len(rlist) > 0 else: # Waiting for connection rlist, _, _ = select([self.socket], [], [], 0) if len(rlist) > 0: (self.client, ipaddr) = self.socket.accept() print "Connected", ipaddr[0] self.filelike = self.client.makefile() # FakeRead(self.client) # self.client.makefile() return self.ready_to_read() return False def _write(self, msg): if self.filelike: # None on disconnected client try: self.filelike.write(msg) self.filelike.flush() except socket.error: print "Socket error" self._disconnect_client() def _read(self): try: (msg_type, datalen) = self._read_headers(self.filelike) return msg_type, self.filelike.read(datalen) except Exception: print "Failed to read from device" self._disconnect_client() return None
gpl-3.0
natuan241/twidere
src/org/mariotaku/twidere/loader/support/StatusConversationLoader.java
2605
/* * Twidere - Twitter client for Android * * Copyright (C) 2012-2014 Mariotaku Lee <mariotaku.lee@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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.mariotaku.twidere.loader.support; import static org.mariotaku.twidere.util.Utils.isOfficialConsumerKeySecret; import static org.mariotaku.twidere.util.Utils.shouldForceUsingPrivateAPIs; import android.content.Context; import org.mariotaku.twidere.model.ParcelableStatus; import twitter4j.Paging; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.auth.Authorization; import twitter4j.auth.OAuthAuthorization; import twitter4j.auth.XAuthAuthorization; import twitter4j.conf.Configuration; import java.util.Collections; import java.util.List; public class StatusConversationLoader extends UserMentionsLoader { private final long mInReplyToStatusId; public StatusConversationLoader(final Context context, final long accountId, final String screenName, final long statusId, final long maxId, final long sinceId, final List<ParcelableStatus> data, final String[] savedStatusesArgs, final int tabPosition) { super(context, accountId, screenName, maxId, sinceId, data, savedStatusesArgs, tabPosition); mInReplyToStatusId = statusId; } @Override public List<Status> getStatuses(final Twitter twitter, final Paging paging) throws TwitterException { final Context context = getContext(); final Configuration conf = twitter.getConfiguration(); final Authorization auth = twitter.getAuthorization(); final boolean isOAuth = auth instanceof OAuthAuthorization || auth instanceof XAuthAuthorization; final String consumerKey = conf.getOAuthConsumerKey(), consumerSecret = conf.getOAuthConsumerSecret(); if (shouldForceUsingPrivateAPIs(context) || isOAuth && isOfficialConsumerKeySecret(context, consumerKey, consumerSecret)) return twitter.showConversation(mInReplyToStatusId, paging); return Collections.emptyList(); } }
gpl-3.0
Abitim/signcrypt-projects
signcrypt-common/Digital signature/src/main/java/net/sf/dsig/verify/KeyUsageHelper.java
2845
/* * Copyright 2007-2014 Anestis Georgiadis * * 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 net.sf.dsig.verify; import java.security.cert.X509Certificate; /** * * @author <a href="mailto:mranest@iname.com">Anestis Georgiadis</a> */ public class KeyUsageHelper { public static final String[] KEY_USAGE = { "DigitalSignature", "NonRepudiation", "KeyEncipherment", "DataEncipherment", "KeyAgreement", "KeyCertSign", "CRLSign", "EncipherOnly", "DecipherOnly" }; public static String getKeyUsageByValue(int pos) { return KEY_USAGE[pos]; } public static int getValueByKeyUsage(String keyUsage) { for (int i=0; i<KEY_USAGE.length; i++) { if (KEY_USAGE[i].equals(keyUsage)) { return i; } } return -1; } /** * * @param certificate * @param keyUsageRestrictions * @return */ public static boolean validateKeyUsage( X509Certificate certificate, String keyUsageRestrictions) { String[] purposes = keyUsageRestrictions.split(","); for (int i=0; i<purposes.length; i++) { String keyUsage = purposes[i].trim(); int pos = getValueByKeyUsage(keyUsage); if (pos == -1) { throw new UnsupportedOperationException( "Unsupported key usage restriction; purpose=" + keyUsage); } if ( certificate.getKeyUsage() == null || !certificate.getKeyUsage()[pos]) { return false; } } return true; } public static String printKeyUsage(X509Certificate certificate) { StringBuffer sb = new StringBuffer(); boolean[] keyUsageBitmap = certificate.getKeyUsage(); if (keyUsageBitmap == null) { return "(No key usage set)"; } for (int i=0; i<keyUsageBitmap.length; i++) { if (keyUsageBitmap[i]) { if (sb.length() > 0) { sb.append(", "); } sb.append(getKeyUsageByValue(i)); } } return sb.toString(); } }
gpl-3.0
gpoulet/moodle
theme/shoehorn/tests/corerenderer_test.php
2590
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Shoehorn theme. * * @package theme * @subpackage shoehorn * @copyright &copy; 2015-onwards G J Barnard in respect to modifications of the Bootstrap theme. * @author G J Barnard - gjbarnard at gmail dot com and {@link http://moodle.org/user/profile.php?id=442195} * @author Based on code originally written by Bas Brands, David Scotson and many other contributors. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ /** * Core renderer unit tests for the Shoehorn theme. * @group theme_shoehorn */ class theme_shoehorn_corerenderer_testcase extends advanced_testcase { protected $outputus; protected function setUp() { set_config('textcolour', '#00ff00', 'theme_shoehorn'); set_config('logo', '/test.jpg', 'theme_shoehorn'); $this->resetAfterTest(true); global $PAGE; $this->outputus = $PAGE->get_renderer('theme_shoehorn', 'core'); \theme_shoehorn\toolbox::set_core_renderer($this->outputus); } public function test_version() { $ourversion = \theme_shoehorn\toolbox::get_setting('version'); $coretheme = \theme_config::load('shoehorn'); $this->assertEquals($coretheme->settings->version, $ourversion); } public function test_textcolour() { $ourcolour = \theme_shoehorn\toolbox::get_setting('textcolour'); $this->assertEquals('#00ff00', $ourcolour); } public function test_logo() { $ourlogo = \theme_shoehorn\toolbox::setting_file_url('logo', 'logo'); $this->assertEquals('//www.example.com/moodle/pluginfile.php/1/theme_shoehorn/logo/1/test.jpg', $ourlogo); } public function test_pix() { $ouricon = \theme_shoehorn\toolbox::pix_url('icon', 'theme'); $this->assertEquals('http://www.example.com/moodle/theme/image.php/_s/shoehorn/theme/1/icon', $ouricon->out(false)); } }
gpl-3.0
metasfresh/metasfresh-webui-api
src/main/java/de/metas/ui/web/view/descriptor/SqlViewRowFieldBinding.java
3131
package de.metas.ui.web.view.descriptor; import java.sql.ResultSet; import java.sql.SQLException; import javax.annotation.Nullable; import de.metas.ui.web.window.descriptor.DocumentFieldWidgetType; import de.metas.ui.web.window.descriptor.sql.SqlEntityFieldBinding; import de.metas.ui.web.window.descriptor.sql.SqlOrderByValue; import de.metas.ui.web.window.descriptor.sql.SqlSelectDisplayValue; import de.metas.ui.web.window.descriptor.sql.SqlSelectValue; import lombok.Builder; import lombok.NonNull; import lombok.Value; /* * #%L * metasfresh-webui-api * %% * Copyright (C) 2017 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ @Value public class SqlViewRowFieldBinding implements SqlEntityFieldBinding { /** * Retrieves a particular field from given {@link ResultSet}. */ @FunctionalInterface public interface SqlViewRowFieldLoader { Object retrieveValue(ResultSet rs, String adLanguage) throws SQLException; } private final String fieldName; private final String columnName; private final boolean keyColumn; private final DocumentFieldWidgetType widgetType; private final boolean virtualColumn; private final Class<?> sqlValueClass; private final SqlSelectValue sqlSelectValue; private final SqlSelectDisplayValue sqlSelectDisplayValue; private final SqlOrderByValue sqlOrderBy; private final SqlViewRowFieldLoader fieldLoader; @Builder private SqlViewRowFieldBinding( @NonNull final String fieldName, @Nullable final String columnName, final boolean keyColumn, @NonNull final DocumentFieldWidgetType widgetType, final boolean virtualColumn, // @Nullable final Class<?> sqlValueClass, @NonNull final SqlSelectValue sqlSelectValue, @Nullable final SqlSelectDisplayValue sqlSelectDisplayValue, // @Nullable final SqlOrderByValue sqlOrderBy, @NonNull final SqlViewRowFieldLoader fieldLoader) { this.fieldName = fieldName; this.columnName = columnName != null ? columnName : this.fieldName; this.keyColumn = keyColumn; this.widgetType = widgetType; this.virtualColumn = virtualColumn; this.sqlValueClass = sqlValueClass != null ? sqlValueClass : widgetType.getValueClass(); this.sqlSelectValue = sqlSelectValue; this.sqlSelectDisplayValue = sqlSelectDisplayValue; this.sqlOrderBy = sqlOrderBy != null ? sqlOrderBy : SqlOrderByValue.builder().sqlSelectDisplayValue(sqlSelectDisplayValue).sqlSelectValue(sqlSelectValue).columnName(columnName).build(); this.fieldLoader = fieldLoader; } }
gpl-3.0
Chao1009/PRadEventViewer
src/QRootCanvas.cpp
17716
//============================================================================// // Below is the class to handle root canvas embedded as a QWidget // // Based on TQRootCanvas, Denis Bertini, M. Al-Turany // // A brief instruction on embeded root canvas can be found at // // https://root.cern.ch/how/how-embed-tcanvas-external-applications // // Chao Peng // // 02/28/2016 // //============================================================================// #include <QEvent> #include <QMouseEvent> #include <QPainter> #include "QRootCanvas.h" QRootCanvas::QRootCanvas(QWidget *parent) : QWidget(parent, 0), fCanvas(0) { // set options needed to properly update the canvas when resizing the widget // and to properly handle context menus and mouse move events #if QT_VERSION < 0x050000 setAttribute(Qt::WA_PaintOnScreen, true); setAttribute(Qt::WA_OpaquePaintEvent, true); #endif // setUpdatesEnabled(kFALSE); setMouseTracking(kTRUE); // register the QWidget in TVirtualX, giving its native window id int wid = gVirtualX->AddWindow((ULong_t)winId(), width(), height()); // create the ROOT TCanvas, giving as argument the QWidget registered id fCanvas = new TCanvas("Root Canvas", width(), height(), wid); } QRootCanvas::~QRootCanvas() { delete fCanvas; } void QRootCanvas::mouseMoveEvent(QMouseEvent *e) { // Handle mouse move events. if(fCanvas) { if(e->buttons() & Qt::LeftButton) { fCanvas->HandleInput(kButton1Motion, e->x(), e->y()); } else if(e->buttons() & Qt::MidButton) { fCanvas->HandleInput(kButton2Motion, e->x(), e->y()); } else if(e->buttons() & Qt::RightButton) { fCanvas->HandleInput(kButton3Motion, e->x(), e->y()); } else { fCanvas->HandleInput(kMouseMotion, e->x(), e->y()); } } } void QRootCanvas::mousePressEvent(QMouseEvent *e) { // Handle mouse button press events. if(fCanvas) { switch (e->button()) { case Qt::LeftButton: fCanvas->HandleInput(kButton1Down, e->x(), e->y()); emit TObjectSelected(fCanvas->GetSelected(), fCanvas); break; case Qt::MidButton: fCanvas->HandleInput(kButton2Down, e->x(), e->y()); break; case Qt::RightButton: // does not work properly on Linux... // ...adding setAttribute(Qt::WA_PaintOnScreen, true) // seems to cure the problem fCanvas->HandleInput(kButton3Down, e->x(), e->y()); break; default: break; } } } void QRootCanvas::mouseReleaseEvent(QMouseEvent *e) { // Handle mouse button release events. if(fCanvas) { switch (e->button()) { case Qt::LeftButton: fCanvas->HandleInput(kButton1Up, e->x(), e->y()); break; case Qt::MidButton: fCanvas->HandleInput(kButton2Up, e->x(), e->y()); break; case Qt::RightButton: // does not work properly on Linux... // ...adding setAttribute(Qt::WA_PaintOnScreen, true) // seems to cure the problem fCanvas->HandleInput(kButton3Up, e->x(), e->y()); break; default: break; } } } void QRootCanvas::mouseDoubleClickEvent(QMouseEvent *e) { // Handle mouse button release events. if(fCanvas) { switch (e->button()) { case Qt::LeftButton: fCanvas->HandleInput(kButton1Double, e->x(), e->y()); break; case Qt::MidButton: fCanvas->HandleInput(kButton2Double, e->x(), e->y()); break; case Qt::RightButton: fCanvas->HandleInput(kButton3Double, e->x(), e->y()); break; default: break; } } } void QRootCanvas::resizeEvent(QResizeEvent *e) { // Handle resize events. QWidget::resizeEvent(e); fNeedResize = true; } void QRootCanvas::paintEvent(QPaintEvent *) { // Handle paint events. if(fCanvas) { QPainter p; p.begin(this); p.end(); if(fNeedResize) { fCanvas->Resize(); fNeedResize = false; } fCanvas->Update(); } } void QRootCanvas::leaveEvent(QEvent * /*e*/) { if(fCanvas) fCanvas->HandleInput(kMouseLeave, 0, 0); } bool QRootCanvas ::eventFilter(QObject *o, QEvent *e) { switch(e->type()) { case QEvent::Close: if(fCanvas) delete fCanvas; break; case QEvent::ChildRemoved: case QEvent::Destroy: case QEvent::Move: case QEvent::Paint: return false; default: break; } return QWidget::eventFilter(o, e); } void QRootCanvas::SetFillColor(Color_t c) { fCanvas->SetFillColor(c); } void QRootCanvas::SetFrameFillColor(Color_t c) { fCanvas->SetFrameFillColor(c); } void QRootCanvas::SetGrid() { fCanvas->SetGrid(); } //////////////////////////////////////////////////////////////////////////////// /// Just a wrapper void QRootCanvas::cd(Int_t subpadnumber) { fCanvas->cd(subpadnumber); } //////////////////////////////////////////////////////////////////////////////// /// Just a wrapper. void QRootCanvas::Browse(TBrowser *b) { fCanvas->Browse(b); } //////////////////////////////////////////////////////////////////////////////// /// Just a wrapper. void QRootCanvas::Clear(Option_t *option) { fCanvas->Clear(option); } //////////////////////////////////////////////////////////////////////////////// /// Just a wrapper. void QRootCanvas::Close(Option_t *option) { fCanvas->Close(option); } //////////////////////////////////////////////////////////////////////////////// /// Just a wrapper. void QRootCanvas::Draw(Option_t *option) { fCanvas->Draw(option); } //////////////////////////////////////////////////////////////////////////////// /// Just a wrapper. TObject *QRootCanvas::DrawClone(Option_t *option) { return fCanvas->DrawClone(option); } //////////////////////////////////////////////////////////////////////////////// /// Just a wrapper. TObject *QRootCanvas::DrawClonePad() { return fCanvas->DrawClonePad(); } //////////////////////////////////////////////////////////////////////////////// /// Just a wrapper. void QRootCanvas::EditorBar() { fCanvas->EditorBar(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::EnterLeave(TPad *prevSelPad, TObject *prevSelObj) { fCanvas->EnterLeave(prevSelPad, prevSelObj); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::FeedbackMode(Bool_t set) { fCanvas->FeedbackMode(set); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::Flush() { fCanvas->Flush(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::UseCurrentStyle() { fCanvas->UseCurrentStyle(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::ForceUpdate() { fCanvas->ForceUpdate() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper const char *QRootCanvas::GetDISPLAY() { return fCanvas->GetDISPLAY() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper TContextMenu *QRootCanvas::GetContextMenu() { return fCanvas->GetContextMenu() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Int_t QRootCanvas::GetDoubleBuffer() { return fCanvas->GetDoubleBuffer(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Int_t QRootCanvas::GetEvent() { return fCanvas->GetEvent(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Int_t QRootCanvas::GetEventX() { return fCanvas->GetEventX() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Int_t QRootCanvas::GetEventY() { return fCanvas->GetEventY() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Color_t QRootCanvas::GetHighLightColor() { return fCanvas->GetHighLightColor() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper TVirtualPad *QRootCanvas::GetPadSave() { return fCanvas->GetPadSave(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper TObject *QRootCanvas::GetSelected() { return fCanvas->GetSelected() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Option_t *QRootCanvas::GetSelectedOpt() { return fCanvas->GetSelectedOpt(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper TVirtualPad *QRootCanvas::GetSelectedPad() { return fCanvas->GetSelectedPad(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Bool_t QRootCanvas::GetShowEventStatus() { return fCanvas->GetShowEventStatus() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Bool_t QRootCanvas::GetAutoExec() { return fCanvas->GetAutoExec(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Size_t QRootCanvas::GetXsizeUser() { return fCanvas->GetXsizeUser(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Size_t QRootCanvas::GetYsizeUser() { return fCanvas->GetYsizeUser(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Size_t QRootCanvas::GetXsizeReal() { return fCanvas->GetXsizeReal(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Size_t QRootCanvas::GetYsizeReal() { return fCanvas->GetYsizeReal(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Int_t QRootCanvas::GetCanvasID() { return fCanvas->GetCanvasID(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Int_t QRootCanvas::GetWindowTopX() { return fCanvas->GetWindowTopX(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Int_t QRootCanvas::GetWindowTopY() { return fCanvas->GetWindowTopY(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper UInt_t QRootCanvas::GetWindowWidth() { return fCanvas->GetWindowWidth() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper UInt_t QRootCanvas::GetWindowHeight() { return fCanvas->GetWindowHeight(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper UInt_t QRootCanvas::GetWw() { return fCanvas->GetWw(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper UInt_t QRootCanvas::GetWh() { return fCanvas->GetWh() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::GetCanvasPar(Int_t &wtopx, Int_t &wtopy, UInt_t &ww, UInt_t &wh) { fCanvas->GetCanvasPar(wtopx, wtopy, ww, wh); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::HandleInput(EEventType button, Int_t x, Int_t y) { fCanvas->HandleInput(button, x, y); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Bool_t QRootCanvas::HasMenuBar() { return fCanvas->HasMenuBar() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::Iconify() { fCanvas->Iconify(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Bool_t QRootCanvas::IsBatch() { return fCanvas->IsBatch() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Bool_t QRootCanvas::IsRetained() { return fCanvas->IsRetained(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::ls(Option_t *option) { fCanvas->ls(option); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::MoveOpaque(Int_t set) { fCanvas->MoveOpaque(set); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Bool_t QRootCanvas::OpaqueMoving() { return fCanvas->OpaqueMoving(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper Bool_t QRootCanvas::OpaqueResizing() { return fCanvas->OpaqueResizing(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::Paint(Option_t *option) { fCanvas->Paint(option); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper TPad *QRootCanvas::Pick(Int_t px, Int_t py, TObjLink *&pickobj) { return fCanvas->Pick(px, py, pickobj); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper TPad *QRootCanvas::Pick(Int_t px, Int_t py, TObject *prevSelObj) { return fCanvas->Pick(px, py, prevSelObj); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::Resize(Option_t *option) { fCanvas->Resize(option); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::ResizeOpaque(Int_t set) { fCanvas->ResizeOpaque(set); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SaveSource(const char *filename, Option_t *option) { fCanvas->SaveSource(filename, option); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SetCursor(ECursor cursor) { fCanvas->SetCursor(cursor); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SetDoubleBuffer(Int_t mode) { fCanvas->SetDoubleBuffer(mode); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SetWindowPosition(Int_t x, Int_t y) { fCanvas->SetWindowPosition(x, y) ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SetWindowSize(UInt_t ww, UInt_t wh) { fCanvas->SetWindowSize(ww,wh) ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SetCanvasSize(UInt_t ww, UInt_t wh) { fCanvas->SetCanvasSize(ww, wh); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SetHighLightColor(Color_t col) { fCanvas->SetHighLightColor(col); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SetSelected(TObject *obj) { fCanvas->SetSelected(obj); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SetSelectedPad(TPad *pad) { fCanvas->SetSelectedPad(pad); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::Show() { fCanvas->Show() ; } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::Size(Float_t xsizeuser, Float_t ysizeuser) { fCanvas->Size(xsizeuser, ysizeuser); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SetBatch(Bool_t batch) { fCanvas->SetBatch(batch); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SetRetained(Bool_t retained) { fCanvas->SetRetained(retained); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::SetTitle(const char *title) { fCanvas->SetTitle(title); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::ToggleEventStatus() { fCanvas->ToggleEventStatus(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::ToggleAutoExec() { fCanvas->ToggleAutoExec(); } //////////////////////////////////////////////////////////////////////////////// /// just a wrapper void QRootCanvas::Update() { fCanvas->Update(); } ////////////////////////////////////////////////////////////////////////////////
gpl-3.0
Afsana-Afroze/escb-mysql
joomla/libraries/quix/src/FormEngine/Contracts/ControlTransformer.php
1813
<?php namespace ThemeXpert\FormEngine\Contracts; abstract class ControlTransformer implements ControlTransformerInterface { public function transform( $config ) { $output = [ ]; $output['advanced'] = $this->get( $config, 'advanced', false ); $output['depends'] = $this->getDepends( $config ); $output['default'] = $this->getValue( $config ); $output['reset'] = $this->get( $config, 'reset', false ); return $output; } public function getValue( $config ) { return $this->get( $config, 'value', "" ); } public function getLabel( $config, $label = null ) { if ( ! $label ) { $label = ucfirst( str_replace( "_", " ", $config['name'] ) ); } return $this->get( $config, 'label', $label ); } public function getPlaceholder( $config ) { return $this->get( $config, 'placeholder' ); } public function getHelp( $config ) { return $this->get( $config, 'help' ); } public function getClass( $config, $klass = null ) { if ( ! $klass ) { $klass = "fe-control-" . $this->getType( $config ) . " fe-control-name-" . $this->getName( $config ); } return $klass . " " . $this->get( $config, 'class', '' ); } public function getSchema( $config ) { return $this->get( $config, 'schema', [ ] ); } public function getType( $config, $type = "text" ) { return $this->get( $config, 'type', $type ); } public function getName( $config ) { return $this->get( $config, 'name' ); } public function getDepends( $config ) { $depends = $this->get( $config, 'depends', [ ] ); if ( ! is_array( $depends ) ) { return [ $depends => "*", ]; } return $depends; } public function get( $config, $key, $default = null ) { return array_get( $config, $key, $default ); } }
gpl-3.0
eraffxi/darkstar
scripts/zones/Windurst_Waters/npcs/Angelica.lua
5361
----------------------------------- -- Area: Windurst Waters -- NPC: Angelica -- Starts and Finished Quest: A Pose By Any Other Name -- !pos -70 -10 -6 238 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/globals/status"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) posestatus = player:getQuestStatus(WINDURST,A_POSE_BY_ANY_OTHER_NAME); if (posestatus == QUEST_AVAILABLE and player:getVar("QuestAPoseByOtherName_prog") == 0 and player:needToZone() == false) then player:startEvent(87); -- A POSE BY ANY dsp.nation.OTHER NAME: Before Quest player:setVar("QuestAPoseByOtherName_prog",1); elseif (posestatus == QUEST_AVAILABLE and player:getVar("QuestAPoseByOtherName_prog") == 1) then player:setVar("QuestAPoseByOtherName_prog",2); mjob = player:getMainJob(); if (mjob == dsp.job.WAR or mjob == dsp.job.PLD or mjob == dsp.job.DRK or mjob == dsp.job.DRG or mjob == dsp.job.COR) then -- Quest Start: Bronze Harness (War/Pld/Drk/Drg/Crs) player:startEvent(92,0,0,0,12576); player:setVar("QuestAPoseByOtherName_equip",12576); elseif (mjob == dsp.job.MNK or mjob == dsp.job.BRD or mjob == dsp.job.BLU) then -- Quest Start: Robe (Mnk/Brd/Blu) player:startEvent(92,0,0,0,12600); player:setVar("QuestAPoseByOtherName_equip",12600); elseif (mjob == dsp.job.THF or mjob == dsp.job.BST or mjob == dsp.job.RNG or mjob == dsp.job.DNC) then -- Quest Start: Leather Vest (Thf/Bst/Rng/Dnc) player:startEvent(92,0,0,0,12568); player:setVar("QuestAPoseByOtherName_equip",12568); elseif (mjob == dsp.job.WHM or mjob == dsp.job.BLM or mjob == dsp.job.SMN or mjob == dsp.job.PUP or mjob == dsp.job.SCH) then -- Quest Start: Tunic (Whm/Blm/Rdm/Smn/Pup/Sch) player:startEvent(92,0,0,0,12608); player:setVar("QuestAPoseByOtherName_equip",12608); elseif (mjob == dsp.job.SAM or mjob == dsp.job.NIN) then -- Quest Start: Kenpogi(Sam/Nin) player:startEvent(92,0,0,0,12584); player:setVar("QuestAPoseByOtherName_equip",12584); end elseif (posestatus == QUEST_ACCEPTED) then starttime = player:getVar("QuestAPoseByOtherName_time"); if ((starttime + 600) >= os.time()) then if (player:getEquipID(dsp.slot.BODY) == player:getVar("QuestAPoseByOtherName_equip")) then player:startEvent(96); ------------------------------------------ QUEST FINISH else player:startEvent(93,0,0,0,player:getVar("QuestAPoseByOtherName_equip"));-- QUEST REMINDER end else player:startEvent(102); ------------------------------------------ QUEST FAILURE end elseif (posestatus == QUEST_COMPLETED and player:needToZone()) then player:startEvent(101); ----------------------------------------------- AFTER QUEST else rand = math.random(1,3); if (rand == 1) then player:startEvent(86); -------------------------------------------- Standard Conversation 1 elseif (rand == 2) then player:startEvent(88); -------------------------------------------- Standard Conversation 2 else player:startEvent(89); -------------------------------------------- Standard Conversation 3 end end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 92) then -------------------------- QUEST START player:addQuest(WINDURST,A_POSE_BY_ANY_OTHER_NAME); player:setVar("QuestAPoseByOtherName_time",os.time()); elseif (csid == 96) then --------------------- QUEST FINFISH if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,206); else player:completeQuest(WINDURST,A_POSE_BY_ANY_OTHER_NAME) player:addTitle(dsp.title.SUPER_MODEL); player:addItem(206); player:messageSpecial(ITEM_OBTAINED,206); player:addKeyItem(dsp.ki.ANGELICAS_AUTOGRAPH); player:messageSpecial(KEYITEM_OBTAINED,dsp.ki.ANGELICAS_AUTOGRAPH); player:addFame(WINDURST,75); player:setVar("QuestAPoseByOtherName_time",0); player:setVar("QuestAPoseByOtherName_equip",0); player:setVar("QuestAPoseByOtherName_prog",0); player:needToZone(true); end elseif (csid == 102) then ---------------------- QUEST FAILURE player:delQuest(WINDURST,A_POSE_BY_ANY_OTHER_NAME); player:addTitle(dsp.title.LOWER_THAN_THE_LOWEST_TUNNEL_WORM); player:setVar("QuestAPoseByOtherName_time",0); player:setVar("QuestAPoseByOtherName_equip",0); player:setVar("QuestAPoseByOtherName_prog",0); player:needToZone(true); end end;
gpl-3.0
stephanfo/AWG
src/CartBundle/Controller/TarifController.php
1100
<?php namespace CartBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use CartBundle\Form\Type\FormatType; use CartBundle\Entity\Format; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; class TarifController extends Controller { /** * @Route("/tarifs/list", name="tarif_index") * @Method({"GET"}) */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $formats = $em->getRepository('CartBundle:Format')->getAllFormatPriceDiscount(); $discounts = $em->getRepository('CartBundle:Discount')->findAll(); $format = new Format(); $formFormat = $this->createForm(FormatType::class, $format, array( 'action' => $this->generateUrl('format_add') )); return $this->render('CartBundle:Tarif:index.html.twig', array( 'formats' => $formats, 'discounts' => $discounts, 'formFormat' => $formFormat->createView() )); } }
gpl-3.0
ForestryMC/ForestryLegacy
forestry_common/cultivation/forestry/cultivation/providers/CropProviderCacti.java
1414
/******************************************************************************* * 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/gpl-3.0.txt * * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ package forestry.cultivation.providers; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import forestry.api.cultivation.ICropEntity; import forestry.api.cultivation.ICropProvider; public class CropProviderCacti implements ICropProvider { @Override public boolean isGermling(ItemStack germling) { return false; } @Override public boolean isCrop(World world, int x, int y, int z) { int blockid = world.getBlockId(x, y, z); return blockid == Block.cactus.blockID; } @Override public ItemStack[] getWindfall() { return null; } @Override public boolean doPlant(ItemStack germling, World world, int x, int y, int z) { return false; } @Override public ICropEntity getCrop(World world, int x, int y, int z) { return new CropCacti(world, x, y, z); } }
gpl-3.0
autopin/autopin-plus
vendor/fast-lib/serialization/serializable.cpp
490
/* * This file is part of fast-lib. * Copyright (C) 2015 RWTH Aachen University - ACS * * This file is licensed under the GNU Lesser General Public License Version 3 * Version 3, 29 June 2007. For details see 'LICENSE.md' in the root directory. */ #include "serializable.hpp" namespace fast { std::string Serializable::to_string() const { return "---\n" + YAML::Dump(emit()) + "\n---"; } void Serializable::from_string(const std::string &str) { load(YAML::Load(str)); } }
gpl-3.0
deep9/zurmo
app/protected/modules/zurmo/models/ExplicitReadWriteModelPermissions.php
7888
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2012 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207, * Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com. ********************************************************************************/ /** * Class helps interaction between the user interface, forms, and controllers that are involved in setting * the explicit permissions on a model. This class merges permission concepts together to form easier to * understand structures for the user interface. Currently this only supports either readOnly or readWrite * permission combinations against a model for a user or group. * @see ExplicitReadWriteModelPermissionsElement * @see ExplicitReadWriteModelPermissionsUtil */ class ExplicitReadWriteModelPermissions { /** * Array of permitable objects that will be explicity set to read only. * @var array */ protected $readOnlyPermitables = array(); /** * Array of permitable objects that will be explicity set to read and write. * @var array */ protected $readWritePermitables = array(); /** * Array of permitable objects that are explicity set to read only that need to be * removed from a securable item. * @var array */ protected $readOnlyPermitablesToRemove = array(); /** * Array of permitable objects that are explicity set to read and write that need to * be removed from a securable item. * @var array */ protected $readWritePermitablesToRemove = array(); /** * Add a permitable object to the read only array. * @param object $permitable */ public function addReadOnlyPermitable($permitable) { assert('$permitable instanceof Permitable'); if (!isset($this->readOnlyPermitables[$permitable->id])) { $this->readOnlyPermitables[$permitable->id] = $permitable; } else { throw notSupportedException(); } } /** * Add a permitable object to the read write array. * @param object $permitable */ public function addReadWritePermitable($permitable) { assert('$permitable instanceof Permitable'); if (!isset($this->readWritePermitables[$permitable->id])) { $this->readWritePermitables[$permitable->id] = $permitable; } else { throw notSupportedException(); } } /** * Add a permitable object that needs to be removed from the securable item. * @param object $permitable */ public function addReadOnlyPermitableToRemove($permitable) { assert('$permitable instanceof Permitable'); if (!isset($this->readOnlyPermitablesToRemove[$permitable->id])) { $this->readOnlyPermitablesToRemove[$permitable->id] = $permitable; } else { throw notSupportedException(); } } /** * Add a permitable object that needs to be removed from the securable item. * @param object $permitable */ public function addReadWritePermitableToRemove($permitable) { assert('$permitable instanceof Permitable'); if (!isset($this->readWritePermitablesToRemove[$permitable->id])) { $this->readWritePermitablesToRemove[$permitable->id] = $permitable; } else { throw notSupportedException(); } } public function removeAllReadWritePermitables() { foreach ($this->readWritePermitables as $permitable) { if (!isset($this->readWritePermitablesToRemove[$permitable->id])) { $this->readWritePermitablesToRemove[$permitable->id] = $permitable; } } } /** * @return integer count of read only permitables */ public function getReadOnlyPermitablesCount() { return count($this->readOnlyPermitables); } /** * @return integer count of read/write permitables */ public function getReadWritePermitablesCount() { return count($this->readWritePermitables); } /** * @return integer count of read only permitables to remove from a securable item. */ public function getReadOnlyPermitablesToRemoveCount() { return count($this->readOnlyPermitablesToRemove); } /** * @return integer count of read/write permitables to remove from a securable item. */ public function getReadWritePermitablesToRemoveCount() { return count($this->readWritePermitablesToRemove); } /** * @return array of read only permitables */ public function getReadOnlyPermitables() { return $this->readOnlyPermitables; } /** * @return array of read/write permitables */ public function getReadWritePermitables() { return $this->readWritePermitables; } /** * @return array of read only permitables to remove from a securable item. */ public function getReadOnlyPermitablesToRemove() { return $this->readOnlyPermitablesToRemove; } /** * @return array of read/write permitables to remove to remove from a securable item. */ public function getReadWritePermitablesToRemove() { return $this->readWritePermitablesToRemove; } /** * Given a permitable, is that permitable in the read only data or the read write data? * @param Permitable $permitable * @return boolean true if it is in one of the data arrays. */ public function isReadOrReadWritePermitable($permitable) { assert('$permitable instanceof Permitable'); if (isset($this->readWritePermitables[$permitable->id]) || isset($this->readOnlyPermitables[$permitable->id])) { return true; } return false; } } ?>
gpl-3.0
dmolchanenko/RedwoodHQ
public/store/VariableTags.js
528
Ext.define('Redwood.store.VariableTags', { extend: 'Ext.data.Store', model: 'Redwood.model.VariableTags', autoLoad: true, autoSync: false, actionMethods: { create : 'POST', read : 'GET', update : 'PUT', destroy: 'DELETE' }, sorters: [{ property : 'value' }], proxy: { type: 'rest', url: '/variabletags', reader: { type: 'json', root: 'tags', successProperty: 'success' } } });
gpl-3.0
harmonycms/harmonycms
data/install/upgradestep/upgradedb.php
1373
<?php /** * HarmonyCMS Upgrade UpgradeDB step class * @copyright Copyright (C) 2016 al3xable <al3xable@yandex.com>. All rights reserved. * @license https://opensource.org/licenses/GPL-3.0 GNU General Public License version 3 * * 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/> */ namespace upgradestep; use UpgradeStep; /** * HarmonyCMS Upgrade UpgradeDB step class */ class UpgradeDB extends UpgradeStep { public function init() { $code = ""; if (isset($_POST["start"])) { $this->_setStep("modules"); } $code .= <<<HTML <form method="post"> <h1>{$this->_getLang("title")}</h1> <p>{$this->_getLang("text")}</p> <button class="btn btn-primary" type="submit" name="start">{$this->_getLang("submit")}</button> </form> HTML; $this->_render($code); } }
gpl-3.0
DawesLab/arduino
libraries/Adafruit_IO_Arduino/src/AdafruitIO_Data.cpp
8933
// // Adafruit invests time and resources providing this open source code. // Please support Adafruit and open source hardware by purchasing // products from Adafruit! // // Copyright (c) 2015-2016 Adafruit Industries // Authors: Tony DiCola, Todd Treece // Licensed under the MIT license. // // All text above must be included in any redistribution. // #include "AdafruitIO_Data.h" #include "AdafruitIO_Feed.h" AdafruitIO_Data::AdafruitIO_Data() { _lat = 0; _lon = 0; _ele = 0; next_data = 0; memset(_feed, 0, AIO_FEED_NAME_LENGTH); memset(_value, 0, AIO_DATA_LENGTH); memset(_csv, 0, AIO_CSV_LENGTH); } AdafruitIO_Data::AdafruitIO_Data(AdafruitIO_Feed *f) { _lat = 0; _lon = 0; _ele = 0; next_data = 0; memset(_feed, 0, AIO_FEED_NAME_LENGTH); strcpy(_feed, f->name); memset(_value, 0, AIO_DATA_LENGTH); memset(_csv, 0, AIO_CSV_LENGTH); } AdafruitIO_Data::AdafruitIO_Data(AdafruitIO_Feed *f, char *csv) { _lat = 0; _lon = 0; _ele = 0; next_data = 0; memset(_feed, 0, AIO_FEED_NAME_LENGTH); strcpy(_feed, f->name); memset(_value, 0, AIO_DATA_LENGTH); memset(_csv, 0, AIO_CSV_LENGTH); strcpy(_csv, csv); _parseCSV(); } AdafruitIO_Data::AdafruitIO_Data(const char *f) { _lat = 0; _lon = 0; _ele = 0; next_data = 0; memset(_feed, 0, AIO_FEED_NAME_LENGTH); strcpy(_feed, f); memset(_value, 0, AIO_DATA_LENGTH); } AdafruitIO_Data::AdafruitIO_Data(const char *f, char *csv) { _lat = 0; _lon = 0; _ele = 0; next_data = 0; memset(_feed, 0, AIO_FEED_NAME_LENGTH); strcpy(_feed, f); memset(_value, 0, AIO_DATA_LENGTH); memset(_csv, 0, AIO_CSV_LENGTH); strcpy(_csv, csv); _parseCSV(); } bool AdafruitIO_Data::setCSV(char *csv) { memset(_csv, 0, AIO_CSV_LENGTH); strcpy(_csv, csv); return _parseCSV(); } void AdafruitIO_Data::setLocation(double lat, double lon, double ele) { // if lat, lon, ele == 0, don't set them if((abs(0-lat) < 0.000001) && (abs(0-lon) < 0.000001) && (abs(0-ele) < 0.000001)) return; _lat = lat; _lon = lon; _ele = ele; } void AdafruitIO_Data::setValue(const char *value, double lat, double lon, double ele) { strcpy(_value, value); setLocation(lat, lon, ele); } void AdafruitIO_Data::setValue(char *value, double lat, double lon, double ele) { strcpy(_value, value); setLocation(lat, lon, ele); } void AdafruitIO_Data::setValue(bool value, double lat, double lon, double ele) { if(value) strcpy(_value, "1"); else strcpy(_value, "0"); setLocation(lat, lon, ele); } void AdafruitIO_Data::setValue(String value, double lat, double lon, double ele) { value.toCharArray(_value, value.length() + 1); setLocation(lat, lon, ele); } void AdafruitIO_Data::setValue(int value, double lat, double lon, double ele) { memset(_value, 0, AIO_DATA_LENGTH); itoa(value, _value, 10); setLocation(lat, lon, ele); } void AdafruitIO_Data::setValue(unsigned int value, double lat, double lon, double ele) { memset(_value, 0, AIO_DATA_LENGTH); utoa(value, _value, 10); setLocation(lat, lon, ele); } void AdafruitIO_Data::setValue(long value, double lat, double lon, double ele) { memset(_value, 0, AIO_DATA_LENGTH); ltoa(value, _value, 10); setLocation(lat, lon, ele); } void AdafruitIO_Data::setValue(unsigned long value, double lat, double lon, double ele) { memset(_value, 0, AIO_DATA_LENGTH); ultoa(value, _value, 10); setLocation(lat, lon, ele); } void AdafruitIO_Data::setValue(float value, double lat, double lon, double ele, int precision) { memset(_value, 0, AIO_DATA_LENGTH); #if defined(ARDUINO_ARCH_AVR) // Use avrlibc dtostre function on AVR platforms. dtostre(value, _value, 10, 0); #elif defined(ESP8266) // ESP8266 Arduino only implements dtostrf and not dtostre. Use dtostrf // but accept a hint as to how many decimals of precision are desired. dtostrf(value, 0, precision, _value); #else // Otherwise fall back to snprintf on other platforms. snprintf(_value, sizeof(_value)-1, "%f", value); #endif setLocation(lat, lon, ele); } void AdafruitIO_Data::setValue(double value, double lat, double lon, double ele, int precision) { memset(_value, 0, AIO_DATA_LENGTH); #if defined(ARDUINO_ARCH_AVR) // Use avrlibc dtostre function on AVR platforms. dtostre(value, _value, 10, 0); #elif defined(ESP8266) // ESP8266 Arduino only implements dtostrf and not dtostre. Use dtostrf // but accept a hint as to how many decimals of precision are desired. dtostrf(value, 0, precision, _value); #else // Otherwise fall back to snprintf on other platforms. snprintf(_value, sizeof(_value)-1, "%f", value); #endif setLocation(lat, lon, ele); } char* AdafruitIO_Data::feedName() { if(! _feed) return (char*)""; return _feed; } char* AdafruitIO_Data::value() { return toChar(); } char* AdafruitIO_Data::toChar() { return _value; } String AdafruitIO_Data::toString() { if(! _value) return String(); return String(_value); } bool AdafruitIO_Data::toBool() { if(! _value) return false; if(strcmp(_value, "1") == 0 || _value[0] == 't' || _value[0] == 'T') return true; else return false; } bool AdafruitIO_Data::isTrue() { return toBool(); } bool AdafruitIO_Data::isFalse() { return !toBool(); } int AdafruitIO_Data::toInt() { if(! _value) return 0; char* endptr; return (int)strtol(_value, &endptr, 10); } int AdafruitIO_Data::toPinLevel() { if(isTrue()) return HIGH; else return LOW; } unsigned int AdafruitIO_Data::toUnsignedInt() { if(! _value) return 0; char* endptr; #ifdef ESP8266 // For some reason strtoul is not defined on the ESP8266 platform right now. // Just use a strtol function and hope for the best. return (unsigned int)strtol(_value, &endptr, 10); #else return (unsigned int)strtoul(_value, &endptr, 10); #endif } float AdafruitIO_Data::toFloat() { if(! _value) return 0; char* endptr; return (float)strtod(_value, &endptr); } double AdafruitIO_Data::toDouble() { if(! _value) return 0; char* endptr; return strtod(_value, &endptr); } long AdafruitIO_Data::toLong() { if(! _value) return 0; char* endptr; return strtol(_value, &endptr, 10); } unsigned long AdafruitIO_Data::toUnsignedLong() { if(! _value) return 0; char* endptr; #ifdef ESP8266 // For some reason strtoul is not defined on the ESP8266 platform right now. // Just use a strtol function and hope for the best. return (unsigned long)strtol(_value, &endptr, 10); #else return strtoul(_value, &endptr, 10); #endif } int AdafruitIO_Data::toRed() { if(! _value) return 0; char r[] = "0x"; strncat(r, toChar() + 1, 2); return (int)strtol(r, NULL, 0); } int AdafruitIO_Data::toGreen() { if(! _value) return 0; char g[] = "0x"; strncat(g, toChar() + 3, 2); return (int)strtol(g, NULL, 0); } int AdafruitIO_Data::toBlue() { if(! _value) return 0; char b[] = "0x"; strncat(b, toChar() + 5, 2); return (int)strtol(b, NULL, 0); } long AdafruitIO_Data::toNeoPixel() { if(! _value) return 0; char rgb_string[9] = "0x"; strncat(rgb_string, toChar() + 1, 6); return strtol(rgb_string, NULL, 0); } char* AdafruitIO_Data::toCSV() { if(! _value) return _csv; memset(_csv, 0, AIO_CSV_LENGTH); strcpy(_csv, _value); strcat(_csv, ","); strcat(_csv, charFromDouble(_lat)); strcat(_csv, ","); strcat(_csv, charFromDouble(_lon)); strcat(_csv, ","); strcat(_csv, charFromDouble(_ele, 2)); return _csv; } double AdafruitIO_Data::lat() { return _lat; } double AdafruitIO_Data::lon() { return _lon; } double AdafruitIO_Data::ele() { return _ele; } static char _double_buffer[20]; char* AdafruitIO_Data::charFromDouble(double d, int precision) { memset(_double_buffer, 0, sizeof(_double_buffer)); #if defined(ARDUINO_ARCH_AVR) // Use avrlibc dtostre function on AVR platforms. dtostre(d, _double_buffer, 10, 0); #elif defined(ESP8266) // ESP8266 Arduino only implements dtostrf and not dtostre. Use dtostrf // but accept a hint as to how many decimals of precision are desired. dtostrf(d, 0, precision, _double_buffer); #else // Otherwise fall back to snprintf on other platforms. snprintf(_double_buffer, sizeof(_double_buffer)-1, "%f", d); #endif return _double_buffer; } bool AdafruitIO_Data::_parseCSV() { // parse value from csv strcpy(_value, strtok(_csv, ",")); if (! _value) return false; // parse lat from csv and convert to float char *lat = strtok(NULL, ","); if (! lat) return false; _lat = atof(lat); // parse lon from csv and convert to float char *lon = strtok(NULL, ","); if (! lon) return false; _lon = atof(lon); // parse ele from csv and convert to float char *ele = strtok(NULL, ","); if (! ele) return false; _ele = atof(ele); return true; }
gpl-3.0
Dwarfex/Hosting-Service
admin/gallery.php
27665
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2010 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Society / Edition # # / # # # # modified by webspell|k3rmit (Stefan Giesecke) in 2009 # # # # - Modifications are released under the GNU GENERAL PUBLIC LICENSE # # - It is NOT allowed to remove this copyright-tag # # - http://www.fsf.org/licensing/licenses/gpl.html # # # ########################################################################## */ $_language->read_module('gallery'); if(!isgalleryadmin($userID) OR mb_substr(basename($_SERVER['REQUEST_URI']),0,15) != "admincenter.php") die($_language->module['access_denied']); $galclass = new Gallery; if(isset($_GET['part'])) $part = $_GET['part']; else $part = ''; if(isset($_GET['action'])) $action = $_GET['action']; else $action = ''; if($part=="groups") { if(isset($_POST['save'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) safe_query("INSERT INTO ".PREFIX."gallery_groups ( name, sort ) values( '".$_POST['name']."', '1' ) "); else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveedit'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) safe_query("UPDATE ".PREFIX."gallery_groups SET name='".$_POST['name']."' WHERE groupID='".$_POST['groupID']."'"); else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['sort'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(isset($_POST['sortlist'])){ if(is_array($_POST['sortlist'])) { foreach($_POST['sortlist'] as $sortstring) { $sorter=explode("-", $sortstring); safe_query("UPDATE ".PREFIX."gallery_groups SET sort='$sorter[1]' WHERE groupID='$sorter[0]' "); } } } } else echo $_language->module['transaction_invalid']; } elseif(isset($_GET['delete'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_GET['captcha_hash'])) { $db_result=safe_query("SELECT * FROM ".PREFIX."gallery WHERE groupID='".$_GET['groupID']."'"); $any=mysql_num_rows($db_result); if($any){ echo $_language->module['galleries_available'].'<br /><br />'; } else{ safe_query("DELETE FROM ".PREFIX."gallery_groups WHERE groupID='".$_GET['groupID']."'"); } } else echo $_language->module['transaction_invalid']; } if($action=="add") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=groups" class="white">'.$_language->module['groups'].'</a> &raquo; '.$_language->module['add_group'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=groups"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['group_name'].'</b></td> <td width="85%"><input type="text" name="name" size="60" /></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /></td> <td><input type="submit" name="save" value="'.$_language->module['add_group'].'" /></td> </tr> </table> </form>'; } elseif($action=="edit") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups WHERE groupID='".$_GET['groupID']."'"); $ds=mysql_fetch_array($ergebnis); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=groups" class="white">'.$_language->module['groups'].'</a> &raquo; '.$_language->module['edit_group'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=groups"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['group_name'].'</b></td> <td><input type="text" name="name" size="60" value="'.getinput($ds['name']).'" /></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="groupID" value="'.$ds['groupID'].'" /></td> <td><input type="submit" name="saveedit" value="'.$_language->module['edit_group'].'" /></td> </tr> </table> </form>'; } else { echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; '.$_language->module['groups'].'</h1>'; echo'<input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=groups&amp;action=add\');return document.MM_returnValue" value="'.$_language->module['new_group'].'" /><br /><br />'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups ORDER BY sort"); echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&amp;part=groups"> <table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD"> <tr> <td width="70%" class="title"><b>'.$_language->module['group_name'].'</b></td> <td width="20%" class="title"><b>'.$_language->module['actions'].'</b></td> <td width="10%" class="title"><b>'.$_language->module['sort'].'</b></td> </tr>'; $n=1; $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); while($ds=mysql_fetch_array($ergebnis)) { if($n%2) { $td='td1'; } else { $td='td2'; } $list = '<select name="sortlist[]">'; for($i=1;$i<=mysql_num_rows($ergebnis);$i++) { $list.='<option value="'.$ds['groupID'].'-'.$i.'">'.$i.'</option>'; } $list .= '</select>'; $list = str_replace('value="'.$ds['groupID'].'-'.$ds['sort'].'"','value="'.$ds['groupID'].'-'.$ds['sort'].'" selected="selected"',$list); echo'<tr> <td class="'.$td.'">'.$ds['name'].'</td> <td class="'.$td.'" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=groups&amp;action=edit&amp;groupID='.$ds['groupID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" /> <input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_group'].'\', \'admincenter.php?site=gallery&amp;part=groups&amp;delete=true&amp;groupID='.$ds['groupID'].'&amp;captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td> <td class="'.$td.'" align="center">'.$list.'</td> </tr>'; $n++; } echo'<tr> <td class="td_head" colspan="3" align="right"><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="submit" name="sort" value="'.$_language->module['to_sort'].'" /></td> </tr> </table> </form>'; } } //part: gallerys elseif($part=="gallerys") { if(isset($_POST['save'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) { safe_query("INSERT INTO ".PREFIX."gallery ( name, date, groupID ) values( '".$_POST['name']."', '".time()."', '".$_POST['group']."' ) "); $id = mysql_insert_id(); } else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveedit'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) { if(!isset($_POST['group'])) { $_POST['group'] = 0; } safe_query("UPDATE ".PREFIX."gallery SET name='".$_POST['name']."', groupID='".$_POST['group']."' WHERE galleryID='".$_POST['galleryID']."'"); } else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveftp'])) { $dir = '../images/gallery/'; $pictures = array(); if(isset($_POST['comment'])) $comment = $_POST['comment']; if(isset($_POST['name'])) $name = $_POST['name']; if(isset($_POST['pictures'])) $pictures = $_POST['pictures']; $i=0; $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { foreach($pictures as $picture) { $typ = getimagesize($dir.$picture); switch ($typ[2]) { case 1: $typ = '.gif'; break; case 2: $typ = '.jpg'; break; case 3: $typ = '.png'; break; } if($name[$i]) $insertname = $name[$i]; else $insertname = $picture; safe_query("INSERT INTO ".PREFIX."gallery_pictures ( galleryID, name, comment, comments) VALUES ('".$_POST['galleryID']."', '".$insertname."', '".$comment[$i]."', '".$_POST['comments']."' )"); $insertid = mysql_insert_id(); copy($dir.$picture, $dir.'large/'.$insertid.$typ); $galclass->savethumb($dir.'large/'.$insertid.$typ, $dir.'thumb/'.$insertid.'.jpg'); @unlink($dir.$picture); $i++; } } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveform'])) { $dir = '../images/gallery/'; $picture = $_FILES['picture']; $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if($picture['name'] != "") { if($_POST['name']) $insertname = $_POST['name']; else $insertname = $picture['name']; safe_query("INSERT INTO ".PREFIX."gallery_pictures ( galleryID, name, comment, comments) VALUES ('".$_POST['galleryID']."', '".$insertname."', '".$_POST['comment']."', '".$_POST['comments']."' )"); $insertid = mysql_insert_id(); $typ = getimagesize($picture['tmp_name']); switch ($typ[2]) { case 1: $typ = '.gif'; break; case 2: $typ = '.jpg'; break; case 3: $typ = '.png'; break; } move_uploaded_file($picture['tmp_name'], $dir.'large/'.$insertid.$typ); $galclass->savethumb($dir.'large/'.$insertid.$typ, $dir.'thumb/'.$insertid.'.jpg'); } } else echo $_language->module['transaction_invalid']; } elseif(isset($_GET['delete'])) { //SQL $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_GET['captcha_hash'])) { if(safe_query("DELETE FROM ".PREFIX."gallery WHERE galleryID='".$_GET['galleryID']."'")) { //FILES $ergebnis=safe_query("SELECT picID FROM ".PREFIX."gallery_pictures WHERE galleryID='".$_GET['galleryID']."'"); while($ds=mysql_fetch_array($ergebnis)) { @unlink('../images/gallery/thumb/'.$ds['picID'].'.jpg'); //thumbnails $path = '../images/gallery/large/'; if(file_exists($path.$ds['picID'].'.jpg')) $path = $path.$ds['picID'].'.jpg'; elseif(file_exists($path.$ds['picID'].'.png')) $path = $path.$ds['picID'].'.png'; else $path = $path.$ds['picID'].'.gif'; @unlink($path); //large safe_query("DELETE FROM ".PREFIX."comments WHERE parentID='".$ds['picID']."' AND type='ga'"); } safe_query("DELETE FROM ".PREFIX."gallery_pictures WHERE galleryID='".$_GET['galleryID']."'"); } } else echo $_language->module['transaction_invalid']; } if($action=="add") { $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups"); $any=mysql_num_rows($ergebnis); if($any){ $groups = '<select name="group">'; while($ds=mysql_fetch_array($ergebnis)) { $groups.='<option value="'.$ds['groupID'].'">'.getinput($ds['name']).'</option>'; } $groups.='</select>'; $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=gallerys" class="white">'.$_language->module['galleries'].'</a> &raquo; '.$_language->module['add_gallery'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=gallerys&amp;action=upload"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['gallery_name'].'</b></td> <td width="85%"><input type="text" name="name" size="60" /></td> </tr> <tr> <td><b>'.$_language->module['group'].'</b></td> <td>'.$groups.'</td> </tr> <tr> <td><b>'.$_language->module['pic_upload'].'</b></td> <td><select name="upload"> <option value="ftp">'.$_language->module['ftp'].'</option> <option value="form">'.$_language->module['formular'].'</option> </select></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /></td> <td><input type="submit" name="save" value="'.$_language->module['add_gallery'].'" /></td> </tr> </table> </form> <br /><small>'.$_language->module['ftp_info'].' "http://'.$hp_url.'/images/gallery"</small>'; } else{ echo '<br>'.$_language->module['need_group']; } } elseif($action=="edit") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups"); $groups = '<select name="group">'; while($ds=mysql_fetch_array($ergebnis)) { $groups.='<option value="'.$ds['groupID'].'">'.getinput($ds['name']).'</option>'; } $groups.='</select>'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery WHERE galleryID='".$_GET['galleryID']."'"); $ds=mysql_fetch_array($ergebnis); $groups = str_replace('value="'.$ds['groupID'].'"','value="'.$ds['groupID'].'" selected="selected"',$groups); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=gallerys" class="white">'.$_language->module['galleries'].'</a> &raquo; '.$_language->module['edit_gallery'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['gallery_name'].'</b></td> <td width="85%"><input type="text" name="name" value="'.getinput($ds['name']).'" /></td> </tr>'; if($ds['userID'] != 0) echo ' <tr> <td><b>'.$_language->module['usergallery_of'].'</b></td> <td><a href="../index.php?site=profile&amp;id='.$userID.'" target="_blank">'.getnickname($ds['userID']).'</a></td> </tr>'; else echo '<tr> <td><b>'.$_language->module['group'].'</b></td> <td>'.$groups.'</td> </tr>'; echo'<tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$ds['galleryID'].'" /></td> <td><input type="submit" name="saveedit" value="'.$_language->module['edit_gallery'].'" /></td> </tr> </table> </form>'; } elseif($action=="upload") { echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=gallerys" class="white">'.$_language->module['galleries'].'</a> &raquo; '.$_language->module['upload'].'</h1>'; $dir = '../images/gallery/'; if(isset($_POST['upload'])) $upload_type = $_POST['upload']; elseif(isset($_GET['upload'])) $upload_type = $_GET['upload']; else $upload_type = null; if(isset($_GET['galleryID'])) $id=$_GET['galleryID']; if($upload_type == "ftp") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); echo'<form method="post" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td>'; $pics = Array(); $picdir = opendir($dir); while (false !== ($file = readdir($picdir))) { if ($file != "." && $file != "..") { if(is_file($dir.$file)) { if($info = getimagesize($dir.$file)) { if($info[2]==1 OR $info[2]==2 || $info[2]==3) $pics[] = $file; } } } } closedir($picdir); natcasesort ($pics); reset ($pics); echo '<script language="JavaScript" type="text/javascript"> function fillcomments(){ document.getElementById(\'comments\').value=getselection(\'access\'); } </script> <table border="0" width="100%" cellspacing="1" cellpadding="1"> <tr> <td></td> <td><b>'.$_language->module['filename'].'</b></td> <td><b>'.$_language->module['name'].'</b></td> <td><b>'.$_language->module['comment'].'</b></td> </tr>'; foreach($pics as $val) { if(is_file($dir.$val)) { echo '<tr> <td><input type="checkbox" value="'.$val.'" name="pictures[]" checked="checked" /></td> <td><a href="'.$dir.$val.'" target="_blank">'.$val.'</a></td> <td><input type="text" name="name[]" size="40" /></td> <td><input type="text" name="comment[]" size="40" /></td> </tr>'; } } $accesses=generateaccessdropdown('access', 'access', '', 'fillcomments();'); echo '</table></td> </tr> <tr> <td><br /><b>'.$_language->module['visitor_comments'].'</b> &nbsp; '.$accesses.' <input type="hidden" value="" name="comments" id="comments" /></td> </tr> <tr> <td><br /><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$id.'" /> <input type="submit" name="saveftp" value="'.$_language->module['upload'].'" /></td> </tr> </table> </form>'; } elseif($upload_type == "form") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $accesses=generateaccessdropdown('access', 'access', '', 'fillcomments();'); echo '<script language="JavaScript" type="text/javascript"> function fillcomments(){ document.getElementById(\'comments\').value=getselection(\'access\'); } </script> <form method="post" action="admincenter.php?site=gallery&amp;part=gallerys" enctype="multipart/form-data"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="20%"><b>'.$_language->module['name'].'</b></td> <td width="80%"><input type="text" name="name" size="60" /></td> </tr> <tr> <td><b>'.$_language->module['comment'].'</b></td> <td><input type="text" name="comment" size="60" maxlength="255" /></td> </tr> <tr> <td valign="top"><b>'.$_language->module['visitor_comments'].'</b></td> <td> '.$accesses.' <input type="hidden" value="" name="comments" id="comments" /> </td> </tr> <tr> <td><b>'.$_language->module['picture'].'</b></td> <td><input name="picture" type="file" size="40" /></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$id.'" /></td> <td><input type="submit" name="saveform" value="'.$_language->module['upload'].'" /></td> </tr> </table> </form>'; } } else { echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; '.$_language->module['galleries'].'</h1>'; echo'<input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=add\');return document.MM_returnValue" value="'.$_language->module['new_gallery'].'" /><br /><br />'; echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD"> <tr> <td width="50%" class="title"><b>'.$_language->module['gallery_name'].'</b></td> <td width="50%" class="title" colspan="2"><b>'.$_language->module['actions'].'</b></td> </tr>'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups ORDER BY sort"); while($ds=mysql_fetch_array($ergebnis)) { echo'<tr> <td class="td_head" colspan="3"><b>'.getinput($ds['name']).'</b></td> </tr>'; $galleries=safe_query("SELECT * FROM ".PREFIX."gallery WHERE groupID='$ds[groupID]' AND userID='0' ORDER BY date"); $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $i=1; while($db=mysql_fetch_array($galleries)) { if($i%2) { $td='td1'; } else { $td='td2'; } echo'<tr> <td class="'.$td.'" width="50%"><a href="../index.php?site=gallery&amp;galleryID='.$db['galleryID'].'" target="_blank">'.getinput($db['name']).'</a></td> <td class="'.$td.'" width="30%" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=upload&amp;upload=form&amp;galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['add_img'].' ('.$_language->module['per_form'].')" style="margin:1px;" /> <input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=upload&amp;upload=ftp&amp;galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['add_img'].' ('.$_language->module['per_ftp'].')" style="margin:1px;" /></td> <td class="'.$td.'" width="20%" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=edit&amp;galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" /> <input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_gallery'].'\', \'admincenter.php?site=gallery&amp;part=gallerys&amp;delete=true&amp;galleryID='.$db['galleryID'].'&amp;captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td> </tr>'; $i++; } } echo'</table></form><br /><br />'; echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; '.$_language->module['usergalleries'].'</h1>'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery WHERE userID!='0'"); echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD"> <tr> <td width="50%" class="title"><b>'.$_language->module['gallery_name'].'</b></td> <td width="30%" class="title"><b>'.$_language->module['usergallery_of'].'</b></td> <td width="20%" class="title"><b>'.$_language->module['actions'].'</b></td> </tr>'; $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $i=1; while($ds=mysql_fetch_array($ergebnis)) { if($i%2) { $td='td1'; } else { $td='td2'; } echo'<tr> <td class="'.$td.'"><a href="../index.php?site=gallery&amp;galleryID='.$ds['galleryID'].'" target="_blank">'.getinput($ds['name']).'</a></td> <td class="'.$td.'"><a href="../index.php?site=profile&amp;id='.$userID.'" target="_blank">'.getnickname($ds['userID']).'</a></td> <td class="'.$td.'" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=edit&amp;galleryID='.$ds['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" /> <input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_gallery'].'\', \'admincenter.php?site=gallery&amp;part=gallerys&amp;delete=true&amp;galleryID='.$ds['galleryID'].'&amp;captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td> </tr>'; $i++; } echo'</table></form>'; } } ?>
gpl-3.0
bsmr-eve/Pyfa
eos/effects/shipbonusnoctistractorvelocity.py
365
# shipBonusNoctisTractorVelocity # # Used by: # Ship: Noctis type = "passive" def handler(fit, ship, context): fit.modules.filteredItemBoost(lambda mod: mod.item.group.name == "Tractor Beam", "maxTractorVelocity", ship.getModifiedItemAttr("shipBonusOreIndustrial2"), skill="ORE Industrial")
gpl-3.0
voltagex/rencode-sharp
rencode-sharp/BStruct.cs
3816
using System; using MiscUtil.Conversion; namespace rencodesharp { public class BStruct { /// <summary> /// Pack the object 'x' into (network order byte format). /// </summary> public static string Pack(object x, int n) { byte[] b = EndianBitConverter.Big.GetBytes(x); string output = ""; for(int i = 0; i < b.Length; i++) { output += (char)b[i]; } return output.Substring(output.Length - n, n); } /// <summary> /// Unpack the string 'x' (network order byte format) into object. /// </summary> public static object Unpack(string x, int n) { x = Util.StringPad(x, n); byte[] b = new byte[n]; for(int i = 0; i < x.Length; i++) { b[i] = (byte)x[i]; } if(b.Length == 1) return BStruct.ToInt1(b, 0); if(b.Length == 2) return BStruct.ToInt2(b, 0); if(b.Length == 4) return BStruct.ToInt4(b, 0); if(b.Length == 8) return BStruct.ToInt8(b, 0); return null; } /// <summary> /// Gets the bytes of an Int32. /// </summary> public unsafe static void GetBytes(Int32 value, byte[] buffer, int startIndex) { fixed(byte* numRef = buffer) { *((int*)(numRef+startIndex)) = value; } } /// <summary> /// Gets the bytes of an Int64. /// </summary> public unsafe static void GetBytes(Int64 value, byte[] buffer, int startingIndex) { fixed(byte* numRef = buffer) { *((long*)(numRef + startingIndex)) = value; } } /// <summary> /// Converts byte array to INT1 (8 bit integer) /// </summary> public static int ToInt1(byte[] value, int startIndex) { if(value.Length == 4) return EndianBitConverter.Big.ToInt16(value, startIndex); else { byte[] newValue; if(value[0] >= 0 && value[0] < 128) newValue = new byte[2] { 0, 0 }; else newValue = new byte[2] { 255, 255 }; int ni = newValue.Length - 1; for(int i = value.Length - 1; i >= 0; i--) { newValue[ni] = value[i]; ni--; } return EndianBitConverter.Big.ToInt16(newValue, startIndex); } } /// <summary> /// Converts byte array to INT2 (16 bit integer) /// </summary> public static int ToInt2(byte[] value, int startIndex) { if(value.Length == 2) return EndianBitConverter.Big.ToInt16(value, startIndex); else throw new ArgumentException("\"value\" doesn't have 2 bytes."); } /// <summary> /// Converts byte array to INT4 (32 bit integer) /// </summary> public static int ToInt4(byte[] value, int startIndex) { if(value.Length == 4) return EndianBitConverter.Big.ToInt32(value, startIndex); else throw new ArgumentException("\"value\" doesn't have 4 bytes."); } /// <summary> /// Converts byte array to INT8 (64 bit integer) /// </summary> public static long ToInt8(byte[] value, int startIndex) { if(value.Length == 8) return EndianBitConverter.Big.ToInt64(value, startIndex); else throw new ArgumentException("\"value\" doesn't have 8 bytes."); } /// <summary> /// Converts byte array to Float (32 bit float) /// </summary> public static float ToFloat(byte[] value, int startIndex) { if(value.Length == 4) return EndianBitConverter.Big.ToSingle(value, startIndex); else throw new ArgumentException("\"value\" doesn't have 4 bytes."); } /// <summary> /// Converts byte array to Double (64 bit float) /// </summary> public static double ToDouble(byte[] value, int startIndex) { if(value.Length == 8) return EndianBitConverter.Big.ToDouble(value, startIndex); else throw new ArgumentException("\"value\" doesn't have 8 bytes."); } } }
gpl-3.0
ddikodroid/-college_related_stuff
Tugas Pemrograman - Looping/prime.cpp
515
/* Bilangan Prima atau Bukan Bilangan Prima */ #include<bits/stdc++.h> using namespace std; int main() { cout << "BILANGAN PRIMA ATAU BUKAN BILANGAN PRIMA \n"; int angka, jumlah=0; cout << "MASUKKAN BILANGAN: "; cin >> angka; for(int faktor=1;faktor<=angka;faktor++) { if(angka%faktor==0) jumlah++; } if(jumlah==2) cout << angka << " MERUPAKAN BILANGAN PRIMA \n"; else cout << angka << " BUKAN MERUPAKAN BILANGAN PRIMA \n"; system("PAUSE"); return 0; }
gpl-3.0
NovaViper/TetraCraft
src-1.10.2/main/java/com/novaviper/tetracraft/common/CommonProxy.java
2230
package com.novaviper.tetracraft.common; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.fml.common.event.*; import net.minecraftforge.fml.common.network.IGuiHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; /** * @author NovaViper <nova.gamez15@gmail.com> * @date 7/10/2016 * @purpose Loads stuff on the server side */ public class CommonProxy implements IGuiHandler{ @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { /*if (ID == IDs.nileTableGUI) { TileEntity target = world.getTileEntity(new BlockPos(x, y, z)); if (!(target instanceof TileEntityNileWorkbench)) { return null; } TileEntityNileWorkbench tileNileTable = (TileEntityNileWorkbench) target; ContainerNileWorkbench tableContainer = new ContainerNileWorkbench(tileNileTable, player.inventory, world, new BlockPos(x, y, z)); return tableContainer; }*/ return null; } @Override public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { /*if (ID == IDs.nileTableGUI) { TileEntity target = world.getTileEntity(new BlockPos(x, y, z)); if (!(target instanceof TileEntityNileWorkbench)) { return null; } TileEntityNileWorkbench tileNileTable = (TileEntityNileWorkbench) target; GuiNileWorkbench tableGui = new GuiNileWorkbench(player.inventory, tileNileTable, world, new BlockPos(x, y, z)); return tableGui; }*/ return null; } // Client Objects\\ public void onPreInit(FMLPreInitializationEvent event){} public void onInit(FMLInitializationEvent event){} public void onPostInit(FMLPostInitializationEvent event){} public void onServerStarting(FMLServerStartingEvent event){} public void onServerStarted(FMLServerStartedEvent event){} public void onServerStopping(FMLServerStoppingEvent event){} public void onServerStopped(FMLServerStoppedEvent event){} public EntityPlayer getPlayerEntity(MessageContext ctx) { return ctx.getServerHandler().playerEntity; } public EntityPlayer getPlayerEntity() { return null; } //Particles //public void spawnName(World world, Entity entity) {} }
gpl-3.0
cemc/cscircles-wp-content
themes/twentyeleven/content-single.php
3837
<?php /** * The template for displaying content in the single.php template * * @package WordPress * @subpackage Twenty_Eleven * @since Twenty Eleven 1.0 */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <h1 class="entry-title"><?php the_title(); ?></h1> <?php if ( 'post' == get_post_type() ) : ?> <div class="entry-meta"> <?php twentyeleven_posted_on(); ?> </div><!-- .entry-meta --> <?php endif; ?> </header><!-- .entry-header --> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'twentyeleven' ) . '</span>', 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-meta"> <?php /* translators: Used between list items, there is a space after the comma. */ $categories_list = get_the_category_list( __( ', ', 'twentyeleven' ) ); /* translators: Used between list items, there is a space after the comma. */ $tag_list = get_the_tag_list( '', __( ', ', 'twentyeleven' ) ); if ( '' != $tag_list ) { /* translators: 1: Categories list, 2: Tag list, 3: Permalink, 4: Post title, 5: Author name, 6: Author URL. */ $utility_text = __( 'This entry was posted in %1$s and tagged %2$s by <a href="%6$s">%5$s</a>. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'twentyeleven' ); } elseif ( '' != $categories_list ) { /* translators: 1: Categories list, 2: Tag list, 3: Permalink, 4: Post title, 5: Author name, 6: Author URL. */ $utility_text = __( 'This entry was posted in %1$s by <a href="%6$s">%5$s</a>. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'twentyeleven' ); } else { /* translators: 1: Categories list, 2: Tag list, 3: Permalink, 4: Post title, 5: Author name, 6: Author URL. */ $utility_text = __( 'This entry was posted by <a href="%6$s">%5$s</a>. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'twentyeleven' ); } printf( $utility_text, $categories_list, $tag_list, esc_url( get_permalink() ), the_title_attribute( 'echo=0' ), get_the_author(), esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) ); ?> <?php edit_post_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '</span>' ); ?> <?php // If a user has filled out their description and this is a multi-author blog, show a bio on their entries. if ( get_the_author_meta( 'description' ) && ( ! function_exists( 'is_multi_author' ) || is_multi_author() ) ) : ?> <div id="author-info"> <div id="author-avatar"> <?php /** This filter is documented in author.php */ $author_bio_avatar_size = apply_filters( 'twentyeleven_author_bio_avatar_size', 68 ); echo get_avatar( get_the_author_meta( 'user_email' ), $author_bio_avatar_size ); ?> </div><!-- #author-avatar --> <div id="author-description"> <h2> <?php /* translators: %s: Author name. */ printf( __( 'About %s', 'twentyeleven' ), get_the_author() ); ?> </h2> <?php the_author_meta( 'description' ); ?> <div id="author-link"> <a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" rel="author"> <?php /* translators: %s: Author name. */ printf( __( 'View all posts by %s <span class="meta-nav">&rarr;</span>', 'twentyeleven' ), get_the_author() ); ?> </a> </div><!-- #author-link --> </div><!-- #author-description --> </div><!-- #author-info --> <?php endif; ?> </footer><!-- .entry-meta --> </article><!-- #post-<?php the_ID(); ?> -->
gpl-3.0
prozakis/mywms-Server
rich.client/los.clientsuite/LOS Common/src/de/linogistix/common/gui/layout/WrapFlowLayout.java
4613
/* * Copyright (c) 2006 - 2010 LinogistiX GmbH * * www.linogistix.com * * Project myWMS-LOS */ package de.linogistix.common.gui.layout; import java.awt.*; import javax.swing.*; /** * FlowLayout subclass that fully supports wrapping of components. */ public class WrapFlowLayout extends FlowLayout { // The preferred size for this container. private Dimension preferredLayoutSize; /** * Constructs a new <code>WrapLayout</code> with a left * alignment and a default 5-unit horizontal and vertical gap. */ public WrapFlowLayout() { super(LEFT); } /** * Constructs a new <code>FlowLayout</code> with the specified * alignment and a default 5-unit horizontal and vertical gap. * The value of the alignment argument must be one of * <code>WrapLayout</code>, <code>WrapLayout</code>, * or <code>WrapLayout</code>. * @param align the alignment value */ public WrapFlowLayout(int align) { super(align); } /** * Creates a new flow layout manager with the indicated alignment * and the indicated horizontal and vertical gaps. * <p> * The value of the alignment argument must be one of * <code>WrapLayout</code>, <code>WrapLayout</code>, * or <code>WrapLayout</code>. * @param align the alignment value * @param hgap the horizontal gap between components * @param vgap the vertical gap between components */ public WrapFlowLayout(int align, int hgap, int vgap) { super(align, hgap, vgap); } /** * Returns the preferred dimensions for this layout given the * <i>visible</i> components in the specified target container. * @param target the component which needs to be laid out * @return the preferred dimensions to lay out the * subcomponents of the specified container */ /* public Dimension preferredLayoutSize(Container target) { return layoutSize(target, true); }*/ /** * Returns the minimum dimensions needed to layout the <i>visible</i> * components contained in the specified target container. * @param target the component which needs to be laid out * @return the minimum dimensions to lay out the * subcomponents of the specified container */ /* public Dimension minimumLayoutSize(Container target) { return layoutSize(target, false); }*/ public Dimension preferredLayoutSize (Container target) { synchronized (target.getTreeLock()) { Insets insets = target.getInsets(); int maxwidth = target.getWidth() - (insets.left + insets.right + getHgap() * 2); int nmembers = target.getComponentCount(); int x = 0, y = insets.top + getVgap(); int rowh = 0, start = 0; boolean ltr = target.getComponentOrientation().isLeftToRight(); for (int i = 0; i < nmembers; i++) { Component m = target.getComponent(i); if (m.isVisible()) { Dimension d = m.getPreferredSize(); if ((x == 0) || ((x + d.width) <= maxwidth)) { if (x > 0) { x += getHgap(); } x += d.width; rowh = Math.max(rowh, d.height); } else { processComponents(target, insets.left + getHgap(), y, maxwidth - x, rowh, start, i, ltr); x = d.width; y += getVgap() + rowh; rowh = d.height; start = i; } } } processComponents(target, insets.left + getHgap(), y, maxwidth - x, rowh, start, nmembers, ltr); y += rowh; return new Dimension (maxwidth, y+5); } } private void processComponents(Container target, int x, int y, int width, int height, int rowStart, int rowEnd, boolean ltr) { synchronized (target.getTreeLock()) { switch (getAlignment()) { case LEFT: x += ltr ? 0 : width; break; case CENTER: x += width / 2; break; case RIGHT: x += ltr ? width : 0; break; case LEADING: break; case TRAILING: x += width; break; } for (int i = rowStart; i < rowEnd; i++) { Component m = target.getComponent(i); if (m.isVisible()) { x += m.getWidth() + getHgap(); } } } } }
gpl-3.0
eraffxi/darkstar
scripts/zones/Valley_of_Sorrows/npcs/qm1.lua
1322
----------------------------------- -- Area: Valley of Sorrows -- NPC: qm1 (???) -- Spawns Adamantoise or Aspidochelone -- !pos 0 0 -37 59 ----------------------------------- package.loaded["scripts/zones/Valley_of_Sorrows/TextIDs"] = nil ----------------------------------- require("scripts/zones/Valley_of_Sorrows/TextIDs") require("scripts/zones/Valley_of_Sorrows/MobIDs") require("scripts/globals/npc_util") require("scripts/globals/settings") require("scripts/globals/status") ----------------------------------- function onSpawn(npc) if LandKingSystem_NQ < 1 and LandKingSystem_HQ < 1 then npc:setStatus(dsp.status.DISAPPEAR) end end function onTrade(player,npc,trade) if not GetMobByID(ADAMANTOISE):isSpawned() and not GetMobByID(ASPIDOCHELONE):isSpawned() then if LandKingSystem_NQ ~= 0 and npcUtil.tradeHas(trade, 3343) and npcUtil.popFromQM(player, npc, ADAMANTOISE) then player:confirmTrade() elseif LandKingSystem_HQ ~= 0 and npcUtil.tradeHas(trade, 3344) and npcUtil.popFromQM(player, npc, ASPIDOCHELONE) then player:confirmTrade() end end end function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
gpl-3.0
osroca/gvnix
addon-dynamic-configuration/src/main/java/org/gvnix/dynamic/configuration/roo/addon/entity/DynProperty.java
2650
/* * gvNIX is an open source tool for rapid application development (RAD). * Copyright (C) 2010 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 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.gvnix.dynamic.configuration.roo.addon.entity; import org.apache.commons.lang3.ObjectUtils; /** * Dynamic configuration property entity. * * @author <a href="http://www.disid.com">DISID Corporation S.L.</a> made for <a * href="http://www.dgti.gva.es">General Directorate for Information * Technologies (DGTI)</a> */ public class DynProperty { private String key; private String value; public DynProperty(String key, String value) { super(); this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } /** {@inheritDoc} */ @Override public String toString() { return "DynProperty [key=" + key + ", value=" + value + "]"; } /** * {@inheritDoc} Two properties are equal if their key and value are equals. */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } DynProperty other = (DynProperty) obj; if (!ObjectUtils.equals(key, other.key)) { return false; } if (!ObjectUtils.equals(value, other.value)) { return false; } return true; } /** {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } }
gpl-3.0
senbox-org/snap-desktop
snap-worldwind/src/main/java/org/esa/snap/worldwind/LayerPanel.java
4767
/* * Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca * * 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.esa.snap.worldwind; import gov.nasa.worldwind.WorldWindow; import gov.nasa.worldwind.layers.Layer; import javax.swing.*; import javax.swing.border.CompoundBorder; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; class LayerPanel extends JPanel { private JPanel layersPanel; private JPanel westPanel; private JScrollPane scrollPane; private Font defaultFont; public LayerPanel(WorldWindow wwd) { // Make a panel at a default size. super(new BorderLayout()); this.makePanel(wwd, new Dimension(100, 400)); } public LayerPanel(WorldWindow wwd, Dimension size) { // Make a panel at a specified size. super(new BorderLayout()); this.makePanel(wwd, size); } private void makePanel(WorldWindow wwd, Dimension size) { // Make and fill the panel holding the layer titles. this.layersPanel = new JPanel(new GridLayout(0, 1, 0, 4)); this.layersPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.fill(wwd); // Must put the layer grid in a container to prevent scroll panel from stretching their vertical spacing. final JPanel dummyPanel = new JPanel(new BorderLayout()); dummyPanel.add(this.layersPanel, BorderLayout.NORTH); // Put the name panel in a scroll bar. this.scrollPane = new JScrollPane(dummyPanel); this.scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); if (size != null) this.scrollPane.setPreferredSize(size); // Add the scroll bar and name panel to a titled panel that will resize with the main window. westPanel = new JPanel(new GridLayout(0, 1, 0, 10)); westPanel.setBorder( new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Layers"))); westPanel.setToolTipText("Layers to Show"); westPanel.add(scrollPane); this.add(westPanel, BorderLayout.CENTER); } private void fill(WorldWindow wwd) { // Fill the layers panel with the titles of all layers in the world window's current model. for (Layer layer : wwd.getModel().getLayers()) { if (layer.getName().equalsIgnoreCase("Atmosphere") || layer.getName().equalsIgnoreCase("World Map") || layer.getName().equalsIgnoreCase("Scale bar") || layer.getName().equalsIgnoreCase("Compass")) continue; final LayerAction action = new LayerAction(layer, wwd, layer.isEnabled()); final JCheckBox jcb = new JCheckBox(action); jcb.setSelected(action.selected); this.layersPanel.add(jcb); if (defaultFont == null) { this.defaultFont = jcb.getFont(); } } } public void update(WorldWindow wwd) { // Replace all the layer names in the layers panel with the names of the current layers. this.layersPanel.removeAll(); this.fill(wwd); this.westPanel.revalidate(); this.westPanel.repaint(); } @Override public void setToolTipText(String string) { this.scrollPane.setToolTipText(string); } private static class LayerAction extends AbstractAction { final WorldWindow wwd; private final Layer layer; private final boolean selected; public LayerAction(Layer layer, WorldWindow wwd, boolean selected) { super(layer.getName()); this.wwd = wwd; this.layer = layer; this.selected = selected; this.layer.setEnabled(this.selected); } public void actionPerformed(ActionEvent actionEvent) { // Simply enable or disable the layer based on its toggle button. if (((JCheckBox) actionEvent.getSource()).isSelected()) this.layer.setEnabled(true); else this.layer.setEnabled(false); wwd.redraw(); } } }
gpl-3.0
esri-es/awesome-arcgis
node_modules/caniuse-lite/data/features/media-session-api.js
867
module.exports={A:{A:{"2":"K D G E A B hB"},B:{"2":"2 C d J M H I"},C:{"2":"0 1 2 3 4 6 7 8 eB BB F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z HB GB AB CB DB FB YB XB"},D:{"1":"0 1 3 4 7 8 HB GB AB CB DB FB RB LB JB jB MB NB OB PB","2":"2 6 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z"},E:{"2":"F N K D G E A B C QB IB SB TB UB VB WB p","16":"5 ZB"},F:{"2":"0 1 5 6 9 E B C J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z aB bB cB dB p fB"},G:{"2":"G IB gB EB iB KB kB lB mB nB oB pB qB rB sB tB"},H:{"2":"uB"},I:{"2":"4 BB F vB wB xB yB EB zB 0B"},J:{"2":"D A"},K:{"2":"5 9 A B C L p"},L:{"2":"JB"},M:{"2":"3"},N:{"2":"A B"},O:{"2":"1B"},P:{"2":"F 2B 3B 4B 5B"},Q:{"2":"6B"},R:{"2":"7B"}},B:6,C:"Media Session API"};
gpl-3.0
vSaKv/backend
framework/views/no/profile-callstack.php
809
<!-- start profiling callstack --> <table class="yiiLog" width="100%" cellpadding="2" style="border-spacing:1px;font:11px Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;color:#666666;"> <tr> <th style="background:black;color:white;" colspan="2"> Profileringsrapport </th> </tr> <tr style="background-color: #ccc;"> <th>Funksjone</th> <th>Tid (sek)</th> </tr> <?php foreach ($data as $index => $entry) { $color = ($index % 2) ? '#F5F5F5' : '#FFFFFF'; list($proc, $time, $level) = $entry; $proc = CHtml::encode($proc); $time = sprintf('%0.5f', $time); $spaces = str_repeat('&nbsp;', $level * 8); echo <<<EOD <tr style="background:{$color}"> <td>{$spaces}{$proc}</td> <td align="center">{$time}</td> </tr> EOD; } ?> </table> <!-- end of profiling callstack -->
gpl-3.0
PetteriAimonen/solvespace
src/ttf.cpp
24974
//----------------------------------------------------------------------------- // Routines to read a TrueType font as vector outlines, and generate them // as entities, since they're always representable as either lines or // quadratic Bezier curves. // // Copyright 2008-2013 Jonathan Westhues. //----------------------------------------------------------------------------- #include "solvespace.h" //----------------------------------------------------------------------------- // Get the list of available font filenames, and load the name for each of // them. Only that, though, not the glyphs too. //----------------------------------------------------------------------------- void TtfFontList::LoadAll(void) { if(loaded) return; // Get the list of font files from the platform-specific code. LoadAllFontFiles(); int i; for(i = 0; i < l.n; i++) { TtfFont *tf = &(l.elem[i]); tf->LoadFontFromFile(true); } loaded = true; } void TtfFontList::PlotString(char *font, char *str, double spacing, SBezierList *sbl, Vector origin, Vector u, Vector v) { LoadAll(); int i; for(i = 0; i < l.n; i++) { TtfFont *tf = &(l.elem[i]); if(strcmp(tf->FontFileBaseName(), font)==0) { tf->LoadFontFromFile(false); tf->PlotString(str, spacing, sbl, origin, u, v); return; } } // Couldn't find the font; so draw a big X for an error marker. SBezier sb; sb = SBezier::From(origin, origin.Plus(u).Plus(v)); sbl->l.Add(&sb); sb = SBezier::From(origin.Plus(v), origin.Plus(u)); sbl->l.Add(&sb); } //============================================================================= //----------------------------------------------------------------------------- // Get a single character from the open .ttf file; EOF is an error, since // we can always see that coming. //----------------------------------------------------------------------------- int TtfFont::Getc(void) { int c = fgetc(fh); if(c == EOF) { throw "EOF"; } return c; } //----------------------------------------------------------------------------- // Helpers to get 1, 2, or 4 bytes from the .ttf file. Big endian. // The BYTE, USHORT and ULONG nomenclature comes from the OpenType spec. //----------------------------------------------------------------------------- uint8_t TtfFont::GetBYTE(void) { return (uint8_t)Getc(); } uint16_t TtfFont::GetUSHORT(void) { uint8_t b0, b1; b1 = (uint8_t)Getc(); b0 = (uint8_t)Getc(); return (uint16_t)(b1 << 8) | b0; } uint32_t TtfFont::GetULONG(void) { uint8_t b0, b1, b2, b3; b3 = (uint8_t)Getc(); b2 = (uint8_t)Getc(); b1 = (uint8_t)Getc(); b0 = (uint8_t)Getc(); return (uint32_t)(b3 << 24) | (uint32_t)(b2 << 16) | (uint32_t)(b1 << 8) | b0; } //----------------------------------------------------------------------------- // Load a glyph from the .ttf file into memory. Assumes that the .ttf file // is already seeked to the correct location, and writes the result to // glyphs[index] //----------------------------------------------------------------------------- void TtfFont::LoadGlyph(int index) { if(index < 0 || index >= glyphs) return; int i; int16_t contours = (int16_t)GetUSHORT(); int16_t xMin = (int16_t)GetUSHORT(); int16_t yMin = (int16_t)GetUSHORT(); int16_t xMax = (int16_t)GetUSHORT(); int16_t yMax = (int16_t)GetUSHORT(); if(useGlyph[(int)'A'] == index) { scale = (1024*1024) / yMax; } if(contours > 0) { uint16_t *endPointsOfContours = (uint16_t *)AllocTemporary(contours*sizeof(uint16_t)); for(i = 0; i < contours; i++) { endPointsOfContours[i] = GetUSHORT(); } uint16_t totalPts = endPointsOfContours[i-1] + 1; uint16_t instructionLength = GetUSHORT(); for(i = 0; i < instructionLength; i++) { // We can ignore the instructions, since we're doing vector // output. (void)GetBYTE(); } uint8_t *flags = (uint8_t *)AllocTemporary(totalPts*sizeof(uint8_t)); int16_t *x = (int16_t *)AllocTemporary(totalPts*sizeof(int16_t)); int16_t *y = (int16_t *)AllocTemporary(totalPts*sizeof(int16_t)); // Flags, that indicate format of the coordinates #define FLAG_ON_CURVE (1 << 0) #define FLAG_DX_IS_BYTE (1 << 1) #define FLAG_DY_IS_BYTE (1 << 2) #define FLAG_REPEAT (1 << 3) #define FLAG_X_IS_SAME (1 << 4) #define FLAG_X_IS_POSITIVE (1 << 4) #define FLAG_Y_IS_SAME (1 << 5) #define FLAG_Y_IS_POSITIVE (1 << 5) for(i = 0; i < totalPts; i++) { flags[i] = GetBYTE(); if(flags[i] & FLAG_REPEAT) { int n = GetBYTE(); uint8_t f = flags[i]; int j; for(j = 0; j < n; j++) { i++; if(i >= totalPts) { throw "too many points in glyph"; } flags[i] = f; } } } // x coordinates int16_t xa = 0; for(i = 0; i < totalPts; i++) { if(flags[i] & FLAG_DX_IS_BYTE) { uint8_t v = GetBYTE(); if(flags[i] & FLAG_X_IS_POSITIVE) { xa += v; } else { xa -= v; } } else { if(flags[i] & FLAG_X_IS_SAME) { // no change } else { int16_t d = (int16_t)GetUSHORT(); xa += d; } } x[i] = xa; } // y coordinates int16_t ya = 0; for(i = 0; i < totalPts; i++) { if(flags[i] & FLAG_DY_IS_BYTE) { uint8_t v = GetBYTE(); if(flags[i] & FLAG_Y_IS_POSITIVE) { ya += v; } else { ya -= v; } } else { if(flags[i] & FLAG_Y_IS_SAME) { // no change } else { int16_t d = (int16_t)GetUSHORT(); ya += d; } } y[i] = ya; } Glyph *g = &(glyph[index]); g->pt = (FontPoint *)MemAlloc(totalPts*sizeof(FontPoint)); int contour = 0; for(i = 0; i < totalPts; i++) { g->pt[i].x = x[i]; g->pt[i].y = y[i]; g->pt[i].onCurve = (uint8_t)(flags[i] & FLAG_ON_CURVE); if(i == endPointsOfContours[contour]) { g->pt[i].lastInContour = true; contour++; } else { g->pt[i].lastInContour = false; } } g->pts = totalPts; g->xMax = xMax; g->xMin = xMin; } else { // This is a composite glyph, TODO. } } //----------------------------------------------------------------------------- // Return the basename of our font filename; that's how the requests and // entities that reference us will store it. //----------------------------------------------------------------------------- const char *TtfFont::FontFileBaseName(void) { char *sb = strrchr(fontFile, '\\'); char *sf = strrchr(fontFile, '/'); char *s = sf ? sf : sb; if(!s) return ""; return s + 1; } //----------------------------------------------------------------------------- // Load a TrueType font into memory. We care about the curves that define // the letter shapes, and about the mappings that determine which glyph goes // with which character. //----------------------------------------------------------------------------- bool TtfFont::LoadFontFromFile(bool nameOnly) { if(loaded) return true; int i; fh = fopen(fontFile, "rb"); if(!fh) { return false; } try { // First, load the Offset Table uint32_t version = GetULONG(); uint16_t numTables = GetUSHORT(); uint16_t searchRange = GetUSHORT(); uint16_t entrySelector = GetUSHORT(); uint16_t rangeShift = GetUSHORT(); // Now load the Table Directory; our goal in doing this will be to // find the addresses of the tables that we will need. uint32_t glyfAddr = (uint32_t)-1, glyfLen; uint32_t cmapAddr = (uint32_t)-1, cmapLen; uint32_t headAddr = (uint32_t)-1, headLen; uint32_t locaAddr = (uint32_t)-1, locaLen; uint32_t maxpAddr = (uint32_t)-1, maxpLen; uint32_t nameAddr = (uint32_t)-1, nameLen; uint32_t hmtxAddr = (uint32_t)-1, hmtxLen; uint32_t hheaAddr = (uint32_t)-1, hheaLen; for(i = 0; i < numTables; i++) { char tag[5] = "xxxx"; tag[0] = (char)GetBYTE(); tag[1] = (char)GetBYTE(); tag[2] = (char)GetBYTE(); tag[3] = (char)GetBYTE(); uint32_t checksum = GetULONG(); uint32_t offset = GetULONG(); uint32_t length = GetULONG(); if(strcmp(tag, "glyf")==0) { glyfAddr = offset; glyfLen = length; } else if(strcmp(tag, "cmap")==0) { cmapAddr = offset; cmapLen = length; } else if(strcmp(tag, "head")==0) { headAddr = offset; headLen = length; } else if(strcmp(tag, "loca")==0) { locaAddr = offset; locaLen = length; } else if(strcmp(tag, "maxp")==0) { maxpAddr = offset; maxpLen = length; } else if(strcmp(tag, "name")==0) { nameAddr = offset; nameLen = length; } else if(strcmp(tag, "hhea")==0) { hheaAddr = offset; hheaLen = length; } else if(strcmp(tag, "hmtx")==0) { hmtxAddr = offset; hmtxLen = length; } } if(glyfAddr == (uint32_t)-1 || cmapAddr == (uint32_t)-1 || headAddr == (uint32_t)-1 || locaAddr == (uint32_t)-1 || maxpAddr == (uint32_t)-1 || hmtxAddr == (uint32_t)-1 || nameAddr == (uint32_t)-1 || hheaAddr == (uint32_t)-1) { throw "missing table addr"; } // Load the name table. This gives us display names for the font, which // we need when we're giving the user a list to choose from. fseek(fh, nameAddr, SEEK_SET); uint16_t nameFormat = GetUSHORT(); uint16_t nameCount = GetUSHORT(); uint16_t nameStringOffset = GetUSHORT(); // And now we're at the name records. Go through those till we find // one that we want. int displayNameOffset = 0, displayNameLength = 0; for(i = 0; i < nameCount; i++) { uint16_t platformID = GetUSHORT(); uint16_t encodingID = GetUSHORT(); uint16_t languageID = GetUSHORT(); uint16_t nameId = GetUSHORT(); uint16_t length = GetUSHORT(); uint16_t offset = GetUSHORT(); if(nameId == 4) { displayNameOffset = offset; displayNameLength = length; break; } } if(nameOnly && i >= nameCount) { throw "no name"; } if(nameOnly) { // Find the display name, and store it in the provided buffer. fseek(fh, nameAddr+nameStringOffset+displayNameOffset, SEEK_SET); int c = 0; for(i = 0; i < displayNameLength; i++) { uint8_t b = GetBYTE(); if(b && c < ((int)sizeof(name.str) - 2)) { name.str[c++] = b; } } name.str[c++] = '\0'; fclose(fh); return true; } // Load the head table; we need this to determine the format of the // loca table, 16- or 32-bit entries fseek(fh, headAddr, SEEK_SET); uint32_t headVersion = GetULONG(); uint32_t headFontRevision = GetULONG(); uint32_t headCheckSumAdj = GetULONG(); uint32_t headMagicNumber = GetULONG(); uint16_t headFlags = GetUSHORT(); uint16_t headUnitsPerEm = GetUSHORT(); (void)GetULONG(); // created time (void)GetULONG(); (void)GetULONG(); // modified time (void)GetULONG(); uint16_t headXmin = GetUSHORT(); uint16_t headYmin = GetUSHORT(); uint16_t headXmax = GetUSHORT(); uint16_t headYmax = GetUSHORT(); uint16_t headMacStyle = GetUSHORT(); uint16_t headLowestRecPPEM = GetUSHORT(); uint16_t headFontDirectionHint = GetUSHORT(); uint16_t headIndexToLocFormat = GetUSHORT(); uint16_t headGlyphDataFormat = GetUSHORT(); if(headMagicNumber != 0x5F0F3CF5) { throw "bad magic number"; } // Load the hhea table, which contains the number of entries in the // horizontal metrics (hmtx) table. fseek(fh, hheaAddr, SEEK_SET); uint32_t hheaVersion = GetULONG(); uint16_t hheaAscender = GetUSHORT(); uint16_t hheaDescender = GetUSHORT(); uint16_t hheaLineGap = GetUSHORT(); uint16_t hheaAdvanceWidthMax = GetUSHORT(); uint16_t hheaMinLsb = GetUSHORT(); uint16_t hheaMinRsb = GetUSHORT(); uint16_t hheaXMaxExtent = GetUSHORT(); uint16_t hheaCaretSlopeRise = GetUSHORT(); uint16_t hheaCaretSlopeRun = GetUSHORT(); uint16_t hheaCaretOffset = GetUSHORT(); (void)GetUSHORT(); (void)GetUSHORT(); (void)GetUSHORT(); (void)GetUSHORT(); uint16_t hheaMetricDataFormat = GetUSHORT(); uint16_t hheaNumberOfMetrics = GetUSHORT(); // Load the maxp table, which determines (among other things) the number // of glyphs in the font fseek(fh, maxpAddr, SEEK_SET); uint32_t maxpVersion = GetULONG(); uint16_t maxpNumGlyphs = GetUSHORT(); uint16_t maxpMaxPoints = GetUSHORT(); uint16_t maxpMaxContours = GetUSHORT(); uint16_t maxpMaxComponentPoints = GetUSHORT(); uint16_t maxpMaxComponentContours = GetUSHORT(); uint16_t maxpMaxZones = GetUSHORT(); uint16_t maxpMaxTwilightPoints = GetUSHORT(); uint16_t maxpMaxStorage = GetUSHORT(); uint16_t maxpMaxFunctionDefs = GetUSHORT(); uint16_t maxpMaxInstructionDefs = GetUSHORT(); uint16_t maxpMaxStackElements = GetUSHORT(); uint16_t maxpMaxSizeOfInstructions = GetUSHORT(); uint16_t maxpMaxComponentElements = GetUSHORT(); uint16_t maxpMaxComponentDepth = GetUSHORT(); glyphs = maxpNumGlyphs; glyph = (Glyph *)MemAlloc(glyphs*sizeof(glyph[0])); // Load the hmtx table, which gives the horizontal metrics (spacing // and advance width) of the font. fseek(fh, hmtxAddr, SEEK_SET); uint16_t hmtxAdvanceWidth = 0; int16_t hmtxLsb = 0; for(i = 0; i < min(glyphs, hheaNumberOfMetrics); i++) { hmtxAdvanceWidth = GetUSHORT(); hmtxLsb = (int16_t)GetUSHORT(); glyph[i].leftSideBearing = hmtxLsb; glyph[i].advanceWidth = hmtxAdvanceWidth; } // The last entry in the table applies to all subsequent glyphs also. for(; i < glyphs; i++) { glyph[i].leftSideBearing = hmtxLsb; glyph[i].advanceWidth = hmtxAdvanceWidth; } // Load the cmap table, which determines the mapping of characters to // glyphs. fseek(fh, cmapAddr, SEEK_SET); uint32_t usedTableAddr = (uint32_t)-1; uint16_t cmapVersion = GetUSHORT(); uint16_t cmapTableCount = GetUSHORT(); for(i = 0; i < cmapTableCount; i++) { uint16_t platformId = GetUSHORT(); uint16_t encodingId = GetUSHORT(); uint32_t offset = GetULONG(); if(platformId == 3 && encodingId == 1) { // The Windows Unicode mapping is our preference usedTableAddr = cmapAddr + offset; } } if(usedTableAddr == (uint32_t)-1) { throw "no used table addr"; } // So we can load the desired subtable; in this case, Windows Unicode, // which is us. fseek(fh, usedTableAddr, SEEK_SET); uint16_t mapFormat = GetUSHORT(); uint16_t mapLength = GetUSHORT(); uint16_t mapVersion = GetUSHORT(); uint16_t mapSegCountX2 = GetUSHORT(); uint16_t mapSearchRange = GetUSHORT(); uint16_t mapEntrySelector = GetUSHORT(); uint16_t mapRangeShift = GetUSHORT(); if(mapFormat != 4) { // Required to use format 4 per spec throw "not format 4"; } int segCount = mapSegCountX2 / 2; uint16_t *endChar = (uint16_t *)AllocTemporary(segCount*sizeof(uint16_t)); uint16_t *startChar = (uint16_t *)AllocTemporary(segCount*sizeof(uint16_t)); uint16_t *idDelta = (uint16_t *)AllocTemporary(segCount*sizeof(uint16_t)); uint16_t *idRangeOffset = (uint16_t *)AllocTemporary(segCount*sizeof(uint16_t)); uint32_t *filePos = (uint32_t *)AllocTemporary(segCount*sizeof(uint32_t)); for(i = 0; i < segCount; i++) { endChar[i] = GetUSHORT(); } uint16_t mapReservedPad = GetUSHORT(); for(i = 0; i < segCount; i++) { startChar[i] = GetUSHORT(); } for(i = 0; i < segCount; i++) { idDelta[i] = GetUSHORT(); } for(i = 0; i < segCount; i++) { filePos[i] = (uint32_t)ftell(fh); idRangeOffset[i] = GetUSHORT(); } // So first, null out the glyph table in our in-memory representation // of the font; any character for which cmap does not provide a glyph // corresponds to -1 for(i = 0; i < (int)arraylen(useGlyph); i++) { useGlyph[i] = 0; } for(i = 0; i < segCount; i++) { uint16_t v = idDelta[i]; if(idRangeOffset[i] == 0) { int j; for(j = startChar[i]; j <= endChar[i]; j++) { if(j > 0 && j < (int)arraylen(useGlyph)) { // Don't create a reference to a glyph that we won't // store because it's bigger than the table. if((uint16_t)(j + v) < glyphs) { // Arithmetic is modulo 2^16 useGlyph[j] = (uint16_t)(j + v); } } } } else { int j; for(j = startChar[i]; j <= endChar[i]; j++) { if(j > 0 && j < (int)arraylen(useGlyph)) { int fp = filePos[i]; fp += (j - startChar[i])*sizeof(uint16_t); fp += idRangeOffset[i]; fseek(fh, fp, SEEK_SET); useGlyph[j] = GetUSHORT(); } } } } // Load the loca table. This contains the offsets of each glyph, // relative to the beginning of the glyf table. fseek(fh, locaAddr, SEEK_SET); uint32_t *glyphOffsets = (uint32_t *)AllocTemporary(glyphs*sizeof(uint32_t)); for(i = 0; i < glyphs; i++) { if(headIndexToLocFormat == 1) { // long offsets, 32 bits glyphOffsets[i] = GetULONG(); } else if(headIndexToLocFormat == 0) { // short offsets, 16 bits but divided by 2 glyphOffsets[i] = GetUSHORT()*2; } else { throw "bad headIndexToLocFormat"; } } scale = 1024; // Load the glyf table. This contains the actual representations of the // letter forms, as piecewise linear or quadratic outlines. for(i = 0; i < glyphs; i++) { fseek(fh, glyfAddr + glyphOffsets[i], SEEK_SET); LoadGlyph(i); } } catch (const char *s) { dbp("ttf: file %s failed: '%s'", fontFile, s); fclose(fh); return false; } fclose(fh); loaded = true; return true; } void TtfFont::Flush(void) { lastWas = NOTHING; } void TtfFont::Handle(int *dx, int x, int y, bool onCurve) { x = ((x + *dx)*scale + 512) >> 10; y = (y*scale + 512) >> 10; if(lastWas == ON_CURVE && onCurve) { // This is a line segment. LineSegment(lastOnCurve.x, lastOnCurve.y, x, y); } else if(lastWas == ON_CURVE && !onCurve) { // We can't do the Bezier until we get the next on-curve point, // but we must store the off-curve point. } else if(lastWas == OFF_CURVE && onCurve) { // We are ready to do a Bezier. Bezier(lastOnCurve.x, lastOnCurve.y, lastOffCurve.x, lastOffCurve.y, x, y); } else if(lastWas == OFF_CURVE && !onCurve) { // Two consecutive off-curve points implicitly have an on-point // curve between them, and that should trigger us to generate a // Bezier. IntPoint fake; fake.x = (x + lastOffCurve.x) / 2; fake.y = (y + lastOffCurve.y) / 2; Bezier(lastOnCurve.x, lastOnCurve.y, lastOffCurve.x, lastOffCurve.y, fake.x, fake.y); lastOnCurve.x = fake.x; lastOnCurve.y = fake.y; } if(onCurve) { lastOnCurve.x = x; lastOnCurve.y = y; lastWas = ON_CURVE; } else { lastOffCurve.x = x; lastOffCurve.y = y; lastWas = OFF_CURVE; } } void TtfFont::PlotCharacter(int *dx, int c, double spacing) { int gli = useGlyph[c]; if(gli < 0 || gli >= glyphs) return; Glyph *g = &(glyph[gli]); if(!g->pt) return; if(c == ' ') { *dx += g->advanceWidth; return; } int dx0 = *dx; // A point that has x = xMin should be plotted at (dx0 + lsb); fix up // our x-position so that the curve-generating code will put stuff // at the right place. *dx = dx0 - g->xMin; *dx += g->leftSideBearing; int i; int firstInContour = 0; for(i = 0; i < g->pts; i++) { Handle(dx, g->pt[i].x, g->pt[i].y, g->pt[i].onCurve); if(g->pt[i].lastInContour) { int f = firstInContour; Handle(dx, g->pt[f].x, g->pt[f].y, g->pt[f].onCurve); firstInContour = i + 1; Flush(); } } // And we're done, so advance our position by the requested advance // width, plus the user-requested extra advance. *dx = dx0 + g->advanceWidth + (int)(spacing + 0.5); } void TtfFont::PlotString(char *str, double spacing, SBezierList *sbl, Vector porigin, Vector pu, Vector pv) { beziers = sbl; u = pu; v = pv; origin = porigin; if(!loaded || !str || *str == '\0') { LineSegment(0, 0, 1024, 0); LineSegment(1024, 0, 1024, 1024); LineSegment(1024, 1024, 0, 1024); LineSegment(0, 1024, 0, 0); return; } int dx = 0; while(*str) { PlotCharacter(&dx, *str, spacing); str++; } } Vector TtfFont::TransformIntPoint(int x, int y) { Vector r = origin; r = r.Plus(u.ScaledBy(x / 1024.0)); r = r.Plus(v.ScaledBy(y / 1024.0)); return r; } void TtfFont::LineSegment(int x0, int y0, int x1, int y1) { SBezier sb = SBezier::From(TransformIntPoint(x0, y0), TransformIntPoint(x1, y1)); beziers->l.Add(&sb); } void TtfFont::Bezier(int x0, int y0, int x1, int y1, int x2, int y2) { SBezier sb = SBezier::From(TransformIntPoint(x0, y0), TransformIntPoint(x1, y1), TransformIntPoint(x2, y2)); beziers->l.Add(&sb); }
gpl-3.0
frozzare/woocommerce
includes/data-stores/class-wc-customer-download-data-store.php
8336
<?php if ( ! defined( 'ABSPATH' ) ) { exit; } /** * WC Customer Download Data Store. * * @version 2.7.0 * @category Class * @author WooThemes */ class WC_Customer_Download_Data_Store implements WC_Customer_Download_Data_Store_Interface { /** * Create dowload permission for a user. * * @param WC_Customer_Download $download */ public function create( &$download ) { global $wpdb; $data = array( 'download_id' => $download->get_download_id( 'edit' ), 'product_id' => $download->get_product_id( 'edit' ), 'user_id' => $download->get_user_id( 'edit' ), 'user_email' => $download->get_user_email( 'edit' ), 'order_id' => $download->get_order_id( 'edit' ), 'order_key' => $download->get_order_key( 'edit' ), 'downloads_remaining' => $download->get_downloads_remaining( 'edit' ), 'access_granted' => date( 'Y-m-d', $download->get_access_granted( 'edit' ) ), 'download_count' => $download->get_download_count( 'edit' ), 'access_expires' => $download->get_access_expires( 'edit' ) ? date( 'Y-m-d', $download->get_access_expires( 'edit' ) ) : null, ); $format = array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', ); $result = $wpdb->insert( $wpdb->prefix . 'woocommerce_downloadable_product_permissions', apply_filters( 'woocommerce_downloadable_file_permission_data', $data ), apply_filters( 'woocommerce_downloadable_file_permission_format', $format, $data ) ); do_action( 'woocommerce_grant_product_download_access', $data ); if ( $result ) { $download->set_id( $wpdb->insert_id ); $download->apply_changes(); } } /** * Method to read a download permission from the database. * * @param WC_Customer_Download */ public function read( &$download ) { global $wpdb; $download->set_defaults(); if ( ! $download->get_id() || ! ( $raw_download = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions WHERE permission_id = %d", $download->get_id() ) ) ) ) { throw new Exception( __( 'Invalid download.', 'woocommerce' ) ); } $download->set_props( $raw_download ); $download->set_object_read( true ); } /** * Method to update a download in the database. * * @param WC_Customer_Download $download */ public function update( &$download ) { global $wpdb; $data = array( 'download_id' => $download->get_download_id( 'edit' ), 'product_id' => $download->get_product_id( 'edit' ), 'user_id' => $download->get_user_id( 'edit' ), 'user_email' => $download->get_user_email( 'edit' ), 'order_id' => $download->get_order_id( 'edit' ), 'order_key' => $download->get_order_key( 'edit' ), 'downloads_remaining' => $download->get_downloads_remaining( 'edit' ), 'access_granted' => date( 'Y-m-d', $download->get_access_granted( 'edit' ) ), 'download_count' => $download->get_download_count( 'edit' ), 'access_expires' => $download->get_access_expires( 'edit' ) ? date( 'Y-m-d', $download->get_access_expires( 'edit' ) ) : null, ); $format = array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', ); $wpdb->update( $wpdb->prefix . 'woocommerce_downloadable_product_permissions', $data, array( 'permission_id' => $download->get_id(), ), $format ); $download->apply_changes(); } /** * Method to delete a download permission from the database. * * @param WC_Customer_Download $download * @param array $args Array of args to pass to the delete method. */ public function delete( &$download, $args = array() ) { global $wpdb; $wpdb->query( $wpdb->prepare( " DELETE FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions WHERE permission_id = %d ", $download->get_id() ) ); $download->set_id( 0 ); } /** * Method to delete a download permission from the database by ID. * * @param int $id */ public function delete_by_id( $id ) { global $wpdb; $wpdb->query( $wpdb->prepare( " DELETE FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions WHERE permission_id = %d ", $id ) ); } /** * Method to delete a download permission from the database by order ID. * * @param int $id */ public function delete_by_order_id( $id ) { global $wpdb; $wpdb->query( $wpdb->prepare( " DELETE FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions WHERE order_id = %d ", $id ) ); } /** * Method to delete a download permission from the database by download ID. * * @param int $id */ public function delete_by_download_id( $id ) { global $wpdb; $wpdb->query( $wpdb->prepare( " DELETE FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions WHERE download_id = %s ", $id ) ); } /** * Get a download object. * * @param array $data From the DB. * @return WC_Customer_Download */ private function get_download( $data ) { return new WC_Customer_Download( $data ); } /** * Get array of download ids by specified args. * * @param array $args * @return array */ public function get_downloads( $args = array() ) { global $wpdb; $args = wp_parse_args( $args, array( 'user_email' => '', 'order_id' => '', 'order_key' => '', 'product_id' => '', 'orderby' => 'permission_id', 'order' => 'DESC', 'limit' => -1, 'return' => 'objects', ) ); extract( $args ); $query = array(); $query[] = "SELECT * FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions WHERE 1=1"; if ( $user_email ) { $query[] = $wpdb->prepare( "AND user_email = %s", $user_email ); } if ( $order_id ) { $query[] = $wpdb->prepare( "AND order_id = %d", $order_id ); } if ( $order_key ) { $query[] = $wpdb->prepare( "AND order_key = %s", $order_key ); } if ( $product_id ) { $query[] = $wpdb->prepare( "AND product_id = %d", $product_id ); } $orderby = esc_sql( $orderby ); $order = esc_sql( $order ); $query[] = "ORDER BY {$orderby} {$order}"; if ( 0 < $limit ) { $query[] = $wpdb->prepare( "LIMIT %d", $limit ); } $raw_downloads = $wpdb->get_results( implode( ' ', $query ) ); switch ( $return ) { case 'ids' : return wp_list_pluck( $raw_downloads, 'permission_id' ); default : return array_map( array( $this, 'get_download' ), $raw_downloads ); } } /** * Update download ids if the hash changes. * * @param int $product_id * @param string $old_id * @param string $new_id */ public function update_download_id( $product_id, $old_id, $new_id ) { global $wpdb; $wpdb->update( $wpdb->prefix . 'woocommerce_downloadable_product_permissions', array( 'download_id' => $new_id, ), array( 'download_id' => $old_id, 'product_id' => $product_id, ) ); } /** * Get a customers downloads. * * @param int $customer_id * @return array */ public function get_downloads_for_customer( $customer_id ) { global $wpdb; return $wpdb->get_results( $wpdb->prepare( " SELECT * FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions as permissions WHERE user_id = %d AND permissions.order_id > 0 AND ( permissions.downloads_remaining > 0 OR permissions.downloads_remaining = '' ) AND ( permissions.access_expires IS NULL OR permissions.access_expires >= %s OR permissions.access_expires = '0000-00-00 00:00:00' ) ORDER BY permissions.order_id, permissions.product_id, permissions.permission_id; ", $customer_id, date( 'Y-m-d', current_time( 'timestamp' ) ) ) ); } /** * Update user prop for downloads based on order id. * * @param int $order_id * @param int $customer_id * @param string $email */ public function update_user_by_order_id( $order_id, $customer_id, $email ) { global $wpdb; $wpdb->update( $wpdb->prefix . 'woocommerce_downloadable_product_permissions', array( 'user_id' => $customer_id, 'user_email' => $email, ), array( 'order_id' => $order_id, ), array( '%d', '%s', ), array( '%d', ) ); } }
gpl-3.0
boudel/pje
classes/PhpEncryption.php
3394
<?php /** * 2007-2016 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <contact@prestashop.com> * @copyright 2007-2016 PrestaShop SA * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ use Defuse\Crypto\Exception\EnvironmentIsBrokenException; /** * Class PhpEncryptionCore for openSSL 1.0.1+. */ class PhpEncryptionCore { const ENGINE = 'PhpEncryptionEngine'; const LEGACY_ENGINE = 'PhpEncryptionLegacyEngine'; private static $engine; /** * PhpEncryptionCore constructor. * * @param string $hexString A string that only contains hexadecimal characters * Bother upper and lower case are allowed */ public function __construct($hexString) { $engineClass = self::resolveEngineToUse(); self::$engine = new $engineClass($hexString); } /** * Encrypt the plaintext. * * @param string $plaintext Plaintext * * @return string Cipher text */ public function encrypt($plaintext) { return self::$engine->encrypt($plaintext); } /** * Decrypt the cipher text. * * @param string $cipherText Cipher text * * @return bool|string Plaintext * `false` if unable to decrypt * * @throws Exception */ public function decrypt($cipherText) { return self::$engine->decrypt($cipherText); } /** * @param $header * @param $bytes * * @return string * * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException */ public static function saveBytesToChecksummedAsciiSafeString($header, $bytes) { $engine = self::resolveEngineToUse(); return $engine::saveBytesToChecksummedAsciiSafeString($header, $bytes); } /** * @return string * @throws Exception * */ public static function createNewRandomKey() { $engine = self::resolveEngineToUse(); try { $randomKey = $engine::createNewRandomKey(); } catch (EnvironmentIsBrokenException $exception) { $buf = $engine::randomCompat(); $randomKey = $engine::saveToAsciiSafeString($buf); } return $randomKey; } /** * Choose which engine use regarding the OpenSSL cipher methods available. */ public static function resolveEngineToUse() { if (false === in_array(\Defuse\Crypto\Core::CIPHER_METHOD, openssl_get_cipher_methods())) { return self::LEGACY_ENGINE; } return self::ENGINE; } }
gpl-3.0
xYalla/KicksEmu
src/main/java/com/neikeq/kicksemu/game/characters/PlayerInfo.java
40562
package com.neikeq.kicksemu.game.characters; import com.neikeq.kicksemu.game.characters.types.PlayerHistory; import com.neikeq.kicksemu.game.characters.types.PlayerStats; import com.neikeq.kicksemu.game.misc.quests.QuestState; import com.neikeq.kicksemu.game.misc.tutorial.TutorialState; import com.neikeq.kicksemu.game.inventory.products.Celebration; import com.neikeq.kicksemu.game.inventory.products.DefaultClothes; import com.neikeq.kicksemu.game.inventory.types.Expiration; import com.neikeq.kicksemu.game.inventory.InventoryManager; import com.neikeq.kicksemu.game.inventory.products.Item; import com.neikeq.kicksemu.game.inventory.types.ItemType; import com.neikeq.kicksemu.game.inventory.products.Skill; import com.neikeq.kicksemu.game.inventory.products.Training; import com.neikeq.kicksemu.game.table.TableManager; import com.neikeq.kicksemu.game.table.OptionInfo; import com.neikeq.kicksemu.game.misc.friendship.FriendsList; import com.neikeq.kicksemu.game.misc.ignored.IgnoredList; import com.neikeq.kicksemu.game.sessions.Session; import com.neikeq.kicksemu.io.Output; import com.neikeq.kicksemu.io.logging.Level; import com.neikeq.kicksemu.storage.ConnectionRef; import com.neikeq.kicksemu.storage.SqlUtils; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; public class PlayerInfo { private static final String TABLE = "characters"; private static final String ITEM_ACTIVE = String.format("(" + "((expiration = %d OR expiration = %d OR expiration = %d) AND usages > 0) OR" + "((expiration = %d OR expiration = %d) AND timestamp_expire > CURRENT_TIMESTAMP) OR" + " expiration = %d)", Expiration.USAGE_10.toInt(), Expiration.USAGE_50.toInt(), Expiration.USAGE_100.toInt(), Expiration.DAYS_7.toInt(), Expiration.DAYS_30.toInt(), Expiration.DAYS_PERM.toInt()); private static final String PRODUCT_ACTIVE = String.format( "(timestamp_expire > CURRENT_TIMESTAMP OR expiration = %d)", Expiration.DAYS_PERM.toInt()); // getters public static int getOwner(int id, ConnectionRef ... con) { return SqlUtils.getInt("owner", TABLE, id, con); } public static String getName(int id, ConnectionRef ... con) { return SqlUtils.getString("name", TABLE, id, con); } public static boolean isBlocked(int id, ConnectionRef ... con) { return SqlUtils.getBoolean("blocked", TABLE, id, con); } public static boolean isVisibleInLobby(int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "SELECT moderator, visible FROM " + TABLE + " WHERE id = ? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); try (ResultSet rs = stmt.executeQuery()) { return rs.next() && (!rs.getBoolean("moderator") || rs.getBoolean("visible")); } } } catch (SQLException e) { return false; } } public static boolean isModerator(int id, ConnectionRef ... con) { return SqlUtils.getBoolean("moderator", TABLE, id, con); } public static boolean isVisible(int id, ConnectionRef ... con) { return SqlUtils.getBoolean("visible", TABLE, id, con); } public static short getLevel(int id, ConnectionRef ... con) { return SqlUtils.getShort("level", TABLE, id, con); } public static short getPosition(int id, ConnectionRef ... con) { return SqlUtils.getShort("position", TABLE, id, con); } public static QuestState getQuestState(int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "SELECT quest_current, quest_matches_left FROM " + TABLE + " WHERE id = ? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); try (ResultSet rs = stmt.executeQuery()) { return rs.next() ? new QuestState(rs.getShort("quest_current"), rs.getShort("quest_matches_left")) : new QuestState(); } } } catch (SQLException e) { return new QuestState(); } } public static TutorialState getTutorialState(int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "SELECT tutorial_dribbling, tutorial_passing, tutorial_shooting, " + "tutorial_defense FROM " + TABLE + " WHERE id = ? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); try (ResultSet rs = stmt.executeQuery()) { return rs.next() ? new TutorialState( rs.getByte("tutorial_dribbling"), rs.getByte("tutorial_passing"), rs.getByte("tutorial_shooting"), rs.getByte("tutorial_defense")) : new TutorialState(); } } } catch (SQLException e) { return new TutorialState(); } } public static boolean getReceivedReward(int id, ConnectionRef ... con) { return SqlUtils.getBoolean("received_reward", TABLE, id, con); } public static int getExperience(int id, ConnectionRef ... con) { return SqlUtils.getInt("experience", TABLE, id, con); } public static int getPoints(int id, ConnectionRef ... con) { return SqlUtils.getInt("points", TABLE, id, con); } public static short getTicketsCash(int id, ConnectionRef ... con) { return SqlUtils.getShort("tickets_kash", TABLE, id, con); } public static short getTicketsPoints(int id, ConnectionRef ... con) { return SqlUtils.getShort("tickets_points", TABLE, id, con); } public static short getAnimation(int id, ConnectionRef ... con) { return SqlUtils.getShort("animation", TABLE, id, con); } public static short getFace(int id, ConnectionRef ... con) { return SqlUtils.getShort("face", TABLE, id, con); } public static DefaultClothes getDefaultClothes(int id, ConnectionRef ... con) { DefaultClothes defaultClothes; try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "SELECT default_head, default_shirts, default_pants, " + "default_shoes FROM " + TABLE + " WHERE id = ? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); try (ResultSet rs = stmt.executeQuery()) { defaultClothes = rs.next() ? new DefaultClothes( rs.getInt("default_head"), rs.getInt("default_shirts"), rs.getInt("default_pants"), rs.getInt("default_shoes")) : new DefaultClothes(-1, -1, -1, -1); } } } catch (SQLException e) { defaultClothes = new DefaultClothes(-1, -1, -1, -1); } return defaultClothes; } public static byte getSkillSlots(Map<Integer, Item> itemList) { Iterator<Item> items = itemList.values().stream() .filter(i -> (i.getId() == 2021010) && i.isSelected()).iterator(); // Default and minimum skill slots is 6 byte slots = 6; while (items.hasNext()) { Item item = items.next(); slots += TableManager.getOptionInfo(oi -> oi.getId() == item.getBonusOne()) .map(OptionInfo::getValue).orElse((short) 0); } return slots; } public static Item getItemInUseByType(ItemType type, Session session, ConnectionRef ... con) { Optional<Item> result = session.getCache().getItems(con).values().stream() .filter(item -> TableManager.getItemInfo(i -> i.getId() == item.getId()) .map(itemInfo -> (itemInfo.getType() == type.toInt()) && item.isSelected()) .orElse(false)) .findFirst(); return result.map(item -> item).orElse(null); } public static Item getItemHead(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.HEAD, session, con); } public static Item getItemGlasses(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.GLASSES, session, con); } public static Item getItemShirts(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.SHIRTS, session, con); } public static Item getItemPants(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.PANTS, session, con); } public static Item getItemGlove(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.GLOVES, session, con); } public static Item getItemShoes(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.SHOES, session, con); } public static Item getItemSocks(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.SOCKS, session, con); } public static Item getItemWrist(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.WRIST, session, con); } public static Item getItemArm(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.ARM, session, con); } public static Item getItemKnee(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.KNEE, session, con); } public static Item getItemEar(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.EAR, session, con); } public static Item getItemNeck(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.NECK, session, con); } public static Item getItemMask(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.MASK, session, con); } public static Item getItemMuffler(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.MUFFLER, session, con); } public static Item getItemPackage(Session session, ConnectionRef ... con) { return getItemInUseByType(ItemType.PACKAGE, session, con); } public static short getStatsPoints(int id, ConnectionRef ... con) { return SqlUtils.getShort("stats_points", TABLE, id, con); } public static PlayerStats getStats(int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "SELECT stats_running, stats_endurance, stats_agility, " + "stats_ball_control, stats_dribbling, stats_stealing, stats_tackling, " + "stats_heading, stats_short_shots, stats_long_shots, stats_crossing, " + "stats_short_passes, stats_long_passes, stats_marking, stats_goalkeeping, " + "stats_punching, stats_defense FROM " + TABLE + " WHERE id = ? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); try (ResultSet rs = stmt.executeQuery()) { return rs.next() ? new PlayerStats( rs.getShort("stats_running"), rs.getShort("stats_endurance"), rs.getShort("stats_agility"), rs.getShort("stats_ball_control"), rs.getShort("stats_dribbling"), rs.getShort("stats_stealing"), rs.getShort("stats_tackling"), rs.getShort("stats_heading"), rs.getShort("stats_short_shots"), rs.getShort("stats_long_shots"), rs.getShort("stats_crossing"), rs.getShort("stats_short_passes"), rs.getShort("stats_long_passes"), rs.getShort("stats_marking"), rs.getShort("stats_goalkeeping"), rs.getShort("stats_punching"), rs.getShort("stats_defense")) : new PlayerStats(); } } } catch (SQLException e) { return new PlayerStats(); } } public static PlayerStats getTrainingStats(Session session, ConnectionRef ... con) { PlayerStats learnStats = new PlayerStats(); session.getCache().getLearns(con).values().stream().forEach(learn -> TableManager.getLearnInfo(l -> l.getId() == learn.getId()) .ifPresent(learnInfo -> CharacterUtils.sumStatsByIndex(learnInfo.getStatIndex(), learnInfo.getStatPoints(), learnStats))); return learnStats; } public static PlayerStats getBonusStats(Session session, ConnectionRef ... con) { PlayerStats bonusStats = new PlayerStats(); session.getCache().getItems(con).values().stream().filter(Item::isSelected).forEach(item -> { TableManager.getOptionInfo(of -> of.getId() == item.getBonusOne()) .ifPresent(optionInfoOne -> CharacterUtils.sumStatsByIndex(optionInfoOne.getType() - 10, optionInfoOne.getValue(), bonusStats)); TableManager.getOptionInfo(of -> of.getId() == item.getBonusTwo()) .ifPresent(optionInfoTwo -> CharacterUtils.sumStatsByIndex(optionInfoTwo.getType() - 10, optionInfoTwo.getValue(), bonusStats)); }); return bonusStats; } public static PlayerHistory getHistory(int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "SELECT history_matches, history_wins, history_draws, history_MOM, " + "history_valid_goals, history_valid_assists, history_valid_interception, " + "history_valid_shooting, history_valid_stealing, history_valid_tackling, " + "history_shooting, history_stealing, history_tackling, history_total_points " + "FROM " + TABLE + " WHERE id = ? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); try (ResultSet rs = stmt.executeQuery()) { return rs.next() ? new PlayerHistory( rs.getInt("history_matches"), rs.getInt("history_wins"), rs.getInt("history_draws"), rs.getInt("history_MOM"), rs.getInt("history_valid_goals"), rs.getInt("history_valid_assists"), rs.getInt("history_valid_interception"), rs.getInt("history_valid_shooting"), rs.getInt("history_valid_stealing"), rs.getInt("history_valid_tackling"), rs.getInt("history_shooting"), rs.getInt("history_stealing"), rs.getInt("history_tackling"), rs.getInt("history_total_points")) : new PlayerHistory(); } } } catch (SQLException e) { return new PlayerHistory(); } } public static PlayerHistory getMonthHistory(int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "SELECT history_month_matches, history_month_wins, " + "history_month_draws, history_month_MOM, history_month_valid_goals, " + "history_month_valid_assists, history_month_valid_interception, " + "history_month_valid_shooting, history_month_valid_stealing, " + "history_month_valid_tackling, history_month_shooting, " + "history_month_stealing, history_month_tackling, history_month_total_points " + "FROM " + TABLE + " WHERE id = ? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); try (ResultSet rs = stmt.executeQuery()) { return rs.next() ? new PlayerHistory( rs.getInt("history_month_matches"), rs.getInt("history_month_wins"), rs.getInt("history_month_draws"), rs.getInt("history_month_MOM"), rs.getInt("history_month_valid_goals"), rs.getInt("history_month_valid_assists"), rs.getInt("history_month_valid_interception"), rs.getInt("history_month_valid_shooting"), rs.getInt("history_month_valid_stealing"), rs.getInt("history_month_valid_tackling"), rs.getInt("history_month_shooting"), rs.getInt("history_month_stealing"), rs.getInt("history_month_tackling"), rs.getInt("history_month_total_points")) : new PlayerHistory(); } } } catch (SQLException e) { return new PlayerHistory(); } } public static String getStatusMessage(int id, ConnectionRef ... con) { return SqlUtils.getString("status_message", TABLE, id, con); } public static Map<Integer, Item> getInventoryItems(int id, ConnectionRef ... con) { Map<Integer, Item> items = new LinkedHashMap<>(); final String query = "SELECT * FROM items WHERE player_id = ? AND " + ITEM_ACTIVE + " LIMIT " + InventoryManager.MAX_INVENTORY_ITEMS; try (ConnectionRef connection = ConnectionRef.ref(con)) { try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { Item item = new Item(rs.getInt("item_id"), rs.getInt("inventory_id"), rs.getInt("expiration"), rs.getInt("bonus_one"), rs.getInt("bonus_two"), rs.getShort("usages"), rs.getTimestamp("timestamp_expire"), rs.getBoolean("selected"), rs.getBoolean("visible")); items.put(item.getInventoryId(), item); } } } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } return items; } public static Map<Integer, Training> getInventoryTraining(int id, ConnectionRef ... con) { Map<Integer, Training> learns = new LinkedHashMap<>(); try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "SELECT * FROM learns WHERE player_id = ?"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { Training skill = new Training(rs.getInt("learn_id"), rs.getInt("inventory_id"), rs.getBoolean("visible")); learns.put(skill.getInventoryId(), skill); } } } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } return learns; } public static Map<Integer, Skill> getInventorySkills(Session session, ConnectionRef ... con) { Map<Integer, Skill> skills = new LinkedHashMap<>(); byte slots = getSkillSlots(session.getCache().getItems(con)); try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "SELECT * FROM skills WHERE player_id = ? AND " + PRODUCT_ACTIVE; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, session.getPlayerId()); try (ResultSet rs = stmt.executeQuery()) { byte slotsUsed = 0; while (rs.next()) { byte selectionIndex = rs.getByte("selection_index"); if (selectionIndex > 0) { if (slotsUsed >= slots) { selectionIndex = 0; } else { slotsUsed++; } } Skill skill = new Skill( rs.getInt("skill_id"), rs.getInt("inventory_id"), rs.getInt("expiration"), selectionIndex, rs.getTimestamp("timestamp_expire"), rs.getBoolean("visible")); skills.put(skill.getInventoryId(), skill); } } } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } return skills; } public static Map<Integer, Celebration> getInventoryCelebration(int id, ConnectionRef ... con) { Map<Integer, Celebration> celebrations = new LinkedHashMap<>(); try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "SELECT * FROM ceres WHERE player_id = ? AND " + PRODUCT_ACTIVE; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { Celebration cele = new Celebration( rs.getInt("cere_id"), rs.getInt("inventory_id"), rs.getInt("expiration"), rs.getByte("selection_index"), rs.getTimestamp("timestamp_expire"), rs.getBoolean("visible")); celebrations.put(cele.getInventoryId(), cele); } } } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } return celebrations; } public static FriendsList getFriendsList(int id, ConnectionRef ... con) { return FriendsList.fromString(SqlUtils.getString("friends_list", TABLE, id, con), id); } public static IgnoredList getIgnoredList(int id, ConnectionRef ... con) { return IgnoredList.fromString(SqlUtils.getString("ignored_list", TABLE, id, con), id); } // setters public static void setVisible(boolean value, int id, ConnectionRef ... con) { SqlUtils.setBoolean("visible", value, TABLE, id, con); } public static void setLevel(short value, int id, ConnectionRef ... con) { SqlUtils.setShort("level", value, TABLE, id, con); } public static void setPosition(short value, int id, ConnectionRef ... con) { SqlUtils.setShort("position", value, TABLE, id, con); } public static void setQuestState(QuestState questState, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "UPDATE " + TABLE + " SET quest_current=?, quest_matches_left=? " + "WHERE id = ? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setShort(1, questState.getCurrentQuest()); stmt.setShort(2, questState.getRemainMatches()); stmt.setInt(3, id); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void setTutorialState(TutorialState tutorial, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "UPDATE " + TABLE + " SET tutorial_dribbling=?, tutorial_passing=?, " + "tutorial_shooting=?, tutorial_defense=? WHERE id=? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setByte(1, tutorial.getDribbling()); stmt.setByte(2, tutorial.getPassing()); stmt.setByte(3, tutorial.getShooting()); stmt.setByte(4, tutorial.getDefense()); stmt.setInt(5, id); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void setReceivedReward(boolean value, int id, ConnectionRef ... con) { SqlUtils.setBoolean("received_reward", value, TABLE, id, con); } public static void sumRewards(int experience, int points, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "UPDATE " + TABLE + " SET experience = experience + ?, " + "points = points + ? WHERE id = ? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, (experience >= 0) ? experience : 0); stmt.setInt(2, (points >= 0) ? points : 0); stmt.setInt(3, id); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void sumPoints(int value, int id, ConnectionRef ... con) { SqlUtils.sumInt("points", value, TABLE, id, con); } public static void setTicketsCash(short value, int id, ConnectionRef ... con) { SqlUtils.setShort("tickets_kash", value, TABLE, id, con); } public static void setTicketsPoints(short value, int id, ConnectionRef ... con) { SqlUtils.setShort("tickets_points", value, TABLE, id, con); } public static void setFace(short value, int id, ConnectionRef ... con) { SqlUtils.setShort("face", value, TABLE, id, con); } public static void setStatsPoints(short value, int id, ConnectionRef ... con) { SqlUtils.setShort("stats_points", value, TABLE, id, con); } public static void setStats(PlayerStats stats, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "UPDATE " + TABLE + " SET stats_running = ?, stats_endurance = ?, " + "stats_agility = ?, stats_ball_control = ?, stats_dribbling = ?," + "stats_stealing = ?, stats_tackling = ?, stats_heading = ?, " + "stats_short_shots = ?, stats_long_shots = ?, stats_crossing = ?, " + "stats_short_passes = ?, stats_long_passes = ?, stats_marking = ?," + "stats_goalkeeping = ?, stats_punching = ?, stats_defense = ? " + "WHERE id = ? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setShort(1, stats.getRunning()); stmt.setShort(2, stats.getEndurance()); stmt.setShort(3, stats.getAgility()); stmt.setShort(4, stats.getBallControl()); stmt.setShort(5, stats.getDribbling()); stmt.setShort(6, stats.getStealing()); stmt.setShort(7, stats.getTackling()); stmt.setShort(8, stats.getHeading()); stmt.setShort(9, stats.getShortShots()); stmt.setShort(10, stats.getLongShots()); stmt.setShort(11, stats.getCrossing()); stmt.setShort(12, stats.getShortPasses()); stmt.setShort(13, stats.getLongPasses()); stmt.setShort(14, stats.getMarking()); stmt.setShort(15, stats.getGoalkeeping()); stmt.setShort(16, stats.getPunching()); stmt.setShort(17, stats.getDefense()); stmt.setInt(18, id); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void sumHistory(PlayerHistory history, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "UPDATE " + TABLE + " SET history_matches = history_matches + ?, " + "history_wins = history_wins + ?, history_draws = history_draws + ?, " + "history_MOM = history_MOM + ?, history_valid_goals = history_valid_goals + ?, " + "history_valid_assists = history_valid_assists + ?, " + "history_valid_interception = history_valid_interception + ?, " + "history_valid_shooting = history_valid_shooting + ?, " + "history_valid_stealing = history_valid_stealing + ?, " + "history_valid_tackling = history_valid_tackling + ?, " + "history_shooting = history_shooting + ?, " + "history_stealing = history_stealing + ?, " + "history_tackling = history_tackling + ?, " + "history_total_points = history_total_points + ?, " + "history_month_matches = history_month_matches + ?, " + "history_month_wins = history_month_wins + ?, " + "history_month_draws = history_month_draws + ?, " + "history_month_MOM = history_month_MOM + ?, " + "history_month_valid_goals = history_month_valid_goals + ?, " + "history_month_valid_assists = history_month_valid_assists + ?, " + "history_month_valid_interception = history_month_valid_interception + ?, " + "history_month_valid_shooting = history_month_valid_shooting + ?, " + "history_month_valid_stealing = history_month_valid_stealing + ?, " + "history_month_valid_tackling = history_month_valid_tackling + ?, " + "history_month_shooting = history_month_shooting + ?, " + "history_month_stealing = history_month_stealing + ?, " + "history_month_tackling = history_month_tackling + ?, " + "history_month_total_points = history_month_total_points + ?" + " WHERE id = ? LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, history.getMatches()); stmt.setInt(2, history.getWins()); stmt.setInt(3, history.getDraws()); stmt.setInt(4, history.getMom()); stmt.setInt(5, history.getValidGoals()); stmt.setInt(6, history.getValidAssists()); stmt.setInt(7, history.getValidInterception()); stmt.setInt(8, history.getValidShooting()); stmt.setInt(9, history.getValidStealing()); stmt.setInt(10, history.getValidTackling()); stmt.setInt(11, history.getShooting()); stmt.setInt(12, history.getStealing()); stmt.setInt(13, history.getTackling()); stmt.setInt(14, history.getTotalPoints()); stmt.setInt(15, history.getMatches()); stmt.setInt(16, history.getWins()); stmt.setInt(17, history.getDraws()); stmt.setInt(18, history.getMom()); stmt.setInt(19, history.getValidGoals()); stmt.setInt(20, history.getValidAssists()); stmt.setInt(21, history.getValidInterception()); stmt.setInt(22, history.getValidShooting()); stmt.setInt(23, history.getValidStealing()); stmt.setInt(24, history.getValidTackling()); stmt.setInt(25, history.getShooting()); stmt.setInt(26, history.getStealing()); stmt.setInt(27, history.getTackling()); stmt.setInt(28, history.getTotalPoints()); stmt.setInt(29, id); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void sumStatsPoints(short value, int id, ConnectionRef ... con) { SqlUtils.sumShort("stats_points", value, TABLE, id, con); } public static void setStatusMessage(String value, int id, ConnectionRef ... con) { SqlUtils.setString("status_message", value, TABLE, id, con); } public static void addInventoryItem(Item item, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "INSERT INTO items VALUES(?,?,?,?,?,?,?,?,?,?)"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); stmt.setInt(2, item.getInventoryId()); stmt.setInt(3, item.getId()); stmt.setInt(4, item.getExpiration().toInt()); stmt.setInt(5, item.getBonusOne()); stmt.setInt(6, item.getBonusTwo()); stmt.setShort(7, item.getUsages()); stmt.setTimestamp(8, item.getTimestampExpire()); stmt.setBoolean(9, item.isSelected()); stmt.setBoolean(10, item.isVisible()); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void setInventoryItem(Item item, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "UPDATE items SET " + "bonus_one=?, bonus_two=?, usages=?, timestamp_expire=?, selected=? " + "WHERE player_id=? AND inventory_id=? AND " + ITEM_ACTIVE + " LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, item.getBonusOne()); stmt.setInt(2, item.getBonusTwo()); stmt.setShort(3, item.getUsages()); stmt.setTimestamp(4, item.getTimestampExpire()); stmt.setBoolean(5, item.isSelected()); stmt.setInt(6, id); stmt.setInt(7, item.getInventoryId()); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void removeInventoryItem(Item item, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "DELETE FROM items WHERE player_id = ? AND inventory_id = ?;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); stmt.setInt(2, item.getInventoryId()); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void addInventoryTraining(Training training, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "INSERT INTO learns VALUES(?,?,?,?)"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); stmt.setInt(2, training.getInventoryId()); stmt.setInt(3, training.getId()); stmt.setBoolean(4, training.isVisible()); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void addInventorySkill(Skill skill, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "INSERT INTO skills VALUES(?,?,?,?,?,?,?)"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); stmt.setInt(2, skill.getInventoryId()); stmt.setInt(3, skill.getId()); stmt.setInt(4, skill.getExpiration().toInt()); stmt.setByte(5, skill.getSelectionIndex()); stmt.setTimestamp(6, skill.getTimestampExpire()); stmt.setBoolean(7, skill.isVisible()); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void setInventorySkill(Skill skill, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "UPDATE skills SET selection_index=?, timestamp_expire=? " + "WHERE player_id=? AND inventory_id=? AND " + PRODUCT_ACTIVE + " LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setByte(1, skill.getSelectionIndex()); stmt.setTimestamp(2, skill.getTimestampExpire()); stmt.setInt(3, id); stmt.setInt(4, skill.getInventoryId()); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void addInventoryCele(Celebration cele, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "INSERT INTO ceres VALUES(?,?,?,?,?,?,?)"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setInt(1, id); stmt.setInt(2, cele.getInventoryId()); stmt.setInt(3, cele.getId()); stmt.setInt(4, cele.getExpiration().toInt()); stmt.setByte(5, cele.getSelectionIndex()); stmt.setTimestamp(6, cele.getTimestampExpire()); stmt.setBoolean(7, cele.isVisible()); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void setInventoryCele(Celebration cele, int id, ConnectionRef ... con) { try (ConnectionRef connection = ConnectionRef.ref(con)) { final String query = "UPDATE ceres SET selection_index=?, timestamp_expire=? " + "WHERE player_id=? AND inventory_id=? AND " + PRODUCT_ACTIVE + " LIMIT 1;"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setByte(1, cele.getSelectionIndex()); stmt.setTimestamp(2, cele.getTimestampExpire()); stmt.setInt(3, id); stmt.setInt(4, cele.getInventoryId()); stmt.executeUpdate(); } } catch (SQLException e) { Output.println(e.getMessage(), Level.DEBUG); } } public static void setFriendsList(FriendsList value, int id, ConnectionRef ... con) { SqlUtils.setString("friends_list", value.toString(), TABLE, id, con); } public static void setIgnoredList(IgnoredList value, int id, ConnectionRef ... con) { SqlUtils.setString("ignored_list", value.toString(), TABLE, id, con); } }
gpl-3.0
SkyLightMCPE/SkyLightPM
src/pocketmine/network/protocol/BlockEventPacket.php
1252
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * 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. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ namespace pocketmine\network\protocol; #include <rules/DataPacket.h> class BlockEventPacket extends DataPacket{ const NETWORK_ID = Info::BLOCK_EVENT_PACKET; public $x; public $y; public $z; public $case1; public $case2; public function decode(){ } public function encode(){ $this->reset(); $this->putBlockCoords($this->x, $this->y, $this->z); $this->putVarInt($this->case1); $this->putVarInt($this->case2); } /** * @return PacketName|string */ public function getName(){ return "BlockEventPacket"; } }
gpl-3.0
aelred/grakn
grakn-test/src/test/java/ai/grakn/graphs/MatrixGraphII.java
3091
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn 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. * * Grakn 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 Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.graphs; import ai.grakn.GraknGraph; import ai.grakn.GraknGraphFactory; import ai.grakn.concept.ConceptId; import ai.grakn.concept.EntityType; import ai.grakn.concept.Instance; import ai.grakn.concept.RelationType; import ai.grakn.concept.RoleType; import ai.grakn.concept.TypeName; import java.util.function.Consumer; public class MatrixGraphII extends TestGraph { private final static TypeName key = TypeName.of("index"); private final static String gqlFile = "matrix-testII.gql"; private final int n; private final int m; public MatrixGraphII(int n, int m){ this.m = m; this.n = n; } public static Consumer<GraknGraph> get(int n, int m) { return new MatrixGraphII(n, m).build(); } @Override public Consumer<GraknGraph> build(){ return (GraknGraph graph) -> { loadFromFile(graph, gqlFile); buildExtensionalDB(graph, n, m); }; } private void buildExtensionalDB(GraknGraph graph, int n, int m) { RoleType Qfrom = graph.getRoleType("Q-from"); RoleType Qto = graph.getRoleType("Q-to"); EntityType aEntity = graph.getEntityType("a-entity"); RelationType Q = graph.getRelationType("Q"); ConceptId[][] aInstancesIds = new ConceptId[n+1][m+1]; Instance aInst = putEntity(graph, "a", graph.getEntityType("entity2"), key); for(int i = 1 ; i <= n ;i++) for(int j = 1 ; j <= m ;j++) aInstancesIds[i][j] = putEntity(graph, "a" + i + "," + j, aEntity, key).getId(); Q.addRelation() .putRolePlayer(Qfrom, aInst) .putRolePlayer(Qto, graph.getConcept(aInstancesIds[1][1])); for(int i = 1 ; i <= n ; i++) { for (int j = 1; j <= m; j++) { if ( i < n ) { Q.addRelation() .putRolePlayer(Qfrom, graph.getConcept(aInstancesIds[i][j])) .putRolePlayer(Qto, graph.getConcept(aInstancesIds[i+1][j])); } if ( j < m){ Q.addRelation() .putRolePlayer(Qfrom, graph.getConcept(aInstancesIds[i][j])) .putRolePlayer(Qto, graph.getConcept(aInstancesIds[i][j+1])); } } } } }
gpl-3.0
xrunuo/xrunuo
Scripts/Distro/Items/Resources/Imbuing/VialOfVitriol.cs
792
using System; using Server; namespace Server.Items { public class VialOfVitriol : Item, ICommodity { public override int LabelNumber { get { return 1113331; } } // vial of vitriol [Constructable] public VialOfVitriol() : this( 1 ) { } [Constructable] public VialOfVitriol( int amount ) : base( 0x5722 ) { Weight = 0.1; Stackable = true; Amount = amount; } public VialOfVitriol( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); /*int version = */ reader.ReadInt(); } } }
gpl-3.0
gwpy/gwpy
gwpy/astro/__init__.py
1909
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2014-2020) # # This file is part of GWpy. # # GWpy 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. # # GWpy 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 GWpy. If not, see <http://www.gnu.org/licenses/>. """The `astro` module provides methods for sensitivity calculations of gravitational-wave interferometer data. The LIGO project measures time-dependent sensitivity by calculating the distance at which the gravitational-wave signature of a binary neutron star (BNS) inspiral would be recorded by an instrument with a signal-to-noise ratio (SNR) of 8. In most of the literature, this is known as the 'inspiral range' or the 'horizon distance'. The following methods are provided in order to calculate the sensitive distance range of a detector .. autosummary:: ~gwpy.astro.burst_range ~gwpy.astro.burst_range_spectrum ~gwpy.astro.inspiral_range ~gwpy.astro.inspiral_range_psd ~gwpy.astro.sensemon_range ~gwpy.astro.sensemon_range_psd ~gwpy.astro.range_timeseries ~gwpy.astro.range_spectrogram Each of the above methods has been given default parameters corresponding to the standard usage by the LIGO project. """ from .range import ( burst_range, burst_range_spectrum, inspiral_range, inspiral_range_psd, sensemon_range, sensemon_range_psd, range_timeseries, range_spectrogram, ) __author__ = 'Duncan Macleod <duncan.macleod@ligo.org>'
gpl-3.0
zhijunh/eacopenemr
interface/main/messages/messages.php
26259
<?php /** * Copyright (C) 2010 OpenEMR Support 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 2 * of the License, or (at your option) any later version. * * 2013/02/08 Minor tweaks by EMR Direct to allow integration with Direct messaging * 2013-03-27 by sunsetsystems: Fixed some weirdness with assigning a message recipient, * and allowing a message to be closed with a new note appended and no recipient. */ //SANITIZE ALL ESCAPES $sanitize_all_escapes=true; //STOP FAKE REGISTER GLOBALS $fake_register_globals=false; require_once("../../globals.php"); require_once("$srcdir/pnotes.inc"); require_once("$srcdir/patient.inc"); require_once("$srcdir/acl.inc"); require_once("$srcdir/log.inc"); require_once("$srcdir/options.inc.php"); require_once("$srcdir/formdata.inc.php"); require_once("$srcdir/classes/Document.class.php"); require_once("$srcdir/gprelations.inc.php"); require_once("$srcdir/formatting.inc.php"); ?> <html> <head> <?php html_header_show();?> <link rel="stylesheet" href="<?php echo $css_header;?>" type="text/css"> <script type="text/javascript" src="../../../library/dialog.js"></script> <script type="text/javascript" src="../../../library/textformat.js"></script> <script type="text/javascript" src="<?php echo $GLOBALS['webroot']; ?>/library/js/jquery.js"></script> </head> <body class="body_top"> <table width="100%" height="100%" border="0" > <tr> <td class="messages" > <?php // TajEmo Work by CB 2012/01/11 02:51:25 PM adding dated reminders // I am asuming that at this point security checks have been performed require_once '../dated_reminders/dated_reminders.php'; // Check to see if the user has Admin rights, and if so, allow access to See All. $showall = isset($_GET['show_all']) ? $_GET['show_all'] : "" ; if ($showall == "yes") { $show_all = $showall; } else { $show_all= "no"; } // Collect active variable and applicable html code for links $form_active = (isset($_REQUEST['form_active']) ? $_REQUEST['form_active'] : FALSE); $form_inactive = (isset($_REQUEST['form_inactive']) ? $_REQUEST['form_inactive'] : FALSE); if ($form_active) { $active = '1'; $activity_string_html = 'form_active=1'; } else if ($form_inactive) { $active = '0'; $activity_string_html = 'form_inactive=1'; } else { $active = 'all'; $activity_string_html = ''; } //collect the task setting $task= isset($_REQUEST['task']) ? $_REQUEST['task'] : ""; if (acl_check('admin', 'super' )) { if ($show_all=='yes') { $showall = "yes"; $lnkvar="'messages.php?show_all=no&$activity_string_html' name='Just Mine' onclick=\"top.restoreSession()\"> (".htmlspecialchars( xl('Just Mine'), ENT_NOQUOTES).")"; } else { $showall = "no"; $lnkvar="'messages.php?show_all=yes&$activity_string_html' name='See All' onclick=\"top.restoreSession()\"> (".htmlspecialchars( xl('See All'), ENT_NOQUOTES).")"; } } ?> <br> <table> <tr> <td><span class="title"><?php echo htmlspecialchars( xl('Messages'), ENT_NOQUOTES); ?></span> <a class='more' href=<?php echo $lnkvar; ?></a></a></td> </tr> </table> <?php //show the activity links if (empty($task) || $task=="add" || $task=="delete") { ?> <?php if ($active == "all") { ?> <span class="show"><?php echo xlt('Show All'); ?></span> <?php } else { ?> <a href="messages.php" class="link" onClick="top.restoreSession()"><span><?php echo xlt('Show All'); ?></span></a> <?php } ?> | <?php if ($active == '1') { ?> <span class="show"><?php echo xlt('Show Active'); ?></span> <?php } else { ?> <a href="messages.php?form_active=1" class="link" onClick="top.restoreSession()"><span><?php echo xlt('Show Active'); ?></span></a> <?php } ?> | <?php if ($active == '0') { ?> <span class="show"><?php echo xlt('Show Inactive'); ?></span> <?php } else { ?> <a href="messages.php?form_inactive=1" class="link" onClick="top.restoreSession()"><span><?php echo xlt('Show Inactive'); ?></span></a> <?php } ?> <?php } ?> <?php switch($task) { case "add" : { // Add a new message for a specific patient; the message is documented in Patient Notes. // Add a new message; it's treated as a new note in Patient Notes. $note = $_POST['note']; $noteid = $_POST['noteid']; $form_note_type = $_POST['form_note_type']; $form_message_status = $_POST['form_message_status']; $reply_to = $_POST['reply_to']; $assigned_to_list = explode(';', $_POST['assigned_to']); foreach($assigned_to_list as $assigned_to){ if ($noteid && $assigned_to != '-patient-') { updatePnote($noteid, $note, $form_note_type, $assigned_to, $form_message_status); $noteid = ''; } else { if($noteid && $assigned_to == '-patient-'){ // When $assigned_to == '-patient-' we don't update the current note, but // instead create a new one with the current note's body prepended and // attributed to the patient. This seems to be all for the patient portal. $row = getPnoteById($noteid); if (! $row) die("getPnoteById() did not find id '".text($noteid)."'"); $pres = sqlQuery("SELECT lname, fname " . "FROM patient_data WHERE pid = ?", array($reply_to) ); $patientname = $pres['lname'] . ", " . $pres['fname']; $note .= "\n\n$patientname on ".$row['date']." wrote:\n\n"; $note .= $row['body']; } // There's no note ID, and/or it's assigned to the patient. // In these cases a new note is created. addPnote($reply_to, $note, $userauthorized, '1', $form_note_type, $assigned_to, '', $form_message_status); } } } break; case "savePatient": case "save" : { // Update alert. $noteid = $_POST['noteid']; $form_message_status = $_POST['form_message_status']; $reply_to = $_POST['reply_to']; if ($task=="save") updatePnoteMessageStatus($noteid,$form_message_status); else updatePnotePatient($noteid,$reply_to); $task = "edit"; $note = $_POST['note']; $title = $_POST['form_note_type']; $reply_to = $_POST['reply_to']; } case "edit" : { if ($noteid == "") { $noteid = $_GET['noteid']; } // Update the message if it already exists; it's appended to an existing note in Patient Notes. $result = getPnoteById($noteid); if ($result) { if ($title == ""){ $title = $result['title']; } $body = $result['body']; if ($reply_to == ""){ $reply_to = $result['pid']; } $form_message_status = $result['message_status']; } } break; case "delete" : { // Delete selected message(s) from the Messages box (only). $delete_id = $_POST['delete_id']; for($i = 0; $i < count($delete_id); $i++) { deletePnote($delete_id[$i]); newEvent("delete", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "pnotes: id ".$delete_id[$i]); } } break; } if($task == "addnew" or $task == "edit") { // Display the Messages page layout. echo " <form name=new_note id=new_note action=\"messages.php?showall=".attr($showall)."&sortby=".attr($sortby)."&sortorder=".attr($sortorder)."&begin=".attr($begin)."&$activity_string_html\" method=post> <input type=hidden name=noteid id=noteid value=".htmlspecialchars( $noteid, ENT_QUOTES)."> <input type=hidden name=task id=task value=add>"; ?> <div id="pnotes"> <center> <table border='0' cellspacing='8'> <tr> <td class='text'><b><?php echo htmlspecialchars( xl('Type'), ENT_NOQUOTES); ?>:</b> <?php if ($title == "") { $title = "Unassigned"; } // Added 6/2009 by BM to incorporate the patient notes into the list_options listings. generate_form_field(array('data_type'=>1,'field_id'=>'note_type','list_id'=>'note_type','empty_title'=>'SKIP','order_by'=>'title'), $title); ?> &nbsp; &nbsp; <?php if ($task != "addnew" && $result['pid'] != 0) { ?> <a class="patLink" onClick="goPid('<?php echo attr($result['pid']);?>')"><?php echo htmlspecialchars( xl('Patient'), ENT_NOQUOTES); ?>:</a> <?php } else { ?> <b class='<?php echo ($task=="addnew"?"required":"") ?>'><?php echo htmlspecialchars( xl('Patient'), ENT_NOQUOTES); ?>:</b> <?php } if ($reply_to) { $prow = sqlQuery("SELECT lname, fname " . "FROM patient_data WHERE pid = ?", array($reply_to) ); $patientname = $prow['lname'] . ", " . $prow['fname']; } if ($patientname == '') { $patientname = xl('Click to select'); } ?> <input type='text' size='10' name='form_patient' style='width:150px;<?php echo ($task=="addnew"?"cursor:pointer;cursor:hand;":"") ?>' value='<?php echo htmlspecialchars($patientname, ENT_QUOTES); ?>' <?php echo (($task=="addnew" || $result['pid']==0) ? "onclick='sel_patient()' readonly":"disabled") ?> title='<?php echo ($task=="addnew"?(htmlspecialchars( xl('Click to select patient'), ENT_QUOTES)):"") ?>' /> <input type='hidden' name='reply_to' id='reply_to' value='<?php echo htmlspecialchars( $reply_to, ENT_QUOTES) ?>' /> &nbsp; &nbsp; <b><?php echo htmlspecialchars( xl('Status'), ENT_NOQUOTES); ?>:</b> <?php if ($form_message_status == "") { $form_message_status = 'New'; } generate_form_field(array('data_type'=>1,'field_id'=>'message_status','list_id'=>'message_status','empty_title'=>'SKIP','order_by'=>'title'), $form_message_status); ?></td> </tr> <tr> <td class='text'><b><?php echo htmlspecialchars( xl('To'), ENT_QUOTES); ?>:</b> <input type='textbox' name='assigned_to_text' id='assigned_to_text' size='40' readonly='readonly' value='<?php echo htmlspecialchars(xl("Select Users From The Dropdown List"), ENT_QUOTES)?>' > <input type='hidden' name='assigned_to' id='assigned_to' > <select name='users' id='users' onChange='addtolist(this);' > <?php echo "<option value='" . htmlspecialchars( '--', ENT_QUOTES) . "'"; echo ">" . htmlspecialchars( xl('Select User'), ENT_NOQUOTES); echo "</option>\n"; $ures = sqlStatement("SELECT username, fname, lname FROM users " . "WHERE username != '' AND active = 1 AND " . "( info IS NULL OR info NOT LIKE '%Inactive%' ) " . "ORDER BY lname, fname"); while ($urow = sqlFetchArray($ures)) { echo " <option value='" . htmlspecialchars( $urow['username'], ENT_QUOTES) . "'"; echo ">" . htmlspecialchars( $urow['lname'], ENT_NOQUOTES); if ($urow['fname']) echo ", " . htmlspecialchars( $urow['fname'], ENT_NOQUOTES); echo "</option>\n"; } echo "<option value='" . htmlspecialchars( '-patient-', ENT_QUOTES) . "'"; echo ">" . htmlspecialchars( '-Patient-', ENT_NOQUOTES); echo "</option>\n"; ?> </select></td> </tr> <?php if ($noteid) { // Get the related document IDs if any. $tmp = sqlStatement("SELECT id1 FROM gprelations WHERE " . "type1 = ? AND type2 = ? AND id2 = ?", array('1', '6', $noteid)); if (sqlNumRows($tmp)) { echo " <tr>\n"; echo " <td class='text'><b>"; echo xlt('Linked document') . ":</b>\n"; while ($gprow = sqlFetchArray($tmp)) { $d = new Document($gprow['id1']); echo " <a href='"; echo $GLOBALS['webroot'] . "/controller.php?document&retrieve"; echo "&patient_id=" . $d->get_foreign_id(); echo "&document_id=" . $d->get_id(); echo "&as_file=true' target='_blank' onclick='top.restoreSession()'>"; echo text($d->get_url_file()); echo "</a>\n"; } echo " </td>\n"; echo " </tr>\n"; } // Get the related procedure order IDs if any. $tmp = sqlStatement("SELECT id1 FROM gprelations WHERE " . "type1 = ? AND type2 = ? AND id2 = ?", array('2', '6', $noteid)); if (sqlNumRows($tmp)) { echo " <tr>\n"; echo " <td class='text'><b>"; echo xlt('Linked procedure order') . ":</b>\n"; while ($gprow = sqlFetchArray($tmp)) { echo " <a href='"; echo $GLOBALS['webroot'] . "/interface/orders/single_order_results.php?orderid="; echo $gprow['id1']; echo "' target='_blank' onclick='top.restoreSession()'>"; echo $gprow['id1']; echo "</a>\n"; } echo " </td>\n"; echo " </tr>\n"; } } ?> <tr> <td><?php if ($noteid) { $body = preg_replace('/(:\d{2}\s\()'.$result['pid'].'(\sto\s)/','${1}'.$patientname.'${2}',$body); $body = nl2br(htmlspecialchars( $body, ENT_NOQUOTES)); echo "<div class='text' style='background-color:white; color: gray; border:1px solid #999; padding: 5px; width: 640px;'>".$body."</div>"; } ?> <textarea name='note' id='note' rows='8' style="width: 660px; "><?php echo htmlspecialchars( $note, ENT_NOQUOTES) ?></textarea></td> </tr> </table> <?php if ($noteid) { ?> <!-- This is for displaying an existing note. --> <input type="button" id="newnote" value="<?php echo htmlspecialchars( xl('Send message'), ENT_QUOTES); ?>"> <input type="button" id="printnote" value="<?php echo htmlspecialchars( xl('Print message'), ENT_QUOTES); ?>"> <input type="button" id="cancel" value="<?php echo htmlspecialchars( xl('Cancel'), ENT_QUOTES); ?>"> <?php } else { ?> <!-- This is for displaying a new note. --> <input type="button" id="newnote" value="<?php echo htmlspecialchars( xl('Send message'), ENT_QUOTES); ?>"> <input type="button" id="cancel" value="<?php echo htmlspecialchars( xl('Cancel'), ENT_QUOTES); ?>"> <?php } ?> <br> </center> </div> <script language="javascript"> // jQuery stuff to make the page a little easier to use $(document).ready(function(){ $("#newnote").click(function() { NewNote(); }); $("#printnote").click(function() { PrintNote(); }); obj = document.getElementById("form_message_status"); obj.onchange = function(){SaveNote();}; $("#cancel").click(function() { CancelNote(); }); $("#note").focus(); var NewNote = function () { top.restoreSession(); if (document.forms[0].reply_to.value.length == 0 || document.forms[0].reply_to.value == '0') { alert('<?php echo htmlspecialchars( xl('Please choose a patient'), ENT_QUOTES); ?>'); } else if (document.forms[0].assigned_to.value.length == 0 && document.getElementById("form_message_status").value != 'Done') { alert('<?php echo addslashes(xl('Recipient required unless status is Done')); ?>'); } else { $("#new_note").submit(); } } var PrintNote = function () { top.restoreSession(); window.open('../../patient_file/summary/pnotes_print.php?noteid=<?php echo htmlspecialchars( $noteid, ENT_QUOTES); ?>', '_blank', 'resizable=1,scrollbars=1,width=600,height=500'); } var SaveNote = function () { <?php if ($noteid) { ?> top.restoreSession(); $("#task").val("save"); $("#new_note").submit(); <?php } ?> } var CancelNote = function () { top.restoreSession(); $("#task").val(""); $("#new_note").submit(); } }); // This is for callback by the find-patient popup. function setpatient(pid, lname, fname, dob) { var f = document.forms[0]; f.form_patient.value = lname + ', ' + fname; f.reply_to.value = pid; <?php if ($noteid) { ?> //used when direct messaging service inserts a pnote with indeterminate patient //to allow the user to assign the message to a patient. top.restoreSession(); $("#task").val("savePatient"); $("#new_note").submit(); <?php } ?> } // This invokes the find-patient popup. function sel_patient() { dlgopen('../../main/calendar/find_patient_popup.php', '_blank', 500, 400); } function addtolist(sel){ var itemtext = document.getElementById('assigned_to_text'); var item = document.getElementById('assigned_to'); if(sel.value != '--'){ if(item.value){ if(item.value.indexOf(sel.value) == -1){ itemtext.value = itemtext.value +' ; '+ sel.options[sel.selectedIndex].text; item.value = item.value +';'+ sel.value; } }else{ itemtext.value = sel.options[sel.selectedIndex].text; item.value = sel.value; } } } </script> <?php } else { // This is for sorting the records. $sort = array("users.lname", "patient_data.lname", "pnotes.title", "pnotes.date", "pnotes.message_status"); $sortby = (isset($_REQUEST['sortby']) && ($_REQUEST['sortby']!="")) ? $_REQUEST['sortby'] : $sort[0]; $sortorder = (isset($_REQUEST['sortorder']) && ($_REQUEST['sortorder']!="")) ? $_REQUEST['sortorder'] : "asc"; $begin = isset($_REQUEST['begin']) ? $_REQUEST['begin'] : 0; for($i = 0; $i < count($sort); $i++) { $sortlink[$i] = "<a href=\"messages.php?show_all=".attr($showall)."&sortby=".attr($sort[$i])."&sortorder=asc&$activity_string_html\" onclick=\"top.restoreSession()\"><img src=\"../../../images/sortdown.gif\" border=0 alt=\"".htmlspecialchars( xl('Sort Up'), ENT_QUOTES)."\"></a>"; } for($i = 0; $i < count($sort); $i++) { if($sortby == $sort[$i]) { switch($sortorder) { case "asc" : $sortlink[$i] = "<a href=\"messages.php?show_all=".attr($showall)."&sortby=".attr($sortby)."&sortorder=desc&$activity_string_html\" onclick=\"top.restoreSession()\"><img src=\"../../../images/sortup.gif\" border=0 alt=\"".htmlspecialchars( xl('Sort Up'), ENT_QUOTES)."\"></a>"; break; case "desc" : $sortlink[$i] = "<a href=\"messages.php?show_all=".attr($showall)."&sortby=".attr($sortby)."&sortorder=asc&$activity_string_html\" onclick=\"top.restoreSession()\"><img src=\"../../../images/sortdown.gif\" border=0 alt=\"".htmlspecialchars( xl('Sort Down'), ENT_QUOTES)."\"></a>"; break; } break; } } // Manage page numbering and display beneath the Messages table. $listnumber = 25; $total = getPnotesByUser($active,$show_all,$_SESSION['authUser'],true); if($begin == "" or $begin == 0) { $begin = 0; } $prev = $begin - $listnumber; $next = $begin + $listnumber; $start = $begin + 1; $end = $listnumber + $start - 1; if($end >= $total) { $end = $total; } if($end < $start) { $start = 0; } if($prev >= 0) { $prevlink = "<a href=\"messages.php?show_all=".attr($showall)."&sortby=".attr($sortby)."&sortorder=".attr($sortorder)."&begin=".attr($prev)."&$activity_string_html\" onclick=\"top.restoreSession()\"><<</a>"; } else { $prevlink = "<<"; } if($next < $total) { $nextlink = "<a href=\"messages.php?show_all=".attr($showall)."&sortby=".attr($sortby)."&sortorder=".attr($sortorder)."&begin=".attr($next)."&$activity_string_html\" onclick=\"top.restoreSession()\">>></a>"; } else { $nextlink = ">>"; } // Display the Messages table header. echo " <table width=100%><tr><td><table border=0 cellpadding=1 cellspacing=0 width=100% style=\"border-left: 0px #000000 solid; border-right: 0px #000000 solid; border-bottom: 0px #000000 solid;\"> <form name=MessageList action=\"messages.php?showall=".attr($showall)."&sortby=".attr($sortby)."&sortorder=".attr($sortorder)."&begin=".attr($begin)."&$activity_string_html\" method=post> <input type=hidden name=task value=delete> <tr height=\"24\" class=message_title_bar > <td align=\"center\" width=\"25\" style=\"border-bottom: 0px #000000 solid; border-right: 0px #000000 solid;\"><input type=checkbox id=\"checkAll\" onclick=\"selectAll()\"></td> <td width=\"20%\" style=\"border-bottom: 0px #000000 solid; border-right: 0px #000000 solid;\" class=message_bold>&nbsp;<b>" . htmlspecialchars( xl('From'), ENT_NOQUOTES) . "</b> $sortlink[0]</td> <td width=\"20%\" style=\"border-bottom: 0px #000000 solid; border-right: 0px #000000 solid;\" class=message_bold>&nbsp;<b>" . htmlspecialchars( xl('Patient'), ENT_NOQUOTES) . "</b> $sortlink[1]</td> <td style=\"border-bottom: 0px #000000 solid; border-right: 0px #000000 solid;\" class=message_bold>&nbsp;<b>" . htmlspecialchars( xl('Type'), ENT_NOQUOTES) . "</b> $sortlink[2]</td> <td width=\"15%\" style=\"border-bottom: 0px #000000 solid; border-right: 0px #000000 solid;\" class=message_bold>&nbsp;<b>" . htmlspecialchars( xl('Date'), ENT_NOQUOTES) . "</b> $sortlink[3]</td> <td width=\"15%\" style=\"border-bottom: 0px #000000 solid; \" class=message_bold>&nbsp;<b>" . htmlspecialchars( xl('Status'), ENT_NOQUOTES) . "</b> $sortlink[4]</td> </tr>"; // Display the Messages table body. Change the style of Message title bar $count = 0; $result = getPnotesByUser($active,$show_all,$_SESSION['authUser'],false,$sortby,$sortorder,$begin,$listnumber); while ($myrow = sqlFetchArray($result)) { $name = $myrow['user']; $name = $myrow['users_lname']; if ($myrow['users_fname']) { $name .= ", " . $myrow['users_fname']; } $patient = $myrow['pid']; if ($patient>0) { $patient = $myrow['patient_data_lname']; if ($myrow['patient_data_fname']) { $patient .= ", " . $myrow['patient_data_fname']; } } else { $patient = "* Patient must be set manually *"; } $count++; echo " <tr id=\"row$count\" style=\"background:white\" height=\"24\"> <td align=\"center\" style=\"border-bottom: 0px #000000 solid; border-right: 0px #000000 solid;\"><input type=checkbox id=\"check$count\" name=\"delete_id[]\" value=\"" . htmlspecialchars( $myrow['id'], ENT_QUOTES) . "\" onclick=\"if(this.checked==true){ selectRow('row$count'); }else{ deselectRow('row$count'); }\"></td> <td style=\"border-bottom: 0px #000000 solid; border-right: 0px #000000 solid;\"><table cellspacing=0 cellpadding=0 width=100%><tr><td width=5></td><td class=\"text\">" . htmlspecialchars( $name, ENT_NOQUOTES) . "</td><td width=5></td></tr></table></td> <td style=\"border-bottom: 0px #000000 solid; border-right: 0px #000000 solid;\"><table cellspacing=0 cellpadding=0 width=100%><tr><td width=5></td><td class=\"text\"><a href=\"messages.php?showall=".attr($showall)."&sortby=".attr($sortby)."&sortorder=".attr($sortorder)."&begin=".attr($begin)."&task=edit&noteid=" . htmlspecialchars( $myrow['id'], ENT_QUOTES) . "&$activity_string_html\" onclick=\"top.restoreSession()\">" . htmlspecialchars( $patient, ENT_NOQUOTES) . "</a></td><td width=5></td></tr></table></td> <td style=\"border-bottom: 0px #000000 solid; border-right: 0px #000000 solid;\"><table cellspacing=0 cellpadding=0 width=100%><tr><td width=5></td><td class=\"text\">" . htmlspecialchars( $myrow['title'], ENT_NOQUOTES) . "</td><td width=5></td></tr></table></td> <td style=\"border-bottom: 0px #000000 solid; border-right: 0px #000000 solid;\"><table cellspacing=0 cellpadding=0 width=100%><tr><td width=5></td><td class=\"text\">" . htmlspecialchars( oeFormatShortDate(substr($myrow['date'], 0, strpos($myrow['date'], " "))), ENT_NOQUOTES) . "</td><td width=5></td></tr></table></td> <td style=\"border-bottom: 0px #000000 solid;\"><table cellspacing=0 cellpadding=0 width=100%><tr><td width=5></td><td class=\"text\">" . htmlspecialchars( $myrow['message_status'], ENT_NOQUOTES) . "</td><td width=5></td></tr></table></td> </tr>"; } // Display the Messages table footer. echo " </form></table> <table border=0 cellpadding=5 cellspacing=0 width=100%> <tr> <td class=link><a href=\"messages.php?showall=".attr($showall)."&sortby=".attr($sortby)."&sortorder=".attr($sortorder)."&begin=".attr($begin)."&task=addnew&$activity_string_html\" onclick=\"top.restoreSession()\">" . htmlspecialchars( xl('Add New'), ENT_NOQUOTES) . "</a> &nbsp; <a href=\"javascript:confirmDeleteSelected()\" onclick=\"top.restoreSession()\">" . htmlspecialchars( xl('Delete'), ENT_NOQUOTES) . "</a></td> <td align=right class=\"text\">$prevlink &nbsp; $end of $total &nbsp; $nextlink</td> </tr> </table></td></tr></table><br>"; ?> <?php } ?></td> </tr> </table> <script language="javascript"> // This is to confirm delete action. function confirmDeleteSelected() { if(confirm("<?php echo htmlspecialchars( xl('Do you really want to delete the selection?'), ENT_QUOTES); ?>")) { document.MessageList.submit(); } } // This is to allow selection of all items in Messages table for deletion. function selectAll() { if(document.getElementById("checkAll").checked==true) { document.getElementById("checkAll").checked=true;<?php for($i = 1; $i <= $count; $i++) { echo "document.getElementById(\"check$i\").checked=true; document.getElementById(\"row$i\").style.background='#E7E7E7'; "; } ?> } else { document.getElementById("checkAll").checked=false;<?php for($i = 1; $i <= $count; $i++) { echo "document.getElementById(\"check$i\").checked=false; document.getElementById(\"row$i\").style.background='#F7F7F7'; "; } ?> } } // The two functions below are for managing row styles in Messages table. function selectRow(row) { document.getElementById(row).style.background = "#E7E7E7"; } function deselectRow(row) { document.getElementById(row).style.background = "#F7F7F7"; } </script> </body> </html>
gpl-3.0
mhbu50/erpnext
erpnext/patches/v14_0/delete_shopify_doctypes.py
168
import frappe def execute(): frappe.delete_doc("DocType", "Shopify Settings", ignore_missing=True) frappe.delete_doc("DocType", "Shopify Log", ignore_missing=True)
gpl-3.0
wyuka/rekonq
src/tests/findbar_test.cpp
1494
/* * Copyright 2010 Andrea Diamantini <adjam7@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ #include <qtest_kde.h> #include <QtTest/QtTest> #include "findbar.h" #include "mainwindow.h" class FindBarTest : public QObject { Q_OBJECT public slots: void initTestCase(); void cleanupTestCase(); private slots: void matchCase(); void notifyMatch(); private: FindBar *bar; MainWindow *w; }; // ------------------------------------------- void FindBarTest::initTestCase() { w = new MainWindow; bar = new FindBar(w); } void FindBarTest::cleanupTestCase() { delete bar; } void FindBarTest::matchCase() { } void FindBarTest::notifyMatch() { } // ------------------------------------------- QTEST_KDEMAIN(FindBarTest, GUI) #include "findbar_test.moc"
gpl-3.0
sangwook236/SWDT
sw_dev/cpp/rnd/test/signal_processing/sigproc_lib/bwlpf.cpp
2311
/* * COPYRIGHT * * Copyright (C) 2014 Exstrom Laboratories 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 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. * * A copy of the GNU General Public License is available on the internet at: * http://www.gnu.org/copyleft/gpl.html * * or you can write to: * * The Free Software Foundation, Inc. * 675 Mass Ave * Cambridge, MA 02139, USA * * Exstrom Laboratories LLC contact: * stefan(AT)exstrom.com * * Exstrom Laboratories LLC * Longmont, CO 80503, USA * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> // Compile: gcc -lm -o bwlpf bwlpf.c int main( int argc, char *argv[] ) { if(argc < 4) { printf("Usage: %s n s f\n", argv[0]); printf("Butterworth lowpass filter.\n"); printf(" n = filter order 2,4,6,...\n"); printf(" s = sampling frequency\n"); printf(" f = half power frequency\n"); return(-1); } int i, n = (int)strtol(argv[1], NULL, 10); n = n/2; double s = strtod(argv[2], NULL); double f = strtod(argv[3], NULL); double a = tan(M_PI*f/s); double a2 = a*a; double r; double *A = (double *)malloc(n*sizeof(double)); double *d1 = (double *)malloc(n*sizeof(double)); double *d2 = (double *)malloc(n*sizeof(double)); double *w0 = (double *)calloc(n, sizeof(double)); double *w1 = (double *)calloc(n, sizeof(double)); double *w2 = (double *)calloc(n, sizeof(double)); double x; for(i=0; i<n; ++i){ r = sin(M_PI*(2.0*i+1.0)/(4.0*n)); s = a2 + 2.0*a*r + 1.0; A[i] = a2/s; d1[i] = 2.0*(1-a2)/s; d2[i] = -(a2 - 2.0*a*r + 1.0)/s;} while(scanf("%lf", &x)!=EOF){ for(i=0; i<n; ++i){ w0[i] = d1[i]*w1[i] + d2[i]*w2[i] + x; x = A[i]*(w0[i] + 2.0*w1[i] + w2[i]); w2[i] = w1[i]; w1[i] = w0[i];} printf("%lf\n", x);} return(0); }
gpl-3.0
it-novum/openITCOCKPIT
tests/TestCase/Model/Table/CommandargumentsTableTest.php
1926
<?php namespace App\Test\TestCase\Model\Table; use App\Model\Table\CommandargumentsTable; use Cake\ORM\TableRegistry; use Cake\TestSuite\TestCase; /** * App\Model\Table\CommandargumentsTable Test Case */ class CommandargumentsTableTest extends TestCase { /** * Test subject * * @var \App\Model\Table\CommandargumentsTable */ public $Commandarguments; /** * Fixtures * * @var array */ public $fixtures = [ 'app.Commandarguments', 'app.Commands', 'app.Hostcommandargumentvalues', 'app.Hosttemplatecommandargumentvalues', 'app.Servicecommandargumentvalues', 'app.Serviceeventcommandargumentvalues', 'app.Servicetemplatecommandargumentvalues', 'app.Servicetemplateeventcommandargumentvalues' ]; /** * setUp method * * @return void */ public function setUp() { parent::setUp(); $config = TableRegistry::getTableLocator()->exists('Commandarguments') ? [] : ['className' => CommandargumentsTable::class]; $this->Commandarguments = TableRegistry::getTableLocator()->get('Commandarguments', $config); } /** * tearDown method * * @return void */ public function tearDown() { unset($this->Commandarguments); parent::tearDown(); } /** * Test initialize method * * @return void */ public function testInitialize() { $this->markTestIncomplete('Not implemented yet.'); } /** * Test validationDefault method * * @return void */ public function testValidationDefault() { $this->markTestIncomplete('Not implemented yet.'); } /** * Test buildRules method * * @return void */ public function testBuildRules() { $this->markTestIncomplete('Not implemented yet.'); } }
gpl-3.0
Necktrox/mtasa-blue
Server/mods/deathmatch/logic/packets/CEntityAddPacket.cpp
48766
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: mods/deathmatch/logic/packets/CEntityAddPacket.cpp * PURPOSE: Entity-add packet class * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #include "StdInc.h" // // Temporary helper functions for fixing crashes on pre r6459 clients. // Cause of #IND numbers should be handled before it gets here. (To avoid desync) // bool IsIndeterminate(float fValue) { return fValue - fValue != 0; } void SilentlyFixIndeterminate(float& fValue) { if (IsIndeterminate(fValue)) fValue = 0; } void SilentlyFixIndeterminate(CVector& vecValue) { SilentlyFixIndeterminate(vecValue.fX); SilentlyFixIndeterminate(vecValue.fY); SilentlyFixIndeterminate(vecValue.fZ); } void SilentlyFixIndeterminate(CVector2D& vecValue) { SilentlyFixIndeterminate(vecValue.fX); SilentlyFixIndeterminate(vecValue.fY); } void CEntityAddPacket::Add(CElement* pElement) { // Only add it if it has a parent. if (pElement->GetParentEntity()) { // Jax: adding some checks here because map/element loading is all over the fucking place! switch (pElement->GetType()) { case CElement::COLSHAPE: { CColShape* pColShape = static_cast<CColShape*>(pElement); // If its a server side element only, dont send it if (pColShape->IsPartnered()) { return; } break; } default: break; } m_Entities.push_back(pElement); } } bool CEntityAddPacket::Write(NetBitStreamInterface& BitStream) const { SPositionSync position(false); // Check that we have any entities if (m_Entities.size() > 0) { // Write the number of entities unsigned int NumElements = m_Entities.size(); BitStream.WriteCompressed(NumElements); // For each entity ... CVector vecTemp; vector<CElement*>::const_iterator iter = m_Entities.begin(); for (; iter != m_Entities.end(); ++iter) { // Entity id CElement* pElement = *iter; BitStream.Write(pElement->GetID()); // Entity type id unsigned char ucEntityTypeID = static_cast<unsigned char>(pElement->GetType()); BitStream.Write(ucEntityTypeID); // Entity parent CElement* pParent = pElement->GetParentEntity(); ElementID ParentID = INVALID_ELEMENT_ID; if (pParent) ParentID = pParent->GetID(); BitStream.Write(ParentID); // Entity interior BitStream.Write(pElement->GetInterior()); // Entity dimension BitStream.WriteCompressed(pElement->GetDimension()); // Entity attached to CElement* pElementAttachedTo = pElement->GetAttachedToElement(); if (pElementAttachedTo) { BitStream.WriteBit(true); BitStream.Write(pElementAttachedTo->GetID()); // Attached position and rotation SPositionSync attachedPosition(false); SRotationDegreesSync attachedRotation(false); pElement->GetAttachedOffsets(attachedPosition.data.vecPosition, attachedRotation.data.vecRotation); BitStream.Write(&attachedPosition); BitStream.Write(&attachedRotation); } else BitStream.WriteBit(false); // Entity collisions enabled bool bCollisionsEnabled = true; switch (pElement->GetType()) { case CElement::VEHICLE: { CVehicle* pVehicle = static_cast<CVehicle*>(pElement); bCollisionsEnabled = pVehicle->GetCollisionEnabled(); break; } case CElement::OBJECT: case CElement::WEAPON: { CObject* pObject = static_cast<CObject*>(pElement); bCollisionsEnabled = pObject->GetCollisionEnabled(); break; } case CElement::PED: case CElement::PLAYER: { CPed* pPed = static_cast<CPed*>(pElement); bCollisionsEnabled = pPed->GetCollisionEnabled(); break; } default: break; } BitStream.WriteBit(bCollisionsEnabled); if (BitStream.Version() >= 0x56) BitStream.WriteBit(pElement->IsCallPropagationEnabled()); // Write custom data CCustomData* pCustomData = pElement->GetCustomDataPointer(); assert(pCustomData); BitStream.WriteCompressed(pCustomData->CountOnlySynchronized()); map<string, SCustomData>::const_iterator iter = pCustomData->SyncedIterBegin(); for (; iter != pCustomData->SyncedIterEnd(); ++iter) { const char* szName = iter->first.c_str(); const CLuaArgument* pArgument = &iter->second.Variable; bool bSynchronized = iter->second.bSynchronized; if (bSynchronized) { unsigned char ucNameLength = static_cast<unsigned char>(strlen(szName)); BitStream.Write(ucNameLength); BitStream.Write(szName, ucNameLength); pArgument->WriteToBitStream(BitStream); } } // Grab its name char szEmpty[1]; szEmpty[0] = 0; const char* szName = pElement->GetName().c_str(); if (!szName) szName = szEmpty; // Write the name. It can be empty. unsigned short usNameLength = static_cast<unsigned short>(strlen(szName)); BitStream.WriteCompressed(usNameLength); if (usNameLength > 0) { BitStream.Write(szName, usNameLength); } // Write the sync time context BitStream.Write(pElement->GetSyncTimeContext()); // Write the rest depending on the type switch (ucEntityTypeID) { case CElement::OBJECT: case CElement::WEAPON: { CObject* pObject = static_cast<CObject*>(pElement); // Position position.data.vecPosition = pObject->GetPosition(); SilentlyFixIndeterminate(position.data.vecPosition); // Crash fix for pre r6459 clients BitStream.Write(&position); // Rotation SRotationRadiansSync rotationRadians(false); pObject->GetRotation(rotationRadians.data.vecRotation); BitStream.Write(&rotationRadians); // Object id BitStream.WriteCompressed(pObject->GetModel()); // Alpha SEntityAlphaSync alpha; alpha.data.ucAlpha = pObject->GetAlpha(); BitStream.Write(&alpha); // Low LOD stuff bool bIsLowLod = pObject->IsLowLod(); BitStream.WriteBit(bIsLowLod); CObject* pLowLodObject = pObject->GetLowLodObject(); ElementID LowLodObjectID = pLowLodObject ? pLowLodObject->GetID() : INVALID_ELEMENT_ID; BitStream.Write(LowLodObjectID); // Double sided bool bIsDoubleSided = pObject->IsDoubleSided(); BitStream.WriteBit(bIsDoubleSided); // Visible in all dimensions if (BitStream.Version() >= 0x068) { bool bIsVisibleInAllDimensions = pObject->IsVisibleInAllDimensions(); BitStream.WriteBit(bIsVisibleInAllDimensions); } // Moving const CPositionRotationAnimation* pMoveAnimation = pObject->GetMoveAnimation(); if (pMoveAnimation) { BitStream.WriteBit(true); pMoveAnimation->ToBitStream(BitStream, true); } else { BitStream.WriteBit(false); } // Scale const CVector& vecScale = pObject->GetScale(); if (BitStream.Version() >= 0x41) { bool bIsUniform = (vecScale.fX == vecScale.fY && vecScale.fX == vecScale.fZ); BitStream.WriteBit(bIsUniform); if (bIsUniform) { bool bIsUnitSize = (vecScale.fX == 1.0f); BitStream.WriteBit(bIsUnitSize); if (!bIsUnitSize) BitStream.Write(vecScale.fX); } else { BitStream.Write(vecScale.fX); BitStream.Write(vecScale.fY); BitStream.Write(vecScale.fZ); } } else { BitStream.Write(vecScale.fX); } // Frozen bool bFrozen = pObject->IsFrozen(); BitStream.WriteBit(bFrozen); // Health SObjectHealthSync health; health.data.fValue = pObject->GetHealth(); BitStream.Write(&health); if (ucEntityTypeID == CElement::WEAPON) { CCustomWeapon* pWeapon = static_cast<CCustomWeapon*>(pElement); unsigned char targetType = pWeapon->GetTargetType(); BitStream.WriteBits(&targetType, 3); // 3 bits = 4 possible values. switch (targetType) { case TARGET_TYPE_FIXED: { break; } case TARGET_TYPE_ENTITY: { CElement* pTarget = pWeapon->GetElementTarget(); ElementID targetID = pTarget->GetID(); BitStream.Write(targetID); if (IS_PED(pTarget)) { // Send full unsigned char... bone documentation looks scarce. unsigned char ucSubTarget = pWeapon->GetTargetBone(); BitStream.Write(ucSubTarget); // Send the entire unsigned char as there are a lot of bones. } else if (IS_VEHICLE(pTarget)) { unsigned char ucSubTarget = pWeapon->GetTargetWheel(); BitStream.WriteBits(&ucSubTarget, 4); // 4 bits = 8 possible values. } break; } case TARGET_TYPE_VECTOR: { CVector vecTarget = pWeapon->GetVectorTarget(); BitStream.WriteVector(vecTarget.fX, vecTarget.fY, vecTarget.fZ); break; } } bool bChanged = false; BitStream.WriteBit(bChanged); if (bChanged) { CWeaponStat* pWeaponStat = pWeapon->GetWeaponStat(); unsigned short usDamage = pWeaponStat->GetDamagePerHit(); float fAccuracy = pWeaponStat->GetAccuracy(); float fTargetRange = pWeaponStat->GetTargetRange(); float fWeaponRange = pWeaponStat->GetWeaponRange(); BitStream.WriteBits(&usDamage, 12); // 12 bits = 2048 values... plenty. BitStream.Write(fAccuracy); BitStream.Write(fTargetRange); BitStream.Write(fWeaponRange); } SWeaponConfiguration weaponConfig = pWeapon->GetFlags(); BitStream.WriteBit(weaponConfig.bDisableWeaponModel); BitStream.WriteBit(weaponConfig.bInstantReload); BitStream.WriteBit(weaponConfig.bShootIfTargetBlocked); BitStream.WriteBit(weaponConfig.bShootIfTargetOutOfRange); BitStream.WriteBit(weaponConfig.flags.bCheckBuildings); BitStream.WriteBit(weaponConfig.flags.bCheckCarTires); BitStream.WriteBit(weaponConfig.flags.bCheckDummies); BitStream.WriteBit(weaponConfig.flags.bCheckObjects); BitStream.WriteBit(weaponConfig.flags.bCheckPeds); BitStream.WriteBit(weaponConfig.flags.bCheckVehicles); BitStream.WriteBit(weaponConfig.flags.bIgnoreSomeObjectsForCamera); BitStream.WriteBit(weaponConfig.flags.bSeeThroughStuff); BitStream.WriteBit(weaponConfig.flags.bShootThroughStuff); unsigned short usAmmo = pWeapon->GetAmmo(); unsigned short usClipAmmo = pWeapon->GetAmmo(); ElementID OwnerID = pWeapon->GetOwner() == NULL ? INVALID_ELEMENT_ID : pWeapon->GetOwner()->GetID(); unsigned char ucWeaponState = pWeapon->GetWeaponState(); BitStream.WriteBits(&ucWeaponState, 4); // 4 bits = 8 possible values for weapon state BitStream.Write(usAmmo); BitStream.Write(usClipAmmo); BitStream.Write(OwnerID); } break; } case CElement::PICKUP: { CPickup* pPickup = static_cast<CPickup*>(pElement); // Position position.data.vecPosition = pPickup->GetPosition(); SilentlyFixIndeterminate(position.data.vecPosition); // Crash fix for pre r6459 clients BitStream.Write(&position); // Grab the model and write it unsigned short usModel = pPickup->GetModel(); BitStream.WriteCompressed(usModel); // Write if it's visible bool bVisible = pPickup->IsVisible(); BitStream.WriteBit(bVisible); // Write the type SPickupTypeSync pickupType; pickupType.data.ucType = pPickup->GetPickupType(); BitStream.Write(&pickupType); switch (pPickup->GetPickupType()) { case CPickup::ARMOR: { SPlayerArmorSync armor; armor.data.fValue = pPickup->GetAmount(); BitStream.Write(&armor); break; } case CPickup::HEALTH: { SPlayerHealthSync health; health.data.fValue = pPickup->GetAmount(); BitStream.Write(&health); break; } case CPickup::WEAPON: { SWeaponTypeSync weaponType; weaponType.data.ucWeaponType = pPickup->GetWeaponType(); BitStream.Write(&weaponType); SWeaponAmmoSync ammo(weaponType.data.ucWeaponType, true, false); ammo.data.usTotalAmmo = pPickup->GetAmmo(); BitStream.Write(&ammo); break; } default: break; } break; } case CElement::VEHICLE: { CVehicle* pVehicle = static_cast<CVehicle*>(pElement); // Write the vehicle position and rotation position.data.vecPosition = pVehicle->GetPosition(); SRotationDegreesSync rotationDegrees(false); pVehicle->GetRotationDegrees(rotationDegrees.data.vecRotation); // Write it BitStream.Write(&position); BitStream.Write(&rotationDegrees); // Vehicle id as a char // I'm assuming the "-400" is for adjustment so that all car values can // fit into a char? Why doesn't someone document this? // // --slush BitStream.Write(static_cast<unsigned char>(pVehicle->GetModel() - 400)); // Health SVehicleHealthSync health; health.data.fValue = pVehicle->GetHealth(); BitStream.Write(&health); // Color CVehicleColor& vehColor = pVehicle->GetColor(); uchar ucNumColors = vehColor.GetNumColorsUsed() - 1; BitStream.WriteBits(&ucNumColors, 2); for (uint i = 0; i <= ucNumColors; i++) { SColor RGBColor = vehColor.GetRGBColor(i); BitStream.Write(RGBColor.R); BitStream.Write(RGBColor.G); BitStream.Write(RGBColor.B); } // Paintjob SPaintjobSync paintjob; paintjob.data.ucPaintjob = pVehicle->GetPaintjob(); BitStream.Write(&paintjob); // Write the damage model SVehicleDamageSync damage(true, true, true, true, false); damage.data.ucDoorStates = pVehicle->m_ucDoorStates; damage.data.ucWheelStates = pVehicle->m_ucWheelStates; damage.data.ucPanelStates = pVehicle->m_ucPanelStates; damage.data.ucLightStates = pVehicle->m_ucLightStates; BitStream.Write(&damage); unsigned char ucVariant = pVehicle->GetVariant(); BitStream.Write(ucVariant); unsigned char ucVariant2 = pVehicle->GetVariant2(); BitStream.Write(ucVariant2); // If the vehicle has a turret, send its position too unsigned short usModel = pVehicle->GetModel(); if (CVehicleManager::HasTurret(usModel)) { SVehicleTurretSync specific; specific.data.fTurretX = pVehicle->GetTurretPositionX(); specific.data.fTurretY = pVehicle->GetTurretPositionY(); BitStream.Write(&specific); } // If the vehicle has an adjustable property send its value if (CVehicleManager::HasAdjustableProperty(usModel)) { BitStream.WriteCompressed(pVehicle->GetAdjustableProperty()); } // If the vehicle has doors, sync their open angle ratios. if (CVehicleManager::HasDoors(usModel)) { SDoorOpenRatioSync door; for (unsigned char i = 0; i < 6; ++i) { door.data.fRatio = pVehicle->GetDoorOpenRatio(i); BitStream.Write(&door); } } // Write all the upgrades CVehicleUpgrades* pUpgrades = pVehicle->GetUpgrades(); unsigned char ucNumUpgrades = pUpgrades->Count(); const SSlotStates& usSlotStates = pUpgrades->GetSlotStates(); BitStream.Write(ucNumUpgrades); if (ucNumUpgrades > 0) { unsigned char ucSlot = 0; for (; ucSlot < VEHICLE_UPGRADE_SLOTS; ucSlot++) { unsigned short usUpgrade = usSlotStates[ucSlot]; /* * This is another retarded modification in an attempt to save * a byte. We're apparently subtracting 1000 so we can store the * information in a single byte instead of two. This only gives us * a maximum of 256 vehicle slots. * * --slush * -- ChrML: Ehm, GTA only has 17 upgrade slots... This is a valid optimization. */ if (usUpgrade) BitStream.Write(static_cast<unsigned char>(usSlotStates[ucSlot] - 1000)); } } // Get the vehicle's reg plate as 8 bytes of chars with the not used bytes // nulled. const char* cszRegPlate = pVehicle->GetRegPlate(); BitStream.Write(cszRegPlate, 8); // Light override SOverrideLightsSync overrideLights; overrideLights.data.ucOverride = pVehicle->GetOverrideLights(); BitStream.Write(&overrideLights); // Grab various vehicle flags BitStream.WriteBit(pVehicle->IsLandingGearDown()); BitStream.WriteBit(pVehicle->IsSirenActive()); BitStream.WriteBit(pVehicle->IsFuelTankExplodable()); BitStream.WriteBit(pVehicle->IsEngineOn()); BitStream.WriteBit(pVehicle->IsLocked()); BitStream.WriteBit(pVehicle->AreDoorsUndamageable()); BitStream.WriteBit(pVehicle->IsDamageProof()); BitStream.WriteBit(pVehicle->IsFrozen()); BitStream.WriteBit(pVehicle->IsDerailed()); BitStream.WriteBit(pVehicle->IsDerailable()); BitStream.WriteBit(pVehicle->GetTrainDirection()); BitStream.WriteBit(pVehicle->IsTaxiLightOn()); // Write alpha SEntityAlphaSync alpha; alpha.data.ucAlpha = pVehicle->GetAlpha(); BitStream.Write(&alpha); // Write headlight color SColor color = pVehicle->GetHeadLightColor(); if (color.R != 255 || color.G != 255 || color.B != 255) { BitStream.WriteBit(true); BitStream.Write(color.R); BitStream.Write(color.G); BitStream.Write(color.B); } else BitStream.WriteBit(false); // Write handling if (g_pGame->GetHandlingManager()->HasModelHandlingChanged(static_cast<eVehicleTypes>(pVehicle->GetModel())) || pVehicle->HasHandlingChanged()) { BitStream.WriteBit(true); SVehicleHandlingSync handling; CHandlingEntry* pEntry = pVehicle->GetHandlingData(); handling.data.fMass = pEntry->GetMass(); handling.data.fTurnMass = pEntry->GetTurnMass(); handling.data.fDragCoeff = pEntry->GetDragCoeff(); handling.data.vecCenterOfMass = pEntry->GetCenterOfMass(); handling.data.ucPercentSubmerged = pEntry->GetPercentSubmerged(); handling.data.fTractionMultiplier = pEntry->GetTractionMultiplier(); handling.data.ucDriveType = pEntry->GetCarDriveType(); handling.data.ucEngineType = pEntry->GetCarEngineType(); handling.data.ucNumberOfGears = pEntry->GetNumberOfGears(); handling.data.fEngineAcceleration = pEntry->GetEngineAcceleration(); handling.data.fEngineInertia = pEntry->GetEngineInertia(); handling.data.fMaxVelocity = pEntry->GetMaxVelocity(); handling.data.fBrakeDeceleration = pEntry->GetBrakeDeceleration(); handling.data.fBrakeBias = pEntry->GetBrakeBias(); handling.data.bABS = pEntry->GetABS(); handling.data.fSteeringLock = pEntry->GetSteeringLock(); handling.data.fTractionLoss = pEntry->GetTractionLoss(); handling.data.fTractionBias = pEntry->GetTractionBias(); handling.data.fSuspensionForceLevel = pEntry->GetSuspensionForceLevel(); handling.data.fSuspensionDamping = pEntry->GetSuspensionDamping(); handling.data.fSuspensionHighSpdDamping = pEntry->GetSuspensionHighSpeedDamping(); handling.data.fSuspensionUpperLimit = pEntry->GetSuspensionUpperLimit(); handling.data.fSuspensionLowerLimit = pEntry->GetSuspensionLowerLimit(); handling.data.fSuspensionFrontRearBias = pEntry->GetSuspensionFrontRearBias(); handling.data.fSuspensionAntiDiveMultiplier = pEntry->GetSuspensionAntiDiveMultiplier(); handling.data.fCollisionDamageMultiplier = pEntry->GetCollisionDamageMultiplier(); handling.data.uiModelFlags = pEntry->GetModelFlags(); handling.data.uiHandlingFlags = pEntry->GetHandlingFlags(); handling.data.fSeatOffsetDistance = pEntry->GetSeatOffsetDistance(); // handling.data.uiMonetary = pEntry->GetMonetary (); // handling.data.ucHeadLight = pEntry->GetHeadLight (); // handling.data.ucTailLight = pEntry->GetTailLight (); handling.data.ucAnimGroup = pEntry->GetAnimGroup(); // Lower and Upper limits cannot match or LSOD (unless boat) // if ( pVehicle->GetModel() != VEHICLE_BOAT ) // Commented until fully tested { float fSuspensionLimitSize = handling.data.fSuspensionUpperLimit - handling.data.fSuspensionLowerLimit; if (fSuspensionLimitSize > -0.1f && fSuspensionLimitSize < 0.1f) { if (fSuspensionLimitSize >= 0.f) handling.data.fSuspensionUpperLimit = handling.data.fSuspensionLowerLimit + 0.1f; else handling.data.fSuspensionUpperLimit = handling.data.fSuspensionLowerLimit - 0.1f; } } BitStream.Write(&handling); } else BitStream.WriteBit(false); if (BitStream.Version() >= 0x02B) { unsigned char ucSirenCount = pVehicle->m_tSirenBeaconInfo.m_ucSirenCount; unsigned char ucSirenType = pVehicle->m_tSirenBeaconInfo.m_ucSirenType; bool bSync = pVehicle->m_tSirenBeaconInfo.m_bOverrideSirens; BitStream.WriteBit(bSync); if (bSync) { BitStream.Write(ucSirenCount); BitStream.Write(ucSirenType); for (int i = 0; i < ucSirenCount; i++) { SVehicleSirenSync syncData; syncData.data.m_bOverrideSirens = true; syncData.data.m_b360Flag = pVehicle->m_tSirenBeaconInfo.m_b360Flag; syncData.data.m_bDoLOSCheck = pVehicle->m_tSirenBeaconInfo.m_bDoLOSCheck; syncData.data.m_bUseRandomiser = pVehicle->m_tSirenBeaconInfo.m_bUseRandomiser; syncData.data.m_bEnableSilent = pVehicle->m_tSirenBeaconInfo.m_bSirenSilent; syncData.data.m_ucSirenID = i; syncData.data.m_vecSirenPositions = pVehicle->m_tSirenBeaconInfo.m_tSirenInfo[i].m_vecSirenPositions; syncData.data.m_colSirenColour = pVehicle->m_tSirenBeaconInfo.m_tSirenInfo[i].m_RGBBeaconColour; syncData.data.m_dwSirenMinAlpha = pVehicle->m_tSirenBeaconInfo.m_tSirenInfo[i].m_dwMinSirenAlpha; BitStream.Write(&syncData); } } } break; } case CElement::MARKER: { CMarker* pMarker = static_cast<CMarker*>(pElement); // Position position.data.vecPosition = pMarker->GetPosition(); SilentlyFixIndeterminate(position.data.vecPosition); // Crash fix for pre r6459 clients BitStream.Write(&position); // Type SMarkerTypeSync markerType; markerType.data.ucType = pMarker->GetMarkerType(); BitStream.Write(&markerType); // Size float fSize = pMarker->GetSize(); BitStream.Write(fSize); // Colour SColorSync color; color = pMarker->GetColor(); BitStream.Write(&color); // Write the target position vector eventually if (markerType.data.ucType == CMarker::TYPE_CHECKPOINT || markerType.data.ucType == CMarker::TYPE_RING) { if (pMarker->HasTarget()) { BitStream.WriteBit(true); position.data.vecPosition = pMarker->GetTarget(); BitStream.Write(&position); } else BitStream.WriteBit(false); } break; } case CElement::BLIP: { CBlip* pBlip = static_cast<CBlip*>(pElement); // Grab the blip position position.data.vecPosition = pBlip->GetPosition(); BitStream.Write(&position); // Write the ordering id BitStream.WriteCompressed(pBlip->m_sOrdering); // Write the visible distance - 14 bits allows 16383. SIntegerSync<unsigned short, 14> visibleDistance(std::min(pBlip->m_usVisibleDistance, (unsigned short)16383)); BitStream.Write(&visibleDistance); // Write the icon SIntegerSync<unsigned char, 6> icon(pBlip->m_ucIcon); BitStream.Write(&icon); if (pBlip->m_ucIcon == 0) { // Write the size SIntegerSync<unsigned char, 5> size(pBlip->m_ucSize); BitStream.Write(&size); // Write the color SColorSync color; color = pBlip->GetColor(); BitStream.Write(&color); } break; } case CElement::RADAR_AREA: { CRadarArea* pArea = static_cast<CRadarArea*>(pElement); // Write the position SPosition2DSync position2D(false); position2D.data.vecPosition = pArea->GetPosition(); SilentlyFixIndeterminate(position2D.data.vecPosition); // Crash fix for pre r6459 clients BitStream.Write(&position2D); // Write the size SPosition2DSync size2D(false); size2D.data.vecPosition = pArea->GetSize(); SilentlyFixIndeterminate(size2D.data.vecPosition); // Crash fix for pre r6459 clients BitStream.Write(&size2D); // And the color SColor color = pArea->GetColor(); BitStream.Write(color.R); BitStream.Write(color.G); BitStream.Write(color.B); BitStream.Write(color.A); // Write whether it is flashing bool bIsFlashing = pArea->IsFlashing(); BitStream.WriteBit(bIsFlashing); break; } case CElement::WORLD_MESH_UNUSED: { /* CWorldMesh* pMesh = static_cast < CWorldMesh* > ( pElement ); // Write the name char* szName = pMesh->GetName (); unsigned short usNameLength = static_cast < unsigned short > ( strlen ( szName ) ); BitStream.Write ( usNameLength ); BitStream.Write ( szName, static_cast < int > ( usNameLength ) ); // Write the position and rotation CVector vecTemp = pMesh->GetPosition (); BitStream.Write ( vecTemp.fX ); BitStream.Write ( vecTemp.fY ); BitStream.Write ( vecTemp.fZ ); vecTemp = pMesh->GetRotation (); BitStream.Write ( vecTemp.fX ); BitStream.Write ( vecTemp.fY ); BitStream.Write ( vecTemp.fZ ); */ break; } case CElement::TEAM: { CTeam* pTeam = static_cast<CTeam*>(pElement); // Write the name const char* szTeamName = pTeam->GetTeamName(); unsigned short usNameLength = static_cast<unsigned short>(strlen(szTeamName)); unsigned char ucRed, ucGreen, ucBlue; pTeam->GetColor(ucRed, ucGreen, ucBlue); bool bFriendlyFire = pTeam->GetFriendlyFire(); BitStream.WriteCompressed(usNameLength); BitStream.Write(szTeamName, usNameLength); BitStream.Write(ucRed); BitStream.Write(ucGreen); BitStream.Write(ucBlue); BitStream.WriteBit(bFriendlyFire); BitStream.Write(pTeam->CountPlayers()); for (list<CPlayer*>::const_iterator iter = pTeam->PlayersBegin(); iter != pTeam->PlayersEnd(); ++iter) BitStream.Write((*iter)->GetID()); break; } case CElement::PED: { CPed* pPed = static_cast<CPed*>(pElement); // position position.data.vecPosition = pPed->GetPosition(); BitStream.Write(&position); // model unsigned short usModel = pPed->GetModel(); BitStream.WriteCompressed(usModel); // rotation SPedRotationSync pedRotation; pedRotation.data.fRotation = pPed->GetRotation(); BitStream.Write(&pedRotation); // health SPlayerHealthSync health; health.data.fValue = pPed->GetHealth(); BitStream.Write(&health); // Armor SPlayerArmorSync armor; armor.data.fValue = pPed->GetArmor(); BitStream.Write(&armor); // vehicle CVehicle* pVehicle = pPed->GetOccupiedVehicle(); if (pVehicle) { BitStream.WriteBit(true); BitStream.Write(pVehicle->GetID()); SOccupiedSeatSync seat; seat.data.ucSeat = pPed->GetOccupiedVehicleSeat(); BitStream.Write(&seat); } else BitStream.WriteBit(false); // flags BitStream.WriteBit(pPed->HasJetPack()); BitStream.WriteBit(pPed->IsSyncable()); BitStream.WriteBit(pPed->IsHeadless()); BitStream.WriteBit(pPed->IsFrozen()); // alpha SEntityAlphaSync alpha; alpha.data.ucAlpha = pPed->GetAlpha(); BitStream.Write(&alpha); // Move anim if (BitStream.Version() > 0x4B) { uchar ucMoveAnim = pPed->GetMoveAnim(); BitStream.Write(ucMoveAnim); } // clothes unsigned char ucNumClothes = 0; CPlayerClothes* pClothes = pPed->GetClothes(); for (unsigned char ucType = 0; ucType < PLAYER_CLOTHING_SLOTS; ucType++) { const SPlayerClothing* pClothing = pClothes->GetClothing(ucType); if (pClothing) { ucNumClothes++; } } BitStream.Write(ucNumClothes); for (unsigned char ucType = 0; ucType < PLAYER_CLOTHING_SLOTS; ucType++) { const SPlayerClothing* pClothing = pClothes->GetClothing(ucType); if (pClothing) { unsigned char ucTextureLength = strlen(pClothing->szTexture); unsigned char ucModelLength = strlen(pClothing->szModel); BitStream.Write(ucTextureLength); BitStream.Write(pClothing->szTexture, ucTextureLength); BitStream.Write(ucModelLength); BitStream.Write(pClothing->szModel, ucModelLength); BitStream.Write(ucType); } } // weapons if (BitStream.Version() >= 0x61) { // Get a list of weapons for (unsigned char slot = 0; slot < WEAPONSLOT_MAX; ++slot) { CWeapon* pWeapon = pPed->GetWeapon(slot); if (pWeapon->ucType != 0) { BitStream.Write(slot); BitStream.Write(pWeapon->ucType); BitStream.Write(pWeapon->usAmmo); // ammoInClip is not implemented generally // BitStream.Write ( pWeapon->usAmmoInClip ); } } // Write end marker (slot) BitStream.Write((unsigned char)0xFF); // Send the current weapon spot unsigned char currentWeaponSlot = pPed->GetWeaponSlot(); BitStream.Write(currentWeaponSlot); } break; } case CElement::DUMMY: { CDummy* pDummy = static_cast<CDummy*>(pElement); // Type Name const char* szTypeName = pDummy->GetTypeName().c_str(); unsigned short usTypeNameLength = static_cast<unsigned short>(strlen(szTypeName)); BitStream.WriteCompressed(usTypeNameLength); BitStream.Write(szTypeName, usTypeNameLength); // Position position.data.vecPosition = pDummy->GetPosition(); if (position.data.vecPosition != CVector(0.0f, 0.0f, 0.0f)) { BitStream.WriteBit(true); BitStream.Write(&position); } else BitStream.WriteBit(false); break; } case CElement::PLAYER: { break; } case CElement::SCRIPTFILE: { // No extra data break; } case CElement::COLSHAPE: { CColShape* pColShape = static_cast<CColShape*>(pElement); if (!pColShape->GetParentEntity()) { // Jax: i'm pretty sure this is fucking up our packet somehow.. // all valid col-shapes should have a parent! assert(false); } // Type SColshapeTypeSync colType; colType.data.ucType = static_cast<unsigned char>(pColShape->GetShapeType()); BitStream.Write(&colType); // Position position.data.vecPosition = pColShape->GetPosition(); BitStream.Write(&position); // Enabled BitStream.WriteBit(pColShape->IsEnabled()); // Auto Call Event BitStream.WriteBit(pColShape->GetAutoCallEvent()); switch (pColShape->GetShapeType()) { case COLSHAPE_CIRCLE: { BitStream.Write(static_cast<CColCircle*>(pColShape)->GetRadius()); break; } case COLSHAPE_CUBOID: { SPositionSync size(false); size.data.vecPosition = static_cast<CColCuboid*>(pColShape)->GetSize(); BitStream.Write(&size); break; } case COLSHAPE_SPHERE: { BitStream.Write(static_cast<CColSphere*>(pColShape)->GetRadius()); break; } case COLSHAPE_RECTANGLE: { SPosition2DSync size(false); size.data.vecPosition = static_cast<CColRectangle*>(pColShape)->GetSize(); BitStream.Write(&size); break; } case COLSHAPE_TUBE: { BitStream.Write(static_cast<CColTube*>(pColShape)->GetRadius()); BitStream.Write(static_cast<CColTube*>(pColShape)->GetHeight()); break; } case COLSHAPE_POLYGON: { CColPolygon* pPolygon = static_cast<CColPolygon*>(pColShape); BitStream.WriteCompressed(pPolygon->CountPoints()); std::vector<CVector2D>::const_iterator iter = pPolygon->IterBegin(); for (; iter != pPolygon->IterEnd(); ++iter) { SPosition2DSync vertex(false); vertex.data.vecPosition = *iter; BitStream.Write(&vertex); } break; } default: break; } break; } case CElement::WATER: { CWater* pWater = static_cast<CWater*>(pElement); unsigned char ucNumVertices = (unsigned char)pWater->GetNumVertices(); BitStream.Write(ucNumVertices); CVector vecVertex; for (int i = 0; i < ucNumVertices; i++) { pWater->GetVertex(i, vecVertex); BitStream.Write((short)vecVertex.fX); BitStream.Write((short)vecVertex.fY); BitStream.Write(vecVertex.fZ); } break; } default: { assert(0); CLogger::LogPrintf("not sending this element - id: %i\n", pElement->GetType()); } } } // Success return true; } return false; }
gpl-3.0
ScreamingUdder/mantid
scripts/Diffraction/isis_powder/routines/instrument_settings.py
9455
from __future__ import (absolute_import, division, print_function) from six import iteritems from isis_powder.routines import yaml_parser import warnings # Have to patch warnings at runtime to not print the source code. This is even advertised as a 'feature' of # the warnings library in the documentation: https://docs.python.org/3/library/warnings.html#warnings.showwarning def _warning_no_source(msg, *_, **__): return str(msg) + '\n' warnings.formatwarning = _warning_no_source warnings.simplefilter('always', UserWarning) class InstrumentSettings(object): # Holds instance variables updated at runtime def __init__(self, param_map, adv_conf_dict=None, kwargs=None): self._param_map = param_map self._adv_config_dict = adv_conf_dict self._kwargs = kwargs self._basic_conf_dict = None # Check if we have kwargs otherwise this work cannot be completed (e.g. using automated testing) if kwargs: config_file_path = kwargs.get("config_file", None) if not config_file_path: warnings.warn("No config file was specified. If a configuration file was meant to be used " "the path to the file is set with the 'config_file' parameter.\n") # Always do this so we have a known state of the internal variable self._basic_conf_dict = yaml_parser.open_yaml_file_as_dictionary(config_file_path) # We parse in the order advanced config, basic config (if specified), kwargs. # This means that users can use the advanced config as a safe set of defaults, with their own preferences as # the next layer which can override defaults and finally script arguments as their final override. self._parse_attributes(dict_to_parse=adv_conf_dict) self._parse_attributes(dict_to_parse=self._basic_conf_dict) self._parse_attributes(dict_to_parse=kwargs) # __getattr__ is only called if the attribute was not set so we already know # were going to throw at this point unless the attribute was optional. def __getattr__(self, item): # Check if it is in our parameter mapping known_param = next((param_entry for param_entry in self._param_map if item == param_entry.int_name), None) if known_param: if known_param.optional: # Optional param return none return None else: # User forgot to enter the param: self._raise_user_param_missing_error(known_param) else: # If you have got here from a grep or something similar this error message means the line caller # has asked for a class attribute which does not exist. These attributes are set in a mapping file which # is passed in whilst InstrumentSettings is being constructed. Check that the 'script name' (i.e. not user # friendly name) is typed correctly in both the script(s) and mapping file. raise AttributeError("The attribute in the script with name " + str(item) + " was not found in the " "mapping file. \nPlease contact the development team.") def update_attributes(self, advanced_config=None, basic_config=None, kwargs=None, suppress_warnings=False): self._adv_config_dict = advanced_config if advanced_config else self._adv_config_dict self._basic_conf_dict = basic_config if basic_config else self._basic_conf_dict self._kwargs = kwargs if kwargs else self._kwargs # Only update if one in hierarchy below it has been updated # so if advanced_config has been changed we need to parse the basic and kwargs again to ensure # the overrides are respected. Additionally we check whether we should suppress warnings based on # whether this was the attribute that was changed. If it was then produce warnings - if we are # reapplying overrides silence them. if advanced_config: self._parse_attributes(self._adv_config_dict, suppress_warnings=suppress_warnings) if advanced_config or basic_config: self._parse_attributes(self._basic_conf_dict, suppress_warnings=(not basic_config or suppress_warnings)) if advanced_config or basic_config or kwargs: self._parse_attributes(self._kwargs, suppress_warnings=(not kwargs or suppress_warnings)) def _parse_attributes(self, dict_to_parse, suppress_warnings=False): if not dict_to_parse: return for config_key in dict_to_parse: # Recurse down all dictionaries if isinstance(dict_to_parse[config_key], dict): self._parse_attributes(dict_to_parse[config_key]) continue # Skip so we don't accidentally re-add this dictionary # Update attributes from said dictionary found_param_entry = next((param_entry for param_entry in self._param_map if config_key == param_entry.ext_name), None) if found_param_entry: # Update the internal parameter entry self._update_attribute( param_map=found_param_entry, param_val=dict_to_parse[found_param_entry.ext_name], suppress_warnings=suppress_warnings) else: # Key is unknown to us _print_known_keys(self._param_map) raise ValueError("Unknown configuration key: " + str(config_key)) @staticmethod def _raise_user_param_missing_error(param_entry): err_text = "The parameter with name: '" + str(param_entry.ext_name) + "' is required but " err_text += "was not set or passed.\n" # If this item is an enum print known values if param_entry.enum_class: known_vals = _get_enum_values(param_entry.enum_class) err_text += "Acceptable values for this parameter are: " + str(known_vals[0]) for val in known_vals[1:]: err_text += ", " + str(val) raise AttributeError(err_text) def _update_attribute(self, param_map, param_val, suppress_warnings): attribute_name = param_map.int_name if param_map.enum_class: # Check value falls within valid enum range and get the correct capital version param_val = _check_value_is_in_enum(param_val, param_map.enum_class) # Does the attribute exist - has it changed and are we suppressing warnings if not suppress_warnings: previous_value = getattr(self, attribute_name) if hasattr(self, attribute_name) else None if previous_value and previous_value != param_val: # Print warning of what we value we are replacing for which parameter warnings.warn("Replacing parameter: '" + str(param_map.ext_name) + "' which was previously set to: '" + str(getattr(self, attribute_name)) + "' with new value: '" + str(param_val) + "'") # Finally set the new attribute value setattr(self, attribute_name, param_val) def _check_value_is_in_enum(val, enum): """ Checks the the specified value is in the enum object. If it is it will return the correctly capitalised version which should be used. This is so the script not longer needs to convert to lower / upper case. If the value was not in the enum it raises a value error and tells the user the values available :param val: The value to search for in the enumeration :param enum: The enum object to check against. :return: The correctly cased val. Otherwise raises a value error. """ seen_val_in_enum = False enum_known_vals = _get_enum_values(enum_cls=enum) lower_string_val = str(val).lower() for enum_val in enum_known_vals: if lower_string_val == enum_val.lower(): # Get the correctly capitalised value so we no longer have to call lower val = enum_val seen_val_in_enum = True break # Check to see if the value was seen if seen_val_in_enum: # Return the correctly capitalised value to be set return val else: e_msg = "The user specified value: '" + str(val) + "' is unknown. " e_msg += "Known values for " + enum.enum_friendly_name + " are: \n" for key in enum_known_vals: e_msg += '\'' + key + '\' ' raise ValueError(e_msg) def _get_enum_values(enum_cls): """ Gets all acceptable values for the specified enum class and returns them as a list :param enum_cls: The enum to process :return: List of accepted values for this enum """ enum_known_vals = [] for k, enum_val in iteritems(enum_cls.__dict__): # Get all class attribute and value pairs except enum_friendly_name if k.startswith("__") or k.lower() == "enum_friendly_name": continue enum_known_vals.append(enum_val) return enum_known_vals def _print_known_keys(master_mapping): print ("\nKnown keys are:") print("----------------------------------") sorted_attributes = sorted(master_mapping, key=lambda param_map_entry: param_map_entry.ext_name) for param_entry in sorted_attributes: print (param_entry.ext_name + ', ', end="") print("\n----------------------------------")
gpl-3.0
nacjm/MatterOverdrive
src/main/java/matteroverdrive/client/data/Color.java
3056
/* * This file is part of Matter Overdrive * Copyright (c) 2015., Simeon Radivoev, All rights reserved. * * Matter Overdrive 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. * * Matter Overdrive 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 Matter Overdrive. If not, see <http://www.gnu.org/licenses>. */ package matteroverdrive.client.data; /** * Created by Simeon on 12/22/2015. */ public class Color extends Number { public static final Color WHITE = new Color(255, 255, 255); public static final Color RED = new Color(255, 0, 0); public static final Color GREEN = new Color(0, 255, 0); public static final Color BLUE = new Color(0, 0, 255); private final int color; public Color(int color) { this.color = color; } public Color(int r, int g, int b) { this(r, g, b, 255); } public Color(int r, int g, int b, int a) { this(b & 255 | (g & 255) << 8 | (r & 255) << 16 | (a & 255) << 24); } public Color multiplyWithoutAlpha(float multiply) { return multiply(multiply, multiply, multiply, 1f); } public Color multiplyWithAlpha(float multiply) { return multiply(multiply, multiply, multiply, multiply); } public Color multiply(float rm, float gm, float bm, float am) { return new Color((int)(getIntR() * rm), (int)(getIntG() * gm), (int)(getIntB() * bm), (int)(getIntA() * am)); } public Color add(Color color) { return new Color(getIntR() + color.getIntR(), getIntG() + color.getIntG(), getIntB() + color.getIntB(), getIntA() + color.getIntA()); } public Color subtract(Color color) { return new Color(getIntR() - color.getIntR(), getIntG() - color.getIntG(), getIntB() - color.getIntB(), getIntA() - color.getIntA()); } //region INT getters and setters public int getIntR() { return this.color >> 16 & 255; } public int getIntG() { return this.color >> 8 & 255; } public int getIntB() { return this.color & 255; } public int getIntA() { return this.color >> 24 & 255; } public int getColor() { return color; } //endregion //region FLOAT setters and getters public float getFloatR() { return (float)getIntR() / 255f; } public float getFloatG() { return (float)getIntG() / 255f; } public float getFloatB() { return (float)getIntB() / 255f; } public float getFloatA() { return (float)getIntA() / 255f; } @Override public int intValue() { return color; } @Override public long longValue() { return (long)color; } @Override public float floatValue() { return (float)color; } @Override public double doubleValue() { return (double)color; } //endregion }
gpl-3.0
dkavraal/typecatcher
typecatcher_lib/xdg.py
1047
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # Copyright (C) 2012 Andrew Starr-Bochicchio <a.starr.b@gmail.com> # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. ### END LICENSE import os from gi.repository import GLib homeDir = os.environ.get('HOME') confDir = os.path.join(GLib.get_user_config_dir(), 'typecatcher/') cacheDir = os.path.join(GLib.get_user_cache_dir(), 'typecatcher/') fontDir = os.path.join(homeDir, '.fonts/typecatcher/')
gpl-3.0
frazzy123/madisonclone
app/database/migrations/2014_05_22_163151_alter_annotations_increase_field_length.php
2458
<?php class AlterAnnotationsIncreaseFieldLength extends DualMigration { public function upMySQL(){ DB::statement('ALTER TABLE `annotations` MODIFY COLUMN `quote` TEXT'); DB::statement('ALTER TABLE `annotations` MODIFY COLUMN `text` TEXT'); } public function downMySQL(){ DB::statement('ALTER TABLE `annotations` MODIFY COLUMN `quote` VARCHAR(255)'); DB::statement('ALTER TABLE `annotations` MODIFY COLUMN `text` VARCHAR(255)'); } public function upSQLite() { DB::statement('PRAGMA foreign_keys = OFF'); Schema::create('annotations_temp', function($table) { $table->engine = "InnoDB"; $table->increments('id'); $table->string('search_id')->nullable(); $table->integer('user_id')->unsigned(); $table->integer('doc_id')->unsigned(); $table->text('quote'); $table->text('text'); $table->string('uri'); $table->timestamps(); // $table->foreign('user_id')->references('id')->on('users'); // $table->foreign('doc_id')->references('id')->on('docs'); // $table->unique('search_id'); }); DB::statement('INSERT INTO `annotations_temp` (`id`, `search_id`, `user_id`, `doc_id`, `quote`, `text`, `uri`, `created_at`, `updated_at`) SELECT `id`, `search_id`, `user_id`, `doc_id`, `quote`, `text`, `uri`, `created_at`, `updated_at` FROM `annotations`'); Schema::drop('annotations'); Schema::rename('annotations_temp', 'annotations'); DB::statement('PRAGMA foreign_keys = ON'); } public function downSQLite() { DB::statement('PRAGMA foreign_keys = OFF'); Schema::create('annotations_temp', function($table) { $table->engine = "InnoDB"; $table->increments('id'); $table->string('search_id')->nullable(); $table->integer('user_id')->unsigned(); $table->integer('doc_id')->unsigned(); $table->string('quote'); $table->string('text'); $table->string('uri'); $table->timestamps(); // $table->foreign('user_id')->references('id')->on('users'); // $table->foreign('doc_id')->references('id')->on('docs'); // $table->unique('search_id'); }); DB::statement('INSERT INTO `annotations_temp` (`id`, `search_id`, `user_id`, `doc_id`, `quote`, `text`, `uri`, `created_at`, `updated_at`) SELECT `id`, `search_id`, `user_id`, `doc_id`, `quote`, `text`, `uri`, `created_at`, `updated_at` FROM `annotations`'); Schema::drop('annotations'); Schema::rename('annotations_temp', 'annotations'); DB::statement('PRAGMA foreign_keys = ON'); } }
gpl-3.0
lrpirlet/Marlin
Marlin/src/lcd/menu/menu_delta_calibrate.cpp
5065
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ // // Delta Calibrate Menu // #include "../../inc/MarlinConfigPre.h" #if HAS_LCD_MENU && EITHER(DELTA_CALIBRATION_MENU, DELTA_AUTO_CALIBRATION) #include "menu_item.h" #include "../../module/delta.h" #include "../../module/motion.h" #include "../../module/planner.h" #if HAS_LEVELING #include "../../feature/bedlevel/bedlevel.h" #endif #if ENABLED(EXTENSIBLE_UI) #include "../extui/ui_api.h" #endif void _man_probe_pt(const xy_pos_t &xy) { if (!ui.wait_for_move) { ui.wait_for_move = true; do_blocking_move_to_xy_z(xy, Z_CLEARANCE_BETWEEN_PROBES); ui.wait_for_move = false; ui.synchronize(); ui.manual_move.menu_scale = _MAX(PROBE_MANUALLY_STEP, MIN_STEPS_PER_SEGMENT / planner.settings.axis_steps_per_mm[0]); // Use first axis as for delta XYZ should always match ui.goto_screen(lcd_move_z); } } #if ENABLED(DELTA_AUTO_CALIBRATION) #include "../../MarlinCore.h" // for wait_for_user_response() #include "../../gcode/gcode.h" #if ENABLED(HOST_PROMPT_SUPPORT) #include "../../feature/host_actions.h" // for host_prompt_do #endif float lcd_probe_pt(const xy_pos_t &xy) { _man_probe_pt(xy); ui.defer_status_screen(); TERN_(HOST_PROMPT_SUPPORT, host_prompt_do(PROMPT_USER_CONTINUE, PSTR("Delta Calibration in progress"), CONTINUE_STR)); TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired_P(PSTR("Delta Calibration in progress"))); wait_for_user_response(); ui.goto_previous_screen_no_defer(); return current_position.z; } #endif #if ENABLED(DELTA_CALIBRATION_MENU) #include "../../gcode/queue.h" void _lcd_calibrate_homing() { _lcd_draw_homing(); if (all_axes_homed()) ui.goto_previous_screen(); } void _lcd_delta_calibrate_home() { queue.inject_P(G28_STR); ui.goto_screen(_lcd_calibrate_homing); } void _goto_tower_a(const_float_t a) { xy_pos_t tower_vec = { cos(RADIANS(a)), sin(RADIANS(a)) }; _man_probe_pt(tower_vec * delta_calibration_radius()); } void _goto_tower_x() { _goto_tower_a(210); } void _goto_tower_y() { _goto_tower_a(330); } void _goto_tower_z() { _goto_tower_a( 90); } void _goto_center() { xy_pos_t ctr{0}; _man_probe_pt(ctr); } #endif void lcd_delta_settings() { auto _recalc_delta_settings = []{ TERN_(HAS_LEVELING, reset_bed_level()); // After changing kinematics bed-level data is no longer valid recalc_delta_settings(); }; START_MENU(); BACK_ITEM(MSG_DELTA_CALIBRATE); EDIT_ITEM(float52sign, MSG_DELTA_HEIGHT, &delta_height, delta_height - 10, delta_height + 10, _recalc_delta_settings); #define EDIT_ENDSTOP_ADJ(LABEL,N) EDIT_ITEM_P(float43, PSTR(LABEL), &delta_endstop_adj.N, -5, 0, _recalc_delta_settings) EDIT_ENDSTOP_ADJ("Ex", a); EDIT_ENDSTOP_ADJ("Ey", b); EDIT_ENDSTOP_ADJ("Ez", c); EDIT_ITEM(float52sign, MSG_DELTA_RADIUS, &delta_radius, delta_radius - 5, delta_radius + 5, _recalc_delta_settings); #define EDIT_ANGLE_TRIM(LABEL,N) EDIT_ITEM_P(float43, PSTR(LABEL), &delta_tower_angle_trim.N, -5, 5, _recalc_delta_settings) EDIT_ANGLE_TRIM("Tx", a); EDIT_ANGLE_TRIM("Ty", b); EDIT_ANGLE_TRIM("Tz", c); EDIT_ITEM(float52sign, MSG_DELTA_DIAG_ROD, &delta_diagonal_rod, delta_diagonal_rod - 5, delta_diagonal_rod + 5, _recalc_delta_settings); END_MENU(); } void menu_delta_calibrate() { #if ENABLED(DELTA_CALIBRATION_MENU) const bool all_homed = all_axes_homed(); // Acquire ahead of loop #endif START_MENU(); BACK_ITEM(MSG_MAIN); #if ENABLED(DELTA_AUTO_CALIBRATION) GCODES_ITEM(MSG_DELTA_AUTO_CALIBRATE, PSTR("G33")); #if ENABLED(EEPROM_SETTINGS) ACTION_ITEM(MSG_STORE_EEPROM, ui.store_settings); ACTION_ITEM(MSG_LOAD_EEPROM, ui.load_settings); #endif #endif SUBMENU(MSG_DELTA_SETTINGS, lcd_delta_settings); #if ENABLED(DELTA_CALIBRATION_MENU) SUBMENU(MSG_AUTO_HOME, _lcd_delta_calibrate_home); if (all_homed) { SUBMENU(MSG_DELTA_CALIBRATE_X, _goto_tower_x); SUBMENU(MSG_DELTA_CALIBRATE_Y, _goto_tower_y); SUBMENU(MSG_DELTA_CALIBRATE_Z, _goto_tower_z); SUBMENU(MSG_DELTA_CALIBRATE_CENTER, _goto_center); } #endif END_MENU(); } #endif // HAS_LCD_MENU && (DELTA_CALIBRATION_MENU || DELTA_AUTO_CALIBRATION)
gpl-3.0
LivingInSyn/Py_LogOff
V2_Current/HTC-LogOut/HTC-LogOut/obj/x64/Release/Warning.g.i.cs
4812
#pragma checksum "..\..\..\Warning.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "5AFCDE6A1623AAE5141E8E271535F389" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using HTC_LogOut; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace HTC_LogOut { /// <summary> /// Warning /// </summary> public partial class Warning : System.Windows.Controls.Page, System.Windows.Markup.IComponentConnector { #line 20 "..\..\..\Warning.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock TextLine1; #line default #line hidden #line 21 "..\..\..\Warning.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock TextLine2; #line default #line hidden #line 22 "..\..\..\Warning.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock TextLine3; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/HTC-LogOut;component/warning.xaml", System.UriKind.Relative); #line 1 "..\..\..\Warning.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.TextLine1 = ((System.Windows.Controls.TextBlock)(target)); return; case 2: this.TextLine2 = ((System.Windows.Controls.TextBlock)(target)); return; case 3: this.TextLine3 = ((System.Windows.Controls.TextBlock)(target)); return; case 4: #line 25 "..\..\..\Warning.xaml" ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.five_more); #line default #line hidden return; case 5: #line 28 "..\..\..\Warning.xaml" ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.logout_now); #line default #line hidden return; } this._contentLoaded = true; } } }
gpl-3.0
Philips14171/qt-creator-opensource-src-4.2.1
src/plugins/help/openpageswidget.cpp
4460
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "openpageswidget.h" #include "centralwidget.h" #include "openpagesmodel.h" #include <coreplugin/coreconstants.h> #include <QAbstractItemModel> #include <QApplication> #include <QMenu> using namespace Help::Internal; // -- OpenPagesWidget OpenPagesWidget::OpenPagesWidget(OpenPagesModel *sourceModel, QWidget *parent) : OpenDocumentsTreeView(parent) , m_allowContextMenu(true) { setModel(sourceModel); setContextMenuPolicy(Qt::CustomContextMenu); updateCloseButtonVisibility(); connect(this, &OpenDocumentsTreeView::activated, this, &OpenPagesWidget::handleActivated); connect(this, &OpenDocumentsTreeView::closeActivated, this, &OpenPagesWidget::handleCloseActivated); connect(this, &OpenDocumentsTreeView::customContextMenuRequested, this, &OpenPagesWidget::contextMenuRequested); connect(model(), &QAbstractItemModel::rowsInserted, this, &OpenPagesWidget::updateCloseButtonVisibility); connect(model(), &QAbstractItemModel::rowsRemoved, this, &OpenPagesWidget::updateCloseButtonVisibility); } OpenPagesWidget::~OpenPagesWidget() { } void OpenPagesWidget::selectCurrentPage() { QItemSelectionModel * const selModel = selectionModel(); selModel->clearSelection(); selModel->select(model()->index(CentralWidget::instance()->currentIndex(), 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); scrollTo(currentIndex()); } void OpenPagesWidget::allowContextMenu(bool ok) { m_allowContextMenu = ok; } // -- private void OpenPagesWidget::contextMenuRequested(QPoint pos) { QModelIndex index = indexAt(pos); if (!index.isValid() || !m_allowContextMenu) return; if (index.column() == 1) index = index.sibling(index.row(), 0); QMenu contextMenu; QAction *closeEditor = contextMenu.addAction(tr("Close %1").arg(index.data() .toString())); QAction *closeOtherEditors = contextMenu.addAction(tr("Close All Except %1") .arg(index.data().toString())); if (model()->rowCount() == 1) { closeEditor->setEnabled(false); closeOtherEditors->setEnabled(false); } QAction *action = contextMenu.exec(mapToGlobal(pos)); if (action == closeEditor) emit closePage(index); else if (action == closeOtherEditors) emit closePagesExcept(index); } void OpenPagesWidget::handleActivated(const QModelIndex &index) { if (index.column() == 0) { emit setCurrentPage(index); } else if (index.column() == 1) { // the funky close button if (model()->rowCount() > 1) emit closePage(index); // work around a bug in itemviews where the delegate wouldn't get the QStyle::State_MouseOver QWidget *vp = viewport(); const QPoint &cursorPos = QCursor::pos(); QMouseEvent e(QEvent::MouseMove, vp->mapFromGlobal(cursorPos), cursorPos, Qt::NoButton, 0, 0); QCoreApplication::sendEvent(vp, &e); } } void OpenPagesWidget::handleCloseActivated(const QModelIndex &index) { if (model()->rowCount() > 1) emit closePage(index); } void OpenPagesWidget::updateCloseButtonVisibility() { setCloseButtonVisible(model() && model()->rowCount() > 1); }
gpl-3.0
Revaj/MyCourses
TallerProgsis/Practica 6/src/Convertidor.java
1931
import java.util.StringTokenizer; public class Convertidor { public Convertidor(){ } //Decimales vuelven normal, demas bases se analizan si son negativos o no public int regresaConversion(String cadena){ int num = 0; if(cadena.startsWith("#")) cadena = cadena.substring(1); if(cadena.startsWith(",")) return 0; StringTokenizer separaComa = new StringTokenizer(cadena,","); cadena = separaComa.nextToken(); System.out.print(cadena); if(!cadena.startsWith("%") && !cadena.startsWith("@") && !cadena.startsWith("$") ) num = Integer.parseInt(cadena); else{ switch(cadena.charAt(0)){ case '%': num = conversionBases(cadena.substring(1),"1", 2); break; case '$': num = conversionBases(cadena.substring(1),"F", 16); break; case '@': num = conversionBases(cadena.substring(1),"7", 8); break; default: num = Integer.parseInt(cadena); break; } } return num; } private static int conversionBases(String cadena, String base, int numBase){ int num = 0; //Posicion libre del bit significativo int sinBitSigno = 0; System.out.println(cadena + numBase); //Buscamos donde eliminar los bits if(cadena.startsWith(base)){ if(base.equals("F")){ cadena = Integer.toBinaryString(Integer.parseInt(cadena,16)); base = "1"; numBase = 2; } else if (base.equals("7")){ cadena = Integer.toBinaryString(Integer.parseInt(cadena,8)); base = "1"; numBase = 2; } for(int i = 0; i<cadena.length(); i++){ if(cadena.charAt(i) == base.charAt(0)) sinBitSigno = i; else break; } cadena = cadena.substring(sinBitSigno); num = ~ Integer.parseInt(cadena, numBase) + 1; } else //Numeros positivos num = Integer.parseInt(cadena, numBase); System.out.println(num); return num; } }
gpl-3.0
Allors/apps
Domains/Apps/Workspace/Typescript/Intranet/src/allors/material/apps/objects/upcaidentification/edit/upcaidentification.module.ts
2517
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule, MatCardModule, MatDividerModule, MatFormFieldModule, MatIconModule, MatListModule, MatMenuModule, MatRadioModule, MatToolbarModule, MatTooltipModule, MatOptionModule, MatSelectModule, MatInputModule, MatTabsModule } from '@angular/material'; import { AllorsMaterialChipsModule } from '../../../../base/components/chips'; import { AllorsMaterialFooterModule } from '../../../../base/components/footer'; import { AllorsMaterialDatepickerModule } from '../../../../base/components/datepicker'; import { AllorsMaterialDatetimepickerModule } from '../../../../base/components/datetimepicker'; import { AllorsMaterialFileModule } from '../../../../base/components/file'; import { AllorsMaterialInputModule } from '../../../../base/components/input'; import { AllorsMaterialSelectModule } from '../../../../base/components/select'; import { AllorsMaterialSideNavToggleModule } from '../../../../base/components/sidenavtoggle'; import { AllorsMaterialSlideToggleModule } from '../../../../base/components/slidetoggle'; import { AllorsMaterialStaticModule } from '../../../../base/components/static'; import { AllorsMaterialTextAreaModule } from '../../../../base/components/textarea'; import { EditUpcaIdentificationComponent } from './upcaidentification-edit.component'; export { EditUpcaIdentificationComponent } from './upcaidentification-edit.component'; @NgModule({ declarations: [ EditUpcaIdentificationComponent, ], exports: [ EditUpcaIdentificationComponent, ], imports: [ AllorsMaterialChipsModule, AllorsMaterialDatepickerModule, AllorsMaterialDatetimepickerModule, AllorsMaterialFileModule, AllorsMaterialFooterModule, AllorsMaterialInputModule, AllorsMaterialSelectModule, AllorsMaterialSideNavToggleModule, AllorsMaterialSlideToggleModule, AllorsMaterialStaticModule, AllorsMaterialTextAreaModule, CommonModule, FormsModule, MatButtonModule, MatCardModule, MatDividerModule, MatFormFieldModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatRadioModule, MatSelectModule, MatTabsModule, MatToolbarModule, MatTooltipModule, MatOptionModule, ReactiveFormsModule, RouterModule, ], }) export class UpcaIdentificationModule { }
gpl-3.0
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/LanguageSelector/ImSwitch.py
55
../../../../share/pyshared/LanguageSelector/ImSwitch.py
gpl-3.0
telerik/justdecompile-plugins
Reflexil.JustDecompile/reflexil.1.5.src/Handlers/PropertyDefinitionHandler.Designer.cs
5249
namespace Reflexil.Handlers { partial class PropertyDefinitionHandler { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.TabControl = new System.Windows.Forms.TabControl(); this.TabAttributes = new System.Windows.Forms.TabPage(); this.Attributes = new Reflexil.Editors.PropertyAttributesControl(); this.TabCustomAttributes = new System.Windows.Forms.TabPage(); this.CustomAttributes = new Reflexil.Editors.CustomAttributeGridControl(); this.TabControl.SuspendLayout(); this.TabAttributes.SuspendLayout(); this.TabCustomAttributes.SuspendLayout(); this.SuspendLayout(); // // TabControl // this.TabControl.Controls.Add(this.TabAttributes); this.TabControl.Controls.Add(this.TabCustomAttributes); this.TabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.TabControl.Location = new System.Drawing.Point(0, 0); this.TabControl.Name = "TabControl"; this.TabControl.SelectedIndex = 0; this.TabControl.Size = new System.Drawing.Size(526, 400); this.TabControl.TabIndex = 0; // // TabAttributes // this.TabAttributes.Controls.Add(this.Attributes); this.TabAttributes.Location = new System.Drawing.Point(4, 22); this.TabAttributes.Name = "TabAttributes"; this.TabAttributes.Padding = new System.Windows.Forms.Padding(3); this.TabAttributes.Size = new System.Drawing.Size(518, 374); this.TabAttributes.TabIndex = 0; this.TabAttributes.Text = "Attributes"; this.TabAttributes.UseVisualStyleBackColor = true; // // Attributes // this.Attributes.Dock = System.Windows.Forms.DockStyle.Fill; this.Attributes.Item = null; this.Attributes.Location = new System.Drawing.Point(3, 3); this.Attributes.Name = "Attributes"; this.Attributes.ReadOnly = false; this.Attributes.Size = new System.Drawing.Size(512, 368); this.Attributes.TabIndex = 0; // // TabCustomAttributes // this.TabCustomAttributes.Controls.Add(this.CustomAttributes); this.TabCustomAttributes.Location = new System.Drawing.Point(4, 22); this.TabCustomAttributes.Name = "TabCustomAttributes"; this.TabCustomAttributes.Padding = new System.Windows.Forms.Padding(3); this.TabCustomAttributes.Size = new System.Drawing.Size(518, 374); this.TabCustomAttributes.TabIndex = 1; this.TabCustomAttributes.Text = "Custom attributes"; this.TabCustomAttributes.UseVisualStyleBackColor = true; // // CustomAttributes // this.CustomAttributes.Dock = System.Windows.Forms.DockStyle.Fill; this.CustomAttributes.Location = new System.Drawing.Point(3, 3); this.CustomAttributes.Name = "CustomAttributes"; this.CustomAttributes.ReadOnly = false; this.CustomAttributes.Size = new System.Drawing.Size(512, 368); this.CustomAttributes.TabIndex = 0; this.CustomAttributes.GridUpdated += new Reflexil.Editors.GridControl<Mono.Cecil.CustomAttribute, Mono.Cecil.ICustomAttributeProvider>.GridUpdatedEventHandler(this.CustomAttributes_GridUpdated); // // PropertyDefinitionHandler // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.TabControl); this.Name = "PropertyDefinitionHandler"; this.Size = new System.Drawing.Size(526, 400); this.TabControl.ResumeLayout(false); this.TabAttributes.ResumeLayout(false); this.TabCustomAttributes.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabControl TabControl; private System.Windows.Forms.TabPage TabAttributes; private Reflexil.Editors.PropertyAttributesControl Attributes; private System.Windows.Forms.TabPage TabCustomAttributes; private Editors.CustomAttributeGridControl CustomAttributes; } }
gpl-3.0
Polfo/sigma-h
sigmah/src/main/java/org/sigmah/server/endpoint/export/sigmah/spreadsheet/template/LogFrameCalcTemplate.java
21012
/* * All Sigmah code is released under the GNU General Public License v3 * See COPYRIGHT.txt and LICENSE.txt. */ package org.sigmah.server.endpoint.export.sigmah.spreadsheet.template; import java.io.OutputStream; import java.util.List; import java.util.Set; import org.odftoolkit.odfdom.dom.style.OdfStyleFamily; import org.odftoolkit.odfdom.dom.style.props.OdfParagraphProperties; import org.odftoolkit.odfdom.dom.style.props.OdfTableCellProperties; import org.odftoolkit.odfdom.dom.style.props.OdfTextProperties; import org.odftoolkit.odfdom.incubator.doc.office.OdfOfficeAutomaticStyles; import org.odftoolkit.odfdom.incubator.doc.style.OdfStyle; import org.odftoolkit.odfdom.type.Color; import org.odftoolkit.simple.SpreadsheetDocument; import org.odftoolkit.simple.style.Border; import org.odftoolkit.simple.style.Font; import org.odftoolkit.simple.style.StyleTypeDefinitions; import org.odftoolkit.simple.style.StyleTypeDefinitions.CellBordersType; import org.odftoolkit.simple.style.StyleTypeDefinitions.FontStyle; import org.odftoolkit.simple.style.StyleTypeDefinitions.HorizontalAlignmentType; import org.odftoolkit.simple.style.StyleTypeDefinitions.VerticalAlignmentType; import org.odftoolkit.simple.table.Cell; import org.odftoolkit.simple.table.CellRange; import org.odftoolkit.simple.table.Row; import org.odftoolkit.simple.table.Table; import org.sigmah.server.endpoint.export.sigmah.spreadsheet.CalcUtils; import org.sigmah.server.endpoint.export.sigmah.spreadsheet.ExportConstants; import org.sigmah.server.endpoint.export.sigmah.spreadsheet.data.LogFrameExportData; import org.sigmah.shared.domain.Indicator; import org.sigmah.shared.domain.logframe.ExpectedResult; import org.sigmah.shared.domain.logframe.LogFrameActivity; import org.sigmah.shared.domain.logframe.LogFrameGroup; import org.sigmah.shared.domain.logframe.Prerequisite; import org.sigmah.shared.domain.logframe.SpecificObjective; /* * Open document spreadsheet template for log logframe * * @author sherzod */ public class LogFrameCalcTemplate implements ExportTemplate { private final LogFrameExportData data; private Row row; private Cell cell; private CellRange cellRange; private final Table table; private final SpreadsheetDocument doc; private StringBuilder builder; private final Color gray = Color.valueOf(ExportConstants.GRAY_10_HEX); private final Color lightOrange = Color.valueOf(ExportConstants.LIGHTORANGE_HEX); private String coreCellStyle; public LogFrameCalcTemplate(final LogFrameExportData data,final SpreadsheetDocument exDoc) throws Throwable { this.data=data; if(exDoc==null){ doc = SpreadsheetDocument.newSpreadsheetDocument(); table = doc.getSheetByIndex(0); table.setTableName(data.getLocalizedVersion("logFrame").replace(" ", "_")); }else{ doc=exDoc; table=doc.appendSheet(data.getLocalizedVersion("logFrame").replace(" ", "_")); } setUpCoreStyle(); int rowIndex = -1; int cellIndex = 0; //skip row ++rowIndex; // title row = table.getRowByIndex(++rowIndex); cell = row.getCellByIndex(1); cell.setStringValue(data.getLocalizedVersion("logFrame").toUpperCase()); cell.setTextWrapped(true); cell.setFont(getBoldFont(14)); cell.setVerticalAlignment(ExportConstants.ALIGN_VER_MIDDLE); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_CENTER); cellRange = table.getCellRangeByPosition(1, rowIndex, data.getNumbOfCols(), rowIndex); cellRange.merge(); row.setHeight(7, false); putEmptyRow(++rowIndex); // info putInfoRow(++rowIndex, data.getLocalizedVersion("logFrameActionTitle"), data.getTitleOfAction()); putInfoRow(++rowIndex, data.getLocalizedVersion("logFrameMainObjective"), data.getMainObjective()); putEmptyRow(++rowIndex); // column headers row = table.getRowByIndex(++rowIndex); cellIndex = 3; putHeader(++cellIndex, data.getLocalizedVersion("logFrameInterventionLogic")); putHeader(++cellIndex, data.getLocalizedVersion("indicators")); putHeader(++cellIndex,data.getLocalizedVersion("logFrameMeansOfVerification")); putHeader(++cellIndex, data.getLocalizedVersion("logFrameRisksAndAssumptions")); row.setHeight(6, false); //empty row row = table.getRowByIndex(++rowIndex); row.setHeight(3.8, false); row.getCellByIndex(4).setCellStyleName(null); row.getCellByIndex(5).setCellStyleName(null); row.getCellByIndex(6).setCellStyleName(null); row.getCellByIndex(7).setCellStyleName(null); //TODO consider to implement freeze pane boolean titleIsSet = false; boolean hasElement=false; int typeStartRow = rowIndex + 1; //SO if (data.getEnableSpecificObjectivesGroups()) { hasElement=data.getSoMap().keySet().size()>0; for (final LogFrameGroup soGroup : data.getSoMap().keySet()) { ++rowIndex; // type (only once) SO,ER,A if (!titleIsSet) { putTypeCell(rowIndex, data.getLocalizedVersion("logFrameSpecificObjectives"), data.getLocalizedVersion("logFrameSpecificObjectivesCode")); titleIsSet = true; } // groups putGroupCell(rowIndex,data.getLocalizedVersion("logFrameGroup") , data.getLocalizedVersion("logFrameSpecificObjectivesCode"), soGroup.getLabel()); // items per group rowIndex=putSOItems(rowIndex, false, data.getSoMap().get(soGroup)); } // merge type cell if(hasElement){ mergeCell(1, typeStartRow, 1, rowIndex); } }else{ hasElement=data.getSoMainList().size()>0; if(hasElement){ ++rowIndex; putTypeCell(rowIndex, data.getLocalizedVersion("logFrameSpecificObjectives"), data.getLocalizedVersion("logFrameSpecificObjectivesCode")); rowIndex = putSOItems(rowIndex, true,data.getSoMainList()); mergeCell(1, typeStartRow, 1, rowIndex); } } //ER if(data.getEnableExpectedResultsGroups()){ hasElement=data.getErMap().keySet().size()>0; titleIsSet = false; typeStartRow = rowIndex + 1; for (final LogFrameGroup erGroup : data.getErMap().keySet()) { ++rowIndex; // type (only once) SO,ER,A if (!titleIsSet) { putTypeCell(rowIndex, data.getLocalizedVersion("logFrameExceptedResults"), data.getLocalizedVersion("logFrameExceptedResultsCode")); titleIsSet = true; } // groups putGroupCell(rowIndex,data.getLocalizedVersion("logFrameGroup") , data.getLocalizedVersion("logFrameExceptedResultsCode"), erGroup.getLabel()); // items per group rowIndex=putERItems(rowIndex, false, data.getErMap().get(erGroup)); } // merge type cell if(data.getErMap().keySet().size()>0){ mergeCell(1, typeStartRow, 1, rowIndex); } }else{ hasElement=data.getErMainList().size()>0; if(hasElement){ typeStartRow = rowIndex + 1; ++rowIndex; putTypeCell(rowIndex, data.getLocalizedVersion("logFrameExceptedResults"), data.getLocalizedVersion("logFrameExceptedResultsCode")); rowIndex = putERItems(rowIndex, true,data.getErMainList()); mergeCell(1, typeStartRow, 1, rowIndex); } } //Activities if(data.getEnableActivitiesGroups()){ hasElement=data.getAcMap().keySet().size()>0; titleIsSet = false; typeStartRow = rowIndex + 1; for (final LogFrameGroup aGroup : data.getAcMap().keySet()) { ++rowIndex; // type (only once) SO,ER,A if (!titleIsSet) { putTypeCell(rowIndex, data.getLocalizedVersion("logFrameActivities"), data.getLocalizedVersion("logFrameActivitiesCode")); titleIsSet = true; } // groups putGroupCell(rowIndex,data.getLocalizedVersion("logFrameGroup"), data.getLocalizedVersion("logFrameActivitiesCode"), aGroup.getLabel()); // items per group rowIndex=putAcItems(rowIndex, false, data.getAcMap().get(aGroup)); } // merge type cell if(data.getAcMap().keySet().size()>0){ mergeCell(1, typeStartRow, 1, rowIndex); } }else{ hasElement=data.getAcMainList().size()>0; if(hasElement){ typeStartRow = rowIndex + 1; ++rowIndex; putTypeCell(rowIndex,data.getLocalizedVersion("logFrameActivities"), data.getLocalizedVersion("logFrameActivitiesCode")); rowIndex = putAcItems(rowIndex, true,data.getAcMainList()); mergeCell(1, typeStartRow, 1, rowIndex); } } //Prerequisites if(data.getEnablePrerequisitesGroups()){ hasElement=data.getPrMap().keySet().size()>0; titleIsSet = false; typeStartRow = rowIndex + 1; for (final LogFrameGroup pGroup : data.getPrMap().keySet()) { ++rowIndex; // type (only once) SO,ER,A if (!titleIsSet) { putTypeCell(rowIndex, data.getLocalizedVersion("logFramePrerequisites"), data.getLocalizedVersion("logFramePrerequisitesCode")); titleIsSet = true; } // groups putGroupCell(rowIndex,data.getLocalizedVersion("logFrameGroup"), data.getLocalizedVersion("logFramePrerequisitesCode"), pGroup.getLabel()); // items per group rowIndex=putPrItems(rowIndex, false, data.getPrMap().get(pGroup)); } // merge type cell if(data.getPrMap().keySet().size()>0){ mergeCell(1, typeStartRow, 1, rowIndex); } }else{ hasElement=data.getPrMainList().size()>0; if(hasElement){ typeStartRow = rowIndex + 1; ++rowIndex; putTypeCell(rowIndex,data.getLocalizedVersion("logFramePrerequisites"), data.getLocalizedVersion("logFramePrerequisitesCode")); rowIndex = putPrItems(rowIndex, true,data.getPrMainList()); mergeCell(1, typeStartRow, 1, rowIndex); } } table.getColumnByIndex(0).setWidth(3.8); table.getColumnByIndex(1).setWidth(37.3); table.getColumnByIndex(2).setWidth(24); table.getColumnByIndex(3).setWidth(24); table.getColumnByIndex(4).setWidth(68); table.getColumnByIndex(5).setWidth(49); table.getColumnByIndex(6).setWidth(49); table.getColumnByIndex(7).setWidth(68); } private int putPrItems(int rowIndex,boolean skipFirst,List<Prerequisite> prList){ for (final Prerequisite p : prList) { if(!skipFirst){ ++rowIndex; } skipFirst=false; builder = new StringBuilder(data.getLocalizedVersion("logFramePrerequisitesCode")); builder.append(" "); builder.append(p.getCode()); builder.append("."); cell = createBasicCell(2, rowIndex,builder.toString()); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_CENTER); cell = createBasicCell(3, rowIndex,p.getContent()); cellRange = table.getCellRangeByPosition(3, rowIndex, data.getNumbOfCols(),rowIndex); cellRange.merge(); } return rowIndex; } private int putAcItems(int rowIndex,boolean skipFirst,List<LogFrameActivity> acList) throws Throwable{ for (final LogFrameActivity a : acList) { if(!skipFirst){ ++rowIndex; } skipFirst=false; builder = new StringBuilder(data.getLocalizedVersion("logFrameActivitiesCode")); builder.append(" ("); builder.append(data.getLocalizedVersion("logFrameExceptedResultsCode")); builder.append(" "); builder.append(data.getFormattedCode(a.getParentExpectedResult().getParentSpecificObjective().getCode())); builder.append(a.getParentExpectedResult().getCode()); builder.append("."); builder.append(")"); cell = createBasicCell(2, rowIndex,builder.toString()); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_CENTER); builder = new StringBuilder(data.getLocalizedVersion("logFrameActivitiesCode")); builder.append(" "); builder.append(data.getFormattedCode(a.getParentExpectedResult().getParentSpecificObjective().getCode())); builder.append(a.getParentExpectedResult().getCode()); builder.append("."); builder.append(a.getCode()); builder.append("."); cell = createBasicCell(3, rowIndex,builder.toString()); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_CENTER); createBasicCell(4, rowIndex, a.getTitle()); createBasicCell(7, rowIndex,""); // indicators and their means of verifications rowIndex = putIndicators(a.getIndicators(),rowIndex,false); } return rowIndex; } private int putERItems(int rowIndex,boolean skipFirst,List<ExpectedResult> erList) throws Throwable{ for (final ExpectedResult er : erList) { if(!skipFirst){ ++rowIndex; } skipFirst=false; builder = new StringBuilder(data.getLocalizedVersion("logFrameExceptedResultsCode")); builder.append(" ("); builder.append(data.getLocalizedVersion("logFrameSpecificObjectivesCode")); builder.append(" "); builder.append(data.getFormattedCode(er.getParentSpecificObjective().getCode())); builder.append(")"); cell = createBasicCell(2, rowIndex,builder.toString()); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_CENTER); builder = new StringBuilder(data.getLocalizedVersion("logFrameExceptedResultsCode")); builder.append(" "); builder.append(data.getFormattedCode(er.getParentSpecificObjective().getCode())); builder.append(er.getCode()); builder.append("."); cell = createBasicCell(3, rowIndex,builder.toString()); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_CENTER); createBasicCell(4, rowIndex, er.getInterventionLogic()); createBasicCell(7, rowIndex,er.getRisksAndAssumptions()); // indicators and their means of verifications rowIndex = putIndicators(er.getIndicators(),rowIndex,false); } return rowIndex; } private int putSOItems(int rowIndex,boolean skipFirst,List<SpecificObjective> soList) throws Throwable{ for (final SpecificObjective so :soList) { if(!skipFirst){ ++rowIndex; } skipFirst=false; builder = new StringBuilder(data.getLocalizedVersion("logFrameSpecificObjectivesCode")); builder.append(" "); builder.append(data.getFormattedCode(so.getCode())); cell = createBasicCell(2, rowIndex,builder.toString()); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_CENTER); createBasicCell(4, rowIndex, so.getInterventionLogic()); createBasicCell(7, rowIndex,so.getRisksAndAssumptions()); // indicators and their means of verifications rowIndex = putIndicators(so.getIndicators(),rowIndex,true); } return rowIndex; } private void mergeCell(int startCol, int startRow, int endCol, int endRow){ cellRange = table.getCellRangeByPosition( startCol, startRow, endCol, endRow); cellRange.merge(); } private void setUpCoreStyle() throws Throwable{ OdfOfficeAutomaticStyles styles = doc.getContentDom().getOrCreateAutomaticStyles(); OdfStyle style = styles.newStyle(OdfStyleFamily.TableCell); style.setProperty(OdfTableCellProperties.Border,"0.035cm solid #000000"); style.setProperty(OdfTableCellProperties.WrapOption, "wrap"); style.setProperty(OdfTableCellProperties.BackgroundColor, "#ffffff"); style.setProperty(OdfTableCellProperties.VerticalAlign, "middle"); style.setProperty(OdfParagraphProperties.TextAlign, "left"); style.setProperty(OdfParagraphProperties.MarginBottom, "0.2cm"); style.setProperty(OdfParagraphProperties.MarginTop, "0.2cm"); style.setProperty(OdfTableCellProperties.PaddingTop, "0.2cm"); style.setProperty(OdfTableCellProperties.PaddingBottom, "0.2cm"); style.setProperty(OdfTableCellProperties.PaddingLeft, "0.2cm"); style.setProperty(OdfTextProperties.FontWeight, "Regular"); style.setProperty(OdfTextProperties.FontSize, "10pt"); coreCellStyle = style.getStyleNameAttribute(); } private int putIndicators(final Set<Indicator> indicators, int rowIndex,boolean mergeCodeCells) throws Throwable{ if (indicators.size() > 0) { int startIndex = rowIndex; for (final Indicator indicator : indicators) { if(data.isIndicatorsSheetExist()){ cell=createBasicCell(5, rowIndex, null); CalcUtils.applyLink(cell, indicator.getName(),ExportConstants.INDICATOR_SHEET_PREFIX+ indicator.getName()); }else{ cell = createBasicCell(5, rowIndex, data.getDetailedIndicatorName(indicator.getId())); } cell = createBasicCell(6, rowIndex, indicator.getSourceOfVerification()); rowIndex++; } rowIndex--; for (int i = startIndex; i <= rowIndex; i++) { cell = cellRange.getCellByPosition(7, i); cell.setBorders(CellBordersType.RIGHT, getBorder()); } if(mergeCodeCells){ cellRange = table.getCellRangeByPosition(2, startIndex, 3,rowIndex); cellRange.merge(); }else{ cellRange = table.getCellRangeByPosition(2, startIndex, 2,rowIndex); cellRange.merge(); cellRange = table.getCellRangeByPosition(3, startIndex, 3,rowIndex); cellRange.merge(); } cellRange = table.getCellRangeByPosition(4, startIndex, 4,rowIndex); cellRange.merge(); cellRange = table.getCellRangeByPosition(7, startIndex, 7,rowIndex); cellRange.merge(); } else { cell = createBasicCell(5, rowIndex, null); cell = createBasicCell(6, rowIndex, null); if(mergeCodeCells){ cellRange = table.getCellRangeByPosition(2, rowIndex, 3,rowIndex); cellRange.merge(); }else{ cellRange = table.getCellRangeByPosition(2, rowIndex, 2,rowIndex); cellRange.merge(); cellRange = table.getCellRangeByPosition(3, rowIndex, 3,rowIndex); cellRange.merge(); } } return rowIndex; } private void putTypeCell(int rowIndex,String label,String code){ StringBuilder builder = new StringBuilder(label); builder.append(" ("); builder.append(code); builder.append(")"); cell = createBasicCell(1, rowIndex,builder.toString()); cell.setCellBackgroundColor(gray); cell.setFont(getBoldFont(10)); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_CENTER); } private void putGroupCell(int rowIndex,String groupType,String code,String groupLabel){ StringBuilder builder = new StringBuilder(groupType); builder.append(" ("); builder.append(code); builder.append(") - "); builder.append(groupLabel); cell = createBasicCell(2, rowIndex, builder.toString()); cell.setCellBackgroundColor(lightOrange); cell.setFont(getFont(10, false, true)); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_LEFT); cellRange = table.getCellRangeByPosition(2, rowIndex, data.getNumbOfCols(), rowIndex); cellRange.merge(); } private Cell createBasicCell(int colIndex, int rowIndex, String value) { cell = table.getCellByPosition(colIndex, rowIndex); cell.setStringValue(value); cell.setCellStyleName(coreCellStyle); return cell; } private void putHeader(int cellIndex, String header) { cell = row.getCellByIndex(cellIndex); cell.setStringValue(header); cell.setBorders(CellBordersType.ALL_FOUR, getBorder()); cell.setCellBackgroundColor(gray); cell.setFont(getBoldFont(10)); cell.setVerticalAlignment(ExportConstants.ALIGN_VER_MIDDLE); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_CENTER); cell.setTextWrapped(true); } private Border getBorder() { return new Border(Color.BLACK, 1, StyleTypeDefinitions.SupportedLinearMeasure.PT); } private void putEmptyRow(int rowIndex) { row = table.getRowByIndex(rowIndex); row.setHeight(3.8, false); } private void putInfoRow(int rowIndex, String key, String value) { String space = " "; row = table.getRowByIndex(rowIndex); cell = row.getCellByIndex(1); cell.setStringValue(space + key); cell.setFont(getBoldFont(11)); cell.setTextWrapped(true); cell.setVerticalAlignment(ExportConstants.ALIGN_VER_MIDDLE); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_LEFT); cell = row.getCellByIndex(2); if(value!=null) cell.setStringValue(space + value); cell.setFont(getRegFont(11)); cell.setVerticalAlignment(ExportConstants.ALIGN_VER_MIDDLE); cell.setHorizontalAlignment(ExportConstants.ALIGH_HOR_LEFT); cellRange = table.getCellRangeByPosition(2, rowIndex, data.getNumbOfCols(), rowIndex); cellRange.merge(); row.setHeight(6, false); } private Font getFont(int size, boolean bold, boolean italic) { FontStyle style = StyleTypeDefinitions.FontStyle.REGULAR; if (bold) style = StyleTypeDefinitions.FontStyle.BOLD; if (italic) style = StyleTypeDefinitions.FontStyle.ITALIC; return new Font("Arial", style, size, Color.BLACK); } private Font getBoldFont(int size) { return getFont(size, true, false); } private Font getRegFont(int size) { return getFont(size, false, false); } @Override public void write(OutputStream output) throws Throwable { doc.save(output); doc.close(); } }
gpl-3.0
bcgov/sbc-qsystem
QSystem/src/ru/apertum/qsystem/client/forms/FTimedDialog.java
10088
/* * Copyright (C) 2010 {Apertum}Projects. web: www.apertum.ru email: info@apertum.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 * (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 ru.apertum.qsystem.client.forms; import java.awt.Font; import java.awt.Frame; import org.jdesktop.application.Application; import org.jdesktop.application.ResourceMap; import ru.apertum.qsystem.QSystem; import ru.apertum.qsystem.client.common.WelcomeParams; import ru.apertum.qsystem.client.model.QButton; import ru.apertum.qsystem.common.Uses; import ru.apertum.qsystem.common.model.ATalkingClock; /** * Created on 15.01.2010, 17:49:14 * * @author Evgeniy Egorov */ public class FTimedDialog extends javax.swing.JDialog { private static FTimedDialog dialog; private static ResourceMap localeMap = null; /** * Таймер висения диалога на мониторе */ public ATalkingClock clockClose; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton buttonClose; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JLabel labelMess; /** * Creates new form FTimedDialog */ public FTimedDialog(Frame parent, boolean modal) { super(parent, modal); initComponents(); buttonClose.setIcon(new javax.swing.ImageIcon( getClass() .getResource("/ru/apertum/qsystem/client/forms/resources/stop.png"))); // NOI18N if (WelcomeParams.getInstance().btnFont != null) { buttonClose.setFont(WelcomeParams.getInstance().btnFont); } else { buttonClose.setFont(Font.decode("Tahoma-Plain-36")); } } private static String getLocaleMessage(String key) { if (localeMap == null) { localeMap = Application.getInstance(QSystem.class).getContext() .getResourceMap(FTimedDialog.class); } return localeMap.getString(key); } /** * Статический метод который показывает модально диалог регистрации клиентов. * * @param parent фрейм относительно которого будет модальность * @param modal модальный диалог или нет */ public static void showTimedDialog(Frame parent, boolean modal, String message, int timeout) { if (dialog == null) { dialog = new FTimedDialog(parent, modal); dialog.setTitle("Сообщение."); } dialog.setBounds(10, 10, 1024, 400); dialog.changeTextToLocale(); dialog.labelMess.setText(message); Uses.setLocation(dialog); dialog.clockClose = new ATalkingClock(timeout, 1) { @Override public void run() { dialog.buttonCloseActionPerformed(null); } }; dialog.clockClose.start(); dialog.setVisible(true); } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT * modify this code. The content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); buttonClose = new QButton(WelcomeParams.getInstance().servButtonType); labelMess = new javax.swing.JLabel(); setName("Form"); // NOI18N setUndecorated(true); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application .getInstance(ru.apertum.qsystem.QSystem.class).getContext() .getResourceMap(FTimedDialog.class); jPanel1.setBackground(resourceMap.getColor("jPanel1.background")); // NOI18N jPanel1.setName("jPanel1"); // NOI18N jPanel2.setBackground(resourceMap.getColor("jPanel2.background")); // NOI18N jPanel2.setName("jPanel2"); // NOI18N buttonClose.setFont(resourceMap.getFont("buttonClose.font")); // NOI18N buttonClose.setIcon(resourceMap.getIcon("buttonClose.icon")); // NOI18N buttonClose.setText(resourceMap.getString("buttonClose.text")); // NOI18N buttonClose .setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory .createBevelBorder(javax.swing.border.BevelBorder.RAISED, null, resourceMap.getColor("buttonClose.border.outsideBorder.highlightInnerColor"), null, null), javax.swing.BorderFactory .createBevelBorder(javax.swing.border.BevelBorder.RAISED))); // NOI18N buttonClose.setName("buttonClose"); // NOI18N buttonClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonCloseActionPerformed(evt); } }); labelMess.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); labelMess.setText(resourceMap.getString("labelMess.text")); // NOI18N labelMess.setName("labelMess"); // NOI18N javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(buttonClose, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(labelMess, javax.swing.GroupLayout.DEFAULT_SIZE, 769, Short.MAX_VALUE)) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(labelMess, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(buttonClose, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents private void changeTextToLocale() { final org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application .getInstance(ru.apertum.qsystem.QSystem.class).getContext() .getResourceMap(FTimedDialog.class); buttonClose.setText(resourceMap.getString("buttonClose.text")); // NOI18N } private void buttonCloseActionPerformed( java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCloseActionPerformed if (clockClose.isActive()) { clockClose.stop(); } clockClose = null; setVisible(false); }//GEN-LAST:event_buttonCloseActionPerformed // End of variables declaration//GEN-END:variables }
gpl-3.0
tokuhirom/roma
java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CloseCommand.java
747
package jp.co.rakuten.rit.roma.client.commands; import java.io.IOException; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.command.CommandContext; /** * */ public class CloseCommand extends DefaultCommand { @Override protected void create(CommandContext context) throws BadCommandException { // TODO Auto-generated method stub } @Override protected boolean parseResult(CommandContext context) throws ClientException { // TODO Auto-generated method stub return false; } @Override protected void sendAndReceive(CommandContext context) throws IOException, ClientException { // TODO Auto-generated method stub } }
gpl-3.0
cylc/cylc
cylc/flow/scripts/report_timings.py
13218
#!/usr/bin/env python3 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. # Copyright (C) NIWA & British Crown (Met Office) & Contributors. # # 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/>. """cylc report-timings [OPTIONS] ARGS Display workflow timing information. Retrieve workflow timing information for wait and run time performance analysis. Raw output and summary output (in text or HTML format) are available. Output is sent to standard output, unless an output filename is supplied. Summary Output (the default): Data stratified by host and job runner that provides a statistical summary of: 1. Queue wait time (duration between task submission and start times) 2. Task run time (duration between start and succeed times) 3. Total run time (duration between task submission and succeed times) Summary tables can be output in plain text format, or HTML with embedded SVG boxplots. Both summary options require the Pandas library, and the HTML summary option requires the Matplotlib library. Raw Output: A flat list of tabular data that provides (for each task and cycle) the 1. Time of successful submission 2. Time of task start 3. Time of task successful completion as well as information about the job runner and remote host to permit stratification/grouping if desired by downstream processors. Timings are shown only for succeeded tasks. For long-running or large workflows (i.e. workflows with many task events), the database query to obtain the timing information may take some time. """ import collections import contextlib import io as StringIO import sys from typing import TYPE_CHECKING from cylc.flow.exceptions import CylcError from cylc.flow.option_parsers import CylcOptionParser as COP from cylc.flow.pathutil import get_workflow_run_pub_db_name from cylc.flow.rundb import CylcWorkflowDAO from cylc.flow.terminal import cli_function from cylc.flow.workflow_files import parse_reg if TYPE_CHECKING: from optparse import Values @contextlib.contextmanager def smart_open(filename=None): """ Allow context management for output to either a file or to standard output transparently. See https://stackoverflow.com/a/17603000 """ if filename and filename != '-': fh = open(filename, 'w') # noqa SIM115 (close done in finally block) else: fh = sys.stdout try: yield fh finally: if fh is not sys.stdout: fh.close() def get_option_parser(): parser = COP( __doc__, argdoc=[('WORKFLOW', 'Workflow name or ID')] ) parser.add_option( "-r", "--raw", help="Show raw timing output suitable for custom diagnostics.", action="store_true", default=False, dest="show_raw" ) parser.add_option( "-s", "--summary", help="Show textual summary timing output for tasks.", action="store_true", default=False, dest="show_summary" ) parser.add_option( "-w", "--web-summary", help="Show HTML summary timing output for tasks.", action="store_true", default=False, dest="html_summary" ) parser.add_option( "-O", "--output-file", help="Output to a specific file", action="store", default=None, dest="output_filename") return parser @cli_function(get_option_parser) def main(parser: COP, options: 'Values', workflow: str) -> None: workflow, _ = parse_reg(workflow) output_options = [ options.show_raw, options.show_summary, options.html_summary ] if output_options.count(True) > 1: parser.error('Cannot combine output formats (choose one)') if not any(output_options): # No output specified - choose summary by default options.show_summary = True run_db = _get_dao(workflow) row_buf = format_rows(*run_db.select_task_times()) with smart_open(options.output_filename) as output: if options.show_raw: output.write(row_buf.getvalue()) else: summary: TimingSummary if options.show_summary: summary = TextTimingSummary(row_buf) elif options.html_summary: summary = HTMLTimingSummary(row_buf) summary.write_summary(output) def format_rows(header, rows): """Write the rows in tabular format to a string buffer. Ensure that each column is wide enough to contain the widest data value and the widest header value. """ sio = StringIO.StringIO() max_lengths = [ max(data_len, head_len) for data_len, head_len in zip( (max(len(r[i]) for r in rows) for i in range(len(header))), (len(h) for h in header) ) ] formatter = ' '.join('%%-%ds' % line for line in max_lengths) + '\n' sio.write(formatter % header) for r in rows: sio.write(formatter % r) sio.seek(0) return sio def _get_dao(workflow): """Return the DAO (public) for workflow.""" return CylcWorkflowDAO( get_workflow_run_pub_db_name(workflow), is_public=True) class TimingSummary: """Base class for summarizing timing output from cylc.flow run database.""" def __init__(self, filepath_or_buffer=None): """Set up internal dataframe storage for time durations.""" self._check_imports() if filepath_or_buffer is not None: self.read_timings(filepath_or_buffer) else: self.df = None self.by_host_and_job_runner = None def read_timings(self, filepath_or_buffer): """ Set up time duration dataframe storage based on start/stop/succeed times from flat database output. """ import pandas as pd # Avoid truncation of content in columns. pd.set_option('display.max_colwidth', 10000) df = pd.read_csv( filepath_or_buffer, delim_whitespace=True, index_col=[0, 1, 2, 3], parse_dates=[4, 5, 6] ) self.df = pd.DataFrame({ 'queue_time': ( df['start_time'] - df['submit_time']).apply(self._dt_to_s), 'run_time': ( df['succeed_time'] - df['start_time']).apply(self._dt_to_s), 'total_time': ( df['succeed_time'] - df['submit_time']).apply(self._dt_to_s), }) self.df = self.df.rename_axis('timing_category', axis='columns') self.by_host_and_job_runner = self.df.groupby( level=['host', 'job_runner'] ) def write_summary(self, buf=None): """Using the stored timings dataframe, output the data summary.""" if buf is None: buf = sys.stdout self.write_summary_header(buf) for group, df in self.by_host_and_job_runner: self.write_group_header(buf, group) df_reshape = self._reshape_timings(df) df_describe = df.groupby(level='name').describe() if df_describe.index.nlevels > 1: df_describe = df_describe.unstack() # for pandas < 0.20.0 df_describe.index.rename(None, inplace=True) for timing_category in self.df.columns: self.write_category( buf, timing_category, df_reshape, df_describe ) self.write_summary_footer(buf) def write_summary_header(self, buf): pass def write_summary_footer(self, buf): pass def write_group_header(self, buf, group): pass def write_category(self, buf, category, df_reshape, df_describe): pass def _check_imports(self): try: import pandas except ImportError: raise CylcError('Cannot import pandas - summary unavailable.') else: del pandas @staticmethod def _reshape_timings(timings): """ Given a dataframe of timings returned from the Cylc DAO methods indexed by (task, cycle point, ...) with columns for the various timing categories, return a dataframe reshaped with an index of (timing category, cycle point, ...) with columns for each task. Need a special method rather than standard Pandas pivot-table to handle duplicated index entries properly. """ if timings.index.duplicated().any(): # The 'unstack' used to pivot the dataframe gives an error if # there are duplicate entries in the index (see #2509). The # best way around this seems to be to add an intermediate index # level (in this case a retry counter) to de-duplicate indices. counts = collections.defaultdict(int) retry = [] for t in timings.index: counts[t] += 1 retry.append(counts[t]) timings = timings.assign(retry=retry) timings = timings.set_index('retry', append=True) return timings.unstack('name').stack(level=0) @staticmethod def _dt_to_s(dt): import pandas as pd try: return dt.total_seconds() except AttributeError: # Older versions of pandas have the timedelta as a numpy # timedelta64 type, which didn't support total_seconds return pd.Timedelta(dt).total_seconds() class TextTimingSummary(TimingSummary): """Timing summary in text form.""" line_width = 80 def write_group_header(self, buf, group): title = 'Host: %s\tJob Runner: %s' % group buf.write('=' * self.line_width + '\n') buf.write(title.center(self.line_width - 1) + '\n') buf.write('=' * self.line_width + '\n') def write_category(self, buf, category, df_reshape, df_describe): buf.write(category.center(self.line_width) + '\n') buf.write(('-' * len(category)).center(self.line_width) + '\n') buf.write(df_describe[category].to_string()) buf.write('\n\n') class HTMLTimingSummary(TimingSummary): """Timing summary in HTML form.""" def write_summary_header(self, buf): css = """ body { font-family: Sans-Serif; text-align: center; } h1 { background-color: grey; } h2 { width: 85%; background-color: #f0f0f0; margin: auto; } table { width: 75%; margin: auto; border-collapse: collapse; } tr:nth-child(even) { background-color: #f2f2f2; } td { text-align: right; } th, td { border-bottom: 1px solid grey; } svg { width: 65%; height: auto; margin: auto; display: block; } .timing { padding-bottom: 40px; } """ buf.write('<html><head><style>%s</style></head><body>' % css) def write_summary_footer(self, buf): buf.write('</body></html>') def write_group_header(self, buf, group): buf.write('<h1>Timings for host %s using job runner %s</h1>' % group) def write_category(self, buf, category, df_reshape, df_describe): import matplotlib.pyplot as plt buf.write('<div class="timing" id=%s>' % category) buf.write('<h2>%s</h2>\n' % (category.replace('_', ' ').title())) ax = ( df_reshape .xs(category, level='timing_category') .plot(kind='box', vert=False) ) ax.invert_yaxis() ax.set_xlabel('Seconds') plt.tight_layout() plt.gcf().savefig(buf, format='svg') try: table = df_describe[category].to_html( classes="summary", index_names=False, border=0 ) except TypeError: # older pandas don't support the "border" argument # so explicitly remove it table = df_describe[category].to_html( classes="summary", index_names=False ) table = table.replace('border="1"', '') buf.write(table) buf.write('</div>') pass def _check_imports(self): try: import matplotlib matplotlib.use('Agg') except ImportError: raise CylcError( 'Cannot import matplotlib - HTML summary unavailable.' ) super(HTMLTimingSummary, self)._check_imports()
gpl-3.0
syslover33/ctank
java/android-sdk-linux_r24.4.1_src/sources/android-23/android/databinding/testapp/BasicDependantBindingTest.java
3165
/* * Copyright (C) 2015 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 android.databinding.testapp; import android.databinding.testapp.databinding.BasicDependantBindingBinding; import android.databinding.testapp.vo.NotBindableVo; import android.test.UiThreadTest; import java.util.ArrayList; import java.util.List; public class BasicDependantBindingTest extends BaseDataBinderTest<BasicDependantBindingBinding> { public BasicDependantBindingTest() { super(BasicDependantBindingBinding.class); } @Override protected void setUp() throws Exception { super.setUp(); initBinder(); } public List<NotBindableVo> permutations(String value) { List<NotBindableVo> result = new ArrayList<>(); result.add(null); result.add(new NotBindableVo(null)); result.add(new NotBindableVo(value)); return result; } @UiThreadTest public void testAllPermutations() { List<NotBindableVo> obj1s = permutations("a"); List<NotBindableVo> obj2s = permutations("b"); for (NotBindableVo obj1 : obj1s) { for (NotBindableVo obj2 : obj2s) { reCreateBinder(null); //get a new one testWith(obj1, obj2); reCreateBinder(null); mBinder.executePendingBindings(); testWith(obj1, obj2); } } } private void testWith(NotBindableVo obj1, NotBindableVo obj2) { mBinder.setObj1(obj1); mBinder.setObj2(obj2); mBinder.executePendingBindings(); assertValues(safeGet(obj1), safeGet(obj2), obj1 == null ? "" : obj1.mergeStringFields(obj2), obj2 == null ? "" : obj2.mergeStringFields(obj1), (obj1 == null ? null : obj1.getStringValue()) + (obj2 == null ? null : obj2.getStringValue()) ); } private String safeGet(NotBindableVo vo) { if (vo == null || vo.getStringValue() == null) { return ""; } return vo.getStringValue(); } private void assertValues(String textView1, String textView2, String mergedView1, String mergedView2, String rawMerge) { assertEquals(textView1, mBinder.textView1.getText().toString()); assertEquals(textView2, mBinder.textView2.getText().toString()); assertEquals(mergedView1, mBinder.mergedTextView1.getText().toString()); assertEquals(mergedView2, mBinder.mergedTextView2.getText().toString()); assertEquals(rawMerge, mBinder.rawStringMerge.getText().toString()); } }
gpl-3.0
Yuuji/bf-utils
samples/op/.brainfuckex/4b1df377af150556c5bd17477a453ebd.js
3492
var bfCall = function(bf, bfe, parameters, output, input) { bf.init(bfe, parameters, output, input); bf.move(1); var ret = bf.add(1); if (ret!==false) { return ret; } while (bf.getMem()) { while (bf.getMem()) { var ret =bf.add(-1); if (ret!==false) { return ret; } } bf.move(1); var ret = bf.add(5); if (ret!==false) { return ret; } while (bf.getMem()) { bf.move(-1); var ret = bf.add(5); if (ret!==false) { return ret; } bf.move(1); var ret =bf.add(-1); if (ret!==false) { return ret; } } bf.move(-1); var ret = bf.add(2); if (ret!==false) { return ret; } bf.move(-1); var ret = bf.add(1); if (ret!==false) { return ret; } bf.move(1); var ret =bf.add(-1); if (ret!==false) { return ret; } } bf.move(-1); bf.debug(); bf.move(5); while (bf.getMem()) { var ret =bf.add(-1); if (ret!==false) { return ret; } } bf.move(-1); bf.debug(); bf.move(2); while (bf.getMem()) { bf.move(1); } var ret = bf.add(3); if (ret!==false) { return ret; } bf.move(-1); while (bf.getMem()) { bf.move(-1); } bf.move(-1); bf.debug(); var ret =bf.add(-2); if (ret!==false) { return ret; } var ret = bf.add(2); if (ret!==false) { return ret; } var ret =bf.add(-1); if (ret!==false) { return ret; } while (bf.getMem()) { bf.move(2); var ret =bf.add(-3); if (ret!==false) { return ret; } while (bf.getMem()) { var ret = bf.add(3); if (ret!==false) { return ret; } while (bf.getMem()) { var ret =bf.add(-1); if (ret!==false) { return ret; } } bf.move(-2); while (bf.getMem()) { bf.move(2); var ret = bf.add(1); if (ret!==false) { return ret; } bf.move(-2); var ret =bf.add(-1); if (ret!==false) { return ret; } } bf.move(3); var ret =bf.add(-3); if (ret!==false) { return ret; } } var ret = bf.add(3); if (ret!==false) { return ret; } bf.move(-2); while (bf.getMem()) { var ret =bf.add(-1); if (ret!==false) { return ret; } } var ret = bf.add(1); if (ret!==false) { return ret; } bf.move(3); while (bf.getMem()) { bf.move(-3); while (bf.getMem()) { var ret =bf.add(-1); if (ret!==false) { return ret; } } } bf.move(1); bf.move(-2); while (bf.getMem()) { bf.move(-6); while (bf.getMem()) { var ret =bf.add(-1); if (ret!==false) { return ret; } } var ret = bf.add(4); if (ret!==false) { return ret; } bf.move(-1); while (bf.getMem()) { var ret =bf.add(-1); if (ret!==false) { return ret; } } var ret = bf.add(4); if (ret!==false) { return ret; } bf.move(-1); while (bf.getMem()) { var ret =bf.add(-1); if (ret!==false) { return ret; } } var ret = bf.add(4); if (ret!==false) { return ret; } bf.move(-1); while (bf.getMem()) { var ret =bf.add(-1); if (ret!==false) { return ret; } } var ret = bf.add(1); if (ret!==false) { return ret; } bf.move(-1); var ret = bf.add(1); if (ret!==false) { return ret; } } bf.move(3); while (bf.getMem()) { var ret =bf.add(-1); if (ret!==false) { return ret; } } bf.move(-1); var ret =bf.add(-1); if (ret!==false) { return ret; } } bf.move(2); var ret =bf.add(-3); if (ret!==false) { return ret; } while (bf.getMem()) { var ret = bf.add(3); if (ret!==false) { return ret; } bf.move(1); var ret =bf.add(-3); if (ret!==false) { return ret; } } var ret = bf.add(4); if (ret!==false) { return ret; } bf.move(-1); while (bf.getMem()) { bf.move(-1); } bf.move(1); var ret =bf.add(-4); if (ret!==false) { return ret; } while (bf.getMem()) { var ret = bf.add(4); if (ret!==false) { return ret; } bf.output(); bf.move(1); var ret =bf.add(-4); if (ret!==false) { return ret; } } var ret = bf.add(4); if (ret!==false) { return ret; } } module.exports = bfCall
gpl-3.0
webuildcity/hamburg
manage.py
246
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wbh.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
gpl-3.0
simonward86/spinw
external/chol_omp/chol_omp.cpp
17179
/*=========================================================== * chol_omp.cpp - Forms the Cholesky factorisation of a stack * of matrices using Lapack calls and OpenMP. * * R = chol_omp(M); - Errors if M != +ve def * [R,p] = chol_omp(M); - No error, R is p x p * L = chol_omp(M,'lower'); * [L,p] = chol_omp(M,'lower'); * where M is n x n x l, M=R'*R=L*L' * * Unlike the matlab built-in this mex does not handle sparse * matrices. In addition, spinW specific option are: * * ... = chol_omp(...,'tol',val) * where val is a constant to add to get +ve def-ness. * [K2,invK] = chol_omp(M,'Colpa') * where K2 = (R*gComm*R') is Hermitian. * gComm = [1...1,-1...1] is the commutator * invK = inv(R) * * Note this function does not check for symmetry. * Also note that we do not truncate the output matrix if * the input is not positive definite, unlike the built-in. * i.e. R or L is _always_ of size (n x n) not (p x p) * * This is a MEX-file for MATLAB. * * Original Author: M. D. Le [duc.le@stfc.ac.uk] * $Revision$ ($Date$) *=========================================================*/ #include <cfloat> #include <cstring> #include <cmath> #include <algorithm> #include "mex.h" #include "matrix.h" #include "blas.h" #include "lapack.h" #ifndef _OPENMP void omp_set_num_threads(int nThreads) {}; #define omp_get_num_threads() 1 #define omp_get_max_threads() 1 #define omp_get_thread_num() 0 #else #include <omp.h> #endif // Define templated gateways to single / double LAPACK functions template <typename T> void potrf(const char *uplo, const ptrdiff_t *n, T *a, const ptrdiff_t *lda, ptrdiff_t *info, bool is_complex) { mexErrMsgIdAndTxt("chol_omp:wrongtype","This function is only defined for single and double floats."); } template <> void potrf(const char *uplo, const ptrdiff_t *n, float *a, const ptrdiff_t *lda, ptrdiff_t *info, bool is_complex) { if(is_complex) return cpotrf(uplo, n, a, lda, info); else return spotrf(uplo, n, a, lda, info); } template <> void potrf(const char *uplo, const ptrdiff_t *n, double *a, const ptrdiff_t *lda, ptrdiff_t *info, bool is_complex) { if(is_complex) return zpotrf(uplo, n, a, lda, info); else return dpotrf(uplo, n, a, lda, info); } template <typename T> void trtri(const char *uplo, const char *diag, const ptrdiff_t *n, T *a, const ptrdiff_t *lda, ptrdiff_t *info, bool is_complex) { mexErrMsgIdAndTxt("chol_omp:wrongtype","This function is only defined for single and double floats."); } template <> void trtri(const char *uplo, const char *diag, const ptrdiff_t *n, float *a, const ptrdiff_t *lda, ptrdiff_t *info, bool is_complex) { if(is_complex) return ctrtri(uplo, diag, n, a, lda, info); else return strtri(uplo, diag, n, a, lda, info); } template <> void trtri(const char *uplo, const char *diag, const ptrdiff_t *n, double *a, const ptrdiff_t *lda, ptrdiff_t *info, bool is_complex) { if(is_complex) return ztrtri(uplo, diag, n, a, lda, info); else return dtrtri(uplo, diag, n, a, lda, info); } template <typename T> void trmm(const char *side, const char *uplo, const char *transa, const char *diag, const ptrdiff_t *m, const ptrdiff_t *n, const T *alpha, const T *a, const ptrdiff_t *lda, T *b, const ptrdiff_t *ldb, bool is_complex) { mexErrMsgIdAndTxt("chol_omp:wrongtype","This function is only defined for single and double floats."); } template <> void trmm(const char *side, const char *uplo, const char *transa, const char *diag, const ptrdiff_t *m, const ptrdiff_t *n, const float *alpha, const float *a, const ptrdiff_t *lda, float *b, const ptrdiff_t *ldb, bool is_complex) { if(is_complex) return ctrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); else return strmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); } template <> void trmm(const char *side, const char *uplo, const char *transa, const char *diag, const ptrdiff_t *m, const ptrdiff_t *n, const double *alpha, const double *a, const ptrdiff_t *lda, double *b, const ptrdiff_t *ldb, bool is_complex) { if(is_complex) return ztrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); else return dtrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb); } template <typename T> int do_loop(mxArray *plhs[], const mxArray *prhs[], int nthread, mwSignedIndex m, int nlhs, int *blkid, char uplo, T tol, bool do_Colpa); void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwSignedIndex m, n, nd; const size_t *dims; int ib, nblock, nb, err_code=0; bool do_Colpa = false; bool is_single = false; int *blkid; char uplo = 'U', *parstr; int nthread = omp_get_max_threads(); double tol = 0.; // mexPrintf("Number of threads = %d\n",nthread); // Checks inputs if(mxIsDouble(prhs[0])) { is_single = false; } else if(mxIsSingle(prhs[0])) { is_single = true; } else { mexErrMsgIdAndTxt("chol_omp:notfloat","Input matrix must be a float array."); } nd = mxGetNumberOfDimensions(prhs[0]); if(nd<2 || nd>3) { mexErrMsgIdAndTxt("chol_omp:wrongdims","Only 2D or 3D arrays are supported."); } dims = mxGetDimensions(prhs[0]); m = dims[0]; n = dims[1]; if(m!=n) { mexErrMsgIdAndTxt("chol_omp:notsquare","Input matrix is not square."); } if(nd==3) nblock = (int)dims[2]; else nblock = 1; // Checks for optional arguments for(ib=1; ib<nrhs; ib++) { if(mxIsChar(prhs[ib])) { parstr = mxArrayToString(prhs[ib]); if(strcmp(parstr,"lower")==0) uplo = 'L'; else if(strcmp(parstr,"Colpa")==0) do_Colpa = true; else if(strcmp(parstr,"tol")==0) { if((nrhs-1)>ib) { tol = *(mxGetPr(prhs[ib+1])); ib++; } else mexErrMsgIdAndTxt("chol_omp:badtolarg","'tol' option requires a scalar tolerance value."); } } } // More efficient to group blocks together to run in a single thread than to spawn one thread per matrix. if(nblock<nthread) { nthread = nblock; } blkid = new int[nthread+1]; blkid[0] = 0; blkid[nthread] = nblock; nb = nblock/nthread; for(int nt=1; nt<nthread; nt++) { blkid[nt] = blkid[nt-1]+nb; } // Creates outputs mxComplexity complexflag = mxIsComplex(prhs[0]) ? mxCOMPLEX : mxREAL; mxClassID classid = is_single ? mxSINGLE_CLASS : mxDOUBLE_CLASS; if(nd==2) plhs[0] = mxCreateNumericMatrix(m, m, classid, complexflag); else plhs[0] = mxCreateNumericArray(3, dims, classid, complexflag); if(nlhs>1) { if(do_Colpa) { if(nd==2) plhs[1] = mxCreateNumericMatrix(m, m, classid, complexflag); else plhs[1] = mxCreateNumericArray(3, dims, classid, complexflag); } else { if(nd==2) plhs[1] = mxCreateNumericMatrix(1, 1, classid, mxREAL); else plhs[1] = mxCreateNumericMatrix(1, nblock, classid, mxREAL); } } if(is_single) { float stol = std::max((float)tol, (float)sqrt(FLT_EPSILON)); err_code = do_loop(plhs, prhs, nthread, m, nlhs, blkid, uplo, stol, do_Colpa); } else { err_code = do_loop(plhs, prhs, nthread, m, nlhs, blkid, uplo, tol, do_Colpa); } delete[]blkid; if(err_code==1) mexErrMsgIdAndTxt("chol_omp:notposdef","The input matrix is not positive definite."); else if(err_code==2) mexErrMsgIdAndTxt("chol_omp:singular","The input matrix is singular."); } template <typename T> int do_loop(mxArray *plhs[], const mxArray *prhs[], int nthread, mwSignedIndex m, int nlhs, int *blkid, char uplo, T tol, bool do_Colpa) { int err_code = 0, ib=0; #pragma omp parallel default(none) shared(plhs,prhs,err_code) \ firstprivate(nthread, m, nlhs, ib, blkid, uplo, tol, do_Colpa) { #pragma omp for for(int nt=0; nt<nthread; nt++) { // These variables must be declared within the loop to make them local (and private) // or we get memory errors. T *M, *Mp, *ptr_M, *ptr_Mi, *ptr_I; mwSignedIndex lda = m, m2 = m*m, info, ii, jj, kk; mwSignedIndex f = mxIsComplex(prhs[0]) ? 2 : 1; char diag = 'N'; char trans = 'C'; char side = 'R'; T *alpha; if(mxIsComplex(prhs[0])) M = new T[2*m*m]; if(do_Colpa) { if(mxIsComplex(prhs[0])) { Mp = new T[2*m*m]; alpha = new T[2]; } else { Mp = new T[m*m]; alpha = new T[1]; } alpha[0] = 1.; } // Actual loop over individual matrices start here for(ib=blkid[nt]; ib<blkid[nt+1]; ib++) { // Loop is in case we want to try again with a constant added to the diagonal for(kk=0; kk<(tol>0?2:1); kk++) { // Populate the matrix input array (which will be overwritten by the Lapack function) if(mxIsComplex(prhs[0])) { memset(M, 0, 2*m*m*sizeof(T)); ptr_M = (T*)mxGetData(prhs[0]) + ib*m2; ptr_Mi = (T*)mxGetImagData(prhs[0]) + ib*m2; // Interleaves complex matrices - Matlab stores complex matrix as an array of real // values followed by an array of imaginary values; Fortran (and C++ std::complex) // and hence Lapack stores it as arrays of pairs of values (real,imaginary). for(ii=0; ii<m; ii++) { for(jj=(uplo=='U'?0:ii); jj<(uplo=='U'?ii+1:m); jj++) { M[ii*2*m+jj*2] = ptr_M[ii*m+jj]; M[ii*2*m+jj*2+1] = ptr_Mi[ii*m+jj]; } } } else { // *potrf overwrites the input array - copy only upper or lower triangle of input. M = (T*)mxGetData(plhs[0]) + ib*m2; ptr_M = (T*)mxGetData(prhs[0]) + ib*m2; if(uplo=='U') for(ii=0; ii<m; ii++) memcpy(M+ii*m, ptr_M+ii*m, (ii+1)*sizeof(T)); else for(ii=0; ii<m; ii++) memcpy(M+ii*m+ii, ptr_M+ii*m+ii, (m-ii)*sizeof(T)); } // Matrix not positive definite - try adding a small number to the diagonal. if(kk==1) for(ii=0; ii<m; ii++) M[ii*m*f+ii*f] += tol; // Calls the actual Lapack algorithm for real or complex input. if(mxIsComplex(prhs[0])) potrf(&uplo, &m, M, &lda, &info, true); else potrf(&uplo, &m, M, &lda, &info, false); // Matrix is positive definite, break out of loop. if(info==0) break; } if(info>0) { if(nlhs<=1 || do_Colpa) { #pragma omp critical { err_code = 1; } break; } else { ptr_I = (T*)mxGetData(plhs[1]) + ib; *ptr_I = (T)info; // Zeros the non positive parts of the factor. //kk = (mwSignedIndex)info-1; //if(uplo=='U') // for(ii=kk; ii<m; ii++) // memset(M+ii*f*m, 0, mxIsComplex(prhs[0]) ? m*2*sizeof(double) : m*sizeof(double)); //else // for(ii=0; ii<m; ii++) // memset(M+ii*f*m+kk*f, 0, mxIsComplex(prhs[0]) ? (m-kk)*2*sizeof(double) : (m-kk)*sizeof(double)); } } if(do_Colpa) { // Computes the Hermitian K^2 matrix = R*gComm*R'; memcpy(Mp, M, mxIsComplex(prhs[0]) ? m*m*2*sizeof(T) : m*m*sizeof(T)); // Applies the commutator [1..1,-1..-1] to the cholesky factor transposed for(ii=m/2; ii<m; ii++) for(jj=0; jj<m; jj++) Mp[ii*f*m+jj*f] = -Mp[ii*f*m+jj*f]; if(mxIsComplex(prhs[0])) for(ii=m/2; ii<m; ii++) for(jj=0; jj<m; jj++) Mp[ii*f*m+jj*f+1] = -Mp[ii*f*m+jj*f+1]; if(mxIsComplex(prhs[0])) trmm(&side, &uplo, &trans, &diag, &m, &m, alpha, M, &lda, Mp, &lda, true); else trmm(&side, &uplo, &trans, &diag, &m, &m, alpha, M, &lda, Mp, &lda, false); // Computes the inverse of the triangular factors (still stored in M) if(nlhs>1) { if(mxIsComplex(prhs[0])) { trtri(&uplo, &diag, &m, M, &lda, &info, true); } else { M = (T*)mxGetData(plhs[1]) + ib*m2; ptr_M = (T*)mxGetData(plhs[0]) + ib*m2; if(uplo=='U') for(ii=0; ii<m; ii++) memcpy(M+ii*m, ptr_M+ii*m, (ii+1)*sizeof(T)); else for(ii=0; ii<m; ii++) memcpy(M+ii*m+ii, ptr_M+ii*m+ii, (m-ii)*sizeof(T)); trtri(&uplo, &diag, &m, M, &lda, &info, false); } if(info>0) { #pragma omp critical { err_code = 2; } break; } if(mxIsComplex(prhs[0])) { ptr_M = (T*)mxGetData(plhs[1]) + ib*m2; ptr_Mi = (T*)mxGetImagData(plhs[1]) + ib*m2; for(ii=0; ii<m; ii++) { for(jj=(uplo=='U'?0:ii); jj<(uplo=='U'?ii+1:m); jj++) { ptr_M[ii*m+jj] = M[ii*2*m+jj*2]; ptr_Mi[ii*m+jj] = M[ii*2*m+jj*2+1]; } } } } // Finally copies the output of the K^2=K*g*K' calculation to Matlab left-hand-side // (We had to keep it memory to compute the inverse) if(mxIsComplex(prhs[0])) { ptr_M = (T*)mxGetData(plhs[0]) + ib*m2; ptr_Mi = (T*)mxGetImagData(plhs[0]) + ib*m2; for(ii=0; ii<m; ii++) { for(jj=0; jj<m; jj++) { *ptr_M++ = Mp[ii*2*m+jj*2]; *ptr_Mi++ = Mp[ii*2*m+jj*2+1]; } } } else { memcpy((T*)mxGetData(plhs[0])+ib*m2, Mp, m*m*sizeof(T)); } } else if(mxIsComplex(prhs[0])) { // Copy lapack output to matlab with interleaving ptr_M = (T*)mxGetData(plhs[0]) + ib*m2; ptr_Mi = (T*)mxGetImagData(plhs[0]) + ib*m2; for(ii=0; ii<m; ii++) { //for(jj=(uplo=='U'?ii:0); jj<(uplo=='U'?m:ii+1); jj++) { } for(jj=0; jj<m; jj++) { *ptr_M++ = M[ii*2*m+jj*2]; *ptr_Mi++ = M[ii*2*m+jj*2+1]; } } } if(err_code!=0) break; // One of the threads got a singular or not pos def error - break loop here. } // Free memory... if(mxIsComplex(prhs[0])) delete[]M; if(do_Colpa) { delete[]Mp; delete[]alpha; } #ifndef _OPENMP if(err_code!=0) break; #endif } } return err_code; }
gpl-3.0
lejacome/TranEspol
routes/posicionbus.js
1928
var meanCaseBase = require('../config/helpers/meanCaseBase.js'); var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var posicionbus = mongoose.model('posicionbus'); router.get('/posicionbus/:id', function (req, res) { posicionbus.findById(req.params.id, function (err, data) { res.json(data); }) }) /* GET posicionbus listing. */ router.get('/posicionbus', function(req, res, next) { posicionbus.find(function(err, models){ if(err){return next(err)} res.json(models) meanCaseBase.auditSave(req,'Query all Registers','posicionbus','Query all Registers'); }) }); /* POST - Add posicionbus. */ router.post('/posicionbus', function(req, res, next){ var model = new posicionbus(req.body); model.save(function(err, data){ if(err){return next(err)} res.json(data); meanCaseBase.auditSave(req,'Insert Register','posicionbus',data); }) }); /* PUT - Update posicionbus. */ router.put('/posicionbus/:id', function(req, res){ posicionbus.findById(req.params.id, function(err, data){ if(typeof req.body.idbus != "undefined"){data.idbus = req.body.idbus;} if(typeof req.body.fecha != "undefined"){data.fecha = req.body.fecha;} if(typeof req.body.latitud != "undefined"){data.latitud = req.body.latitud;} if(typeof req.body.longitud != "undefined"){data.longitud = req.body.longitud;} data.save(function(err){ if(err){res.send(err)} res.json(data); meanCaseBase.auditSave(req,'Update Register','posicionbus',data); }) }) }); /* DELETE - posicionbus. */ router.delete('/posicionbus/:id', function(req, res){ posicionbus.findByIdAndRemove(req.params.id, function(err){ if(err){res.send(err)} res.json({message: 'posicionbus delete successful!'}); meanCaseBase.auditSave(req,'Delete Register','posicionbus','Id: '+req.params.id); }) }); module.exports = router;
gpl-3.0
arielalmendral/ert
python/python/ert_gui/shell/results.py
1800
from ert.util import BoolVector from ert_gui.shell import assertConfigLoaded, ErtShellCollection from ert_gui.shell.libshell import splitArguments class Results(ErtShellCollection): def __init__(self, parent): super(Results, self).__init__("results", parent) self.addShellFunction(name="runpath", function=Results.runpath, help_message="Shows the current runpath.") self.addShellFunction(name="load", function=Results.load, completer=Results.completeLoad, help_arguments="<realizations>", help_message="Load results from the specified realizations.") #todo iterations @assertConfigLoaded def runpath(self, args): runpath = self.ert().getModelConfig().getRunpathAsString() print("Runpath set to: %s" % runpath) @assertConfigLoaded def load(self, args): arguments = splitArguments(args) if len(arguments) < 1: self.lastCommandFailed("Loading requires a realization mask.") return False realization_count = self.ert().getEnsembleSize() mask = BoolVector(False, realization_count) mask_success = mask.updateActiveMask(arguments[0]) if not mask_success: self.lastCommandFailed("The realization mask: '%s' is not valid." % arguments[0]) return False fs = self.ert().getEnkfFsManager().getCurrentFileSystem() self.ert().loadFromForwardModel(mask, 0, fs) @assertConfigLoaded def completeLoad(self, text, line, begidx, endidx): arguments = splitArguments(line) if len(arguments) > 2 or len(arguments) == 2 and not text: return [] if not text: return ["0-%d" % self.ert().getEnsembleSize()] # todo should generate based on realization directories. return []
gpl-3.0
richard-taylor/manyworlds
manyworlds/test/__init__.py
19
# not quite empty
gpl-3.0