code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
# This file is part of Rubber and thus covered by the GPL import rubber.dvip_tool import rubber.module_interface class Module (rubber.module_interface.Module): def __init__ (self, document, opt): self.dep = rubber.dvip_tool.Dvip_Tool_Dep_Node (document, 'dvips')
skapfer/rubber
src/latex_modules/dvips.py
Python
gpl-2.0
278
# Copyright (C) 2005 Colin McMillen <mcmillen@cs.cmu.edu> # # This file is part of GalaxyMage. # # GalaxyMage 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. # # GalaxyMage 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 GalaxyMage; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. import pygame import logging logger = logging.getLogger("gui") CURSOR_UP = pygame.USEREVENT + 1 CURSOR_DOWN = pygame.USEREVENT + 2 CURSOR_LEFT = pygame.USEREVENT + 3 CURSOR_RIGHT = pygame.USEREVENT + 4 CURSOR_ACCEPT = pygame.USEREVENT + 5 CURSOR_CANCEL = pygame.USEREVENT + 6 LOWER_CAMERA = pygame.USEREVENT + 7 RAISE_CAMERA = pygame.USEREVENT + 8 ROTATE_CAMERA_CW = pygame.USEREVENT + 9 ROTATE_CAMERA_CCW = pygame.USEREVENT + 10 ROTATE_CAMERA = pygame.USEREVENT + 11 PITCH_CAMERA = pygame.USEREVENT + 12 TRANSLATE_CAMERA = pygame.USEREVENT + 13 RAISE_TILE = pygame.USEREVENT + 14 LOWER_TILE = pygame.USEREVENT + 15 RAISE_CENTER = pygame.USEREVENT + 16 LOWER_CENTER = pygame.USEREVENT + 17 RAISE_B_BL_CORNER = pygame.USEREVENT + 18 RAISE_L_FL_CORNER = pygame.USEREVENT + 20 RAISE_F_FR_CORNER = pygame.USEREVENT + 21 RAISE_R_BR_CORNER = pygame.USEREVENT + 19 LOWER_B_BL_CORNER = pygame.USEREVENT + 22 LOWER_L_FL_CORNER = pygame.USEREVENT + 24 LOWER_F_FR_CORNER = pygame.USEREVENT + 25 LOWER_R_BR_CORNER = pygame.USEREVENT + 23 RAISE_WATER = pygame.USEREVENT + 26 LOWER_WATER = pygame.USEREVENT + 27 FPS = pygame.USEREVENT + 28 TOGGLE_SOUND = pygame.USEREVENT + 29 TOGGLE_FULLSCREEN = pygame.USEREVENT + 30 UNDO = pygame.USEREVENT + 31 START_CHAT = pygame.USEREVENT + 32 _input = None def get(): return _input class Event(object): def __init__(self, type_, data): self.type = type_ self.__dict__.update(data) def postUserEvent(type_, data={}): e = Event(type_, data) pygame.event.post(pygame.event.Event(pygame.USEREVENT, {'event': e})) class Input(object): def __init__(self, joystickID): global _input _input = self self._repeatDelay = 0.5 # seconds self._repeatInterval = 0.05 # seconds self.inDialog = False self._eventRepeatTime = {} self._joystick = None if pygame.joystick.get_count() > joystickID: self._joystick = pygame.joystick.Joystick(joystickID) self._joystick.init() logger.debug(("Initialized joystick %d " + "(buttons: %d, hats: %d, axes: %d)") % (self._joystick.get_id(), self._joystick.get_numbuttons(), self._joystick.get_numhats(), self._joystick.get_numaxes())) def joyButton(self, number): if self._joystick == None or self._joystick.get_numbuttons() <= number: return False return self._joystick.get_button(number) def joyHat(self, number, axis): if self._joystick == None or self._joystick.get_numhats() <= number: return 0 hat = self._joystick.get_hat(number) return hat[axis] def joyAxis(self, number): if self._joystick == None or self._joystick.get_numaxes() <= number: return 0.0 return self._joystick.get_axis(number) def setInDialog(self, inDialog): self.inDialog = inDialog if inDialog: pygame.key.set_repeat(300,100) else: pygame.key.set_repeat() for button in self._eventRepeatTime: self._eventRepeatTime[button] = self._repeatDelay def update(self, timeElapsed): if not self.inDialog: self.updateGuiEvents(timeElapsed) def updateGuiEvents(self, timeElapsed): keysPressed = pygame.key.get_pressed() mousePressed = pygame.mouse.get_pressed() mouseMotion = pygame.mouse.get_rel() # Generate events that are subject to repeat self.buttonPressed(timeElapsed, START_CHAT, keysPressed[pygame.K_t]) self.buttonPressed(timeElapsed, FPS, keysPressed[pygame.K_f]) self.buttonPressed(timeElapsed, TOGGLE_SOUND, keysPressed[pygame.K_s]) self.buttonPressed(timeElapsed, TOGGLE_FULLSCREEN, keysPressed[pygame.K_F12]) self.buttonPressed(timeElapsed, CURSOR_UP, keysPressed[pygame.K_UP] or self.joyAxis(5) < -0.8 or self.joyHat(0, 1) == 1) self.buttonPressed(timeElapsed, CURSOR_DOWN, keysPressed[pygame.K_DOWN] or self.joyAxis(5) > 0.8 or self.joyHat(0, 1) == -1) self.buttonPressed(timeElapsed, CURSOR_LEFT, keysPressed[pygame.K_LEFT] or self.joyAxis(4) < -0.8 or self.joyHat(0, 0) == -1) self.buttonPressed(timeElapsed, CURSOR_RIGHT, keysPressed[pygame.K_RIGHT] or self.joyAxis(4) > 0.8 or self.joyHat(0, 0) == 1) self.buttonPressed(timeElapsed, CURSOR_ACCEPT, keysPressed[pygame.K_RETURN] or self.joyButton(1)) self.buttonPressed(timeElapsed, CURSOR_CANCEL, keysPressed[pygame.K_ESCAPE] or self.joyButton(2)) self.buttonPressed(timeElapsed, LOWER_CAMERA, keysPressed[pygame.K_PAGEUP] or self.joyButton(6)) self.buttonPressed(timeElapsed, RAISE_CAMERA, keysPressed[pygame.K_PAGEDOWN] or self.joyButton(7)) self.buttonPressed(timeElapsed, ROTATE_CAMERA_CCW, keysPressed[pygame.K_LEFTBRACKET] or keysPressed[pygame.K_HOME] or self.joyButton(4)) self.buttonPressed(timeElapsed, ROTATE_CAMERA_CW, keysPressed[pygame.K_RIGHTBRACKET] or keysPressed[pygame.K_END] or self.joyButton(5)) self.buttonPressed(timeElapsed, RAISE_TILE, keysPressed[pygame.K_EQUALS]) self.buttonPressed(timeElapsed, LOWER_TILE, keysPressed[pygame.K_MINUS]) self.buttonPressed(timeElapsed, RAISE_CENTER, (keysPressed[pygame.K_s] and not (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT]))) self.buttonPressed(timeElapsed, LOWER_CENTER, (keysPressed[pygame.K_s] and (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT]))) self.buttonPressed(timeElapsed, RAISE_B_BL_CORNER, keysPressed[pygame.K_w] and not (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT])) self.buttonPressed(timeElapsed, RAISE_L_FL_CORNER, keysPressed[pygame.K_a] and not (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT])) self.buttonPressed(timeElapsed, RAISE_F_FR_CORNER, keysPressed[pygame.K_x] and not (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT])) self.buttonPressed(timeElapsed, RAISE_R_BR_CORNER, keysPressed[pygame.K_d] and not (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT])) self.buttonPressed(timeElapsed, LOWER_B_BL_CORNER, keysPressed[pygame.K_w] and (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT])) self.buttonPressed(timeElapsed, LOWER_L_FL_CORNER, keysPressed[pygame.K_a] and (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT])) self.buttonPressed(timeElapsed, LOWER_F_FR_CORNER, keysPressed[pygame.K_x] and (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT])) self.buttonPressed(timeElapsed, LOWER_R_BR_CORNER, keysPressed[pygame.K_d] and (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT])) self.buttonPressed(timeElapsed, RAISE_WATER, keysPressed[pygame.K_e] and not (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT])) self.buttonPressed(timeElapsed, LOWER_WATER, keysPressed[pygame.K_e] and (keysPressed[pygame.K_LSHIFT] or keysPressed[pygame.K_RSHIFT])) self.buttonPressed(timeElapsed, UNDO, keysPressed[pygame.K_BACKSPACE]) # Generate misc events # Quit if keysPressed[pygame.K_q] or self.joyButton(9): pygame.event.post(pygame.event.Event(pygame.QUIT)) # Rotate camera smoothly if mousePressed[2] and mouseMotion[0] != 0: postUserEvent(ROTATE_CAMERA, {'amount': mouseMotion[0]}) if abs(self.joyAxis(0)) > 0.8: amount = self.joyAxis(0) * timeElapsed * 180.0 postUserEvent(ROTATE_CAMERA, {'amount': amount}) # Pitch camera if mousePressed[2]: postUserEvent(PITCH_CAMERA, {'amount': mouseMotion[1]/3.0}) if abs(self.joyAxis(1)) > 0.8: amount = self.joyAxis(1) * timeElapsed * 90.0 postUserEvent(PITCH_CAMERA, {'amount': amount}) # Translate view if mousePressed[0]: x = mouseMotion[0] / 750.0 y = mouseMotion[1] / 750.0 postUserEvent(TRANSLATE_CAMERA, {'amount': (x, y)}) if abs(self.joyAxis(2)) > 0.2 or abs(self.joyAxis(3)) > 0.2: (x, y) = (0.0, 0.0) if abs(self.joyAxis(2)) > 0.2: x = -self.joyAxis(2) * timeElapsed * 0.75 if abs(self.joyAxis(3)) > 0.2: y = -self.joyAxis(3) * timeElapsed * 0.75 postUserEvent(TRANSLATE_CAMERA, {'amount': (x, y)}) def buttonPressed(self, timeElapsed, button, pressed): if not self._eventRepeatTime.has_key(button): self._eventRepeatTime[button] = -1.0 if pressed: generateEvent = False oldTime = self._eventRepeatTime[button] if oldTime == -1.0: generateEvent = True self._eventRepeatTime[button] = self._repeatDelay elif oldTime <= 0.0: generateEvent = True self._eventRepeatTime[button] = self._repeatInterval else: self._eventRepeatTime[button] -= timeElapsed if generateEvent: postUserEvent(button) else: self._eventRepeatTime[button] = -1.0
jemofthewest/GalaxyMage
src/gui/Input.py
Python
gpl-2.0
12,695
t = 1 # triangle number order, e.g. t=7 is 7th triangle number or 1+2+3+4+5+6+7=28 divisors = [] while len(divisors) <= 500: n = sum(range(1,t+1)) # Generate triangle number step = 2 if n%2 else 1 divisors = reduce(list.__add__, ([i, n//i] for i in range(1, int((n**0.5))+1, step) if n % i == 0)) # divisors = set(reduce(list.__add__, ([i, n//i] for i in range(1, int((n**0.5))+1, step) if n % i == 0))) t += 1 print n
blakegarretson/projecteuler
prob12.py
Python
gpl-2.0
452
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ .. module:: measurematrix.py .. moduleauthor:: Jozsef Attila Janko, Bence Takacs, Zoltan Siki (code optimalization) Sample application of Ulyxes PyAPI to measure within a rectangular area :param argv[1] (int): number of horizontal intervals (between measurements), default 1 (perimeter only) :param argv[2] (int): number of vertical intervals(between measurements), default 1 (perimeter only) :param argv[3] (sensor): 1100/1800/1200/5500, default 1100 :param argv[4] (port): serial port, default COM5 :param argv[5]: output file, default stdout usage: python measurematrix.py 9 3 1100 COM5 """ import re import sys sys.path.append('../pyapi/') from angle import Angle from serialiface import SerialIface from totalstation import TotalStation from echowriter import EchoWriter from filewriter import FileWriter from leicatps1200 import LeicaTPS1200 from leicatcra1100 import LeicaTCRA1100 from trimble5500 import Trimble5500 if __name__ == "__main__": if sys.version_info[0] > 2: # Python 3 compatibility raw_input = input if len(sys.argv) == 1: print("Usage: {0:s} horizontal_step vertical_step instrument port output_file".format(sys.argv[0])) exit(1) # set horizontal stepping interval dh_nr dh_nr = 1 if len(sys.argv) > 1: try: dh_nr = int(sys.argv[1]) except ValueError: print("invalid numeric value " + sys.argv[1]) sys.exit(1) # set vertical stepping interval dv_nr dv_nr = 1 if len(sys.argv) > 2: try: dv_nr = int(sys.argv[2]) except ValueError: print("invalid numeric value " + sys.argv[2]) #sys.exit(1) # set instrument stationtype = '1100' if len(sys.argv) > 3: stationtype = sys.argv[3] if re.search('120[0-9]$', stationtype): mu = LeicaTPS1200() elif re.search('110[0-9]$', stationtype): mu = LeicaTCRA1100() elif re.search('550[0-9]$', stationtype): mu = Trimble5500() else: print("unsupported instrument type") sys.exit(1) # set port port = '/dev/ttyUSB0' if len(sys.argv) > 4: port = sys.argv[4] iface = SerialIface("test", port) # set output file name fn = None if len(sys.argv) > 5: fn = sys.argv[5] # write out measurements if fn: wrt = FileWriter(angle='DEG', dist='.3f', fname=fn) else: wrt = EchoWriter(angle='DEG', dist='.3f') if wrt.GetState() != wrt.WR_OK: sys.exit(-1) # open error ts = TotalStation(stationtype, mu, iface, wrt) if isinstance(mu, Trimble5500): print("Please change to reflectorless EDM mode (MNU 722 from keyboard)") print("and turn on red laser (MNU 741 from keyboard) and press enter!") raw_input() else: ts.SetATR(0) # turn ATR off ts.SetEDMMode('RLSTANDARD') # reflectorless distance measurement ts.SetRedLaser(1) # turn red laser on w = raw_input("Target on lower left corner and press Enter") w1 = ts.GetAngles() w = raw_input("Target on upper right corner and press Enter") w2 = ts.GetAngles() dh = (w2['hz'].GetAngle() - w1['hz'].GetAngle()) / dh_nr dv = (w2['v'].GetAngle() - w1['v'].GetAngle()) / dv_nr # measurement loops for i in range(dh_nr+1): # horizontal loop measdir = i % 2 # check modulo hz = Angle(w1['hz'].GetAngle() + i * dh, 'RAD') for j in range(dv_nr+1): # vertical loop if measdir == 0: # move downward at odd steps to right ts.Move(hz, Angle(w1['v'].GetAngle() + j * dv, 'RAD')) else: # move upward at event steps to right ts.Move(hz, Angle(w2['v'].GetAngle() - j * dv, 'RAD')) ts.Measure() meas = ts.GetMeasure() if ts.measureIface.state != ts.measureIface.IF_OK or 'errorCode' in meas: print('FATAL Cannot measure point')
zsiki/ulyxes
pyapps/measurematrix.py
Python
gpl-2.0
4,051
import os import sys def main(): if len(sys.argv) <= 2: print("This script generates the .expected file from your PS3's debug logs.") print("") print("Usage: convert-ps3-output.py <input> <output>") print("Example: convert-ps3-output.py hello_world.log hello_world.expected") return False #Parse and check arguments inputFile = sys.argv[1] outputFile = sys.argv[2] if not os.path.isfile(inputFile): print("[!] Input file does not exist") return False f = open(inputFile, 'rb') w = open(outputFile, 'wb') data = f.read() data = data[data.find(b"/app_home/"):] data = data[data.find(b"\x0D\x0A")+2:] data = data[:data.rindex(b"END LOG")-12] data = data.replace(b"\x0D\x0A", b"\x0A") w.write(data) w.close() if __name__ == "__main__": main()
RPCS3/ps3autotests
utils/convert-ps3-output.py
Python
gpl-2.0
868
__author__ = 'Matteo' __doc__='''This could be made into a handy mutagenesis library if I had time.''' from Bio.Seq import Seq,MutableSeq from Bio import SeqIO from Bio.Alphabet import IUPAC from difflib import Differ def Gthg01471(): ori=Seq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCATTTATTTTCGGTACCGTTTCCAATGCATCAGCAACAATTAACTATGGGGAGGAAGTCGCGGCAGTAGCAAATGACTATGTAGGAAGCCCATATAAATATGGAGGTACAACGCCAAAAGGATTTGATGCGAGTGGCTTTACTCAGTATGTGTATAAAAATGCTGCAACCAAATTGGCTATTCCGCGAACGAGTGCCGCACAGTATAAAGTCGGTAAATTTGTTAAACAAAGTGCGTTACAAAGAGGCGATTTAGTGTTTTATGCAACAGGAGCAAAAGGAAAGGTATCCTTTGTGGGAATTTATAATGGAAATGGTACGTTTATTGGTGCCACATCAAAAGGGGTAAAAGTGGTTAAAATGAGTGATAAATATTGGAAAGACCGGTATATAGGGGCTAAGCGAGTCATTAAGTAA", IUPAC.unambiguous_dna) mut=MutableSeq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCATTTATTTTCGGTACCGTTTCCAATGCATCAGCAACAATTAACTATGGGGAGGAAGTCGCGGCAGTAGCAAATGACTATGTAGGAAGCCCATATAAATATGGAGGTACAACGCCAAAAGGATTTGATGCGAGTGGCTTTACTCAGTATGTGTATAAAAATGCTGCAACCAAATTGGCTATTCCGCGAACGAGTGCCGCACAGTATAAAGTCGGTAAATTTGTTAAACAAAGTGCGTTACAAAGAGGCGATTTAGTGTTTTATGCAACAGGAGCAAAAGGAAAGGTATCCTTTGTGGGAATTTATAATGGAAATGGTACGTTTATTGGTGCCACATCAAAAGGGGTAAAAGTGGTTAAAATGAGTGATAAATATTGGAAAGACCGGTATATAGGGGCTAAGCGAGTCATTAAGTAA", IUPAC.unambiguous_dna) a="AGTCGA" b="GACTAG" for i,v in enumerate([259,277,282,295,299,306]): print(mut[v-1]+a[i]) mut[v-1]=b[i] print(ori.translate()) print(mut.toseq().translate()) def Gthg04369(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[3583975:3585290].translate(to_stop=1) x=genome[0].seq[3583975:3585290].tomutable() print(x.pop(895-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) def Gthg01115(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[891404:892205].reverse_complement().translate(to_stop=1) x=genome[0].seq[891404:892205].reverse_complement().tomutable() print(x.pop(421-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) def Gthg03544(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[2885410:2887572].reverse_complement().translate(to_stop=1) x=genome[0].seq[2885410:2887572].reverse_complement().tomutable() print(x.pop(1748-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) if __name__ == "main": pass
matteoferla/Geobacillus
geo_mutagenesis.py
Python
gpl-2.0
2,769
from django.conf.urls import patterns, url from django.views.generic import TemplateView from django.contrib.auth.decorators import login_required, user_passes_test urlpatterns = patterns('', url(r'^$', 'website.views.index', name='website_index'), url(r'^termos/$',TemplateView.as_view(template_name='website/termos_de_uso.html'), name='website_termos'), url(r'^sobre/$', TemplateView.as_view(template_name='website/sobre.html'), name='website_sobre'), url(r'^relatorios/$', login_required(TemplateView.as_view(template_name='website/relatorios.html')), name='website_relatorios'), )
agendaTCC/AgendaTCC
tccweb/apps/website/urls.py
Python
gpl-2.0
603
# -*- coding: utf-8 -*- """Models for database connection""" import settings
vprusso/us_patent_scraper
patent_spider/patent_spider/models.py
Python
gpl-2.0
80
################################################################################ # # This program is part of the HPMon Zenpack for Zenoss. # Copyright (C) 2008, 2009, 2010, 2011 Egor Puzanov. # # This program can be used under the GNU General Public License version 2 # You can find full information here: http://www.zenoss.com/oss # ################################################################################ __doc__="""cpqScsiPhyDrv cpqScsiPhyDrv is an abstraction of a HP SCSI Hard Disk. $Id: cpqScsiPhyDrv.py,v 1.2 2011/01/04 23:27:26 egor Exp $""" __version__ = "$Revision: 1.2 $"[11:-2] from HPHardDisk import HPHardDisk from HPComponent import * class cpqScsiPhyDrv(HPHardDisk): """cpqScsiPhyDrv object """ statusmap ={1: (DOT_GREY, SEV_WARNING, 'other'), 2: (DOT_GREEN, SEV_CLEAN, 'Ok'), 3: (DOT_RED, SEV_CRITICAL, 'Failed'), 4: (DOT_YELLOW, SEV_WARNING, 'Not Configured'), 5: (DOT_ORANGE, SEV_ERROR, 'Bad Cable'), 6: (DOT_RED, SEV_CRITICAL, 'Missing was Ok'), 7: (DOT_RED, SEV_CRITICAL, 'Missing was Failed'), 8: (DOT_ORANGE, SEV_ERROR, 'Predictive Failure'), 9: (DOT_RED, SEV_CRITICAL, 'Missing was Predictive Failure'), 10:(DOT_RED, SEV_CRITICAL, 'Offline'), 11:(DOT_RED, SEV_CRITICAL, 'Missing was Offline'), 12:(DOT_RED, SEV_CRITICAL, 'Hard Error'), } InitializeClass(cpqScsiPhyDrv)
epuzanov/ZenPacks.community.HPMon
ZenPacks/community/HPMon/cpqScsiPhyDrv.py
Python
gpl-2.0
1,513
#!/usr/bin/env python # vim:fileencoding=utf-8 # Find the best reactor reactorchoices = ["epollreactor", "kqreactor", "cfreactor", "pollreactor", "selectreactor", "posixbase", "default"] for choice in reactorchoices: try: exec("from twisted.internet import %s as bestreactor" % choice) break except: pass bestreactor.install() #from twisted.application import internet, service from twisted.internet import reactor from twisted.protocols import basic, policies import yaml import socket import select import re import logging import sys import signal import os import traceback import codecs import time import resource logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) #logging.getLogger().addHandler() resource.setrlimit(resource.RLIMIT_NOFILE, [32768,65536]) trace=None if 'format_exc' in dir(traceback): from traceback import format_exc as trace else: from traceback import print_exc as trace reload(sys) def lock2key (lock): key = {} for i in xrange(1, len(lock)): key[i] = ord(lock[i]) ^ ord(lock[i-1]) key[0] = ord(lock[0]) ^ ord(lock[len(lock)-1]) ^ ord(lock[len(lock)-2]) ^ 5 for i in xrange(0, len(lock)): key[i] = ((key[i]<<4) & 240) | ((key[i]>>4) & 15) out = '' for i in xrange(0, len(lock)): out += unichr(key[i]) out = out.replace(u'\0', u'/%DCN000%/').replace(u'\5', u'/%DCN005%/').replace(u'\44', u'/%DCN036%/') out = out.replace(u'\140', u'/%DCN096%/').replace(u'\174', u'/%DCN124%/').replace(u'\176', u'/%DCN126%/') return out def number_to_human_size(size, precision=1): """ Returns a formatted-for-humans file size. ``precision`` The level of precision, defaults to 1 Examples:: >>> number_to_human_size(123) '123 Bytes' >>> number_to_human_size(1234) '1.2 KB' >>> number_to_human_size(12345) '12.1 KB' >>> number_to_human_size(1234567) '1.2 MB' >>> number_to_human_size(1234567890) '1.1 GB' >>> number_to_human_size(1234567890123) '1.1 TB' >>> number_to_human_size(1234567, 2) '1.18 MB' """ if size == 1: return "1 Byte" elif size < 1024: return "%d Bytes" % size elif size < (1024**2): return ("%%.%if KB" % precision) % (size / 1024.00) elif size < (1024**3): return ("%%.%if MB" % precision) % (size / 1024.00**2) elif size < (1024**4): return ("%%.%if GB" % precision) % (size / 1024.00**3) elif size < (1024**5): return ("%%.%if TB" % precision) % (size / 1024.00**4) return "" class DCUser: recp={} recp['tag']=re.compile('[<](.*)[>]$') recp['slots']=re.compile('S:(\d*)') recp['hubs']=re.compile('H:([0-9/]*)') def __init__(self,myinfo="",descr=None,addr=None): self.nick = '' self.connection = '' self.flag = '' self.mail = '' self.share = 0 self.descr = None self.MyINFO = None self.level = 0 self.tag = '' self.slots = 0 self.hubs = 0 self.sum_hubs = 0 if len( myinfo )>0: self.upInfo( myinfo ) self.descr = descr self.addr = addr def upInfo(self,myinfo): self.MyINFO = myinfo ar = myinfo.split("$") ar2 = ar[2].split(" ",2) self.nick = ar2[1] self.description = ar2[2] self.connection = ar[4][0:-1] self.flag = ar[4][-1] self.mail = ar[5] self.share = int( ar[6] ) # Parsing TAG tag = self.recp['tag'].search( self.description ) if self.tag != None: self.tag=tag.group( 1 ) slots = self.recp['slots'].search( self.tag ) if slots != None: self.slots = int( slots.group( 1 ) ) hubs = self.recp['hubs'].search( self.tag ) if hubs != None: self.hubs = hubs.group( 1 ) try: self.sum_hubs=self.get_sum_hubs() except: logging.warning( 'WRONG TAG: %s' % tag ) def get_ip( self ): return self.addr.split(':')[0] def get_sum_hubs( self ): s=0 for i in self.hubs.split('/'): s=s+int( i ) return s class DCHub( policies.ServerFactory ): # CONSTANTS LOCK='EXTENDEDPROTOCOL_VIPERHUB Pk=versionHidden' SUPPORTS='OpPlus NoGetINFO NoHello UserIP UserIP2' def _(self,string): # Translate function return self.lang.get(string,string) def tUCR( self, req ): '''translate and make usercmmand request %[line:req:] ''' return '%%[line:%s:]' % self._( req ) def UC( self, menu, params ): '''make UserCommands''' return '$UserCommand 1 2 %s %s %s%s&#124;|' % ( menu, '$<%[mynick]>', self.core_settings['cmdsymbol'], ' '.join( params ) ) def Gen_UC( self ): self.usercommands={} # -- CORE USERCOMMANDS -- self.usercommands['Quit'] = self.UC( self._('Core\\Quit'), ['Quit'] ) self.usercommands['Save'] = self.UC( self._('Settings\\Save settings'), ['Save'] ) self.usercommands['SetTopic'] = self.UC( self._('Settings\\Set hub topic'), ['SetTopic', self.tUCR('New Topic')] ) self.usercommands['Help'] = self.UC( self._('Help'), ['Help'] ) self.usercommands['RegenMenu'] = self.UC( self._( 'Core\\Regenerate menu' ), ['RegenMenu'] ) self.usercommands['ReloadSettings'] = self.UC( self._( 'Core\\Reload settings (DANGEROUS)' ), ['ReloadSettings'] ) # -- settings get/set self.usercommands['Get'] = self.UC( self._('Settings\\List settings files'), ['Get'] ) self.usercommands['Set'] = self.UC( self._('Settings\\Set variable'), ['Set', self.tUCR( 'File' ), self.tUCR( 'Variable' ), self.tUCR( 'New Value' )] ) # -- Limits control self.usercommands['Set'] += self.UC( self._('Settings\\Limits\\Set max users'), ['Set core max_users', self.tUCR( 'New max users' )] ) self.usercommands['Set'] += self.UC( self._('Settings\\Limits\\Set min share'), ['Set core min_share', self.tUCR( 'New min share (in bytes)' )] ) self.usercommands['Set'] += self.UC( self._('Settings\\Limits\\Set max hubs'), ['Set core max_hubs', self.tUCR( 'New max hubs' )] ) self.usercommands['Set'] += self.UC( self._('Settings\\Limits\\Set min slots'), ['Set core min_slots', self.tUCR( 'New min slots' )] ) # -- User control self.usercommands['AddReg'] = '' self.usercommands['SetLevel'] = '' for i in self.settings['privlist'].keys(): self.usercommands['AddReg'] += self.UC( self._( 'Users\\Selected\\Register selected nick as\\%s' ) % i, ['AddReg %[nick]', i, self.tUCR( 'Password' )] ) self.usercommands['AddReg'] += self.UC( self._( 'Users\\Register nick...' ), ['AddReg', self.tUCR( 'nick' ), self.tUCR( 'level' ), self.tUCR( 'Password' )] ) self.usercommands['ListReg'] = self.UC( self._( 'Users\\List registred nicks' ), ['ListReg'] ) self.usercommands['DelReg'] = self.UC( self._( 'Users\\Selected\\Unreg selected nick' ), ['DelReg %[nick]'] ) self.usercommands['DelReg'] += self.UC( self._( 'Users\\Unreg nick...' ), ['DelReg', self.tUCR('Nick')] ) for i in self.settings['privlist'].keys(): self.usercommands['SetLevel'] += self.UC( self._( 'Users\\Selected\\Set level for selected nick\\%s' ) % i, ['SetLevel %[nick]', i] ) self.usercommands['PasswdTo'] = self.UC( self._( 'Users\\Selected\\Set password for selected nick...' ), ['PasswdTo %[nick]', self.tUCR('new password')] ) self.usercommands['Kick'] = self.UC( self._( 'Kick selected nick...' ), ['Kick %[nick]', self.tUCR( 'reason (may be empty)' )] ) self.usercommands['UI'] = self.UC( self._( 'Users\\Selected\\User Info' ), ['UI %[nick]'] ) # -- Plugin control #self.usercommands['ListPlugins'] = self.UC( self._( 'Plugins\\List aviable plugins' ), ['ListPlugins'] ) #self.usercommands['ActivePlugins'] = self.UC( self._( 'Plugins\\List active plugins' ), ['ListPlugins'] ) menu = self._( 'Plugins\\Load/Reload Plugin\\' ) menuU = self._( 'Plugins\\Unload Plugin\\' ) loaded = self._( '(loaded)' ) aplugs = self.get_aviable_plugins() self.usercommands['ReloadPlugin'] = '' self.usercommands['LoadPlugin'] = '' self.usercommands['UnloadPlugin'] = '' for i in aplugs: if i in self.plugs: self.usercommands['ReloadPlugin'] += self.UC( menu + i + ' ' + loaded, ['ReloadPlugin', i] ) else: self.usercommands['LoadPlugin'] += self.UC( menu + i, ['LoadPlugin', i] ) for i in self.plugs.keys(): self.usercommands['UnloadPlugin'] += self.UC( menuU + i, ['UnloadPlugin', i] ) #self.usercommands['ListPlugins']='$UserCommand 1 2 '+self._('Plugins\\List aviable plugins')+'$<%[mynick]> '+self.core_settings['cmdsymbol']+'ListPlugins&#124;|' #self.usercommands['ActivePlugins']='$UserCommand 1 2 '+self._('Plugins\\List active plugins')+'$<%[mynick]> '+self.core_settings['cmdsymbol']+'ActivePlugins&#124;|' #self.usercommands['LoadPlugin']='$UserCommand 1 2 '+self._('Plugins\\Load plugin..')+'$<%[mynick]> '+self.core_settings['cmdsymbol']+'LoadPlugin %[line:'+self._('plugin')+':]&#124;|' #self.usercommands['UnloadPlugin']='$UserCommand 1 2 '+self._('Plugins\\Unload plugin...')+'$<%[mynick]> '+self.core_settings['cmdsymbol']+'UnloadPlugin %[line:'+self._('plugin')+':]&#124;|' #self.usercommands['ReloadPlugin']='$UserCommand 1 2 '+self._('Plugins\\Reload plugin...')+'$<%[mynick]> '+self.core_settings['cmdsymbol']+'ReloadPlugin %[line:'+self._('plugin')+':]&#124;|' # -- Self control self.usercommands['Passwd'] = self.UC( self._('Me\\Set MY password...'), [ 'Passwd', self.tUCR( 'new password' ) ] ) for i in self.plugs.values(): i.update_menu() self.usercommands.update( i.usercommands ) #logging.debug ('UC: %s' % repr(self.usercommands) ) return def __init__( self ): # COMMANDS self.commands={} # SIGNAL-SLOT EVENT SUBSYSTEM self.slots={} # COMPILE REGEXPS self.recp={} #self.recp['Key']=re.compile('(?<=\$Key )[^|]*(?=[|])') #self.recp['ValidateNick']=re.compile('(?<=\$ValidateNick )[^|]*(?=[|])') #self.recp['Supports']=re.compile('(?<=\$Supports )[^|]*(?=[|])') #self.recp['MyPass']=re.compile('(?<=\$MyPass )[^|]*(?=[|])') #self.recp['MyINFO']=re.compile('\$MyINFO [^|]*(?=[|])') #self.recp['NoGetINFO']=re.compile('NoGetINFO') #self.recp['NoHello']=re.compile('NoHello') self.recp['.yaml']=re.compile('\.yaml$') self.recp['before.yaml']=re.compile('.*(?=\.yaml)') self.recp['.py']=re.compile('\.py$') self.recp['before.py']=re.compile('.*(?=\.py)') self.recp['tag']=re.compile('[<](.*)[>]$') # SET PATHS self.path_to_settings="./settings/" self.path_to_plugins="./plugins/" # ----- SETTINGS ----- self.settings={} # LOADING SETTINGS self.load_settings() # SHORTCUTS self.core_settings=self.settings.get('core',{}) self.reglist=self.settings.get('reglist',{}) self.privlist=self.settings.get('privlist',{}) # DEFAULTS defcore_settings={} defcore_settings['port']=[411] defcore_settings['hubname']='ViperPeers' defcore_settings['topic']='' defcore_settings['cmdsymbol']='!' defcore_settings['OpLevels']=['owner'] defcore_settings['Protected']=['owner', 'op'] defcore_settings['Lang']='ru.cp1251' defcore_settings['autoload']=[ 'ban', 'chatlist', 'chatroom', 'forbid', 'goodplug', 'iplog', 'massmsg', 'motd', 'mute', 'say', 'regme' ] defcore_settings['logfile']='' defcore_settings['loglevel']=10 defcore_settings['autosave']=120 defcore_settings['userip']=['owner', 'op'] # ---- LIMITS ---- defcore_settings['max_users'] = 10000 defcore_settings['min_share'] = 0 defcore_settings['max_hubs'] = 1000 defcore_settings['min_slots'] = 0 defcore_settings['pass_limits'] = ['owner', 'op', 'chatroom'] defcore_settings['hubinfo']={'address':'127.0.0.1','description':'ViperPeers powered hub (vipehive fork)','type':'ViperPeers Hub', 'hubowner':'owner'} defreglist={'admin':{'level':'owner', 'passwd':'megapass'}} defprivlist={'owner':['*']} # If loaded core_settings miss some stuff - load defaults if len(self.core_settings)==0: self.settings['core']=self.core_settings={} for i in defcore_settings.keys(): if not i in self.core_settings: self.core_settings[i]=defcore_settings[i] #------UPDATE SETTINGS FROM OLD VERSION:------- # UPDATE PORT SETTINGS FOR VERSIONS <= svn r168 if not isinstance( self.core_settings['port'], list ): self.core_settings['port'] = [ self.core_settings['port'] ] if len(self.reglist)==0: self.settings['reglist']=self.reglist=defreglist if len(self.privlist)==0: self.settings['privlist']=self.privlist=defprivlist # MORE SHORTCUTS self.oplevels=self.core_settings['OpLevels'] self.protected=self.core_settings['Protected'] self.KEY=lock2key(self.LOCK) # ---- TRANSPORTS ---- self.transports=[] # User hashes self.nicks={} self.addrs={} # Support for very, VERY old clients self.hello=[] self.getinfo=[] self.clthreads=[] # Reinitialize Logging self.reload_logging() # REGISTERING CORE COMMANDS self.commands['Quit']=self.Quit #Usercommands + self.commands['AddReg']=self.AddReg #Usercommands + self.commands['DelReg']=self.DelReg #Usercommands + self.commands['ListReg']=self.ListReg #Usercommands + self.commands['Get']=self.Get #Usercommands + self.commands['Set']=self.Set #Usercommands + self.commands['SetLevel']=self.SetLevel #Usercommands + self.commands['Help']=self.Help #Usercommands + self.commands['ListPlugins']=self.ListPlugins #Usercommands + self.commands['LoadPlugin']=self.LoadPlugin #Usercommands + self.commands['UnloadPlugin']=self.UnloadPlugin #Usercommands + self.commands['ActivePlugins']=self.ActivePlugins #Usercommands + self.commands['Save']=self.Save #Usercommands + self.commands['ReloadPlugin']=self.ReloadPlugin self.commands['RP']=self.ReloadPlugin #Usercommands + self.commands['Passwd']=self.Passwd self.commands['PasswdTo']=self.PasswdTo #Usercommands + self.commands['Kick']=self.Kick #Usercommands + self.commands['UI']=self.UI #Usercoommands + self.commands['SetTopic']=self.SetTopic #Usercommands + self.commands['RegenMenu'] = self.RegenMenu #Usercommands + self.commands['ReloadSettings'] = self.ReloadSettings #Usercommands + # TRANSLATION SYSTEM self.lang={} # Current language array self.help={} # Help for current language # -- LOADING LANGUAGE lang=self.core_settings['Lang'].split('.')[0] self.charset=cpage=self.core_settings['Lang'].split('.')[1] try: lpath='./languages/'+lang+'/' lfiles=os.listdir(lpath) for i in lfiles: # LOAD MESSAGES FOR CURRENT LANGUAGE if self.recp['.yaml'].search(i)!=None: try: arr=yaml.load(codecs.open(lpath+i,'r','utf-8').read()) #for key,value in arr.iteritems(): # arr[key]=value.encode(cpage) self.lang.update(arr) except: logging.error('file %s in wrong format: %s' % ((lpath+i), trace())) if 'help' in lfiles: # LOAD HELP FOR CURRENT LANGUAGE hpath=lpath+'help/' hfiles=os.listdir(hpath) for i in hfiles: if self.recp['.yaml'].search(i)!=None: try: arr=yaml.load(codecs.open(hpath+i,'r','utf-8').read()) #for key,value in arr.iteritems(): # arr[key]=value.encode(cpage) self.help.update(arr) except: logging.error('file %s in wrong format: %s' % ((lpath+i), trace())) except: logging.error('language directory not found %s' % (trace())) logging.info('Language loaded: %s strings' % str(len(self.lang))) logging.info('Help loaded: %s strings' % str(len(self.help))) # PLUGINS self.plugs={} self.Gen_UC() # Queue for queue_worker self.queue = [] self.queue_lock = False self.delay = 0.5 self.ping_time = 150. reactor.callLater(self.delay, self.queue_worker, self.ping_time) # AUTOLOAD PLUGINS for i in self.settings['core']['autoload']: reactor.callLater(self.delay, self.LoadPlugin, None, [i]) # SETTING AUTOSAVER reactor.callLater(self.settings['core']['autosave'], self.settings_autosaver) logging.info ('Hub ready to start on port %s...' % self.core_settings['port']) self.skipme=[] def reload_logging(self): logging.debug('Set logging to %s, level %s' % (self.settings['core']['logfile'], str(self.settings['core']['loglevel']))) reload(sys.modules['logging']) if self.settings['core']['logfile']: logging.basicConfig(filename=self.settings['core']['logfile'],) logging.getLogger().setLevel(self.settings['core']['loglevel']) def emit(self,signal,*args): #logging.debug('emitting %s' % signal) #logging.debug('emit map %s' % repr(self.slots)) for slot in self.slots.get(signal,[]): logging.debug( 'Emitting: %s, for %s slot' % ( signal, repr( slot )) ) try: if not slot(*args): logging.debug( 'Emit %s: FALSE' % signal ) return False except: logging.error('PLUGIN ERROR: %s' % trace()) logging.debug( 'Emit %s: True' % signal ) return True def settings_autosaver(self): logging.debug('settings autosave') self.save_settings() reactor.callLater(self.settings['core']['autosave'], self.settings_autosaver) def drop_user_by_addr(self,addr): if addr in self.addrs: transport=self.addrs[addr].descr nick=self.addrs[addr].nick self.drop_user(addr,nick,transport) def drop_user(self, addr, nick, transport): logging.debug('dropping %s %s' % (addr, nick)) try: if transport in self.transports: self.transports.remove(transport) self.addrs.pop(addr,'') self.nicks.pop(nick,'') if transport in self.hello: self.hello.remove(transport) transport.loseConnection() except: logging.debug('something wrong while dropping client %s' % trace()) self.send_to_all('$Quit %s|' % nick) self.emit('onUserLeft',addr,nick) def drop_user_by_nick(self,nick): if nick in self.nicks: transport=self.nicks[nick].descr addr=self.nicks[nick].addr self.drop_user(addr,nick,transport) def drop_user_by_transport(self, transport): A=None N=None for nick, user in self.nicks.items(): if user.descr == transport: N=nick break for addr, user in self.addrs.items(): if user.descr == transport: A=addr break self.drop_user(A, N, transport) def send_to_all(self, msg): if not self.queue_lock: self.queue_lock = True self.queue.append(msg) self.queue_lock = False else: reactor.callLater(self.delay, self.send_to_all, msg) def queue_worker(self, ping_timer): if ping_timer > 0: ping_timer -= self.delay result = '' if not self.queue_lock: self.queue_lock = True msgs = self.queue self.queue = [] self.queue_lock = False if len(msgs)>0: for msg in msgs: logging.debug('sending to all %s' % msg) if not (len(msg)>0 and msg[-1]=="|"): msg += "|" result += msg if not result and ping_timer <= 0: # We should probably "ping" all connections if no messages to send ping_timer += self.ping_time logging.debug('pinging') result = '|' if result: logging.debug('senging "%s" to all' % result) for transport in self.transports: try: transport.write(result.encode(self.charset)) except: logging.debug('transport layer error %s' % trace()) reactor.callLater(0, self.drop_user_by_transport, transport) reactor.callLater(self.delay, self.queue_worker, ping_timer) def send_pm_to_nick(self,fnick,nick,msg): self.send_to_nick(nick,'$To: %s From: %s $<%s> %s|' % (nick, fnick, fnick, msg)) def send_to_nick(self,nick,msg): if nick in self.nicks: if not (len(msg)>0 and msg[-1]=="|"): msg=msg+"|" try: logging.debug('sending "%s" to %s' % (msg, nick)) self.nicks[nick].descr.write(msg.encode(self.charset)) except: #logging.debug('Error while sending "%s" to %s. Dropping. %s' % (msg,nick,trace())) logging.debug('socket error %s. dropping lost user!' % trace() ) self.drop_user_by_nick(nick) else: logging.debug('send to unknown nick: %s' % nick) def send_to_addr(self,addr,msg): if addr in self.addrs: if not (len(msg)>0 and msg[-1]=="|"): msg=msg+"|" try: logging.debug('sending "%s" to %s' % (msg, addr)) self.addrs[addr].descr.write(msg.encode(self.charset)) except: logging.debug('socket error %s' % trace()) else: logging.warning('uknown addres: %s' % addr) def get_nick_list( self ): nicklist="$NickList " oplist="$OpList " for user in self.nicks.values(): nicklist+=user.nick+"$$" if user.level in self.oplevels: oplist+=user.nick+"$$" return "%s|%s|" % (nicklist[:-2], oplist[:-2]) def get_op_list(self): #repeat some code for faster access oplist="$OpList " for user in self.nicks.values(): if user.level in self.oplevels: oplist+=user.nick+"$$" return oplist+'|' def get_userip_list( self ): uip='$UserIP ' for user in self.nicks.values(): uip+='%s %s$$' % (user.nick, user.get_ip()) return uip+'|' def get_userip_acc_list(self): uip=[] for user in self.nicks.values(): if user.level in self.core_settings['userip']: uip.append(user.nick) return uip def save_settings(self): logging.debug('saving settigs') try: for mod, sett in self.settings.items(): try: logging.info('saving settings for %s' % mod) f=open(self.path_to_settings+'/'+mod+'.yaml','wb') f.write(yaml.safe_dump(sett,default_flow_style=False,allow_unicode=True)) except: logging.error('failed to load settings for module %s. cause:' % mod) logging.error('%s' % trace()) return False except: logging.error('!!! SETTINGS NOT SAVED !!!') return False return True def load_settings(self): logging.debug('reading settigs') try: for i in os.listdir(self.path_to_settings): if self.recp['.yaml'].search(i)!=None: mod=self.recp['before.yaml'].search(i).group(0) logging.debug('loading settings for %s' % mod) try: f=codecs.open(self.path_to_settings+'/'+ i,'r','utf-8') text=f.read() dct=yaml.load(text) if dct!=None: self.settings[mod]=dct except: logging.error('failed to load settings for module %s. cause:' % mod) logging.error('%s' % trace()) except: logging.error('error while loading settings: %s', trace()) def check_rights(self, user, command): rights=self.privlist.get(user.level,[]) if ('*' in rights) or (command in rights): return True else: return False def send_usercommands_to_nick(self, nick): for i in range(1,4): self.send_to_nick(nick, '$UserCommand 255 %s |' % i) for name, cmd in self.usercommands.items(): if self.check_rights(self.nicks[nick],name): self.send_to_nick(nick, cmd) def send_usercommands_to_all(self): for nick in self.nicks.keys(): self.send_usercommands_to_nick(nick) # COMMANDS # -- Hub Control def Quit(self,addr,params=[]): self.work=False exit return True def Set(self,addr,params=[]): # Setting param for core or plugin # Params should be: 'core/plugin name' 'parameter' 'value' # Cause 'value' can contain spaces - join params[2:] if len(params)<2: return self._('Params error') try: value=yaml.load(" ".join(params[2:])) self.settings[params[0]][params[1]]=value if params[1].startswith('log'): self.reload_logging() return self._('Settings for %s - %s setted for %s') % (params[0], params[1], value) except: return self._('Error: %s') % trace() def Get(self,addr, params=[]): #Getting params or list # Params can be 'core/plugin name' 'parameter' or 'core/plugin name' if len(params)==0: return self._(' -- Available settings --:\n%s' ) % (unicode(yaml.safe_dump(self.settings.keys(),allow_unicode=True),'utf-8')) elif len(params)==1: if params[0] in self.settings: return self._(' -- Settings for %s --\n%s' ) % (params[0], unicode(yaml.safe_dump(self.settings.get(params[0],''),allow_unicode=True),'utf-8')) elif len(params)==2: if params[0] in self.settings and params[1] in self.settings[params[0]]: return self._(' -- Settings for %s - %s --\n%s' ) % ( params[0], params[1], unicode(yaml.safe_dump(self.settings[params[0]][params[1]],allow_unicode=True),'utf-8')) else: return self._('Params error') else: return self._('Params error') def Save(self, params=[]): try: self.save_settings() return True except: return False def RegenMenu( self, params = [] ): try: self.Gen_UC() self.send_usercommands_to_all() return True except: return False def ReloadSettings( self, params = [] ): try: self.load_settings() except: return False return True # --- User Control def AddReg(self,addr,params=[]): # Params should be: 'nick' 'level' 'passwd' if len(params)==3: # Check if 'nick' already registred if params[0] not in self.reglist: self.reglist[params[0]]={'level': params[1],'passwd':params[2]} return self._('User Registred:\n nick: %s\n level: %s\n passwd:%s') % (params[0],params[1],params[2]) else: return self._('User already registred') else: return self._('Params error.') def DelReg(self,addr,params=[]): # Params should be 'nick' if len(params)==1: # Check if 'nick' registred if params[0] in self.reglist: if params[0] not in self.protected: del self.reglist[params[0]] return self._('User deleted') else: return self._('User protected!') else: return self._('User not registred') else: return self._('Params error') def ListReg(self,addr): s=self._('--- REGISTRED USERES --- \n') for nick, param in self.reglist.items(): s=s+('nick: %s level: %s' % (nick, param['level'],))+'\n' return s #return self._('--- REGISTRED USERES --- \n') + "\n".join('nick: %s level: %s' % (nick, param['level'],) for nick, param in self.reglist.iteritems()) def SetLevel(self,addr,params=[]): # Params should be: 'nick' 'level' if len(params)==2: if params[0] in self.reglist: self.reglist[params[0]]['level']=yaml.load(params[1]) return self._('Success') else: return self._('No such user') else: return self._('Params error.') def Kick (self, addr, params=[]): # Params should be: 'nick' if len(params)>=1: if params[0] in self.nicks: if self.nicks[params[0]].level in self.protected: return self._('User protected!') msg = '<%s> is kicking %s because: ' % (self.addrs[addr].nick, params[0]) if len(params)>1: fnick = self.core_settings['hubname'].replace(' ','_') reason = ' '.join(params[1:]) self.send_pm_to_nick(fnick, params[0], reason) msg += reason else: msg += '-' self.drop_user_by_nick(params[0]) self.send_to_all(msg) return self._('Success') else: return self._('No such user') else: return self._('Usage: !Kick <Username> [<reason>]') # -- Help System def Help(self,addr,params=""): # Params can be empty or 'command' if len(params)==1: if self.check_rights(self.addrs[addr], params[0]): return self.help[params[0]] else: return self._('Premission denied') elif len(params)==0: ans=self._(' -- Aviable commands for you--\n') for cmd in self.commands.keys(): if self.check_rights(self.addrs[addr],cmd): ans+='%s\n' % self.help.get(cmd,cmd) return ans else: return self._('Params error') # -- Plugin control def get_aviable_plugins( self ): ans = [] try: for i in os.listdir(self.path_to_plugins): if self.recp['.py'].search(i)!=None and i!="__init__.py" and i!="plugin.py": mod=self.recp['before.py'].search(i).group(0) ans.append( mod ) return ans except: logging.error('error while listing plugins: %s', trace()) return ans def ListPlugins(self,addr): logging.debug('listing plugins') ans = self._(' -- Aviable plugins --\n%s') % '\n'.join( self.get_aviable_plugins() ) return ans def LoadPlugin(self,addr,params=[]): # Params should be: 'plugin' if len(params)==1: logging.debug('loading plugin %s' % params[0]) if params[0] not in self.plugs: try: if not '.' in sys.path: sys.path.append('.') if 'plugins.'+params[0] not in sys.modules: plugins=__import__('plugins.'+params[0]) plugin=getattr(plugins,params[0]) else: plugin=reload(sys.modules['plugins.'+params[0]]) logging.getLogger().setLevel(self.settings['core']['loglevel']) logging.debug('loaded plugin file success') cls=getattr(plugin,params[0]+'_plugin') obj=cls(self) self.plugs[params[0]]=obj self.commands.update(obj.commands) #self.usercommands.update(obj.usercommands) logging.debug( 'Plugin %s slots: %s' % (params[0], repr( obj.slots ) ) ) for key,value in obj.slots.iteritems(): logging.debug( 'Activating Slot: %s, on plugin %s' % ( key, params[0] ) ) if key in self.slots: self.slots[key].append(value) else: self.slots[key]=[value] logging.debug( 'MessageMap: %s' % repr( self.slots )) self.Gen_UC() self.send_usercommands_to_all() return self._('Success') except: e=trace() logging.debug( 'Plugin load error: %s' % (e,) ) return self._( 'Plugin load error: %s' % (e,) ) else: return self._('Plugin already loaded') else: return self._('Params error') def UnloadPlugin(self,addr,params=[]): # Params should be: 'plugin' logging.debug('unloading plugin') if len(params)==1: try: if params[0] in self.plugs: plug=self.plugs.pop(params[0]) plug.unload() for key in plug.commands.keys(): self.commands.pop(key,None) for key in plug.usercommands.keys(): self.usercommands.pop(key,None) for key, value in plug.slots.iteritems(): if key in self.slots: if value in self.slots[key]: self.slots[key].remove(value) self.Gen_UC() self.send_usercommands_to_all() return self._('Success') else: return self._('Plugin not loaded') except: return self._('Plugin unload error: %s' % trace()) else: return self._('Params error') def ReloadPlugin(self, addr, params=[]): # Params 'plugin' return 'Unload: %s, Load %s' % (self.UnloadPlugin(addr, params), self.LoadPlugin(addr, params)) def ActivePlugins(self,addr,params=[]): return self._(' -- ACTIVE PLUGINS -- \n')+"\n".join(self.plugs.keys()) def Passwd(self,addr,params=[]): # Params 'nick' if len(params)>0: newpass=" ".join(params) nick=self.addrs[addr].nick if nick in self.reglist: self.reglist[nick]['passwd']=newpass return self._('Your password updated') else: return self._('You are not registred') else: return self._('Params error') def PasswdTo(self,addr,params=[]): # Params: 'nick' 'newpass' if len(params)>1: nick=params[0] newpass=" ".join(params[1:]) if nick in self.reglist: if self.nicks[nick].level in self.protected: return self._('User protected!') self.reglist[nick]['passwd']=newpass return self._('User password updated') else: return self._('User not registred') else: return self._('Params error') def UI(self,addr,params=[]): # params: 'nick' if len(params)==1: user=self.nicks.get(params[0],None) if user!=None: return self._(' -- USER %s INFO --\n addres: %s\n level: %s\n is op?: %s\n is protected?: %s') % (user.nick, user.addr, user.level, repr(user.level in self.oplevels), repr(user.level in self.protected)) else: return self._('No such user') else: return self._('Params error') def SetTopic(self,addr,params=[]): #params: ['topic'] if len(params)>=1: topic=' '.join(params) self.core_settings['topic']=topic self.send_to_all('$HubTopic %s|' % topic) return self._('Success') else: return self._('Params error') # -- EXTENDED FUNCTIONS USED FOR SIMPLIFY SOME WRK def masksyms(self, str): ''' return string with ASCII 0, 5, 36, 96, 124, 126 masked with: &# ;. e.g. chr(5) -> &#5; ''' cds=[0, 5, 36, 96, 124, 126] for i in cds: str=str.replace(chr(i),'&#%s;' % i) return str def unmasksyms(self, str): ''' return string with ASCII 0, 5, 36, 96, 124, 126 unmasked from: &# ; mask. e.g. &#5; -> chr(5) ''' cds=[0, 5, 36, 96, 124, 126] for i in cds: str=str.replace('&#%s;' % i, chr(i)) return str class DCProtocol(basic.LineOnlyReceiver, policies.TimeoutMixin): def _(self,string): # Translate function return self.factory._(string) def __init__(self): self.delimiter = '|' self.MAX_LENGTH = 2**16 # default is 16384 def write(self, msg): self.transport.write(msg) logging.debug('sending "%s" to %s' % (msg, self._addr)) def connectionMade(self): self._state = 'connect' self._supports = [] self._hubinfo = self.factory.core_settings['hubinfo'] self._host, self._port = self.transport.socket.getpeername() self._addr = '%s:%s' % (self._host, self._port) self._nick = '' self.setTimeout(None) if len( self.factory.nicks ) >= self.factory.core_settings['max_users']: self.transport.loseConnection() logging.warning( 'MAX USERS REACHED!!!' ) return logging.debug ('connecting: %s' % self._addr) if self.factory.emit('onConnecting', self._addr): self.write('$Lock %s|' % self.factory.LOCK ) else: logging.debug('Connection is not allowed by plugins') self.transport.loseConnection def lineReceived(self, line): line = unicode(line, self.factory.charset) logging.debug ('received: %s from %s' % (line, self._addr)) if self._state in [ 'connect', 'validate', 'negotiate' ] and line.startswith('$'): self.resetTimeout() f = getattr(self, 'parse_' + self._state + '_cmd') f(line) elif self._state == 'logedin': self.resetTimeout() if self.factory.emit('onReceivedSomething', self._addr) and len(line) > 0: if line.startswith('$'): self.parse_protocol_cmd(line) else: self.parse_chat_msg(line) else: logging.debug ( 'Unexpected command sequence received from %s' % self._addr ) self.transport.loseConnection() def lineLengthExceeded(self, line): logging.warning ( 'Too big or wrong message received from %s: %s' % (self._addr, s) ) def connectionLost(self, reason): if self._nick: self.factory.drop_user(self._addr, self._nick, self.transport) logging.debug('User Lost: %s' % reason) def parse_protocol_cmd(self, cmd): acmd=cmd.split(' ') if acmd[0]=='$GetINFO': if len(acmd)==3: if self.factory.addrs[self._addr].nick==acmd[2] and self.factory.nicks.has_key(acmd[1]): if self.factory.emit('onGetINFO',acmd[1],acmd[2]): logging.debug('send myinfo %s' % self.factory.nicks[acmd[1]].MyINFO) self.factory.send_to_nick(acmd[2],self.factory.nicks[acmd[1]].MyINFO) elif acmd[0]=='$MyINFO': if len(acmd)>=3: if self.factory.addrs[self._addr].nick==acmd[2]: try: self.factory.nicks[acmd[2]].upInfo(cmd) if self.factory.emit('onMyINFO',cmd): self.factory.send_to_all(cmd) except: logging.warning( 'Wrong MyINFO by: %s with addr %s: %s' % ( acmd[2], self._addr, trace() ) ) self.factory.drop_user_by_addr(self._addr) elif acmd[0]=='$To:': if len(acmd)>5: if acmd[3]==self.factory.addrs[self._addr].nick==acmd[4][2:-1]: if acmd[1] in self.factory.nicks: tocmd=cmd.split(' ',5) if self.factory.emit('onPrivMsg',acmd[3],acmd[1],tocmd[5]): self.factory.send_to_nick(acmd[1],cmd+"|") elif acmd[0]=='$ConnectToMe': if len(acmd)==3: if acmd[2].split(':')[0]==self._addr.split(':')[0]: if self.factory.emit('onConnectToMe',self._addr,acmd[1]): self.factory.send_to_nick(acmd[1],cmd+"|") elif acmd[0]=='$RevConnectToMe': if len(acmd)==3: if acmd[1] in self.factory.nicks: if self.factory.addrs[self._addr].nick==acmd[1]: if self.factory.emit('onRevConnectToMe',acmd[1],acmd[2]): self.factory.send_to_nick(acmd[2],cmd+"|") elif acmd[0]=='$Search': if len(acmd)>=3: srcport=acmd[1].split(':') if len(srcport)==2: if srcport[0]=='Hub': #Passive Search if srcport[1]==self.factory.addrs[self._addr].nick: bcmd=cmd.split(' ',2) if self.factory.emit('onSearchHub',bcmd[1],bcmd[2]): self.factory.send_to_all(cmd) else: #Active Search if srcport[0]==self.factory.addrs[self._addr].addr.split(':')[0]: bcmd=cmd.split(' ',2) if self.factory.emit('onSearch',bcmd[1],bcmd[2]): self.factory.send_to_all(cmd) elif acmd[0]=='$SR': fcmd=cmd.split(chr(5)) if len(fcmd)==4 and len(acmd)>=3: sender=acmd[1] receiver=fcmd[3] if self.factory.addrs[self._addr].nick==sender: if self.factory.emit('onSearchResult', sender, receiver, cmd): self.factory.send_to_nick(receiver, chr(5).join(fcmd[:3])+'|') elif acmd[0]=='$GetNickList': self.factory.send_to_addr( self._addr, self.factory.get_nick_list() ) elif acmd[0]=='$HubINFO' or acmd[0]=='$BotINFO': hubinfo='$HubINFO ' hubinfo+='%s$' % self.factory.core_settings['hubname'] hubinfo+='%s:%s$' % ( self._hubinfo.get('address',''), self.factory.core_settings['port'][0] ) hubinfo+='%s$' % self._hubinfo.get('description','') hubinfo+='%s$' % self.factory.core_settings.get('max_users','10000') hubinfo+='%s$' % self.factory.core_settings.get('min_share','0') hubinfo+='%s$' % self.factory.core_settings.get('min_slots','0') hubinfo+='%s$' % self.factory.core_settings.get('max_hubs','1000') hubinfo+='%s$' % self._hubinfo.get('type','') hubinfo+='%s$' % self._hubinfo.get('owner','') self.factory.send_to_addr( self._addr, hubinfo ) else: logging.debug('Unknown protocol command: %s from: %s' % (cmd, self._addr)) return def parse_cmd(self, cmd): logging.debug('command received %s' % cmd) acmd=cmd.split(' ') ncmd=acmd[0] for j in self.factory.commands: if acmd[0].lower() == j.lower(): ncmd=j if self.factory.check_rights(self.factory.addrs[self._addr],acmd[0]): if ncmd in self.factory.commands: try: if (len(acmd[1:]))>0: result=self.factory.commands[ncmd](self._addr,acmd[1:]) else: result=self.factory.commands[ncmd](self._addr) if result != '': self.factory.send_to_addr(self._addr, self._('<HUB> %s|') % result) except SystemExit: raise SystemExit except: self.factory.send_to_addr(self._addr, self._('<HUB> Error while proccessing command %s|') % trace()) else: self.factory.send_to_addr(self._addr, self._('<HUB> No such command')) else: self.factory.send_to_addr(self._addr, self._('<HUB> Premission denied')) return def parse_chat_msg(self, msg): acmd=msg.split(' ',1) if len(acmd)==2: if acmd[0][1:-1]==self.factory.addrs[self._addr].nick: if acmd[1][0]==self.factory.core_settings['cmdsymbol']: self.parse_cmd(acmd[1][1:]) else: if self.factory.emit('onMainChatMsg',acmd[0][1:-1],acmd[1]): self.factory.emit('ChatHistEvent',acmd[0][1:-1],acmd[1]) self.factory.send_to_all(msg) else: logging.warning('user tried to use wrong nick in MC. Real nick: %s. Message: %s' % (self.factory.addrs[self._addr].nick, msg)) self.drop_user_by_addr(self._addr) return def parse_connect_cmd(self, cmd): acmd = cmd.split(' ', 1) if acmd[0] == '$Supports': self._supports = acmd[1].split(' ') logging.debug('Supports: %s' % acmd[1]) elif acmd[0] == '$ValidateNick': self.write('<HUB> This hub is powered by ViperPeers specific software.|$HubName %s|' % ( self.factory.core_settings['hubname'].encode(self.factory.charset) ) ) self._nick = acmd[1] if self._nick: logging.debug('validating: %s' % self._nick) if self._nick in self.factory.reglist: self._state = 'validate' self.write('$GetPass|') return elif self._nick not in self.factory.nicks: self.send_negotiate_cmd() return else: logging.debug('this nick is already online.'); else: logging.debug('not validated nick. dropping.') self.write('$ValidateDenide|') self.transport.loseConnection() def parse_validate_cmd(self, cmd): """ if user registred, and passwd is correct we should connect it even if it's already connected (drop & connect) """ acmd = cmd.split(' ', 1) if acmd[0] == '$MyPass': logging.debug('MyPass %s' % acmd[1]) if acmd[1] != self.factory.reglist[self._nick]['passwd']: logging.info('wrong pass') self.write(('<HUB> %s|$BadPass|' % (self._('Password incorrect. Provided: %s') % str(acmd[1]),)).encode(self.factory.charset)) logging.debug('not validated nick. dropping.') self.transport.loseConnection() return else: if self._nick in self.factory.nicks: logging.debug('reconnecting identified user') try: self.factory.nicks[self._nick].descr.write('<HUB> You are connecting from different machine. Bye.|') except: pass self.factory.drop_user_by_nick(self._nick) self.send_negotiate_cmd() return #else: # logging.debug('received wrong cmd: %s' % cmd) def send_negotiate_cmd(self): self._state = 'negotiate' logging.debug ('validated %s' % self._nick) for transport in self.factory.hello: reactor.callLater(0, transport.write, '$Hello %s|' % self._nick.encode(self.factory.charset)) self.write('$Hello %s|$Supports %s |' % (self._nick.encode(self.factory.charset), self.factory.SUPPORTS)) #self.write('$Hello %s|' % self._nick.encode(self.factory.charset)) def parse_negotiate_cmd(self, cmd): acmd = cmd.split(' ', 1) if acmd[0] == '$MyINFO': try: user=DCUser(cmd, self.transport, self._addr) except: logging.warning( 'wrong myinfo from: %s addr: %s info: %s %s' % ( self._nick, self._addr, cmd, trace() ) ) else: if self._nick in self.factory.reglist: user.level=self.factory.reglist[self._nick]['level'] else: user.level='unreg' self.factory.nicks[self._nick] = user self.factory.addrs[self._addr] = user try: # --- APPLY LIMITS --- if user.share < self.factory.core_settings['min_share'] and user.level not in self.factory.core_settings['pass_limits']: self.write( (self._( '<HUB> Too low share. Min share is %s.|' ) % number_to_human_size( self.factory.core_settings['min_share'] ) ).encode( self.factory.charset ) ) logging.debug('not validated. dropping') self.factory.drop_user(self._addr, self._nick, self.transport) return if user.sum_hubs > self.factory.core_settings['max_hubs'] and user.level not in self.factory.core_settings['pass_limits']: self.write( (self._( '<HUB> Too many hubs open. Max hubs is %s.|' ) % self.factory.core_settings['max_hubs']).encode( self.factory.charset ) ) logging.debug('not validated. dropping') self.factory.drop_user(self._addr, self._nick, self.transport) return if user.slots < self.factory.core_settings['min_slots'] and user.level not in self.factory.core_settings['pass_limits']: self.write( (self._( '<HUB> Too few slots open. Min slots is %s.|' ) % self.factory.core_settings['min_slots']).encode( self.factory.charset ) ) logging.debug('not validated. dropping') self.factory.drop_user(self._addr, self._nick, self.transport) return logging.debug('slots: %s, hubs: %s' % (user.slots, user.hubs) ) if self.factory.emit('onConnected',user): logging.debug('Validated. Appending.') self.factory.transports.append(self.transport) if user.level in self.factory.oplevels: self.write('$LogedIn|') self.factory.send_to_all(self.factory.get_op_list()) if not 'NoHello' in self._supports: self.factory.hello.append(self.transport) if not 'NoGetINFO' in self._supports: self.write(self.factory.get_nick_list().encode( self.factory.charset )) else: for i in self.factory.nicks.values(): self.write(i.MyINFO.encode(self.factory.charset)) self.write(self.factory.get_op_list().encode(self.factory.charset)) self.factory.send_to_all(cmd) uips=self.factory.get_userip_acc_list() if ('UserIP' in self._supports) or ('UserIP2' in self._supports): self.factory.send_to_nick(self._nick, '$UserIP %s %s$$' %(self._nick, user.get_ip())) if user.level in self.factory.core_settings['userip']: self.factory.send_to_nick(self._nick, self.factory.get_userip_list()) for unick in uips: self.factory.send_to_nick(unick, '$UserIP %s %s$$' %(self._nick, user.get_ip())) self.factory.send_usercommands_to_nick(self._nick) self.factory.send_to_nick(self._nick, '$HubTopic %s' % self.factory.core_settings['topic']) else: logging.debug('not validated. dropping') self.factory.drop_user(self._addr, self._nick, self.transport) return except: logging.debug('error while connect: %s' % trace()) self.factory.drop_user(self._addr, self._nick, self.transport) return self._state = 'logedin' self.setTimeout(None) def timeoutConnection(self): """ Called when the connection times out. """ logging.debug('timeout: %s' % self._addr) self.write('<HUB> Login timeout!|') self.transport.loseConnection() def on_exit(self): self.work=False self.save_settings() sys.exit() #RUNNING HUB #application = service.Application('DirectConnect Hub') hub = DCHub() hub.protocol = DCProtocol for i in hub.core_settings['port']: try: #internet.TCPServer(i, hub).setServiceParent(application) reactor.listenTCP(i, hub) logging.debug('Started on port %d' % i) except: logging.error('---- A PROBLEM WHILE BINDING TO PORT: %s \n %s----' % (i, trace(),) ) reactor.run()
mayson/viperpeers
viperpeers.py
Python
gpl-2.0
45,342
# ------------------------------------------------------------------------ # Program : gawterm.py # Author : Gerard Wassink # Date : March 17, 2017 # # Function : supply a terminal window with panes for remote control # of my elevator, can also be used for other contraptions # # History : 20170317 - original version # # ------------------------------------------------------------------------ # GNU LICENSE CONDITIONS # ------------------------------------------------------------------------ # 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. # # ------------------------------------------------------------------------ # Copyright (C) 2017 Gerard Wassink # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # Libraries used # ------------------------------------------------------------------------ import curses import curses.textpad import os class term(): """ Screen layout: +--- staFrame -----------------++--- msgFrame -----------------+ |stawin ||msgwin | | || | | || | | || | | || | | || | +--- cmdFrame -----------------+| | |cmdwin || | | || | | || | | || | | || | +------------------------------++------------------------------+ +--- inpFrame -------------------------------------------------+ |> inpwin | +--------------------------------------------------------------+ """ def __init__(self): # ---------------------------------------------------------- # Get terminal size from system # ---------------------------------------------------------- self.termHeight, self.termWidth = \ os.popen('stty size', 'r').read().split() self.termWidth = int(self.termWidth) self.termHeight = int(self.termHeight) # ---------------------------------------------------------- # Calculate various sizes for windows # ---------------------------------------------------------- self.colWidth = (self.termWidth - 4) / 2 self.colHeight = (self.termHeight - 5) self.staHeight = 5 self.cmdHeight = self.colHeight - self.staHeight - 2 # ---------------------------------------------------------- # Initialize curses # ---------------------------------------------------------- stdscr = curses.initscr() curses.noecho() # ---------------------------------------------------------- # Create frame for status window # ---------------------------------------------------------- self.staFrame = curses.newwin(self.staHeight+2, self.colWidth+2, 0, 0) self.staFrame.border() self.staFrame.move(0, 5) self.staFrame.addstr(" Status Window ") self.staFrame.refresh() # ---------------------------------------------------------- # Create status window # ---------------------------------------------------------- self.stawin = curses.newwin(self.staHeight, self.colWidth, 1, 1) # ---------------------------------------------------------- # Create frame for command window # ---------------------------------------------------------- self.cmdFrame = curses.newwin(self.cmdHeight+2, \ self.colWidth+2, \ self.staHeight+2, 0) self.cmdFrame.border() self.cmdFrame.move(0, 5) self.cmdFrame.addstr(" Command Window ") self.cmdFrame.refresh() # ---------------------------------------------------------- # Create command window # ---------------------------------------------------------- self.cmdwin = curses.newwin(self.colHeight-(self.staHeight+2), self.colWidth, \ self.staHeight+3, 1) # ---------------------------------------------------------- # Create frame for message window # ---------------------------------------------------------- self.msgFrame = curses.newwin(self.colHeight+2, self.colWidth+2, \ 0, self.colWidth+2) self.msgFrame.border() self.msgFrame.move(0, 5) self.msgFrame.addstr(" Message Window ") self.msgFrame.refresh() # ---------------------------------------------------------- # Create message window # ---------------------------------------------------------- self.msgwin = curses.newwin(self.colHeight, self.colWidth, \ 1, self.colWidth+3) # ---------------------------------------------------------- # Create frame for input window # ---------------------------------------------------------- self.inpFrame = curses.newwin(3, 2*(self.colWidth+2), \ self.colHeight+2, 0) self.inpFrame.border() self.inpFrame.move(0, 5) self.inpFrame.addstr(" Input: ") self.inpFrame.move(1, 1) self.inpFrame.addstr("> ") self.inpFrame.refresh() # ---------------------------------------------------------- # Create input window # ---------------------------------------------------------- self.inpwin = curses.newwin(1, 2*(self.colWidth), self.colHeight+3, 3) self.inpwin.refresh() # ---------------------------------------------------------- # Create input Textbox # ---------------------------------------------------------- self.inpbox = curses.textpad.Textbox(self.inpwin, insert_mode=True) def inpRead(self): self.inpwin.clear() self.inpwin.move(0, 0) self.inpbox.edit() self.txt = self.inpbox.gather().strip() return self.txt def staPrint(self, text): self.stawin.move(0,0) self.stawin.deleteln() try: self.stawin.addstr(self.staHeight-1, 0, text) except curses.error: pass self.stawin.refresh() def staClear(self): self.stawin.clear() self.stawin.refresh() def cmdPrint(self, text): self.cmdwin.move(0,0) self.cmdwin.deleteln() try: self.cmdwin.addstr(self.cmdHeight-1, 0, text) except curses.error: pass self.cmdwin.refresh() def cmdClear(self): self.cmdwin.clear() self.cmdwin.refresh() def msgPrint(self, text): self.msgwin.move(0,0) self.msgwin.deleteln() try: self.msgwin.addstr(self.colHeight-1, 0, text) except curses.error: pass self.msgwin.refresh() def msgClear(self): self.msgwin.clear() self.msgwin.refresh() def Close(self): curses.echo() curses.endwin()
GerardWassink/elevator.py
gawterm.py
Python
gpl-2.0
7,411
from Probabilidades import Probabilidad from validador import * a = Probabilidad() a.cargarDatos("1","2","3","4","5","6") uno = [" ------- ","| |","| # |","| |"," ------- "] dos = [" ------- ","| # |","| |","| # |"," ------- "] tres = [" ------- ","| # |","| # |","| # |"," ------- "] cuatro = [" ------- ","| # # |","| |","| # # |"," ------- "] cinco = [" ------- ","| # # |","| # |","| # # |"," ------- "] seis = [" ------- ","| # # |","| # # |","| # # |"," ------- "] diccio = {"1":uno,"2":dos,"3":tres,"4":cuatro,"5":cinco,"6":seis} def dado(*repeticiones): tiradas = 1 if (len(repeticiones) > 0): tiradas = repeticiones[0] else: tiradas = 1 for i in range(0,tiradas): numero = a.generar() resultado = diccio[numero] for fila in resultado: print fila seguir = True while (seguir): print "indique la cantidad de tiradas:" ingreso = validador.ingresar(int,validador.entre,0,20) if(ingreso == 0): print "KeepRollingDice4Life" seguir = False else: dado(ingreso) # print "otro?" # seguir = validador.ingresarSINO()
pepitogithub/PythonScripts
Dados.py
Python
gpl-2.0
1,284
from django.shortcuts import redirect from portfolio.models.comments import PhotoComment from portfolio.models.photos import Photo from portfolio.views.base import AuthenticatedView class CommentPhotoView(AuthenticatedView): """ View that handles commenting on a photo """ def post(self, request): comment_content = request.POST.get('comment', '') photo = request.POST.get('photo', 0) if comment_content and photo: comment = PhotoComment( photo=Photo.objects.get(id=photo), owner=request.user, content=comment_content ) comment.save() if not photo: return redirect('portfolio.home') return redirect('portfolio.photo.view', photo_id=photo)
kdimitrov92/Portfolio
portfolio/portfolio/views/comments.py
Python
gpl-2.0
789
# -*- coding: iso-8859-1 -*- # ----------------------------------------------------------------------- # jsonrpc - jsonrpc interface for XBMC-compatible remotes # ----------------------------------------------------------------------- # $Id$ # # JSONRPC and XBMC eventserver to be used for XBMC-compatible # remotes. Only tested with Yatse so far. If something is not working, # do not blame the remote, blame this plugin. # # Not all API calls are implemented yet. # # ----------------------------------------------------------------------- # Freevo - A Home Theater PC framework # Copyright (C) 2014 Dirk Meyer, et al. # # First Edition: Dirk Meyer <https://github.com/Dischi> # Maintainer: Dirk Meyer <https://github.com/Dischi> # # Please see the file AUTHORS for a complete list of authors. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MER- # CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # ----------------------------------------------------------------------- */ # python imports import os import logging import socket import urllib # kaa imports import kaa import kaa.beacon # freevo imports from ... import core as freevo # get logging object log = logging.getLogger('freevo') # generic functions import utils import eventserver # jsonrpc callbacks import videolibrary as VideoLibrary import player as Player import playlist as Playlist class PluginInterface( freevo.Plugin ): """ JSONRPC and XBMC eventserver to be used for XBMC-compatible remotes """ @kaa.coroutine() def plugin_activate(self, level): """ Activate the plugin """ super(PluginInterface, self).plugin_activate(level) self.httpserver = freevo.get_plugin('httpserver') if not self.httpserver: raise RuntimeError('httpserver plugin not running') self.httpserver.server.add_json_handler('/jsonrpc', self.jsonrpc) self.httpserver.server.add_handler('/image/', self.provide_image) self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._sock.bind(('', freevo.config.plugin.jsonrpc.eventserver)) udp = kaa.Socket() udp.wrap(self._sock, kaa.IO_READ | kaa.IO_WRITE) udp.signals['read'].connect(eventserver.handle) utils.imagedir = (yield kaa.beacon.get_db_info())['directory'] utils.cachedir = os.path.join(os.environ['HOME'], '.thumbnails') self.api = {} for module in ('VideoLibrary', 'Player', 'Playlist'): for name in dir(eval(module)): method = getattr(eval(module), name) if callable(method) and not name.startswith('_'): self.api[module + '.' + name] = method @kaa.coroutine() def provide_image(self, path, **attributes): """ HTTP callback for images """ filename = '' path = urllib.unquote(path) if path.startswith('beacon'): filename = os.path.join(utils.imagedir, path[7:]) if path.startswith('cache'): filename = os.path.join(utils.cachedir, path[6:]) if path.startswith('thumbnail'): item = yield kaa.beacon.query(id=int(path.split('/')[2]), type=path.split('/')[1]) if len(item) != 1: log.error('beacon returned wrong results') yield None thumbnail = item[0].get('thumbnail') if thumbnail.needs_update or 1: yield kaa.inprogress(thumbnail.create(priority=kaa.beacon.Thumbnail.PRIORITY_HIGH)) filename = thumbnail.large if filename: if os.path.isfile(filename): yield open(filename).read(), None, None log.error('no file: %s' % filename) yield None else: yield None def Application_GetProperties(self, properties): """ JsonRPC Callback Application.GetProperties """ result = {} for prop in properties: if prop == 'version': result[prop] = {"major": 16,"minor": 0,"revision": "a5f3a99", "tag": "stable"} elif prop == 'volume': result[prop] = 100 elif prop == 'muted': result[prop] = eventserver.muted else: raise AttributeError('unsupported property: %s' % prop) return result def Settings_GetSettingValue(self, setting): """ JsonRPC Settings.GetSettingValue (MISSING) """ return {} def XBMC_GetInfoBooleans(self, booleans): """ JsonRPC Callback XBMC.GetInfoBooleans """ result = {} for b in booleans: if b == 'System.Platform.Linux': result[b] = True else: result[b] = False return result def XBMC_GetInfoLabels(self, labels): """ JsonRPC Callback XBMC.GetInfoLabels """ result = {} for l in labels: # FIXME: use correct values for all these labels if l == 'System.BuildVersion': result[l] = "13.1" elif l == 'System.KernelVersion': result[l] = "Linux 3.11.0" elif l == 'MusicPlayer.Codec': result[l] = "" elif l == 'MusicPlayer.SampleRate': result[l] = "" elif l == 'MusicPlayer.BitRate': result[l] = "" else: raise AttributeError('unsupported label: %s' % l) return result def XBMC_Ping(self): """ JsonRPC Ping """ return '' def JSONRPC_Ping(self): """ JsonRPC Ping """ return '' def GUI_ActivateWindow(self, window, parameters=None): """ Switch Menu Type """ window = window.lower() if window == 'pictures': freevo.Event(freevo.MENU_GOTO_MEDIA).post('image', event_source='user') elif window == 'musiclibrary': freevo.Event(freevo.MENU_GOTO_MEDIA).post('audio', event_source='user') elif window == 'videos': if parameters and parameters[0] == 'MovieTitles': freevo.Event(freevo.MENU_GOTO_MEDIA).post('video', 'movie', event_source='user') if parameters and parameters[0] == 'TvShowTitles': freevo.Event(freevo.MENU_GOTO_MEDIA).post('video', 'tv', event_source='user') elif window == 'home': freevo.Event(freevo.MENU_GOTO_MAINMENU).post(event_source='user') else: log.error('ActivateWindow: unsupported window: %s' % window) @kaa.coroutine() def jsonrpc(self, path, **attributes): """ HTTP callback for /jsonrpc """ if not attributes: # supported XBMC API version yield {"major": 6,"minor": 14,"patch": 3} method = attributes.get('method') params = attributes.get('params') result = None if method.startswith('Input'): callback = eventserver.input(method[6:].lower(), params) yield {'jsonrpc': '2.0', 'result': 'OK', 'id': attributes.get('id')} callback = self.api.get(method, None) or getattr(self, method.replace('.', '_'), None) if callback: # log.info('%s(%s)' % (method, params)) if params is None: result = callback() else: result = callback(**params) if isinstance(result, kaa.InProgress): result = yield result else: raise AttributeError('unsupported method: %s' % method) yield {'jsonrpc': '2.0', 'result': result, 'id': attributes.get('id')}
freevo/freevo2
src/plugins/jsonrpc/__init__.py
Python
gpl-2.0
8,340
#!/usr/bin/env python3 # External command, intended to be called with run_command() or custom_target() # in meson.build # argv[1] argv[2] argv[3:] # skeletonmm-tarball.py <output_file_or_check> <source_dir> <input_files...> import os import sys import shutil import tarfile if sys.argv[1] == 'check': # Called from run_command() during setup or configuration. # Check which archive format can be used. # In order from most wanted to least wanted: .tar.xz, .tar.gz, .tar available_archive_formats = [] for af in shutil.get_archive_formats(): # Keep the formats in a list, skip the descriptions. available_archive_formats += [af[0]] if 'xztar' in available_archive_formats: suffix = '.tar.xz' elif 'gztar' in available_archive_formats: suffix = '.tar.gz' else: # Uncompressed tar format is always available. suffix = '.tar' print(suffix, end='') # stdout can be read in the meson.build file. sys.exit(0) # Create an archive. output_file = sys.argv[1] source_dir = sys.argv[2] if output_file.endswith('.xz'): mode = 'w:xz' elif output_file.endswith('.gz'): mode = 'w:gz' else: mode = 'w' with tarfile.open(output_file, mode=mode) as tar_file: os.chdir(source_dir) # Input filenames are relative to source_dir. for file in sys.argv[3:]: tar_file.add(file) # Errors raise exceptions. If an exception is raised, Meson+ninja will notice # that the command failed, despite exit(0). sys.exit(0) # shutil.make_archive() might be an alternative, but it only archives # whole directories. It's not useful, if you want to have full control # of which files are archived.
GNOME/mm-common
util/meson_aux/skeletonmm-tarball.py
Python
gpl-2.0
1,665
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ nums = [0 for _ in xrange(n + 1)] for i in xrange(1, n + 1): if i == 1: nums[1] = 1 elif i == 2: nums[2] = 2 else: nums[i] = nums[i - 1] + nums[i - 2] return nums[n]
Jacy-Wang/MyLeetCode
ClimbStairs70.py
Python
gpl-2.0
393
"This program will parse matrix files to convert them into objects usable by JS files" # libraries' imports for create the parser ## librairy to create the json object import json import os ## library for using regular expressions import re # opening of all files, each containing an EDNA matrix EDNAFULL=open("EDNA/EDNAFULL.txt") EDNAMAT=open("EDNA/EDNAMAT.txt") EDNASIMPLE=open("EDNA/EDNASIMPLE.txt") #opening of the file which will be writed mat=open ("matrixEDNA.json","w") #creation of the beginning of the file mat.write("matrixEDNA=") mat.write("{") test=os.listdir("./EDNA") print test def parserEDNA(matrix1,name): #reading of the matrix file, line by line matrix=[] content= matrix1.read() lines= content.split("\n") #for each line, delete spaces, write the matrix name and, after, scores into the matrix for i in lines: j=i.split(" ") for k in range(len(j)): if j[0]=="#": pass if j[0]!="#": if re.match(r"[-][0-9]",j[k]) or re.match(r"[0-9]",j[k]): matrix.append(float(j[k])) #convert the Python list in JSON object matrix2=json.dumps(matrix) #writing in the JSON document of the matrix mat.write(name) mat.write(":") mat.write(matrix2) mat.write("\n") #execution of the parser for all matrices liste=[EDNAFULL,EDNAMAT,EDNASIMPLE] for i in range(len(test)): test1=test[i].split(".") parserEDNA(liste[i],test1[0]) # closing of all matrix files, writing the end of the JSON file et closing of this one EDNAFULL.close() EDNAMAT.close() EDNASIMPLE.close() mat.write("}") mat.close()
crazybiocomputing/align2seq
matrix/parserEDNA.py
Python
gpl-2.0
1,539
"""Module to read/write ascii catalog files (CSV and DS9)""" ##@package catalogs ##@file ascii_data """ The following functions are meant to help in reading and writing text CSV catalogs as well as DS9 region files. Main structure used is dictionaries do deal with catalog data in a proper way. """ import sys import logging import csv import re import string # --- def dict_to_csv(columns, fieldnames=[], filename='cat.csv', mode='w', delimiter=','): """ Write a CSV catalog from given dictionary contents Given dictionary is meant to store lists of values corresponding to key/column in the csv file. So that each entry 'fieldnames' is expected to be found within 'columns' keys, and the associated value (list) will be written in a csv column Input: - columns {str:[]} : Contents to be write in csv catalog - fieldnames [str] : List with fieldnames/keys to read from 'columns' - filename str : Name of csv catalog to write - mode str : Write a new catalog, 'w', or append to an existing one, 'a'. - delimiter str : Delimiter to use between columns in 'filename' Output: * If no error messages are returned, a file 'filename' is created. Example: >>> D = {'x':[0,0,1,1],'y':[0,1,0,1],'id':['0_0','0_1','1_0','1_1'],'z':[0,0.5,0.5,1]} #\ >>> fields = ['id','x','y','z'] #\ >>> #\ >>> dict_to_csv( D, fields, filename='test.csv') #\ >>> #\ >>> import os #\ >>> #\ --- """ dictionary = columns.copy() if fieldnames == []: fieldnames = dictionary.keys() for k in fieldnames: if type(dictionary[k])!=type([]) and type(dictionary[k])!=type(()): dictionary[k] = [dictionary[k]] logging.debug("Fields being written to (csv) catalog: %s",fieldnames) max_leng = max([ len(dictionary[k]) for k in fieldnames if type(dictionary[k])==type([]) ]) for k in fieldnames: leng = len(dictionary[k]) if leng != max_leng: dictionary[k].extend(dictionary[k]*(max_leng-leng)) catFile = open(filename,mode) catObj = csv.writer(catFile, delimiter=delimiter) catObj.writerow(fieldnames) LL = [ dictionary[k] for k in fieldnames ] for _row in zip(*LL): catObj.writerow(_row) catFile.close() return # --- def dict_from_csv(filename, fieldnames, header_lines=1, delimiter=',',dialect='excel'): """ Read CSV catalog and return a dictionary with the contents dict_from_csv( filename, fieldnames, ...) -> {} To each column data read from 'filename' is given the respective 'fieldnames' entry. (So that is expected that len(filednames) == #filename-columns) It is expected that the first lines of the CSV file are header lines (comments). The amount of header lines to avoid reading is given through 'header_lines'. 'delimiter' specifies the field separators and 'dialect' is the CSV pattern used. Use 'header_lines' to remove non-data lines from the head of the file. Header lines are taken as comments and are not read. Input: - filename str : Name of csv catalog to read - fieldnames [str] : Fieldnames to be read from catalog - header_lines int : Number of lines to remove from the head of 'filename' - delimiter str : Delimiter to use between columns in 'filename' - dialect str : CSV file fine structure (See help(csv) for more info) Output: - {*fieldnames} Example: # >>> import os # >>> os.system('grep -v "^#" /etc/passwd | head -n 3 > test.asc') # 0 # >>> s = os.system('cat test.asc') nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false root:*:0:0:System Administrator:/var/root:/bin/sh daemon:*:1:1:System Services:/var/root:/usr/bin/false >>> >>> D = dict_from_csv('test.asc',['user','star'],delimiter=':',header_lines=0) >>> --- """ # Initialize output dictionary Dout = {}; for k in fieldnames: Dout[k] = []; #Initialize csv reader catFile = open(filename,'r'); lixo_head = [ catFile.next() for i in range(header_lines) ]; catObj = csv.DictReader(catFile,fieldnames,delimiter=delimiter,dialect=dialect); for row in catObj: for k in fieldnames: Dout[k].append(row[k]); return Dout; # --- def write_ds9cat(x,y,size=20,marker='circle',color='red',outputfile='ds9.reg',filename='None'): """ Function to write a ds9 region file given a set of centroids It works only with a circular 'marker' with fixed radius for all (x,y) - 'centroids' - given. Input: - x : int | [] X-axis points - y : int | [] Y-axis points - size : int | [] - marker : str | [str] - outputfile : str | [str] Output: <bool> Example: >>> write_ds9cat(x=100,y=100,outputfile='test.reg') >>> >>> import os >>> s = os.system('cat test.reg') # Region file format: DS9 version 4.1 # Filename: None global color=green dashlist=8 3 width=1 font="helvetica 10 normal" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 image circle(100,100,20) # color=red >>> >>> >>> >>> write_ds9cat(x=[1,2],y=[0,3],outputfile='test.reg',size=[10,15],marker=['circle','box']) >>> >>> s = os.system('cat test.reg') # Region file format: DS9 version 4.1 # Filename: None global color=green dashlist=8 3 width=1 font="helvetica 10 normal" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1 image circle(1,0,10) # color=red box(2,3,15,15,0) # color=red >>> """ try: if len(x) != len(y): sys.stderr.write("X and Y lengths do not math. Check their sizes.") return False; except: x = [x]; y = [y]; centroids = zip(x,y); length = len(centroids); # Lets verify if everyone here is a list/tuple: # try: len(size); except TypeError: size = [size]; _diff = max(0,length-len(size)) if _diff: size.extend([ size[-1] for i in range(0,_diff+1) ]); # if type(marker) == type(str()): marker = [marker]; _diff = max(0,length-len(marker)) if _diff: marker.extend([ marker[-1] for i in range(0,_diff+1) ]); # if type(color) == type(str()): color = [color]; _diff = max(0,length-len(color)) if _diff: color.extend([ color[-1] for i in range(0,_diff+1) ]); output = open(outputfile,'w'); # DS9 region file header output.write("# Region file format: DS9 version 4.1\n"); output.write("# Filename: %s\n" % (filename)); output.write("global color=green dashlist=8 3 width=1 font=\"helvetica 10 normal\" "); output.write("select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\n"); output.write("image\n"); for i in range(length): if marker[i] == 'circle': output.write("circle(%s,%s,%s) # color=%s\n" % (x[i],y[i],size[i],color[i])); elif marker[i] == 'box': output.write("box(%s,%s,%s,%s,0) # color=%s\n" % (x[i],y[i],size[i],size[i],color[i])); output.close(); return # --- def read_ds9cat(regionfile): """ Function to read ds9 region file Only regions marked with a 'circle' or 'box' are read. 'color' used for region marks (circle/box) are given as output together with 'x','y','dx','dy' as list in a dictionary. The key 'image' in the output (<dict>) gives the filename in the 'regionfile'. Input: - regionfile : ASCII (ds9 format) file Output: -> {'image':str,'x':[],'y':[],'size':[],'marker':[],'color':[]} Example: >>> write_ds9cat(x=[1,2],y=[0,3],outputfile='test.reg',size=[10,15]) >>> >>> D = read_ds9cat('test.reg') >>> """ D_out = {'filename':'', 'marker':[], 'color':[], 'x':[], 'y':[], 'size':[]}; fp = open(regionfile,'r'); for line in fp.readlines(): if (re.search("^#",line)): if (re.search("Filename",line)): imagename = string.split(line,"/")[-1]; D_out['filename'] = re.sub("# Filename: ","",imagename).rstrip('\n'); continue; else: try: _cl = re.search('(?<=color\=).*',line).group(); color = string.split(_cl)[0]; except AttributeError: pass; if re.search("circle",line) or re.search("box",line): marker = string.split(line,"(")[0]; else: continue; try: _fg = re.sub("\)","",re.search('(?<=box\().*\)',line).group()); x,y,dx,dy = string.split(_fg,sep=",")[:4]; D_out['x'].append(eval(x)); D_out['y'].append(eval(y)); D_out['size'].append(max(eval(dx),eval(dy))); D_out['color'].append(color); D_out['marker'].append(marker); continue; except AttributeError: pass; try: _fg = re.sub("\)","",re.search('(?<=circle\().*\)',line).group()); x,y,R = string.split(_fg,sep=",")[:3]; D_out['x'].append(eval(x)); D_out['y'].append(eval(y)); D_out['size'].append(eval(R)); D_out['color'].append(color); D_out['marker'].append(marker); continue; except AttributeError: pass; fp.close(); return D_out; # --- if __name__ == "__main__": import doctest; doctest.testmod()
chbrandt/zyxw
eada/io/ascii.py
Python
gpl-2.0
9,744
# -*- coding: utf-8 -*- # # PyBorg: The python AI bot. # # Copyright (c) 2000, 2006 Tom Morton, Sebastien Dailly # # # This bot was inspired by the PerlBorg, by Eric Bock. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Tom Morton <tom@moretom.net> # Seb Dailly <seb.dailly@gmail.com> # from random import * import ctypes import sys import os import fileinput import marshal # buffered marshal is bloody fast. wish i'd found this before :) import struct import time import zipfile import re import threading timers_started = False def to_sec(s): seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800} return int(s[:-1])*seconds_per_unit[s[-1]] # This will make the !learn and !teach magic work ;) def dbread(key): value = None if os.path.isfile("qdb.dat"): file = open("qdb.dat") for line in file.readlines(): reps = int(len(line.split(":=:"))-1) data = line.split(":=:")[0] dlen = r'\b.{2,}\b' if re.search(dlen, key, re.IGNORECASE): if key.lower() in data.lower() or data.lower() in key.lower(): if reps > 1: repnum = randint(1, int(reps)) value = line.split(":=:")[repnum].strip() else: value = line.split(":=:")[1].strip() break else: value = None break file.close() return value def dbwrite(key, value): if dbread(key) is None: file = open("qdb.dat", "a") file.write(str(key)+":=:"+str(value)+"\n") file.close() else: for line in fileinput.input("qdb.dat",inplace=1): data = line.split(":=:")[0] dlen = r'\b.{2,}\b' if re.search(dlen, key, re.IGNORECASE): if key.lower() in data.lower() or data.lower() in key.lower(): print str(line.strip())+":=:"+str(value) else: print line.strip() # Some more machic to fix some common issues with the teach system def teach_filter(message): message = message.replace("||", "$C4") message = message.replace("|-:", "$b7") message = message.replace(":-|", "$b6") message = message.replace(";-|", "$b5") message = message.replace("|:", "$b4") message = message.replace(";|", "$b3") message = message.replace("=|", "$b2") message = message.replace(":|", "$b1") return message def unfilter_reply(message): """ This undoes the phrase mangling the central code does so the bot sounds more human :P """ # Had to write my own initial capitalizing code *sigh* message = "%s%s" % (message[:1].upper(), message[1:]) # Fixes punctuation message = message.replace(" ?", "?") message = message.replace(" !", "!") message = message.replace(" .", ".") message = message.replace(" ,", ",") message = message.replace(" : ", ": ") message = message.replace(" ; ", "; ") # Fixes I and I contractions message = message.replace(" i ", " I ") message = message.replace("i'", "I'") # Fixes the common issues with the teach system message = message.replace("$C4", "||") message = message.replace("$b7", "|-:") message = message.replace("$b6", ";-|") message = message.replace("$b5", ":-|") message = message.replace("$b4", "|:") message = message.replace("$b3", ";|") message = message.replace("$b2", "=|") message = message.replace("$b1", ":|") # Fixes emoticons that don't work in lowercase emoticon = re.search("(:|x|;|=|8){1}(-)*(p|x|d){1}", message, re.IGNORECASE) if not emoticon == None: emoticon = "%s" % emoticon.group() message = message.replace(emoticon, emoticon.upper()) # Fixes the annoying XP capitalization in words... message = message.replace("XP", "xp") message = message.replace(" xp", " XP") message = message.replace("XX", "xx") return message def filter_message(message, bot): """ Filter a message body so it is suitable for learning from and replying to. This involves removing confusing characters, padding ? and ! with ". " so they also terminate lines and converting to lower case. """ # remove garbage message = message.replace("\"", "") # remove "s message = message.replace("\n", " ") # remove newlines message = message.replace("\r", " ") # remove carriage returns # remove matching brackets (unmatched ones are likely smileys :-) *cough* # should except out when not found. index = 0 try: while 1: index = message.index("(", index) # Remove matching ) bracket i = message.index(")", index+1) message = message[0:i]+message[i+1:] # And remove the ( message = message[0:index]+message[index+1:] except ValueError, e: pass # Strips out mIRC Control codes ccstrip = re.compile("\x1f|\x02|\x12|\x0f|\x16|\x03(?:\d{1,2}(?:,\d{1,2})?)?", re.UNICODE) message = ccstrip.sub("", message) # Few of my fixes... message = message.replace(": ", " : ") message = message.replace("; ", " ; ") # ^--- because some : and ; might be smileys... message = message.replace("`", "'") message = message.replace("?", " ? ") message = message.replace("!", " ! ") message = message.replace(".", " . ") message = message.replace(",", " , ") # Fixes broken emoticons... message = message.replace("^ . ^", "^.^") message = message.replace("- . -", "-.-") message = message.replace("0 . o", "0.o") message = message.replace("o . o", "o.o") message = message.replace("O . O", "O.O") message = message.replace("< . <", "<.<") message = message.replace("> . >", ">.>") message = message.replace("> . <", ">.<") message = message.replace(": ?", ":?") message = message.replace(":- ?", ":-?") message = message.replace(", , l , ,", ",,l,,") message = message.replace("@ . @", "@.@") words = message.split() if bot.settings.process_with == "pyborg": for x in xrange(0, len(words)): #is there aliases ? for z in bot.settings.aliases.keys(): for alias in bot.settings.aliases[z]: pattern = "^%s$" % alias if re.search(pattern, words[x]): words[x] = z message = " ".join(words) return message class pyborg: import re import cfgfile ver_string = "PyBorg version 1.1.0" saves_version = "1.1.0" # Main command list commandlist = "Pyborg commands:\n!checkdict, !contexts, !help, !known, !learning, !rebuilddict, !replace, !unlearn, !purge, !version, !words, !limit, !alias, !save, !censor, !uncensor, !learn, !teach, !forget, !find, !responses" commanddict = { "help": "Owner command. Usage: !help [command]\nPrints information about using a command, or a list of commands if no command is given", "version": "Usage: !version\nDisplay what version of Pyborg we are running", "words": "Usage: !words\nDisplay how many words are known", "known": "Usage: !known word1 [word2 [...]]\nDisplays if one or more words are known, and how many contexts are known", "contexts": "Owner command. Usage: !contexts <phrase>\nPrint contexts containing <phrase>", "unlearn": "Owner command. Usage: !unlearn <expression>\nRemove all occurances of a word or expression from the dictionary. For example '!unlearn of of' would remove all contexts containing double 'of's", "purge": "Owner command. Usage: !purge [number]\nRemove all occurances of the words that appears in less than <number> contexts", "replace": "Owner command. Usage: !replace <old> <new>\nReplace all occurances of word <old> in the dictionary with <new>", "learning": "Owner command. Usage: !learning [on|off]\nToggle bot learning. Without arguments shows the current setting", "checkdict": "Owner command. Usage: !checkdict\nChecks the dictionary for broken links. Shouldn't happen, but worth trying if you get KeyError crashes", "rebuilddict": "Owner command. Usage: !rebuilddict\nRebuilds dictionary links from the lines of known text. Takes a while. You probably don't need to do it unless your dictionary is very screwed", "censor": "Owner command. Usage: !censor [word1 [...]]\nPrevent the bot using one or more words. Without arguments lists the currently censored words", "uncensor": "Owner command. Usage: !uncensor word1 [word2 [...]]\nRemove censorship on one or more words", "limit": "Owner command. Usage: !limit [number]\nSet the number of words that pyBorg can learn", "alias": "Owner command. Usage: !alias : Show the differents aliases\n!alias <alias> : show the words attached to this alias\n!alias <alias> <word> : link the word to the alias", "learn": "Owner command. Usage: !learn trigger | response\nTeaches the bot to respond the any words similar to the trigger word or phrase with a certain response", "teach": "Owner command. Usage: !teach trigger | response\nTeaches the bot to respond the any words similar to the trigger word or phrase with a certain response", "forget": "Owner command. Usage: !forget trigger\nForces the bot to forget all previously learned responses to a certain trigger word or phrase", "find": "Owner command. Usage: !find trigger\nFinds all matches to the trigger word or phrase and displays the amount of matches", "responses": "Owner command. Usage: !responses\nDisplays the total number of trigger/response pairs the bot has learned" } def __init__(self): """ Open the dictionary. Resize as required. """ # Attempt to load settings self.settings = self.cfgfile.cfgset() self.settings.load("pyborg.cfg", { "num_contexts": ("Total word contexts", 0), "num_words": ("Total unique words known", 0), "max_words": ("max limits in the number of words known", 6000), "learning": ("Allow the bot to learn", 1), "ignore_list":("Words that can be ignored for the answer", ['!.', '?.', "'", ',', ';']), "censored": ("Don't learn the sentence if one of those words is found", []), "num_aliases":("Total of aliases known", 0), "aliases": ("A list of similars words", {}), "process_with":("Wich way for generate the reply ( pyborg|megahal)", "pyborg"), "no_save" :("If True, Pyborg don't saves the dictionary and configuration on disk", "False") } ) self.answers = self.cfgfile.cfgset() self.answers.load("answers.txt", { "sentences": ("A list of prepared answers", {}) } ) self.unfilterd = {} # Starts the timers: global timers_started if timers_started is False: try: self.autosave = threading.Timer(to_sec("125m"), self.save_all) self.autosave.start() self.autopurge = threading.Timer(to_sec("5h"), self.auto_optimise) self.autopurge.start() self.autorebuild = threading.Timer(to_sec("71h"), self.auto_rebuild) self.autorebuild.start() timers_started = True except SystemExit, e: self.autosave.cancel() self.autopurge.cancel() self.autorebuild.cancel() if dbread("hello") is None: dbwrite("hello", "hi #nick") # Read the dictionary if self.settings.process_with == "pyborg": print "Reading dictionary..." try: zfile = zipfile.ZipFile('archive.zip','r') for filename in zfile.namelist(): data = zfile.read(filename) file = open(filename, 'w+b') file.write(data) file.close() except (EOFError, IOError), e: print "no zip found" try: f = open("version", "rb") s = f.read() f.close() if s != self.saves_version: print "Error loading dictionary\Please convert it before launching pyborg" sys.exit(1) f = open("words.dat", "rb") s = f.read() f.close() self.words = marshal.loads(s) del s f = open("lines.dat", "rb") s = f.read() f.close() self.lines = marshal.loads(s) del s except (EOFError, IOError), e: # Create new database self.words = {} self.lines = {} print "Error reading saves. New database created." # Is a resizing required? if len(self.words) != self.settings.num_words: print "Updating dictionary information..." self.settings.num_words = len(self.words) num_contexts = 0 # Get number of contexts for x in self.lines.keys(): num_contexts += len(self.lines[x][0].split()) self.settings.num_contexts = num_contexts # Save new values self.settings.save() # Is an aliases update required ? compteur = 0 for x in self.settings.aliases.keys(): compteur += len(self.settings.aliases[x]) if compteur != self.settings.num_aliases: print "check dictionary for new aliases" self.settings.num_aliases = compteur for x in self.words.keys(): #is there aliases ? if x[0] != '~': for z in self.settings.aliases.keys(): for alias in self.settings.aliases[z]: pattern = "^%s$" % alias if self.re.search(pattern, x, re.IGNORECASE): print "replace %s with %s" %(x, z) self.replace(x, z) for x in self.words.keys(): if not (x in self.settings.aliases.keys()) and x[0] == '~': print "unlearn %s" % x self.settings.num_aliases -= 1 self.unlearn(x) print "unlearned aliases %s" % x #unlearn words in the unlearn.txt file. try: f = open("unlearn.txt", "r") while 1: word = f.readline().strip('\n') if word == "": break if self.words.has_key(word): self.unlearn(word) f.close() except (EOFError, IOError), e: # No words to unlearn pass self.settings.save() def save_all(self, restart_timer = True): if self.settings.process_with == "pyborg" and self.settings.no_save != "True": print "Writing dictionary..." nozip = "no" try: zfile = zipfile.ZipFile('archive.zip','r') for filename in zfile.namelist(): data = zfile.read(filename) file = open(filename, 'w+b') file.write(data) file.close() except (OSError, IOError), e: print "no zip found. Is the programm launch for first time ?" try: os.remove('archive.zip') except: pass f = open("words.dat", "wb") s = marshal.dumps(self.words) f.write(s) f.close() f = open("lines.dat", "wb") s = marshal.dumps(self.lines) f.write(s) f.close() #save the version f = open("version", "w") f.write(self.saves_version) f.close() #zip the files f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED) f.write('words.dat') f.write('lines.dat') f.write('version') f.close() try: os.remove('words.dat') os.remove('lines.dat') os.remove('version') except (OSError, IOError), e: print "could not remove the files" f = open("words.txt", "w") # write each words known wordlist = [] #Sort the list befor to export for key in self.words.keys(): wordlist.append([key, len(self.words[key])]) wordlist.sort(lambda x,y: cmp(x[1],y[1])) map( (lambda x: f.write(str(x[0])+"\n\r") ), wordlist) f.close() f = open("sentences.txt", "w") # write each words known wordlist = [] #Sort the list befor to export for key in self.unfilterd.keys(): wordlist.append([key, self.unfilterd[key]]) wordlist.sort(lambda x,y: cmp(y[1],x[1])) map( (lambda x: f.write(str(x[0])+"\n") ), wordlist) f.close() if restart_timer is True: self.autosave = threading.Timer(to_sec("125m"), self.save_all) self.autosave.start() # Save settings self.settings.save() def auto_optimise(self): if self.settings.process_with == "pyborg" and self.settings.learning == 1: # Let's purge out words with little or no context every day to optimise the word list t = time.time() liste = [] compteur = 0 for w in self.words.keys(): digit = 0 char = 0 for c in w: if c.isalpha(): char += 1 if c.isdigit(): digit += 1 try: c = len(self.words[w]) except: c = 2 if c < 2 or ( digit and char ): liste.append(w) compteur += 1 for w in liste[0:]: self.unlearn(w) # Restarts the timer: self.autopurge = threading.Timer(to_sec("5h"), self.auto_optimise) self.autopurge.start() # Now let's save the changes to disk and be done ;) self.save_all(False) def auto_rebuild(self): if self.settings.process_with == "pyborg" and self.settings.learning == 1: t = time.time() old_lines = self.lines old_num_words = self.settings.num_words old_num_contexts = self.settings.num_contexts self.words = {} self.lines = {} self.settings.num_words = 0 self.settings.num_contexts = 0 for k in old_lines.keys(): self.learn(old_lines[k][0], old_lines[k][1]) # Restarts the timer self.autorebuild = threading.Timer(to_sec("71h"), self.auto_rebuild) self.autorebuild.start() def kill_timers(self): self.autosave.cancel() self.autopurge.cancel() self.autorebuild.cancel() def process_msg(self, io_module, body, replyrate, learn, args, owner=0, not_quiet=1): """ Process message 'body' and pass back to IO module with args. If owner==1 allow owner commands. """ try: if self.settings.process_with == "megahal": import mh_python except: self.settings.process_with = "pyborg" self.settings.save() print "Could not find megahal python library\nProgram ending" sys.exit(1) # add trailing space so sentences are broken up correctly body = body + " " # Parse commands if body[0] == "!": self.do_commands(io_module, body, args, owner) return # Filter out garbage and do some formatting body = filter_message(body, self) # Learn from input if learn == 1: if self.settings.process_with == "pyborg": self.learn(body) elif self.settings.process_with == "megahal" and self.settings.learning == 1: mh_python.learn(body) # Make a reply if desired if randint(0, 99) < replyrate: message = "" #Look if we can find a prepared answer if dbread(body): message = unfilter_reply(dbread(body)) elif not_quiet == 1: for sentence in self.answers.sentences.keys(): pattern = "^%s$" % sentence if re.search(pattern, body, re.IGNORECASE): message = self.answers.sentences[sentence][randint(0, len(self.answers.sentences[sentence])-1)] message = unfilter_reply(message) break else: if body in self.unfilterd: self.unfilterd[body] = self.unfilterd[body] + 1 else: self.unfilterd[body] = 0 if message == "": if self.settings.process_with == "pyborg": message = self.reply(body) message = unfilter_reply(message) elif self.settings.process_with == "megahal": message = mh_python.doreply(body) else: return # single word reply: always output if len(message.split()) == 1: io_module.output(message, args) return # empty. do not output if message == "": return # else output if len(message) >= 25: # Quicker response time for long responses time.sleep(5) else: time.sleep(.2*len(message)) io_module.output(message, args) def do_commands(self, io_module, body, args, owner): """ Respond to user comands. """ msg = "" command_list = body.split() command_list[0] = command_list[0].lower() # Guest commands. # Version string if command_list[0] == "!version": msg = self.ver_string # Learn/Teach commands if command_list[0] == "!teach" or command_list[0] == "!learn": try: key = ' '.join(command_list[1:]).split("|")[0].strip() key = re.sub("[\.\,\?\*\"\'!]","", key) rnum = int(len(' '.join(command_list[1:]).split("|"))-1) if "#nick" in key: msg = "Stop trying to teach me something that will break me!" else: value = teach_filter(' '.join(command_list[1:]).split("|")[1].strip()) dbwrite(key[0:], value[0:]) if rnum > 1: array = ' '.join(command_list[1:]).split("|") rcount = 1 for value in array: if rcount == 1: rcount = rcount+1 else: dbwrite(key[0:], teach_filter(value[0:].strip())) else: value = ' '.join(command_list[1:]).split("|")[1].strip() dbwrite(key[0:], teach_filter(value[0:])) msg = "New response learned for %s" % key except: msg = "I couldn't learn that!" # Forget command if command_list[0] == "!forget": if os.path.isfile("qdb.dat"): try: key = ' '.join(command_list[1:]).strip() for line in fileinput.input("qdb.dat" ,inplace =1): data = line.split(":=:")[0] dlen = r'\b.{2,}\b' if re.search(dlen, key, re.IGNORECASE): if key.lower() in data.lower() or data.lower() in key.lower(): pass else: print line.strip() msg = "I've forgotten %s" % key except: msg = "Sorry, I couldn't forget that!" else: msg = "You have to teach me before you can make me forget it!" # Find response command if command_list[0] == "!find": if os.path.isfile("qdb.dat"): rcount = 0 matches = "" key = ' '.join(command_list[1:]).strip() file = open("qdb.dat") for line in file.readlines(): data = line.split(":=:")[0] dlen = r'\b.{2,}\b' if re.search(dlen, key, re.IGNORECASE): if key.lower() in data.lower() or data.lower() in key.lower(): if key.lower() is "": pass else: rcount = rcount+1 if matches == "": matches = data else: matches = matches+", "+data file.close() if rcount < 1: msg = "I have no match for %s" % key elif rcount == 1: msg = "I found 1 match: %s" % matches else: msg = "I found %d matches: %s" % (rcount, matches) else: msg = "You need to teach me something first!" if command_list[0] == "!responses": if os.path.isfile("qdb.dat"): rcount = 0 file = open("qdb.dat") for line in file.readlines(): if line is "": pass else: rcount = rcount+1 file.close() if rcount < 1: msg = "I've learned no responses" elif rcount == 1: msg = "I've learned only 1 response" else: msg = "I've learned %d responses" % rcount else: msg = "You need to teach me something first!" # How many words do we know? elif command_list[0] == "!words" and self.settings.process_with == "pyborg": num_w = self.settings.num_words num_c = self.settings.num_contexts num_l = len(self.lines) if num_w != 0: num_cpw = num_c/float(num_w) # contexts per word else: num_cpw = 0.0 msg = "I know %d words (%d contexts, %.2f per word), %d lines." % (num_w, num_c, num_cpw, num_l) # Do i know this word elif command_list[0] == "!known" and self.settings.process_with == "pyborg": if len(command_list) == 2: # single word specified word = command_list[1].lower() if self.words.has_key(word): c = len(self.words[word]) msg = "%s is known (%d contexts)" % (word, c) else: msg = "%s is unknown." % word elif len(command_list) > 2: # multiple words. words = [] for x in command_list[1:]: words.append(x.lower()) msg = "Number of contexts: " for x in words: if self.words.has_key(x): c = len(self.words[x]) msg += x+"/"+str(c)+" " else: msg += x+"/0 " # Owner commands if owner == 1: # Save dictionary if command_list[0] == "!save": self.save_all() msg = "Dictionary saved" # Command list elif command_list[0] == "!help": if len(command_list) > 1: # Help for a specific command cmd = command_list[1].lower() dic = None if cmd in self.commanddict.keys(): dic = self.commanddict elif cmd in io_module.commanddict.keys(): dic = io_module.commanddict if dic: for i in dic[cmd].split("\n"): io_module.output(i, args) else: msg = "No help on command '%s'" % cmd else: for i in self.commandlist.split("\n"): io_module.output(i, args) for i in io_module.commandlist.split("\n"): io_module.output(i, args) # Change the max_words setting elif command_list[0] == "!limit" and self.settings.process_with == "pyborg": msg = "The max limit is " if len(command_list) == 1: msg += str(self.settings.max_words) else: limit = int(command_list[1].lower()) self.settings.max_words = limit msg += "now " + command_list[1] # Check for broken links in the dictionary elif command_list[0] == "!checkdict" and self.settings.process_with == "pyborg": t = time.time() num_broken = 0 num_bad = 0 for w in self.words.keys(): wlist = self.words[w] for i in xrange(len(wlist)-1, -1, -1): line_idx, word_num = struct.unpack("iH", wlist[i]) # Nasty critical error we should fix if not self.lines.has_key(line_idx): print "Removing broken link '%s' -> %d" % (w, line_idx) num_broken = num_broken + 1 del wlist[i] else: # Check pointed to word is correct split_line = self.lines[line_idx][0].split() if split_line[word_num] != w: print "Line '%s' word %d is not '%s' as expected." % \ (self.lines[line_idx][0], word_num, w) num_bad = num_bad + 1 del wlist[i] if len(wlist) == 0: del self.words[w] self.settings.num_words = self.settings.num_words - 1 print "\"%s\" vaped totally" % w msg = "Checked dictionary in %0.2fs. Fixed links: %d broken, %d bad." % \ (time.time()-t, num_broken, num_bad) # Rebuild the dictionary by discarding the word links and # re-parsing each line elif command_list[0] == "!rebuilddict" and self.settings.process_with == "pyborg": if self.settings.learning == 1: t = time.time() old_lines = self.lines old_num_words = self.settings.num_words old_num_contexts = self.settings.num_contexts self.words = {} self.lines = {} self.settings.num_words = 0 self.settings.num_contexts = 0 for k in old_lines.keys(): self.learn(old_lines[k][0], old_lines[k][1]) msg = "Rebuilt dictionary in %0.2fs. Words %d (%+d), contexts %d (%+d)" % \ (time.time()-t, old_num_words, self.settings.num_words - old_num_words, old_num_contexts, self.settings.num_contexts - old_num_contexts) #Remove rares words elif command_list[0] == "!purge" and self.settings.process_with == "pyborg": t = time.time() liste = [] compteur = 0 if len(command_list) == 2: # limite d occurences a effacer c_max = command_list[1].lower() else: c_max = 0 c_max = int(c_max) for w in self.words.keys(): digit = 0 char = 0 for c in w: if c.isalpha(): char += 1 if c.isdigit(): digit += 1 #Compte les mots inferieurs a cette limite c = len(self.words[w]) if c < 2 or ( digit and char ): liste.append(w) compteur += 1 if compteur == c_max: break if c_max < 1: #io_module.output(str(compteur)+" words to remove", args) io_module.output("%s words to remove" %compteur, args) return #supprime les mots for w in liste[0:]: self.unlearn(w) msg = "Purge dictionary in %0.2fs. %d words removed" % \ (time.time()-t, compteur) # Change a typo in the dictionary elif command_list[0] == "!replace" and self.settings.process_with == "pyborg": if len(command_list) < 3: return old = command_list[1].lower() new = command_list[2].lower() msg = self.replace(old, new) # Print contexts [flooding...:-] elif command_list[0] == "!contexts" and self.settings.process_with == "pyborg": # This is a large lump of data and should # probably be printed, not module.output XXX # build context we are looking for context = " ".join(command_list[1:]) context = context.lower() if context == "": return io_module.output("Contexts containing \""+context+"\":", args) # Build context list # Pad it context = " "+context+" " c = [] # Search through contexts for x in self.lines.keys(): # get context ctxt = self.lines[x][0] # add leading whitespace for easy sloppy search code ctxt = " "+ctxt+" " if ctxt.find(context) != -1: # Avoid duplicates (2 of a word # in a single context) if len(c) == 0: c.append(self.lines[x][0]) elif c[len(c)-1] != self.lines[x][0]: c.append(self.lines[x][0]) x = 0 while x < 5: if x < len(c): io_module.output(c[x], args) x += 1 if len(c) == 5: return if len(c) > 10: io_module.output("...("+`len(c)-10`+" skipped)...", args) x = len(c) - 5 if x < 5: x = 5 while x < len(c): io_module.output(c[x], args) x += 1 # Remove a word from the vocabulary [use with care] elif command_list[0] == "!unlearn" and self.settings.process_with == "pyborg": # build context we are looking for context = " ".join(command_list[1:]) context = context.lower() if context == "": return print "Looking for: "+context # Unlearn contexts containing 'context' t = time.time() self.unlearn(context) # we don't actually check if anything was # done.. msg = "Unlearn done in %0.2fs" % (time.time()-t) # Query/toggle bot learning elif command_list[0] == "!learning": msg = "Learning mode " if len(command_list) == 1: if self.settings.learning == 0: msg += "off" else: msg += "on" else: toggle = command_list[1].lower() if toggle == "on": msg += "on" self.settings.learning = 1 else: msg += "off" self.settings.learning = 0 # add a word to the 'censored' list elif command_list[0] == "!censor" and self.settings.process_with == "pyborg": # no arguments. list censored words if len(command_list) == 1: if len(self.settings.censored) == 0: msg = "No words censored" else: msg = "I will not use the word(s) %s" % ", ".join(self.settings.censored) # add every word listed to censored list else: for x in xrange(1, len(command_list)): if command_list[x] in self.settings.censored: msg += "%s is already censored" % command_list[x] else: self.settings.censored.append(command_list[x].lower()) self.unlearn(command_list[x]) msg += "done" msg += "\n" # remove a word from the censored list elif command_list[0] == "!uncensor" and self.settings.process_with == "pyborg": # Remove everyone listed from the ignore list # eg !unignore tom dick harry for x in xrange(1, len(command_list)): try: self.settings.censored.remove(command_list[x].lower()) msg = "done" except ValueError, e: pass elif command_list[0] == "!alias" and self.settings.process_with == "pyborg": # no arguments. list aliases words if len(command_list) == 1: if len(self.settings.aliases) == 0: msg = "No aliases" else: msg = "I will alias the word(s) %s" \ % ", ".join(self.settings.aliases.keys()) # add every word listed to alias list elif len(command_list) == 2: if command_list[1][0] != '~': command_list[1] = '~' + command_list[1] if command_list[1] in self.settings.aliases.keys(): msg = "Thoses words : %s are aliases to %s" \ % ( " ".join(self.settings.aliases[command_list[1]]), command_list[1] ) else: msg = "The alias %s is not known" % command_list[1][1:] elif len(command_list) > 2: #create the aliases msg = "The words : " if command_list[1][0] != '~': command_list[1] = '~' + command_list[1] if not(command_list[1] in self.settings.aliases.keys()): self.settings.aliases[command_list[1]] = [command_list[1][1:]] self.replace(command_list[1][1:], command_list[1]) msg += command_list[1][1:] + " " for x in xrange(2, len(command_list)): msg += "%s " % command_list[x] self.settings.aliases[command_list[1]].append(command_list[x]) #replace each words by his alias self.replace(command_list[x], command_list[1]) msg += "have been aliases to %s" % command_list[1] # Quit elif command_list[0] == "!quit": # Close the dictionary self.save_all() sys.exit() # Save changes self.settings.save() if msg != "": io_module.output(msg, args) def replace(self, old, new): """ Replace all occuraces of 'old' in the dictionary with 'new'. Nice for fixing learnt typos. """ try: pointers = self.words[old] except KeyError, e: return old+" not known." changed = 0 for x in pointers: # pointers consist of (line, word) to self.lines l, w = struct.unpack("iH", x) line = self.lines[l][0].split() number = self.lines[l][1] if line[w] != old: # fucked dictionary print "Broken link: %s %s" % (x, self.lines[l][0] ) continue else: line[w] = new self.lines[l][0] = " ".join(line) self.lines[l][1] += number changed += 1 if self.words.has_key(new): self.settings.num_words -= 1 self.words[new].extend(self.words[old]) else: self.words[new] = self.words[old] del self.words[old] return "%d instances of %s replaced with %s" % ( changed, old, new ) def unlearn(self, context): """ Unlearn all contexts containing 'context'. If 'context' is a single word then all contexts containing that word will be removed, just like the old !unlearn <word> """ # Pad thing to look for # We pad so we don't match 'shit' when searching for 'hit', etc. context = " "+context+" " # Search through contexts # count deleted items dellist = [] # words that will have broken context due to this wordlist = [] for x in self.lines.keys(): # get context. pad c = " "+self.lines[x][0]+" " if c.find(context) != -1: # Split line up wlist = self.lines[x][0].split() # add touched words to list for w in wlist: if not w in wordlist: wordlist.append(w) dellist.append(x) del self.lines[x] words = self.words unpack = struct.unpack # update links for x in wordlist: word_contexts = words[x] # Check all the word's links (backwards so we can delete) for y in xrange(len(word_contexts)-1, -1, -1): # Check for any of the deleted contexts if unpack("iH", word_contexts[y])[0] in dellist: del word_contexts[y] self.settings.num_contexts = self.settings.num_contexts - 1 if len(words[x]) == 0: del words[x] self.settings.num_words = self.settings.num_words - 1 print "\"%s\" vaped totally" %x def reply(self, body): """ Reply to a line of text. """ # split sentences into list of words _words = body.split(" ") words = [] for i in _words: words += i.split() del _words if len(words) == 0: return "" #remove words on the ignore list #words = filter((lambda x: x not in self.settings.ignore_list and not x.isdigit() ), words) words = [x for x in words if x not in self.settings.ignore_list and not x.isdigit()] # Find rarest word (excluding those unknown) index = [] known = -1 #The word has to bee seen in already 3 contexts differents for being choosen known_min = 3 for x in xrange(0, len(words)): if self.words.has_key(words[x]): k = len(self.words[words[x]]) else: continue if (known == -1 or k < known) and k > known_min: index = [words[x]] known = k continue elif k == known: index.append(words[x]) continue # Index now contains list of rarest known words in sentence if len(index)==0: return "" word = index[randint(0, len(index)-1)] # Build sentence backwards from "chosen" word sentence = [word] done = 0 while done == 0: #create a dictionary wich will contain all the words we can found before the "chosen" word pre_words = {"" : 0} #this is for prevent the case when we have an ignore_listed word word = str(sentence[0].split(" ")[0]) for x in xrange(0, len(self.words[word]) -1 ): l, w = struct.unpack("iH", self.words[word][x]) context = self.lines[l][0] num_context = self.lines[l][1] cwords = context.split() #if the word is not the first of the context, look the previous one if cwords[w] != word: print context if w: #look if we can found a pair with the choosen word, and the previous one if len(sentence) > 1 and len(cwords) > w+1: if sentence[1] != cwords[w+1]: continue #if the word is in ignore_list, look the previous word look_for = cwords[w-1] if look_for in self.settings.ignore_list and w > 1: look_for = cwords[w-2]+" "+look_for #saves how many times we can found each word if not(pre_words.has_key(look_for)): pre_words[look_for] = num_context else : pre_words[look_for] += num_context else: pre_words[""] += num_context #Sort the words liste = pre_words.items() liste.sort(lambda x,y: cmp(y[1],x[1])) numbers = [liste[0][1]] for x in xrange(1, len(liste) ): numbers.append(liste[x][1] + numbers[x-1]) #take one them from the list ( randomly ) mot = randint(0, numbers[len(numbers) -1]) for x in xrange(0, len(numbers)): if mot <= numbers[x]: mot = liste[x][0] break #if the word is already choosen, pick the next one while mot in sentence: x += 1 if x >= len(liste) -1: mot = '' mot = liste[x][0] mot = mot.split(" ") mot.reverse() if mot == ['']: done = 1 else: map( (lambda x: sentence.insert(0, x) ), mot ) pre_words = sentence sentence = sentence[-2:] # Now build sentence forwards from "chosen" word #We've got #cwords: ... cwords[w-1] cwords[w] cwords[w+1] cwords[w+2] #sentence: ... sentence[-2] sentence[-1] look_for look_for ? #we are looking, for a cwords[w] known, and maybe a cwords[w-1] known, what will be the cwords[w+1] to choose. #cwords[w+2] is need when cwords[w+1] is in ignored list done = 0 while done == 0: #create a dictionary wich will contain all the words we can found before the "chosen" word post_words = {"" : 0} word = str(sentence[-1].split(" ")[-1]) for x in xrange(0, len(self.words[word]) ): l, w = struct.unpack("iH", self.words[word][x]) context = self.lines[l][0] num_context = self.lines[l][1] cwords = context.split() #look if we can found a pair with the choosen word, and the next one if len(sentence) > 1: if sentence[len(sentence)-2] != cwords[w-1]: continue if w < len(cwords)-1: #if the word is in ignore_list, look the next word look_for = cwords[w+1] if look_for in self.settings.ignore_list and w < len(cwords) -2: look_for = look_for+" "+cwords[w+2] if not(post_words.has_key(look_for)): post_words[look_for] = num_context else : post_words[look_for] += num_context else: post_words[""] += num_context #Sort the words liste = post_words.items() liste.sort(lambda x,y: cmp(y[1],x[1])) numbers = [liste[0][1]] for x in xrange(1, len(liste) ): numbers.append(liste[x][1] + numbers[x-1]) #take one them from the list ( randomly ) mot = randint(0, numbers[len(numbers) -1]) for x in xrange(0, len(numbers)): if mot <= numbers[x]: mot = liste[x][0] break x = -1 while mot in sentence: x += 1 if x >= len(liste) -1: mot = '' break mot = liste[x][0] mot = mot.split(" ") if mot == ['']: done = 1 else: map( (lambda x: sentence.append(x) ), mot ) sentence = pre_words[:-2] + sentence #Replace aliases for x in xrange(0, len(sentence)): if sentence[x][0] == "~": sentence[x] = sentence[x][1:] #Insert space between each words map( (lambda x: sentence.insert(1+x*2, " ") ), xrange(0, len(sentence)-1) ) #correct the ' & , spaces problem #code is not very good and can be improve but does his job... for x in xrange(0, len(sentence)): if sentence[x] == "'": sentence[x-1] = "" sentence[x+1] = "" if sentence[x] == ",": sentence[x-1] = "" #return as string.. return "".join(sentence) def learn(self, body, num_context=1): """ Lines should be cleaned (filter_message()) before passing to this. """ def learn_line(self, body, num_context): """ Learn from a sentence. """ import re words = body.split() # Ignore sentences of < 1 words XXX was <3 if len(words) < 1: return voyelles = "aàâeéèêiîïoöôuüûy" for x in xrange(0, len(words)): nb_voy = 0 digit = 0 char = 0 for c in words[x]: if c in voyelles: nb_voy += 1 if c.isalpha(): char += 1 if c.isdigit(): digit += 1 for censored in self.settings.censored: pattern = "^%s$" % censored if re.search(pattern, words[x]): print "Censored word %s" %words[x] return if len(words[x]) > 13 \ or ( ((nb_voy*100) / len(words[x]) < 26) and len(words[x]) > 5 ) \ or ( char and digit ) \ or ( self.words.has_key(words[x]) == 0 and self.settings.learning == 0 ): #if one word as more than 13 characters, don't learn # ( in french, this represent 12% of the words ) #and d'ont learn words where there are less than 25% of voyels #don't learn the sentence if one word is censored #don't learn too if there are digits and char in the word #same if learning is off return elif ( "-" in words[x] or "_" in words[x] ) : words[x]="#nick" num_w = self.settings.num_words if num_w != 0: num_cpw = self.settings.num_contexts/float(num_w) # contexts per word else: num_cpw = 0 cleanbody = " ".join(words) # Hash collisions we don't care about. 2^32 is big :-) hashval = ctypes.c_int32(hash(cleanbody)).value # Check context isn't already known if not self.lines.has_key(hashval): if not(num_cpw > 100 and self.settings.learning == 0): self.lines[hashval] = [cleanbody, num_context] # Add link for each word for x in xrange(0, len(words)): if self.words.has_key(words[x]): # Add entry. (line number, word number) self.words[words[x]].append(struct.pack("iH", hashval, x)) else: self.words[words[x]] = [ struct.pack("iH", hashval, x) ] self.settings.num_words += 1 self.settings.num_contexts += 1 else : self.lines[hashval][1] += num_context #is max_words reached, don't learn more if self.settings.num_words >= self.settings.max_words: self.settings.learning = 0 # Split body text into sentences and parse them # one by one. body += " " map ( (lambda x : learn_line(self, x, num_context)), body.split(". "))
awildeone/Wusif
pyborg.py
Python
gpl-2.0
42,867
from datetime import date class YearInfo(object): def __init__(self, year, months_ok, months_na): self.year = year self.months = set(range(1, 13)) self.months_ok = set(months_ok) self.months_na = set(months_na) self.months_er = self.months - (self.months_ok | self.months_na) today = date.today() if self.year == today.year: self.months_er -= set(range(today.month, 13)) def __unicode__(self): return u'%s' % self.year def missing(self): return len(self.months_er) != 0 def payments_by_month(payments_list): monthly_data = set() if not payments_list: return [] for payment in payments_list: for m in payment.formonths(): monthly_data.add(m) since_year = payment.user.date_joined.year since_month = payment.user.date_joined.month years = set(range(since_year, date.today().year+1)) out = [] for y in years: ok = map(lambda x: x[1], filter(lambda x: x[0] == y, monthly_data)) na = [] if y == since_year: na = range(1, since_month) yi = YearInfo(y, ok, na) out.append(yi) return out def no_missing_payments(payments_list): plist = payments_by_month(payments_list) for year in plist: if year.missing(): return False return True def missing_months(payments_list): plist = payments_by_month(payments_list) missing = [] for yi in plist: if yi.missing(): for month in yi.months_er: missing.append((yi.year, month)) return missing
hackerspace/memberportal
payments/common.py
Python
gpl-2.0
1,647
# # Copyright (c) 1999--2015 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # # This thing gets the hardware configuraion out of a system """Used to read hardware info from kudzu, /proc, etc""" from socket import gethostname, getaddrinfo, AF_INET, AF_INET6 import socket import re import os import sys from up2date_client import config from up2date_client import rhnserver from rhn.i18n import ustr try: long except NameError: # long is not defined in python3 long = int try: import ethtool ethtool_present = True except ImportError: sys.stderr.write("Warning: information about network interfaces could not be retrieved on this platform.\n") ethtool_present = False import gettext t = gettext.translation('rhn-client-tools', fallback=True) # Python 3 translations don't have a ugettext method if not hasattr(t, 'ugettext'): t.ugettext = t.gettext _ = t.ugettext import dbus import dmidecode from up2date_client import up2dateLog try: # F13 and EL6 from up2date_client.hardware_gudev import get_devices, get_computer_info using_gudev = 1 except ImportError: from up2date_client.hardware_hal import check_hal_dbus_status, get_hal_computer, read_hal using_gudev = 0 # Some systems don't have the _locale module installed try: import locale except ImportError: locale = None sys.path.append("/usr/share/rhsm") try: from subscription_manager.hwprobe import Hardware as SubManHardware subscription_manager_available = True except ImportError: subscription_manager_available = False # this does not change, we can cache it _dmi_data = None _dmi_not_available = 0 def dmi_warnings(): if not hasattr(dmidecode, 'get_warnings'): return None return dmidecode.get_warnings() dmi_warn = dmi_warnings() if dmi_warn: dmidecode.clear_warnings() log = up2dateLog.initLog() log.log_debug("Warnings collected during dmidecode import: %s" % dmi_warn) def _initialize_dmi_data(): """ Initialize _dmi_data unless it already exist and returns it """ global _dmi_data, _dmi_not_available if _dmi_data is None: if _dmi_not_available: # do not try to initialize it again and again if not available return None else : dmixml = dmidecode.dmidecodeXML() dmixml.SetResultType(dmidecode.DMIXML_DOC) # Get all the DMI data and prepare a XPath context try: data = dmixml.QuerySection('all') dmi_warn = dmi_warnings() if dmi_warn: dmidecode.clear_warnings() log = up2dateLog.initLog() log.log_debug("dmidecode warnings: " % dmi_warn) except: # DMI decode FAIL, this can happend e.g in PV guest _dmi_not_available = 1 dmi_warn = dmi_warnings() if dmi_warn: dmidecode.clear_warnings() return None _dmi_data = data.xpathNewContext() return _dmi_data def get_dmi_data(path): """ Fetch DMI data from given section using given path. If data could not be retrieved, returns empty string. General method and should not be used outside of this module. """ dmi_data = _initialize_dmi_data() if dmi_data is None: return '' data = dmi_data.xpathEval(path) if data != []: return data[0].content else: # The path do not exist return '' def dmi_vendor(): """ Return Vendor from dmidecode bios information. If this value could not be fetch, returns empty string. """ return get_dmi_data('/dmidecode/BIOSinfo/Vendor') def dmi_system_uuid(): """ Return UUID from dmidecode system information. If this value could not be fetch, returns empty string. """ # if guest was created manualy it can have empty UUID, in this # case dmidecode set attribute unavailable to 1 uuid = get_dmi_data("/dmidecode/SystemInfo/SystemUUID[not(@unavailable='1')]") if not uuid: uuid = '' return uuid def read_installinfo(): if not os.access("/etc/sysconfig/installinfo", os.R_OK): return {} installinfo = open("/etc/sysconfig/installinfo", "r").readlines() installdict = {} installdict['class'] = "INSTALLINFO" for info in installinfo: if not len(info): continue vals = info.split('=') if len(vals) <= 1: continue strippedstring = vals[0].strip() vals[0] = strippedstring installdict[vals[0]] = ''.join(vals[1:]).strip() return installdict def cpu_count(): """ returns number of CPU in system Beware that it can be different from number of active CPU (e.g. on s390x architecture """ try: cpu_dir = os.listdir('/sys/devices/system/cpu/') except OSError: cpu_dir = [] re_cpu = re.compile(r"^cpu[0-9]+$") return len([i for i in cpu_dir if re_cpu.match(i)]) # get the number of sockets available on this machine def __get_number_sockets(): try: if subscription_manager_available: return SubManHardware().getCpuInfo()['cpu.cpu_socket(s)'] except: pass # something went wrong, let's figure it out ourselves number_sockets = 0 # Try lscpu command if available if os.access("/usr/bin/lscpu", os.X_OK): try: lines = os.popen("/usr/bin/lscpu -p").readlines() max_socket_index = -1 for line in lines: if line.startswith('#'): continue # get the socket index from the output socket_index = int(line.split(',')[2]) if socket_index > max_socket_index: max_socket_index = socket_index if max_socket_index > -1: return 1 + max_socket_index except: pass # Next try parsing /proc/cpuinfo if os.access("/proc/cpuinfo", os.R_OK): try: lines = open("/proc/cpuinfo", 'r').readlines() socket_ids = set() for line in lines: if 'physical id' in line: socket_index = int(line.split(':')[1].strip()) socket_ids.add(socket_index) if len(socket_ids) > 0: return len(socket_ids) except: pass # Next try dmidecode if os.access("/usr/sbin/dmidecode", os.X_OK): try: lines = os.popen("/usr/sbin/dmidecode -t processor").readlines() count = 0 for line in lines: if 'Processor Information' in line: count += 1 if count > 0: return count except: pass return None # This has got to be one of the ugliest fucntions alive def read_cpuinfo(): def get_entry(a, entry): e = entry.lower() if not e in a: return "" return a[e] # read cpu list and return number of cpus and list as dictionary def get_cpulist_as_dict(cpulist): count = 0 tmpdict = {} for cpu in cpulist.split("\n\n"): if not len(cpu): continue count = count + 1 if count > 1: break # no need to parse rest for cpu_attr in cpu.split("\n"): if not len(cpu_attr): continue vals = cpu_attr.split(":") if len(vals) != 2: # XXX: make at least some effort to recover this data... continue name, value = vals[0].strip(), vals[1].strip() tmpdict[name.lower()] = value return tmpdict if not os.access("/proc/cpuinfo", os.R_OK): return {} # Okay, the kernel likes to give us the information we need in the # standard "C" locale. if locale: # not really needed if you don't plan on using atof() locale.setlocale(locale.LC_NUMERIC, "C") cpulist = open("/proc/cpuinfo", "r").read() uname = os.uname()[4].lower() count = cpu_count() # This thing should return a hwdict that has the following # members: # # class, desc (required to identify the hardware device) # count, type, model, model_number, model_ver, model_rev # bogomips, platform, speed, cache hwdict = { 'class': "CPU", "desc" : "Processor", } if uname[0] == "i" and uname[-2:] == "86" or (uname == "x86_64"): # IA32 compatible enough tmpdict = get_cpulist_as_dict(cpulist) if uname == "x86_64": hwdict['platform'] = 'x86_64' else: hwdict['platform'] = "i386" hwdict['count'] = count hwdict['type'] = get_entry(tmpdict, 'vendor_id') hwdict['model'] = get_entry(tmpdict, 'model name') hwdict['model_number'] = get_entry(tmpdict, 'cpu family') hwdict['model_ver'] = get_entry(tmpdict, 'model') hwdict['model_rev'] = get_entry(tmpdict, 'stepping') hwdict['cache'] = get_entry(tmpdict, 'cache size') hwdict['bogomips'] = get_entry(tmpdict, 'bogomips') hwdict['other'] = get_entry(tmpdict, 'flags') mhz_speed = get_entry(tmpdict, 'cpu mhz') if mhz_speed == "": # damn, some machines don't report this mhz_speed = "-1" try: hwdict['speed'] = int(round(float(mhz_speed)) - 1) except ValueError: hwdict['speed'] = -1 elif uname in["alpha", "alphaev6"]: # Treat it as an an Alpha tmpdict = get_cpulist_as_dict(cpulist) hwdict['platform'] = "alpha" hwdict['count'] = get_entry(tmpdict, 'cpus detected') hwdict['type'] = get_entry(tmpdict, 'cpu') hwdict['model'] = get_entry(tmpdict, 'cpu model') hwdict['model_number'] = get_entry(tmpdict, 'cpu variation') hwdict['model_version'] = "%s/%s" % (get_entry(tmpdict, 'system type'), get_entry(tmpdict,'system variation')) hwdict['model_rev'] = get_entry(tmpdict, 'cpu revision') hwdict['cache'] = "" # pitty the kernel doesn't tell us this. hwdict['bogomips'] = get_entry(tmpdict, 'bogomips') hwdict['other'] = get_entry(tmpdict, 'platform string') hz_speed = get_entry(tmpdict, 'cycle frequency [Hz]') # some funky alphas actually report in the form "462375000 est." hz_speed = hz_speed.split() try: hwdict['speed'] = int(round(float(hz_speed[0]))) / 1000000 except ValueError: hwdict['speed'] = -1 elif uname in ["ia64"]: tmpdict = get_cpulist_as_dict(cpulist) hwdict['platform'] = uname hwdict['count'] = count hwdict['type'] = get_entry(tmpdict, 'vendor') hwdict['model'] = get_entry(tmpdict, 'family') hwdict['model_ver'] = get_entry(tmpdict, 'archrev') hwdict['model_rev'] = get_entry(tmpdict, 'revision') hwdict['bogomips'] = get_entry(tmpdict, 'bogomips') mhz_speed = tmpdict['cpu mhz'] try: hwdict['speed'] = int(round(float(mhz_speed)) - 1) except ValueError: hwdict['speed'] = -1 hwdict['other'] = get_entry(tmpdict, 'features') elif uname in ['ppc64']: tmpdict = get_cpulist_as_dict(cpulist) hwdict['platform'] = uname hwdict['count'] = count hwdict['model'] = get_entry(tmpdict, "cpu") hwdict['model_ver'] = get_entry(tmpdict, 'revision') hwdict['bogomips'] = get_entry(tmpdict, 'bogomips') hwdict['type'] = get_entry(tmpdict, 'machine') # strings are postpended with "mhz" mhz_speed = get_entry(tmpdict, 'clock')[:-3] try: hwdict['speed'] = int(round(float(mhz_speed)) - 1) except ValueError: hwdict['speed'] = -1 elif uname in ['s390', 's390x']: tmpdict = {} for cpu in cpulist.split("\n"): vals = cpu.split(": ") if len(vals) != 2: continue tmpdict[vals[0].strip()] = vals[1].strip() hwdict['platform'] = uname hwdict['type'] = get_entry(tmpdict,'vendor_id') hwdict['model'] = uname hwdict['count'] = count hwdict['bogomips'] = get_entry(tmpdict, 'bogomips per cpu') hwdict['model_number'] = "" hwdict['model_ver'] = "" hwdict['model_rev'] = "" hwdict['cache'] = "" hwdict['other'] = get_entry(tmpdict, 'features') hwdict['speed'] = 0 else: # XXX: expand me. Be nice to others hwdict['platform'] = uname hwdict['count'] = count hwdict['type'] = uname hwdict['model'] = uname hwdict['model_number'] = "" hwdict['model_ver'] = "" hwdict['model_rev'] = "" hwdict['cache'] = "" hwdict['bogomips'] = "" hwdict['other'] = "" hwdict['speed'] = 0 # make sure we get the right number here if not hwdict["count"]: hwdict["count"] = 1 else: try: hwdict["count"] = int(hwdict["count"]) except: hwdict["count"] = 1 else: if hwdict["count"] == 0: # we have at least one hwdict["count"] = 1 # Network communication doesn't really belong in here. Sadly though # this is the only single place we can put this check. If it's not # here then it would need to be in five or six other places, which # is not good from a DRY and quality-assurance perspective. s = rhnserver.RhnServer() if s.capabilities.hasCapability('cpu_sockets'): # If we know it add in the number of sockets number_sockets = __get_number_sockets() if number_sockets: hwdict['socket_count'] = number_sockets # This whole things hurts a lot. return hwdict def read_memory(): un = os.uname() kernel = un[2] if kernel[:3] >= "2.6": return read_memory_2_6() if kernel[:3] == "2.4": return read_memory_2_4() def read_memory_2_4(): if not os.access("/proc/meminfo", os.R_OK): return {} meminfo = open("/proc/meminfo", "r").read() lines = meminfo.split("\n") curline = lines[1] memlist = curline.split() memdict = {} memdict['class'] = "MEMORY" megs = int(long(memlist[1])/(1024*1024)) if megs < 32: megs = megs + (4 - (megs % 4)) else: megs = megs + (16 - (megs % 16)) memdict['ram'] = str(megs) curline = lines[2] memlist = curline.split() # otherwise, it breaks on > ~4gigs of swap megs = int(long(memlist[1])/(1024*1024)) memdict['swap'] = str(megs) return memdict def read_memory_2_6(): if not os.access("/proc/meminfo", os.R_OK): return {} meminfo = open("/proc/meminfo", "r").read() lines = meminfo.split("\n") meminfo_dict = {} for line in lines: blobs = line.split(":", 1) key = blobs[0] if len(blobs) == 1: continue #print(blobs) value = blobs[1].strip() meminfo_dict[key] = value memdict = {} memdict["class"] = "MEMORY" total_str = meminfo_dict['MemTotal'] blips = total_str.split(" ") total_k = long(blips[0]) megs = long(total_k/(1024)) swap_str = meminfo_dict['SwapTotal'] blips = swap_str.split(' ') swap_k = long(blips[0]) swap_megs = long(swap_k/(1024)) memdict['ram'] = str(megs) memdict['swap'] = str(swap_megs) return memdict def findHostByRoute(): """ returns [hostname, intf, intf6] Where hostname is you FQDN of this machine. And intf is numeric IPv4 address. And intf6 is IPv6 address. """ cfg = config.initUp2dateConfig() sl = config.getServerlURL() st = {'https':443, 'http':80} hostname = None intf = None intf6 = None for serverUrl in sl: server = serverUrl.split('/')[2] servertype = serverUrl.split(':')[0] port = st[servertype] for family in (AF_INET6, AF_INET): try: s = socket.socket(family) except socket.error: continue if cfg['enableProxy']: server_port = config.getProxySetting() (server, port) = server_port.split(':') port = int(port) try: s.settimeout(5) s.connect((server, port)) intf_tmp = s.getsockname()[0] if family == AF_INET: intf = intf_tmp else: intf6 = intf_tmp hostname_tmp = socket.getfqdn(intf_tmp) if hostname_tmp != intf_tmp: hostname = hostname_tmp except socket.error: s.close() continue s.close() # Override hostname with the value from /etc/hostname if os.path.isfile("/etc/hostname") and os.access("/etc/hostname", os.R_OK): hostnameinfo = open("/etc/hostname", "r").readlines() for info in hostnameinfo: if not len(info): continue hostname = info.strip() # Override hostname with the one in /etc/sysconfig/network # for bz# 457953 elif os.path.isfile("/etc/sysconfig/network") and os.access("/etc/sysconfig/network", os.R_OK): networkinfo = open("/etc/sysconfig/network", "r").readlines() for info in networkinfo: if not len(info): continue vals = info.split('=') if len(vals) <= 1: continue strippedstring = vals[0].strip() vals[0] = strippedstring if vals[0] == "HOSTNAME": hostname = ''.join(vals[1:]).strip() break if hostname == None or hostname == 'localhost.localdomain': hostname = "unknown" return hostname, intf, intf6 def get_slave_hwaddr(master, slave): hwaddr = "" try: bonding = open('/proc/net/bonding/%s' % master, "r") except: return hwaddr slave_found = False for line in bonding.readlines(): if slave_found and line.find("Permanent HW addr: ") != -1: hwaddr = line.split()[3] break if line.find("Slave Interface: ") != -1: ifname = line.split()[2] if ifname == slave: slave_found = True bonding.close() return hwaddr def read_network(): netdict = {} netdict['class'] = "NETINFO" netdict['hostname'], netdict['ipaddr'], netdict['ip6addr'] = findHostByRoute() if netdict['hostname'] == "unknown": netdict['hostname'] = gethostname() if "." not in netdict['hostname']: netdict['hostname'] = socket.getfqdn() if netdict['ipaddr'] is None: try: list_of_addrs = getaddrinfo(netdict['hostname'], None) ipv4_addrs = filter(lambda x:x[0]==socket.AF_INET, list_of_addrs) # take first ipv4 addr netdict['ipaddr'] = ipv4_addrs[0][4][0] except: netdict['ipaddr'] = "127.0.0.1" if netdict['ip6addr'] is None: try: list_of_addrs = getaddrinfo(netdict['hostname'], None) ipv6_addrs = filter(lambda x:x[0]==socket.AF_INET6, list_of_addrs) # take first ipv6 addr netdict['ip6addr'] = ipv6_addrs[0][4][0] except: netdict['ip6addr'] = "::1" if netdict['ipaddr'] is None: netdict['ipaddr'] = '' if netdict['ip6addr'] is None: netdict['ip6addr'] = '' return netdict def read_network_interfaces(): intDict = {} intDict['class'] = "NETINTERFACES" if not ethtool_present: # ethtool is not available on non-linux platforms (as kfreebsd), skip it return intDict interfaces = list(set(ethtool.get_devices() + ethtool.get_active_devices())) for interface in interfaces: try: hwaddr = ethtool.get_hwaddr(interface) except: hwaddr = "" # slave devices can have their hwaddr changed try: master = os.readlink('/sys/class/net/%s/master' % interface) except: master = None if master: master_interface = os.path.basename(master) hwaddr = get_slave_hwaddr(master_interface, interface) try: module = ethtool.get_module(interface) except: if interface == 'lo': module = "loopback" else: module = "Unknown" try: ipaddr = ethtool.get_ipaddr(interface) except: ipaddr = "" try: netmask = ethtool.get_netmask(interface) except: netmask = "" try: broadcast = ethtool.get_broadcast(interface) except: broadcast = "" ip6_list = [] dev_info = ethtool.get_interfaces_info(interface) for info in dev_info: # one interface may have more IPv6 addresses for ip6 in info.get_ipv6_addresses(): scope = ip6.scope if scope == 'global': scope = 'universe' ip6_list.append({ 'scope': scope, 'addr': ip6.address, 'netmask': ip6.netmask }) intDict[interface] = {'hwaddr':hwaddr, 'ipaddr':ipaddr, 'netmask':netmask, 'broadcast':broadcast, 'module': module, 'ipv6': ip6_list} return intDict # Read DMI information via hal. def read_dmi(): dmidict = {} dmidict["class"] = "DMI" # Try to obtain DMI info if architecture is i386, x86_64 or ia64 uname = os.uname()[4].lower() if not (uname[0] == "i" and uname[-2:] == "86") and not (uname == "x86_64"): return dmidict # System Information vendor = dmi_vendor() if vendor: dmidict["vendor"] = vendor product = get_dmi_data('/dmidecode/SystemInfo/ProductName') if product: dmidict["product"] = product version = get_dmi_data('/dmidecode/SystemInfo/Version') if version: system = product + " " + version dmidict["system"] = system # BaseBoard Information dmidict["board"] = get_dmi_data('/dmidecode/BaseBoardInfo/Manufacturer') # Bios Information vendor = get_dmi_data('/dmidecode/BIOSinfo/Vendor') if vendor: dmidict["bios_vendor"] = vendor version = get_dmi_data('/dmidecode/BIOSinfo/Version') if version: dmidict["bios_version"] = version release = get_dmi_data('/dmidecode/BIOSinfo/ReleaseDate') if release: dmidict["bios_release"] = release # Chassis Information # The hairy part is figuring out if there is an asset tag/serial number of importance chassis_serial = get_dmi_data('/dmidecode/ChassisInfo/SerialNumber') chassis_tag = get_dmi_data('/dmidecode/ChassisInfo/AssetTag') board_serial = get_dmi_data('/dmidecode/BaseBoardInfo/SerialNumber') system_serial = get_dmi_data('/dmidecode/SystemInfo/SerialNumber') dmidict["asset"] = "(%s: %s) (%s: %s) (%s: %s) (%s: %s)" % ("chassis", chassis_serial, "chassis", chassis_tag, "board", board_serial, "system", system_serial) # Clean up empty entries for k in list(dmidict.keys()): if dmidict[k] is None: del dmidict[k] # Finished return dmidict def get_hal_system_and_smbios(): try: if using_gudev: props = get_computer_info() else: computer = get_hal_computer() props = computer.GetAllProperties() except Exception: log = up2dateLog.initLog() msg = "Error reading system and smbios information: %s\n" % (sys.exc_info()[1]) log.log_debug(msg) return {} system_and_smbios = {} for key in props: if key.startswith('system'): system_and_smbios[ustr(key)] = ustr(props[key]) system_and_smbios.update(get_smbios()) return system_and_smbios def get_smbios(): """ Returns dictionary with values we are interested for. For historical reason it is in format, which use HAL. Currently in dictionary are keys: smbios.system.uuid, smbios.bios.vendor, smbios.system.serial, smbios.system.manufacturer. """ _initialize_dmi_data() if _dmi_not_available: return {} else: return { 'smbios.system.uuid': dmi_system_uuid(), 'smbios.bios.vendor': dmi_vendor(), 'smbios.system.serial': get_dmi_data('/dmidecode/SystemInfo/SerialNumber'), 'smbios.system.manufacturer': get_dmi_data('/dmidecode/SystemInfo/Manufacturer'), 'smbios.system.product': get_dmi_data('/dmidecode/SystemInfo/ProductName'), 'smbios.system.skunumber': get_dmi_data('/dmidecode/SystemInfo/SKUnumber'), 'smbios.system.family': get_dmi_data('/dmidecode/SystemInfo/Family'), 'smbios.system.version': get_dmi_data('/dmidecode/SystemInfo/Version'), } # this one reads it all def Hardware(): if using_gudev: allhw = get_devices() else: hal_status, dbus_status = check_hal_dbus_status() hwdaemon = 1 if hal_status or dbus_status: # if status != 0 haldaemon or messagebus service not running. # set flag and dont try probing hardware and DMI info # and warn the user. log = up2dateLog.initLog() msg = "Warning: haldaemon or messagebus service not running. Cannot probe hardware and DMI information.\n" log.log_me(msg) hwdaemon = 0 allhw = [] if hwdaemon: try: ret = read_hal() if ret: allhw = ret except: # bz253596 : Logging Dbus Error messages instead of printing on stdout log = up2dateLog.initLog() msg = "Error reading hardware information: %s\n" % (sys.exc_info()[0]) log.log_me(msg) # all others return individual arrays # cpu info try: ret = read_cpuinfo() if ret: allhw.append(ret) except: print(_("Error reading cpu information:"), sys.exc_info()[0]) # memory size info try: ret = read_memory() if ret: allhw.append(ret) except: print(_("Error reading system memory information:"), sys.exc_info()[0]) cfg = config.initUp2dateConfig() if not cfg["skipNetwork"]: # minimal networking info try: ret = read_network() if ret: allhw.append(ret) except: print(_("Error reading networking information:"), sys.exc_info()[0]) # dont like catchall exceptions but theres not # really anything useful we could do at this point # and its been trouble prone enough # minimal DMI info try: ret = read_dmi() if ret: allhw.append(ret) except: # bz253596 : Logging Dbus Error messages instead of printing on stdout log = up2dateLog.initLog() msg = "Error reading DMI information: %s\n" % (sys.exc_info()[0]) log.log_me(msg) try: ret = read_installinfo() if ret: allhw.append(ret) except: print(_("Error reading install method information:"), sys.exc_info()[0]) if not cfg["skipNetwork"]: try: ret = read_network_interfaces() if ret: allhw.append(ret) except: print(_("Error reading network interface information:"), sys.exc_info()[0]) # all Done. return allhw # XXX: Need more functions here: # - filesystems layout (/proc.mounts and /proc/mdstat) # - is the kudzu config enough or should we strat chasing lscpi and try to parse that # piece of crap output? # # Main program # if __name__ == '__main__': for hw in Hardware(): for k in hw.keys(): print("'%s' : '%s'" % (k, hw[k])) print
xkollar/spacewalk
client/rhel/rhn-client-tools/src/up2date_client/hardware.py
Python
gpl-2.0
29,568
from logger import log import os import gconf import urllib class Configuration(object): def __init__(self): self._config = {} self._file_path = os.path.join(os.path.dirname(__file__), 'config', 'config.ini') # Read Files self._read_file() def get_value(self, key): if key in self._config: log.debug("[Config] Getting Value for %s" % key) value = self._config[key] if value == "True": return True elif value == "False": return False return value else: return None def set_value(self, key, value): self._config[key] = value self._write_file() def _write_file(self): f = file(self._file_path, "wb") config_list = [("%s=%s\n" % (key, value)) for key, value in self._config.iteritems()] f.writelines(config_list) f.close() def _read_file(self): f = file(self._file_path, "rb") file_list = f.readlines() f.close() self._config = {} # reset config for line in file_list: line = line.strip() if len(line) > 0: name, value = line.split("=") value = value.strip() value = value.replace("[", "") value = value.replace("]", "") value = value.replace("'", "") if value.find(",") > -1: self.set_value(name, [v.strip() for v in value.split(',')]) else: self.set_value(name, value) log.info("[Config] Config Map = %s", self._config)
vbabiy/gedit-openfiles
gedit_openfiles/configuration.py
Python
gpl-2.0
1,698
from landscape.client.tests.helpers import LandscapeTest from landscape.client.patch import UpgradeManager from landscape.client.upgraders import monitor class TestMonitorUpgraders(LandscapeTest): def test_monitor_upgrade_manager(self): self.assertEqual(type(monitor.upgrade_manager), UpgradeManager)
CanonicalLtd/landscape-client
landscape/client/upgraders/tests/test_monitor.py
Python
gpl-2.0
317
# SecuML # Copyright (C) 2016 ANSSI # # SecuML 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. # # SecuML 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 SecuML. If not, see <http://www.gnu.org/licenses/>. from SecuML.core.DimensionReduction.Algorithms.Projection.Sdml import Sdml from SecuML.core.DimensionReduction.Configuration import DimensionReductionConfFactory from .SemiSupervisedProjectionConfiguration import SemiSupervisedProjectionConfiguration class SdmlConfiguration(SemiSupervisedProjectionConfiguration): def __init__(self, families_supervision=None): SemiSupervisedProjectionConfiguration.__init__( self, Sdml, families_supervision=families_supervision) @staticmethod def fromJson(obj): conf = SdmlConfiguration( families_supervision=obj['families_supervision']) conf.num_components = obj['num_components'] return conf def toJson(self): conf = SemiSupervisedProjectionConfiguration.toJson(self) conf['__type__'] = 'SdmlConfiguration' return conf DimensionReductionConfFactory.getFactory().registerClass('SdmlConfiguration', SdmlConfiguration)
ah-anssi/SecuML
SecuML/core/DimensionReduction/Configuration/Projection/SdmlConfiguration.py
Python
gpl-2.0
1,670
#!/usr/bin/env python3 # coding=utf-8 """ # fias2postgresql Импорт ФИАС (http://fias.nalog.ru) в PostgreSQL. Необходимы: * *python3.2+* с пакетами [requests](http://docs.python-requests.org/en/latest/), [lxml](http://lxml.de) * *unrar* * [*pgdbf*](https://github.com/kstrauser/pgdbf), обязательно с [патчем](https://github.com/kstrauser/pgdbf/commit/baa1d9579274a979aaf2f2d880f5ee566ddeb905). Версия 0.6.2, установленная через homebrew например не годится. [Здесь](https://github.com/bacilla-ru/pgdbf/archive/master.zip) поправленая версия под autotools 1.15. Запуск sql-скриптов производится посредством ``psql``. База данных и схема данных, в которую производится импорт, должны быть созданы предварительно. Использование: ```sh python3 fias.py -d your-db-name -s schema-in-db -u db-user ``` your-db-name - база данных (по умолчанию - fias) schema-in-db - схема данных (по умолчанию - public) db-user - пользователь базы данных Рабочие файлы создаются в текущем каталоге. Требуется ~9Gb свободного места. Скачаный rar-файл с файлами .dbf после работы не удаляется; также, .sql файлы, созданные в процессе работы, пакуются в отдельный файл. """ import argparse from os import path, listdir, rename, unlink import re import subprocess from textwrap import dedent import requests from lxml import etree def shell_cmd(info, cmd): print(info) if subprocess.call(cmd, shell=True) != 0: print('error') exit(1) def run(db, schema, username): data = dedent('''\ <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Body> <GetLastDownloadFileInfo xmlns="http://fias.nalog.ru/WebServices/Public/DownloadService.asmx" /> </soap12:Body> </soap12:Envelope> ''') headers = {'content-type': 'application/soap+xml; charset=utf-8'} resp = requests.post('http://fias.nalog.ru/WebServices/Public/DownloadService.asmx', data, headers=headers) tree = etree.fromstring(resp.content) version = tree.xpath('//fias:VersionId[1]/text()', namespaces={'fias': 'http://fias.nalog.ru/WebServices/Public/DownloadService.asmx'})[0] dbf_rar_url = tree.xpath('//fias:FiasCompleteDbfUrl[1]/text()', namespaces={'fias': 'http://fias.nalog.ru/WebServices/Public/DownloadService.asmx'})[0] dbf_rar_name = dbf_rar_url.rsplit('/', 1)[1] try: with open(dbf_rar_name + '.url', 'r') as url_file: last_dbf_url = url_file.read().strip() except FileNotFoundError: last_dbf_url = '' if last_dbf_url == dbf_rar_url: #print('using already downloaded [{}]'.format(dbf_rar_url)) print('no updates available') return shell_cmd('downloading [{}]...'.format(dbf_rar_url), 'curl -O {}'.format(dbf_rar_url)) shell_cmd('unpacking [{}]...'.format(dbf_rar_name), 'unrar x {}'.format(dbf_rar_name)) multi = {} for dbf in listdir('.'): f, ext = path.splitext(dbf) if ext == '.DBF': cmd = 'pgdbf -s cp866' dbt = f + '.DBT' if path.exists(dbt): cmd += ' -m ' + dbt sql = f.lower() + '.sql' if not path.exists(sql): if schema != 'public': with open(sql, 'w') as sql_file: sql_file.write('SET SCHEMA \'{}\';\n'.format(schema)) cmd += ' ' + dbf + ' >> ' + sql shell_cmd('executing [{}]...'.format(cmd), cmd) cmd = 'psql' if username != '-': cmd += ' -U ' + username cmd += ' {} < {}'.format(db, sql) shell_cmd('executing [{}]...'.format(cmd), cmd) m = re.match(r'^([A-Z]+)\d+', dbf) if m: multi.setdefault(m.group(1).lower(), []).append(f.lower()) sql_postprocess = '' if schema != 'public': sql_postprocess += 'SET SCHEMA \'{}\';\n'.format(schema) for table in iter(multi): sql_postprocess += 'drop table if exists {};\ncreate table {} as \n'.format(table, table) + '\n union all '.join( map(lambda t: 'select * from {}'.format(t), multi[table])) + ';\n' sql_postprocess += ''.join(map(lambda t: 'drop table {};\n'.format(t), multi[table])) sql_postprocess += dedent('''\ alter table addrobj add primary key(aoid); delete from addrobj where aoid in (select aoid from daddrobj); create index on addrobj(aoguid); drop table daddrobj; drop table if exists tmp_house_dup; create table tmp_house_dup as select distinct * from house where houseid in ( select houseid from house group by houseid having count(houseid) > 1); create index on tmp_house_dup(houseid); create index tmp_idx_house_houseid on house(houseid); delete from house where houseid in (select houseid from tmp_house_dup); insert into house select * from tmp_house_dup; drop table tmp_house_dup; drop index tmp_idx_house_houseid; alter table house add primary key(houseid); delete from house where houseid in (select houseid from dhouse); create index on house(aoguid); drop table dhouse; alter table houseint add primary key(houseintid); delete from houseint where houseintid in (select houseintid from dhousint); create index on houseint(aoguid); drop table dhousint; create table if not exists dlandmrk ( landid character varying(36) ); alter table landmark add primary key(landid); delete from landmark where landid in (select landid from dlandmrk); create index on landmark(aoguid); drop table dlandmrk; create index tmp_idx_nordoc_normdocid on nordoc(normdocid); create table tmp_nordoc_dup as select distinct * from nordoc where normdocid in ( select normdocid from nordoc group by normdocid having count(normdocid) > 1); delete from nordoc where normdocid in (select normdocid from tmp_nordoc_dup); insert into nordoc select * from tmp_nordoc_dup; drop index tmp_idx_nordoc_normdocid; drop table tmp_nordoc_dup; alter table nordoc add primary key(normdocid); delete from nordoc where normdocid in (select normdocid from dnordoc); drop table dnordoc; alter table ndoctype alter ndtypeid type int; alter table ndoctype add primary key(ndtypeid); ''') for table, col in ( ('actstat', 'actstatid'), ('centerst', 'centerstid'), ('curentst', 'curentstid'), ('eststat', 'eststatid'), ('hststat', 'housestid'), ('intvstat', 'intvstatid'), ('operstat', 'operstatid'), ('strstat', 'strstatid'), ): sql_postprocess += dedent('''\ alter table {} alter {} type numeric(2,0); alter table {} add primary key({}); '''.format(table, col, table, col)) postprocess_sql_file = '_postprocess.sql' with open(postprocess_sql_file, 'w') as sql_file: sql_file.write(sql_postprocess) cmd = 'psql -U {} {} < {}'.format(username, db, postprocess_sql_file) shell_cmd('postprocessing database...', cmd) shell_cmd('packing sql files...', 'tar cvzf fias_sql_v{}.tar.gz *.sql'.format(version)) f, ext = path.splitext(dbf_rar_name) rename(dbf_rar_name, '{}_v{}{}'.format(f, version, ext)) print('cleanup...') for file_name in listdir('.'): f, ext = path.splitext(file_name) if ext in ('.DBF', '.DBT', '.sql'): unlink(file_name) with open(dbf_rar_name + '.url', 'w') as url_file: url_file.write(dbf_rar_url) print('success.') parser = argparse.ArgumentParser(description='Import FIAS DB (http://fias.nalog.ru) into PostgreSQL database.') parser.add_argument('-d', dest='db', type=str, default='fias', help='database (default: fias)') parser.add_argument('-s', dest='schema', type=str, default='public', help='schema (default: public)') parser.add_argument('-u', dest='username', type=str, default='-', help='user') args = parser.parse_args() run(args.db, args.schema, args.username)
bacilla-ru/fias2postgresql
fias.py
Python
gpl-2.0
8,843
# Copyright (C) 2008, Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 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 St, Fifth Floor, Boston, MA 02110-1301 USA from gi.repository import Gtk import dbus import os import signal import sys import logging from sugar3 import session from sugar3 import env _session_manager = None def have_systemd(): return os.access("/run/systemd/seats", 0) >= 0 class SessionManager(session.SessionManager): MODE_LOGOUT = 0 MODE_SHUTDOWN = 1 MODE_REBOOT = 2 def __init__(self): session.SessionManager.__init__(self) self._logout_mode = None def logout(self): self._logout_mode = self.MODE_LOGOUT self.initiate_shutdown() def shutdown(self): self._logout_mode = self.MODE_SHUTDOWN self.initiate_shutdown() def reboot(self): self._logout_mode = self.MODE_REBOOT self.initiate_shutdown() def shutdown_completed(self): if env.is_emulator(): self._close_emulator() elif self._logout_mode != self.MODE_LOGOUT: bus = dbus.SystemBus() if have_systemd(): try: proxy = bus.get_object('org.freedesktop.login1', '/org/freedesktop/login1') pm = dbus.Interface(proxy, 'org.freedesktop.login1.Manager') if self._logout_mode == self.MODE_SHUTDOWN: pm.PowerOff(False) elif self._logout_mode == self.MODE_REBOOT: pm.Reboot(True) except: logging.exception('Can not stop sugar') self.session.cancel_shutdown() return else: CONSOLEKIT_DBUS_PATH = '/org/freedesktop/ConsoleKit/Manager' try: proxy = bus.get_object('org.freedesktop.ConsoleKit', CONSOLEKIT_DBUS_PATH) pm = dbus.Interface(proxy, 'org.freedesktop.ConsoleKit.Manager') if self._logout_mode == self.MODE_SHUTDOWN: pm.Stop() elif self._logout_mode == self.MODE_REBOOT: pm.Restart() except: logging.exception('Can not stop sugar') self.session.cancel_shutdown() return session.SessionManager.shutdown_completed(self) Gtk.main_quit() def _close_emulator(self): Gtk.main_quit() if 'SUGAR_EMULATOR_PID' in os.environ: pid = int(os.environ['SUGAR_EMULATOR_PID']) os.kill(pid, signal.SIGTERM) # Need to call this ASAP so the atexit handlers get called before we # get killed by the X (dis)connection sys.exit() def get_session_manager(): global _session_manager if _session_manager == None: _session_manager = SessionManager() return _session_manager
ajaygarg84/sugar
src/jarabe/model/session.py
Python
gpl-2.0
3,705
from picamera.exc import PiCameraError from picamera.camera import PiCamera
CoderBotOrg/coderbot
stub/picamera/__init__.py
Python
gpl-2.0
77
# encoding: utf-8 # module PyKDE4.kdeui # from /usr/lib/python3/dist-packages/PyKDE4/kdeui.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc # imports import PyKDE4.kdecore as __PyKDE4_kdecore import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.QtGui as __PyQt4_QtGui import PyQt4.QtSvg as __PyQt4_QtSvg from .int import int class KColorChooserMode(int): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass __dict__ = None # (!) real value is ''
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247971765/PyKDE4/kdeui/KColorChooserMode.py
Python
gpl-2.0
508
""" OpenStreetMap boundary generator. Author: Andrzej Talarczyk <andrzej@talarczyk.com> Based on work of Michał Rogalski (Rogal). License: GPLv3. """ import os import platform import shutil def clean(src_dir): """Remove target files. Args: src_dir (string): path to the directory from which target files will be removed """ if os.path.isfile("{dane_osm}/poland.o5m".format(dane_osm=src_dir)): os.remove("{dane_osm}/poland.o5m".format(dane_osm=src_dir)) if os.path.isfile("{dane_osm}/poland-boundaries.osm".format(dane_osm=src_dir)): os.remove("{dane_osm}/poland-boundaries.osm".format(dane_osm=src_dir)) if os.path.exists("{dane_osm}/bounds".format(dane_osm=src_dir)): shutil.rmtree("{dane_osm}/bounds".format(dane_osm=src_dir)) def generate(bin_dir, src_dir, pbf_filename) -> int: """Generates boundaries. Args: bin_dir (string): path to a directory holding compilation tools src_dir (string): path to a directory with source data pbf_filename (string): source PBF file Raises: Exception: [description] Returns: int: 0 if succes. """ ret = -1 if platform.system() == 'Windows': ret = os.system("start /low /b /wait {binarki}/osmconvert.exe {dane_osm}/{pbf_filename} --out-o5m >{dane_osm}/poland.o5m".format( binarki=bin_dir, dane_osm=src_dir, pbf_filename=pbf_filename)) ret = os.system("start /low /b /wait {binarki}/osmfilter.exe {dane_osm}/poland.o5m --keep-nodes= --keep-ways-relations=\"boundary=administrative =postal_code postal_code=\" >{dane_osm}/poland-boundaries.osm".format( dane_osm=src_dir, binarki=bin_dir)) ret = os.system("start /low /b /wait java -cp {binarki}/mkgmap.jar uk.me.parabola.mkgmap.reader.osm.boundary.BoundaryPreprocessor {dane_osm}/poland-boundaries.osm {dane_osm}/bounds".format( binarki=bin_dir, dane_osm=src_dir)) elif platform.system() == 'Linux': ret = os.system("osmconvert {dane_osm}/{pbf_filename} --out-o5m >{dane_osm}/poland.o5m".format( dane_osm=src_dir, pbf_filename=pbf_filename)) ret = os.system("osmfilter {dane_osm}/poland.o5m --keep-nodes= --keep-ways-relations=\"boundary=administrative =postal_code postal_code=\" >{dane_osm}/poland-boundaries.osm".format( dane_osm=src_dir)) ret = os.system("java -cp {binarki}/mkgmap.jar uk.me.parabola.mkgmap.reader.osm.boundary.BoundaryPreprocessor {dane_osm}/poland-boundaries.osm {dane_osm}/bounds".format( binarki=bin_dir, dane_osm=src_dir)) else: raise Exception("Unsupported operating system.") return ret
basement-labs/osmapa-garmin
osmapa/boundaries.py
Python
gpl-2.0
2,693
from filetypes.basefile import BaseFile from filetypes.plainfile import PlainFile from filetypes.plainfile import ReviewTest import filetypes class JFLAPReviewTest(ReviewTest): def __init__(self, dict_, file_type): super().__init__(dict_, file_type) def run(self, path): """A JFLAP review test calls the ReviewTest run() method but suppresses printing the file. """ return super().run(path, False) class JFLAPFile(PlainFile): yaml_type = 'jflap' extensions = ['jff'] supported_tests = PlainFile.supported_tests.copy() supported_tests.append(JFLAPReviewTest) def __init__(self, dict_): BaseFile.__init__(self, dict_) if 'tests' in dict_: for t in dict_['tests']: test_cls = filetypes.find_test_class(JFLAPFile.yaml_type, t['type']) self.tests.append(test_cls(t, JFLAPFile.yaml_type)) def run_tests(self): results = [] for t in self.tests: result = t.run(self.path) if result: if type(result) is list: for r in result: results.append(r) else: results.append(result) return results def __str__(self): return self.path + " (JFLAP file)"
abreen/socrates.py
filetypes/jflapfile.py
Python
gpl-2.0
1,386
# # test_tracking_events.py # # Copyright (C) 2017 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # # Unit tests for functions related to tracking events: # `kano_profile.tracker.tracking_events` # import os import json import time import pytest from kano_profile.paths import tracker_events_file import kano_profile.tracker.tracking_events as tracking_events from kano_profile.tracker.tracker_token import TOKEN @pytest.mark.parametrize('event_name, event_type, event_data', [ ('low-battery', 'battery', '{"status": "low-charge"}'), ('auto-poweroff', 'battery', '{"status": "automatic-poweroff"}') ]) def test_generate_low_battery_event(event_name, event_type, event_data): if os.path.exists(tracker_events_file): os.remove(tracker_events_file) tracking_events.generate_event(event_name) assert os.path.exists(tracker_events_file) events = [] with open(tracker_events_file, 'r') as events_f: events.append(json.loads(events_f.readline())) assert len(events) == 1 event = events[0] expected_keys = [ 'name', 'language', 'type', 'timezone_offset', 'cpu_id', 'os_version', 'token', 'time', 'data' ] for key in expected_keys: assert key in event assert event['name'] == event_type # language: en_GB, assert event['type'] == 'data' # timezone_offset: 3600, # cpu_id: None, # os_version: None, assert event['token'] == TOKEN # Allow some margin for time passing assert abs(time.time() - event['time']) < 5 assert event['data'] == json.loads(event_data)
KanoComputing/kano-profile
tests/profile/tracking/test_tracking_events.py
Python
gpl-2.0
1,689
from Tools.HardwareInfo import HardwareInfo from Tools.BoundFunction import boundFunction from config import config, ConfigSubsection, ConfigSelection, ConfigFloat, \ ConfigSatlist, ConfigYesNo, ConfigInteger, ConfigSubList, ConfigNothing, \ ConfigSubDict, ConfigOnOff, ConfigDateTime from enigma import eDVBSatelliteEquipmentControl as secClass, \ eDVBSatelliteLNBParameters as lnbParam, \ eDVBSatelliteDiseqcParameters as diseqcParam, \ eDVBSatelliteSwitchParameters as switchParam, \ eDVBSatelliteRotorParameters as rotorParam, \ eDVBResourceManager, eDVBDB, eEnv from time import localtime, mktime from datetime import datetime from Tools.BoundFunction import boundFunction from Tools import Directories import xml.etree.cElementTree def getConfigSatlist(orbpos, satlist): default_orbpos = None for x in satlist: if x[0] == orbpos: default_orbpos = orbpos break return ConfigSatlist(satlist, default_orbpos) class SecConfigure: def getConfiguredSats(self): return self.configuredSatellites def addSatellite(self, sec, orbpos): sec.addSatellite(orbpos) self.configuredSatellites.add(orbpos) def addLNBSimple(self, sec, slotid, diseqcmode, toneburstmode = diseqcParam.NO, diseqcpos = diseqcParam.SENDNO, orbpos = 0, longitude = 0, latitude = 0, loDirection = 0, laDirection = 0, turningSpeed = rotorParam.FAST, useInputPower=True, inputPowerDelta=50, fastDiSEqC = False, setVoltageTone = True, diseqc13V = False): if orbpos is None or orbpos == 3600 or orbpos == 3601: return #simple defaults sec.addLNB() tunermask = 1 << slotid if self.equal.has_key(slotid): for slot in self.equal[slotid]: tunermask |= (1 << slot) if self.linked.has_key(slotid): for slot in self.linked[slotid]: tunermask |= (1 << slot) sec.setLNBSatCR(-1) sec.setLNBNum(1) sec.setLNBLOFL(9750000) sec.setLNBLOFH(10600000) sec.setLNBThreshold(11700000) sec.setLNBIncreasedVoltage(lnbParam.OFF) sec.setRepeats(0) sec.setFastDiSEqC(fastDiSEqC) sec.setSeqRepeat(0) sec.setCommandOrder(0) #user values sec.setDiSEqCMode(diseqcmode) sec.setToneburst(toneburstmode) sec.setCommittedCommand(diseqcpos) sec.setUncommittedCommand(0) # SENDNO #print "set orbpos to:" + str(orbpos) if 0 <= diseqcmode < 3: self.addSatellite(sec, orbpos) if setVoltageTone: if diseqc13V: sec.setVoltageMode(switchParam.HV_13) else: sec.setVoltageMode(switchParam.HV) sec.setToneMode(switchParam.HILO) else: sec.setVoltageMode(switchParam._14V) sec.setToneMode(switchParam.OFF) elif (diseqcmode == 3): # diseqc 1.2 if self.satposdepends.has_key(slotid): for slot in self.satposdepends[slotid]: tunermask |= (1 << slot) sec.setLatitude(latitude) sec.setLaDirection(laDirection) sec.setLongitude(longitude) sec.setLoDirection(loDirection) sec.setUseInputpower(useInputPower) sec.setInputpowerDelta(inputPowerDelta) sec.setRotorTurningSpeed(turningSpeed) for x in self.NimManager.satList: print "Add sat " + str(x[0]) self.addSatellite(sec, int(x[0])) if diseqc13V: sec.setVoltageMode(switchParam.HV_13) else: sec.setVoltageMode(switchParam.HV) sec.setToneMode(switchParam.HILO) sec.setRotorPosNum(0) # USALS sec.setLNBSlotMask(tunermask) def setSatposDepends(self, sec, nim1, nim2): print "tuner", nim1, "depends on satpos of", nim2 sec.setTunerDepends(nim1, nim2) def linkInternally(self, slotid): nim = self.NimManager.getNim(slotid) if nim.internallyConnectableTo is not None: nim.setInternalLink() def linkNIMs(self, sec, nim1, nim2): print "link tuner", nim1, "to tuner", nim2 if nim2 == (nim1 - 1): self.linkInternally(nim1) sec.setTunerLinked(nim1, nim2) def getRoot(self, slotid, connto): visited = [] while (self.NimManager.getNimConfig(connto).configMode.value in ("satposdepends", "equal", "loopthrough")): connto = int(self.NimManager.getNimConfig(connto).connectedTo.value) if connto in visited: # prevent endless loop return slotid visited.append(connto) return connto def update(self): sec = secClass.getInstance() self.configuredSatellites = set() for slotid in self.NimManager.getNimListOfType("DVB-S"): if self.NimManager.nimInternallyConnectableTo(slotid) is not None: self.NimManager.nimRemoveInternalLink(slotid) sec.clear() ## this do unlinking NIMs too !! print "sec config cleared" self.linked = { } self.satposdepends = { } self.equal = { } nim_slots = self.NimManager.nim_slots used_nim_slots = [ ] for slot in nim_slots: if slot.type is not None: used_nim_slots.append((slot.slot, slot.description, slot.config.configMode.value != "nothing" and True or False, slot.isCompatible("DVB-S2"), slot.frontend_id is None and -1 or slot.frontend_id)) eDVBResourceManager.getInstance().setFrontendSlotInformations(used_nim_slots) for slot in nim_slots: if slot.frontend_id is not None: types = [type for type in ["DVB-T", "DVB-C", "DVB-S", "ATSC"] if eDVBResourceManager.getInstance().frontendIsCompatible(slot.frontend_id, type)] if len(types) > 1: slot.multi_type = {} for type in types: slot.multi_type[str(types.index(type))] = type for slot in nim_slots: x = slot.slot nim = slot.config if slot.isCompatible("DVB-S"): # save what nim we link to/are equal to/satposdepends to. # this is stored in the *value* (not index!) of the config list if nim.configMode.value == "equal": connto = self.getRoot(x, int(nim.connectedTo.value)) if not self.equal.has_key(connto): self.equal[connto] = [] self.equal[connto].append(x) elif nim.configMode.value == "loopthrough": self.linkNIMs(sec, x, int(nim.connectedTo.value)) connto = self.getRoot(x, int(nim.connectedTo.value)) if not self.linked.has_key(connto): self.linked[connto] = [] self.linked[connto].append(x) elif nim.configMode.value == "satposdepends": self.setSatposDepends(sec, x, int(nim.connectedTo.value)) connto = self.getRoot(x, int(nim.connectedTo.value)) if not self.satposdepends.has_key(connto): self.satposdepends[connto] = [] self.satposdepends[connto].append(x) for slot in nim_slots: x = slot.slot nim = slot.config hw = HardwareInfo() if slot.isCompatible("DVB-S"): print "slot: " + str(x) + " configmode: " + str(nim.configMode.value) if nim.configMode.value in ( "loopthrough", "satposdepends", "nothing" ): pass else: sec.setSlotNotLinked(x) if nim.configMode.value == "equal": pass elif nim.configMode.value == "simple": #simple config print "diseqcmode: ", nim.diseqcMode.value if nim.diseqcMode.value == "single": #single if nim.simpleSingleSendDiSEqC.value: self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA, diseqc13V = nim.diseqc13V.value) else: self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.NONE, diseqcpos = diseqcParam.SENDNO, diseqc13V = nim.diseqc13V.value) elif nim.diseqcMode.value == "toneburst_a_b": #Toneburst A/B self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.A, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.SENDNO, diseqc13V = nim.diseqc13V.value) self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.B, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.SENDNO, diseqc13V = nim.diseqc13V.value) elif nim.diseqcMode.value == "diseqc_a_b": #DiSEqC A/B fastDiSEqC = nim.simpleDiSEqCOnlyOnSatChange.value setVoltageTone = nim.simpleDiSEqCSetVoltageTone.value self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value) self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AB, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value) elif nim.diseqcMode.value == "diseqc_a_b_c_d": #DiSEqC A/B/C/D fastDiSEqC = nim.simpleDiSEqCOnlyOnSatChange.value setVoltageTone = nim.simpleDiSEqCSetVoltageTone.value self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value) self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AB, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value) self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcC.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.BA, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value) self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcD.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.BB, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value) elif nim.diseqcMode.value == "positioner": #Positioner if nim.latitudeOrientation.value == "north": laValue = rotorParam.NORTH else: laValue = rotorParam.SOUTH if nim.longitudeOrientation.value == "east": loValue = rotorParam.EAST else: loValue = rotorParam.WEST inputPowerDelta=nim.powerThreshold.value useInputPower=False turning_speed=0 if nim.powerMeasurement.value: useInputPower=True turn_speed_dict = { "fast": rotorParam.FAST, "slow": rotorParam.SLOW } if turn_speed_dict.has_key(nim.turningSpeed.value): turning_speed = turn_speed_dict[nim.turningSpeed.value] else: beg_time = localtime(nim.fastTurningBegin.value) end_time = localtime(nim.fastTurningEnd.value) turning_speed = ((beg_time.tm_hour+1) * 60 + beg_time.tm_min + 1) << 16 turning_speed |= (end_time.tm_hour+1) * 60 + end_time.tm_min + 1 self.addLNBSimple(sec, slotid = x, diseqcmode = 3, longitude = nim.longitude.float, loDirection = loValue, latitude = nim.latitude.float, laDirection = laValue, turningSpeed = turning_speed, useInputPower = useInputPower, inputPowerDelta = inputPowerDelta, diseqc13V = nim.diseqc13V.value) elif nim.configMode.value == "advanced": #advanced config self.updateAdvanced(sec, x) print "sec config completed" def updateAdvanced(self, sec, slotid): try: if config.Nims[slotid].advanced.unicableconnected is not None: if config.Nims[slotid].advanced.unicableconnected.value == True: config.Nims[slotid].advanced.unicableconnectedTo.save_forced = True self.linkNIMs(sec, slotid, int(config.Nims[slotid].advanced.unicableconnectedTo.value)) connto = self.getRoot(slotid, int(config.Nims[slotid].advanced.unicableconnectedTo.value)) if not self.linked.has_key(connto): self.linked[connto] = [] self.linked[connto].append(slotid) else: config.Nims[slotid].advanced.unicableconnectedTo.save_forced = False except: pass lnbSat = {} for x in range(1,37): lnbSat[x] = [] #wildcard for all satellites ( for rotor ) for x in range(3601, 3605): lnb = int(config.Nims[slotid].advanced.sat[x].lnb.value) if lnb != 0: for x in self.NimManager.satList: print "add", x[0], "to", lnb lnbSat[lnb].append(x[0]) for x in self.NimManager.satList: lnb = int(config.Nims[slotid].advanced.sat[x[0]].lnb.value) if lnb != 0: print "add", x[0], "to", lnb lnbSat[lnb].append(x[0]) for x in range(1,37): if len(lnbSat[x]) > 0: currLnb = config.Nims[slotid].advanced.lnb[x] sec.addLNB() if x < 33: sec.setLNBNum(x) tunermask = 1 << slotid if self.equal.has_key(slotid): for slot in self.equal[slotid]: tunermask |= (1 << slot) if self.linked.has_key(slotid): for slot in self.linked[slotid]: tunermask |= (1 << slot) if currLnb.lof.value != "unicable": sec.setLNBSatCR(-1) if currLnb.lof.value == "universal_lnb": sec.setLNBLOFL(9750000) sec.setLNBLOFH(10600000) sec.setLNBThreshold(11700000) elif currLnb.lof.value == "unicable": def setupUnicable(configManufacturer, ProductDict): manufacturer_name = configManufacturer.value manufacturer = ProductDict[manufacturer_name] product_name = manufacturer.product.value sec.setLNBSatCR(manufacturer.scr[product_name].index) sec.setLNBSatCRvco(manufacturer.vco[product_name][manufacturer.scr[product_name].index].value*1000) sec.setLNBSatCRpositions(manufacturer.positions[product_name][0].value) sec.setLNBLOFL(manufacturer.lofl[product_name][0].value * 1000) sec.setLNBLOFH(manufacturer.lofh[product_name][0].value * 1000) sec.setLNBThreshold(manufacturer.loft[product_name][0].value * 1000) configManufacturer.save_forced = True manufacturer.product.save_forced = True manufacturer.vco[product_name][manufacturer.scr[product_name].index].save_forced = True if currLnb.unicable.value == "unicable_user": #TODO satpositions for satcruser sec.setLNBLOFL(currLnb.lofl.value * 1000) sec.setLNBLOFH(currLnb.lofh.value * 1000) sec.setLNBThreshold(currLnb.threshold.value * 1000) sec.setLNBSatCR(currLnb.satcruser.index) sec.setLNBSatCRvco(currLnb.satcrvcouser[currLnb.satcruser.index].value*1000) sec.setLNBSatCRpositions(1) #HACK elif currLnb.unicable.value == "unicable_matrix": setupUnicable(currLnb.unicableMatrixManufacturer, currLnb.unicableMatrix) elif currLnb.unicable.value == "unicable_lnb": setupUnicable(currLnb.unicableLnbManufacturer, currLnb.unicableLnb) elif currLnb.lof.value == "c_band": sec.setLNBLOFL(5150000) sec.setLNBLOFH(5150000) sec.setLNBThreshold(5150000) elif currLnb.lof.value == "user_defined": sec.setLNBLOFL(currLnb.lofl.value * 1000) sec.setLNBLOFH(currLnb.lofh.value * 1000) sec.setLNBThreshold(currLnb.threshold.value * 1000) # if currLnb.output_12v.value == "0V": # pass # nyi in drivers # elif currLnb.output_12v.value == "12V": # pass # nyi in drivers if currLnb.increased_voltage.value: sec.setLNBIncreasedVoltage(lnbParam.ON) else: sec.setLNBIncreasedVoltage(lnbParam.OFF) dm = currLnb.diseqcMode.value if dm == "none": sec.setDiSEqCMode(diseqcParam.NONE) elif dm == "1_0": sec.setDiSEqCMode(diseqcParam.V1_0) elif dm == "1_1": sec.setDiSEqCMode(diseqcParam.V1_1) elif dm == "1_2": sec.setDiSEqCMode(diseqcParam.V1_2) if self.satposdepends.has_key(slotid): for slot in self.satposdepends[slotid]: tunermask |= (1 << slot) if dm != "none": if currLnb.toneburst.value == "none": sec.setToneburst(diseqcParam.NO) elif currLnb.toneburst.value == "A": sec.setToneburst(diseqcParam.A) elif currLnb.toneburst.value == "B": sec.setToneburst(diseqcParam.B) # Committed Diseqc Command cdc = currLnb.commitedDiseqcCommand.value c = { "none": diseqcParam.SENDNO, "AA": diseqcParam.AA, "AB": diseqcParam.AB, "BA": diseqcParam.BA, "BB": diseqcParam.BB } if c.has_key(cdc): sec.setCommittedCommand(c[cdc]) else: sec.setCommittedCommand(long(cdc)) sec.setFastDiSEqC(currLnb.fastDiseqc.value) sec.setSeqRepeat(currLnb.sequenceRepeat.value) if currLnb.diseqcMode.value == "1_0": currCO = currLnb.commandOrder1_0.value sec.setRepeats(0) else: currCO = currLnb.commandOrder.value udc = int(currLnb.uncommittedDiseqcCommand.value) if udc > 0: sec.setUncommittedCommand(0xF0|(udc-1)) else: sec.setUncommittedCommand(0) # SENDNO sec.setRepeats({"none": 0, "one": 1, "two": 2, "three": 3}[currLnb.diseqcRepeats.value]) setCommandOrder = False # 0 "committed, toneburst", # 1 "toneburst, committed", # 2 "committed, uncommitted, toneburst", # 3 "toneburst, committed, uncommitted", # 4 "uncommitted, committed, toneburst" # 5 "toneburst, uncommitted, commmitted" order_map = {"ct": 0, "tc": 1, "cut": 2, "tcu": 3, "uct": 4, "tuc": 5} sec.setCommandOrder(order_map[currCO]) if dm == "1_2": latitude = currLnb.latitude.float sec.setLatitude(latitude) longitude = currLnb.longitude.float sec.setLongitude(longitude) if currLnb.latitudeOrientation.value == "north": sec.setLaDirection(rotorParam.NORTH) else: sec.setLaDirection(rotorParam.SOUTH) if currLnb.longitudeOrientation.value == "east": sec.setLoDirection(rotorParam.EAST) else: sec.setLoDirection(rotorParam.WEST) if currLnb.powerMeasurement.value: sec.setUseInputpower(True) sec.setInputpowerDelta(currLnb.powerThreshold.value) turn_speed_dict = { "fast": rotorParam.FAST, "slow": rotorParam.SLOW } if turn_speed_dict.has_key(currLnb.turningSpeed.value): turning_speed = turn_speed_dict[currLnb.turningSpeed.value] else: beg_time = localtime(currLnb.fastTurningBegin.value) end_time = localtime(currLnb.fastTurningEnd.value) turning_speed = ((beg_time.tm_hour + 1) * 60 + beg_time.tm_min + 1) << 16 turning_speed |= (end_time.tm_hour + 1) * 60 + end_time.tm_min + 1 sec.setRotorTurningSpeed(turning_speed) else: sec.setUseInputpower(False) sec.setLNBSlotMask(tunermask) sec.setLNBPrio(int(currLnb.prio.value)) # finally add the orbital positions for y in lnbSat[x]: self.addSatellite(sec, y) if x > 32: satpos = x > 32 and (3604-(36 - x)) or y else: satpos = y currSat = config.Nims[slotid].advanced.sat[satpos] if currSat.voltage.value == "polarization": if config.Nims[slotid].diseqc13V.value: sec.setVoltageMode(switchParam.HV_13) else: sec.setVoltageMode(switchParam.HV) elif currSat.voltage.value == "13V": sec.setVoltageMode(switchParam._14V) elif currSat.voltage.value == "18V": sec.setVoltageMode(switchParam._18V) if currSat.tonemode.value == "band": sec.setToneMode(switchParam.HILO) elif currSat.tonemode.value == "on": sec.setToneMode(switchParam.ON) elif currSat.tonemode.value == "off": sec.setToneMode(switchParam.OFF) if not currSat.usals.value and x < 34: sec.setRotorPosNum(currSat.rotorposition.value) else: sec.setRotorPosNum(0) #USALS def __init__(self, nimmgr): self.NimManager = nimmgr self.configuredSatellites = set() self.update() class NIM(object): def __init__(self, slot, type, description, has_outputs = True, internally_connectable = None, multi_type = {}, frontend_id = None, i2c = None, is_empty = False): self.slot = slot if type not in ("DVB-S", "DVB-C", "DVB-T", "DVB-S2", "DVB-T2", "DVB-C2", "ATSC", None): print "warning: unknown NIM type %s, not using." % type type = None self.type = type self.description = description self.has_outputs = has_outputs self.internally_connectable = internally_connectable self.multi_type = multi_type self.i2c = i2c self.frontend_id = frontend_id self.__is_empty = is_empty self.compatible = { None: (None,), "DVB-S": ("DVB-S", None), "DVB-C": ("DVB-C", None), "DVB-T": ("DVB-T", None), "DVB-S2": ("DVB-S", "DVB-S2", None), "DVB-C2": ("DVB-C", "DVB-C2", None), "DVB-T2": ("DVB-T", "DVB-T2", None), "ATSC": ("ATSC", None), } def isCompatible(self, what): if not self.isSupported(): return False return what in self.compatible[self.getType()] def canBeCompatible(self, what): if not self.isSupported(): return False if self.isCompatible(what): return True for type in self.multi_type.values(): if what in self.compatible[type]: return True return False def getType(self): try: if self.isMultiType(): return self.multi_type[self.config.multiType.value] except: pass return self.type def connectableTo(self): connectable = { "DVB-S": ("DVB-S", "DVB-S2"), "DVB-C": ("DVB-C", "DVB-C2"), "DVB-T": ("DVB-T","DVB-T2"), "DVB-S2": ("DVB-S", "DVB-S2"), "DVB-C2": ("DVB-C", "DVB-C2"), "DVB-T2": ("DVB-T", "DVB-T2"), "ATSC": ("ATSC"), } return connectable[self.getType()] def getSlotName(self): # get a friendly description for a slot name. # we name them "Tuner A/B/C/...", because that's what's usually written on the back # of the device. return _("Tuner") + " " + chr(ord('A') + self.slot) slot_name = property(getSlotName) def getSlotID(self): return chr(ord('A') + self.slot) def getI2C(self): return self.i2c def hasOutputs(self): return self.has_outputs def internallyConnectableTo(self): return self.internally_connectable def setInternalLink(self): if self.internally_connectable is not None: print "setting internal link on frontend id", self.frontend_id open("/proc/stb/frontend/%d/rf_switch" % self.frontend_id, "w").write("internal") def removeInternalLink(self): if self.internally_connectable is not None: print "removing internal link on frontend id", self.frontend_id open("/proc/stb/frontend/%d/rf_switch" % self.frontend_id, "w").write("external") def isMultiType(self): return (len(self.multi_type) > 0) def isEmpty(self): return self.__is_empty # empty tuners are supported! def isSupported(self): return (self.frontend_id is not None) or self.__is_empty # returns dict {<slotid>: <type>} def getMultiTypeList(self): return self.multi_type slot_id = property(getSlotID) def getFriendlyType(self): return { "DVB-S": "DVB-S", "DVB-T": "DVB-T", "DVB-C": "DVB-C", "DVB-S2": "DVB-S2", "DVB-T2": "DVB-T2", "DVB-C2": "DVB-C2", "ATSC": "ATSC", None: _("empty") }[self.getType()] friendly_type = property(getFriendlyType) def getFriendlyFullDescription(self): nim_text = self.slot_name + ": " if self.empty: nim_text += _("(empty)") elif not self.isSupported(): nim_text += self.description + " (" + _("not supported") + ")" else: nim_text += self.description + " (" + self.friendly_type + ")" return nim_text friendly_full_description = property(getFriendlyFullDescription) config_mode = property(lambda self: config.Nims[self.slot].configMode.value) config = property(lambda self: config.Nims[self.slot]) empty = property(lambda self: self.getType is None) class NimManager: def getConfiguredSats(self): return self.sec.getConfiguredSats() def getTransponders(self, pos): if self.transponders.has_key(pos): return self.transponders[pos] else: return [] def getTranspondersCable(self, nim): nimConfig = config.Nims[nim] if nimConfig.configMode.value != "nothing" and nimConfig.cable.scan_type.value == "provider": return self.transponderscable[self.cablesList[nimConfig.cable.scan_provider.index][0]] return [ ] def getTranspondersTerrestrial(self, region): return self.transpondersterrestrial[region] def getCableDescription(self, nim): return self.cablesList[config.Nims[nim].scan_provider.index][0] def getCableFlags(self, nim): return self.cablesList[config.Nims[nim].scan_provider.index][1] def getTerrestrialDescription(self, nim): return self.terrestrialsList[config.Nims[nim].terrestrial.index][0] def getTerrestrialFlags(self, nim): return self.terrestrialsList[config.Nims[nim].terrestrial.index][1] def getSatDescription(self, pos): return self.satellites[pos] def sortFunc(self, x): orbpos = x[0] if orbpos > 1800: return orbpos - 3600 else: return orbpos + 1800 def readTransponders(self): # read initial networks from file. we only read files which we are interested in, # which means only these where a compatible tuner exists. self.satellites = { } self.transponders = { } self.transponderscable = { } self.transpondersterrestrial = { } self.transpondersatsc = { } db = eDVBDB.getInstance() if self.hasNimType("DVB-S"): print "Reading satellites.xml" db.readSatellites(self.satList, self.satellites, self.transponders) self.satList.sort() # sort by orbpos #print "SATLIST", self.satList #print "SATS", self.satellites #print "TRANSPONDERS", self.transponders if self.hasNimType("DVB-C"): print "Reading cables.xml" db.readCables(self.cablesList, self.transponderscable) # print "CABLIST", self.cablesList # print "TRANSPONDERS", self.transponders if self.hasNimType("DVB-T"): print "Reading terrestrial.xml" db.readTerrestrials(self.terrestrialsList, self.transpondersterrestrial) # print "TERLIST", self.terrestrialsList # print "TRANSPONDERS", self.transpondersterrestrial if self.hasNimType("ATSC"): print "Reading atsc.xml" #db.readATSC(self.atscList, self.transpondersatsc) def enumerateNIMs(self): # enum available NIMs. This is currently very dreambox-centric and uses the /proc/bus/nim_sockets interface. # the result will be stored into nim_slots. # the content of /proc/bus/nim_sockets looks like: # NIM Socket 0: # Type: DVB-S # Name: BCM4501 DVB-S2 NIM (internal) # NIM Socket 1: # Type: DVB-S # Name: BCM4501 DVB-S2 NIM (internal) # NIM Socket 2: # Type: DVB-T # Name: Philips TU1216 # NIM Socket 3: # Type: DVB-S # Name: Alps BSBE1 702A # # Type will be either "DVB-S", "DVB-S2", "DVB-T", "DVB-C" or None. # nim_slots is an array which has exactly one entry for each slot, even for empty ones. self.nim_slots = [ ] try: nimfile = open("/proc/bus/nim_sockets") except IOError: return current_slot = None entries = {} for line in nimfile: if not line: break line = line.strip() if line.startswith("NIM Socket"): parts = line.split(" ") current_slot = int(parts[2][:-1]) entries[current_slot] = {} elif line.startswith("Type:"): entries[current_slot]["type"] = str(line[6:]) entries[current_slot]["isempty"] = False elif line.startswith("Name:"): entries[current_slot]["name"] = str(line[6:]) entries[current_slot]["isempty"] = False elif line.startswith("Has_Outputs:"): input = str(line[len("Has_Outputs:") + 1:]) entries[current_slot]["has_outputs"] = (input == "yes") elif line.startswith("Internally_Connectable:"): input = int(line[len("Internally_Connectable:") + 1:]) entries[current_slot]["internally_connectable"] = input elif line.startswith("Frontend_Device:"): input = int(line[len("Frontend_Device:") + 1:]) entries[current_slot]["frontend_device"] = input elif line.startswith("Mode"): # "Mode 0: DVB-T" -> ["Mode 0", "DVB-T"] split = line.split(": ") if len(split) > 1 and split[1]: # "Mode 0" -> ["Mode", "0"] split2 = split[0].split(" ") modes = entries[current_slot].get("multi_type", {}) modes[split2[1]] = split[1] entries[current_slot]["multi_type"] = modes elif line.startswith("I2C_Device:"): input = int(line[len("I2C_Device:") + 1:]) entries[current_slot]["i2c"] = input elif line.startswith("empty"): entries[current_slot]["type"] = None entries[current_slot]["name"] = _("N/A") entries[current_slot]["isempty"] = True nimfile.close() from os import path for id, entry in entries.items(): if not (entry.has_key("name") and entry.has_key("type")): entry["name"] = _("N/A") entry["type"] = None if not (entry.has_key("i2c")): entry["i2c"] = None if not (entry.has_key("has_outputs")): entry["has_outputs"] = True if entry.has_key("frontend_device"): # check if internally connectable if path.exists("/proc/stb/frontend/%d/rf_switch" % entry["frontend_device"]): entry["internally_connectable"] = entry["frontend_device"] - 1 else: entry["internally_connectable"] = None else: entry["frontend_device"] = entry["internally_connectable"] = None if not (entry.has_key("multi_type")): entry["multi_type"] = {} self.nim_slots.append(NIM(slot = id, description = entry["name"], type = entry["type"], has_outputs = entry["has_outputs"], internally_connectable = entry["internally_connectable"], multi_type = entry["multi_type"], frontend_id = entry["frontend_device"], i2c = entry["i2c"], is_empty = entry["isempty"])) def hasNimType(self, chktype): for slot in self.nim_slots: if slot.isCompatible(chktype): return True for type in slot.getMultiTypeList().values(): if chktype == type: return True return False def getNimType(self, slotid): return self.nim_slots[slotid].type def getNimDescription(self, slotid): return self.nim_slots[slotid].friendly_full_description def getNimName(self, slotid): return self.nim_slots[slotid].description def getNim(self, slotid): return self.nim_slots[slotid] def getI2CDevice(self, slotid): return self.nim_slots[slotid].getI2C() def getNimListOfType(self, type, exception = -1): # returns a list of indexes for NIMs compatible to the given type, except for 'exception' list = [] for x in self.nim_slots: if x.isCompatible(type) and x.slot != exception: list.append(x.slot) return list def __init__(self): self.satList = [ ] self.cablesList = [] self.terrestrialsList = [] self.atscList = [] self.enumerateNIMs() self.readTransponders() InitNimManager(self) #init config stuff # get a list with the friendly full description def nimList(self): list = [ ] for slot in self.nim_slots: list.append(slot.friendly_full_description) return list def getSlotCount(self): return len(self.nim_slots) def hasOutputs(self, slotid): return self.nim_slots[slotid].hasOutputs() def nimInternallyConnectableTo(self, slotid): return self.nim_slots[slotid].internallyConnectableTo() def nimRemoveInternalLink(self, slotid): self.nim_slots[slotid].removeInternalLink() def canConnectTo(self, slotid): slots = [] if self.nim_slots[slotid].internallyConnectableTo() is not None: slots.append(self.nim_slots[slotid].internallyConnectableTo()) for type in self.nim_slots[slotid].connectableTo(): for slot in self.getNimListOfType(type, exception = slotid): if self.hasOutputs(slot): slots.append(slot) # remove nims, that have a conntectedTo reference on for testnim in slots[:]: for nim in self.getNimListOfType("DVB-S", slotid): nimConfig = self.getNimConfig(nim) if nimConfig.content.items.has_key("configMode") and nimConfig.configMode.value == "loopthrough" and int(nimConfig.connectedTo.value) == testnim: slots.remove(testnim) break slots.sort() return slots def canEqualTo(self, slotid): type = self.getNimType(slotid) type = type[:5] # DVB-S2 --> DVB-S, DVB-T2 --> DVB-T, DVB-C2 --> DVB-C nimList = self.getNimListOfType(type, slotid) for nim in nimList[:]: mode = self.getNimConfig(nim) if mode.configMode.value == "loopthrough" or mode.configMode.value == "satposdepends": nimList.remove(nim) return nimList def canDependOn(self, slotid): type = self.getNimType(slotid) type = type[:5] # DVB-S2 --> DVB-S, DVB-T2 --> DVB-T, DVB-C2 --> DVB-C nimList = self.getNimListOfType(type, slotid) positionerList = [] for nim in nimList[:]: mode = self.getNimConfig(nim) nimHaveRotor = mode.configMode.value == "simple" and mode.diseqcMode.value == "positioner" if not nimHaveRotor and mode.configMode.value == "advanced": for x in range(3601, 3605): lnb = int(mode.advanced.sat[x].lnb.value) if lnb != 0: nimHaveRotor = True break if not nimHaveRotor: for sat in mode.advanced.sat.values(): lnb_num = int(sat.lnb.value) diseqcmode = lnb_num and mode.advanced.lnb[lnb_num].diseqcMode.value or "" if diseqcmode == "1_2": nimHaveRotor = True break if nimHaveRotor: alreadyConnected = False for testnim in nimList: testmode = self.getNimConfig(testnim) if testmode.configMode.value == "satposdepends" and int(testmode.connectedTo.value) == int(nim): alreadyConnected = True break if not alreadyConnected: positionerList.append(nim) return positionerList def getNimConfig(self, slotid): return config.Nims[slotid] def getSatName(self, pos): for sat in self.satList: if sat[0] == pos: return sat[1] return _("N/A") def getSatList(self): return self.satList # returns True if something is configured to be connected to this nim # if slotid == -1, returns if something is connected to ANY nim def somethingConnected(self, slotid = -1): if (slotid == -1): connected = False for id in range(self.getSlotCount()): if self.somethingConnected(id): connected = True return connected else: nim = config.Nims[slotid] configMode = nim.configMode.value if self.nim_slots[slotid].isCompatible("DVB-S") or self.nim_slots[slotid].isCompatible("DVB-T") or self.nim_slots[slotid].isCompatible("DVB-C"): return not (configMode == "nothing") def getSatListForNim(self, slotid): list = [] if self.nim_slots[slotid].isCompatible("DVB-S"): nim = config.Nims[slotid] #print "slotid:", slotid #print "self.satellites:", self.satList[config.Nims[slotid].diseqcA.index] #print "diseqcA:", config.Nims[slotid].diseqcA.value configMode = nim.configMode.value if configMode == "equal": slotid = int(nim.connectedTo.value) nim = config.Nims[slotid] configMode = nim.configMode.value elif configMode == "loopthrough": slotid = self.sec.getRoot(slotid, int(nim.connectedTo.value)) nim = config.Nims[slotid] configMode = nim.configMode.value if configMode == "simple": dm = nim.diseqcMode.value if dm in ("single", "toneburst_a_b", "diseqc_a_b", "diseqc_a_b_c_d"): if nim.diseqcA.orbital_position < 3600: list.append(self.satList[nim.diseqcA.index - 2]) if dm in ("toneburst_a_b", "diseqc_a_b", "diseqc_a_b_c_d"): if nim.diseqcB.orbital_position < 3600: list.append(self.satList[nim.diseqcB.index - 2]) if dm == "diseqc_a_b_c_d": if nim.diseqcC.orbital_position < 3600: list.append(self.satList[nim.diseqcC.index - 2]) if nim.diseqcD.orbital_position < 3600: list.append(self.satList[nim.diseqcD.index - 2]) if dm == "positioner": for x in self.satList: list.append(x) elif configMode == "advanced": for x in range(3601, 3605): if int(nim.advanced.sat[x].lnb.value) != 0: for x in self.satList: list.append(x) if not list: for x in self.satList: if int(nim.advanced.sat[x[0]].lnb.value) != 0: list.append(x) return list def getRotorSatListForNim(self, slotid): list = [] if self.nim_slots[slotid].isCompatible("DVB-S"): #print "slotid:", slotid #print "self.satellites:", self.satList[config.Nims[slotid].diseqcA.value] #print "diseqcA:", config.Nims[slotid].diseqcA.value configMode = config.Nims[slotid].configMode.value if configMode == "simple": if config.Nims[slotid].diseqcMode.value == "positioner": for x in self.satList: list.append(x) elif configMode == "advanced": nim = config.Nims[slotid] for x in range(3601, 3605): if int(nim.advanced.sat[x].lnb.value) != 0: for x in self.satList: list.append(x) if not list: for x in self.satList: lnbnum = int(nim.advanced.sat[x[0]].lnb.value) if lnbnum != 0: lnb = nim.advanced.lnb[lnbnum] if lnb.diseqcMode.value == "1_2": list.append(x) return list def InitSecParams(): config.sec = ConfigSubsection() x = ConfigInteger(default=25, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_CONT_TONE_DISABLE_BEFORE_DISEQC, configElement.value)) config.sec.delay_after_continuous_tone_disable_before_diseqc = x x = ConfigInteger(default=10, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_FINAL_CONT_TONE_CHANGE, configElement.value)) config.sec.delay_after_final_continuous_tone_change = x x = ConfigInteger(default=10, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_FINAL_VOLTAGE_CHANGE, configElement.value)) config.sec.delay_after_final_voltage_change = x x = ConfigInteger(default=120, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_BETWEEN_DISEQC_REPEATS, configElement.value)) config.sec.delay_between_diseqc_repeats = x x = ConfigInteger(default=50, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_LAST_DISEQC_CMD, configElement.value)) config.sec.delay_after_last_diseqc_command = x x = ConfigInteger(default=50, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_TONEBURST, configElement.value)) config.sec.delay_after_toneburst = x x = ConfigInteger(default=20, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_VOLTAGE_CHANGE_BEFORE_SWITCH_CMDS, configElement.value)) config.sec.delay_after_change_voltage_before_switch_command = x x = ConfigInteger(default=200, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_ENABLE_VOLTAGE_BEFORE_SWITCH_CMDS, configElement.value)) config.sec.delay_after_enable_voltage_before_switch_command = x x = ConfigInteger(default=700, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_BETWEEN_SWITCH_AND_MOTOR_CMD, configElement.value)) config.sec.delay_between_switch_and_motor_command = x x = ConfigInteger(default=500, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_VOLTAGE_CHANGE_BEFORE_MEASURE_IDLE_INPUTPOWER, configElement.value)) config.sec.delay_after_voltage_change_before_measure_idle_inputpower = x x = ConfigInteger(default=900, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_ENABLE_VOLTAGE_BEFORE_MOTOR_CMD, configElement.value)) config.sec.delay_after_enable_voltage_before_motor_command = x x = ConfigInteger(default=500, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_MOTOR_STOP_CMD, configElement.value)) config.sec.delay_after_motor_stop_command = x x = ConfigInteger(default=500, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_VOLTAGE_CHANGE_BEFORE_MOTOR_CMD, configElement.value)) config.sec.delay_after_voltage_change_before_motor_command = x x = ConfigInteger(default=70, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_BEFORE_SEQUENCE_REPEAT, configElement.value)) config.sec.delay_before_sequence_repeat = x x = ConfigInteger(default=360, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.MOTOR_RUNNING_TIMEOUT, configElement.value)) config.sec.motor_running_timeout = x x = ConfigInteger(default=1, limits = (0, 5)) x.addNotifier(lambda configElement: secClass.setParam(secClass.MOTOR_COMMAND_RETRIES, configElement.value)) config.sec.motor_command_retries = x x = ConfigInteger(default=50, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_DISEQC_RESET_CMD, configElement.value)) config.sec.delay_after_diseqc_reset_cmd = x x = ConfigInteger(default=150, limits = (0, 9999)) x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_DISEQC_PERIPHERIAL_POWERON_CMD, configElement.value)) config.sec.delay_after_diseqc_peripherial_poweron_cmd = x # TODO add support for satpos depending nims to advanced nim configuration # so a second/third/fourth cable from a motorized lnb can used behind a # diseqc 1.0 / diseqc 1.1 / toneburst switch # the C(++) part should can handle this # the configElement should be only visible when diseqc 1.2 is disabled def InitNimManager(nimmgr): hw = HardwareInfo() addNimConfig = False try: config.Nims except: addNimConfig = True if addNimConfig: InitSecParams() config.Nims = ConfigSubList() for x in range(len(nimmgr.nim_slots)): config.Nims.append(ConfigSubsection()) lnb_choices = { "universal_lnb": _("Universal LNB"), "unicable": _("Unicable"), "c_band": _("C-Band"), "user_defined": _("User defined")} lnb_choices_default = "universal_lnb" unicablelnbproducts = {} unicablematrixproducts = {} doc = xml.etree.cElementTree.parse(eEnv.resolve("${datadir}/enigma2/unicable.xml")) root = doc.getroot() entry = root.find("lnb") for manufacturer in entry.getchildren(): m={} for product in manufacturer.getchildren(): scr=[] lscr=("scr1","scr2","scr3","scr4","scr5","scr6","scr7","scr8") for i in range(len(lscr)): scr.append(product.get(lscr[i],"0")) for i in range(len(lscr)): if scr[len(lscr)-i-1] == "0": scr.pop() else: break; lof=[] lof.append(int(product.get("positions",1))) lof.append(int(product.get("lofl",9750))) lof.append(int(product.get("lofh",10600))) lof.append(int(product.get("threshold",11700))) scr.append(tuple(lof)) m.update({product.get("name"):tuple(scr)}) unicablelnbproducts.update({manufacturer.get("name"):m}) entry = root.find("matrix") for manufacturer in entry.getchildren(): m={} for product in manufacturer.getchildren(): scr=[] lscr=("scr1","scr2","scr3","scr4","scr5","scr6","scr7","scr8") for i in range(len(lscr)): scr.append(product.get(lscr[i],"0")) for i in range(len(lscr)): if scr[len(lscr)-i-1] == "0": scr.pop() else: break; lof=[] lof.append(int(product.get("positions",1))) lof.append(int(product.get("lofl",9750))) lof.append(int(product.get("lofh",10600))) lof.append(int(product.get("threshold",11700))) scr.append(tuple(lof)) m.update({product.get("name"):tuple(scr)}) unicablematrixproducts.update({manufacturer.get("name"):m}) UnicableLnbManufacturers = unicablelnbproducts.keys() UnicableLnbManufacturers.sort() UnicableMatrixManufacturers = unicablematrixproducts.keys() UnicableMatrixManufacturers.sort() unicable_choices = { "unicable_lnb": _("Unicable LNB"), "unicable_matrix": _("Unicable Martix"), "unicable_user": "Unicable "+_("User defined")} unicable_choices_default = "unicable_lnb" advanced_lnb_satcruser_choices = [ ("1", "SatCR 1"), ("2", "SatCR 2"), ("3", "SatCR 3"), ("4", "SatCR 4"), ("5", "SatCR 5"), ("6", "SatCR 6"), ("7", "SatCR 7"), ("8", "SatCR 8")] prio_list = [ ("-1", _("Auto")) ] prio_list += [(str(prio), str(prio)) for prio in range(65)+range(14000,14065)+range(19000,19065)] advanced_lnb_csw_choices = [("none", _("None")), ("AA", _("AA")), ("AB", _("AB")), ("BA", _("BA")), ("BB", _("BB"))] advanced_lnb_csw_choices += [(str(0xF0|y), "Input " + str(y+1)) for y in range(0, 16)] advanced_lnb_ucsw_choices = [("0", _("None"))] + [(str(y), "Input " + str(y)) for y in range(1, 17)] diseqc_mode_choices = [ ("single", _("Single")), ("toneburst_a_b", _("Toneburst A/B")), ("diseqc_a_b", "DiSEqC A/B"), ("diseqc_a_b_c_d", "DiSEqC A/B/C/D"), ("positioner", _("Positioner"))] positioner_mode_choices = [("usals", _("USALS")), ("manual", _("manual"))] diseqc_satlist_choices = [(3600, _('automatic'), 1), (3601, _('nothing connected'), 1)] + nimmgr.satList longitude_orientation_choices = [("east", _("East")), ("west", _("West"))] latitude_orientation_choices = [("north", _("North")), ("south", _("South"))] turning_speed_choices = [("fast", _("Fast")), ("slow", _("Slow")), ("fast epoch", _("Fast epoch"))] advanced_satlist_choices = nimmgr.satList + [ (3601, _('All satellites')+' 1', 1), (3602, _('All satellites')+' 2', 1), (3603, _('All satellites')+' 3', 1), (3604, _('All satellites')+' 4', 1)] advanced_lnb_choices = [("0", "not available")] + [(str(y), "LNB " + str(y)) for y in range(1, 33)] advanced_voltage_choices = [("polarization", _("Polarization")), ("13V", _("13 V")), ("18V", _("18 V"))] advanced_tonemode_choices = [("band", _("Band")), ("on", _("On")), ("off", _("Off"))] advanced_lnb_toneburst_choices = [("none", _("None")), ("A", _("A")), ("B", _("B"))] advanced_lnb_allsat_diseqcmode_choices = [("1_2", _("1.2"))] advanced_lnb_diseqcmode_choices = [("none", _("None")), ("1_0", _("1.0")), ("1_1", _("1.1")), ("1_2", _("1.2"))] advanced_lnb_commandOrder1_0_choices = [("ct", "committed, toneburst"), ("tc", "toneburst, committed")] advanced_lnb_commandOrder_choices = [ ("ct", "committed, toneburst"), ("tc", "toneburst, committed"), ("cut", "committed, uncommitted, toneburst"), ("tcu", "toneburst, committed, uncommitted"), ("uct", "uncommitted, committed, toneburst"), ("tuc", "toneburst, uncommitted, commmitted")] advanced_lnb_diseqc_repeat_choices = [("none", _("None")), ("one", _("One")), ("two", _("Two")), ("three", _("Three"))] advanced_lnb_fast_turning_btime = mktime(datetime(1970, 1, 1, 7, 0).timetuple()); advanced_lnb_fast_turning_etime = mktime(datetime(1970, 1, 1, 19, 0).timetuple()); def configLOFChanged(configElement): if configElement.value == "unicable": x = configElement.slot_id lnb = configElement.lnb_id nim = config.Nims[x] lnbs = nim.advanced.lnb section = lnbs[lnb] if isinstance(section.unicable, ConfigNothing): if lnb == 1: section.unicable = ConfigSelection(unicable_choices, unicable_choices_default) elif lnb == 2: section.unicable = ConfigSelection(choices = {"unicable_matrix": _("Unicable Martix"),"unicable_user": "Unicable "+_("User defined")}, default = "unicable_matrix") else: section.unicable = ConfigSelection(choices = {"unicable_user": _("User defined")}, default = "unicable_user") def fillUnicableConf(sectionDict, unicableproducts, vco_null_check): for y in unicableproducts: products = unicableproducts[y].keys() products.sort() tmp = ConfigSubsection() tmp.product = ConfigSelection(choices = products, default = products[0]) tmp.scr = ConfigSubDict() tmp.vco = ConfigSubDict() tmp.lofl = ConfigSubDict() tmp.lofh = ConfigSubDict() tmp.loft = ConfigSubDict() tmp.positions = ConfigSubDict() for z in products: scrlist = [] vcolist = unicableproducts[y][z] tmp.vco[z] = ConfigSubList() for cnt in range(1,1+len(vcolist)-1): vcofreq = int(vcolist[cnt-1]) if vcofreq == 0 and vco_null_check: scrlist.append(("%d" %cnt,"SCR %d " %cnt +_("not used"))) else: scrlist.append(("%d" %cnt,"SCR %d" %cnt)) tmp.vco[z].append(ConfigInteger(default=vcofreq, limits = (vcofreq, vcofreq))) tmp.scr[z] = ConfigSelection(choices = scrlist, default = scrlist[0][0]) positions = int(vcolist[len(vcolist)-1][0]) tmp.positions[z] = ConfigSubList() tmp.positions[z].append(ConfigInteger(default=positions, limits = (positions, positions))) lofl = vcolist[len(vcolist)-1][1] tmp.lofl[z] = ConfigSubList() tmp.lofl[z].append(ConfigInteger(default=lofl, limits = (lofl, lofl))) lofh = int(vcolist[len(vcolist)-1][2]) tmp.lofh[z] = ConfigSubList() tmp.lofh[z].append(ConfigInteger(default=lofh, limits = (lofh, lofh))) loft = int(vcolist[len(vcolist)-1][3]) tmp.loft[z] = ConfigSubList() tmp.loft[z].append(ConfigInteger(default=loft, limits = (loft, loft))) sectionDict[y] = tmp if lnb < 3: print "MATRIX" section.unicableMatrix = ConfigSubDict() section.unicableMatrixManufacturer = ConfigSelection(UnicableMatrixManufacturers, UnicableMatrixManufacturers[0]) fillUnicableConf(section.unicableMatrix, unicablematrixproducts, True) if lnb < 2: print "LNB" section.unicableLnb = ConfigSubDict() section.unicableLnbManufacturer = ConfigSelection(UnicableLnbManufacturers, UnicableLnbManufacturers[0]) fillUnicableConf(section.unicableLnb, unicablelnbproducts, False) #TODO satpositions for satcruser section.satcruser = ConfigSelection(advanced_lnb_satcruser_choices, default="1") tmp = ConfigSubList() tmp.append(ConfigInteger(default=1284, limits = (950, 2150))) tmp.append(ConfigInteger(default=1400, limits = (950, 2150))) tmp.append(ConfigInteger(default=1516, limits = (950, 2150))) tmp.append(ConfigInteger(default=1632, limits = (950, 2150))) tmp.append(ConfigInteger(default=1748, limits = (950, 2150))) tmp.append(ConfigInteger(default=1864, limits = (950, 2150))) tmp.append(ConfigInteger(default=1980, limits = (950, 2150))) tmp.append(ConfigInteger(default=2096, limits = (950, 2150))) section.satcrvcouser = tmp nim.advanced.unicableconnected = ConfigYesNo(default=False) nim.advanced.unicableconnectedTo = ConfigSelection([(str(id), nimmgr.getNimDescription(id)) for id in nimmgr.getNimListOfType("DVB-S") if id != x]) def configDiSEqCModeChanged(configElement): section = configElement.section if configElement.value == "1_2" and isinstance(section.longitude, ConfigNothing): #section.longitude = ConfigFloat(default = [5,100], limits = [(0,359),(0,999)]) section.longitude = ConfigFloat(default = [0,000], limits = [(0,359),(0,999)]) # [iq] section.longitudeOrientation = ConfigSelection(longitude_orientation_choices, "east") #section.latitude = ConfigFloat(default = [50,767], limits = [(0,359),(0,999)]) section.latitude = ConfigFloat(default = [51,500], limits = [(0,359),(0,999)]) # [iq] section.latitudeOrientation = ConfigSelection(latitude_orientation_choices, "north") section.tuningstepsize = ConfigFloat(default = [0,360], limits = [(0,9),(0,999)]) section.turningspeedH = ConfigFloat(default = [2,3], limits = [(0,9),(0,9)]) section.turningspeedV = ConfigFloat(default = [1,7], limits = [(0,9),(0,9)]) section.powerMeasurement = ConfigYesNo(default=True) section.powerThreshold = ConfigInteger(default=hw.get_device_name() == "dm7025" and 50 or 15, limits=(0, 100)) section.turningSpeed = ConfigSelection(turning_speed_choices, "fast") section.fastTurningBegin = ConfigDateTime(default=advanced_lnb_fast_turning_btime, formatstring = _("%H:%M"), increment = 600) section.fastTurningEnd = ConfigDateTime(default=advanced_lnb_fast_turning_etime, formatstring = _("%H:%M"), increment = 600) def configLNBChanged(configElement): x = configElement.slot_id nim = config.Nims[x] if isinstance(configElement.value, tuple): lnb = int(configElement.value[0]) else: lnb = int(configElement.value) lnbs = nim.advanced.lnb if lnb and lnb not in lnbs: section = lnbs[lnb] = ConfigSubsection() section.lofl = ConfigInteger(default=9750, limits = (0, 99999)) section.lofh = ConfigInteger(default=10600, limits = (0, 99999)) section.threshold = ConfigInteger(default=11700, limits = (0, 99999)) # section.output_12v = ConfigSelection(choices = [("0V", _("0 V")), ("12V", _("12 V"))], default="0V") section.increased_voltage = ConfigYesNo(False) section.toneburst = ConfigSelection(advanced_lnb_toneburst_choices, "none") section.longitude = ConfigNothing() if lnb > 32: tmp = ConfigSelection(advanced_lnb_allsat_diseqcmode_choices, "1_2") tmp.section = section configDiSEqCModeChanged(tmp) else: tmp = ConfigSelection(advanced_lnb_diseqcmode_choices, "none") tmp.section = section tmp.addNotifier(configDiSEqCModeChanged) section.diseqcMode = tmp section.commitedDiseqcCommand = ConfigSelection(advanced_lnb_csw_choices) section.fastDiseqc = ConfigYesNo(False) section.sequenceRepeat = ConfigYesNo(False) section.commandOrder1_0 = ConfigSelection(advanced_lnb_commandOrder1_0_choices, "ct") section.commandOrder = ConfigSelection(advanced_lnb_commandOrder_choices, "ct") section.uncommittedDiseqcCommand = ConfigSelection(advanced_lnb_ucsw_choices) section.diseqcRepeats = ConfigSelection(advanced_lnb_diseqc_repeat_choices, "none") section.prio = ConfigSelection(prio_list, "-1") section.unicable = ConfigNothing() tmp = ConfigSelection(lnb_choices, lnb_choices_default) tmp.slot_id = x tmp.lnb_id = lnb tmp.addNotifier(configLOFChanged, initial_call = False) section.lof = tmp def configModeChanged(configMode): slot_id = configMode.slot_id nim = config.Nims[slot_id] if configMode.value == "advanced" and isinstance(nim.advanced, ConfigNothing): # advanced config: nim.advanced = ConfigSubsection() nim.advanced.sat = ConfigSubDict() nim.advanced.sats = getConfigSatlist(192, advanced_satlist_choices) nim.advanced.lnb = ConfigSubDict() nim.advanced.lnb[0] = ConfigNothing() for x in nimmgr.satList: tmp = ConfigSubsection() tmp.voltage = ConfigSelection(advanced_voltage_choices, "polarization") tmp.tonemode = ConfigSelection(advanced_tonemode_choices, "band") tmp.usals = ConfigYesNo(True) tmp.rotorposition = ConfigInteger(default=1, limits=(1, 255)) lnb = ConfigSelection(advanced_lnb_choices, "0") lnb.slot_id = slot_id lnb.addNotifier(configLNBChanged, initial_call = False) tmp.lnb = lnb nim.advanced.sat[x[0]] = tmp for x in range(3601, 3605): tmp = ConfigSubsection() tmp.voltage = ConfigSelection(advanced_voltage_choices, "polarization") tmp.tonemode = ConfigSelection(advanced_tonemode_choices, "band") tmp.usals = ConfigYesNo(default=True) tmp.rotorposition = ConfigInteger(default=1, limits=(1, 255)) lnbnum = 33+x-3601 lnb = ConfigSelection([("0", "not available"), (str(lnbnum), "LNB %d"%(lnbnum))], "0") lnb.slot_id = slot_id lnb.addNotifier(configLNBChanged, initial_call = False) tmp.lnb = lnb nim.advanced.sat[x] = tmp def toneAmplitudeChanged(configElement): fe_id = configElement.fe_id slot_id = configElement.slot_id if nimmgr.nim_slots[slot_id].description == 'Alps BSBE2': open("/proc/stb/frontend/%d/tone_amplitude" %(fe_id), "w").write(configElement.value) def createSatConfig(nim, x, empty_slots): try: nim.toneAmplitude except: nim.toneAmplitude = ConfigSelection([("11", "340mV"), ("10", "360mV"), ("9", "600mV"), ("8", "700mV"), ("7", "800mV"), ("6", "900mV"), ("5", "1100mV")], "7") nim.toneAmplitude.fe_id = x - empty_slots nim.toneAmplitude.slot_id = x nim.toneAmplitude.addNotifier(toneAmplitudeChanged) nim.diseqc13V = ConfigYesNo(False) nim.diseqcMode = ConfigSelection(diseqc_mode_choices, "diseqc_a_b") nim.connectedTo = ConfigSelection([(str(id), nimmgr.getNimDescription(id)) for id in nimmgr.getNimListOfType("DVB-S") if id != x]) nim.simpleSingleSendDiSEqC = ConfigYesNo(False) nim.simpleDiSEqCSetVoltageTone = ConfigYesNo(True) nim.simpleDiSEqCOnlyOnSatChange = ConfigYesNo(False) nim.diseqcA = ConfigSatlist(list = diseqc_satlist_choices) nim.diseqcB = ConfigSatlist(list = diseqc_satlist_choices) nim.diseqcC = ConfigSatlist(list = diseqc_satlist_choices) nim.diseqcD = ConfigSatlist(list = diseqc_satlist_choices) nim.positionerMode = ConfigSelection(positioner_mode_choices, "usals") #nim.longitude = ConfigFloat(default=[5,100], limits=[(0,359),(0,999)]) nim.longitude = ConfigFloat(default=[0,000], limits=[(0,359),(0,999)]) # [iq] nim.longitudeOrientation = ConfigSelection(longitude_orientation_choices, "east") #nim.latitude = ConfigFloat(default=[50,767], limits=[(0,359),(0,999)]) nim.latitude = ConfigFloat(default=[51,500], limits=[(0,359),(0,999)]) # [iq] nim.latitudeOrientation = ConfigSelection(latitude_orientation_choices, "north") nim.tuningstepsize = ConfigFloat(default = [0,360], limits = [(0,9),(0,999)]) nim.turningspeedH = ConfigFloat(default = [2,3], limits = [(0,9),(0,9)]) nim.turningspeedV = ConfigFloat(default = [1,7], limits = [(0,9),(0,9)]) nim.powerMeasurement = ConfigYesNo(True) nim.powerThreshold = ConfigInteger(default=hw.get_device_name() == "dm8000" and 15 or 50, limits=(0, 100)) nim.turningSpeed = ConfigSelection(turning_speed_choices, "fast") btime = datetime(1970, 1, 1, 7, 0); nim.fastTurningBegin = ConfigDateTime(default = mktime(btime.timetuple()), formatstring = _("%H:%M"), increment = 900) etime = datetime(1970, 1, 1, 19, 0); nim.fastTurningEnd = ConfigDateTime(default = mktime(etime.timetuple()), formatstring = _("%H:%M"), increment = 900) def createCableConfig(nim, x): try: nim.cable except: list = [ ] n = 0 for x in nimmgr.cablesList: list.append((str(n), x[0])) n += 1 nim.cable = ConfigSubsection() nim.cable.scan_networkid = ConfigInteger(default = 0, limits = (0, 9999)) possible_scan_types = [("bands", _("Frequency bands")), ("steps", _("Frequency steps"))] if n: possible_scan_types.append(("provider", _("Provider"))) nim.cable.scan_provider = ConfigSelection(default = "0", choices = list) nim.cable.scan_type = ConfigSelection(default = "bands", choices = possible_scan_types) nim.cable.scan_band_EU_VHF_I = ConfigYesNo(default = True) nim.cable.scan_band_EU_MID = ConfigYesNo(default = True) nim.cable.scan_band_EU_VHF_III = ConfigYesNo(default = True) nim.cable.scan_band_EU_UHF_IV = ConfigYesNo(default = True) nim.cable.scan_band_EU_UHF_V = ConfigYesNo(default = True) nim.cable.scan_band_EU_SUPER = ConfigYesNo(default = True) nim.cable.scan_band_EU_HYPER = ConfigYesNo(default = True) nim.cable.scan_band_US_LOW = ConfigYesNo(default = False) nim.cable.scan_band_US_MID = ConfigYesNo(default = False) nim.cable.scan_band_US_HIGH = ConfigYesNo(default = False) nim.cable.scan_band_US_SUPER = ConfigYesNo(default = False) nim.cable.scan_band_US_HYPER = ConfigYesNo(default = False) nim.cable.scan_frequency_steps = ConfigInteger(default = 1000, limits = (1000, 10000)) nim.cable.scan_mod_qam16 = ConfigYesNo(default = False) nim.cable.scan_mod_qam32 = ConfigYesNo(default = False) nim.cable.scan_mod_qam64 = ConfigYesNo(default = True) nim.cable.scan_mod_qam128 = ConfigYesNo(default = False) nim.cable.scan_mod_qam256 = ConfigYesNo(default = True) nim.cable.scan_sr_6900 = ConfigYesNo(default = True) nim.cable.scan_sr_6875 = ConfigYesNo(default = True) nim.cable.scan_sr_ext1 = ConfigInteger(default = 0, limits = (0, 7230)) nim.cable.scan_sr_ext2 = ConfigInteger(default = 0, limits = (0, 7230)) def createTerrestrialConfig(nim, x): try: nim.terrestrial except: list = [] n = 0 for x in nimmgr.terrestrialsList: list.append((str(n), x[0])) n += 1 nim.terrestrial = ConfigSelection(choices = list) nim.terrestrial_5V = ConfigOnOff() empty_slots = 0 for slot in nimmgr.nim_slots: x = slot.slot nim = config.Nims[x] if slot.isCompatible("DVB-S"): createSatConfig(nim, x, empty_slots) config_mode_choices = [("nothing", _("nothing connected")), ("simple", _("simple")), ("advanced", _("advanced"))] if len(nimmgr.getNimListOfType(slot.type, exception = x)) > 0: config_mode_choices.append(("equal", _("equal to"))) config_mode_choices.append(("satposdepends", _("second cable of motorized LNB"))) if len(nimmgr.canConnectTo(x)) > 0: config_mode_choices.append(("loopthrough", _("loopthrough to"))) nim.advanced = ConfigNothing() tmp = ConfigSelection(config_mode_choices, "simple") tmp.slot_id = x tmp.addNotifier(configModeChanged, initial_call = False) nim.configMode = tmp elif slot.isCompatible("DVB-C"): nim.configMode = ConfigSelection( choices = { "enabled": _("enabled"), "nothing": _("nothing connected"), }, default = "enabled") createCableConfig(nim, x) elif slot.isCompatible("DVB-T"): nim.configMode = ConfigSelection( choices = { "enabled": _("enabled"), "nothing": _("nothing connected"), }, default = "enabled") createTerrestrialConfig(nim, x) else: empty_slots += 1 nim.configMode = ConfigSelection(choices = { "nothing": _("disabled") }, default="nothing"); if slot.type is not None: print "pls add support for this frontend type!", slot.type # assert False nimmgr.sec = SecConfigure(nimmgr) def tunerTypeChanged(nimmgr, configElement): fe_id = configElement.fe_id eDVBResourceManager.getInstance().setFrontendType(nimmgr.nim_slots[fe_id].frontend_id, nimmgr.nim_slots[fe_id].getType()) import os if os.path.exists("/proc/stb/frontend/%d/mode" % fe_id): cur_type = int(open("/proc/stb/frontend/%d/mode" % (fe_id), "r").read()) if cur_type != int(configElement.value): print "tunerTypeChanged feid %d from %d to mode %d" % (fe_id, cur_type, int(configElement.value)) try: oldvalue = open("/sys/module/dvb_core/parameters/dvb_shutdown_timeout", "r").readline() open("/sys/module/dvb_core/parameters/dvb_shutdown_timeout", "w").write("0") except: print "[info] no /sys/module/dvb_core/parameters/dvb_shutdown_timeout available" frontend = eDVBResourceManager.getInstance().allocateRawChannel(fe_id).getFrontend() frontend.closeFrontend() open("/proc/stb/frontend/%d/mode" % (fe_id), "w").write(configElement.value) frontend.reopenFrontend() try: open("/sys/module/dvb_core/parameters/dvb_shutdown_timeout", "w").write(oldvalue) except: print "[info] no /sys/module/dvb_core/parameters/dvb_shutdown_timeout available" nimmgr.enumerateNIMs() else: print "tuner type is already already %d" %cur_type empty_slots = 0 for slot in nimmgr.nim_slots: x = slot.slot nim = config.Nims[x] addMultiType = False try: nim.multiType except: addMultiType = True if slot.isMultiType() and addMultiType: typeList = [] for id in slot.getMultiTypeList().keys(): type = slot.getMultiTypeList()[id] typeList.append((id, type)) nim.multiType = ConfigSelection(typeList, "0") nim.multiType.fe_id = x - empty_slots nim.multiType.addNotifier(boundFunction(tunerTypeChanged, nimmgr)) empty_slots = 0 for slot in nimmgr.nim_slots: x = slot.slot nim = config.Nims[x] empty = True if slot.canBeCompatible("DVB-S"): createSatConfig(nim, x, empty_slots) empty = False if slot.canBeCompatible("DVB-C"): createCableConfig(nim, x) empty = False if slot.canBeCompatible("DVB-T"): createTerrestrialConfig(nim, x) empty = False if empty: empty_slots += 1 nimmanager = NimManager()
pli3/enigma2-git
lib/python/Components/NimManager.py
Python
gpl-2.0
63,253
# encoding: utf-8 # module samba.dcerpc.lsa # from /usr/lib/python2.7/dist-packages/samba/dcerpc/lsa.so # by generator 1.135 """ lsa DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class ForestTrustInformation(__talloc.Object): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass def __ndr_pack__(self, *args, **kwargs): # real signature unknown """ S.ndr_pack(object) -> blob NDR pack """ pass def __ndr_print__(self, *args, **kwargs): # real signature unknown """ S.ndr_print(object) -> None NDR print """ pass def __ndr_unpack__(self, *args, **kwargs): # real signature unknown """ S.ndr_unpack(class, blob, allow_remaining=False) -> None NDR unpack """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default entries = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/lsa/ForestTrustInformation.py
Python
gpl-2.0
1,274
# Kingsoft Antivirus # CVE-NOMATCH import logging log = logging.getLogger("Thug") def SetUninstallName(self, arg): if len(arg) > 900: log.ThugLogging.log_exploit_event(self._window.url, "Kingsoft AntiVirus ActiveX", "SetUninstallName Heap Overflow")
tweemeterjop/thug
thug/ActiveX/modules/Kingsoft.py
Python
gpl-2.0
350
# -*- coding: utf-8 -*- version=0.2 visitedVersion=0.2 enableNotification=True isFirstStart=True countClickUp=0 langList=['English','Russian'] searchEngines=['Google','Bing','Yahoo','Yandex'] defaultSearchEngine=0 defaultLangFrom='Auto' defaultLangTo='Russian' useControl=True useDblControl=True useNothing=False useGoogle=True useBing=False useProxy=False enableApp=True startWithOS=True proxyAddress="" proxyPort="" proxyLogin="" proxyPassword="" isRunTranslate=False translatedTextSize=8 langForTran = { 'ar':'Arabic', 'bg':'Bulgarian', 'ca':'Catalan', 'zh-CHS':'Chinese Simplified', 'zh-CHT':'Chinese Traditional', 'cs':'Czech', 'da':'Danish', 'nl':'Dutch', 'en':'English', 'et':'Estonian', 'fi':'Finnish', 'fr':'French', 'de':'German', 'el':'Greek', 'ht':'Haitian Creole', 'he':'Hebrew', 'hu':'Hungarian', 'id':'Indonesian', 'it':'Italian', 'ja':'Japanese', 'ko':'Korean', 'lv':'Latvian', 'lt':'Lithuanian', 'no':'Norwegian', 'pl':'Polish', 'pt':'Portuguese', 'ro':'Romanian', 'ru':'Russian', 'sk':'Slovak', 'sl':'Slovenian', 'es':'Spanish', 'sv':'Swedish', 'th':'Thai', 'tr':'Turkish', 'uk':'Ukrainian', 'vi':'Vietnamese' } langForListen = { 'ca':'Catalan', 'ca-es':' Catalan (Spain)', 'da':'Danish', 'da-dk':'Danish (Denmark)', 'de':'German', 'de-de':'German (Germany)', 'en':'English', 'en-au':'English (Australia)', 'en-ca':'English (Canada)', 'en-gb':'English (United Kingdom)', 'en-in':'English (India)', 'en-us':'English (United States)', 'es':'Spanish', 'es-es':'Spanish (Spain)', 'es-mx':'Spanish (Mexico)', 'fi ':'Finnish', 'fi-fi':'Finnish (Finland)', 'fr ':'French', 'fr-ca':'French (Canada)', 'fr-fr':'French (France)', 'it ':'Italian', 'it-it':'Italian (Italy)', 'ja ':'Japanese', 'ja-jp':'Japanese (Japan)', 'ko ':'Korean', 'ko-kr':'Korean (Korea)', 'nb-no':'Norwegian (Norway)', 'nl':'Dutch', 'nl-nl':'Dutch (Netherlands)', 'no':'Norwegian', 'pl':'Polish', 'pl-pl':'Polish (Poland)', 'pt':'Portuguese', 'pt-br':'Portuguese (Brazil)', 'pt-pt':'Portuguese (Portugal)', 'ru':'Russian', 'ru-ru':'Russian (Russia)', 'sv':'Swedish', 'sv-se':'Swedish (Sweden)', 'zh-chs':'Chinese Simplified', 'zh-cht':'Chinese Traditional', 'zh-hk':'Chinese Traditional (Hong Kong S.A.R.)', 'zh-tw':'Chinese Traditional (Taiwan)' } import imp import os import sys def main_is_frozen(): return (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") # old py2exe or imp.is_frozen("__main__")) # tools/freeze def get_main_dir(): if main_is_frozen(): # print 'Running from path', os.path.dirname(sys.executable) return os.path.dirname(sys.executable) return os.path.dirname(sys.argv[0])
ambyte/Vertaler
src/modules/settings/config.py
Python
gpl-2.0
2,655
#!/usr/bin/env python # -*- coding:utf-8 -*- """ """ from exception import * class base_storage: def __init__(self, usr=None, usr_key=None): self.usr_key = None self.usr = None self.records = [] if usr is None: return self.load_info_from_file() if self.usr != usr: raise UsrError if self.usr_key != usr_key: raise PasswdError def new_user(self, usr, usr_key): """ create or register new user to file storage """ if self.usr is not None: raise LoginError, "Login In Usr Can Not Create New Usr,You Should Logout First." self.usr = usr self.usr_key = usr_key self.flush_all() def load_info_from_file(self, filename="passwd"): """ load and parse usr-passwd and usr account info """ with open(filename) as f: for line in f: line = line.strip('\n') if line is "" or line.startswith("#") or line.startswith('"""'): continue if self.parse_manager_usr_info(line): continue else: record = self.parse_manager_record(line) self.records.append(record) if self.usr is None or self.usr_key is None: raise UsrError def parse_manager_usr_info(self, info_str): """ parse account-manager usr info to usr and passwd """ info_list = info_str.split(":") if len(info_list) is not 2: return False else: if info_list[0] == "usr": self.usr = info_list[1] elif info_list[0] == "key": self.usr_key = info_list[1] if len(self.usr_key) is not 64: raise ValueError else: return False return True def parse_manager_record(self, info_str): """ parse one record string to record tuple """ info_list = info_str.split(":") if len(info_list) is not 6: return None return info_list[0], info_list[1], info_list[2], info_list[3], info_list[4], info_list[5] def get_usr_info(self, usr=None): """Export interface """ return self.usr, self.usr_key def get_usr_key(self, usr=None): """Export interface """ return self.usr_key def get_records(self): """Export interface """ return self.records def flush_one_record(self, record): """ append one record to record file """ with open("passwd", "a+") as f: f.write("{0}:{1}:{2}:{3}:{4}:{5}\n".format(record[0], record[1], record[2], record[3], record[4], record[5])) def flush_all(self): """ flush usr&passwd and account record info to record file """ with open("passwd", "w+") as f: if self.usr is not None: f.write("usr:{0}\n".format(self.usr)) if self.usr_key is not None: f.write("key:{0}\n".format(self.usr_key)) f.write("#{0}\t:\t{1}\t:\t{2}\t:\t{3}\t:\t{4}\t:\t{5}\n". format("Ower", "Account", "Alias", "Email", "Mobile", "Passwd")) for record in self.records: f.write("{0}:{1}:{2}:{3}:{4}:{5}\n".format(record[0], record[1], record[2], record[3], record[4], record[5])) def set_usr_info(self, info): """Export interface set usr&key to account info storage """ if type(info) is not tuple: raise TypeError if len(info) is not 2: raise ValueError self.usr = info[0] self.usr_key = info[1] self.flush_all() def set_key(self, key): """Export interface set usr key to account info storage """ if self.usr is None: raise UsrError, "Usr Is None." if type(key) is not str: raise TypeError if key is None: raise ValueError self.usr_key = key self.flush_all() def put_record(self, record): """Export interface """ if record is not tuple: raise TypeError if len(record) is not 6: raise ValueError self.records.append(record) self.flush_all() #Check repeat def append_record(self, record): """Export interface """ if type(record) is not tuple: raise TypeError if len(record) is not 6: raise ValueError self.records.append(record) self.flush_one_record(record) def put_records(self, records): pass def append_records(self, records): if type(records) is not list: raise TypeError for record in records: if type(record) is not tuple: raise TypeError if len(record) is not 6: raise ValueError self.records.append(record) self.flush_one_record(record) if __name__ == '__main__' : pass
lifulong/account-manager
src/core/file_store.py
Python
gpl-2.0
4,172
## # Copyright 2013-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for DB, implemented as an easyblock @author: Kenneth Hoste (Ghent University) """ import os import shutil from easybuild.easyblocks.generic.configuremake import ConfigureMake from easybuild.tools.build_log import EasyBuildError class EB_DB(ConfigureMake): """Support for building and installing DB.""" def configure_step(self): """Configure build: change to build dir and call configure script.""" try: os.chdir('build_unix') except OSError as err: raise EasyBuildError("Failed to move to build dir: %s", err) super(EB_DB, self).configure_step(cmd_prefix='../dist/')
pescobar/easybuild-easyblocks
easybuild/easyblocks/d/db.py
Python
gpl-2.0
1,707
# gentrace.py # # Trace a generator by printing items received def trace(source): for item in source: print item yield item # Example use if __name__ == '__main__': from apachelog import * lines = open("access-log") log = trace(apache_log(lines)) r404 = (r for r in log if r['status'] == 404) for r in r404: pass
benosment/generators
generators-for-system-programmers/gentrace.py
Python
gpl-2.0
385
"""SCons.Tool.aixc++ Tool-specific initialization for IBM xlC / Visual Age C++ compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2015 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/aixc++.py rel_2.3.5:3329:275e75118ad4 2015/06/20 11:18:26 bdbaddog" import os.path import SCons.Platform.aix cplusplus = __import__('c++', globals(), locals(), []) packages = ['vacpp.cmp.core', 'vacpp.cmp.batch', 'vacpp.cmp.C', 'ibmcxx.cmp'] def get_xlc(env): xlc = env.get('CXX', 'xlC') return SCons.Platform.aix.get_xlc(env, xlc, packages) def generate(env): """Add Builders and construction variables for xlC / Visual Age suite to an Environment.""" path, _cxx, version = get_xlc(env) if path and _cxx: _cxx = os.path.join(path, _cxx) if 'CXX' not in env: env['CXX'] = _cxx cplusplus.generate(env) if version: env['CXXVERSION'] = version def exists(env): path, _cxx, version = get_xlc(env) if path and _cxx: xlc = os.path.join(path, _cxx) if os.path.exists(xlc): return xlc return None # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
IljaGrebel/OpenWrt-SDK-imx6_HummingBoard
staging_dir/host/lib/scons-2.3.5/SCons/Tool/aixc++.py
Python
gpl-2.0
2,413
import connman import bluetooth import systemd import sys import pexpect import json RUNNING_IN_KODI = True # XBMC Modules try: import xbmc import xbmcgui import xbmcaddon except: RUNNING_IN_KODI = False DEVICE_PATH = 'org.bluez.Device1' PAIRING_AGENT = 'osmc_bluetooth_agent.py' BLUETOOTH_SERVICE = 'bluetooth.service' PEXPECT_SOL = 'SOL@' PEXPECT_EOL = '@EOL' def log(message): msg_str='OSMC_BLUETOOTH - ' + str(message) if RUNNING_IN_KODI: xbmc.log(msg_str, level=xbmc.LOGDEBUG) else: print(msg_str) def is_bluetooth_available(): return connman.is_technology_available('bluetooth') def is_bluetooth_enabled(): connman_status = connman.is_technology_enabled('bluetooth') service_status = systemd.is_service_running(BLUETOOTH_SERVICE) return connman_status and service_status def toggle_bluetooth_state(state): if state: if not systemd.is_service_running(BLUETOOTH_SERVICE): systemd.toggle_service(BLUETOOTH_SERVICE, state) connman.toggle_technology_state('bluetooth', state) else: connman.toggle_technology_state('bluetooth', state) def get_adapter_property(key): return bluetooth.get_adapter_property(key) def set_adapter_property(key, value): bluetooth.set_adapter_property(key, value) def is_discovering(): return bluetooth.get_adapter_property('Discovering') def start_discovery(): bluetooth.start_discovery() def stop_discovery(): bluetooth.stop_discovery() def list_paired_devices(): return list_devices('Paired', True) def list_discovered_devices(): # assuming discovered device are non paired return list_devices('Paired', False) def get_device_property(deviceAddress, key): return bluetooth.get_device_property(deviceAddress, key) def set_device_property(deviceAddress, key, value): bluetooth.set_device_property(deviceAddress, key, value) def is_device_paired(deviceAddress): return bluetooth.get_device_property(deviceAddress, 'Paired') def remove_device(deviceAddress): bluetooth.remove_device(deviceAddress) def is_device_trusted(deviceAddress): return bluetooth.get_device_property(deviceAddress, 'Trusted') def set_device_trusted(deviceAddress, value): set_device_property(deviceAddress,'Trusted', value) def is_device_connected(deviceAddress): return bluetooth.get_device_property(deviceAddress, 'Connected') def connect_device(deviceAddress): bluetooth.connect_device(deviceAddress) def disconnect_device(deviceAddress): bluetooth.disconnect_device(deviceAddress) ''' returns a dictionary with the key being the device address and value being a dictionary of device information ''' def list_devices(filterkey=None, expectedvalue=None): devices = {} managed_objects = bluetooth.get_managed_objects() for path in managed_objects.keys(): if path.startswith('/org/bluez/hci') and DEVICE_PATH in managed_objects[path].keys(): dbus_dict = managed_objects[path][DEVICE_PATH] device_dict = {} # remove dbus.String from the key for key in dbus_dict: device_dict[str(key)] = dbus_dict[key] if filterkey == None or device_dict[filterkey] == expectedvalue: devices[str(device_dict['Address'])] = device_dict return devices def encode_return(result, messages): return_value = {result : messages} return PEXPECT_SOL+ json.dumps(return_value) + PEXPECT_EOL def pair_device(deviceAddress, scriptBasePath = ''): script_path = scriptBasePath + PAIRING_AGENT script = str.join(' ', [sys.executable, script_path,deviceAddress]) child = pexpect.spawn(script) paired = False while True: try: index = child.expect(['@EOL'], timeout=None) split = child.before.split('SOL@') if len(split[0]) >0: log('Output From Pairing Agent ' + split[0]) d = json.loads(split[1]) return_value = d.keys()[0] messages = d.values()[0] log(['return_value = '+ return_value, 'Messages = ' + str(messages)]) if return_value == 'PAIRING_OK': paired = True break if return_value == 'DEVICE_NOT_FOUND': return False # return early no need to call remove_device() if RUNNING_IN_KODI: deviceAlias = get_device_property(deviceAddress, 'Alias') returnValue = handleAgentInteraction(deviceAlias, return_value , messages) if returnValue: if returnValue == 'NO_PIN_ENTERED': return False sendStr = encode_return('RETURN_VALUE', [ returnValue ]) child.sendline(sendStr) except pexpect.EOF: break if not paired: bluetooth.remove_device(deviceAddress) return False return True def handleAgentInteraction(deviceAlias, command , messages): supported_commands = ['NOTIFICATION', 'YESNO_INPUT', 'NUMERIC_INPUT'] if not command in supported_commands: return None # This method is only called when we are running in Kodi dialog = xbmcgui.Dialog() # 'Bluetooth Pairing' heading = lang(32026) if messages[0] == 'ENTER_PIN': # 'Please enter the following on the device' message = lang(32027) + ' ' + messages[1] if messages[0] == 'AUTHORIZE_SERVICE': # 'Authorize Service ' ' on device ' message = lang(32027) + ' ' + messages[0] + ' ' + lang(32029) + ' ' + deviceAddress if messages[0] == 'REQUEST_PIN': # 'Enter PIN to Pair with' message = lang(32030) + ' ' + deviceAlias if messages[0] == 'CONFIRM_PASSKEY': # 'Confirm passkey' 'for' message = lang(32031)+ ' ' +messages[0] + ' ' + lang(32032) + ' ' + deviceAlias if command == 'NOTIFICATION': xbmc.executebuiltin("XBMC.Notification(%s,%s,%s)" % (heading, message, "10000")) if command == 'YESNO_DIALOGUE': if dialog.yesno(heading, message): return 'YES' return 'NO' if command == 'NUMERIC_INPUT': value = dialog.numeric(0, message) if len(value) == 0: value = 'NO_PIN_ENTERED' return value return None def lang(id): addon = xbmcaddon.Addon('script.module.osmcsetting.networking') san =addon.getLocalizedString(id).encode( 'utf-8', 'ignore' ) return san
ActionAdam/osmc
package/mediacenter-addon-osmc/src/script.module.osmcsetting.networking/resources/lib/osmc_bluetooth.py
Python
gpl-2.0
6,660
# Sketch - A Python-based interactive drawing program # Copyright (C) 1997, 1998, 1999, 2001, 2002 by Bernhard Herzog # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # A dialog for specifying line properties # import operator from X import LineDoubleDash from Sketch.const import JoinMiter, JoinBevel, JoinRound,\ CapButt, CapProjecting, CapRound from Sketch.Lib import util from Sketch import _, Trafo, SimpleGC, SolidPattern, EmptyPattern, \ StandardDashes, StandardArrows, StandardColors from Tkinter import Frame, Label, IntVar, LEFT, X, E, W, GROOVE from tkext import ColorButton, UpdatedCheckbutton, MyOptionMenu2 from sketchdlg import StylePropertyPanel from lengthvar import create_length_entry import skpixmaps pixmaps = skpixmaps.PixmapTk def create_bitmap_image(tk, name, bitmap): data = util.xbm_string(bitmap) tk.call(('image', 'create', 'bitmap', name, '-foreground', 'black', '-data', data, '-maskdata', data)) return name _thickness = 3 _width = 90 def draw_dash_bitmap(gc, dashes): scale = float(_thickness) if dashes: dashes = map(operator.mul, dashes, [scale] * len(dashes)) dashes = map(int, map(round, dashes)) for idx in range(len(dashes)): length = dashes[idx] if length <= 0: dashes[idx] = 1 elif length > 255: dashes[idx] = 255 else: dashes = [_width + 10, 1] gc.SetDashes(dashes) gc.DrawLine(0, _thickness / 2, _width, _thickness / 2) def create_dash_images(tk, tkwin, dashes): bitmap = tkwin.CreatePixmap(_width, _thickness, 1) gc = bitmap.CreateGC(foreground = 1, background = 0, line_style = LineDoubleDash, line_width = _thickness) images = [] for dash in dashes: draw_dash_bitmap(gc, dash) image = create_bitmap_image(tk, 'dash_' + `len(images)`, bitmap) images.append((image, dash)) return gc, bitmap, images _arrow_width = 31 _arrow_height = 25 _mirror = Trafo(-1, 0, 0, 1, 0, 0) def draw_arrow_bitmap(gc, arrow, which = 2): gc.gc.foreground = 0 gc.gc.FillRectangle(0, 0, _arrow_width + 1, _arrow_height + 1) gc.gc.foreground = 1 y = _arrow_height / 2 if which == 1: gc.PushTrafo() gc.Concat(_mirror) gc.DrawLineXY(0, 0, -1000, 0) if arrow is not None: arrow.Draw(gc) if which == 1: gc.PopTrafo() def create_arrow_images(tk, tkwin, arrows): arrows = [None] + arrows bitmap = tkwin.CreatePixmap(_arrow_width, _arrow_height, 1) gc = SimpleGC() gc.init_gc(bitmap, foreground = 1, background = 0, line_width = 3) gc.Translate(_arrow_width / 2, _arrow_height / 2) gc.Scale(2) images1 = [] for arrow in arrows: draw_arrow_bitmap(gc, arrow, 1) image = create_bitmap_image(tk, 'arrow1_' + `len(images1)`, bitmap) images1.append((image, arrow)) images2 = [] for arrow in arrows: draw_arrow_bitmap(gc, arrow, 2) image = create_bitmap_image(tk, 'arrow2_' + `len(images2)`, bitmap) images2.append((image, arrow)) return gc, bitmap, images1, images2 class LinePanel(StylePropertyPanel): title = _("Line Style") def __init__(self, master, main_window, doc): StylePropertyPanel.__init__(self, master, main_window, doc, name = 'linedlg') def build_dlg(self): top = self.top button_frame = self.create_std_buttons(top) button_frame.grid(row = 5, columnspan = 2, sticky = 'ew') color_frame = Frame(top, relief = GROOVE, bd = 2) color_frame.grid(row = 0, columnspan = 2, sticky = 'ew') label = Label(color_frame, text = _("Color")) label.pack(side = LEFT, expand = 1, anchor = E) self.color_but = ColorButton(color_frame, width = 3, height = 1, command = self.set_line_color) self.color_but.SetColor(StandardColors.black) self.color_but.pack(side = LEFT, expand = 1, anchor = W) self.var_color_none = IntVar(top) check = UpdatedCheckbutton(color_frame, text = _("None"), variable = self.var_color_none, command = self.do_apply) check.pack(side = LEFT, expand = 1) width_frame = Frame(top, relief = GROOVE, bd = 2) width_frame.grid(row = 1, columnspan = 2, sticky = 'ew') label = Label(width_frame, text = _("Width")) label.pack(side = LEFT, expand = 1, anchor = E) self.var_width = create_length_entry(top, width_frame, self.set_line_width, scroll_pad = 0) tkwin = self.main_window.canvas.tkwin gc, bitmap, dashlist = create_dash_images(self.top.tk, tkwin, StandardDashes()) self.opt_dash = MyOptionMenu2(top, dashlist, command = self.set_dash, entry_type = 'image', highlightthickness = 0) self.opt_dash.grid(row = 2, columnspan = 2, sticky = 'ew', ipady = 2) self.dash_gc = gc self.dash_bitmap = bitmap gc, bitmap, arrow1, arrow2 = create_arrow_images(self.top.tk, tkwin, StandardArrows()) self.opt_arrow1 = MyOptionMenu2(top, arrow1, command = self.set_arrow, args = 1, entry_type = 'image', highlightthickness = 0) self.opt_arrow1.grid(row = 3, column = 0, sticky = 'ew', ipady = 2) self.opt_arrow2 = MyOptionMenu2(top, arrow2, command = self.set_arrow, args = 2, entry_type = 'image', highlightthickness = 0) self.opt_arrow2.grid(row = 3, column = 1, sticky = 'ew', ipady = 2) self.arrow_gc = gc self.arrow_bitmap = bitmap self.opt_join = MyOptionMenu2(top, [(pixmaps.JoinMiter, JoinMiter), (pixmaps.JoinRound, JoinRound), (pixmaps.JoinBevel, JoinBevel)], command = self.set_line_join, entry_type = 'bitmap', highlightthickness = 0) self.opt_join.grid(row = 4, column = 0, sticky = 'ew') self.opt_cap = MyOptionMenu2(top, [(pixmaps.CapButt, CapButt), (pixmaps.CapRound, CapRound), (pixmaps.CapProjecting, CapProjecting)], command = self.set_line_cap, entry_type = 'bitmap', highlightthickness = 0) self.opt_cap.grid(row = 4, column = 1, sticky = 'ew') self.opt_cap.SetValue(None) def close_dlg(self): StylePropertyPanel.close_dlg(self) self.var_width = None def init_from_style(self, style): if style.HasLine(): self.var_color_none.set(0) self.opt_join.SetValue(style.line_join) self.opt_cap.SetValue(style.line_cap) self.color_but.SetColor(style.line_pattern.Color()) self.var_width.set(style.line_width) self.init_dash(style) self.init_arrow(style) else: self.var_color_none.set(1) def init_from_doc(self): self.Update() def Update(self): if self.document.HasSelection(): properties = self.document.CurrentProperties() self.init_from_style(properties) def do_apply(self): kw = {} if not self.var_color_none.get(): color = self.color_but.Color() kw["line_pattern"] = SolidPattern(color) kw["line_width"] = self.var_width.get() kw["line_join"] = self.opt_join.GetValue() kw["line_cap"] = self.opt_cap.GetValue() kw["line_dashes"] = self.opt_dash.GetValue() kw["line_arrow1"] = self.opt_arrow1.GetValue() kw["line_arrow2"] = self.opt_arrow2.GetValue() else: kw["line_pattern"] = EmptyPattern self.set_properties(_("Set Outline"), 'line', kw) def set_line_join(self, *args): self.document.SetProperties(line_join = self.opt_join.GetValue(), if_type_present = 1) def set_line_cap(self, *args): self.document.SetProperties(line_cap = self.opt_cap.GetValue(), if_type_present = 1) def set_line_color(self): self.document.SetLineColor(self.color_but.Color()) def set_line_width(self, *rest): self.document.SetProperties(line_width = self.var_width.get(), if_type_present = 1) def set_dash(self, *args): self.document.SetProperties(line_dashes = self.opt_dash.GetValue(), if_type_present = 1) def init_dash(self, style): dashes = style.line_dashes draw_dash_bitmap(self.dash_gc, dashes) dash_image = create_bitmap_image(self.top.tk, 'dash_image', self.dash_bitmap) self.opt_dash.SetValue(dashes, dash_image) def set_arrow(self, arrow, which): if which == 1: self.document.SetProperties(line_arrow1 = arrow, if_type_present = 1) else: self.document.SetProperties(line_arrow2 = arrow, if_type_present = 1) def init_arrow(self, style): arrow = style.line_arrow1 draw_arrow_bitmap(self.arrow_gc, arrow, 1) arrow_image = create_bitmap_image(self.top.tk, 'arrow1_image', self.arrow_bitmap) self.opt_arrow1.SetValue(arrow, arrow_image) arrow = style.line_arrow2 draw_arrow_bitmap(self.arrow_gc, arrow, 2) arrow_image = create_bitmap_image(self.top.tk, 'arrow2_image', self.arrow_bitmap) self.opt_arrow2.SetValue(arrow, arrow_image) def update_from_object_cb(self, obj): if obj is not None: self.init_from_style(obj.Properties())
shumik/skencil-c
Sketch/UI/linedlg.py
Python
gpl-2.0
11,272
from openerp import models,fields class OeMedicalMedicamentCategory(models.Model): _name = 'oemedical.medicament.category' childs = fields.One2many('oemedical.medicament.category', 'parent_id', string='Children', ) name = fields.Char(size=256, string='Name', required=True) parent_id = fields.Many2one('oemedical.medicament.category', string='Parent', select=True) _constraints = [ (models.Model._check_recursion, 'Error ! You cannot create recursive \n' 'Category.', ['parent_id']) ]
Manexware/medical
oemedical/oemedical_medicament_category/oemedical_medicament_category.py
Python
gpl-2.0
589
#! /usr/bin/env python # Copyright (C) 2012 dcodix # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source distribution for more information. """ This script will take filenames from the stdin and copy/move them to a directory destination preserving the directory tree and atributes. Most of the functionality is taken from shutil module. """ import os import sys import stat import errno import getopt import argparse from shutil import * import time def copydirtree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False): """This function is a modification of shutil copytree which only copy the directories of a tree but not the files or links. """ names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored_names = set() os.makedirs(dst) errors = [] for name in names: if name in ignored_names: continue srcname = os.path.join(src, name) dstname = os.path.join(dst, name) if os.path.isdir(srcname): copydirtree(srcname, dstname, symlinks, ignore, copy_function) else: continue try: copystat(src, dst) except OSError as why: if WindowsError is not None and isinstance(why, WindowsError): # Copying file access times may fail on Windows pass else: errors.extend((src, dst, str(why))) if errors: raise Error(errors) def printmessage(logstring): print('['+str(time.time())+'] '+logstring) def verbosemessage(logstring): if verbose: printmessage(logstring) def debugmessage(logstring): if debuging: printmessage(logstring) def main(): scriptname = 'mv-elsewhere.py' dst = '' filemove = False override = False readstdin = True global verbose global debuging verbose = False debuging = False exclude = '' excludelist = '' #GET ARGS parser = argparse.ArgumentParser(description='Move files') parser.add_argument('-d', '--destdir', nargs=1, help='destination directory') parser.add_argument('-D', '--debuging', help='debug', action="store_true") parser.add_argument('-m', '--move', help='move instead of copy', action="store_true") parser.add_argument('-o', '--override', help='override in destination', action="store_true") parser.add_argument('-v', '--verbose', help='verbose', action="store_true") parser.add_argument('-e', '--exclude', nargs='+', help='esclude list') args = parser.parse_args() if args.destdir: dst = args.destdir[0] if args.debuging: verbose = True debuging = True if args.move: filemove = True if args.override: override = True if args.verbose: verbose = True if args.exclude: excludelist = args.exclude # PROCESS nfiles = 0 while True: excludefile = False if readstdin: #This condition is meant to add the future posibility to read files directly from a file instead of stdin. file1 = sys.stdin.readline() if not file1: break file1 = file1.rstrip() debugmessage('file '+file1) fpath = os.path.dirname(file1) if len(fpath) == 0: fpath = file1 if debuging: print('fpath '+fpath) if len(excludelist) != 0: for exclude in excludelist: if exclude in file1: excludefile = True debugmessage('file '+file1+' will be excluded') dfile = dst + '/' + file1 dpath = dst + '/' + fpath if not os.path.isdir(dpath): verbosemessage('COPYNG TREE: from '+fpath+' to '+dpath) copydirtree(fpath, dpath) if not os.path.isdir(file1) and not excludefile: if not os.path.exists(dfile) or override: if filemove: verbosemessage('MOVING: '+file1+' to '+dfile) move(file1, dfile) nfiles = nfiles + 1 else: verbosemessage('COPYING: '+file1+' to '+dfile) copy2(file1, dfile) nfiles = nfiles + 1 else: verbosemessage('NOT OVERRIDING: '+dfile) pass else: if excludefile: verbosemessage('EXCLUDED: '+file1) pass if nfiles == 0: printmessage('No files have been moved or copied.') else: if filemove: printmessage(str(nfiles)+' files have been moved.') else: printmessage(str(nfiles)+' files have been copied.') if __name__ == "__main__": main()
dcodix/mv-elsewhere
mv-elsewhere.py
Python
gpl-2.0
5,068
from typing import Any, Dict, Optional from flask import g, render_template, url_for from flask_babel import format_number, lazy_gettext as _ from flask_wtf import FlaskForm from wtforms import ( BooleanField, IntegerField, SelectMultipleField, StringField, SubmitField, widgets) from wtforms.validators import InputRequired from openatlas import app from openatlas.forms.field import TableField from openatlas.models.entity import Entity from openatlas.models.network import Network from openatlas.util.table import Table from openatlas.util.util import link, required_group, uc_first class LinkCheckForm(FlaskForm): # type: ignore cidoc_domain = TableField('Domain', [InputRequired()]) cidoc_property = TableField('Property', [InputRequired()]) cidoc_range = TableField('Range', [InputRequired()]) save = SubmitField(uc_first(_('test'))) @app.route('/overview/model', methods=["GET", "POST"]) @required_group('readonly') def model_index() -> str: form = LinkCheckForm() form_classes = \ {code: f'{code} {class_.name}' for code, class_ in g.cidoc_classes.items()} form.cidoc_domain.choices = form_classes form.cidoc_range.choices = form_classes form.cidoc_property.choices = { code: f'{code} {property_.name}' for code, property_ in g.properties.items()} result = None if form.validate_on_submit(): domain = g.cidoc_classes[form.cidoc_domain.data] range_ = g.cidoc_classes[form.cidoc_range.data] property_ = g.properties[form.cidoc_property.data] result = { 'domain': domain, 'property': property_, 'range': range_, 'domain_valid': property_.find_object( 'domain_class_code', domain.code), 'range_valid': property_.find_object( 'range_class_code', range_.code)} return render_template( 'model/index.html', form=form, result=result, title=_('model'), crumbs=[_('model')]) @app.route('/overview/model/class/<code>') @required_group('readonly') def class_entities(code: str) -> str: table = Table( ['name'], rows=[[link(entity)] for entity in Entity.get_by_cidoc_class(code)]) return render_template( 'table.html', table=table, title=_('model'), crumbs=[ [_('model'), url_for('model_index')], [_('classes'), url_for('class_index')], link(g.cidoc_classes[code]), _('entities')]) @app.route('/overview/model/class') @required_group('readonly') def class_index() -> str: table = Table( ['code', 'name', 'count'], defs=[ {'className': 'dt-body-right', 'targets': 2}, {'orderDataType': 'cidoc-model', 'targets': [0]}, {'sType': 'numeric', 'targets': [0]}]) for class_ in g.cidoc_classes.values(): count = '' if class_.count: count = format_number(class_.count) if class_.code not in ['E53', 'E41', 'E82']: count = link( format_number(class_.count), url_for('class_entities', code=class_.code)) table.rows.append([link(class_), class_.name, count]) return render_template( 'table.html', table=table, title=_('model'), crumbs=[[_('model'), url_for('model_index')], _('classes')]) @app.route('/overview/model/property') @required_group('readonly') def property_index() -> str: classes = g.cidoc_classes properties = g.properties table = Table( [ 'code', 'name', 'inverse', 'domain', 'domain name', 'range', 'range name', 'count'], defs=[ {'className': 'dt-body-right', 'targets': 7}, {'orderDataType': 'cidoc-model', 'targets': [0, 3, 5]}, {'sType': 'numeric', 'targets': [0]}]) for property_ in properties.values(): table.rows.append([ link(property_), property_.name, property_.name_inverse, link(classes[property_.domain_class_code]), classes[property_.domain_class_code].name, link(classes[property_.range_class_code]), classes[property_.range_class_code].name, format_number(property_.count) if property_.count else '']) return render_template( 'table.html', table=table, title=_('model'), crumbs=[[_('model'), url_for('model_index')], _('properties')]) @app.route('/overview/model/class_view/<code>') @required_group('readonly') def class_view(code: str) -> str: class_ = g.cidoc_classes[code] tables = {} for table in ['super', 'sub']: tables[table] = Table(paging=False, defs=[ {'orderDataType': 'cidoc-model', 'targets': [0]}, {'sType': 'numeric', 'targets': [0]}]) for code_ in getattr(class_, table): tables[table].rows.append( [link(g.cidoc_classes[code_]), g.cidoc_classes[code_].name]) tables['domains'] = Table(paging=False, defs=[ {'orderDataType': 'cidoc-model', 'targets': [0]}, {'sType': 'numeric', 'targets': [0]}]) tables['ranges'] = Table(paging=False, defs=[ {'orderDataType': 'cidoc-model', 'targets': [0]}, {'sType': 'numeric', 'targets': [0]}]) for property_ in g.properties.values(): if class_.code == property_.domain_class_code: tables['domains'].rows.append([link(property_), property_.name]) elif class_.code == property_.range_class_code: tables['ranges'].rows.append([link(property_), property_.name]) return render_template( 'model/class_view.html', class_=class_, tables=tables, info={'code': class_.code, 'name': class_.name}, title=_('model'), crumbs=[ [_('model'), url_for('model_index')], [_('classes'), url_for('class_index')], class_.code]) @app.route('/overview/model/property_view/<code>') @required_group('readonly') def property_view(code: str) -> str: property_ = g.properties[code] domain = g.cidoc_classes[property_.domain_class_code] range_ = g.cidoc_classes[property_.range_class_code] info = { 'code': property_.code, 'name': property_.name, 'inverse': property_.name_inverse, 'domain': f'{link(domain)} {domain.name}', 'range': f'{link(range_)} {range_.name}'} tables = {} for table in ['super', 'sub']: tables[table] = Table(paging=False, defs=[ {'orderDataType': 'cidoc-model', 'targets': [0]}, {'sType': 'numeric', 'targets': [0]}]) for code_ in getattr(property_, table): tables[table].rows.append( [link(g.properties[code_]), g.properties[code_].name]) return render_template( 'model/property_view.html', tables=tables, property_=property_, info=info, title=_('model'), crumbs=[ [_('model'), url_for('model_index')], [_('properties'), url_for('property_index')], property_.code]) class NetworkForm(FlaskForm): # type: ignore width = IntegerField(default=1200, validators=[InputRequired()]) height = IntegerField(default=600, validators=[InputRequired()]) charge = StringField(default=-80, validators=[InputRequired()]) distance = IntegerField(default=80, validators=[InputRequired()]) orphans = BooleanField(default=False) classes = SelectMultipleField( _('classes'), widget=widgets.ListWidget(prefix_label=False)) @app.route('/overview/network/', methods=["GET", "POST"]) @app.route('/overview/network/<int:dimensions>', methods=["GET", "POST"]) @required_group('readonly') def model_network(dimensions: Optional[int] = None) -> str: network_classes = [class_ for class_ in g.classes.values() if class_.color] for class_ in network_classes: setattr(NetworkForm, class_.name, StringField( default=class_.color, render_kw={'data-huebee': True, 'class': 'data-huebee'})) setattr(NetworkForm, 'save', SubmitField(_('apply'))) form = NetworkForm() form.classes.choices = [] params: Dict[str, Any] = { 'classes': {}, 'options': { 'orphans': form.orphans.data, 'width': form.width.data, 'height': form.height.data, 'charge': form.charge.data, 'distance': form.distance.data}} for class_ in network_classes: if class_.name == 'object_location': continue form.classes.choices.append((class_.name, class_.label)) return render_template( 'model/network2.html' if dimensions else 'model/network.html', form=form, dimensions=dimensions, network_params=params, json_data=Network.get_network_json(form, dimensions), title=_('model'), crumbs=[_('network visualization')])
craws/OpenAtlas-Python
openatlas/views/model.py
Python
gpl-2.0
9,096
#!/usr/bin/env python #-------------------------------------------------------------------------- # flo2_pid.py # Rick Kauffman a.k.a. Chewie # # Hewlett Packard Company Revision: 1.0 # ~~~~~~~~~ WookieWare ~~~~~~~~~~~~~ # Change history....09/03/2014 # # ##-------------------------------------------------------------------------- # Initial release - Pulls VARS from webform. # build a database of all dpids not in glarn # Calls glarn chooser deletes dpids # # #------Might not need this but please they are handy------------------------ # # Do the imports!!!! #----------------------If you dont have it use "apt-get install (name)" import sys import subprocess import cgi import cgitb; cgitb.enable() import hpsdnclient as hp import sqlite3 import requests from requests.auth import HTTPDigestAuth import xml.etree.ElementTree as xml # import pdb; pdb.set_trace() #------------------------------------------------------------------------- # Get the field VARS from the calling HTML form #------------------------------------------------------------------------- form = cgi.FieldStorage() server = form.getvalue('server') user = form.getvalue('user') passw = form.getvalue('passw') imc_server = form.getvalue('imc_server') imc_user = form.getvalue('imc_user') imc_passw = form.getvalue('imc_passw') pid_list = form.getvalue('list_o_pids') imc = form.getvalue('imc') if pid_list == None: print "Content-type:text/html\r\n\r\n" print "<!DOCTYPE html>" print "<html>" print "<head>" print "<title> Wookieware.com</title>" print "<link rel=\"stylesheet\" type\"text/css\" href=\"../../css/corex.css\"/>" print "<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js\"></script>" print "</head>" print "<body>" print "<h1> <img src=\"../../images/glarn.png\" width=\"50\" height=\"50\">glarn: The dpid database</h1>" print "<HR> " print "<h1> No items selected</h1>" print "<FORM method='post' ACTION=\"./pid_main.py\">" print "<h3> List is empty </h3>" print "<p> Click button below to go back to the system chooser</p>" print "<hr>" print "<input type=\"submit\" style=\"font-face: 'Arial'; font-size: larger; color: black; background-color: #0066FF; border: 3pt ridge lightgrey\" value=\" Main Menu\">" print "<input type=\"hidden\" name=\"server\" value=%s>" % (server) print "<input type=\"hidden\" name=\"user\" value=%s>" % (user) print "<input type=\"hidden\" name=\"passw\" value=%s>" % (passw) print "<input type=\"hidden\" name=\"imc_server\" value=%s>" % (imc_server) print "<input type=\"hidden\" name=\"imc_user\" value=%s>" % (imc_user) print "<input type=\"hidden\" name=\"imc_passw\" value=%s>" % (imc_passw) print "<input type=\"hidden\" name=\"imc\" value=%s>" % (imc) print "<p>For more information on how to use this application <a href=\"/faq.html\">User Guide</a></p>" print "<center><font face=\"Arial\" size=\"1\">SDN Solutions From WookieWare 2014</font></center>" print "</body>" print "</html>" #glarn.close() sys.exit() x = len(pid_list) # Keep track of how many items we need to process # Check to see if anything was chozen. If x is zero goto Nothing Selected page and exit j = 0 #Create authorization Token for the SDN controller auth = hp.XAuthToken(user=user,password=passw,server=server) api=hp.Api(controller=server,auth=auth) #-------------------------------------------------------------------------- # dpid factory: Break up dpis and match to vendor to determin MAC address #--------------------------------------------------------------------------- print "Content-type:text/html\r\n\r\n" print "<!DOCTYPE html>" print "<html>" print "<head>" print "<title> Wookieware.com</title>" print "<link rel=\"stylesheet\" type\"text/css\" href=\"../../css/corex.css\"/>" print "<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js\"></script>" print "</head>" print "<body>" print "<h1> <img src=\"../../images/glarn.png\" width=\"50\" height=\"50\">glarn: The dpid database</h1>" print "<HR> " print "<h3> Dpid flows display</h3>" print "<p>List of current flows by dpid" print "<FORM method='post' ACTION=\"./pid_main.py\">" # Delete records in database if x == 23:#only one entry (dpids are 23 chars long) try: flows = api.get_flows(pid_list) print "<h1>Flows for dpid %s:</h1>" % (pid_list) print "<table border=\"1\" cellpadding=\"3\" class=\"TFtable\">" print "<tr> <td> Host MAC address </td> <td> Destination MAC address </td> <td> Output Port </td> </tr>" for f in flows: eth_src = f.match.eth_src eth_dst = f.match.eth_dst action = f.actions.output print "<tr> <td> %s </td> <td> %s </td> <td> %s </td> </tr>" % (eth_src, eth_dst, action) print "</table>" except: print "<h1>Error getting dpid information %s</h1>" % (pid_list) elif j == 0: for i in pid_list: flows = api.get_flows(i) print "<h1>Flows for dpid %s:</h1>" % (i) print "<table border=\"1\" cellpadding=\"3\" class=\"TFtable\">" print "<tr> <td> Host MAC address </td> <td> Destination MAC address </td> <td> Output Port </td> </tr>" for f in flows: eth_src = f.match.eth_src eth_dst = f.match.eth_dst action = f.actions.output print "<tr> <td> %s </td> <td> %s </td> <td> %s </td> </tr>" % (eth_src, eth_dst, action) print "</table>" #-------------------------------------------------------------------------- # Finish manual or go home #--------------------------------------------------------------------------- #print "Content-type:text/html\r\n\r\n" #print "<!DOCTYPE html>" #print "<html>" #print "<head>" #print "<title> Wookieware.com</title>" #print "<link rel=\"stylesheet\" type\"text/css\" href=\"../../css/corex.css\"/>" #print "<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js\"></script>" #print "</head>" print "<HR>" print "<input type=\"submit\" style=\"font-face: 'Arial'; font-size: larger; color: black; background-color: #0066FF; border: 3pt ridge lightgrey\" value=\" Main Menu\">" print "<input type=\"hidden\" name=\"server\" value=%s>" % (server) print "<input type=\"hidden\" name=\"user\" value=%s>" % (user) print "<input type=\"hidden\" name=\"passw\" value=%s>" % (passw) print "<input type=\"hidden\" name=\"imc_server\" value=%s>" % (imc_server) print "<input type=\"hidden\" name=\"imc_user\" value=%s>" % (imc_user) print "<input type=\"hidden\" name=\"imc_passw\" value=%s>" % (imc_passw) print "<input type=\"hidden\" name=\"imc\" value=%s>" % (imc) print "</form>" print "<footer>" print "<p>For more information on how to use this application <a href=\"/faq.html\">User Guide</a></p>" print "<a href=\"/index.html\">BACK</a>" print "<center><font face=\"Arial\" size=\"1\">SDN Solutions From WookieWare 2014</font></center>" print "</footer>" print "</body>" print "</html>" sys.exit()
xod442/sample_scripts
flo2_pid.py
Python
gpl-2.0
7,035
#encoding=utf8 from rest_framework import permissions from django.contrib import messages from copy import deepcopy from rest_framework.permissions import * def own_object_permission(field_name): class P(permissions.BasePermission): def has_object_permission(self, request, view, obj): print hasattr(obj, field_name) and getattr(obj, field_name) == request.user if hasattr(obj, field_name) and getattr(obj, field_name) == request.user: return True else: return False return P def own_object_or_superuser_permission(field_name): class P(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.user.is_superuser or hasattr(obj, field_name) and getattr(obj, field_name) == request.user: return True else: return False return P def custom_perms_map(perms_map): perms = deepcopy(DjangoModelPermissionsOrAnonReadOnly.perms_map) perms.update(perms_map) class P(DjangoModelPermissionsOrAnonReadOnly): perms_map = perms return P def custom_perm(perm): class P(BasePermission): def has_permission(self, request, view): result = request.user.is_authenticated() and request.user.has_perm(perm) if not result: messages.warning(request._request, u'啊哦,亲~这里不允许访问啵~你要有更厉害的权限才行哟') return result return P
hsfzxjy/wisecitymbc
common/rest/permissions.py
Python
gpl-2.0
1,542
# This file is part of Scapy # Copyright (C) 2007, 2008, 2009 Arnaud Ebalard # 2015, 2016, 2017 Maxence Tury # This program is published under a GPLv2 license """ TLS handshake fields & logic. This module covers the handshake TLS subprotocol, except for the key exchange mechanisms which are addressed with keyexchange.py. """ from __future__ import absolute_import import math import struct from scapy.error import log_runtime, warning from scapy.fields import ByteEnumField, ByteField, EnumField, Field, \ FieldLenField, IntField, PacketField, PacketListField, ShortField, \ StrFixedLenField, StrLenField, ThreeBytesField, UTCTimeField from scapy.compat import hex_bytes, orb, raw from scapy.config import conf from scapy.modules import six from scapy.packet import Packet, Raw, Padding from scapy.utils import randstring, repr_hex from scapy.layers.x509 import OCSP_Response from scapy.layers.tls.cert import Cert from scapy.layers.tls.basefields import (_tls_version, _TLSVersionField, _TLSClientVersionField) from scapy.layers.tls.extensions import (_ExtensionsLenField, _ExtensionsField, _cert_status_type, TLS_Ext_SupportedVersion_CH, # noqa: E501 TLS_Ext_SignatureAlgorithms, TLS_Ext_SupportedVersion_SH, TLS_Ext_EarlyDataIndication) from scapy.layers.tls.keyexchange import (_TLSSignature, _TLSServerParamsField, _TLSSignatureField, ServerRSAParams, SigAndHashAlgsField, _tls_hash_sig, SigAndHashAlgsLenField) from scapy.layers.tls.session import (_GenericTLSSessionInheritance, readConnState, writeConnState) from scapy.layers.tls.crypto.compression import (_tls_compression_algs, _tls_compression_algs_cls, Comp_NULL, _GenericComp, _GenericCompMetaclass) from scapy.layers.tls.crypto.suites import (_tls_cipher_suites, _tls_cipher_suites_cls, _GenericCipherSuite, _GenericCipherSuiteMetaclass) ############################################################################### # Generic TLS Handshake message # ############################################################################### _tls_handshake_type = {0: "hello_request", 1: "client_hello", 2: "server_hello", 3: "hello_verify_request", 4: "session_ticket", 6: "hello_retry_request", 8: "encrypted_extensions", 11: "certificate", 12: "server_key_exchange", 13: "certificate_request", 14: "server_hello_done", 15: "certificate_verify", 16: "client_key_exchange", 20: "finished", 21: "certificate_url", 22: "certificate_status", 23: "supplemental_data", 24: "key_update"} class _TLSHandshake(_GenericTLSSessionInheritance): """ Inherited by other Handshake classes to get post_build(). Also used as a fallback for unknown TLS Handshake packets. """ name = "TLS Handshake Generic message" fields_desc = [ByteEnumField("msgtype", None, _tls_handshake_type), ThreeBytesField("msglen", None), StrLenField("msg", "", length_from=lambda pkt: pkt.msglen)] def post_build(self, p, pay): tmp_len = len(p) if self.msglen is None: l2 = tmp_len - 4 p = struct.pack("!I", (orb(p[0]) << 24) | l2) + p[4:] return p + pay def guess_payload_class(self, p): return conf.padding_layer def tls_session_update(self, msg_str): """ Covers both post_build- and post_dissection- context updates. """ self.tls_session.handshake_messages.append(msg_str) self.tls_session.handshake_messages_parsed.append(self) ############################################################################### # HelloRequest # ############################################################################### class TLSHelloRequest(_TLSHandshake): name = "TLS Handshake - Hello Request" fields_desc = [ByteEnumField("msgtype", 0, _tls_handshake_type), ThreeBytesField("msglen", None)] def tls_session_update(self, msg_str): """ Message should not be added to the list of handshake messages that will be hashed in the finished and certificate verify messages. """ return ############################################################################### # ClientHello fields # ############################################################################### class _GMTUnixTimeField(UTCTimeField): """ "The current time and date in standard UNIX 32-bit format (seconds since the midnight starting Jan 1, 1970, GMT, ignoring leap seconds)." """ def i2h(self, pkt, x): if x is not None: return x return 0 class _TLSRandomBytesField(StrFixedLenField): def i2repr(self, pkt, x): if x is None: return repr(x) return repr_hex(self.i2h(pkt, x)) class _SessionIDField(StrLenField): """ opaque SessionID<0..32>; section 7.4.1.2 of RFC 4346 """ pass class _CipherSuitesField(StrLenField): __slots__ = ["itemfmt", "itemsize", "i2s", "s2i"] islist = 1 def __init__(self, name, default, dico, length_from=None, itemfmt="!H"): StrLenField.__init__(self, name, default, length_from=length_from) self.itemfmt = itemfmt self.itemsize = struct.calcsize(itemfmt) i2s = self.i2s = {} s2i = self.s2i = {} for k in six.iterkeys(dico): i2s[k] = dico[k] s2i[dico[k]] = k def any2i_one(self, pkt, x): if (isinstance(x, _GenericCipherSuite) or isinstance(x, _GenericCipherSuiteMetaclass)): x = x.val if isinstance(x, bytes): x = self.s2i[x] return x def i2repr_one(self, pkt, x): fmt = "0x%%0%dx" % self.itemsize return self.i2s.get(x, fmt % x) def any2i(self, pkt, x): if x is None: return None if not isinstance(x, list): x = [x] return [self.any2i_one(pkt, z) for z in x] def i2repr(self, pkt, x): if x is None: return "None" tmp_len = [self.i2repr_one(pkt, z) for z in x] if len(tmp_len) == 1: tmp_len = tmp_len[0] else: tmp_len = "[%s]" % ", ".join(tmp_len) return tmp_len def i2m(self, pkt, val): if val is None: val = [] return b"".join(struct.pack(self.itemfmt, x) for x in val) def m2i(self, pkt, m): res = [] itemlen = struct.calcsize(self.itemfmt) while m: res.append(struct.unpack(self.itemfmt, m[:itemlen])[0]) m = m[itemlen:] return res def i2len(self, pkt, i): if i is None: return 0 return len(i) * self.itemsize class _CompressionMethodsField(_CipherSuitesField): def any2i_one(self, pkt, x): if (isinstance(x, _GenericComp) or isinstance(x, _GenericCompMetaclass)): x = x.val if isinstance(x, str): x = self.s2i[x] return x ############################################################################### # ClientHello # ############################################################################### class TLSClientHello(_TLSHandshake): """ TLS ClientHello, with abilities to handle extensions. The Random structure follows the RFC 5246: while it is 32-byte long, many implementations use the first 4 bytes as a gmt_unix_time, and then the remaining 28 byts should be completely random. This was designed in order to (sort of) mitigate broken RNGs. If you prefer to show the full 32 random bytes without any GMT time, just comment in/out the lines below. """ name = "TLS Handshake - Client Hello" fields_desc = [ByteEnumField("msgtype", 1, _tls_handshake_type), ThreeBytesField("msglen", None), _TLSClientVersionField("version", None, _tls_version), # _TLSRandomBytesField("random_bytes", None, 32), _GMTUnixTimeField("gmt_unix_time", None), _TLSRandomBytesField("random_bytes", None, 28), FieldLenField("sidlen", None, fmt="B", length_of="sid"), _SessionIDField("sid", "", length_from=lambda pkt: pkt.sidlen), FieldLenField("cipherslen", None, fmt="!H", length_of="ciphers"), _CipherSuitesField("ciphers", None, _tls_cipher_suites, itemfmt="!H", length_from=lambda pkt: pkt.cipherslen), FieldLenField("complen", None, fmt="B", length_of="comp"), _CompressionMethodsField("comp", [0], _tls_compression_algs, itemfmt="B", length_from=lambda pkt: pkt.complen), # noqa: E501 _ExtensionsLenField("extlen", None, length_of="ext"), _ExtensionsField("ext", None, length_from=lambda pkt: (pkt.msglen - (pkt.sidlen or 0) - # noqa: E501 (pkt.cipherslen or 0) - # noqa: E501 (pkt.complen or 0) - # noqa: E501 40))] def post_build(self, p, pay): if self.random_bytes is None: p = p[:10] + randstring(28) + p[10 + 28:] # if no ciphersuites were provided, we add a few usual, supported # ciphersuites along with the appropriate extensions if self.ciphers is None: cipherstart = 39 + (self.sidlen or 0) s = b"001ac02bc023c02fc027009e0067009c003cc009c0130033002f000a" p = p[:cipherstart] + hex_bytes(s) + p[cipherstart + 2:] if self.ext is None: ext_len = b'\x00\x2c' ext_reneg = b'\xff\x01\x00\x01\x00' ext_sn = b'\x00\x00\x00\x0f\x00\r\x00\x00\nsecdev.org' ext_sigalg = b'\x00\r\x00\x08\x00\x06\x04\x03\x04\x01\x02\x01' ext_supgroups = b'\x00\n\x00\x04\x00\x02\x00\x17' p += ext_len + ext_reneg + ext_sn + ext_sigalg + ext_supgroups return super(TLSClientHello, self).post_build(p, pay) def tls_session_update(self, msg_str): """ Either for parsing or building, we store the client_random along with the raw string representing this handshake message. """ super(TLSClientHello, self).tls_session_update(msg_str) s = self.tls_session s.advertised_tls_version = self.version self.random_bytes = msg_str[10:38] s.client_random = (struct.pack('!I', self.gmt_unix_time) + self.random_bytes) # No distinction between a TLS 1.2 ClientHello and a TLS # 1.3 ClientHello when dissecting : TLS 1.3 CH will be # parsed as TLSClientHello if self.ext: for e in self.ext: if isinstance(e, TLS_Ext_SupportedVersion_CH): s.advertised_tls_version = e.versions[0] if isinstance(e, TLS_Ext_SignatureAlgorithms): s.advertised_sig_algs = e.sig_algs class TLS13ClientHello(_TLSHandshake): """ TLS 1.3 ClientHello, with abilities to handle extensions. The Random structure is 32 random bytes without any GMT time """ name = "TLS 1.3 Handshake - Client Hello" fields_desc = [ByteEnumField("msgtype", 1, _tls_handshake_type), ThreeBytesField("msglen", None), _TLSClientVersionField("version", None, _tls_version), _TLSRandomBytesField("random_bytes", None, 32), FieldLenField("sidlen", None, fmt="B", length_of="sid"), _SessionIDField("sid", "", length_from=lambda pkt: pkt.sidlen), FieldLenField("cipherslen", None, fmt="!H", length_of="ciphers"), _CipherSuitesField("ciphers", None, _tls_cipher_suites, itemfmt="!H", length_from=lambda pkt: pkt.cipherslen), FieldLenField("complen", None, fmt="B", length_of="comp"), _CompressionMethodsField("comp", [0], _tls_compression_algs, itemfmt="B", length_from=lambda pkt: pkt.complen), # noqa: E501 _ExtensionsLenField("extlen", None, length_of="ext"), _ExtensionsField("ext", None, length_from=lambda pkt: (pkt.msglen - (pkt.sidlen or 0) - # noqa: E501 (pkt.cipherslen or 0) - # noqa: E501 (pkt.complen or 0) - # noqa: E501 40))] def post_build(self, p, pay): if self.random_bytes is None: p = p[:6] + randstring(32) + p[6 + 32:] return super(TLS13ClientHello, self).post_build(p, pay) def tls_session_update(self, msg_str): """ Either for parsing or building, we store the client_random along with the raw string representing this handshake message. """ super(TLS13ClientHello, self).tls_session_update(msg_str) s = self.tls_session if self.sidlen and self.sidlen > 0: s.sid = self.sid self.random_bytes = msg_str[10:38] s.client_random = self.random_bytes if self.ext: for e in self.ext: if isinstance(e, TLS_Ext_SupportedVersion_CH): self.tls_session.advertised_tls_version = e.versions[0] if isinstance(e, TLS_Ext_SignatureAlgorithms): s.advertised_sig_algs = e.sig_algs ############################################################################### # ServerHello # ############################################################################### class TLSServerHello(_TLSHandshake): """ TLS ServerHello, with abilities to handle extensions. The Random structure follows the RFC 5246: while it is 32-byte long, many implementations use the first 4 bytes as a gmt_unix_time, and then the remaining 28 byts should be completely random. This was designed in order to (sort of) mitigate broken RNGs. If you prefer to show the full 32 random bytes without any GMT time, just comment in/out the lines below. """ name = "TLS Handshake - Server Hello" fields_desc = [ByteEnumField("msgtype", 2, _tls_handshake_type), ThreeBytesField("msglen", None), _TLSVersionField("version", None, _tls_version), # _TLSRandomBytesField("random_bytes", None, 32), _GMTUnixTimeField("gmt_unix_time", None), _TLSRandomBytesField("random_bytes", None, 28), FieldLenField("sidlen", None, length_of="sid", fmt="B"), _SessionIDField("sid", "", length_from=lambda pkt: pkt.sidlen), EnumField("cipher", None, _tls_cipher_suites), _CompressionMethodsField("comp", [0], _tls_compression_algs, itemfmt="B", length_from=lambda pkt: 1), _ExtensionsLenField("extlen", None, length_of="ext"), _ExtensionsField("ext", None, length_from=lambda pkt: (pkt.msglen - (pkt.sidlen or 0) - # noqa: E501 38))] # 40)) ] @classmethod def dispatch_hook(cls, _pkt=None, *args, **kargs): if _pkt and len(_pkt) >= 6: version = struct.unpack("!H", _pkt[4:6])[0] if version == 0x0304 or version > 0x7f00: return TLS13ServerHello return TLSServerHello def post_build(self, p, pay): if self.random_bytes is None: p = p[:10] + randstring(28) + p[10 + 28:] return super(TLSServerHello, self).post_build(p, pay) def tls_session_update(self, msg_str): """ Either for parsing or building, we store the server_random along with the raw string representing this handshake message. We also store the session_id, the cipher suite (if recognized), the compression method, and finally we instantiate the pending write and read connection states. Usually they get updated later on in the negotiation when we learn the session keys, and eventually they are committed once a ChangeCipherSpec has been sent/received. """ super(TLSServerHello, self).tls_session_update(msg_str) self.tls_session.tls_version = self.version self.random_bytes = msg_str[10:38] self.tls_session.server_random = (struct.pack('!I', self.gmt_unix_time) + self.random_bytes) self.tls_session.sid = self.sid cs_cls = None if self.cipher: cs_val = self.cipher if cs_val not in _tls_cipher_suites_cls: warning("Unknown cipher suite %d from ServerHello" % cs_val) # we do not try to set a default nor stop the execution else: cs_cls = _tls_cipher_suites_cls[cs_val] comp_cls = Comp_NULL if self.comp: comp_val = self.comp[0] if comp_val not in _tls_compression_algs_cls: err = "Unknown compression alg %d from ServerHello" % comp_val warning(err) comp_val = 0 comp_cls = _tls_compression_algs_cls[comp_val] connection_end = self.tls_session.connection_end self.tls_session.pwcs = writeConnState(ciphersuite=cs_cls, compression_alg=comp_cls, connection_end=connection_end, tls_version=self.version) self.tls_session.prcs = readConnState(ciphersuite=cs_cls, compression_alg=comp_cls, connection_end=connection_end, tls_version=self.version) _tls_13_server_hello_fields = [ ByteEnumField("msgtype", 2, _tls_handshake_type), ThreeBytesField("msglen", None), _TLSVersionField("version", 0x0303, _tls_version), _TLSRandomBytesField("random_bytes", None, 32), FieldLenField("sidlen", None, length_of="sid", fmt="B"), _SessionIDField("sid", "", length_from=lambda pkt: pkt.sidlen), EnumField("cipher", None, _tls_cipher_suites), _CompressionMethodsField("comp", [0], _tls_compression_algs, itemfmt="B", length_from=lambda pkt: 1), _ExtensionsLenField("extlen", None, length_of="ext"), _ExtensionsField("ext", None, length_from=lambda pkt: (pkt.msglen - 38)) ] class TLS13ServerHello(_TLSHandshake): """ TLS 1.3 ServerHello """ name = "TLS 1.3 Handshake - Server Hello" fields_desc = _tls_13_server_hello_fields def post_build(self, p, pay): if self.random_bytes is None: p = p[:6] + randstring(32) + p[6 + 32:] return super(TLS13ServerHello, self).post_build(p, pay) def tls_session_update(self, msg_str): """ Either for parsing or building, we store the server_random along with the raw string representing this handshake message. We also store the cipher suite (if recognized), and finally we instantiate the write and read connection states. """ super(TLS13ServerHello, self).tls_session_update(msg_str) s = self.tls_session if self.ext: for e in self.ext: if isinstance(e, TLS_Ext_SupportedVersion_SH): s.tls_version = e.version break s.server_random = self.random_bytes s.ciphersuite = self.cipher cs_cls = None if self.cipher: cs_val = self.cipher if cs_val not in _tls_cipher_suites_cls: warning("Unknown cipher suite %d from ServerHello" % cs_val) # we do not try to set a default nor stop the execution else: cs_cls = _tls_cipher_suites_cls[cs_val] connection_end = s.connection_end if connection_end == "server": s.pwcs = writeConnState(ciphersuite=cs_cls, connection_end=connection_end, tls_version=s.tls_version) s.triggered_pwcs_commit = True elif connection_end == "client": s.prcs = readConnState(ciphersuite=cs_cls, connection_end=connection_end, tls_version=s.tls_version) s.triggered_prcs_commit = True if s.tls13_early_secret is None: # In case the connState was not pre-initialized, we could not # compute the early secrets at the ClientHello, so we do it here. s.compute_tls13_early_secrets() s.compute_tls13_handshake_secrets() if connection_end == "server": shts = s.tls13_derived_secrets["server_handshake_traffic_secret"] s.pwcs.tls13_derive_keys(shts) elif connection_end == "client": shts = s.tls13_derived_secrets["server_handshake_traffic_secret"] s.prcs.tls13_derive_keys(shts) ############################################################################### # HelloRetryRequest # ############################################################################### class TLS13HelloRetryRequest(_TLSHandshake): name = "TLS 1.3 Handshake - Hello Retry Request" fields_desc = _tls_13_server_hello_fields ############################################################################### # EncryptedExtensions # ############################################################################### class TLSEncryptedExtensions(_TLSHandshake): name = "TLS 1.3 Handshake - Encrypted Extensions" fields_desc = [ByteEnumField("msgtype", 8, _tls_handshake_type), ThreeBytesField("msglen", None), _ExtensionsLenField("extlen", None, length_of="ext"), _ExtensionsField("ext", None, length_from=lambda pkt: pkt.msglen - 2)] def post_build_tls_session_update(self, msg_str): self.tls_session_update(msg_str) s = self.tls_session connection_end = s.connection_end # Check if the server early_data extension is present in # EncryptedExtensions message (if so, early data was accepted by the # server) early_data_accepted = False if self.ext: for e in self.ext: if isinstance(e, TLS_Ext_EarlyDataIndication): early_data_accepted = True # If the serveur did not accept early_data, we change prcs traffic # encryption keys. Otherwise, the the keys will be updated after the # EndOfEarlyData message if connection_end == "server": if not early_data_accepted: s.prcs = readConnState(ciphersuite=type(s.wcs.ciphersuite), connection_end=connection_end, tls_version=s.tls_version) s.triggered_prcs_commit = True chts = s.tls13_derived_secrets["client_handshake_traffic_secret"] # noqa: E501 s.prcs.tls13_derive_keys(chts) s.rcs = self.tls_session.prcs s.triggered_prcs_commit = False def post_dissection_tls_session_update(self, msg_str): self.tls_session_update(msg_str) s = self.tls_session connection_end = s.connection_end # Check if the server early_data extension is present in # EncryptedExtensions message (if so, early data was accepted by the # server) early_data_accepted = False if self.ext: for e in self.ext: if isinstance(e, TLS_Ext_EarlyDataIndication): early_data_accepted = True # If the serveur did not accept early_data, we change pwcs traffic # encryption key. Otherwise, the the keys will be updated after the # EndOfEarlyData message if connection_end == "client": if not early_data_accepted: s.pwcs = writeConnState(ciphersuite=type(s.rcs.ciphersuite), connection_end=connection_end, tls_version=s.tls_version) s.triggered_pwcs_commit = True chts = s.tls13_derived_secrets["client_handshake_traffic_secret"] # noqa: E501 s.pwcs.tls13_derive_keys(chts) s.wcs = self.tls_session.pwcs s.triggered_pwcs_commit = False ############################################################################### # Certificate # ############################################################################### # XXX It might be appropriate to rewrite this mess with basic 3-byte FieldLenField. # noqa: E501 class _ASN1CertLenField(FieldLenField): """ This is mostly a 3-byte FieldLenField. """ def __init__(self, name, default, length_of=None, adjust=lambda pkt, x: x): self.length_of = length_of self.adjust = adjust Field.__init__(self, name, default, fmt="!I") def i2m(self, pkt, x): if x is None: if self.length_of is not None: fld, fval = pkt.getfield_and_val(self.length_of) f = fld.i2len(pkt, fval) x = self.adjust(pkt, f) return x def addfield(self, pkt, s, val): return s + struct.pack(self.fmt, self.i2m(pkt, val))[1:4] def getfield(self, pkt, s): return s[3:], self.m2i(pkt, struct.unpack(self.fmt, b"\x00" + s[:3])[0]) # noqa: E501 class _ASN1CertListField(StrLenField): islist = 1 def i2len(self, pkt, i): if i is None: return 0 return len(self.i2m(pkt, i)) def getfield(self, pkt, s): """ Extract Certs in a loop. XXX We should provide safeguards when trying to parse a Cert. """ tmp_len = None if self.length_from is not None: tmp_len = self.length_from(pkt) lst = [] ret = b"" m = s if tmp_len is not None: m, ret = s[:tmp_len], s[tmp_len:] while m: clen = struct.unpack("!I", b'\x00' + m[:3])[0] lst.append((clen, Cert(m[3:3 + clen]))) m = m[3 + clen:] return m + ret, lst def i2m(self, pkt, i): def i2m_one(i): if isinstance(i, str): return i if isinstance(i, Cert): s = i.der tmp_len = struct.pack("!I", len(s))[1:4] return tmp_len + s (tmp_len, s) = i if isinstance(s, Cert): s = s.der return struct.pack("!I", tmp_len)[1:4] + s if i is None: return b"" if isinstance(i, str): return i if isinstance(i, Cert): i = [i] return b"".join(i2m_one(x) for x in i) def any2i(self, pkt, x): return x class _ASN1CertField(StrLenField): def i2len(self, pkt, i): if i is None: return 0 return len(self.i2m(pkt, i)) def getfield(self, pkt, s): tmp_len = None if self.length_from is not None: tmp_len = self.length_from(pkt) ret = b"" m = s if tmp_len is not None: m, ret = s[:tmp_len], s[tmp_len:] clen = struct.unpack("!I", b'\x00' + m[:3])[0] len_cert = (clen, Cert(m[3:3 + clen])) m = m[3 + clen:] return m + ret, len_cert def i2m(self, pkt, i): def i2m_one(i): if isinstance(i, str): return i if isinstance(i, Cert): s = i.der tmp_len = struct.pack("!I", len(s))[1:4] return tmp_len + s (tmp_len, s) = i if isinstance(s, Cert): s = s.der return struct.pack("!I", tmp_len)[1:4] + s if i is None: return b"" return i2m_one(i) def any2i(self, pkt, x): return x class TLSCertificate(_TLSHandshake): """ XXX We do not support RFC 5081, i.e. OpenPGP certificates. """ name = "TLS Handshake - Certificate" fields_desc = [ByteEnumField("msgtype", 11, _tls_handshake_type), ThreeBytesField("msglen", None), _ASN1CertLenField("certslen", None, length_of="certs"), _ASN1CertListField("certs", [], length_from=lambda pkt: pkt.certslen)] @classmethod def dispatch_hook(cls, _pkt=None, *args, **kargs): if _pkt: tls_session = kargs.get("tls_session", None) if tls_session and (tls_session.tls_version or 0) >= 0x0304: return TLS13Certificate return TLSCertificate def post_dissection_tls_session_update(self, msg_str): self.tls_session_update(msg_str) connection_end = self.tls_session.connection_end if connection_end == "client": self.tls_session.server_certs = [x[1] for x in self.certs] else: self.tls_session.client_certs = [x[1] for x in self.certs] class _ASN1CertAndExt(_GenericTLSSessionInheritance): name = "Certificate and Extensions" fields_desc = [_ASN1CertField("cert", ""), FieldLenField("extlen", None, length_of="ext"), _ExtensionsField("ext", [], length_from=lambda pkt: pkt.extlen)] def extract_padding(self, s): return b"", s class _ASN1CertAndExtListField(PacketListField): def m2i(self, pkt, m): return self.cls(m, tls_session=pkt.tls_session) class TLS13Certificate(_TLSHandshake): name = "TLS 1.3 Handshake - Certificate" fields_desc = [ByteEnumField("msgtype", 11, _tls_handshake_type), ThreeBytesField("msglen", None), FieldLenField("cert_req_ctxt_len", None, fmt="B", length_of="cert_req_ctxt"), StrLenField("cert_req_ctxt", "", length_from=lambda pkt: pkt.cert_req_ctxt_len), _ASN1CertLenField("certslen", None, length_of="certs"), _ASN1CertAndExtListField("certs", [], _ASN1CertAndExt, length_from=lambda pkt: pkt.certslen)] # noqa: E501 def post_dissection_tls_session_update(self, msg_str): self.tls_session_update(msg_str) connection_end = self.tls_session.connection_end if connection_end == "client": if self.certs: sc = [x.cert[1] for x in self.certs] self.tls_session.server_certs = sc else: if self.certs: cc = [x.cert[1] for x in self.certs] self.tls_session.client_certs = cc ############################################################################### # ServerKeyExchange # ############################################################################### class TLSServerKeyExchange(_TLSHandshake): name = "TLS Handshake - Server Key Exchange" fields_desc = [ByteEnumField("msgtype", 12, _tls_handshake_type), ThreeBytesField("msglen", None), _TLSServerParamsField("params", None, length_from=lambda pkt: pkt.msglen), _TLSSignatureField("sig", None, length_from=lambda pkt: pkt.msglen - len(pkt.params))] # noqa: E501 def build(self, *args, **kargs): r""" We overload build() method in order to provide a valid default value for params based on TLS session if not provided. This cannot be done by overriding i2m() because the method is called on a copy of the packet. The 'params' field is built according to key_exchange.server_kx_msg_cls which should have been set after receiving a cipher suite in a previous ServerHello. Usual cases are: - None: for RSA encryption or fixed FF/ECDH. This should never happen, as no ServerKeyExchange should be generated in the first place. - ServerDHParams: for ephemeral FFDH. In that case, the parameter to server_kx_msg_cls does not matter. - ServerECDH\*Params: for ephemeral ECDH. There are actually three classes, which are dispatched by _tls_server_ecdh_cls_guess on the first byte retrieved. The default here is b"\03", which corresponds to ServerECDHNamedCurveParams (implicit curves). When the Server\*DHParams are built via .fill_missing(), the session server_kx_privkey will be updated accordingly. """ fval = self.getfieldval("params") if fval is None: s = self.tls_session if s.pwcs: if s.pwcs.key_exchange.export: cls = ServerRSAParams(tls_session=s) else: cls = s.pwcs.key_exchange.server_kx_msg_cls(b"\x03") cls = cls(tls_session=s) try: cls.fill_missing() except Exception: if conf.debug_dissector: raise pass else: cls = Raw() self.params = cls fval = self.getfieldval("sig") if fval is None: s = self.tls_session if s.pwcs: if not s.pwcs.key_exchange.anonymous: p = self.params if p is None: p = b"" m = s.client_random + s.server_random + raw(p) cls = _TLSSignature(tls_session=s) cls._update_sig(m, s.server_key) else: cls = Raw() else: cls = Raw() self.sig = cls return _TLSHandshake.build(self, *args, **kargs) def post_dissection(self, pkt): """ While previously dissecting Server*DHParams, the session server_kx_pubkey should have been updated. XXX Add a 'fixed_dh' OR condition to the 'anonymous' test. """ s = self.tls_session if s.prcs and s.prcs.key_exchange.no_ske: pkt_info = pkt.firstlayer().summary() log_runtime.info("TLS: useless ServerKeyExchange [%s]", pkt_info) if (s.prcs and not s.prcs.key_exchange.anonymous and s.client_random and s.server_random and s.server_certs and len(s.server_certs) > 0): m = s.client_random + s.server_random + raw(self.params) sig_test = self.sig._verify_sig(m, s.server_certs[0]) if not sig_test: pkt_info = pkt.firstlayer().summary() log_runtime.info("TLS: invalid ServerKeyExchange signature [%s]", pkt_info) # noqa: E501 ############################################################################### # CertificateRequest # ############################################################################### _tls_client_certificate_types = {1: "rsa_sign", 2: "dss_sign", 3: "rsa_fixed_dh", 4: "dss_fixed_dh", 5: "rsa_ephemeral_dh_RESERVED", 6: "dss_ephemeral_dh_RESERVED", 20: "fortezza_dms_RESERVED", 64: "ecdsa_sign", 65: "rsa_fixed_ecdh", 66: "ecdsa_fixed_ecdh"} class _CertTypesField(_CipherSuitesField): pass class _CertAuthoritiesField(StrLenField): """ XXX Rework this with proper ASN.1 parsing. """ islist = 1 def getfield(self, pkt, s): tmp_len = self.length_from(pkt) return s[tmp_len:], self.m2i(pkt, s[:tmp_len]) def m2i(self, pkt, m): res = [] while len(m) > 1: tmp_len = struct.unpack("!H", m[:2])[0] if len(m) < tmp_len + 2: res.append((tmp_len, m[2:])) break dn = m[2:2 + tmp_len] res.append((tmp_len, dn)) m = m[2 + tmp_len:] return res def i2m(self, pkt, i): return b"".join(map(lambda x_y: struct.pack("!H", x_y[0]) + x_y[1], i)) def addfield(self, pkt, s, val): return s + self.i2m(pkt, val) def i2len(self, pkt, val): if val is None: return 0 else: return len(self.i2m(pkt, val)) class TLSCertificateRequest(_TLSHandshake): name = "TLS Handshake - Certificate Request" fields_desc = [ByteEnumField("msgtype", 13, _tls_handshake_type), ThreeBytesField("msglen", None), FieldLenField("ctypeslen", None, fmt="B", length_of="ctypes"), _CertTypesField("ctypes", [1, 64], _tls_client_certificate_types, itemfmt="!B", length_from=lambda pkt: pkt.ctypeslen), SigAndHashAlgsLenField("sig_algs_len", None, length_of="sig_algs"), SigAndHashAlgsField("sig_algs", [0x0403, 0x0401, 0x0201], EnumField("hash_sig", None, _tls_hash_sig), # noqa: E501 length_from=lambda pkt: pkt.sig_algs_len), # noqa: E501 FieldLenField("certauthlen", None, fmt="!H", length_of="certauth"), _CertAuthoritiesField("certauth", [], length_from=lambda pkt: pkt.certauthlen)] # noqa: E501 class TLS13CertificateRequest(_TLSHandshake): name = "TLS 1.3 Handshake - Certificate Request" fields_desc = [ByteEnumField("msgtype", 13, _tls_handshake_type), ThreeBytesField("msglen", None), FieldLenField("cert_req_ctxt_len", None, fmt="B", length_of="cert_req_ctxt"), StrLenField("cert_req_ctxt", "", length_from=lambda pkt: pkt.cert_req_ctxt_len), _ExtensionsLenField("extlen", None, length_of="ext"), _ExtensionsField("ext", None, length_from=lambda pkt: pkt.msglen - pkt.cert_req_ctxt_len - 3)] ############################################################################### # ServerHelloDone # ############################################################################### class TLSServerHelloDone(_TLSHandshake): name = "TLS Handshake - Server Hello Done" fields_desc = [ByteEnumField("msgtype", 14, _tls_handshake_type), ThreeBytesField("msglen", None)] ############################################################################### # CertificateVerify # ############################################################################### class TLSCertificateVerify(_TLSHandshake): name = "TLS Handshake - Certificate Verify" fields_desc = [ByteEnumField("msgtype", 15, _tls_handshake_type), ThreeBytesField("msglen", None), _TLSSignatureField("sig", None, length_from=lambda pkt: pkt.msglen)] def build(self, *args, **kargs): sig = self.getfieldval("sig") if sig is None: s = self.tls_session m = b"".join(s.handshake_messages) if s.tls_version >= 0x0304: if s.connection_end == "client": context_string = b"TLS 1.3, client CertificateVerify" elif s.connection_end == "server": context_string = b"TLS 1.3, server CertificateVerify" m = b"\x20" * 64 + context_string + b"\x00" + s.wcs.hash.digest(m) # noqa: E501 self.sig = _TLSSignature(tls_session=s) if s.connection_end == "client": self.sig._update_sig(m, s.client_key) elif s.connection_end == "server": # should be TLS 1.3 only self.sig._update_sig(m, s.server_key) return _TLSHandshake.build(self, *args, **kargs) def post_dissection(self, pkt): s = self.tls_session m = b"".join(s.handshake_messages) if s.tls_version >= 0x0304: if s.connection_end == "client": context_string = b"TLS 1.3, server CertificateVerify" elif s.connection_end == "server": context_string = b"TLS 1.3, client CertificateVerify" m = b"\x20" * 64 + context_string + b"\x00" + s.rcs.hash.digest(m) if s.connection_end == "server": if s.client_certs and len(s.client_certs) > 0: sig_test = self.sig._verify_sig(m, s.client_certs[0]) if not sig_test: pkt_info = pkt.firstlayer().summary() log_runtime.info("TLS: invalid CertificateVerify signature [%s]", pkt_info) # noqa: E501 elif s.connection_end == "client": # should be TLS 1.3 only if s.server_certs and len(s.server_certs) > 0: sig_test = self.sig._verify_sig(m, s.server_certs[0]) if not sig_test: pkt_info = pkt.firstlayer().summary() log_runtime.info("TLS: invalid CertificateVerify signature [%s]", pkt_info) # noqa: E501 ############################################################################### # ClientKeyExchange # ############################################################################### class _TLSCKExchKeysField(PacketField): __slots__ = ["length_from"] holds_packet = 1 def __init__(self, name, length_from=None, remain=0): self.length_from = length_from PacketField.__init__(self, name, None, None, remain=remain) def m2i(self, pkt, m): """ The client_kx_msg may be either None, EncryptedPreMasterSecret (for RSA encryption key exchange), ClientDiffieHellmanPublic, or ClientECDiffieHellmanPublic. When either one of them gets dissected, the session context is updated accordingly. """ tmp_len = self.length_from(pkt) tbd, rem = m[:tmp_len], m[tmp_len:] s = pkt.tls_session cls = None if s.prcs and s.prcs.key_exchange: cls = s.prcs.key_exchange.client_kx_msg_cls if cls is None: return Raw(tbd) / Padding(rem) return cls(tbd, tls_session=s) / Padding(rem) class TLSClientKeyExchange(_TLSHandshake): """ This class mostly works like TLSServerKeyExchange and its 'params' field. """ name = "TLS Handshake - Client Key Exchange" fields_desc = [ByteEnumField("msgtype", 16, _tls_handshake_type), ThreeBytesField("msglen", None), _TLSCKExchKeysField("exchkeys", length_from=lambda pkt: pkt.msglen)] def build(self, *args, **kargs): fval = self.getfieldval("exchkeys") if fval is None: s = self.tls_session if s.prcs: cls = s.prcs.key_exchange.client_kx_msg_cls cls = cls(tls_session=s) else: cls = Raw() self.exchkeys = cls return _TLSHandshake.build(self, *args, **kargs) ############################################################################### # Finished # ############################################################################### class _VerifyDataField(StrLenField): def getfield(self, pkt, s): if pkt.tls_session.tls_version == 0x0300: sep = 36 elif pkt.tls_session.tls_version >= 0x0304: sep = pkt.tls_session.rcs.hash.hash_len else: sep = 12 return s[sep:], s[:sep] class TLSFinished(_TLSHandshake): name = "TLS Handshake - Finished" fields_desc = [ByteEnumField("msgtype", 20, _tls_handshake_type), ThreeBytesField("msglen", None), _VerifyDataField("vdata", None)] def build(self, *args, **kargs): fval = self.getfieldval("vdata") if fval is None: s = self.tls_session handshake_msg = b"".join(s.handshake_messages) con_end = s.connection_end if s.tls_version < 0x0304: ms = s.master_secret self.vdata = s.wcs.prf.compute_verify_data(con_end, "write", handshake_msg, ms) else: self.vdata = s.compute_tls13_verify_data(con_end, "write") return _TLSHandshake.build(self, *args, **kargs) def post_dissection(self, pkt): s = self.tls_session if not s.frozen: handshake_msg = b"".join(s.handshake_messages) if s.tls_version < 0x0304 and s.master_secret is not None: ms = s.master_secret con_end = s.connection_end verify_data = s.rcs.prf.compute_verify_data(con_end, "read", handshake_msg, ms) if self.vdata != verify_data: pkt_info = pkt.firstlayer().summary() log_runtime.info("TLS: invalid Finished received [%s]", pkt_info) # noqa: E501 elif s.tls_version >= 0x0304: con_end = s.connection_end verify_data = s.compute_tls13_verify_data(con_end, "read") if self.vdata != verify_data: pkt_info = pkt.firstlayer().summary() log_runtime.info("TLS: invalid Finished received [%s]", pkt_info) # noqa: E501 def post_build_tls_session_update(self, msg_str): self.tls_session_update(msg_str) s = self.tls_session if s.tls_version >= 0x0304: s.pwcs = writeConnState(ciphersuite=type(s.wcs.ciphersuite), connection_end=s.connection_end, tls_version=s.tls_version) s.triggered_pwcs_commit = True if s.connection_end == "server": s.compute_tls13_traffic_secrets() elif s.connection_end == "client": s.compute_tls13_traffic_secrets_end() s.compute_tls13_resumption_secret() def post_dissection_tls_session_update(self, msg_str): self.tls_session_update(msg_str) s = self.tls_session if s.tls_version >= 0x0304: s.prcs = readConnState(ciphersuite=type(s.rcs.ciphersuite), connection_end=s.connection_end, tls_version=s.tls_version) s.triggered_prcs_commit = True if s.connection_end == "client": s.compute_tls13_traffic_secrets() elif s.connection_end == "server": s.compute_tls13_traffic_secrets_end() s.compute_tls13_resumption_secret() # Additional handshake messages ############################################################################### # HelloVerifyRequest # ############################################################################### class TLSHelloVerifyRequest(_TLSHandshake): """ Defined for DTLS, see RFC 6347. """ name = "TLS Handshake - Hello Verify Request" fields_desc = [ByteEnumField("msgtype", 21, _tls_handshake_type), ThreeBytesField("msglen", None), FieldLenField("cookielen", None, fmt="B", length_of="cookie"), StrLenField("cookie", "", length_from=lambda pkt: pkt.cookielen)] ############################################################################### # CertificateURL # ############################################################################### _tls_cert_chain_types = {0: "individual_certs", 1: "pkipath"} class URLAndOptionalHash(Packet): name = "URLAndOptionHash structure for TLSCertificateURL" fields_desc = [FieldLenField("urllen", None, length_of="url"), StrLenField("url", "", length_from=lambda pkt: pkt.urllen), FieldLenField("hash_present", None, fmt="B", length_of="hash", adjust=lambda pkt, x: int(math.ceil(x / 20.))), # noqa: E501 StrLenField("hash", "", length_from=lambda pkt: 20 * pkt.hash_present)] def guess_payload_class(self, p): return Padding class TLSCertificateURL(_TLSHandshake): """ Defined in RFC 4366. PkiPath structure of section 8 is not implemented yet. """ name = "TLS Handshake - Certificate URL" fields_desc = [ByteEnumField("msgtype", 21, _tls_handshake_type), ThreeBytesField("msglen", None), ByteEnumField("certchaintype", None, _tls_cert_chain_types), FieldLenField("uahlen", None, length_of="uah"), PacketListField("uah", [], URLAndOptionalHash, length_from=lambda pkt: pkt.uahlen)] ############################################################################### # CertificateStatus # ############################################################################### class ThreeBytesLenField(FieldLenField): def __init__(self, name, default, length_of=None, adjust=lambda pkt, x: x): FieldLenField.__init__(self, name, default, length_of=length_of, fmt='!I', adjust=adjust) def i2repr(self, pkt, x): if x is None: return 0 return repr(self.i2h(pkt, x)) def addfield(self, pkt, s, val): return s + struct.pack(self.fmt, self.i2m(pkt, val))[1:4] def getfield(self, pkt, s): return s[3:], self.m2i(pkt, struct.unpack(self.fmt, b"\x00" + s[:3])[0]) # noqa: E501 _cert_status_cls = {1: OCSP_Response} class _StatusField(PacketField): def m2i(self, pkt, m): idtype = pkt.status_type cls = self.cls if idtype in _cert_status_cls: cls = _cert_status_cls[idtype] return cls(m) class TLSCertificateStatus(_TLSHandshake): name = "TLS Handshake - Certificate Status" fields_desc = [ByteEnumField("msgtype", 22, _tls_handshake_type), ThreeBytesField("msglen", None), ByteEnumField("status_type", 1, _cert_status_type), ThreeBytesLenField("responselen", None, length_of="response"), _StatusField("response", None, Raw)] ############################################################################### # SupplementalData # ############################################################################### class SupDataEntry(Packet): name = "Supplemental Data Entry - Generic" fields_desc = [ShortField("sdtype", None), FieldLenField("len", None, length_of="data"), StrLenField("data", "", length_from=lambda pkt:pkt.len)] def guess_payload_class(self, p): return Padding class UserMappingData(Packet): name = "User Mapping Data" fields_desc = [ByteField("version", None), FieldLenField("len", None, length_of="data"), StrLenField("data", "", length_from=lambda pkt: pkt.len)] def guess_payload_class(self, p): return Padding class SupDataEntryUM(Packet): name = "Supplemental Data Entry - User Mapping" fields_desc = [ShortField("sdtype", None), FieldLenField("len", None, length_of="data", adjust=lambda pkt, x: x + 2), FieldLenField("dlen", None, length_of="data"), PacketListField("data", [], UserMappingData, length_from=lambda pkt:pkt.dlen)] def guess_payload_class(self, p): return Padding class TLSSupplementalData(_TLSHandshake): name = "TLS Handshake - Supplemental Data" fields_desc = [ByteEnumField("msgtype", 23, _tls_handshake_type), ThreeBytesField("msglen", None), ThreeBytesLenField("sdatalen", None, length_of="sdata"), PacketListField("sdata", [], SupDataEntry, length_from=lambda pkt: pkt.sdatalen)] ############################################################################### # NewSessionTicket # ############################################################################### class TLSNewSessionTicket(_TLSHandshake): """ XXX When knowing the right secret, we should be able to read the ticket. """ name = "TLS Handshake - New Session Ticket" fields_desc = [ByteEnumField("msgtype", 4, _tls_handshake_type), ThreeBytesField("msglen", None), IntField("lifetime", 0xffffffff), FieldLenField("ticketlen", None, length_of="ticket"), StrLenField("ticket", "", length_from=lambda pkt: pkt.ticketlen)] @classmethod def dispatch_hook(cls, _pkt=None, *args, **kargs): s = kargs.get("tls_session", None) if s and s.tls_version and s.tls_version >= 0x0304: return TLS13NewSessionTicket return TLSNewSessionTicket def post_dissection_tls_session_update(self, msg_str): self.tls_session_update(msg_str) if self.tls_session.connection_end == "client": self.tls_session.client_session_ticket = self.ticket class TLS13NewSessionTicket(_TLSHandshake): """ Uncomment the TicketField line for parsing a RFC 5077 ticket. """ name = "TLS 1.3 Handshake - New Session Ticket" fields_desc = [ByteEnumField("msgtype", 4, _tls_handshake_type), ThreeBytesField("msglen", None), IntField("ticket_lifetime", 0xffffffff), IntField("ticket_age_add", 0), FieldLenField("noncelen", None, fmt="B", length_of="ticket_nonce"), StrLenField("ticket_nonce", "", length_from=lambda pkt: pkt.noncelen), FieldLenField("ticketlen", None, length_of="ticket"), # TicketField("ticket", "", StrLenField("ticket", "", length_from=lambda pkt: pkt.ticketlen), _ExtensionsLenField("extlen", None, length_of="ext"), _ExtensionsField("ext", None, length_from=lambda pkt: (pkt.msglen - (pkt.ticketlen or 0) - # noqa: E501 pkt.noncelen or 0) - 13)] # noqa: E501 def post_dissection_tls_session_update(self, msg_str): self.tls_session_update(msg_str) if self.tls_session.connection_end == "client": self.tls_session.client_session_ticket = self.ticket ############################################################################### # EndOfEarlyData # ############################################################################### class TLS13EndOfEarlyData(_TLSHandshake): name = "TLS 1.3 Handshake - End Of Early Data" fields_desc = [ByteEnumField("msgtype", 5, _tls_handshake_type), ThreeBytesField("msglen", None)] ############################################################################### # KeyUpdate # ############################################################################### _key_update_request = {0: "update_not_requested", 1: "update_requested"} class TLS13KeyUpdate(_TLSHandshake): name = "TLS 1.3 Handshake - Key Update" fields_desc = [ByteEnumField("msgtype", 24, _tls_handshake_type), ThreeBytesField("msglen", None), ByteEnumField("request_update", 0, _key_update_request)] ############################################################################### # All handshake messages defined in this module # ############################################################################### _tls_handshake_cls = {0: TLSHelloRequest, 1: TLSClientHello, 2: TLSServerHello, 3: TLSHelloVerifyRequest, 4: TLSNewSessionTicket, 8: TLSEncryptedExtensions, 11: TLSCertificate, 12: TLSServerKeyExchange, 13: TLSCertificateRequest, 14: TLSServerHelloDone, 15: TLSCertificateVerify, 16: TLSClientKeyExchange, 20: TLSFinished, 21: TLSCertificateURL, 22: TLSCertificateStatus, 23: TLSSupplementalData} _tls13_handshake_cls = {1: TLS13ClientHello, 2: TLS13ServerHello, 4: TLS13NewSessionTicket, 5: TLS13EndOfEarlyData, 8: TLSEncryptedExtensions, 11: TLS13Certificate, 13: TLS13CertificateRequest, 15: TLSCertificateVerify, 20: TLSFinished, 24: TLS13KeyUpdate}
mtury/scapy
scapy/layers/tls/handshake.py
Python
gpl-2.0
61,432
import mox import time import unittest from zoom.agent.predicate.health import PredicateHealth from zoom.common.types import PlatformType class PredicateHealthTest(unittest.TestCase): def setUp(self): self.mox = mox.Mox() self.interval = 0.1 def tearDown(self): self.mox.UnsetStubs() def test_start(self): pred = PredicateHealth("test", "echo", self.interval, PlatformType.LINUX) self.mox.StubOutWithMock(pred, "_run") pred._run().MultipleTimes() self.mox.ReplayAll() print "This test should complete quickly" pred.start() pred.start() # should noop pred.start() # should noop time.sleep(0.25) # give other thread time to check pred.stop() self.mox.VerifyAll() def test_stop(self): pred = PredicateHealth("test", "echo", self.interval, PlatformType.LINUX) self.mox.StubOutWithMock(pred, "_run") pred._run().MultipleTimes() self.mox.ReplayAll() pred.start() time.sleep(0.25) # give other thread time to check pred.stop() pred.stop() pred.stop() self.mox.VerifyAll()
spottradingllc/zoom
test/predicate/health_test.py
Python
gpl-2.0
1,195
""" Care about audio fileformat """ try: from mutagen.flac import FLAC from mutagen.oggvorbis import OggVorbis except ImportError: pass import parser import mutagenstripper class MpegAudioStripper(parser.GenericParser): """ Represent mpeg audio file (mp3, ...) """ def _should_remove(self, field): return field.name in ("id3v1", "id3v2") class OggStripper(mutagenstripper.MutagenStripper): """ Represent an ogg vorbis file """ def _create_mfile(self): self.mfile = OggVorbis(self.filename) class FlacStripper(mutagenstripper.MutagenStripper): """ Represent a Flac audio file """ def _create_mfile(self): self.mfile = FLAC(self.filename) def remove_all(self): """ Remove the "metadata" block from the file """ super(FlacStripper, self).remove_all() self.mfile.clear_pictures() self.mfile.save() return True def is_clean(self): """ Check if the "metadata" block is present in the file """ return super(FlacStripper, self).is_clean() and not self.mfile.pictures def get_meta(self): """ Return the content of the metadata block if present """ metadata = super(FlacStripper, self).get_meta() if self.mfile.pictures: metadata['picture:'] = 'yes' return metadata
jubalh/MAT
libmat/audio.py
Python
gpl-2.0
1,375
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2011, 2012, 2014, 2015 CERN. # # Invenio 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. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Knowledge database models.""" import os from invenio_base.globals import cfg from invenio.ext.sqlalchemy import db from invenio.ext.sqlalchemy.utils import session_manager from invenio_collections.models import Collection from invenio.utils.text import slugify from sqlalchemy.dialects import mysql from sqlalchemy.event import listens_for from sqlalchemy.orm.collections import attribute_mapped_collection from sqlalchemy.schema import Index class KnwKB(db.Model): """Represent a KnwKB record.""" KNWKB_TYPES = { 'written_as': 'w', 'dynamic': 'd', 'taxonomy': 't', } __tablename__ = 'knwKB' id = db.Column(db.MediumInteger(8, unsigned=True), nullable=False, primary_key=True, autoincrement=True) _name = db.Column(db.String(255), server_default='', unique=True, name="name") _description = db.Column(db.Text, nullable=False, name="description", default="") _kbtype = db.Column(db.Char(1), nullable=True, default='w', name="kbtype") slug = db.Column(db.String(255), unique=True, nullable=False, default="") # Enable or disable the access from REST API is_api_accessible = db.Column(db.Boolean, default=True, nullable=False) @db.hybrid_property def name(self): """Get name.""" return self._name @name.setter def name(self, value): """Set name and generate the slug.""" self._name = value # generate slug if not self.slug: self.slug = KnwKB.generate_slug(value) @db.hybrid_property def description(self): """Get description.""" return self._description @description.setter def description(self, value): """Set description.""" # TEXT in mysql don't support default value # @see http://bugs.mysql.com/bug.php?id=21532 self._description = value or '' @db.hybrid_property def kbtype(self): """Get kbtype.""" return self._kbtype @kbtype.setter def kbtype(self, value): """Set kbtype.""" if value is None: # set the default value return # or set one of the available values kbtype = value[0] if len(value) > 0 else 'w' if kbtype not in ['t', 'd', 'w']: raise ValueError('unknown type "{value}", please use one of \ following values: "taxonomy", "dynamic" or \ "written_as"'.format(value=value)) self._kbtype = kbtype def is_dynamic(self): """Return true if the type is dynamic.""" return self._kbtype == 'd' def to_dict(self): """Return a dict representation of KnwKB.""" mydict = {'id': self.id, 'name': self.name, 'description': self.description, 'kbtype': self.kbtype} if self.kbtype == 'd': mydict.update((self.kbdefs.to_dict() if self.kbdefs else {}) or {}) return mydict def get_kbr_items(self, searchkey="", searchvalue="", searchtype='s'): """ Return dicts of 'key' and 'value' from a knowledge base. :param kb_name the name of the knowledge base :param searchkey search using this key :param searchvalue search using this value :param searchtype s=substring, e=exact, sw=startswith :return a list of dictionaries [{'key'=>x, 'value'=>y},..] """ import warnings warnings.warn("The function is deprecated. Please use the " "`KnwKBRVAL.query_kb_mappings()` instead. " "E.g. [kval.to_dict() for kval in " "KnwKBRVAL.query_kb_mappings(kb_id).all()]") if searchtype == 's' and searchkey: searchkey = '%' + searchkey + '%' if searchtype == 's' and searchvalue: searchvalue = '%' + searchvalue + '%' if searchtype == 'sw' and searchvalue: # startswith searchvalue = searchvalue + '%' if not searchvalue: searchvalue = '%' if not searchkey: searchkey = '%' kvals = KnwKBRVAL.query.filter( KnwKBRVAL.id_knwKB.like(self.id), KnwKBRVAL.m_value.like(searchvalue), KnwKBRVAL.m_key.like(searchkey)).all() return [kval.to_dict() for kval in kvals] def get_kbr_values(self, searchkey="", searchvalue="", searchtype='s'): """ Return dicts of 'key' and 'value' from a knowledge base. :param kb_name the name of the knowledge base :param searchkey search using this key :param searchvalue search using this value :param searchtype s=substring, e=exact, sw=startswith :return a list of dictionaries [{'key'=>x, 'value'=>y},..] """ import warnings warnings.warn("The function is deprecated. Please use the " "`KnwKBRVAL.query_kb_mappings()` instead. " "E.g. [(kval.m_value,) for kval in " "KnwKBRVAL.query_kb_mappings(kb_id).all()]") # prepare filters if searchtype == 's': searchkey = '%' + searchkey + '%' if searchtype == 's' and searchvalue: searchvalue = '%' + searchvalue + '%' if searchtype == 'sw' and searchvalue: # startswith searchvalue = searchvalue + '%' if not searchvalue: searchvalue = '%' # execute query return db.session.execute( db.select([KnwKBRVAL.m_value], db.and_(KnwKBRVAL.id_knwKB.like(self.id), KnwKBRVAL.m_value.like(searchvalue), KnwKBRVAL.m_key.like(searchkey)))) @session_manager def set_dyn_config(self, field, expression, collection=None): """Set dynamic configuration.""" if self.kbdefs: # update self.kbdefs.output_tag = field self.kbdefs.search_expression = expression self.kbdefs.collection = collection db.session.merge(self.kbdefs) else: # insert self.kbdefs = KnwKBDDEF(output_tag=field, search_expression=expression, collection=collection) @staticmethod def generate_slug(name): """Generate a slug for the knowledge. :param name: text to slugify :return: slugified text """ slug = slugify(name) i = KnwKB.query.filter(db.or_( KnwKB.slug.like(slug), KnwKB.slug.like(slug + '-%'), )).count() return slug + ('-{0}'.format(i) if i > 0 else '') @staticmethod def exists(kb_name): """Return True if a kb with the given name exists. :param kb_name: the name of the knowledge base :return: True if kb exists """ return KnwKB.query_exists(KnwKB.name.like(kb_name)) @staticmethod def query_exists(filters): """Return True if a kb with the given filters exists. E.g: KnwKB.query_exists(KnwKB.name.like('FAQ')) :param filters: filter for sqlalchemy :return: True if kb exists """ return db.session.query( KnwKB.query.filter( filters).exists()).scalar() def get_filename(self): """Construct the file name for taxonomy knoledge.""" return cfg['CFG_WEBDIR'] + "/kbfiles/" \ + str(self.id) + ".rdf" @listens_for(KnwKB, 'after_delete') def del_kwnkb(mapper, connection, target): """Remove taxonomy file.""" if(target.kbtype == KnwKB.KNWKB_TYPES['taxonomy']): # Delete taxonomy file if os.path.isfile(target.get_filename()): os.remove(target.get_filename()) class KnwKBDDEF(db.Model): """Represent a KnwKBDDEF record.""" __tablename__ = 'knwKBDDEF' id_knwKB = db.Column(db.MediumInteger(8, unsigned=True), db.ForeignKey(KnwKB.id), nullable=False, primary_key=True) id_collection = db.Column(db.MediumInteger(unsigned=True), db.ForeignKey(Collection.id), nullable=True) output_tag = db.Column(db.Text, nullable=True) search_expression = db.Column(db.Text, nullable=True) kb = db.relationship( KnwKB, backref=db.backref('kbdefs', uselist=False, cascade="all, delete-orphan"), single_parent=True) collection = db.relationship( Collection, backref=db.backref('kbdefs')) def to_dict(self): """Return a dict representation of KnwKBDDEF.""" return {'field': self.output_tag, 'expression': self.search_expression, 'coll_id': self.id_collection, 'collection': self.collection.name if self.collection else None} class KnwKBRVAL(db.Model): """Represent a KnwKBRVAL record.""" __tablename__ = 'knwKBRVAL' m_key = db.Column(db.String(255), nullable=False, primary_key=True, index=True) m_value = db.Column( db.Text().with_variant(mysql.TEXT(30), 'mysql'), nullable=False) id_knwKB = db.Column( db.MediumInteger( 8, unsigned=True), db.ForeignKey( KnwKB.id), nullable=False, server_default='0', primary_key=True) kb = db.relationship( KnwKB, backref=db.backref( 'kbrvals', cascade="all, delete-orphan", collection_class=attribute_mapped_collection("m_key"))) @staticmethod def query_kb_mappings(kbid, sortby="to", key="", value="", match_type="s"): """Return a list of all mappings from the given kb, ordered by key. If key given, give only those with left side (mapFrom) = key. If value given, give only those with right side (mapTo) = value. :param kb_name: knowledge base name. if "", return all :param sortby: the sorting criteria ('from' or 'to') :param key: return only entries where key matches this :param value: return only entries where value matches this :param match_type: s=substring, e=exact, sw=startswith """ # query query = KnwKBRVAL.query.filter( KnwKBRVAL.id_knwKB == kbid) # filter if len(key) > 0: if match_type == "s": key = "%" + key + "%" elif match_type == "sw": key = key + "%" else: key = '%' if len(value) > 0: if match_type == "s": value = "%" + value + "%" elif match_type == "sw": value = value + "%" else: value = '%' query = query.filter( KnwKBRVAL.m_key.like(key), KnwKBRVAL.m_value.like(value)) # order by if sortby == "from": query = query.order_by(KnwKBRVAL.m_key) else: query = query.order_by(KnwKBRVAL.m_value) return query def to_dict(self): """Return a dict representation of KnwKBRVAL.""" # FIXME remove 'id' dependency from invenio modules return {'id': self.m_key + "_" + str(self.id_knwKB), 'key': self.m_key, 'value': self.m_value, 'kbid': self.kb.id if self.kb else None, 'kbname': self.kb.name if self.kb else None} Index('ix_knwKBRVAL_m_value', KnwKBRVAL.m_value, mysql_length=30) __all__ = ('KnwKB', 'KnwKBDDEF', 'KnwKBRVAL')
egabancho/invenio-knowledge
invenio_knowledge/models.py
Python
gpl-2.0
12,573
from classes import * sign = Object('sign', 'To the left is a sign.', 'The sign says: Den of Evil') opening = Room('opening', 'You are standing in front of a cave.', {}, {'sign' : sign}) #sign.set_room(opening) opening_w = Room('opening_w', 'You are standing in front of an impassable jungle. There is nothing here you can do.') opening_w.add_room('east', opening) opening.add_room('west', opening_w) opening_e = Room('opening_e', 'You are standing in front of an impassable jungle. There is nothing here you can do.') opening_e.add_room('west', opening) opening.add_room('east', opening_e) lamp = Item('Lamp', 'On the ground is an old and rusty oil lamp.', False) shed = Room('shed', 'In the dim light from outside you can see a small and dirty room.', {'lamp':lamp}, {}, {}, 'The broken door blocks the entrance') door=Object('door','The door barely hangs in its place', None, 'The door explodes under your force.', None, shed) opening_s = Room('opening_s', 'There is a small shed at west side of the road. A path leads back to the north.', {}, {'door':door}) #door.set_room(opening_s) opening_s.add_room('north', opening) opening_s.add_room('west', shed) opening.add_room('south', opening_s) shed.add_room('east',opening_s) thief = Entity('thief','A filthy looking thief stands at the wall.') cave_entrance = Room('cave_entrance', 'You are entering a long tunnel going north, that is dimly lit by the light of your lamp.', {}, {}, {'thief':thief}, 'It is to dark to see anything.') cave_entrance.add_room('south', opening) opening.add_room('north', cave_entrance) rooms = { 'opening' : opening, 'opening_w' : opening_w, 'opening_e' : opening_e, 'opening_s' : opening_s, 'cave_entrance' : cave_entrance, 'shed' : shed }
jbs1/jhack14
rooms.py
Python
gpl-2.0
1,739
# -*-python-*- # GemRB - Infinity Engine Emulator # Copyright (C) 2003-2005 The GemRB Project # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 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. # #Character Generation ################################################### import GemRB from GUIDefines import * from ie_stats import * from ie_spells import LS_MEMO import GUICommon import Spellbook import CommonTables import LUSkillsSelection CharGenWindow = 0 CharGenState = 0 TextArea = 0 PortraitButton = 0 AcceptButton = 0 GenderButton = 0 GenderWindow = 0 GenderTextArea = 0 GenderDoneButton = 0 Portrait = 0 PortraitsTable = 0 PortraitPortraitButton = 0 RaceButton = 0 RaceWindow = 0 RaceTextArea = 0 RaceDoneButton = 0 ClassButton = 0 ClassWindow = 0 ClassTextArea = 0 ClassDoneButton = 0 ClassMultiWindow = 0 ClassMultiTextArea = 0 ClassMultiDoneButton = 0 KitTable = 0 KitWindow = 0 KitTextArea = 0 KitDoneButton = 0 AlignmentButton = 0 AlignmentWindow = 0 AlignmentTextArea = 0 AlignmentDoneButton = 0 AbilitiesButton = 0 AbilitiesWindow = 0 AbilitiesTable = 0 AbilitiesRaceAddTable = 0 AbilitiesRaceReqTable = 0 AbilitiesClassReqTable = 0 AbilitiesMinimum = 0 AbilitiesMaximum = 0 AbilitiesModifier = 0 AbilitiesTextArea = 0 AbilitiesRecallButton = 0 AbilitiesDoneButton = 0 SkillsButton = 0 SkillsWindow = 0 SkillsTable = 0 SkillsTextArea = 0 SkillsDoneButton = 0 SkillsPointsLeft = 0 SkillsState = 0 RacialEnemyButton = 0 RacialEnemyWindow = 0 RacialEnemyTable = 0 RacialEnemyTextArea = 0 RacialEnemyDoneButton = 0 ProficienciesWindow = 0 ProficienciesTable = 0 ProfsMaxTable = 0 ProficienciesTextArea = 0 ProficienciesDoneButton = 0 ProficienciesPointsLeft = 0 MageSpellsWindow = 0 MageSpellsTextArea = 0 MageSpellsDoneButton = 0 MageSpellsSelectPointsLeft = 0 MageMemorizeWindow = 0 MageMemorizeTextArea = 0 MageMemorizeDoneButton = 0 MageMemorizePointsLeft = 0 PriestMemorizeWindow = 0 PriestMemorizeTextArea = 0 PriestMemorizeDoneButton = 0 PriestMemorizePointsLeft = 0 AppearanceButton = 0 AppearanceWindow = 0 AppearanceTable = 0 AppearanceAvatarButton = 0 AppearanceHairButton = 0 AppearanceSkinButton = 0 AppearanceMajorButton = 0 AppearanceMinorButton = 0 HairColor = 0 SkinColor = 0 MajorColor = 0 MinorColor = 0 CharSoundWindow = 0 CharSoundTable = 0 CharSoundStrings = 0 BiographyButton = 0 BiographyWindow = 0 BiographyField = 0 NameButton = 0 NameWindow = 0 NameField = 0 NameDoneButton = 0 SoundIndex = 0 VerbalConstants = None HasStrExtra = 0 MyChar = 0 ImportedChar = 0 def OnLoad(): global CharGenWindow, CharGenState, TextArea, PortraitButton, AcceptButton global GenderButton, RaceButton, ClassButton, AlignmentButton global AbilitiesButton, SkillsButton, AppearanceButton, BiographyButton, NameButton global KitTable, ProficienciesTable, RacialEnemyTable global AbilitiesTable, SkillsTable, PortraitsTable global MyChar, ImportedChar KitTable = GemRB.LoadTable ("magesch") ProficienciesTable = GemRB.LoadTable ("weapprof") RacialEnemyTable = GemRB.LoadTable ("haterace") AbilitiesTable = GemRB.LoadTable ("ability") SkillsTable = GemRB.LoadTable ("skills") PortraitsTable = GemRB.LoadTable ("pictures") GemRB.LoadWindowPack ("GUICG", 640, 480) CharGenWindow = GemRB.LoadWindow (0) CharGenWindow.SetFrame () CharGenState = 0 MyChar = GemRB.GetVar ("Slot") ImportedChar = 0 GenderButton = CharGenWindow.GetControl (0) GenderButton.SetState (IE_GUI_BUTTON_ENABLED) GenderButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) GenderButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, GenderPress) GenderButton.SetText (11956) RaceButton = CharGenWindow.GetControl (1) RaceButton.SetState (IE_GUI_BUTTON_DISABLED) RaceButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, RacePress) RaceButton.SetText (11957) ClassButton = CharGenWindow.GetControl (2) ClassButton.SetState (IE_GUI_BUTTON_DISABLED) ClassButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ClassPress) ClassButton.SetText (11959) AlignmentButton = CharGenWindow.GetControl (3) AlignmentButton.SetState (IE_GUI_BUTTON_DISABLED) AlignmentButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AlignmentPress) AlignmentButton.SetText (11958) AbilitiesButton = CharGenWindow.GetControl (4) AbilitiesButton.SetState (IE_GUI_BUTTON_DISABLED) AbilitiesButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AbilitiesPress) AbilitiesButton.SetText (11960) SkillsButton = CharGenWindow.GetControl (5) SkillsButton.SetState (IE_GUI_BUTTON_DISABLED) SkillsButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, SkillsPress) SkillsButton.SetText (11983) AppearanceButton = CharGenWindow.GetControl (6) AppearanceButton.SetState (IE_GUI_BUTTON_DISABLED) AppearanceButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AppearancePress) AppearanceButton.SetText (11961) BiographyButton = CharGenWindow.GetControl (16) BiographyButton.SetState (IE_GUI_BUTTON_DISABLED) BiographyButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, BiographyPress) BiographyButton.SetText (18003) NameButton = CharGenWindow.GetControl (7) NameButton.SetState (IE_GUI_BUTTON_DISABLED) NameButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, NamePress) NameButton.SetText (11963) BackButton = CharGenWindow.GetControl (11) BackButton.SetState (IE_GUI_BUTTON_ENABLED) BackButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, BackPress) BackButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) PortraitButton = CharGenWindow.GetControl (12) PortraitButton.SetFlags (IE_GUI_BUTTON_PICTURE|IE_GUI_BUTTON_NO_IMAGE, OP_SET) PortraitButton.SetState (IE_GUI_BUTTON_LOCKED) ImportButton = CharGenWindow.GetControl (13) ImportButton.SetState (IE_GUI_BUTTON_ENABLED) ImportButton.SetText (13955) ImportButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ImportPress) CancelButton = CharGenWindow.GetControl (15) CancelButton.SetState (IE_GUI_BUTTON_ENABLED) CancelButton.SetText (13727) CancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, CancelPress) AcceptButton = CharGenWindow.GetControl (8) AcceptButton.SetState (IE_GUI_BUTTON_DISABLED) AcceptButton.SetText (11962) AcceptButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AcceptPress) TextArea = CharGenWindow.GetControl (9) TextArea.SetText (16575) CharGenWindow.SetVisible (WINDOW_VISIBLE) return def BackPress(): global CharGenWindow, CharGenState, SkillsState global GenderButton, RaceButton, ClassButton, AlignmentButton, AbilitiesButton, SkillsButton, AppearanceButton, BiographyButton, NameButton if CharGenState > 0: CharGenState = CharGenState - 1 else: CancelPress() return if CharGenState > 6: CharGenState = 6 GemRB.SetToken ("CHARNAME","") if CharGenState == 0: RaceButton.SetState (IE_GUI_BUTTON_DISABLED) RaceButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) GenderButton.SetState (IE_GUI_BUTTON_ENABLED) GenderButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) elif CharGenState == 1: ClassButton.SetState (IE_GUI_BUTTON_DISABLED) ClassButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) RaceButton.SetState (IE_GUI_BUTTON_ENABLED) RaceButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) elif CharGenState == 2: AlignmentButton.SetState (IE_GUI_BUTTON_DISABLED) AlignmentButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) ClassButton.SetState (IE_GUI_BUTTON_ENABLED) ClassButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) elif CharGenState == 3: AbilitiesButton.SetState (IE_GUI_BUTTON_DISABLED) AbilitiesButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) AlignmentButton.SetState (IE_GUI_BUTTON_ENABLED) AlignmentButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) elif CharGenState == 4: SkillsButton.SetState (IE_GUI_BUTTON_DISABLED) SkillsButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) AbilitiesButton.SetState (IE_GUI_BUTTON_ENABLED) AbilitiesButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) elif CharGenState == 5: AppearanceButton.SetState (IE_GUI_BUTTON_DISABLED) SkillsButton.SetState (IE_GUI_BUTTON_ENABLED) SkillsButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) SkillsState = 0 elif CharGenState == 6: NameButton.SetState (IE_GUI_BUTTON_DISABLED) BiographyButton.SetState (IE_GUI_BUTTON_DISABLED) AppearanceButton.SetState (IE_GUI_BUTTON_ENABLED) AcceptButton.SetState (IE_GUI_BUTTON_DISABLED) SetCharacterDescription() return def CancelPress(): global CharGenWindow if CharGenWindow: CharGenWindow.Unload () GemRB.CreatePlayer ("", MyChar | 0x8000 ) GemRB.SetNextScript ("PartyFormation") return def AcceptPress(): #mage spells Kit = GemRB.GetPlayerStat (MyChar, IE_KIT) KitIndex = KitTable.FindValue (3, Kit) ClassName = GUICommon.GetClassRowName (MyChar) t = GemRB.GetPlayerStat (MyChar, IE_ALIGNMENT) TableName = CommonTables.ClassSkills.GetValue (ClassName, "MAGESPELL", GTV_STR) if TableName != "*": #todo: set up ALL spell levels not just level 1 Spellbook.SetupSpellLevels (MyChar, TableName, IE_SPELL_TYPE_WIZARD, 1) Learnable = Spellbook.GetLearnableMageSpells (KitIndex, t, 1) SpellBook = GemRB.GetVar ("MageSpellBook") MemoBook = GemRB.GetVar ("MageMemorized") j=1 for i in range (len(Learnable) ): if SpellBook & j: if MemoBook & j: memorize = LS_MEMO else: memorize = 0 GemRB.LearnSpell (MyChar, Learnable[i], memorize) j=j<<1 #priest spells TableName = CommonTables.ClassSkills.GetValue (ClassName, "CLERICSPELL", GTV_STR) # druids and rangers have a column of their own if TableName == "*": TableName = CommonTables.ClassSkills.GetValue (ClassName, "DRUIDSPELL", GTV_STR) if TableName != "*": if TableName == "MXSPLPRS" or TableName == "MXSPLPAL": ClassFlag = 0x8000 elif TableName == "MXSPLDRU": #there is no separate druid table, falling back to priest TableName = "MXSPLPRS" ClassFlag = 0x4000 elif TableName == "MXSPLRAN": ClassFlag = 0x4000 else: ClassFlag = 0 Spellbook.SetupSpellLevels (MyChar, TableName, IE_SPELL_TYPE_PRIEST, 1) Learnable = Spellbook.GetLearnablePriestSpells (ClassFlag, t, 1) PriestMemorized = GemRB.GetVar ("PriestMemorized") j = 1 while (PriestMemorized and PriestMemorized != 1<<(j-1)): j = j + 1 for i in range (len(Learnable) ): GemRB.LearnSpell (MyChar, Learnable[i], 0) GemRB.MemorizeSpell (MyChar, IE_SPELL_TYPE_PRIEST, 0, j, 1) # apply class/kit abilities GUICommon.ResolveClassAbilities (MyChar, ClassName) # save all the skills LUSkillsSelection.SkillsSave (MyChar) TmpTable = GemRB.LoadTable ("repstart") t = CommonTables.Aligns.FindValue (3, t) t = TmpTable.GetValue (t, 0) * 10 GemRB.SetPlayerStat (MyChar, IE_REPUTATION, t) # set the party rep if this in the main char if MyChar == 1: GemRB.GameSetReputation (t) print "Reputation", t TmpTable = GemRB.LoadTable ("strtgold") a = TmpTable.GetValue (ClassName, "ROLLS") #number of dice b = TmpTable.GetValue (ClassName, "SIDES") #size c = TmpTable.GetValue (ClassName, "MODIFIER") #adjustment d = TmpTable.GetValue (ClassName, "MULTIPLIER") #external multiplier e = TmpTable.GetValue (ClassName, "BONUS_PER_LEVEL") #level bonus rate (iwd only!) t = GemRB.GetPlayerStat (MyChar, IE_LEVEL) if t>1: e=e*(t-1) else: e=0 t = GemRB.Roll (a,b,c)*d+e GemRB.SetPlayerStat (MyChar, IE_GOLD, t) GemRB.SetPlayerStat (MyChar, IE_EA, 2 ) GemRB.SetPlayerName (MyChar, GemRB.GetToken ("CHARNAME"), 0) GemRB.SetToken ("CHARNAME","") # don't reset imported char's xp back to start if not ImportedChar: GemRB.SetPlayerStat (MyChar, IE_XP, CommonTables.ClassSkills.GetValue (ClassName, "STARTXP")) GUICommon.SetColorStat (MyChar, IE_SKIN_COLOR, GemRB.GetVar ("SkinColor") ) GUICommon.SetColorStat (MyChar, IE_HAIR_COLOR, GemRB.GetVar ("HairColor") ) GUICommon.SetColorStat (MyChar, IE_MAJOR_COLOR, GemRB.GetVar ("MajorColor") ) GUICommon.SetColorStat (MyChar, IE_MINOR_COLOR, GemRB.GetVar ("MinorColor") ) GUICommon.SetColorStat (MyChar, IE_METAL_COLOR, 0x1B ) GUICommon.SetColorStat (MyChar, IE_LEATHER_COLOR, 0x16 ) GUICommon.SetColorStat (MyChar, IE_ARMOR_COLOR, 0x17 ) #does all the rest LargePortrait = GemRB.GetToken ("LargePortrait") SmallPortrait = GemRB.GetToken ("SmallPortrait") GemRB.FillPlayerInfo (MyChar, LargePortrait, SmallPortrait) #10 is a weapon slot (see slottype.2da row 10) GemRB.CreateItem (MyChar, "staf01", 10, 1, 0, 0) GemRB.SetEquippedQuickSlot (MyChar, 0) if CharGenWindow: CharGenWindow.Unload () GemRB.SetNextScript ("PartyFormation") return def SetCharacterDescription(): global CharGenWindow, TextArea, CharGenState, ClassFlag global MyChar TextArea.Clear() if CharGenState > 7: TextArea.Append (1047) TextArea.Append (": ") TextArea.Append (GemRB.GetToken ("CHARNAME")) TextArea.Append ("\n") if CharGenState > 0: TextArea.Append (12135) TextArea.Append (": ") if GemRB.GetPlayerStat (MyChar, IE_SEX) == 1: TextArea.Append (1050) else: TextArea.Append (1051) TextArea.Append ("\n") if CharGenState > 2: ClassName = GUICommon.GetClassRowName (MyChar) TextArea.Append (12136) TextArea.Append (": ") #this is only mage school in iwd Kit = GemRB.GetPlayerStat (MyChar, IE_KIT) KitIndex = KitTable.FindValue (3, Kit) if KitIndex <= 0: ClassTitle = CommonTables.Classes.GetValue (ClassName, "CAP_REF") else: ClassTitle = KitTable.GetValue (KitIndex, 2) TextArea.Append (ClassTitle) TextArea.Append ("\n") if CharGenState > 1: TextArea.Append (1048) TextArea.Append (": ") Race = GemRB.GetPlayerStat (MyChar, IE_RACE) Race = CommonTables.Races.FindValue (3, GemRB.GetPlayerStat (MyChar, IE_RACE) ) TextArea.Append (CommonTables.Races.GetValue (Race, 2) ) TextArea.Append ("\n") if CharGenState > 3: TextArea.Append (1049) TextArea.Append (": ") Alignment = CommonTables.Aligns.FindValue (3, GemRB.GetPlayerStat(MyChar, IE_ALIGNMENT)) TextArea.Append (CommonTables.Aligns.GetValue (Alignment, 2)) TextArea.Append ("\n") if CharGenState > 4: strextra = GemRB.GetPlayerStat (MyChar, IE_STREXTRA) TextArea.Append ("\n") for i in range (6): TextArea.Append (AbilitiesTable.GetValue (i, 2)) TextArea.Append (": " ) StatID = AbilitiesTable.GetValue (i, 3) stat = GemRB.GetPlayerStat (MyChar, StatID) if (i == 0) and HasStrExtra and (stat==18): TextArea.Append (str(stat) + "/" + str(strextra) ) else: TextArea.Append (str(stat) ) TextArea.Append ("\n") if CharGenState > 5: DruidSpell = CommonTables.ClassSkills.GetValue (ClassName, "DRUIDSPELL") PriestSpell = CommonTables.ClassSkills.GetValue (ClassName, "CLERICSPELL") MageSpell = CommonTables.ClassSkills.GetValue (ClassName, "MAGESPELL") IsBard = CommonTables.ClassSkills.GetValue (ClassName, "BARDSKILL") IsThief = CommonTables.ClassSkills.GetValue (ClassName, "THIEFSKILL") if IsThief!="*": TextArea.Append ("\n") TextArea.Append (8442) TextArea.Append ("\n") for i in range (4): TextArea.Append (SkillsTable.GetValue (i+2, 2)) StatID = SkillsTable.GetValue (i+2, 3) TextArea.Append (": " ) TextArea.Append (str(GemRB.GetPlayerStat (MyChar, StatID)) ) TextArea.Append ("%\n") elif DruidSpell!="*": TextArea.Append ("\n") TextArea.Append (8442) TextArea.Append ("\n") for i in range (4): StatID = SkillsTable.GetValue (i+2, 3) Stat = GemRB.GetPlayerStat (MyChar, StatID) if Stat>0: TextArea.Append (SkillsTable.GetValue (i+2, 2)) TextArea.Append (": " ) TextArea.Append (str(Stat) ) TextArea.Append ("%\n") TextArea.Append ("\n") TextArea.Append (15982) TextArea.Append (": " ) RacialEnemy = GemRB.GetVar ("RacialEnemyIndex") + GemRB.GetVar ("RacialEnemy") - 1 TextArea.Append (RacialEnemyTable.GetValue (RacialEnemy, 3) ) TextArea.Append ("\n") elif IsBard!="*": TextArea.Append ("\n") TextArea.Append (8442) TextArea.Append ("\n") for i in range (4): StatID = SkillsTable.GetValue (i+2, 3) Stat = GemRB.GetPlayerStat (MyChar, StatID) if Stat>0: TextArea.Append (SkillsTable.GetValue (i+2, 2)) TextArea.Append (": " ) TextArea.Append (str(Stat) ) TextArea.Append ("%\n") TextArea.Append ("\n") TextArea.Append (9466) TextArea.Append ("\n") for i in range (15): StatID = ProficienciesTable.GetValue (i, 0) ProficiencyValue = GemRB.GetPlayerStat (MyChar, StatID ) if ProficiencyValue > 0: TextArea.Append (ProficienciesTable.GetValue (i, 3)) TextArea.Append (" ") j = 0 while j < ProficiencyValue: TextArea.Append ("+") j = j + 1 TextArea.Append ("\n") if MageSpell !="*": TextArea.Append ("\n") TextArea.Append (11027) TextArea.Append (":\n") t = GemRB.GetPlayerStat (MyChar, IE_ALIGNMENT) Learnable = Spellbook.GetLearnableMageSpells (GemRB.GetPlayerStat (MyChar, IE_KIT), t,1) MageSpellBook = GemRB.GetVar ("MageSpellBook") MageMemorized = GemRB.GetVar ("MageMemorized") for i in range (len(Learnable)): if (1 << i) & MageSpellBook: Spell = GemRB.GetSpell (Learnable[i]) TextArea.Append (Spell["SpellName"]) if (1 << i) & MageMemorized: TextArea.Append (" +") TextArea.Append ("\n") if PriestSpell == "*": PriestSpell = DruidSpell if PriestSpell!="*": TextArea.Append ("\n") TextArea.Append (11028) TextArea.Append (":\n") t = GemRB.GetPlayerStat (MyChar, IE_ALIGNMENT) if PriestSpell == "MXSPLPRS" or PriestSpell == "MXSPLPAL": ClassFlag = 0x4000 elif PriestSpell == "MXSPLDRU" or PriestSpell == "MXSPLRAN": ClassFlag = 0x8000 else: ClassFlag = 0 Learnable = Spellbook.GetLearnablePriestSpells( ClassFlag, t, 1) PriestMemorized = GemRB.GetVar ("PriestMemorized") for i in range (len(Learnable)): if (1 << i) & PriestMemorized: Spell = GemRB.GetSpell (Learnable[i]) TextArea.Append (Spell["SpellName"]) TextArea.Append (" +\n") return # Gender Selection def GenderPress(): global CharGenWindow, GenderWindow, GenderDoneButton, GenderTextArea global MyChar CharGenWindow.SetVisible (WINDOW_INVISIBLE) GenderWindow = GemRB.LoadWindow (1) GemRB.SetVar ("Gender", 0) GemRB.CreatePlayer ("charbase", MyChar | 0x8000 ) MaleButton = GenderWindow.GetControl (2) MaleButton.SetState (IE_GUI_BUTTON_ENABLED) MaleButton.SetFlags (IE_GUI_BUTTON_RADIOBUTTON,OP_OR) MaleButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, MalePress) FemaleButton = GenderWindow.GetControl (3) FemaleButton.SetState (IE_GUI_BUTTON_ENABLED) FemaleButton.SetFlags (IE_GUI_BUTTON_RADIOBUTTON,OP_OR) FemaleButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, FemalePress) MaleButton.SetVarAssoc ("Gender", 1) FemaleButton.SetVarAssoc ("Gender", 2) GenderTextArea = GenderWindow.GetControl (5) GenderTextArea.SetText (17236) GenderDoneButton = GenderWindow.GetControl (0) GenderDoneButton.SetState (IE_GUI_BUTTON_DISABLED) GenderDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, GenderDonePress) GenderDoneButton.SetText (11973) GenderDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) GenderCancelButton = GenderWindow.GetControl (6) GenderCancelButton.SetState (IE_GUI_BUTTON_ENABLED) GenderCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, GenderCancelPress) GenderCancelButton.SetText (13727) GenderCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) GenderWindow.SetVisible (WINDOW_VISIBLE) return def MalePress(): global GenderWindow, GenderDoneButton, GenderTextArea GenderTextArea.SetText (13083) GenderDoneButton.SetState (IE_GUI_BUTTON_ENABLED) return def FemalePress(): global GenderWindow, GenderDoneButton, GenderTextArea GenderTextArea.SetText (13084) GenderDoneButton.SetState (IE_GUI_BUTTON_ENABLED) return def GenderDonePress(): global CharGenWindow, GenderWindow global MyChar if GenderWindow: GenderWindow.Unload () Gender = GemRB.GetVar ("Gender") GemRB.SetPlayerStat (MyChar, IE_SEX, Gender) CharGenWindow.SetVisible (WINDOW_VISIBLE) PortraitSelect() return def GenderCancelPress(): global CharGenWindow, GenderWindow global MyChar GemRB.SetVar ("Gender", 0) GemRB.SetPlayerStat (MyChar, IE_SEX, 0) if GenderWindow: GenderWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) return def PortraitSelect(): global CharGenWindow, PortraitWindow, Portrait, PortraitPortraitButton global MyChar CharGenWindow.SetVisible (WINDOW_INVISIBLE) PortraitWindow = GemRB.LoadWindow (11) # this is not the correct one, but I don't know which is Portrait = 0 PortraitPortraitButton = PortraitWindow.GetControl (1) PortraitPortraitButton.SetState (IE_GUI_BUTTON_DISABLED) PortraitPortraitButton.SetFlags (IE_GUI_BUTTON_PICTURE|IE_GUI_BUTTON_NO_IMAGE, OP_SET) PortraitLeftButton = PortraitWindow.GetControl (2) PortraitLeftButton.SetState (IE_GUI_BUTTON_ENABLED) PortraitLeftButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, CGPortraitLeftPress) PortraitLeftButton.SetFlags (IE_GUI_BUTTON_RADIOBUTTON, OP_OR) PortraitRightButton = PortraitWindow.GetControl (3) PortraitRightButton.SetState (IE_GUI_BUTTON_ENABLED) PortraitRightButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, CGPortraitRightPress) PortraitRightButton.SetFlags (IE_GUI_BUTTON_RADIOBUTTON, OP_OR) PortraitCustomButton = PortraitWindow.GetControl (6) PortraitCustomButton.SetState (IE_GUI_BUTTON_ENABLED) PortraitCustomButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, PortraitCustomPress) PortraitCustomButton.SetText (17545) PortraitDoneButton = PortraitWindow.GetControl (0) PortraitDoneButton.SetState (IE_GUI_BUTTON_ENABLED) PortraitDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, CGPortraitDonePress) PortraitDoneButton.SetText (11973) PortraitDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) PortraitCancelButton = PortraitWindow.GetControl (5) PortraitCancelButton.SetState (IE_GUI_BUTTON_ENABLED) PortraitCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, CGPortraitCancelPress) PortraitCancelButton.SetText (13727) PortraitCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) while PortraitsTable.GetValue (Portrait, 0) != GemRB.GetPlayerStat (MyChar, IE_SEX): Portrait = Portrait + 1 PortraitPortraitButton.SetPicture (PortraitsTable.GetRowName (Portrait) + "G") PortraitWindow.SetVisible (WINDOW_VISIBLE) return def CGPortraitLeftPress(): global PortraitWindow, Portrait, PortraitPortraitButton global MyChar while True: Portrait = Portrait - 1 if Portrait < 0: Portrait = PortraitsTable.GetRowCount () - 1 if PortraitsTable.GetValue (Portrait, 0) == GemRB.GetPlayerStat(MyChar, IE_SEX): PortraitPortraitButton.SetPicture (PortraitsTable.GetRowName (Portrait) + "G") return def CGPortraitRightPress(): global PortraitWindow, Portrait, PortraitPortraitButton global MyChar while True: Portrait = Portrait + 1 if Portrait == PortraitsTable.GetRowCount(): Portrait = 0 if PortraitsTable.GetValue (Portrait, 0) == GemRB.GetPlayerStat(MyChar, IE_SEX): PortraitPortraitButton.SetPicture (PortraitsTable.GetRowName (Portrait) + "G") return def CustomDone(): global CharGenWindow, PortraitWindow global PortraitButton, GenderButton, RaceButton global CharGenState, Portrait Window = CustomWindow PortraitName = PortraitList2.QueryText () GemRB.SetToken ("SmallPortrait", PortraitName) PortraitName = PortraitList1.QueryText () GemRB.SetToken ("LargePortrait", PortraitName) if Window: Window.Unload () if PortraitWindow: PortraitWindow.Unload () PortraitButton.SetPicture(PortraitName) GenderButton.SetState (IE_GUI_BUTTON_DISABLED) GenderButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) RaceButton.SetState (IE_GUI_BUTTON_ENABLED) RaceButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) CharGenState = 1 Portrait = -1 SetCharacterDescription() CharGenWindow.SetVisible (WINDOW_VISIBLE) return def CustomAbort(): if CustomWindow: CustomWindow.Unload () return def CGLargeCustomPortrait(): Window = CustomWindow Portrait = PortraitList1.QueryText () #small hack if GemRB.GetVar ("Row1") == RowCount1: return Label = Window.GetControl (0x10000007) Label.SetText (Portrait) Button = Window.GetControl (6) if Portrait=="": Portrait = "NOPORTMD" Button.SetState (IE_GUI_BUTTON_DISABLED) else: if PortraitList2.QueryText ()!="": Button.SetState (IE_GUI_BUTTON_ENABLED) Button = Window.GetControl (0) Button.SetPicture (Portrait, "NOPORTMD") return def CGSmallCustomPortrait(): Window = CustomWindow Portrait = PortraitList2.QueryText () #small hack if GemRB.GetVar ("Row2") == RowCount2: return Label = Window.GetControl (0x10000008) Label.SetText (Portrait) Button = Window.GetControl (6) if Portrait=="": Portrait = "NOPORTSM" Button.SetState (IE_GUI_BUTTON_DISABLED) else: if PortraitList1.QueryText ()!="": Button.SetState (IE_GUI_BUTTON_ENABLED) Button = Window.GetControl (1) Button.SetPicture (Portrait, "NOPORTSM") return def PortraitCustomPress(): global PortraitList1, PortraitList2 global RowCount1, RowCount2 global CustomWindow CustomWindow = Window = GemRB.LoadWindow (18) PortraitList1 = Window.GetControl (2) RowCount1 = PortraitList1.ListResources (CHR_PORTRAITS, 1) PortraitList1.SetEvent (IE_GUI_TEXTAREA_ON_SELECT, CGLargeCustomPortrait) GemRB.SetVar ("Row1", RowCount1) PortraitList1.SetVarAssoc ("Row1",RowCount1) PortraitList2 = Window.GetControl (4) RowCount2 = PortraitList2.ListResources (CHR_PORTRAITS, 0) PortraitList2.SetEvent (IE_GUI_TEXTAREA_ON_SELECT, CGSmallCustomPortrait) GemRB.SetVar ("Row2", RowCount2) PortraitList2.SetVarAssoc ("Row2",RowCount2) Button = Window.GetControl (6) Button.SetText (11973) Button.SetEvent (IE_GUI_BUTTON_ON_PRESS, CustomDone) Button.SetState (IE_GUI_BUTTON_DISABLED) Button = Window.GetControl (7) Button.SetText (13727) Button.SetEvent (IE_GUI_BUTTON_ON_PRESS, CustomAbort) Button = Window.GetControl (0) PortraitName = PortraitsTable.GetRowName (Portrait)+"L" Button.SetPicture (PortraitName, "NOPORTMD") Button.SetState (IE_GUI_BUTTON_LOCKED) Button = Window.GetControl (1) PortraitName = PortraitsTable.GetRowName (Portrait)+"S" Button.SetPicture (PortraitName, "NOPORTSM") Button.SetState (IE_GUI_BUTTON_LOCKED) Window.ShowModal (MODAL_SHADOW_NONE) return def CGPortraitDonePress(): global CharGenWindow, PortraitWindow, PortraitButton, GenderButton, RaceButton global CharGenState, Portrait PortraitName = PortraitsTable.GetRowName (Portrait ) GemRB.SetToken ("SmallPortrait", PortraitName+"S") GemRB.SetToken ("LargePortrait", PortraitName+"L") PortraitButton.SetPicture(PortraitsTable.GetRowName (Portrait) + "L") GenderButton.SetState (IE_GUI_BUTTON_DISABLED) GenderButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) RaceButton.SetState (IE_GUI_BUTTON_ENABLED) RaceButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) CharGenState = 1 SetCharacterDescription() CharGenWindow.SetVisible (WINDOW_VISIBLE) if PortraitWindow: PortraitWindow.Unload () return def CGPortraitCancelPress(): global CharGenWindow, PortraitWindow if PortraitWindow: PortraitWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Race Selection def RacePress(): global CharGenWindow, RaceWindow, RaceDoneButton, RaceTextArea CharGenWindow.SetVisible (WINDOW_INVISIBLE) RaceWindow = GemRB.LoadWindow (8) GemRB.SetVar ("Race", 0) for i in range (2, 8): RaceSelectButton = RaceWindow.GetControl (i) RaceSelectButton.SetFlags (IE_GUI_BUTTON_RADIOBUTTON, OP_OR) for i in range (2, 8): RaceSelectButton = RaceWindow.GetControl (i) RaceSelectButton.SetState (IE_GUI_BUTTON_ENABLED) RaceSelectButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, RaceSelectPress) RaceSelectButton.SetText (CommonTables.Races.GetValue (i - 2, 0)) RaceSelectButton.SetVarAssoc ("Race", i - 1) RaceTextArea = RaceWindow.GetControl (8) RaceTextArea.SetText (17237) RaceDoneButton = RaceWindow.GetControl (0) RaceDoneButton.SetState (IE_GUI_BUTTON_DISABLED) RaceDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, RaceDonePress) RaceDoneButton.SetText (11973) RaceDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) RaceCancelButton = RaceWindow.GetControl (10) RaceCancelButton.SetState (IE_GUI_BUTTON_ENABLED) RaceCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, RaceCancelPress) RaceCancelButton.SetText (13727) RaceCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) RaceWindow.SetVisible (WINDOW_VISIBLE) return def RaceSelectPress(): global RaceWindow, RaceDoneButton, RaceTextArea Race = GemRB.GetVar ("Race") - 1 RaceTextArea.SetText (CommonTables.Races.GetValue (Race, 1) ) RaceDoneButton.SetState (IE_GUI_BUTTON_ENABLED) return def RaceDonePress(): global CharGenWindow, CharGenState, RaceWindow, RaceButton, ClassButton if RaceWindow: RaceWindow.Unload () RaceButton.SetState (IE_GUI_BUTTON_DISABLED) RaceButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) ClassButton.SetState (IE_GUI_BUTTON_ENABLED) ClassButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) CharGenState = 2 Race = GemRB.GetVar ("Race")-1 Race = CommonTables.Races.GetValue (Race, 3) GemRB.SetPlayerStat (MyChar, IE_RACE, Race) SetCharacterDescription() CharGenWindow.SetVisible (WINDOW_VISIBLE) return def RaceCancelPress(): global CharGenWindow, RaceWindow if RaceWindow: RaceWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Class Selection def ClassPress(): global CharGenWindow, ClassWindow, ClassTextArea, ClassDoneButton CharGenWindow.SetVisible (WINDOW_INVISIBLE) ClassWindow = GemRB.LoadWindow (2) ClassCount = CommonTables.Classes.GetRowCount () RaceRow = CommonTables.Races.FindValue (3, GemRB.GetPlayerStat (MyChar, IE_RACE) ) RaceName = CommonTables.Races.GetRowName (RaceRow) GemRB.SetVar ("Class", 0) GemRB.SetVar ("Class Kit", 0) GemRB.SetVar ("MAGESCHOOL", 0) for i in range (2, 10): ClassSelectButton = ClassWindow.GetControl (i) ClassSelectButton.SetFlags (IE_GUI_BUTTON_RADIOBUTTON, OP_SET) HasMulti = 0 j = 2 for i in range (ClassCount): ClassRowName = CommonTables.Classes.GetRowName (i) Allowed = CommonTables.Classes.GetValue (ClassRowName, RaceName) if CommonTables.Classes.GetValue (ClassRowName, "MULTI"): if Allowed != 0: HasMulti = 1 else: ClassSelectButton = ClassWindow.GetControl (j) j = j + 1 if Allowed > 0: ClassSelectButton.SetState (IE_GUI_BUTTON_ENABLED) else: ClassSelectButton.SetState (IE_GUI_BUTTON_DISABLED) ClassSelectButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ClassSelectPress) ClassSelectButton.SetText (CommonTables.Classes.GetValue (ClassRowName, "NAME_REF")) ClassSelectButton.SetVarAssoc ("Class", i + 1) ClassMultiButton = ClassWindow.GetControl (10) if HasMulti == 0: ClassMultiButton.SetState (IE_GUI_BUTTON_DISABLED) else: ClassMultiButton.SetState (IE_GUI_BUTTON_ENABLED) ClassMultiButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ClassMultiPress) ClassMultiButton.SetText (11993) KitButton = ClassWindow.GetControl (11) #only the mage class has schools Allowed = CommonTables.Classes.GetValue ("MAGE", RaceName) if Allowed: KitButton.SetState (IE_GUI_BUTTON_ENABLED) else: KitButton.SetState (IE_GUI_BUTTON_DISABLED) KitButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, KitPress) KitButton.SetText (11994) ClassTextArea = ClassWindow.GetControl (13) ClassTextArea.SetText (17242) ClassDoneButton = ClassWindow.GetControl (0) ClassDoneButton.SetState (IE_GUI_BUTTON_DISABLED) ClassDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ClassDonePress) ClassDoneButton.SetText (11973) ClassDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) ClassCancelButton = ClassWindow.GetControl (14) ClassCancelButton.SetState (IE_GUI_BUTTON_ENABLED) ClassCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ClassCancelPress) ClassCancelButton.SetText (13727) ClassCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) ClassWindow.SetVisible (WINDOW_VISIBLE) return def ClassSelectPress(): global ClassWindow, ClassTextArea, ClassDoneButton ClassName = GUICommon.GetClassRowName (GemRB.GetVar ("Class")-1, "index") ClassTextArea.SetText (CommonTables.Classes.GetValue (ClassName, "DESC_REF")) ClassDoneButton.SetState (IE_GUI_BUTTON_ENABLED) return def ClassMultiPress(): global ClassWindow, ClassMultiWindow, ClassMultiTextArea, ClassMultiDoneButton ClassWindow.SetVisible (WINDOW_INVISIBLE) ClassMultiWindow = GemRB.LoadWindow (10) ClassCount = CommonTables.Classes.GetRowCount () RaceRow = CommonTables.Races.FindValue (3, GemRB.GetPlayerStat (MyChar, IE_RACE) ) RaceName = CommonTables.Races.GetRowName (RaceRow) print "Multi racename:", RaceName for i in range (2, 10): ClassMultiSelectButton = ClassMultiWindow.GetControl (i) ClassMultiSelectButton.SetFlags (IE_GUI_BUTTON_RADIOBUTTON, OP_SET) j = 2 for i in range (ClassCount): ClassName = CommonTables.Classes.GetRowName (i) if (CommonTables.Classes.GetValue (ClassName, "MULTI") > 0): ClassMultiSelectButton = ClassMultiWindow.GetControl (j) j = j + 1 if (CommonTables.Classes.GetValue (ClassName, RaceName) > 0): ClassMultiSelectButton.SetState (IE_GUI_BUTTON_ENABLED) else: ClassMultiSelectButton.SetState (IE_GUI_BUTTON_DISABLED) ClassMultiSelectButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ClassMultiSelectPress) ClassMultiSelectButton.SetText (CommonTables.Classes.GetValue (ClassName, "NAME_REF")) ClassMultiSelectButton.SetVarAssoc ("Class", i + 1) ClassMultiTextArea = ClassMultiWindow.GetControl (12) ClassMultiTextArea.SetText (17244) ClassMultiDoneButton = ClassMultiWindow.GetControl (0) ClassMultiDoneButton.SetState (IE_GUI_BUTTON_DISABLED) ClassMultiDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ClassMultiDonePress) ClassMultiDoneButton.SetText (11973) ClassMultiDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) ClassMultiCancelButton = ClassMultiWindow.GetControl (14) ClassMultiCancelButton.SetState (IE_GUI_BUTTON_ENABLED) ClassMultiCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ClassMultiCancelPress) ClassMultiCancelButton.SetText (13727) ClassMultiCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) ClassMultiWindow.SetVisible (WINDOW_VISIBLE) return def ClassMultiSelectPress(): global ClassMultiWindow, ClassMultiTextArea, ClassMultiDoneButton ClassName = GUICommon.GetClassRowName (GemRB.GetVar ("Class")-1, "index") ClassMultiTextArea.SetText (CommonTables.Classes.GetValue (ClassName, "DESC_REF")) ClassMultiDoneButton.SetState (IE_GUI_BUTTON_ENABLED) return def ClassMultiDonePress(): global ClassMultiWindow if ClassMultiWindow: ClassMultiWindow.Unload () ClassDonePress() return def ClassMultiCancelPress(): global ClassWindow, ClassMultiWindow if ClassMultiWindow: ClassMultiWindow.Unload () ClassWindow.SetVisible (WINDOW_VISIBLE) return def KitPress(): global ClassWindow, KitWindow, KitTextArea, KitDoneButton ClassWindow.SetVisible (WINDOW_INVISIBLE) KitWindow = GemRB.LoadWindow (12) #only mage class (1) has schools. It is the sixth button GemRB.SetVar ("Class", 6) GemRB.SetVar ("Class Kit",0) GemRB.SetVar ("MAGESCHOOL",0) for i in range (8): Button = KitWindow.GetControl (i+2) Button.SetFlags (IE_GUI_BUTTON_RADIOBUTTON, OP_OR) Button.SetText (KitTable.GetValue (i+1, 0) ) Button.SetVarAssoc ("MAGESCHOOL", i+1) Button.SetEvent (IE_GUI_BUTTON_ON_PRESS, KitSelectPress) KitTextArea = KitWindow.GetControl (11) KitTextArea.SetText (17245) KitDoneButton = KitWindow.GetControl (0) KitDoneButton.SetState (IE_GUI_BUTTON_DISABLED) KitDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, KitDonePress) KitDoneButton.SetText (11973) KitDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) KitCancelButton = KitWindow.GetControl (12) KitCancelButton.SetState (IE_GUI_BUTTON_ENABLED) KitCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, KitCancelPress) KitCancelButton.SetText (13727) KitCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) KitWindow.SetVisible (WINDOW_VISIBLE) return def KitSelectPress(): global KitWindow, KitTextArea Kit = GemRB.GetVar ("MAGESCHOOL") KitTextArea.SetText (KitTable.GetValue (Kit, 1)) KitDoneButton.SetState (IE_GUI_BUTTON_ENABLED) return def KitDonePress(): global KitWindow if KitWindow: KitWindow.Unload () ClassDonePress() return def KitCancelPress(): global ClassWindow, KitWindow if KitWindow: KitWindow.Unload () ClassWindow.SetVisible (WINDOW_VISIBLE) return def ClassDonePress(): global CharGenWindow, CharGenState, ClassWindow, ClassButton, AlignmentButton global MyChar if ClassWindow: ClassWindow.Unload () ClassButton.SetState (IE_GUI_BUTTON_DISABLED) ClassButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) AlignmentButton.SetState (IE_GUI_BUTTON_ENABLED) AlignmentButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) ClassName = GUICommon.GetClassRowName (GemRB.GetVar ("Class")-1, "index") Class = CommonTables.Classes.GetValue (ClassName, "ID") GemRB.SetPlayerStat (MyChar, IE_CLASS, Class) Kit = KitTable.GetValue (GemRB.GetVar ("MAGESCHOOL"), 3 ) if (Kit == -1 ): Kit = 0x4000 GemRB.SetPlayerStat (MyChar, IE_KIT, Kit) CharGenState = 3 SetCharacterDescription() CharGenWindow.SetVisible (WINDOW_VISIBLE) return def ClassCancelPress(): global CharGenWindow, ClassWindow if ClassWindow: ClassWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Alignment Selection def AlignmentPress(): global CharGenWindow, AlignmentWindow, AlignmentTextArea, AlignmentDoneButton CharGenWindow.SetVisible (WINDOW_INVISIBLE) AlignmentWindow = GemRB.LoadWindow (3) ClassAlignmentTable = GemRB.LoadTable ("alignmnt") ClassName = GUICommon.GetClassRowName (MyChar) GemRB.SetVar ("Alignment", 0) for i in range (2, 11): AlignmentSelectButton = AlignmentWindow.GetControl (i) AlignmentSelectButton.SetFlags (IE_GUI_BUTTON_RADIOBUTTON, OP_OR) for i in range (9): AlignmentSelectButton = AlignmentWindow.GetControl (i + 2) if ClassAlignmentTable.GetValue (ClassName, CommonTables.Aligns.GetValue(i, 4)) == 0: AlignmentSelectButton.SetState (IE_GUI_BUTTON_DISABLED) else: AlignmentSelectButton.SetState (IE_GUI_BUTTON_ENABLED) AlignmentSelectButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AlignmentSelectPress) AlignmentSelectButton.SetText (CommonTables.Aligns.GetValue (i, 0)) AlignmentSelectButton.SetVarAssoc ("Alignment", i + 1) AlignmentTextArea = AlignmentWindow.GetControl (11) AlignmentTextArea.SetText (9602) AlignmentDoneButton = AlignmentWindow.GetControl (0) AlignmentDoneButton.SetState (IE_GUI_BUTTON_DISABLED) AlignmentDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AlignmentDonePress) AlignmentDoneButton.SetText (11973) AlignmentDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) AlignmentCancelButton = AlignmentWindow.GetControl (13) AlignmentCancelButton.SetState (IE_GUI_BUTTON_ENABLED) AlignmentCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AlignmentCancelPress) AlignmentCancelButton.SetText (13727) AlignmentCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) AlignmentWindow.SetVisible (WINDOW_VISIBLE) return def AlignmentSelectPress(): global AlignmentWindow, AlignmentTextArea, AlignmentDoneButton Alignment = GemRB.GetVar ("Alignment") - 1 AlignmentTextArea.SetText (CommonTables.Aligns.GetValue (Alignment, 1)) AlignmentDoneButton.SetState (IE_GUI_BUTTON_ENABLED) return def AlignmentDonePress(): global CharGenWindow, CharGenState, AlignmentWindow, AlignmentButton, AbilitiesButton global MyChar if AlignmentWindow: AlignmentWindow.Unload () AlignmentButton.SetState (IE_GUI_BUTTON_DISABLED) AlignmentButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) AbilitiesButton.SetState (IE_GUI_BUTTON_ENABLED) AbilitiesButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) Alignment = CommonTables.Aligns.GetValue (GemRB.GetVar ("Alignment")-1, 3) GemRB.SetPlayerStat (MyChar, IE_ALIGNMENT, Alignment ) CharGenState = 4 SetCharacterDescription() CharGenWindow.SetVisible (WINDOW_VISIBLE) return def AlignmentCancelPress(): global CharGenWindow, AlignmentWindow if AlignmentWindow: AlignmentWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Abilities Selection def AbilitiesPress(): global CharGenWindow, AbilitiesWindow global AbilitiesTextArea, AbilitiesRecallButton, AbilitiesDoneButton global AbilitiesRaceAddTable, AbilitiesRaceReqTable, AbilitiesClassReqTable global HasStrExtra GemRB.SetRepeatClickFlags(GEM_RK_DISABLE, OP_NAND) CharGenWindow.SetVisible (WINDOW_INVISIBLE) AbilitiesWindow = GemRB.LoadWindow (4) AbilitiesRaceAddTable = GemRB.LoadTable ("ABRACEAD") AbilitiesRaceReqTable = GemRB.LoadTable ("ABRACERQ") AbilitiesClassReqTable = GemRB.LoadTable ("ABCLASRQ") PointsLeftLabel = AbilitiesWindow.GetControl (0x10000002) PointsLeftLabel.SetUseRGB (1) ClassName = GUICommon.GetClassRowName (MyChar) HasStrExtra = CommonTables.Classes.GetValue (ClassName, "SAVE") == "SAVEWAR" for i in range (6): AbilitiesLabelButton = AbilitiesWindow.GetControl (30 + i) AbilitiesLabelButton.SetState (IE_GUI_BUTTON_ENABLED) AbilitiesLabelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AbilitiesLabelPress) AbilitiesLabelButton.SetVarAssoc ("AbilityIndex", i + 1) AbilitiesPlusButton = AbilitiesWindow.GetControl (16 + i * 2) AbilitiesPlusButton.SetState (IE_GUI_BUTTON_ENABLED) AbilitiesPlusButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AbilitiesPlusPress) AbilitiesPlusButton.SetVarAssoc ("AbilityIndex", i + 1) AbilitiesMinusButton = AbilitiesWindow.GetControl (17 + i * 2) AbilitiesMinusButton.SetState (IE_GUI_BUTTON_ENABLED) AbilitiesMinusButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AbilitiesMinusPress) AbilitiesMinusButton.SetVarAssoc ("AbilityIndex", i + 1) AbilityLabel = AbilitiesWindow.GetControl (0x10000003 + i) AbilityLabel.SetUseRGB (1) AbilitiesStoreButton = AbilitiesWindow.GetControl (37) AbilitiesStoreButton.SetState (IE_GUI_BUTTON_ENABLED) AbilitiesStoreButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AbilitiesStorePress) AbilitiesStoreButton.SetText (17373) AbilitiesRecallButton = AbilitiesWindow.GetControl (38) AbilitiesRecallButton.SetState (IE_GUI_BUTTON_DISABLED) AbilitiesRecallButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AbilitiesRecallPress) AbilitiesRecallButton.SetText (17374) AbilitiesRerollButton = AbilitiesWindow.GetControl (2) AbilitiesRerollButton.SetState (IE_GUI_BUTTON_ENABLED) AbilitiesRerollButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AbilitiesRerollPress) AbilitiesRerollButton.SetText (11982) AbilitiesTextArea = AbilitiesWindow.GetControl (29) AbilitiesTextArea.SetText (17247) AbilitiesDoneButton = AbilitiesWindow.GetControl (0) AbilitiesDoneButton.SetState (IE_GUI_BUTTON_ENABLED) AbilitiesDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AbilitiesDonePress) AbilitiesDoneButton.SetText (11973) AbilitiesDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) AbilitiesCancelButton = AbilitiesWindow.GetControl (36) AbilitiesCancelButton.SetState (IE_GUI_BUTTON_ENABLED) AbilitiesCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AbilitiesCancelPress) AbilitiesCancelButton.SetText (13727) AbilitiesCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) AbilitiesRerollPress() AbilitiesWindow.SetVisible (WINDOW_VISIBLE) return def AbilitiesCalcLimits(Index): global AbilitiesRaceReqTable, AbilitiesRaceAddTable, AbilitiesClassReqTable global AbilitiesMinimum, AbilitiesMaximum, AbilitiesModifier Race = CommonTables.Races.FindValue (3, GemRB.GetPlayerStat (MyChar, IE_RACE)) RaceName = CommonTables.Races.GetRowName (Race) Race = AbilitiesRaceReqTable.GetRowIndex (RaceName) AbilitiesMinimum = AbilitiesRaceReqTable.GetValue (Race, Index * 2) AbilitiesMaximum = AbilitiesRaceReqTable.GetValue (Race, Index * 2 + 1) AbilitiesModifier = AbilitiesRaceAddTable.GetValue (Race, Index) ClassName = GUICommon.GetClassRowName (MyChar) ClassIndex = AbilitiesClassReqTable.GetRowIndex (ClassName) Min = AbilitiesClassReqTable.GetValue (ClassIndex, Index) if Min > 0 and AbilitiesMinimum < Min: AbilitiesMinimum = Min AbilitiesMinimum = AbilitiesMinimum + AbilitiesModifier AbilitiesMaximum = AbilitiesMaximum + AbilitiesModifier return def AbilitiesLabelPress(): global AbilitiesWindow, AbilitiesTextArea AbilityIndex = GemRB.GetVar ("AbilityIndex") - 1 AbilitiesCalcLimits(AbilityIndex) GemRB.SetToken ("MINIMUM", str(AbilitiesMinimum) ) GemRB.SetToken ("MAXIMUM", str(AbilitiesMaximum) ) AbilitiesTextArea.SetText (AbilitiesTable.GetValue (AbilityIndex, 1) ) return def AbilitiesPlusPress(): global AbilitiesWindow, AbilitiesTextArea global AbilitiesMinimum, AbilitiesMaximum Abidx = GemRB.GetVar ("AbilityIndex") - 1 AbilitiesCalcLimits(Abidx) GemRB.SetToken ("MINIMUM", str(AbilitiesMinimum) ) GemRB.SetToken ("MAXIMUM", str(AbilitiesMaximum) ) AbilitiesTextArea.SetText (AbilitiesTable.GetValue (Abidx, 1) ) PointsLeft = GemRB.GetVar ("Ability0") Ability = GemRB.GetVar ("Ability" + str(Abidx + 1) ) if PointsLeft > 0 and Ability < AbilitiesMaximum: PointsLeft = PointsLeft - 1 GemRB.SetVar ("Ability0", PointsLeft) PointsLeftLabel = AbilitiesWindow.GetControl (0x10000002) PointsLeftLabel.SetText (str(PointsLeft) ) Ability = Ability + 1 GemRB.SetVar ("Ability" + str(Abidx + 1), Ability) Label = AbilitiesWindow.GetControl (0x10000003 + Abidx) StrExtra = GemRB.GetVar("StrExtra") if Abidx==0 and Ability==18 and HasStrExtra: Label.SetText("18/"+str(StrExtra) ) else: Label.SetText(str(Ability) ) if PointsLeft == 0: AbilitiesDoneButton.SetState (IE_GUI_BUTTON_ENABLED) return def AbilitiesMinusPress(): global AbilitiesWindow, AbilitiesTextArea global AbilitiesMinimum, AbilitiesMaximum Abidx = GemRB.GetVar ("AbilityIndex") - 1 AbilitiesCalcLimits(Abidx) GemRB.SetToken ("MINIMUM", str(AbilitiesMinimum) ) GemRB.SetToken ("MAXIMUM", str(AbilitiesMaximum) ) AbilitiesTextArea.SetText (AbilitiesTable.GetValue (Abidx, 1) ) PointsLeft = GemRB.GetVar ("Ability0") Ability = GemRB.GetVar ("Ability" + str(Abidx + 1) ) if Ability > AbilitiesMinimum: Ability = Ability - 1 GemRB.SetVar ("Ability" + str(Abidx + 1), Ability) Label = AbilitiesWindow.GetControl (0x10000003 + Abidx) StrExtra = GemRB.GetVar("StrExtra") if Abidx==0 and Ability==18 and HasStrExtra: Label.SetText("18/"+str(StrExtra) ) else: Label.SetText(str(Ability) ) PointsLeft = PointsLeft + 1 GemRB.SetVar ("Ability0", PointsLeft) PointsLeftLabel = AbilitiesWindow.GetControl (0x10000002) PointsLeftLabel.SetText (str(PointsLeft) ) AbilitiesDoneButton.SetState (IE_GUI_BUTTON_DISABLED) return def AbilitiesStorePress(): global AbilitiesWindow, AbilitiesRecallButton GemRB.SetVar("StoredStrExtra", GemRB.GetVar ("StrExtra") ) for i in range (7): GemRB.SetVar ("Stored" + str(i), GemRB.GetVar ("Ability" + str(i))) AbilitiesRecallButton.SetState (IE_GUI_BUTTON_ENABLED) return def AbilitiesRecallPress(): global AbilitiesWindow AbilitiesWindow.Invalidate () e=GemRB.GetVar("StoredStrExtra") GemRB.SetVar("StrExtra",e) for i in range (7): v = GemRB.GetVar ("Stored" + str(i)) GemRB.SetVar ("Ability" + str(i), v) Label = AbilitiesWindow.GetControl (0x10000002 + i) if i==0 and v==18 and HasStrExtra==1: Label.SetText("18/"+str(e) ) else: Label.SetText(str(v) ) PointsLeft = GemRB.GetVar("Ability0") if PointsLeft == 0: AbilitiesDoneButton.SetState(IE_GUI_BUTTON_ENABLED) else: AbilitiesDoneButton.SetState(IE_GUI_BUTTON_DISABLED) return def AbilitiesRerollPress(): global AbilitiesWindow, AbilitiesMinimum, AbilitiesMaximum, AbilitiesModifier AbilitiesWindow.Invalidate () GemRB.SetVar ("Ability0", 0) PointsLeftLabel = AbilitiesWindow.GetControl (0x10000002) PointsLeftLabel.SetText ("0") Dices = 3 Sides = 5 #roll strextra even when the current stat is not 18 if HasStrExtra: e = GemRB.Roll (1,100,0) else: e = 0 GemRB.SetVar("StrExtra", e) for i in range (6): AbilitiesCalcLimits(i) Value = GemRB.Roll (Dices, Sides, AbilitiesModifier+3) if Value < AbilitiesMinimum: Value = AbilitiesMinimum if Value > AbilitiesMaximum: Value = AbilitiesMaximum GemRB.SetVar ("Ability" + str(i + 1), Value) Label = AbilitiesWindow.GetControl (0x10000003 + i) if i==0 and HasStrExtra and Value==18: Label.SetText("18/"+str(e) ) else: Label.SetText(str(Value) ) AbilitiesDoneButton.SetState(IE_GUI_BUTTON_ENABLED) return def AbilitiesDonePress(): global CharGenWindow, CharGenState, AbilitiesWindow, AbilitiesButton, SkillsButton, SkillsState if AbilitiesWindow: AbilitiesWindow.Unload () AbilitiesButton.SetState (IE_GUI_BUTTON_DISABLED) AbilitiesButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) SkillsButton.SetState (IE_GUI_BUTTON_ENABLED) SkillsButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) Str = GemRB.GetVar ("Ability1") GemRB.SetPlayerStat (MyChar, IE_STR, Str) if Str == 18: GemRB.SetPlayerStat (MyChar, IE_STREXTRA, GemRB.GetVar ("StrExtra")) else: GemRB.SetPlayerStat (MyChar, IE_STREXTRA, 0) GemRB.SetPlayerStat (MyChar, IE_DEX, GemRB.GetVar ("Ability2")) GemRB.SetPlayerStat (MyChar, IE_CON, GemRB.GetVar ("Ability3")) GemRB.SetPlayerStat (MyChar, IE_INT, GemRB.GetVar ("Ability4")) GemRB.SetPlayerStat (MyChar, IE_WIS, GemRB.GetVar ("Ability5")) GemRB.SetPlayerStat (MyChar, IE_CHR, GemRB.GetVar ("Ability6")) CharGenState = 5 SkillsState = 0 SetCharacterDescription() GemRB.SetRepeatClickFlags(GEM_RK_DISABLE, OP_OR) CharGenWindow.SetVisible (WINDOW_VISIBLE) return def AbilitiesCancelPress(): global CharGenWindow, AbilitiesWindow if AbilitiesWindow: AbilitiesWindow.Unload () GemRB.SetRepeatClickFlags(GEM_RK_DISABLE, OP_OR) CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Skills Selection def SkillsPress(): global CharGenWindow, AppearanceButton global SkillsState, SkillsButton, CharGenState, ClassFlag Level = 1 SpellLevel = 1 ClassName = GUICommon.GetClassRowName (MyChar) DruidSpell = CommonTables.ClassSkills.GetValue (ClassName, "DRUIDSPELL") PriestSpell = CommonTables.ClassSkills.GetValue (ClassName, "CLERICSPELL") MageSpell = CommonTables.ClassSkills.GetValue (ClassName, "MAGESPELL") IsBard = CommonTables.ClassSkills.GetValue (ClassName, "BARDSKILL") IsThief = CommonTables.ClassSkills.GetValue (ClassName, "THIEFSKILL") if SkillsState == 0: GemRB.SetVar ("HatedRace", 0) if IsThief!="*": SkillsSelect() elif DruidSpell!="*": Skill = GemRB.LoadTable("SKILLRNG").GetValue(str(Level), "STEALTH") GemRB.SetPlayerStat (MyChar, IE_STEALTH, Skill) RacialEnemySelect() elif IsBard!="*": Skill = GemRB.LoadTable(IsBard).GetValue(str(Level), "PICK_POCKETS") GemRB.SetPlayerStat (MyChar, IE_PICKPOCKET, Skill) SkillsState = 1 else: SkillsState = 1 if SkillsState == 1: ProficienciesSelect() if SkillsState == 2: if MageSpell!="*": MageSpellsSelect(MageSpell, Level, SpellLevel) else: SkillsState = 3 if SkillsState == 3: if MageSpell!="*": MageSpellsMemorize(MageSpell, Level, SpellLevel) else: SkillsState = 4 if SkillsState == 4: if PriestSpell=="MXSPLPRS" or PriestSpell =="MXSPLPAL": ClassFlag = 0x4000 PriestSpellsMemorize(PriestSpell, Level, SpellLevel) elif DruidSpell=="MXSPLDRU" or DruidSpell =="MXSPLRAN": #no separate spell progression if DruidSpell == "MXSPLDRU": DruidSpell = "MXSPLPRS" ClassFlag = 0x8000 PriestSpellsMemorize(DruidSpell, Level, SpellLevel) else: SkillsState = 5 if SkillsState == 5: SkillsButton.SetState (IE_GUI_BUTTON_DISABLED) SkillsButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) AppearanceButton.SetState (IE_GUI_BUTTON_ENABLED) AppearanceButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) Race = GemRB.GetVar ("HatedRace") GemRB.SetPlayerStat (MyChar, IE_HATEDRACE, Race) ProfCount = ProficienciesTable.GetRowCount () for i in range(ProfCount): StatID = ProficienciesTable.GetValue (i, 0) Value = GemRB.GetVar ("Proficiency"+str(i) ) GemRB.SetPlayerStat (MyChar, StatID, Value ) CharGenState = 6 SetCharacterDescription() return def SkillsSelect(): global CharGenWindow, SkillsWindow, SkillsTextArea, SkillsDoneButton, SkillsPointsLeft CharGenWindow.SetVisible (WINDOW_INVISIBLE) SkillsWindow = GemRB.LoadWindow (6) Levels = [GemRB.GetPlayerStat (MyChar, IE_LEVEL), \ GemRB.GetPlayerStat (MyChar, IE_LEVEL2), \ GemRB.GetPlayerStat (MyChar, IE_LEVEL3)] LUSkillsSelection.SetupSkillsWindow (MyChar, \ LUSkillsSelection.LUSKILLS_TYPE_CHARGEN, SkillsWindow, RedrawSkills, [0,0,0], Levels, 0, False) SkillsPointsLeft = GemRB.GetVar ("SkillPointsLeft") if SkillsPointsLeft<=0: SkillsDonePress() return SkillsDoneButton = SkillsWindow.GetControl (0) SkillsDoneButton.SetState (IE_GUI_BUTTON_DISABLED) SkillsDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, SkillsDonePress) SkillsDoneButton.SetText (11973) SkillsDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) SkillsCancelButton = SkillsWindow.GetControl (25) SkillsCancelButton.SetState (IE_GUI_BUTTON_ENABLED) SkillsCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, SkillsCancelPress) SkillsCancelButton.SetText (13727) SkillsCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) GemRB.SetRepeatClickFlags(GEM_RK_DISABLE, OP_NAND) RedrawSkills() SkillsWindow.SetVisible (WINDOW_VISIBLE) return def RedrawSkills(): PointsLeft = GemRB.GetVar ("SkillPointsLeft") if PointsLeft == 0: SkillsDoneButton.SetState(IE_GUI_BUTTON_ENABLED) else: SkillsDoneButton.SetState(IE_GUI_BUTTON_DISABLED) return def SkillsDonePress(): global CharGenWindow, SkillsWindow, SkillsState if SkillsWindow: SkillsWindow.Unload () SkillsState = 1 CharGenWindow.SetVisible (WINDOW_VISIBLE) SkillsPress() return def SkillsCancelPress(): global CharGenWindow, SkillsWindow, SkillsState if SkillsWindow: SkillsWindow.Unload () SkillsState = 0 CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Racial Enemy Selection def RacialEnemySelect(): global CharGenWindow, RacialEnemyWindow, RacialEnemyTextArea, RacialEnemyDoneButton CharGenWindow.SetVisible (WINDOW_INVISIBLE) RacialEnemyWindow = GemRB.LoadWindow (15) RacialEnemyCount = RacialEnemyTable.GetRowCount () for i in range (2, 8): RacialEnemySelectButton = RacialEnemyWindow.GetControl (i) RacialEnemySelectButton.SetFlags (IE_GUI_BUTTON_RADIOBUTTON, OP_OR) for i in range (2, 8): RacialEnemySelectButton = RacialEnemyWindow.GetControl (i) RacialEnemySelectButton.SetState (IE_GUI_BUTTON_ENABLED) RacialEnemySelectButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, RacialEnemySelectPress) RacialEnemySelectButton.SetVarAssoc ("RacialEnemy", i - 1) GemRB.SetVar ("RacialEnemyIndex", 0) GemRB.SetVar ("HatedRace", 0) RacialEnemyScrollBar = RacialEnemyWindow.GetControl (1) RacialEnemyScrollBar.SetVarAssoc ("RacialEnemyIndex", RacialEnemyCount - 5) RacialEnemyScrollBar.SetEvent (IE_GUI_SCROLLBAR_ON_CHANGE, DisplayRacialEnemies) RacialEnemyTextArea = RacialEnemyWindow.GetControl (8) RacialEnemyTextArea.SetText (17256) RacialEnemyDoneButton = RacialEnemyWindow.GetControl (11) RacialEnemyDoneButton.SetState (IE_GUI_BUTTON_DISABLED) RacialEnemyDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, RacialEnemyDonePress) RacialEnemyDoneButton.SetText (11973) RacialEnemyDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) RacialEnemyCancelButton = RacialEnemyWindow.GetControl (10) RacialEnemyCancelButton.SetState (IE_GUI_BUTTON_ENABLED) RacialEnemyCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, RacialEnemyCancelPress) RacialEnemyCancelButton.SetText (13727) RacialEnemyCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) DisplayRacialEnemies() RacialEnemyWindow.SetVisible (WINDOW_VISIBLE) return def DisplayRacialEnemies(): global RacialEnemyWindow RacialEnemyIndex = GemRB.GetVar ("RacialEnemyIndex") for i in range (2, 8): RacialEnemySelectButton = RacialEnemyWindow.GetControl (i) RacialEnemySelectButton.SetText (RacialEnemyTable.GetValue (RacialEnemyIndex + i - 2, 0)) return def RacialEnemySelectPress(): global RacialEnemyWindow, RacialEnemyDoneButton, RacialEnemyTextArea RacialEnemy = GemRB.GetVar ("RacialEnemyIndex") + GemRB.GetVar ("RacialEnemy") - 1 RacialEnemyTextArea.SetText (RacialEnemyTable.GetValue (RacialEnemy, 2) ) GemRB.SetVar ("HatedRace", RacialEnemyTable.GetValue (RacialEnemy, 1) ) RacialEnemyDoneButton.SetState (IE_GUI_BUTTON_ENABLED) return def RacialEnemyDonePress(): global CharGenWindow, RacialEnemyWindow, SkillsState if RacialEnemyWindow: RacialEnemyWindow.Unload () SkillsState = 1 CharGenWindow.SetVisible (WINDOW_VISIBLE) SkillsPress() return def RacialEnemyCancelPress(): global CharGenWindow, RacialEnemyWindow, SkillsState if RacialEnemyWindow: RacialEnemyWindow.Unload () SkillsState = 0 CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Weapon Proficiencies Selection def ProficienciesSelect(): global CharGenWindow, ProficienciesWindow, ProficienciesTextArea global ProficienciesPointsLeft, ProficienciesDoneButton, ProfsMaxTable CharGenWindow.SetVisible (WINDOW_INVISIBLE) ProficienciesWindow = GemRB.LoadWindow (9) ProfsTable = GemRB.LoadTable ("profs") ProfsMaxTable = GemRB.LoadTable ("profsmax") ClassWeaponsTable = GemRB.LoadTable ("clasweap") ClassName = GUICommon.GetClassRowName (MyChar) ProficienciesPointsLeft = ProfsTable.GetValue (ClassName, "FIRST_LEVEL") PointsLeftLabel = ProficienciesWindow.GetControl (0x10000009) PointsLeftLabel.SetUseRGB (1) PointsLeftLabel.SetText (str(ProficienciesPointsLeft)) for i in range (8): ProficienciesLabel = ProficienciesWindow.GetControl (69 + i) ProficienciesLabel.SetState (IE_GUI_BUTTON_ENABLED) ProficienciesLabel.SetEvent (IE_GUI_BUTTON_ON_PRESS, ProficienciesLabelPress) ProficienciesLabel.SetVarAssoc ("ProficienciesIndex", i + 1) for j in range (5): ProficienciesMark = ProficienciesWindow.GetControl (27 + i * 5 + j) ProficienciesMark.SetSprites("GUIPFC", 0, 0, 0, 0, 0) ProficienciesMark.SetState (IE_GUI_BUTTON_DISABLED) ProficienciesMark.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_OR) Allowed = ClassWeaponsTable.GetValue (ClassName, ProficienciesTable.GetRowName (i)) ProficienciesPlusButton = ProficienciesWindow.GetControl (11 + i * 2) if Allowed == 0: ProficienciesPlusButton.SetState (IE_GUI_BUTTON_DISABLED) ProficienciesPlusButton.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_OR) else: ProficienciesPlusButton.SetState (IE_GUI_BUTTON_ENABLED) ProficienciesPlusButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ProficienciesPlusPress) ProficienciesPlusButton.SetVarAssoc ("ProficienciesIndex", i + 1) ProficienciesMinusButton = ProficienciesWindow.GetControl (12 + i * 2) if Allowed == 0: ProficienciesMinusButton.SetState (IE_GUI_BUTTON_DISABLED) ProficienciesMinusButton.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_OR) else: ProficienciesMinusButton.SetState (IE_GUI_BUTTON_ENABLED) ProficienciesMinusButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ProficienciesMinusPress) ProficienciesMinusButton.SetVarAssoc ("ProficienciesIndex", i + 1) for i in range (7): ProficienciesLabel = ProficienciesWindow.GetControl (85 + i) ProficienciesLabel.SetState (IE_GUI_BUTTON_ENABLED) ProficienciesLabel.SetEvent (IE_GUI_BUTTON_ON_PRESS, ProficienciesLabelPress) ProficienciesLabel.SetVarAssoc ("ProficienciesIndex", i + 9) for j in range (5): ProficienciesMark = ProficienciesWindow.GetControl (92 + i * 5 + j) ProficienciesMark.SetSprites("GUIPFC", 0, 0, 0, 0, 0) ProficienciesMark.SetState (IE_GUI_BUTTON_DISABLED) ProficienciesMark.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_OR) Allowed = ClassWeaponsTable.GetValue (ClassName, ProficienciesTable.GetRowName (i + 8)) ProficienciesPlusButton = ProficienciesWindow.GetControl (127 + i * 2) if Allowed == 0: ProficienciesPlusButton.SetState (IE_GUI_BUTTON_DISABLED) ProficienciesPlusButton.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_OR) else: ProficienciesPlusButton.SetState (IE_GUI_BUTTON_ENABLED) ProficienciesPlusButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ProficienciesPlusPress) ProficienciesPlusButton.SetVarAssoc ("ProficienciesIndex", i + 9) ProficienciesMinusButton = ProficienciesWindow.GetControl (128 + i * 2) if Allowed == 0: ProficienciesMinusButton.SetState (IE_GUI_BUTTON_DISABLED) ProficienciesMinusButton.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_OR) else: ProficienciesMinusButton.SetState (IE_GUI_BUTTON_ENABLED) ProficienciesMinusButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ProficienciesMinusPress) ProficienciesMinusButton.SetVarAssoc ("ProficienciesIndex", i + 9) for i in range (15): GemRB.SetVar ("Proficiency" + str(i), 0) GemRB.SetToken ("number", str(ProficienciesPointsLeft) ) ProficienciesTextArea = ProficienciesWindow.GetControl (68) ProficienciesTextArea.SetText (9588) ProficienciesDoneButton = ProficienciesWindow.GetControl (0) ProficienciesDoneButton.SetState (IE_GUI_BUTTON_DISABLED) ProficienciesDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ProficienciesDonePress) ProficienciesDoneButton.SetText (11973) ProficienciesDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) ProficienciesCancelButton = ProficienciesWindow.GetControl (77) ProficienciesCancelButton.SetState (IE_GUI_BUTTON_ENABLED) ProficienciesCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ProficienciesCancelPress) ProficienciesCancelButton.SetText (13727) ProficienciesCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) ProficienciesWindow.SetVisible (WINDOW_VISIBLE) return def ProficienciesLabelPress(): global ProficienciesWindow, ProficienciesTextArea ProficienciesIndex = GemRB.GetVar ("ProficienciesIndex") - 1 ProficienciesTextArea.SetText (ProficienciesTable.GetValue (ProficienciesIndex, 2) ) return def ProficienciesPlusPress(): global ProficienciesWindow, ProficienciesTextArea global ProficienciesPointsLeft, ProfsMaxTable ProficienciesIndex = GemRB.GetVar ("ProficienciesIndex") - 1 ProficienciesValue = GemRB.GetVar ("Proficiency" + str(ProficienciesIndex) ) ClassName = GUICommon.GetClassRowName (MyChar) if ProficienciesPointsLeft > 0 and ProficienciesValue < ProfsMaxTable.GetValue (ClassName, "FIRST_LEVEL"): ProficienciesPointsLeft = ProficienciesPointsLeft - 1 PointsLeftLabel = ProficienciesWindow.GetControl (0x10000009) PointsLeftLabel.SetText (str(ProficienciesPointsLeft)) if ProficienciesPointsLeft == 0: ProficienciesDoneButton.SetState (IE_GUI_BUTTON_ENABLED) ProficienciesValue = ProficienciesValue + 1 GemRB.SetVar ("Proficiency" + str(ProficienciesIndex), ProficienciesValue) if ProficienciesIndex < 8: ControlID = 26 + ProficienciesIndex * 5 + ProficienciesValue else: ControlID = 51 + ProficienciesIndex * 5 + ProficienciesValue ProficienciesMark = ProficienciesWindow.GetControl (ControlID) ProficienciesMark.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_NAND) ProficienciesTextArea.SetText (ProficienciesTable.GetValue (ProficienciesIndex, 2) ) return def ProficienciesMinusPress(): global ProficienciesWindow, ProficienciesTextArea, ProficienciesPointsLeft ProficienciesIndex = GemRB.GetVar ("ProficienciesIndex") - 1 ProficienciesValue = GemRB.GetVar ("Proficiency" + str(ProficienciesIndex) ) if ProficienciesValue > 0: ProficienciesValue = ProficienciesValue - 1 GemRB.SetVar ("Proficiency" + str(ProficienciesIndex), ProficienciesValue) if ProficienciesIndex < 8: ControlID = 27 + ProficienciesIndex * 5 + ProficienciesValue else: ControlID = 52 + ProficienciesIndex * 5 + ProficienciesValue ProficienciesMark = ProficienciesWindow.GetControl (ControlID) ProficienciesMark.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_OR) ProficienciesPointsLeft = ProficienciesPointsLeft + 1 PointsLeftLabel = ProficienciesWindow.GetControl (0x10000009) PointsLeftLabel.SetText (str(ProficienciesPointsLeft)) ProficienciesDoneButton.SetState (IE_GUI_BUTTON_DISABLED) ProficienciesTextArea.SetText (ProficienciesTable.GetValue (ProficienciesIndex, 2) ) return def ProficienciesDonePress(): global CharGenWindow, ProficienciesWindow, SkillsState if ProficienciesWindow: ProficienciesWindow.Unload () SkillsState = 2 CharGenWindow.SetVisible (WINDOW_VISIBLE) SkillsPress() return def ProficienciesCancelPress(): global CharGenWindow, ProficienciesWindow, SkillsState if ProficienciesWindow: ProficienciesWindow.Unload () SkillsState = 0 CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Spells Selection def MageSpellsSelect(SpellTable, Level, SpellLevel): global CharGenWindow, MageSpellsWindow, MageSpellsTextArea, MageSpellsDoneButton, MageSpellsSelectPointsLeft, Learnable CharGenWindow.SetVisible (WINDOW_INVISIBLE) MageSpellsWindow = GemRB.LoadWindow (7) #kit (school), alignment, level k = GemRB.GetPlayerStat (MyChar, IE_KIT) t = GemRB.GetPlayerStat (MyChar, IE_ALIGNMENT) Learnable = Spellbook.GetLearnableMageSpells(k, t, SpellLevel) GemRB.SetVar ("MageSpellBook", 0) GemRB.SetVar ("SpellMask", 0) if len(Learnable)<1: MageSpellsDonePress() return if k>0: MageSpellsSelectPointsLeft = 3 else: MageSpellsSelectPointsLeft = 2 PointsLeftLabel = MageSpellsWindow.GetControl (0x1000001b) PointsLeftLabel.SetUseRGB (1) PointsLeftLabel.SetText (str(MageSpellsSelectPointsLeft)) for i in range (24): SpellButton = MageSpellsWindow.GetControl (i + 2) SpellButton.SetFlags (IE_GUI_BUTTON_PICTURE|IE_GUI_BUTTON_CHECKBOX, OP_OR) if i < len(Learnable): Spell = GemRB.GetSpell (Learnable[i]) SpellButton.SetSpellIcon(Learnable[i], 1) SpellButton.SetState (IE_GUI_BUTTON_ENABLED) SpellButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, MageSpellsSelectPress) SpellButton.SetVarAssoc ("SpellMask", 1 << i) SpellButton.SetTooltip(Spell["SpellName"]) else: SpellButton.SetState (IE_GUI_BUTTON_DISABLED) GemRB.SetToken ("number", str(MageSpellsSelectPointsLeft)) MageSpellsTextArea = MageSpellsWindow.GetControl (27) MageSpellsTextArea.SetText (17250) MageSpellsDoneButton = MageSpellsWindow.GetControl (0) MageSpellsDoneButton.SetState (IE_GUI_BUTTON_DISABLED) MageSpellsDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, MageSpellsDonePress) MageSpellsDoneButton.SetText (11973) MageSpellsDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) MageSpellsCancelButton = MageSpellsWindow.GetControl (29) MageSpellsCancelButton.SetState (IE_GUI_BUTTON_ENABLED) MageSpellsCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, MageSpellsCancelPress) MageSpellsCancelButton.SetText (13727) MageSpellsCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) MageSpellsWindow.SetVisible (WINDOW_VISIBLE) return def MageSpellsSelectPress(): global MageSpellsWindow, MageSpellsTextArea, MageSpellsDoneButton, MageSpellsSelectPointsLeft, Learnable MageSpellBook = GemRB.GetVar ("MageSpellBook") SpellMask = GemRB.GetVar ("SpellMask") #getting the bit index Spell = abs(MageSpellBook - SpellMask) i = -1 while (Spell > 0): i = i + 1 Spell = Spell >> 1 Spell = GemRB.GetSpell (Learnable[i]) MageSpellsTextArea.SetText (Spell["SpellDesc"]) if SpellMask < MageSpellBook: MageSpellsSelectPointsLeft = MageSpellsSelectPointsLeft + 1 else: if MageSpellsSelectPointsLeft==0: SpellMask = MageSpellBook GemRB.SetVar ("SpellMask", SpellMask) else: MageSpellsSelectPointsLeft = MageSpellsSelectPointsLeft - 1 if MageSpellsSelectPointsLeft == 0: MageSpellsDoneButton.SetState (IE_GUI_BUTTON_ENABLED) else: MageSpellsDoneButton.SetState (IE_GUI_BUTTON_DISABLED) for i in range (len(Learnable)): SpellButton = MageSpellsWindow.GetControl (i + 2) if ((1 << i) & SpellMask) == 0: SpellButton.SetState (IE_GUI_BUTTON_LOCKED) PointsLeftLabel = MageSpellsWindow.GetControl (0x1000001b) PointsLeftLabel.SetText (str(MageSpellsSelectPointsLeft)) GemRB.SetVar ("MageSpellBook", SpellMask) return def MageSpellsDonePress(): global CharGenWindow, MageSpellsWindow, SkillsState if MageSpellsWindow: MageSpellsWindow.Unload () SkillsState = 3 CharGenWindow.SetVisible (WINDOW_VISIBLE) SkillsPress() return def MageSpellsCancelPress(): global CharGenWindow, MageSpellsWindow, SkillsState if MageSpellsWindow: MageSpellsWindow.Unload () SkillsState = 0 CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Mage Spells Memorize def MageSpellsMemorize(SpellTable, Level, SpellLevel): global CharGenWindow, MageMemorizeWindow, MageMemorizeTextArea, MageMemorizeDoneButton, MageMemorizePointsLeft CharGenWindow.SetVisible (WINDOW_INVISIBLE) MageMemorizeWindow = GemRB.LoadWindow (16) MaxSpellsMageTable = GemRB.LoadTable (SpellTable) MageSpellBook = GemRB.GetVar ("MageSpellBook") GemRB.SetVar ("MageMemorized", 0) GemRB.SetVar ("SpellMask", 0) MageMemorizePointsLeft = MaxSpellsMageTable.GetValue (str(Level), str(SpellLevel) ) if MageMemorizePointsLeft<1 or len(Learnable)<1: MageMemorizeDonePress() return PointsLeftLabel = MageMemorizeWindow.GetControl (0x1000001b) PointsLeftLabel.SetUseRGB (1) PointsLeftLabel.SetText (str(MageMemorizePointsLeft)) j = 0 for i in range (12): SpellButton = MageMemorizeWindow.GetControl (i + 2) SpellButton.SetFlags (IE_GUI_BUTTON_PICTURE|IE_GUI_BUTTON_CHECKBOX, OP_OR) while (j < len(Learnable)) and (((1 << j) & MageSpellBook) == 0): j = j + 1 if j < len(Learnable): Spell = GemRB.GetSpell (Learnable[j]) SpellButton.SetTooltip(Spell["SpellName"]) SpellButton.SetSpellIcon(Learnable[j], 1) SpellButton.SetState (IE_GUI_BUTTON_ENABLED) SpellButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, MageMemorizeSelectPress) SpellButton.SetVarAssoc ("SpellMask", 1 << j) j = j + 1 else: SpellButton.SetState (IE_GUI_BUTTON_DISABLED) GemRB.SetToken ("number", str(MageMemorizePointsLeft)) MageMemorizeTextArea = MageMemorizeWindow.GetControl (27) MageMemorizeTextArea.SetText (17253) MageMemorizeDoneButton = MageMemorizeWindow.GetControl (0) MageMemorizeDoneButton.SetState (IE_GUI_BUTTON_DISABLED) MageMemorizeDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, MageMemorizeDonePress) MageMemorizeDoneButton.SetText (11973) MageMemorizeDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) MageMemorizeCancelButton = MageMemorizeWindow.GetControl (29) MageMemorizeCancelButton.SetState (IE_GUI_BUTTON_ENABLED) MageMemorizeCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, MageMemorizeCancelPress) MageMemorizeCancelButton.SetText (13727) MageMemorizeCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) MageMemorizeWindow.SetVisible (WINDOW_VISIBLE) return def MageMemorizeSelectPress(): global MageMemorizeWindow, MageMemorizeTextArea, MageMemorizeDoneButton, MageMemorizePointsLeft, Learnable MageSpellBook = GemRB.GetVar ("MageSpellBook") MageMemorized = GemRB.GetVar ("MageMemorized") SpellMask = GemRB.GetVar ("SpellMask") Spell = abs(MageMemorized - SpellMask) i = -1 while (Spell > 0): i = i + 1 Spell = Spell >> 1 Spell = GemRB.GetSpell (Learnable[i]) MageMemorizeTextArea.SetText (Spell["SpellDesc"]) if SpellMask < MageMemorized: MageMemorizePointsLeft = MageMemorizePointsLeft + 1 j = 0 for i in range (12): SpellButton = MageMemorizeWindow.GetControl (i + 2) while (j < len(Learnable) ) and (((1 << j) & MageSpellBook) == 0): j = j + 1 if j < len(Learnable): SpellButton.SetState (IE_GUI_BUTTON_ENABLED) j = j + 1 MageMemorizeDoneButton.SetState (IE_GUI_BUTTON_DISABLED) else: MageMemorizePointsLeft = MageMemorizePointsLeft - 1 if MageMemorizePointsLeft == 0: j = 0 for i in range (12): SpellButton = MageMemorizeWindow.GetControl (i + 2) while (j < len(Learnable) ) and (((1 << j) & MageSpellBook) == 0): j = j + 1 if j < len(Learnable): if ((1 << j) & SpellMask) == 0: SpellButton.SetState (IE_GUI_BUTTON_DISABLED) j = j + 1 MageMemorizeDoneButton.SetState (IE_GUI_BUTTON_ENABLED) PointsLeftLabel = MageMemorizeWindow.GetControl (0x1000001b) PointsLeftLabel.SetText (str(MageMemorizePointsLeft)) GemRB.SetVar ("MageMemorized", SpellMask) return def MageMemorizeDonePress(): global CharGenWindow, MageMemorizeWindow, SkillsState if MageMemorizeWindow: MageMemorizeWindow.Unload () SkillsState = 4 CharGenWindow.SetVisible (WINDOW_VISIBLE) SkillsPress() return def MageMemorizeCancelPress(): global CharGenWindow, MageMemorizeWindow, SkillsState if MageMemorizeWindow: MageMemorizeWindow.Unload () SkillsState = 0 CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Priest Spells Memorize def PriestSpellsMemorize(SpellTable, Level, SpellLevel): global CharGenWindow, PriestMemorizeWindow, Learnable, ClassFlag global PriestMemorizeTextArea, PriestMemorizeDoneButton, PriestMemorizePointsLeft CharGenWindow.SetVisible (WINDOW_INVISIBLE) PriestMemorizeWindow = GemRB.LoadWindow (17) t = CommonTables.Aligns.GetValue (GemRB.GetVar ("Alignment")-1, 3) Learnable = Spellbook.GetLearnablePriestSpells( ClassFlag, t, SpellLevel) MaxSpellsPriestTable = GemRB.LoadTable (SpellTable) GemRB.SetVar ("PriestMemorized", 0) GemRB.SetVar ("SpellMask", 0) PriestMemorizePointsLeft = MaxSpellsPriestTable.GetValue (str(Level), str(SpellLevel) ) if PriestMemorizePointsLeft<1 or len(Learnable)<1: PriestMemorizeDonePress() return PointsLeftLabel = PriestMemorizeWindow.GetControl (0x1000001b) PointsLeftLabel.SetUseRGB (1) PointsLeftLabel.SetText (str(PriestMemorizePointsLeft)) for i in range (12): SpellButton = PriestMemorizeWindow.GetControl (i + 2) SpellButton.SetFlags (IE_GUI_BUTTON_PICTURE|IE_GUI_BUTTON_CHECKBOX, OP_OR) if i < len(Learnable): Spell = GemRB.GetSpell (Learnable[i]) SpellButton.SetTooltip(Spell["SpellName"]) SpellButton.SetSpellIcon(Learnable[i], 1) SpellButton.SetState (IE_GUI_BUTTON_ENABLED) SpellButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, PriestMemorizeSelectPress) SpellButton.SetVarAssoc ("SpellMask", 1 << i) else: SpellButton.SetState (IE_GUI_BUTTON_DISABLED) GemRB.SetToken ("number", str(PriestMemorizePointsLeft)) PriestMemorizeTextArea = PriestMemorizeWindow.GetControl (27) PriestMemorizeTextArea.SetText (17253) PriestMemorizeDoneButton = PriestMemorizeWindow.GetControl (0) PriestMemorizeDoneButton.SetState (IE_GUI_BUTTON_DISABLED) PriestMemorizeDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, PriestMemorizeDonePress) PriestMemorizeDoneButton.SetText (11973) PriestMemorizeDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) PriestMemorizeCancelButton = PriestMemorizeWindow.GetControl (29) PriestMemorizeCancelButton.SetState (IE_GUI_BUTTON_ENABLED) PriestMemorizeCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, PriestMemorizeCancelPress) PriestMemorizeCancelButton.SetText (13727) PriestMemorizeCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) PriestMemorizeWindow.SetVisible (WINDOW_VISIBLE) return def PriestMemorizeSelectPress(): global PriestMemorizeWindow, Learnable, PriestMemorizeTextArea, PriestMemorizeDoneButton, PriestMemorizePointsLeft PriestMemorized = GemRB.GetVar ("PriestMemorized") SpellMask = GemRB.GetVar ("SpellMask") Spell = abs(PriestMemorized - SpellMask) i = -1 while (Spell > 0): i = i + 1 Spell = Spell >> 1 Spell=GemRB.GetSpell (Learnable[i]) PriestMemorizeTextArea.SetText (Spell["SpellDesc"]) if SpellMask < PriestMemorized: PriestMemorizePointsLeft = PriestMemorizePointsLeft + 1 for i in range (len(Learnable)): SpellButton = PriestMemorizeWindow.GetControl (i + 2) if (((1 << i) & SpellMask) == 0): SpellButton.SetState (IE_GUI_BUTTON_ENABLED) PriestMemorizeDoneButton.SetState (IE_GUI_BUTTON_DISABLED) else: PriestMemorizePointsLeft = PriestMemorizePointsLeft - 1 if PriestMemorizePointsLeft == 0: for i in range (len(Learnable)): SpellButton = PriestMemorizeWindow.GetControl (i + 2) if ((1 << i) & SpellMask) == 0: SpellButton.SetState (IE_GUI_BUTTON_DISABLED) PriestMemorizeDoneButton.SetState (IE_GUI_BUTTON_ENABLED) PointsLeftLabel = PriestMemorizeWindow.GetControl (0x1000001b) PointsLeftLabel.SetText (str(PriestMemorizePointsLeft)) GemRB.SetVar ("PriestMemorized", SpellMask) return def PriestMemorizeDonePress(): global CharGenWindow, PriestMemorizeWindow, SkillsState if PriestMemorizeWindow: PriestMemorizeWindow.Unload () SkillsState = 5 CharGenWindow.SetVisible (WINDOW_VISIBLE) SkillsPress() return def PriestMemorizeCancelPress(): global CharGenWindow, PriestMemorizeWindow, SkillsState if PriestMemorizeWindow: PriestMemorizeWindow.Unload () SkillsState = 0 CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Appearance Selection def AppearancePress(): global CharGenWindow, AppearanceWindow, AppearanceTable global Portrait, AppearanceAvatarButton, PortraitName global AppearanceHairButton, AppearanceSkinButton global AppearanceMajorButton, AppearanceMinorButton global HairColor, SkinColor, MajorColor, MinorColor CharGenWindow.SetVisible (WINDOW_INVISIBLE) AppearanceWindow = GemRB.LoadWindow (13) AppearanceTable = GemRB.LoadTable ("PORTCOLR") if Portrait<0: PortraitIndex = 0 else: PortraitName = PortraitsTable.GetRowName (Portrait) PortraitIndex = AppearanceTable.GetRowIndex (PortraitName + "L") HairColor = AppearanceTable.GetValue (PortraitIndex, 1) GemRB.SetVar ("HairColor", HairColor) SkinColor = AppearanceTable.GetValue (PortraitIndex, 0) GemRB.SetVar ("SkinColor", SkinColor) MajorColor = AppearanceTable.GetValue (PortraitIndex, 2) GemRB.SetVar ("MajorColor", MajorColor) MinorColor = AppearanceTable.GetValue (PortraitIndex, 3) GemRB.SetVar ("MinorColor", MinorColor) AppearanceAvatarButton = AppearanceWindow.GetControl (1) AppearanceAvatarButton.SetState (IE_GUI_BUTTON_LOCKED) AppearanceAvatarButton.SetFlags (IE_GUI_BUTTON_PICTURE|IE_GUI_BUTTON_ANIMATED, OP_OR) DrawAvatar() AppearanceHairButton = AppearanceWindow.GetControl (2) AppearanceHairButton.SetFlags (IE_GUI_BUTTON_PICTURE, OP_OR) AppearanceHairButton.SetState (IE_GUI_BUTTON_ENABLED) AppearanceHairButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AppearanceHairPress) AppearanceHairButton.SetBAM ("COLGRAD", 0, 0, HairColor) AppearanceSkinButton = AppearanceWindow.GetControl (3) AppearanceSkinButton.SetFlags (IE_GUI_BUTTON_PICTURE, OP_OR) AppearanceSkinButton.SetState (IE_GUI_BUTTON_ENABLED) AppearanceSkinButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AppearanceSkinPress) AppearanceSkinButton.SetBAM ("COLGRAD", 0, 0, SkinColor) AppearanceMajorButton = AppearanceWindow.GetControl (4) AppearanceMajorButton.SetFlags (IE_GUI_BUTTON_PICTURE, OP_OR) AppearanceMajorButton.SetState (IE_GUI_BUTTON_ENABLED) AppearanceMajorButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AppearanceMajorPress) AppearanceMajorButton.SetBAM ("COLGRAD", 0, 0, MajorColor) AppearanceMinorButton = AppearanceWindow.GetControl (5) AppearanceMinorButton.SetFlags (IE_GUI_BUTTON_PICTURE, OP_OR) AppearanceMinorButton.SetState (IE_GUI_BUTTON_ENABLED) AppearanceMinorButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AppearanceMinorPress) AppearanceMinorButton.SetBAM ("COLGRAD", 0, 0, MinorColor) AppearanceDoneButton = AppearanceWindow.GetControl (0) AppearanceDoneButton.SetState (IE_GUI_BUTTON_ENABLED) AppearanceDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AppearanceDonePress) AppearanceDoneButton.SetText (11973) AppearanceDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) AppearanceCancelButton = AppearanceWindow.GetControl (13) AppearanceCancelButton.SetState (IE_GUI_BUTTON_ENABLED) AppearanceCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AppearanceCancelPress) AppearanceCancelButton.SetText (13727) AppearanceCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) AppearanceWindow.SetVisible (WINDOW_VISIBLE) return def DrawAvatar(): global AppearanceAvatarButton global MyChar AvatarID = 0x6000 table = GemRB.LoadTable ("avprefr") lookup = CommonTables.Races.FindValue (3, GemRB.GetPlayerStat(MyChar, IE_RACE)) lookup = CommonTables.Races.GetRowName (lookup) AvatarID = AvatarID+table.GetValue (lookup, "RACE") table = GemRB.LoadTable ("avprefc") lookup = GUICommon.GetClassRowName (MyChar) AvatarID = AvatarID+table.GetValue (lookup, "PREFIX") table = GemRB.LoadTable ("avprefg") AvatarID = AvatarID + table.GetValue (GemRB.GetPlayerStat(MyChar,IE_SEX), GTV_STR) AvatarRef = CommonTables.Pdolls.GetValue (hex(AvatarID), "LEVEL1") AppearanceAvatarButton.SetPLT(AvatarRef, 0, MinorColor, MajorColor, SkinColor, 0, 0, HairColor, 0) return def AppearanceHairPress(): GemRB.SetVar ("ColorType", 0) AppearanceColorChoice (GemRB.GetVar ("HairColor")) return def AppearanceSkinPress(): GemRB.SetVar ("ColorType", 1) AppearanceColorChoice (GemRB.GetVar ("SkinColor")) return def AppearanceMajorPress(): GemRB.SetVar ("ColorType", 2) AppearanceColorChoice (GemRB.GetVar ("MajorColor")) return def AppearanceMinorPress(): GemRB.SetVar ("ColorType", 3) AppearanceColorChoice (GemRB.GetVar ("MinorColor")) return def AppearanceColorChoice (CurrentColor): global AppearanceWindow, AppearanceColorWindow AppearanceWindow.SetVisible (WINDOW_INVISIBLE) AppearanceColorWindow = GemRB.LoadWindow (14) AppearanceColorTable = GemRB.LoadTable ("clowncol") ColorType = GemRB.GetVar ("ColorType") GemRB.SetVar ("SelectedColor", CurrentColor) for i in range (34): ColorButton = AppearanceColorWindow.GetControl (i) ColorButton.SetState (IE_GUI_BUTTON_ENABLED) ColorButton.SetFlags (IE_GUI_BUTTON_PICTURE, OP_OR) for i in range (34): Color = AppearanceColorTable.GetValue (ColorType, i) if Color != "*": ColorButton = AppearanceColorWindow.GetControl (i) ColorButton.SetBAM ("COLGRAD", 2, 0, Color) ColorButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AppearanceColorSelected) ColorButton.SetVarAssoc ("SelectedColor", Color) AppearanceColorWindow.SetVisible (WINDOW_VISIBLE) return def AppearanceColorSelected(): global HairColor, SkinColor, MajorColor, MinorColor global AppearanceWindow, AppearanceColorWindow global AppearanceHairButton, AppearanceSkinButton global AppearanceMajorButton, AppearanceMinorButton if AppearanceColorWindow: AppearanceColorWindow.Unload () ColorType = GemRB.GetVar ("ColorType") if ColorType == 0: HairColor = GemRB.GetVar ("SelectedColor") GemRB.SetVar ("HairColor", HairColor) AppearanceHairButton.SetBAM ("COLGRAD", 0, 0, HairColor) elif ColorType == 1: SkinColor = GemRB.GetVar ("SelectedColor") GemRB.SetVar ("SkinColor", SkinColor) AppearanceSkinButton.SetBAM ("COLGRAD", 0, 0, SkinColor) elif ColorType == 2: MajorColor = GemRB.GetVar ("SelectedColor") GemRB.SetVar ("MajorColor", MajorColor) AppearanceMajorButton.SetBAM ("COLGRAD", 0, 0, MajorColor) elif ColorType == 3: MinorColor = GemRB.GetVar ("SelectedColor") GemRB.SetVar ("MinorColor", MinorColor) AppearanceMinorButton.SetBAM ("COLGRAD", 0, 0, MinorColor) DrawAvatar() AppearanceWindow.SetVisible (WINDOW_VISIBLE) return def AppearanceDonePress(): global CharGenWindow, AppearanceWindow if AppearanceWindow: AppearanceWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) CharSoundSelect() return def AppearanceCancelPress(): global CharGenWindow, AppearanceWindow if AppearanceWindow: AppearanceWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) return def CharSoundSelect(): global CharGenWindow, CharSoundWindow, CharSoundTable, CharSoundStrings global CharSoundVoiceList, VerbalConstants CharGenWindow.SetVisible (WINDOW_INVISIBLE) CharSoundWindow = GemRB.LoadWindow (19) CharSoundTable = GemRB.LoadTable ("CHARSND") CharSoundStrings = GemRB.LoadTable ("CHARSTR") VerbalConstants = [CharSoundTable.GetRowName(i) for i in range(CharSoundTable.GetRowCount())] CharSoundVoiceList = CharSoundWindow.GetControl (45) RowCount=CharSoundVoiceList.ListResources(CHR_SOUNDS) CharSoundPlayButton = CharSoundWindow.GetControl (47) CharSoundPlayButton.SetState (IE_GUI_BUTTON_ENABLED) CharSoundPlayButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, CharSoundPlayPress) CharSoundPlayButton.SetText (17318) CharSoundTextArea = CharSoundWindow.GetControl (50) CharSoundTextArea.SetText (11315) CharSoundDoneButton = CharSoundWindow.GetControl (0) CharSoundDoneButton.SetState (IE_GUI_BUTTON_ENABLED) CharSoundDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, CharSoundDonePress) CharSoundDoneButton.SetText (11973) CharSoundDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) CharSoundCancelButton = CharSoundWindow.GetControl (10) CharSoundCancelButton.SetState (IE_GUI_BUTTON_ENABLED) CharSoundCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, CharSoundCancelPress) CharSoundCancelButton.SetText (13727) CharSoundCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) CharSoundWindow.SetVisible (WINDOW_VISIBLE) return def CharSoundPlayPress(): global CharGenWindow, CharSoundWindow, CharSoundTable, CharSoundStrings global CharSoundVoiceList, SoundIndex, VerbalConstants row = CharSoundVoiceList.QueryText () GemRB.SetPlayerSound (MyChar, row) #play sound as sound slot GemRB.VerbalConstant (MyChar, int(VerbalConstants[SoundIndex])) SoundIndex += 1 if SoundIndex >= len(VerbalConstants): SoundIndex = 0 return def CharSoundDonePress(): global CharGenWindow, CharSoundWindow, AppearanceButton, BiographyButton, NameButton, CharGenState if CharSoundWindow: CharSoundWindow.Unload () AppearanceButton.SetState (IE_GUI_BUTTON_DISABLED) AppearanceButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) BiographyButton.SetState (IE_GUI_BUTTON_ENABLED) NameButton.SetState (IE_GUI_BUTTON_ENABLED) NameButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) CharGenState = 7 SetCharacterDescription() CharGenWindow.SetVisible (WINDOW_VISIBLE) return def CharSoundCancelPress(): global CharGenWindow, CharSoundWindow if CharSoundWindow: CharSoundWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Biography Selection def BiographyPress(): global CharGenWindow, BiographyWindow, BiographyField CharGenWindow.SetVisible (WINDOW_INVISIBLE) BiographyWindow = GemRB.LoadWindow (51) BiographyField = BiographyWindow.GetControl (4) BiographyTextArea = BiographyWindow.CreateTextArea(100, 0, 0, 0, 0, "NORMAL", IE_FONT_ALIGN_CENTER) # ID/position/size dont matter. we will substitute later BiographyField = BiographyTextArea.SubstituteForControl(BiographyField) BiographyField.SetStatus (IE_GUI_CONTROL_FOCUSED) BIO = GemRB.GetToken("Biography") if BIO: BiographyField.SetText (BIO) else: BiographyField.SetText (19423) BiographyClearButton = BiographyWindow.GetControl (5) BiographyClearButton.SetState (IE_GUI_BUTTON_ENABLED) BiographyClearButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, BiographyClearPress) BiographyClearButton.SetText (18622) BiographyCancelButton = BiographyWindow.GetControl (2) BiographyCancelButton.SetState (IE_GUI_BUTTON_ENABLED) BiographyCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, BiographyCancelPress) BiographyCancelButton.SetText (13727) BiographyCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) BiographyDoneButton = BiographyWindow.GetControl (1) BiographyDoneButton.SetState (IE_GUI_BUTTON_ENABLED) BiographyDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, BiographyDonePress) BiographyDoneButton.SetText (11973) BiographyWindow.SetVisible (WINDOW_VISIBLE) return def BiographyClearPress(): global BiographyWindow, BiographyField BiographyField.SetText ("") return def BiographyCancelPress(): global CharGenWindow, BiographyWindow if BiographyWindow: BiographyWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) return def BiographyDonePress(): global CharGenWindow, BiographyWindow, BiographyField BIO = BiographyField.QueryText () GemRB.SetToken ("Biography", BIO) # just for any window reopens BioStrRefSlot = 63 DefaultBIO = 19423 if BIO == GemRB.GetString (DefaultBIO): GemRB.SetPlayerString (MyChar, BioStrRefSlot, DefaultBIO) else: # unlike tob, iwd has no marked placeholders (or strings) at 62015; but we have special magic in place ... # still, use the returned strref in case anything unexpected happened ref = GemRB.CreateString (62015+MyChar, BIO) GemRB.SetPlayerString (MyChar, BioStrRefSlot, ref) if BiographyWindow: BiographyWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Name Selection def NamePress(): global CharGenWindow, NameWindow, NameDoneButton, NameField CharGenWindow.SetVisible (WINDOW_INVISIBLE) NameWindow = GemRB.LoadWindow (5) NameDoneButton = NameWindow.GetControl (0) NameDoneButton.SetState (IE_GUI_BUTTON_DISABLED) NameDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, NameDonePress) NameDoneButton.SetText (11973) NameDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) NameCancelButton = NameWindow.GetControl (3) NameCancelButton.SetState (IE_GUI_BUTTON_ENABLED) NameCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, NameCancelPress) NameCancelButton.SetText (13727) NameCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) NameField = NameWindow.GetControl (2) NameField.SetEvent (IE_GUI_EDIT_ON_CHANGE, NameEditChange) NameField.SetText (GemRB.GetToken ("CHARNAME") ) NameField.SetStatus (IE_GUI_CONTROL_FOCUSED) NameWindow.SetVisible (WINDOW_VISIBLE) NameEditChange() return def NameEditChange(): global NameField if NameField.QueryText () == "": NameDoneButton.SetState (IE_GUI_BUTTON_DISABLED) else: NameDoneButton.SetState (IE_GUI_BUTTON_ENABLED) return def NameDonePress(): global CharGenWindow, CharGenState, NameWindow, NameField, AcceptButton GemRB.SetToken ("CHARNAME", NameField.QueryText () ) if NameWindow: NameWindow.Unload () CharGenState = 8 AcceptButton.SetState (IE_GUI_BUTTON_ENABLED) AcceptButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) SetCharacterDescription() CharGenWindow.SetVisible (WINDOW_VISIBLE) return def NameCancelPress(): global CharGenWindow, NameWindow GemRB.SetToken ("CHARNAME", "") if NameWindow: NameWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) return # Import Character def ImportPress(): global CharGenWindow, ImportWindow global CharImportList CharGenWindow.SetVisible (WINDOW_INVISIBLE) ImportWindow = GemRB.LoadWindow (20) TextAreaControl = ImportWindow.GetControl(4) TextAreaControl.SetText(10963) GemRB.SetVar ("Selected", 0) CharImportList = ImportWindow.GetControl(2) CharImportList.SetVarAssoc ("Selected",0) CharImportList.ListResources(CHR_EXPORTS) ImportDoneButton = ImportWindow.GetControl (0) ImportDoneButton.SetState (IE_GUI_BUTTON_ENABLED) ImportDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ImportDonePress) ImportDoneButton.SetText (11973) ImportDoneButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) ImportCancelButton = ImportWindow.GetControl (1) ImportCancelButton.SetState (IE_GUI_BUTTON_ENABLED) ImportCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ImportCancelPress) ImportCancelButton.SetText (13727) ImportCancelButton.SetFlags (IE_GUI_BUTTON_CANCEL, OP_OR) ImportWindow.SetVisible (WINDOW_VISIBLE) return def ImportDonePress(): global CharGenWindow, ImportWindow, CharImportList global CharGenState, SkillsState, Portrait, ImportedChar # Import the character from the chosen name GemRB.CreatePlayer (CharImportList.QueryText(), MyChar|0x8000, 1) GemRB.SetToken ("CHARNAME", GemRB.GetPlayerName (MyChar) ) GemRB.SetToken ("SmallPortrait", GemRB.GetPlayerPortrait (MyChar, 1) ) PortraitName = GemRB.GetPlayerPortrait (MyChar, 0) GemRB.SetToken ("LargePortrait", PortraitName ) PortraitButton.SetPicture (PortraitName) Portrait = -1 ImportedChar = 1 CharGenState = 7 SkillsState = 5 SetCharacterDescription () GenderButton.SetState (IE_GUI_BUTTON_DISABLED) GenderButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) RaceButton.SetState (IE_GUI_BUTTON_DISABLED) RaceButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) ClassButton.SetState (IE_GUI_BUTTON_DISABLED) ClassButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) AlignmentButton.SetState (IE_GUI_BUTTON_DISABLED) AlignmentButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) AbilitiesButton.SetState (IE_GUI_BUTTON_DISABLED) AbilitiesButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) SkillsButton.SetState (IE_GUI_BUTTON_DISABLED) SkillsButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_NAND) AppearanceButton.SetState (IE_GUI_BUTTON_ENABLED) AppearanceButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) BiographyButton.SetState (IE_GUI_BUTTON_DISABLED) BiographyButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) NameButton.SetState (IE_GUI_BUTTON_DISABLED) NameButton.SetFlags (IE_GUI_BUTTON_DEFAULT, OP_OR) CharGenWindow.SetVisible (WINDOW_VISIBLE) if ImportWindow: ImportWindow.Unload () return def ImportCancelPress(): global CharGenWindow, ImportWindow if ImportWindow: ImportWindow.Unload () CharGenWindow.SetVisible (WINDOW_VISIBLE) return
Tomsod/gemrb
gemrb/GUIScripts/iwd/CharGen.py
Python
gpl-2.0
92,820
# -*- coding: utf-8 -*- # # This file is part of EUDAT B2Share. # Copyright (C) 2017 CERN, SurfsSara # # B2Share 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. # # B2Share 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 B2Share; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """B2Share migration command line interface. These commands were designed only for the migration of data from the instance hosted by CSC on https://b2share.eudat.eu . WARNING - Operating these commands on local instances may severely impact data integrity and/or lead to dysfunctional behaviour.""" import logging import os import requests import traceback from urllib.parse import urlunsplit, urljoin, urlsplit import click from flask_cli import with_appcontext from flask import current_app from invenio_db import db from invenio_indexer.api import RecordIndexer from invenio_records.api import Record from .migration import (download_v1_data, process_v1_record, main_diff, make_v2_index, records_endpoint, directly_list_v2_record_ids) @click.group() def migrate(): """Migration commands. WARNING csc only.""" @migrate.command() @with_appcontext @click.option('-v', '--verbose', count=True) @click.option('-d', '--download', is_flag=True, default=False) @click.option('-l', '--limit', default=None) @click.argument('token') @click.argument('download_directory') def import_v1_data(verbose, download, token, download_directory,limit): click.secho("Importing data to the current instance") logger = logging.getLogger("sqlalchemy.engine") logger.setLevel(logging.ERROR) logfile = open(current_app.config.get('MIGRATION_LOGFILE'), 'a') logfile.write("\n\n\n~~~ Starting import task download={} limit={}" .format(download, limit)) if os.path.isdir(download_directory): os.chdir(download_directory) else: raise click.ClickException("%s does not exist or is not a directory. If you want to import " "records specify an empty, existing directory." % download_directory) if limit and not download: raise click.ClickException("Limit can only be set with download") if download: filelist = os.listdir('.') if len(filelist) > 0: click.secho("!!! Downloading data into existing directory, " "overwriting previous data", fg='red') click.secho("----------") click.secho("Downloading data into directory %s" % download_directory) if limit is not None: limit = int(limit) click.secho("Limiting to %d records for debug purposes" % limit) download_v1_data(token, download_directory, logfile, limit) indexer = RecordIndexer(record_to_index=lambda record: ('records', 'record')) dirlist = os.listdir('.') click.secho("-----------") click.secho("Processing %d downloaded records" % (len(dirlist))) base_url = urlunsplit(( current_app.config.get('PREFERRED_URL_SCHEME', 'http'), # current_app.config['SERVER_NAME'], current_app.config['JSONSCHEMAS_HOST'], current_app.config.get('APPLICATION_ROOT') or '', '', '' )) for d in dirlist: try: process_v1_record(d, indexer, base_url, logfile) except: logfile.write("\n********************") logfile.write("\nERROR: exception while processing record /{}/___record.json___\n" .format(d)) logfile.write(traceback.format_exc()) logfile.write("\n********************") logfile.close() @migrate.command() @with_appcontext @click.option('-u', '--update', is_flag=True, default=False) @click.argument('base_url') def check_pids(update, base_url): """ Checks and optionally fixes ePIC PIDs from records in the `base_url`. The ePIC PIDs in the first 1000 records of the `base_url` B2SHARE site are checked. The PIDs are extracted from the main ePIC_PID field and the alternative_identifiers fields (based on the type being equal to 'ePIC_PID'). Only the PIDs starting with the configured ePIC prefix are considered. If the PID does not point to the record it's contained in, then an error message is generated. When the `-u` argument is used, the current configuration variables are used to update the PID with the correct target URL. """ epic_base_url = str(current_app.config.get('CFG_EPIC_BASEURL')) epic_username = str(current_app.config.get('CFG_EPIC_USERNAME')) epic_password = str(current_app.config.get('CFG_EPIC_PASSWORD')) epic_prefix = str(current_app.config.get('CFG_EPIC_PREFIX')) click.secho('Checking epic pids for all records') record_search = requests.get(urljoin(base_url, "api/records"), {'size': 1000, 'page': 1}, verify=False) records = record_search.json()['hits']['hits'] for rec in records: recid = str(rec['id']) click.secho('\n--- Checking epic pids for record {}'.format(recid)) rec_url = rec['links']['self'].replace("/api/records/", "/records/") metadata = rec['metadata'] epic_list = [aid['alternate_identifier'] for aid in metadata.get('alternate_identifiers', []) if aid['alternate_identifier_type'] == 'ePIC_PID'] if metadata.get('ePIC_PID'): epic_list.append(metadata.get('ePIC_PID')) for epic_url in epic_list: pid = urlsplit(epic_url).path.strip('/') if not pid.startswith(epic_prefix): continue # is not one of our pids click.secho(' {}'.format(pid)) target_request = requests.get(epic_url, allow_redirects=False) if target_request.status_code < 300 or target_request.status_code >= 400: click.secho('Record {}: error retrieving epic pid information: {}' .format(recid, epic_url), fg='yellow', bold=True) continue target_url = target_request.headers.get('Location') if is_same_url(target_url, rec_url): continue click.secho('Record {}: error: bad epic pid: {}'.format(recid, epic_url), fg='red', bold=True) if update: change_req = requests.put(urljoin(epic_base_url, pid), json=[{'type': 'URL', 'parsed_data': rec_url}], auth=(epic_username, epic_password), headers={'Content-Type': 'application/json', 'Accept': 'application/json'}) if change_req.status_code >= 300: click.secho('Record {}: error setting epic pid target url: {}, error code {}' .format(recid, epic_url, change_req.status_code), fg='red', bold=True) else: click.secho('Record {}: fixed epic pid target url: {}' .format(recid, epic_url), fg='green', bold=True) def is_same_url(url1, url2): u1 = urlsplit(url1) u2 = urlsplit(url2) return u1.scheme == u2.scheme and u1.netloc == u2.netloc and \ u1.path == u2.path and u1.query == u2.query @migrate.command() @with_appcontext def diff_sites(): main_diff() @migrate.command() @with_appcontext def swap_pids(): """ Fix the invalid creation of new ePIC_PIDs for migrated files. Swaps with the old b2share v1 PID that we stored in alternate_identifiers and puts the wrongly created ePIC_PID in alternate_identifiers. Note this creates a new version of the invenio record (at the time of writing we do not show the latest version of invenio record objects) """ for search_record in directly_list_v2_record_ids(): recid = search_record.get('_id') inv_record = Record.get_record(recid) if inv_record.revision_id >= 1: print ("Skipping record {}: too many revisions ({}), " "may have been already updated".format( recid, inv_record.revision_id)) continue aids = None if 'alternate_identifiers' in inv_record.keys(): aids = inv_record['alternate_identifiers'] found = False found_v1_id = False for aid in aids: if aid['alternate_identifier_type']=='B2SHARE_V1_ID': found_v1_id = True if aid['alternate_identifier_type']=='ePIC_PID': new_pid = aid['alternate_identifier'] _pid = inv_record['_pid'] for pid in _pid: if pid['type']=='ePIC_PID': old_pid = pid['value'] found = True break break found = found and found_v1_id if not found: error_msg = """***** INFO - this record does not have ePIC_PID in _pid or alternate_identifiers or does not have a B2SHARE_V1_ID in alternate_identifiers""" print(error_msg) print(inv_record['titles']) print(recid) print("********") else: print("SWAPPING %s %s" % (old_pid, new_pid)) for pid in inv_record['_pid']: if pid['type']=='ePIC_PID': pid['value']=new_pid break for aid in inv_record['alternate_identifiers']: if aid['alternate_identifier_type']=='ePIC_PID': aid['alternate_identifier']=old_pid break inv_record.commit() db.session.commit() @migrate.command() @with_appcontext @click.argument('v1_api_url') @click.argument('v1_access_token') @click.argument('v2_api_url') @click.argument('v2_access_token') def extract_alternate_identifiers(v1_api_url, v1_access_token, v2_api_url, v2_access_token): """Extracting alternate identifiers from v1 records""" v2_index = make_v2_index(v2_api_url, v2_access_token) click.secho('Extracting alternate identifiers from v1 records') params = {'access_token': v1_access_token, 'page_size': 100} for page in range(0, 7): params['page_offset'] = page req = requests.get(records_endpoint(v1_api_url), params=params, verify=False) req.raise_for_status() recs = req.json().get('records') for record in recs: recid = str(record.get('record_id')) alternate_identifier = str(record.get('alternate_identifier')) if not alternate_identifier: continue click.secho("alternate_identifier: {}".format(alternate_identifier)) click.secho(" domain: {}".format(record.get('domain'))) click.secho(" old record ID: {}".format(recid)) v2 = v2_index.get(recid) if v2: click.secho(" new record ID: {}".format(v2.get('id'))) click.secho(" new record URL: {}".format(v2.get('links', {}).get('self'))) click.secho(" new record PID: {}".format(v2.get('metadata', {}).get('ePIC_PID'))) @migrate.command() @with_appcontext @click.argument('v1_api_url') @click.argument('v1_access_token') # @click.argument('v2_api_url') def add_missing_alternate_identifiers(v1_api_url, v1_access_token): """Add missing alternate identifiers from v1 records to the published v2 records in the current instance""" v2_index = make_v2_index(None, None) # make index of current site # v2_index = make_v2_index(v2_api_url, None) click.secho('Adding missing alternate identifiers from v1 records') params = {'access_token': v1_access_token, 'page_size': 100} for page in range(0, 7): params['page_offset'] = page req = requests.get(records_endpoint(v1_api_url), params=params, verify=False) req.raise_for_status() for v1_record in req.json().get('records'): v1_recid = str(v1_record.get('record_id')) alternate_identifier = str(v1_record.get('alternate_identifier', '')).strip() if not alternate_identifier: continue ai_type = guess_alternate_identifier_type(alternate_identifier) click.secho("alternate_identifier: {}" "\n\told id: {}\n\taltid type: {}".format( alternate_identifier, v1_recid, ai_type)) if not v2_index.get(v1_recid): click.secho("\tcannot find recid {}".format(v1_recid), fg='red') continue record_search = v2_index.get(v1_recid) v2_recid = record_search.get('id') or record_search.get('_id') record = Record.get_record(v2_recid) # record = v2_index.get(v1_recid).get('metadata') exists = [ai for ai in record.get('alternate_identifiers', []) if ai.get('alternate_identifier') == alternate_identifier] if exists: click.secho("\talready present in record: {}".format(v2_recid)) else: ais = record.get('alternate_identifiers', []) new_ai = {'alternate_identifier': alternate_identifier, 'alternate_identifier_type': ai_type} ais.insert(0, new_ai) record['alternate_identifiers'] = ais record.commit() click.secho("\tupdated new record: {}".format(v2_recid)) db.session.commit() def guess_alternate_identifier_type(aid): for x in ['http://dx.doi.org/', 'http://doi.org/', 'doi.org', 'dx.doi.org', 'doi.', '10.']: if aid.startswith(x): return 'DOI' if aid.startswith('URN:'): return 'URN' if aid.startswith('http://') or aid.startswith('https://'): return 'URL' return 'Other'
SarahBA/b2share
demo/b2share_demo/migration_cli.py
Python
gpl-2.0
15,061
# coding: utf-8 # In[9]: import numpy as np import networkx as nx # In[2]: G = nx.karate_club_graph() # In[3]: L = nx.laplacian_matrix(G) # In[4]: L # In[11]: d = np.array([v for k,v in nx.degree(G).items()]) # In[12]: d # In[14]: L.dot(d) # In[16]: e = np.array([v for k,v in nx.betweenness_centrality(G).items()]) # In[17]: L.dot(e) # In[ ]:
DavidMcDonald1993/ghsom
laplacian.py
Python
gpl-2.0
376
# -*- coding: utf-8 -*- # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: from pida.core.events import EventsConfig import unittest class MockCallback(object): def __init__(self): self.calls = [] def __call__(self, **kw): self.calls.append(kw) class MockService(object): """used instead of None cause weakref proxy cant handle None""" class EventTestCase(unittest.TestCase): def setUp(self): self.e = EventsConfig(MockService()) self.c = MockCallback() self.e.publish('initial') self.e.subscribe('initial', self.c) def test_emit_event(self): self.e.emit('initial') self.assertEqual(len(self.c.calls), 1) self.assertEqual(self.c.calls[0], {}) def test_emit_event_multiple(self): self.e.emit('initial') self.e.emit('initial') self.e.emit('initial') self.assertEqual(len(self.c.calls), 3) def test_emit_event_with_argument(self): self.e.emit('initial', parameter=1) self.assertEqual(len(self.c.calls), 1) self.assertEqual(self.c.calls[0], {'parameter': 1}) def test_emit_event_bad_argument(self): try: self.e.emit('initial', 1) raise AssertionError('TypeError not raised') except TypeError: pass
fermat618/pida
tests/core/test_events.py
Python
gpl-2.0
1,326
#! /usr/bin/env python """ ############################################################################################# # # # Name: LogFileAccessManager.py # # @author: Nicholas Lemay # # @license: MetPX Copyright (C) 2004-2006 Environment Canada # MetPX comes with ABSOLUTELY NO WARRANTY; For details type see the file # named COPYING in the root of the source directory tree. # # Description : Utility class used to manage the access to the log files by the # the pickle updater. # # Note : If this file is to be modified, please run the main() method at the bottom of this # file to make sure everything still works properly. Feel free to add tests if needed. # # While using this class, you can either use only one file with all your entries # and give a different identifier to all of you entries, or you can use different # files. # # Using a single file however can be problematic if numerous process try to update # the file at the same time. # ############################################################################################# """ import os, sys, commands, time sys.path.insert(1, os.path.dirname( os.path.abspath(__file__) ) + '/../../') from pxStats.lib.StatsPaths import StatsPaths from pxStats.lib.CpickleWrapper import CpickleWrapper class LogFileAccessManager(object): def __init__( self, accessDictionary = None, accessFile = "" ): """ @summary: LogFileAccessManager constructor. @param accessArrays: @param accessFile: """ paths = StatsPaths() paths.setPaths() if accessFile =="": accessFile = paths.STATSLOGACCESS + "default" self.accessDictionary = accessDictionary or {} # Empty array to start with. self.accessFile = accessFile #File that contains the current file acces. if self.accessDictionary == {} and os.path.isfile( self.accessFile ): self.loadAccessFile() def saveAccessDictionary( self ): """ @summary: Saves the current accessDictionary into the accessfile. """ if not os.path.isdir( os.path.dirname( self.accessFile ) ): os.makedirs( os.path.dirname( self.accessFile ) ) CpickleWrapper.save( self.accessDictionary, self.accessFile ) def loadAccessFile(self): """ @summary: Loads the accessFile into the accessDictionary. """ self.accessDictionary = CpickleWrapper.load( self.accessFile ) def getLineAssociatedWith( self, identifier ): """ @param identifier: Identifier string of the following format: fileType_client/sourcename_machineName @return: returns the first line of the last file accessed by the identifier. If identifier has no associated line, the returned line will be "". """ line = "" try:#In case the key does not exist. line = self.accessDictionary[ identifier ][0] except:#Pass keyerror pass return line def getLastReadPositionAssociatedWith(self, identifier): """ @param identifier: Identifier string of the following format: fileType_client/sourcename_machineName @return: returns the last read position of the last file accessed by the identifier. If no position is associated with identifier will return 0. """ lastReadPositon = 0 try:#In case the key does not exist. lastReadPositon = self.accessDictionary[ identifier ][1] except:#Pass keyerror pass return lastReadPositon def getFirstLineFromFile(self, fileName): """ @summary: Reads the first line of a file and returns it. @param fileName: File from wich you want to know @return: The first line of the specified file. """ firstLine = "" if os.path.isfile( fileName ): fileHandle = open( fileName, "r") firstLine = fileHandle.readline() fileHandle.close() return firstLine def getFirstLineAndLastReadPositionAssociatedwith(self, identifier): """ @param identifier: Identifier string of the following format: fileType_client/sourcename_machineName @return : A tuple containing the first line of the last file read(in string format) and the last read position (int format). """ line = "" lastReadPositon = 0 try:#In case the key does not exist. line ,lastReadPositon = self.accessDictionary[ identifier ] except:#Pass keyerror pass return line, lastReadPositon def setFirstLineAssociatedwith(self, firstLine, identifier ): """ @summary: Simple setter that hides data structure implementation so that methods still work if implementation is ever to change. @param firstLine: First line to set. @param identifier:Identifier string of the following format: fileType_client/sourcename_machineName """ currentLastReadPosition = self.getLastReadPositionAssociatedWith(identifier) self.accessDictionary[ identifier ] = firstLine, currentLastReadPosition def setLastReadPositionAssociatedwith(self, lastReadPosition, identifier ): """ @summary: Simple setter that hides data structure implementation so that methods still work if implementation is ever to change. @param lastReadPosition: Position to set. @param identifier:Identifier string of the following format: fileType_client/sourcename_machineName """ currentFirstLine = self.getLineAssociatedWith(identifier) self.accessDictionary[ identifier ] = currentFirstLine, lastReadPosition def setFirstLineAndLastReadPositionAssociatedwith(self, firstLine, lastReadPosition, identifier ): """ @summary: Simple setter that hides data structure implementation so that methods still work if implementation is ever to change. @param firstLine: First line to set. @param lastReadPosition: Position to set. @param identifier:Identifier string of the following format: fileType_client/sourcename_machineName """ self.accessDictionary[ identifier ] = (firstLine, lastReadPosition) def isTheLastFileThatWasReadByThisIdentifier(self, fileName, identifier ): """ @summary : Returns whether or not(True or False ) the specified file was the last one read by the identifier. @param fileName: Name fo the file to be verified. @param identifier: Identifier string of the following format: fileType_client/sourcename_machineName @return: Returns whether or not(True or False ) the specified file was the last one read by the identifier. """ lastFileThatWasRead = False if os.path.isfile(fileName): lastLineRead = self.getLineAssociatedWith(identifier) filehandle = open( fileName, "r") firstLineOfTheFile = filehandle.readline() if lastLineRead == firstLineOfTheFile: lastFileThatWasRead = True filehandle.close() return lastFileThatWasRead def main(): """ @summary: Small test case to see if everything works out well. @note: IMPORTANT if you modifiy this file, run this method to make sure it still passes all the tests. If test are no longer valid, please modify accordingly. """ from LogFileAccessManager import LogFileAccessManager paths = StatsPaths() paths.setPaths() # # Create text file for testing. # testDirectory = paths.STATSDATA + "logFileAccessTestFolder/" if not os.path.isdir( testDirectory ) : os.makedirs(testDirectory) testTextfile = testDirectory + "testTextfile" fileHandle = open( testTextfile , 'w' ) old_stdout = sys.stdout #redirect standard output to the file sys.stdout = fileHandle for i in range(100): print "%s-A line written for testing." %i fileHandle.close() sys.stdout = old_stdout #resets standard output # #Read file like normal file and stop in the middle. # fileHandle = open( testTextfile , 'r' ) for i in range(50): fileHandle.readline() lastReadPosition = fileHandle.tell() fileHandle.close() # # Set LogFileAccessManager with the previous infos. # testFile = testDirectory + "testLFAMfile" lfam = LogFileAccessManager( accessFile = testFile ) firstLine = lfam.getFirstLineFromFile( testTextfile ) lfam.setFirstLineAndLastReadPositionAssociatedwith( firstLine, lastReadPosition, "testId" ) # # Unit-like test every method to make sure the result is what is expected. # Section for getters. # if firstLine != "0-A line written for testing.\n": print "getFirstLineFromFile is corrupted. Please repair " if lfam.getFirstLineAndLastReadPositionAssociatedwith("testId") != ("0-A line written for testing.\n",1540 ): print "getFirstLineAndLastReadPositionAssociatedwith is corrupted. Please repair." if lfam.getLastReadPositionAssociatedWith( "testId" ) != 1540: print "getLastReadPositionAssociatedWith is corrupted. Please repair." # # Section for testing Setters # lfam.setFirstLineAssociatedwith("firstLine", 'testId') if lfam.getLineAssociatedWith('testId') != 'firstLine': print "setFirstLineAssociatedwith is corrupted. Please repair." lfam.setLastReadPositionAssociatedwith( 18987, 'testId') if lfam.getLastReadPositionAssociatedWith('testId') != 18987: print "setLastReadPositionAssociatedwith is corrupted. Please repair." lfam.setFirstLineAndLastReadPositionAssociatedwith("testline2", 1285647, 'testId') if lfam.getFirstLineAndLastReadPositionAssociatedwith('testId') != ("testline2", 1285647): print "setFirstLineAndLastReadPositionAssociatedwith is corrupted. Please repair." lfam.saveAccessDictionary() lfam.loadAccessFile() if lfam.getFirstLineAndLastReadPositionAssociatedwith('testId') != ("testline2", 1285647): print "saveAccessDictionary and/or loadAccessFile is corrupted. Please repair." print "Testing done." if __name__ == '__main__': main()
khosrow/metpx
pxStats/lib/LogFileAccessManager.py
Python
gpl-2.0
12,296
from Components.ActionMap import ActionMap from Components.Sources.List import List from Components.Sources.StaticText import StaticText from Components.ConfigList import ConfigList from Components.config import * from Components.Console import Console from skin import loadSkin from Components.Label import Label from Screens.Screen import Screen from Components.Pixmap import Pixmap from Plugins.Plugin import PluginDescriptor from Tools.Directories import pathExists, fileExists from Weather import * from Search_Id import * from Screens.MessageBox import MessageBox from Screens.Standby import TryQuitMainloop from __init__ import _ import os import commands from enigma import getDesktop from boxbranding import getMachineName, getMachineBrand from Screens.InputBox import PinInput from Tools.BoundFunction import boundFunction config.plugins.mc_global = ConfigSubsection() config.plugins.mc_global.vfd = ConfigSelection(default='off', choices=[('off', 'off'), ('on', 'on')]) config.plugins.mc_globalsettings.upnp_enable = ConfigYesNo(default=False) #change to FullHD if getDesktop(0).size().width() == 1920: loadSkin("/usr/lib/enigma2/python/Plugins/Extensions/BMediaCenter/skins/defaultHD/skinHD.xml") else: loadSkin("/usr/lib/enigma2/python/Plugins/Extensions/BMediaCenter/skins/defaultHD/skin.xml") #try: # from enigma import evfd # config.plugins.mc_global.vfd.value = 'on' # config.plugins.mc_global.save() #except Exception as e: # print 'Media Center: Import evfd failed' try: from Plugins.Extensions.DVDPlayer.plugin import * dvdplayer = True except: print "Media Center: Import DVDPlayer failed" dvdplayer = False mcpath = '/usr/lib/enigma2/python/Plugins/Extensions/BMediaCenter/skins/defaultHD/images/' class DMC_MainMenu(Screen): def __init__(self, session): Screen.__init__(self, session) self["text"] = Label(_("My Music")) self["left"] = Pixmap() self["middle"] = Pixmap() self["right"] = Pixmap() self.Console = Console() self.oldbmcService = self.session.nav.getCurrentlyPlayingServiceReference() self.session.nav.stopService() # Disable OSD Transparency try: self.can_osd_alpha = open("/proc/stb/video/alpha", "r") and True or False except: self.can_osd_alpha = False if self.can_osd_alpha: open("/proc/stb/video/alpha", "w").write(str("255")) open("/proc/sys/vm/drop_caches", "w").write(str("3")) list = [] list.append((_("My Music"), "MC_AudioPlayer", "menu_music", "50")) list.append((_("My Music"), "MC_AudioPlayer", "menu_music", "50")) list.append((_("My Videos"), "MC_VideoPlayer", "menu_video", "50")) list.append((_("DVD Player"), "MC_DVDPlayer", "menu_video", "50")) list.append((_("My Pictures"), "MC_PictureViewer", "menu_pictures", "50")) list.append((_("Web Radio"), "MC_WebRadio", "menu_radio", "50")) list.append((_("VLC Player"), "MC_VLCPlayer", "menu_vlc", "50")) list.append((_("Weather Info"), "MC_WeatherInfo", "menu_weather", "50")) list.append((_("MUZU.TV"), "MUZU.TV", "menu_webmedia", "50")) list.append((_("Opera"), "Webbrowser", "menu_webbrowser", "50")) list.append((_("SHOUTcast"), "SHOUTcast", "menu_shoutcast", "50")) list.append((_("TSMedia"), "TSMedia", "menu_weblinks", "50")) list.append((_("Settings"), "MC_Settings", "menu_settings", "50")) list.append(("Exit", "Exit", "menu_exit", "50")) self["menu"] = List(list) self["actions"] = ActionMap(["OkCancelActions", "DirectionActions"], { "cancel": self.Exit, "ok": self.okbuttonClick, "right": self.next, "upRepeated": self.prev, "down": self.next, "downRepeated": self.next, "leftRepeated": self.prev, "rightRepeated": self.next, "up": self.prev, "left": self.prev }, -1) #if config.plugins.mc_global.vfd.value == "on": # evfd.getInstance().vfd_write_string(_("My Music")) if config.plugins.mc_globalsettings.upnp_enable.getValue(): if fileExists("/media/upnp") is False: os.mkdir("/media/upnp") os.system('djmount /media/upnp &') if self.isProtected() and config.ParentalControl.servicepin[0].value: self.onFirstExecBegin.append(boundFunction(self.session.openWithCallback, self.pinEntered, PinInput, pinList=[x.value for x in config.ParentalControl.servicepin], triesEntry=config.ParentalControl.retries.servicepin, title=_("Please enter the correct pin code"), windowTitle=_("Enter pin code"))) def isProtected(self): return config.ParentalControl.setuppinactive.value and config.ParentalControl.config_sections.bmediacenter.value def pinEntered(self, result): if result is None: self.closeProtectedScreen() elif not result: self.session.openWithCallback(self.close(), MessageBox, _("The pin code you entered is wrong."), MessageBox.TYPE_ERROR, timeout=3) def closeProtectedScreen(self, result=None): self.close(None) def checkNetworkState(self, str, retval, extra_args): if 'Collected errors' in str: self.session.openWithCallback(self.close, MessageBox, _("A background update check is in progress, please wait a few minutes and try again."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) elif not str: self.feedscheck = self.session.open(MessageBox,_('Please wait whilst feeds state is checked.'), MessageBox.TYPE_INFO, enable_input = False) self.feedscheck.setTitle(_('Checking Feeds')) cmd1 = "opkg update" self.CheckConsole = Console() self.CheckConsole.ePopen(cmd1, self.checkNetworkStateFinished) else: self.session.open(MessageBox,"Error: No Updateservice Avaible in Moment", MessageBox.TYPE_INFO) def checkNetworkStateFinished(self, result, retval,extra_args=None): if 'bad address' in result: self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Your %s %s is not connected to the internet, please check your network settings and try again.") % (getMachineBrand(), getMachineName()), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) elif ('wget returned 1' or 'wget returned 255' or '404 Not Found') in result: self.session.openWithCallback(self.InstallPackageFailed, MessageBox, _("Sorry feeds are down for maintenance, please try again later."), type=MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True) else: self.session.openWithCallback(self.InstallPackage, MessageBox, _('Ready to install %s ?') % self.service_name, MessageBox.TYPE_YESNO) self.Exit() def InstallPackageFailed(self, val): self.feedscheck.close() self.close() self.Exit() def InstallPackage(self, val): if val: self.doInstall(self.installComplete, self.service_name) else: self.feedscheck.close() self.close() def doInstall(self, callback, pkgname): self.message = self.session.open(MessageBox,_("please wait..."), MessageBox.TYPE_INFO, enable_input = False) self.message.setTitle(_('Installing Service')) self.Console.ePopen('/usr/bin/opkg install ' + pkgname, callback) def installComplete(self,result = None, retval = None, extra_args = None): self.session.open(TryQuitMainloop, 3) def InstallCheckDVD(self): self.service_name = 'enigma2-plugin-extensions-dvdplayer' self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState) def InstallCheckVLC(self): self.service_name = 'enigma2-plugin-extensions-vlcplayer' self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState) def InstallCheckSHOUT(self): self.service_name = 'enigma2-plugin-extensions-shoutcast' self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState) def InstallCheckTSMedia(self): self.service_name = 'enigma2-plugin-extensions-tsmedia-oe2.0' self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState) def InstallCheckMUZU(self): self.service_name = 'enigma2-plugin-extensions-muzutv' self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState) def InstallCheckWebbrowser(self): self.service_name = 'enigma2-plugin-extensions-hbbtv-opennfr-fullhd' self.Console.ePopen('/usr/bin/opkg list_installed ' + self.service_name, self.checkNetworkState) def next(self): self["menu"].selectNext() if self["menu"].getIndex() == 13: self["menu"].setIndex(1) #if self["menu"].getIndex() == 14: # self["menu"].setIndex(1) self.update() def prev(self): self["menu"].selectPrevious() if self["menu"].getIndex() == 0: self["menu"].setIndex(12) self.update() def update(self): if self["menu"].getIndex() == 1: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconSettingssw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconMusic.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconVideosw.png") elif self["menu"].getIndex() == 2: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconMusicsw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconVideo.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconDVDsw.png") elif self["menu"].getIndex() == 3: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconVideosw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconDVD.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconPicturesw.png") elif self["menu"].getIndex() == 4: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconDVDsw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconPicture.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconRadiosw.png") elif self["menu"].getIndex() == 5: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconPicturesw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconRadio.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconVLCsw.png") elif self["menu"].getIndex() == 6: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconRadiosw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconVLC.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconWeathersw.png") elif self["menu"].getIndex() == 7: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconVLCsw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconWeather.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconWebmediasw.png") elif self["menu"].getIndex() == 8: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconWeathersw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconWebmedia.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconWebbrowsersw.png") elif self["menu"].getIndex() == 9: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconWebmediasw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconWebbrowser.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconShoutcastsw.png") elif self["menu"].getIndex() == 10: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconWebbrowsersw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconShoutcast.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconWeblinkssw.png") elif self["menu"].getIndex() == 11: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconShoutcastsw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconWeblinks.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconSettingssw.png") elif self["menu"].getIndex() == 12: self["left"].instance.setPixmapFromFile(mcpath +"MenuIconWeblinkssw.png") self["middle"].instance.setPixmapFromFile(mcpath +"MenuIconSettings.png") self["right"].instance.setPixmapFromFile(mcpath +"MenuIconMusicsw.png") #if config.plugins.mc_global.vfd.value == "on": # evfd.getInstance().vfd_write_string(self["menu"].getCurrent()[0]) self["text"].setText(self["menu"].getCurrent()[0]) def okbuttonClick(self): from Screens.MessageBox import MessageBox selection = self["menu"].getCurrent() if selection is not None: if selection[1] == "MC_VideoPlayer": from MC_VideoPlayer import MC_VideoPlayer self.session.open(MC_VideoPlayer) elif selection[1] == "MC_DVDPlayer": if dvdplayer: self.session.open(DVDPlayer) else: self.InstallCheckDVD() self.session.open(MessageBox,"Error: DVD-Player Plugin not installed ...", MessageBox.TYPE_INFO, timeout=5) elif selection[1] == "MC_PictureViewer": from MC_PictureViewer import MC_PictureViewer self.session.open(MC_PictureViewer) elif selection[1] == "MC_AudioPlayer": from MC_AudioPlayer import MC_AudioPlayer self.session.open(MC_AudioPlayer) elif selection[1] == "MC_WebRadio": from MC_AudioPlayer import MC_WebRadio self.session.open(MC_WebRadio) elif selection[1] == "MC_VLCPlayer": if pathExists("/usr/lib/enigma2/python/Plugins/Extensions/VlcPlayer/") == True: from MC_VLCPlayer import MC_VLCServerlist self.session.open(MC_VLCServerlist) else: self.session.open(MessageBox,"Error: VLC-Player Plugin not installed ...", MessageBox.TYPE_INFO, timeout=5) self.InstallCheckVLC() elif selection[1] == "Webbrowser": if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/HbbTV/") == True: from Plugins.Extensions.HbbTV.plugin import OperaBrowser global didOpen didOpen = True url = 'http://www.nachtfalke.biz' self.session.open(OperaBrowser, url) global browserinstance else: # self.session.openWithCallback(self.browserCallback, BrowserRemoteControl, url) self.session.open(MessageBox,"Error: WebBrowser Plugin not installed ...", MessageBox.TYPE_INFO, timeout=5) self.InstallCheckWebbrowser() elif selection[1] == "SHOUTcast": if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/SHOUTcast/") == True: from Plugins.Extensions.SHOUTcast.plugin import SHOUTcastWidget self.session.open(SHOUTcastWidget) else: self.session.open(MessageBox,"Error: SHOUTcast Plugin not installed ...", MessageBox.TYPE_INFO, timeout=5) self.InstallCheckSHOUT() elif selection[1] == "MC_WeatherInfo": self.session.nav.playService(self.oldbmcService) self.session.open(MeteoMain) elif selection[1] == "MC_Settings": from MC_Settings import MC_Settings self.session.open(MC_Settings) elif selection[1] == "MUZU.TV": if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/MUZUtv/") == True: from Plugins.Extensions.MUZUtv.plugin import muzuMain self.session.open(muzuMain) else: self.session.open(MessageBox,"Error: MUZUtv Plugin not installed ...", MessageBox.TYPE_INFO, timeout=5) self.InstallCheckMUZU() elif selection[1] == "TSMedia": if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/TSmedia/") == True: from Plugins.Extensions.TSmedia.plugin import TSmediabootlogo self.session.open(TSmediabootlogo) else: self.session.open(MessageBox,"Error: TSmedia Plugin not installed ...", MessageBox.TYPE_INFO, timeout=5) self.InstallCheckTSMedia() else: self.session.open(MessageBox,("Error: Could not find plugin %s\ncoming soon ... :)") % (selection[1]), MessageBox.TYPE_INFO) def error(self, error): from Screens.MessageBox import MessageBox self.session.open(MessageBox,("UNEXPECTED ERROR:\n%s") % (error), MessageBox.TYPE_INFO) def Exit(self): self.session.nav.stopService() # Restore OSD Transparency Settings open("/proc/sys/vm/drop_caches", "w").write(str("3")) if self.can_osd_alpha: try: if config.plugins.mc_global.vfd.value == "on": trans = commands.getoutput('cat /etc/enigma2/settings | grep config.av.osd_alpha | cut -d "=" -f2') else: trans = commands.getoutput('cat /etc/enigma2/settings | grep config.osd.alpha | cut -d "=" -f2') open("/proc/stb/video/alpha", "w").write(str(trans)) except: print "Set OSD Transparacy failed" #if config.plugins.mc_global.vfd.value == "on": # evfd.getInstance().vfd_write_string(_("Media Center")) os.system('umount /media/upnp') self.session.nav.playService(self.oldbmcService) self.close() def main(session, **kwargs): session.open(DMC_MainMenu) def menu(menuid, **kwargs): if menuid == "mainmenu": return [(_("Media Center"), main, "dmc_mainmenu", 44)] return [] def Plugins(**kwargs): if config.plugins.mc_globalsettings.showinmainmenu.value == True and config.plugins.mc_globalsettings.showinextmenu.value == True: return [ PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your OpenNFR-Image", icon="plugin.png", where = PluginDescriptor.WHERE_PLUGINMENU, fnc = main), PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your OpenNFR-Image", where = PluginDescriptor.WHERE_MENU, fnc = menu), PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your OpenNFR-Image", icon="plugin.png", where = PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=main)] elif config.plugins.mc_globalsettings.showinmainmenu.value == True and config.plugins.mc_globalsettings.showinextmenu.value == False: return [ PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your OpenNFR-Image", icon="plugin.png", where = PluginDescriptor.WHERE_PLUGINMENU, fnc = main), PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your OpenNFR-Image", where = PluginDescriptor.WHERE_MENU, fnc = menu)] elif config.plugins.mc_globalsettings.showinmainmenu.value == False and config.plugins.mc_globalsettings.showinextmenu.value == True: return [ PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your OpenNFR-Image", icon="plugin.png", where = PluginDescriptor.WHERE_PLUGINMENU, fnc = main), PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your OpenNFR-Image", icon="plugin.png", where = PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=main)] else: return [ PluginDescriptor(name = "Media Center", description = "Media Center Plugin for your OpenNFR-Image", icon="plugin.png", where = PluginDescriptor.WHERE_PLUGINMENU, fnc = main)]
n3wb13/OpenNfrGui-5.0-1
lib/python/Plugins/Extensions/bmediacenter/src/plugin.py
Python
gpl-2.0
18,939
#author: Nadezhda Shivarova #date created: 30/11/15 #Description: Perform Bi-Level Image Threshold on a histogram to determine the optimal threshold level #Using the algorithm in the paper Bi Level Img Thresholding, Antonio dos Anjos import numpy as np def bi_level_img_threshold( hist ): hist = hist.flatten() print('len hist ', len(hist)) #start and end index of the histogram I_s = 0 I_e = len(hist)-1 print('I_e ', I_e, 'I_m ', (I_s+I_e)/2) print('hist [Ie]', hist[I_e]) # starting point: get right and left weights of histogram and # determine the midpoint base triangle I_m = (I_s+I_e)/2 W_l = np.sum(hist[I_s : I_m]) W_r = np.sum(hist[I_m+1 : I_e]) print('W_l ', W_l, 'W_r ', W_r) while (I_s != I_e): if (W_r > W_l): W_r = W_r - hist[I_e] #print('Wr ', W_r) I_e = I_e - 1 #print('Ie new', I_e) if ((I_s+I_e)/2 < I_m): W_l = W_l - hist[I_m] W_r = W_r + hist[I_m] I_m = I_m - 1 #apply the algorithm mirrored, I_m tends towards depression elif (W_l >= W_r): W_l = W_l + hist[I_s] I_s = I_s + 1 if ((I_s+I_e)/2 > I_m): W_l = W_l + hist[I_m+1] W_r = W_r - hist[I_m+1] I_m = I_m + 1 #I_s and I_e get closer until they are equal to I_m #I_m is the optimal threshold i.e. depression between left and right side return I_m
Qwertycal/19520-Eye-Tracker
GUI and Mouse/View of multiple signals/bi_level_img_threshold.py
Python
gpl-2.0
1,306
# DFF -- An Open Source Digital Forensics Framework # Copyright (C) 2009 ArxSys # # This program is free software, distributed under the terms of # the GNU General Public License Version 2. See the LICENSE file # at the top of the source tree. # # See http://www.digital-forensic.org for more information about this # project. Please do not directly contact any of the maintainers of # DFF for assistance; the project provides a web site, mailing lists # and IRC channels for your use. # # Author(s): # Jeremy Mounier <jmo@digital-forensic.org> # from modules.viewer.hexedit.hexItem import * from modules.viewer.hexedit.offsetItem import * from modules.viewer.hexedit.asciiItem import * from modules.viewer.hexedit.scrollbar import hexScrollBar from PyQt4.QtCore import Qt, QLineF from PyQt4.QtGui import QGraphicsView, QKeySequence, QHBoxLayout, QWidget, QFont, QGraphicsScene, QGraphicsLineItem, QGraphicsTextItem class wHex(QWidget): def __init__(self, parent): QWidget.__init__(self) self.init(parent) self.initShape() self.initMode() def init(self, parent): self.heditor = parent def initShape(self): self.hbox = QHBoxLayout() self.hbox.setContentsMargins(0, 0, 0, 0) self.view = hexView(self) self.scroll = hexScrollBar(self) #Init Items self.hexitem = hexItem(self) self.offsetitem = offsetItem(self) self.asciitem = asciiItem(self) self.hexcursor = hexCursor(self) self.asciicursor = asciiCursor(self) self.view.setItems() self.view.setCursors() self.hbox.addWidget(self.view) self.hbox.addWidget(self.scroll) self.setLayout(self.hbox) #Set Long File Mode def initMode(self): self.lfmod = False self.maxint = 2147483647 self.lines = self.heditor.filesize / self.heditor.bytesPerLine if self.isInt(self.lines): self.scroll.max = self.lines - 1 else: self.lfmod = True self.scroll.max = self.maxint - 1 self.scroll.setValues() def offsetToValue(self, offset): if self.isLFMOD(): # print (self.maxint * offset) / self.heditor.filesize return ((self.maxint * offset) / self.heditor.filesize) else: return (offset / self.heditor.bytesPerLine) def isLFMOD(self): return self.lfmod def isInt(self, val): try: res = int(val) if res < 2147483647: return True else: return False except ValueError, TypeError: return False else: return False class hexView(QGraphicsView): def __init__(self, parent): QGraphicsView.__init__(self, None, parent) self.init(parent) self.initShape() def init(self, parent): self.whex = parent self.heditor = self.whex.heditor #Init scene self.__scene = QGraphicsScene(self) self.setScene(self.__scene) #Get heditor stuff self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setAlignment(Qt.AlignLeft) def setItems(self): self.__scene.addItem(self.whex.offsetitem) self.__scene.addItem(self.whex.hexitem) self.__scene.addItem(self.whex.asciitem) def initShape(self): self.initHeads() #Line decoration offsetLine = QGraphicsLineItem(QLineF(90, 0, 90, 700)) asciiLine = QGraphicsLineItem(QLineF(480, 0, 480, 700)) #Add to scene self.__scene.addItem(offsetLine) self.__scene.addItem(asciiLine) def setCursors(self): self.__scene.addItem(self.whex.hexcursor) self.__scene.addItem(self.whex.asciicursor) def initHeads(self): self.offHead = QGraphicsTextItem() self.hexHead = QGraphicsTextItem() self.asciiHead = QGraphicsTextItem() #Set Color self.offHead.setDefaultTextColor(QColor(Qt.red)) self.hexHead.setDefaultTextColor(QColor(Qt.black)) self.asciiHead.setDefaultTextColor(QColor(Qt.darkCyan)) #Create Font self.font = QFont("Gothic") self.font.setFixedPitch(1) self.font.setBold(False) self.font.setPixelSize(14) #Set Font self.offHead.setFont(self.font) self.hexHead.setFont(self.font) self.asciiHead.setFont(self.font) #Set Text self.offHead.setPlainText("Offset") self.hexHead.setPlainText("0 1 2 3 4 5 6 7 8 9 A B C D E F") self.asciiHead.setPlainText("Ascii") #Position self.offHead.setPos(20, 0) self.hexHead.setPos(95, 0) self.asciiHead.setPos(520, 0) #Add to scene self.__scene.addItem(self.offHead) self.__scene.addItem(self.hexHead) self.__scene.addItem(self.asciiHead) headLine = QGraphicsLineItem(QLineF(0, 20, 615, 20)) self.__scene.addItem(headLine) def move(self, step, way): #step: line = 1 * bytesPerLine, page = pagesize, wheel = 3 * bytesPerLine offset = self.heditor.currentOffset if way == 0: #UP if (offset - (step * self.heditor.bytesPerLine)) >= 0: self.heditor.readOffset(offset - (step * self.heditor.bytesPerLine)) if self.whex.isLFMOD(): self.whex.scroll.setValue(self.whex.offsetToValue(offset - step * (self.heditor.bytesPerLine))) else: self.whex.scroll.setValue(self.whex.scroll.value() - step) else: self.heditor.readOffset(0) self.whex.scroll.setValue(0) elif way == 1: #Down if (offset + (step * self.heditor.bytesPerLine)) <= (self.heditor.filesize - (step * self.heditor.bytesPerLine)): self.heditor.readOffset(offset + (step * self.heditor.bytesPerLine)) if self.whex.isLFMOD(): self.whex.scroll.setValue(self.whex.offsetToValue(offset + step * (self.heditor.bytesPerLine))) else: self.whex.scroll.setValue(self.whex.scroll.value() + step) else: self.heditor.readOffset(self.heditor.filesize - 5 * (self.heditor.bytesPerLine)) self.whex.scroll.setValue(self.whex.scroll.max) #################################### # Navigation Operations # #################################### def wheelEvent(self, event): offset = self.heditor.currentOffset if event.delta() > 0: self.move(3, 0) else: self.move(3, 1) def keyPressEvent(self, keyEvent): # off = self.heditor.currentOffset if keyEvent.matches(QKeySequence.MoveToNextPage): self.move(self.heditor.pageSize / self.heditor.bytesPerLine, 1) elif keyEvent.matches(QKeySequence.MoveToPreviousPage): self.move(self.heditor.pageSize / self.heditor.bytesPerLine, 0) elif keyEvent.matches(QKeySequence.MoveToNextWord): print "Next Word" elif keyEvent.matches(QKeySequence.MoveToPreviousWord): print "Previous word" elif keyEvent.matches(QKeySequence.MoveToNextLine): print "Next Line" elif keyEvent.matches(QKeySequence.MoveToPreviousLine): print "Previous Line"
halbbob/dff
modules/viewer/hexedit/hexView.py
Python
gpl-2.0
7,468
# -*- coding: utf-8 -*- ###################################### # # Détection des modules # ###################################### # # WxGeometrie # Dynamic geometry, graph plotter, and more for french mathematic teachers. # Copyright (C) 2005-2013 Nicolas Pourcelot # # 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 St, Fifth Floor, Boston, MA 02110-1301 USA # ###################################### import os from runpy import run_path from .parametres import modules_par_defaut # Modules a importer # ---------------- _skip_dir = ('OLD', '__pycache__') _modules_dir = os.path.normpath(os.path.join(__file__, '..', '..', 'modules')) def _detecter_modules(): modules = [] descriptions = {} def err(nom, msg): print("Warning: %s n'est pas un module valide (%s)." %(nom, msg)) for nom in os.listdir(_modules_dir): if nom not in _skip_dir and os.path.isdir(os.path.join(_modules_dir, nom)): description_file = os.path.join(_modules_dir, nom, 'description.py') if os.path.isfile(description_file): try: compile(nom + '=0', '', 'single') # On teste si le nom est valide try: d = {} d = run_path(description_file, d) if d['description']['groupe'] != "Modules": # Sert à désactiver les modules en construction. continue descriptions[nom] = d['description'] modules.append(nom) except: err(nom, "fichier '%s' incorrect" %description_file) except Exception: err(nom, "nom de module invalide") else: err(nom, "fichier 'description.py' introuvable") return modules, descriptions try: modules, descriptions_modules = _detecter_modules() except OSError: print("Warning: impossible de détecter les modules (répertoire '%s') !" % _modules_dir) modules = [] descriptions_modules = {} modules_actifs = dict.fromkeys(modules, False) for nom in modules_par_defaut: modules_actifs[nom] = True def _key(nom): # les modules activés par défaut apparaissent en premier, # les autres sont classés par ordre alphabétique. key = [1000000, nom] if nom in modules_par_defaut: key[0] = modules_par_defaut.index(nom) return key modules.sort(key = _key)
wxgeo/geophar
wxgeometrie/param/modules.py
Python
gpl-2.0
3,148
# -*- coding: utf-8 -*- # # papyon - a python client library for Msn # # Copyright (C) 2010 Collabora Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from papyon.msnp2p.constants import ApplicationID, EufGuid from papyon.msnp2p.errors import FTParseError from papyon.msnp2p.session import P2PSession import gobject import struct __all__ = ['FileTransferSession'] class FileTransferSession(P2PSession): def __init__(self, session_manager, peer, guid, message=None): P2PSession.__init__(self, session_manager, peer, guid, EufGuid.FILE_TRANSFER, ApplicationID.FILE_TRANSFER, message) self._filename = "" self._size = 0 self._has_preview = False self._preview = None # data to be send if sending self._data = None @property def filename(self): return self._filename @property def size(self): return self._size @property def has_preview(self): return self._has_preview @property def preview(self): return self._preview def invite(self, filename, size, data): self._filename = filename self._size = size self._data = data context = self._build_context() self._invite(context) def accept(self, buffer=None): if buffer is not None: self.set_receive_data_buffer(buffer, self._size) self._accept() def reject(self): self._decline(603) def cancel(self): self._close() def send(self, data): self._data = data self._send_data("\x00" * 4) self._send_data(self._data) def parse_context(self, context): try: info = struct.unpack("<5I", context[0:20]) self._size = info[2] self._has_preview = not bool(info[4]) self._filename = unicode(context[20:570], "utf-16-le").rstrip("\x00") except: raise FTParseError(context) def _build_context(self): filename = self._filename.encode('utf-16_le') context = struct.pack("<5I", 574, 2, self._size, 0, int(self._has_preview)) context += struct.pack("550s", filename) context += "\xFF" * 4 return context def _on_session_accepted(self): if self._data: self.send(self._data) def _on_bye_received(self, message): if not self.completed: self._emit("canceled") self._dispose()
billiob/papyon
papyon/msnp2p/filetransfer.py
Python
gpl-2.0
3,119
# -*- coding:utf8 -*- """ Handels everthing related to the main Window """ from __future__ import unicode_literals import sys from urllib.parse import urlparse, urlunparse from PyQt5.QtWidgets import QMainWindow, QFileDialog, QMessageBox, QMessageBox from PyQt5.QtCore import (QAbstractListModel, Qt, QModelIndex, QThread, pyqtSlot, pyqtSignal, QCoreApplication) from picuplib.globals import ALLOWED_ROTATION from picup.functions import load_ui from picup.functions import get_api_key, set_api_key from picup.upload import Upload from picup.globals import SUPPORTED_FILE_TYPES, __version__, DEFAULT_API_KEY from picup.dialogs import ShowLinks, UrlInput, KeyRequest import logging LOGGER = logging.getLogger(__name__) class MainWindow(QMainWindow): """ Main window class. Includes the main window itself as well as handling of it's signals """ upload_pictures = pyqtSignal(list) def __init__(self, **kwargs): super().__init__(**kwargs) load_ui('MainWindow.ui', self) self.setWindowTitle('Picup - {}'.format(__version__)) apikey = get_api_key() if not apikey: apikey = self.request_api_key() self.legal_resize = True self.upload_in_progress = False self.upload_thread = QThread(parent=self) self.upload = Upload(apikey=apikey) self.upload_thread.start() self.upload.moveToThread(self.upload_thread) self.list_view_files_model = FileListModel(parent=self) self.list_view_files.setModel(self.list_view_files_model) self.pushButton_close.clicked.connect(self.shutdown) self.pushButton_add_picture.clicked.connect(self.add_file) self.pushButton_add_links.clicked.connect(self.add_url) self.pushButton_upload.clicked.connect(self.start_upload) self.pushButton_clear_list.clicked.connect( self.list_view_files_model.clear_list) self.pushButton_remove_selected.clicked.connect(self.remove_selected) self.upload.upload_finished.connect(self.upload_finished) self.upload.upload_error.connect(self.handle_error) self.upload_pictures.connect(self.upload.upload_multiple) self.dialog = QFileDialog(parent=self) self.dialog.setFileMode(QFileDialog.ExistingFiles) self.dialog.setNameFilters(SUPPORTED_FILE_TYPES) self.resize_container.hide() self.resize_container_percentual.hide() self.check_box_resize.clicked.connect( self.set_resize_box_visibility ) self.radio_button_absolute.toggled.connect( self.set_absolute_resize_box_visibility ) self.radio_button_percentual.toggled.connect( self.set_percentual_resize_box_visibility ) self.spin_box_width.valueChanged.connect(self.update_resize) self.spin_box_higth.valueChanged.connect(self.update_resize) self.spin_box_percentual.valueChanged.connect(self.update_resize) self.comboBox_rotate_options.activated['QString'].connect( self.upload.change_default_rotation ) self.checkBox_delete_exif.toggled.connect( self.upload.change_default_exif ) self.comboBox_rotate_options.addItems(ALLOWED_ROTATION) def request_api_key(self,): """ requests and stores an api key from the user, if non is stores yet. If none is given a default one is used. """ window = KeyRequest(parent=self) if window.exec_(): apikey = window.lineEdit_apikey.text() if apikey: set_api_key(apikey) return apikey return DEFAULT_API_KEY sys.exit(0) @pyqtSlot() def add_file(self): """ add file(s) to the upload list. using Qts file dialog. """ if self.dialog.exec_(): files = self.dialog.selectedFiles() files = [(file_, 'file') for file_ in files] self.list_view_files_model.add_files(files) @pyqtSlot() def add_url(self,): """ add url(s) to the upload list. using a text box. """ url_input = UrlInput() code = url_input.exec_() urls = url_input.text() new_entrys = [] not_added = [] if code and urls != '': for url in urls.split('\n'): # skip empty lines if url == '': continue parsed_url = urlparse(url, scheme='http') scheme = parsed_url.scheme.lower() if scheme in ['http', 'https', 'ftp']: new_entrys.append((urlunparse(parsed_url), 'url')) else: not_added.append(url) if not_added: message = QMessageBox(QMessageBox.Warning, 'Fehler', ('Ein oder mehrere link(s) konnten ' 'nicht hinzugefügt werden.'), buttons=QMessageBox.Ok, parent=self) message.setDetailedText('\n'.join(not_added)) self.list_view_files_model.add_files(new_entrys) @pyqtSlot() def start_upload(self,): """ starts the upload and does some setup for the status/result dialog. As well as some cleanup afterwards. It locks the application for any further uploads until this one is \ finished. """ if (len(self.list_view_files_model.files) and not self.upload_in_progress and self.legal_resize): self.upload_in_progress = True files = self.list_view_files_model.files.copy() link_dialog = ShowLinks(self.upload, len(files), parent=self) link_dialog.readd_pictures.connect( self.list_view_files_model.add_files ) link_dialog.show() LOGGER.debug('emitting upload signal with arguments: %s', files) self.upload_pictures.emit(files) LOGGER.debug('cleanup main window') self.list_view_files_model.clear_list() elif self.upload_in_progress: LOGGER.debug('Upload already in progress.') QMessageBox.warning(self, 'Upload Läuft', 'Es läuft bereits ein Upload Prozess.') elif not self.legal_resize: LOGGER.debug('illegal resize string will not upload.') # pylint: disable=line-too-long # would harm readability QMessageBox.warning(self, 'Auflösung ungültig', ('Die für die Skalierung angegebene Auflösung ist ungültig. ' 'Bitte gib diese im folgendem format an: breite x höhe') ) else: LOGGER.info('There is nothing to upload.') QMessageBox.information(self, 'Nüx da', ('Es wurden keine bilder zum hochladen ' 'hinzugefügt')) @pyqtSlot() def upload_finished(self,): """ called through a signal after upload is finished to release the lock. """ self.upload_in_progress = False @pyqtSlot(type, tuple) def handle_error(self, exception_type, args): """ displays informations about an exception. """ message = QMessageBox(QMessageBox.Warning, 'Fehler', 'Fehler beim upload.', buttons=QMessageBox.Ok, parent=self) message.setDetailedText(repr(exception_type) + '\n' + repr(args)) message.exec_() @pyqtSlot() def update_resize(self,): if (self.check_box_resize.isChecked() and self.radio_button_absolute.isChecked()): width = self.spin_box_width.value() higth = self.spin_box_higth.value() self.upload.change_default_resize("{}x{}".format(width, higth)) elif (self.check_box_resize.isChecked() and self.radio_button_percentual.isChecked()): percentage = self.spin_box_percentual.value() self.upload.change_default_resize("{}%".format(percentage)) else: self.upload.change_default_resize(None) @pyqtSlot(bool) def set_resize_box_visibility(self, visible): if visible: LOGGER.debug('show resize box') self.update_resize() else: LOGGER.debug('hide resize box') self.update_resize() self.resize_container.setVisible(visible) @pyqtSlot(bool) def set_absolute_resize_box_visibility(self, visible): if visible: LOGGER.debug('show absolute resize box') self.update_resize() else: LOGGER.debug('hide absolute resize box') self.resize_container_absolute.setVisible(visible) @pyqtSlot(bool) def set_percentual_resize_box_visibility(self, visible): if visible: LOGGER.debug('show percentual resize box') self.update_resize() else: LOGGER.debug('hide percentual resize box') self.resize_container_percentual.setVisible(visible) @pyqtSlot() def remove_selected(self,): """ remove selected files from the upload list. """ for item in self.list_view_files.selectedIndexes(): self.list_view_files_model.remove_element(item.row(), item.row()) @pyqtSlot() def display_about_qt(self,): """ displays the about qt dialog """ QMessageBox.aboutQt(self,) @pyqtSlot() def shutdown(self,): """shut down Qapp""" self.thread_cleanup() QCoreApplication.instance().quit() def thread_cleanup(self): """ shuts down the upload thread at exit. """ LOGGER.debug('begin cleanup threads') try: self.upload_thread.quit() self.upload_thread.wait() # pylint: disable=bare-except # I do want to catch them all here, to be able to log them. except: LOGGER.exception('Exception while cleanup') LOGGER.debug('thread cleanup finished') class FileListModel(QAbstractListModel): """ Qt Model for the file/upload list. """ def __init__(self, **kwargs): super().__init__(**kwargs) self.files = [] # pylint: disable=invalid-name,unused-argument # this name is neccacary for a working ListModel implementation # same counts for the argument def rowCount(self, parent): """ returns the amount of rows Required for a ListModel implementation. """ return len(self.files) def data(self, index, role): """ returns requestet data. Required for a ListModel implementation. """ if role == Qt.DisplayRole: return self.files[index.row()][0] @pyqtSlot(list) def add_files(self, files): """ add elements to the model """ prev_len = len(self.files) self.beginInsertRows(QModelIndex(), prev_len, prev_len + len(files)) self.files.extend(files) self.endInsertRows() @pyqtSlot() def clear_list(self,): """ remove all elements from the model """ self.beginRemoveRows(QModelIndex(), 0, len(self.files)-1) self.files.clear() self.endRemoveRows() def remove_element(self, first, last): """ remove elements from the model """ self.beginRemoveRows(QModelIndex(), first, last) del self.files[first:last+1] self.endRemoveRows()
Arvedui/picup
picup/main_window.py
Python
gpl-2.0
12,014
#!/usr/bin/env python3 import time import json import requests from datetime import datetime import paho.mqtt.client as mqtt from sense_hat import SenseHat BROKER_URL = '192.168.24.25' CYCLE_TIME = 10 # initialisiere SenseHat-Erweiterung sense = SenseHat() sense.low_light = True def get_location(): """Ermittelt die Stadt zur eigenen IP-Adresse.""" IP_LOCKUP_URL = "https://ipinfo.io/" try: r = requests.get(IP_LOCKUP_URL) except: print("error while querying info...") data = json.loads(r.text) return data['city'] def get_weather(city): """Fragt das aktuelle Wetter bei openweathermap.org ab und gibt Temperatur, Luftfeuchtigkeit, Windgeschwindigkeit und die Zeiten von Sonnenaufgang und Sonnenuntergang zurück.""" URL = 'http://api.openweathermap.org/data/2.5/weather?q={}&APPID={}' API_KEY = '' # <- insert API key for openweathermap.org r = requests.get(URL.format(city, API_KEY)) data = json.loads(r.text) if data['cod'] == '404': return '', 0, 0, 0, '', '' weather = data['weather'][0]['main'] temp = data['main']['temp'] - 273.15 humidity = data['main']['humidity'] wind_speed = data['wind']['speed'] sunrise = datetime.fromtimestamp(data['sys']['sunrise']) sunset = datetime.fromtimestamp(data['sys']['sunset']) return weather, temp, humidity, wind_speed, sunrise, sunset if __name__ == '__main__': try: mqttc = mqtt.Client() mqttc.connect(BROKER_URL, 1883, 60) while True: weather, temp, humidity, wind_speed, sunrise, sunset = get_weather(get_location()) mqttc.publish('umgebung/wetter', str(weather)) mqttc.publish('umgebung/temperatur', str(temp)) mqttc.publish('umgebung/luftfeuchtigkeit', str(humidity)) mqttc.publish('umgebung/windgeschwindigkeit', str(wind_speed)) mqttc.publish('umgebung/sonnenaufgang', str(sunrise)) mqttc.publish('umgebung/sonnenuntergang', str(sunset)) mqttc.publish('wohnzimmer/temperatur', str(sense.get_temperature())) mqttc.publish('wohnzimmer/luftdruck', str(sense.get_pressure())) mqttc.publish('wohnzimmer/luftfeuchtigkeit', str(sense.get_humidity())) # überprüfe, ob das Steuerkreuz nach unten gedrückt wurde for event in sense.stick.get_events(): if 'down' in event.direction: exit() time.sleep(CYCLE_TIME) except KeyboardInterrupt: mqttc.disconnect() sense.clear() print('Tschüß!')
wichmann/PythonExamples
sense-hat/weatherpublisher.py
Python
gpl-2.0
2,604
# -*- coding: utf-8 -*- __author__ = 'Bright Pan' # 注意:我们必须要把old数据库中的yehnet_customer表中的postdate改成add_time import types import urllib.request try: import simplejson as json except Exception: import json import pymysql import datetime import sys print(sys.getdefaultencoding()) def f(x): if isinstance(x, str): return x.encode("gbk", "ignore").decode("gbk") return x class DB(object): def __init__(self, host="localhost", user="root", passwd="", old_db="", new_db="",charset="utf8"): self.new_conn=pymysql.connect(host=host,user=user,passwd=passwd,db=new_db,charset=charset, cursorclass=pymysql.cursors.DictCursor) self.old_conn=pymysql.connect(host=host,user=user,passwd=passwd,db=old_db,charset=charset, cursorclass=pymysql.cursors.DictCursor) self.new_cur = self.new_conn.cursor() self.old_cur = self.old_conn.cursor() def db_clear_data(self): self.new_cur.execute("show tables") qs_new = self.new_cur.fetchall() print(qs_new) for each in qs_new: self.new_cur.execute("truncate %s" % each['Tables_in_new']) self.new_conn.commit() def db_commit(self): self.new_conn.commit() self.old_conn.commit() def table_copy_process(self, new_table="", old_table=""): result = self.new_cur.execute("show columns from %s" % new_table) qs_new = self.new_cur.fetchall() new_cols = {} for each in qs_new: new_cols[each['Field']] = each result = self.old_cur.execute("select * from %s" % old_table) qs_old = self.old_cur.fetchall() for each in qs_old: sql_key = "" sql_value = "" for key,value in each.items(): #print(type(key),type(value)) cols_attr = new_cols.get(key) #print(cols_attr) if cols_attr: if value is None: #if cols_attr['Default'] is None: #sql += "%s=''," % (key) #sql_key += key + ',' pass else: if not cols_attr['Type'].find("date"): #print(cols_attr) if isinstance(value, datetime.datetime): value = value.strftime("%Y-%m-%d %H:%M:%S") else: value = datetime.datetime.fromtimestamp(value).strftime("%Y-%m-%d %H:%M:%S") #sql += "%s='%s'," % (key, value) sql_key += "`%s`," % key if isinstance(value, str): sql_value += "\"%s\"," % pymysql.escape_string(value) else: sql_value += "\"%s\"," % value sql = "INSERT INTO %s (%s) VALUES (%s)" % (new_table,sql_key[:-1],sql_value[:-1]) try: self.new_cur.execute(sql) #print(sql) except pymysql.err.IntegrityError as e: pass #print(e) #print(sql) except pymysql.err.ProgrammingError as e: #捕捉除0异常 print(e) self.db_commit() def db_copy_process(self): self.db_clear_data() result = self.new_cur.execute("show tables") new_tables = self.new_cur.fetchall() new_tables_list = [] for each in new_tables: new_tables_list.append(each["Tables_in_new"]) print(new_tables_list) result = self.old_cur.execute("show tables") old_tables = self.old_cur.fetchall() old_tables_list = [] for each in old_tables: old_tables_list.append(each["Tables_in_old"]) print(old_tables_list) for each in new_tables_list: print(each) try: old_tables_list.index(each) new_tables_list.index(each) except ValueError: continue self.table_copy_process(each, each) def process_update(self, from_table='yehnet_sales', to_table="yehnet_admin", set_dict={}, where_condition=("adminid","id")): map_dict = {"username":(0,"username"), "email":(0,"email"),"phone":(0,"phone"),"company":(0,"company"),"department":(0,"department"),"job":(0,"job"),"add_time":(1,"add_time")} if set_dict: map_dict = set_dict self.old_cur.execute("select * from %s" % from_table) qs_old = self.old_cur.fetchall() # self.new_cur.execute("select * from yehnet_admin") # qs_new = self.new_cur.fetchall() # new_dict = {} # for each in qs_new: # new_dict[each['admin_id']] = each for each in qs_old: #print(each) sql = "UPDATE `%s` SET " % to_table for from_cols, to_cols in map_dict.items(): key = to_cols[1] value = each[from_cols] if value is None: pass else: if to_cols[0]: if isinstance(value, str): value = int(value) value = datetime.datetime.fromtimestamp(value).strftime("%Y-%m-%d %H:%M:%S") if isinstance(value, str): sql += "`%s` = \"%s\"," % (key, pymysql.escape_string(value)) else: sql += "`%s` = \"%s\"," % (key, value) sql = sql[:-1] + " WHERE `%s` = \"%s\"" % (where_condition[1], each[where_condition[0]]) try: #print(sql) self.new_cur.execute(sql) except pymysql.err.IntegrityError as e: pass #print(e) #print(sql) except pymysql.err.ProgrammingError as e: #捕捉除0异常 print(e) self.db_commit() def process_insert(self, from_table='yehnet_sales', to_table="yehnet_admin", set_dict={}, project=False): map_dict = {"username":(0,"username"), "email":(0,"email"),"phone":(0,"phone"),"company":(0,"company"),"department":(0,"department"),"job":(0,"job"),"add_time":(1,"add_time")} if set_dict: map_dict = set_dict if project: sql = "select * from %s " % (from_table) sql += project self.old_cur.execute(sql) else: self.old_cur.execute("select * from %s" % from_table) qs_old = self.old_cur.fetchall() # self.new_cur.execute("select * from yehnet_admin") # qs_new = self.new_cur.fetchall() # new_dict = {} # for each in qs_new: # new_dict[each['admin_id']] = each for each in qs_old: #print(list(map(f,list(each.keys())))) sql_key = "" sql_value = "" for from_cols, to_cols in map_dict.items(): #print(from_cols,to_cols) key = to_cols[1] value = each[from_cols] if value is None: pass else: if to_cols[0] is 1: if isinstance(value, str): value = int(value) value = datetime.datetime.fromtimestamp(value).strftime("%Y-%m-%d %H:%M:%S") if to_cols[0] is 2: value = to_cols[2] if to_cols[0] is 3: value = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") sql_key += "`%s`," % key if isinstance(value, str): sql_value += "\"%s\"," % pymysql.escape_string(value) else: sql_value += "\"%s\"," % value # if isinstance(value, str): # sql += "`%s` = \"%s\"," % (key, pymysql.escape_string(value)) # else: # sql += "`%s` = \"%s\"," % (key, value) sql = "INSERT INTO %s (%s) VALUES (%s)" % (to_table,sql_key[:-1],sql_value[:-1]) try: #print(f(sql)) self.new_cur.execute(sql) except pymysql.err.IntegrityError as e: print(e) #print(sql) except pymysql.err.ProgrammingError as e: #捕捉除0异常 print(e) self.db_commit() def process_invalid_data(self): try: # print(sql) self.new_cur.execute("update yehnet_customer_user set status = '3' where status = '2';") self.new_cur.execute("update yehnet_customer_user set status = '2' where status = '1';") self.new_cur.execute("update yehnet_customer_user set status = '1' where status = '0';") #self.new_cur.execute("delete from yehnet_customer_admin where a_id = 0") #self.new_cur.execute("delete from yehnet_customer_user where u_id = 0") except pymysql.err.IntegrityError as e: print(e) #print(sql) except pymysql.err.ProgrammingError as e: #捕捉除0异常 print(e) self.new_conn.commit() def __del__(self): self.new_conn.close() self.old_conn.close() if __name__ == "__main__": db = DB(old_db="old",new_db="new") #db.table_copy_process("yehnet_admin", "yehnet_admin") db.db_copy_process() db.process_update() from_table = "yehnet_customer" to_table = "yehnet_customer_admin" map_dict = {"id":(0,"c_id"), "guwenid":(0,"a_id"), "status":(2,"status",1), "add_time":(3,"add_time")} db.process_insert(from_table,to_table,map_dict) from_table = "yehnet_customer" to_table = "yehnet_customer_project" map_dict = {"id":(0,"c_id"), "uid":(0,"u_id"),"yehnet_list.id":(0,"p_id"), "wanted":(0,"apartment"),"housetype":(0,"housetype"), "housesquare":(0,"housesquare"),"housefloor":(0,"housefloor"), "other":(0,"other"), "status":(2,"status",1), "add_time":(3,"add_time")} db.process_insert(from_table,to_table,map_dict, "left JOIN yehnet_list ON yehnet_list.title = yehnet_customer.proname") from_table = "yehnet_customer" to_table = "yehnet_customer_user" map_dict = {"id":(0,"c_id"), "uid":(0,"u_id"),"yongjin":(0,"commission"),"status":(0,"status"), "add_time":(0,"add_time")} db.process_insert(from_table,to_table,map_dict, "left JOIN yehnet_list ON yehnet_list.title = yehnet_customer.proname") from_table = "yehnet_customer_log" to_table = "yehnet_customer_status" map_dict = {"yehnet_customer.id":(0,"c_id"), "uid":(0,"u_id"), "guwenid":(0,"a_id"),"yehnet_list.id":(0,"p_id"), "type":(0,"type"), "note":(0,"remark"),"yehnet_customer.status":(0,"status"), "add_time":(1,"add_time")} db.process_insert(from_table,to_table,map_dict, "left JOIN yehnet_customer ON yehnet_customer_log.customer_id = yehnet_customer.id left JOIN yehnet_list ON yehnet_list.title = yehnet_customer.proname") from_table = "yehnet_user" to_table = "yehnet_user" map_dict = {"regdate":(3,"add_time")} db.process_update(from_table,to_table,map_dict, ('id','id')) from_table = "yehnet_user_bk" to_table = "yehnet_user" map_dict = {"jjr_city":(0,"jjr_city"), "jjr_province":(0,"jjr_province")} db.process_update(from_table,to_table,map_dict, ('phone','phone')) db.process_invalid_data()
bright-pan/my_data_sync
old2new.py
Python
gpl-2.0
11,662
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def port_models(apps, schema_editor): Proposal = apps.get_model('core', 'Proposal') Notice = apps.get_model('core', 'Notice') n = Notice() n.title = "Edital" n.description = "Edital info" n.save() for p in Proposal.objects.all(): p.notice = n p.save() def reverse_port_models(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('core', '0003_proposaldate'), ] operations = [ migrations.CreateModel( name='Notice', fields=[ ('id', models.AutoField(serialize=False, primary_key=True)), ('title', models.CharField(max_length=60)), ('description', models.CharField(max_length=500)), ('is_available', models.BooleanField(default=False)), ], ), migrations.AddField( model_name='proposal', name='notice', field=models.ForeignKey(related_name='proposals', to='core.Notice', null=True), ), migrations.RunPython(port_models, reverse_port_models), ]
hackultura/procult
procult/core/migrations/0004_auto_20160905_0938.py
Python
gpl-2.0
1,233
# -*- coding: utf-8 -*- import logging import pickle import re from cacheops import invalidate_model from django import http from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponse from django.shortcuts import redirect, render from ..attendance import generate_roster_pdf from ...forms.admin.blocks import BlockForm, QuickBlockForm from ...models import EighthBlock, EighthScheduledActivity from ....auth.decorators import eighth_admin_required logger = logging.getLogger(__name__) @eighth_admin_required def add_block_view(request): if request.method == "POST" and "custom_block" in request.POST: form = QuickBlockForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Successfully added block.") return redirect("eighth_admin_dashboard") else: messages.error(request, "Error adding block.") request.session["add_block_form"] = pickle.dumps(form) date = None show_letters = None if "date" in request.GET: date = request.GET.get("date") if "date" in request.POST: date = request.POST.get("date") title_suffix = "" if date: date_format = re.compile(r'([0-9]{2})\/([0-9]{2})\/([0-9]{4})') fmtdate = date_format.sub(r'\3-\1-\2', date) logger.debug(fmtdate) title_suffix = " - {}".format(fmtdate) show_letters = True if "modify_blocks" in request.POST: letters = request.POST.getlist("blocks") current_letters = [] blocks_day = EighthBlock.objects.filter(date=fmtdate) for day in blocks_day: current_letters.append(day.block_letter) logger.debug(letters) logger.debug(current_letters) for l in letters: if len(l) == 0: continue if l not in current_letters: EighthBlock.objects.create(date=fmtdate, block_letter=l) messages.success(request, "Successfully added {} Block on {}".format(l, fmtdate)) for l in current_letters: if len(l) == 0: continue if l not in letters: EighthBlock.objects.get(date=fmtdate, block_letter=l).delete() messages.success(request, "Successfully removed {} Block on {}".format(l, fmtdate)) invalidate_model(EighthBlock) letters = [] visible_blocks = ["A", "B", "C", "D", "E", "F", "G", "H"] if show_letters: onday = EighthBlock.objects.filter(date=fmtdate) for l in visible_blocks: exists = onday.filter(block_letter=l) letters.append({"name": l, "exists": exists}) for blk in onday: if blk.block_letter not in visible_blocks: visible_blocks.append(blk.block_letter) letters.append({"name": blk.block_letter, "exists": True}) context = {"admin_page_title": "Add or Remove Blocks{}".format(title_suffix), "date": date, "letters": letters, "show_letters": show_letters, "add_block_form": QuickBlockForm} return render(request, "eighth/admin/add_block.html", context) @eighth_admin_required def edit_block_view(request, block_id): try: block = EighthBlock.objects.get(id=block_id) except EighthBlock.DoesNotExist: raise http.Http404 if request.method == "POST": form = BlockForm(request.POST, instance=block) if form.is_valid(): form.save() invalidate_model(EighthBlock) messages.success(request, "Successfully edited block.") return redirect("eighth_admin_dashboard") else: messages.error(request, "Error adding block.") else: form = BlockForm(instance=block) context = {"form": form, "delete_url": reverse("eighth_admin_delete_block", args=[block_id]), "admin_page_title": "Edit Block"} return render(request, "eighth/admin/edit_form.html", context) @eighth_admin_required def delete_block_view(request, block_id): try: block = EighthBlock.objects.get(id=block_id) except EighthBlock.DoesNotExist: raise http.Http404 if request.method == "POST": block.delete() invalidate_model(EighthBlock) messages.success(request, "Successfully deleted block.") return redirect("eighth_admin_dashboard") else: context = {"admin_page_title": "Delete Block", "item_name": str(block), "help_text": "Deleting this block will remove all records " "of it related to eighth period."} return render(request, "eighth/admin/delete_form.html", context) @eighth_admin_required def print_block_rosters_view(request, block_id): if "schact_id" in request.POST: response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = "inline; filename=\"block_{}_rosters.pdf\"".format(block_id) sched_act_ids = request.POST.getlist("schact_id") pdf_buffer = generate_roster_pdf(sched_act_ids, True) response.write(pdf_buffer.getvalue()) pdf_buffer.close() return response else: try: block = EighthBlock.objects.get(id=block_id) schacts = EighthScheduledActivity.objects.filter(block=block).order_by("sponsors") schacts = sorted(schacts, key=lambda x: "{}".format(x.get_true_sponsors())) except (EighthBlock.DoesNotExist, EighthScheduledActivity.DoesNotExist): raise http.Http404 context = {"eighthblock": block, "admin_page_title": "Choose activities to print", "schacts": schacts} return render(request, "eighth/admin/choose_roster_activities.html", context)
jacobajit/ion
intranet/apps/eighth/views/admin/blocks.py
Python
gpl-2.0
5,960
""" @summary: This script will generate a surface using cones and ellipsoids @author: CJ Grady """ from math import sqrt import numpy as np from random import randint # ............................................................................. class SurfaceGenerator(object): """ @summary: This class is used to generate a surface to be used for testing """ # .................................. def __init__(self, nrows, ncols, xll, yll, cellSize, defVal=1): if defVal == 0: self.grid = np.zeros((nrows, ncols), dtype=int) else: self.grid = np.ones((nrows, ncols), dtype=int) * defVal self.headers = """\ ncols {0} nrows {1} xllcorner {2} yllcorner {3} cellsize {4} NODATA_value {5} """.format(ncols, nrows, xll, yll, cellSize, -9999) # .................................. def addCone(self, xCnt, yCnt, rad, height, maxHeight=None): def insideCircle(x, y): return ((1.0*x - xCnt)**2 / rad**2) + ((1.0*y - yCnt)**2 / rad**2) <= 1 def getZ(x, y): # % 1 - rad * total height xPart = (1.0*x - xCnt)**2 yPart = (1.0*y - yCnt)**2 dist = sqrt(xPart + yPart) val = height * (1 - dist / rad) if maxHeight is not None: val = max(val, maxHeight) return val for x in range(max(0, (xCnt - rad)), min(self.grid.shape[1], (xCnt + rad))): for y in range(max(0, (yCnt - rad)), min(self.grid.shape[0], (yCnt + rad))): if insideCircle(x, y): #self.grid[y,x] = max(getZ(x, y), self.grid[y,x]) try: self.grid[y,x] = self.grid[y,x] + getZ(x, y) except: print "An exception occurred when setting the value of a cell" # .................................. def addEllipsoid(self, xCnt, yCnt, xRad, yRad, height, maxHeight=None): def insideEllipse(x, y): return ((1.0*x - xCnt)**2 / xRad**2) + ((1.0*y - yCnt)**2 / yRad**2) <= 1 def getZ(x, y): xPart = (1.0*x - xCnt)**2 / xRad**2 yPart = (1.0*y - yCnt)**2 / yRad**2 t = 1 - xPart - yPart t2 = height**2 * t val = sqrt(t2) if maxHeight is not None: val = max(val, maxHeight) return val for x in range(max(0, (xCnt - xRad)), min(self.grid.shape[1], (xCnt + xRad))): for y in range(max(0, (yCnt - yRad)), min(self.grid.shape[0], (yCnt + yRad))): if insideEllipse(x, y): #self.grid[y,x] = max(getZ(x, y), self.grid[y,x]) try: self.grid[y,x] = self.grid[y,x] + getZ(x, y) except: print "An exception occurred when setting the value of a cell" # .................................. def addRandom(self, numCones=0, numEllipsoids=0, maxHeight=100, maxRad=100): # TODO: Add mesas? maxX, maxY = self.grid.shape # Add cones for i in range(numCones): h = randint(1, maxHeight) self.addCone(randint(0, maxX), randint(0, maxY), randint(1, maxRad), h, maxHeight=randint(1, h)) # Add ellipsoids for i in range(numEllipsoids): h = randint(1, maxHeight) self.addEllipsoid(randint(0, maxX), randint(0, maxY), randint(1, maxRad), randint(1, maxRad), h, maxHeight=randint(1, h)) # .................................. def writeGrid(self, fn): np.savetxt(fn, self.grid, fmt="%i", header=self.headers, comments='') # ............................................................................. if __name__ == "__main__": #s = SurfaceGenerator(20, 20, 10, 10, 10, defVal=0) #s = SurfaceGenerator(1000, 1000, 0, 0, 0.05, defVal=0) s = SurfaceGenerator(20, 20, 0, 0, 1.0, defVal=0) #s.addEllipsoid(5, 5, 4, 3, 10) #s.addEllipsoid(7, 7, 2, 5, 10) #s.addCone(14, 14, 5, 20) #s.writeGrid('/home/cjgrady/testSurface.asc') s.addRandom(numCones=10, numEllipsoids=10, maxHeight=10, maxRad=10) #s.writeGrid('/home/cjgrady/git/irksome-broccoli/testData/surfaces/testSurface.asc') print s.grid.tolist()
cjgrady/irksome-broccoli
extras/surfaceGenerator.py
Python
gpl-2.0
4,244
# ------------------------------------------------------------------------------------------------ # Copyright (c) 2016 Microsoft Corporation # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and # associated documentation files (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, publish, distribute, # sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT # NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ------------------------------------------------------------------------------------------------ import MalmoPython import os import random import sys import time import json import random import errno def GetMissionXML(): return '''<?xml version="1.0" encoding="UTF-8" ?> <Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <About> <Summary>Moving Times</Summary> </About> <ServerSection> <ServerHandlers> <FlatWorldGenerator generatorString="3;7,220*1,5*3,2;3;,biome_1" /> <DrawingDecorator> <DrawCuboid x1="-21" y1="226" z1="-21" x2="21" y2="236" z2="21" type="air"/> <DrawCuboid x1="-21" y1="226" z1="-21" x2="21" y2="226" z2="21" type="lava"/> <DrawCuboid x1="-20" y1="226" z1="-20" x2="20" y2="16" z2="20" type="gold_block" /> </DrawingDecorator>''' + getAnimation() + ''' <ServerQuitFromTimeUp timeLimitMs="150000" description="out_of_time"/> <ServerQuitWhenAnyAgentFinishes /> </ServerHandlers> </ServerSection> <AgentSection mode="Survival"> <Name>Walt</Name> <AgentStart> <Placement x="0.5" y="227.0" z="0.5"/> <Inventory> </Inventory> </AgentStart> <AgentHandlers> <RewardForMissionEnd rewardForDeath="-1000.0"> <Reward description="out_of_time" reward="-900.0"/> <Reward description="found_goal" reward="100000.0"/> </RewardForMissionEnd> <RewardForTouchingBlockType> <Block type="slime" reward="-100.0"/> </RewardForTouchingBlockType> <AgentQuitFromTouchingBlockType> <Block type="skull" description="found_goal"/> </AgentQuitFromTouchingBlockType> <ContinuousMovementCommands turnSpeedDegs="240"/> </AgentHandlers> </AgentSection> </Mission>''' def getAnimation(): # Silly test of animations: add a few slime constructions and send them moving linearly around the "playing field"... # Create a slowly descending roof... # And an orbiting pumpkin with its own skull sattelite. xml="" for x in xrange(4): xml+=''' <AnimationDecorator ticksPerUpdate="10"> <Linear> <CanvasBounds> <min x="-20" y="226" z="-20"/> <max x="20" y="230" z="20"/> </CanvasBounds> <InitialPos x="''' + str(random.randint(-16,16)) + '''" y="228" z="''' + str(random.randint(-16,16)) + '''"/> <InitialVelocity x="'''+str(random.random()-0.5)+'''" y="0" z="'''+str(random.random()-0.5)+'''"/> </Linear> <DrawingDecorator> <DrawBlock x="0" y="1" z="0" type="slime"/> <DrawBlock x="0" y="-1" z="0" type="slime"/> <DrawBlock x="1" y="0" z="0" type="slime"/> <DrawBlock x="-1" y="0" z="0" type="slime"/> <DrawBlock x="0" y="0" z="1" type="slime"/> <DrawBlock x="0" y="0" z="-1" type="slime"/> </DrawingDecorator> </AnimationDecorator>''' return xml+''' <AnimationDecorator> <Linear> <CanvasBounds> <min x="-21" y="225" z="-21"/> <max x="21" y="247" z="21"/> </CanvasBounds> <InitialPos x="0" y="246" z="0"/> <InitialVelocity x="0" y="-0.025" z="0"/> </Linear> <DrawingDecorator> <DrawCuboid x1="-20" y1="0" z1="-20" x2="20" y2="1" z2="20" type="obsidian"/> </DrawingDecorator> </AnimationDecorator> <AnimationDecorator> <Parametric seed="random"> <x>15*sin(t/20.0)</x> <y>227-(t/120.0)</y> <z>15*cos(t/20.0)</z> </Parametric> <DrawingDecorator> <DrawBlock x="0" y="2" z="0" type="fence"/> <DrawBlock x="0" y="3" z="0" type="fence"/> <DrawBlock x="0" y="4" z="0" type="pumpkin"/> </DrawingDecorator> </AnimationDecorator> <AnimationDecorator> <Parametric seed="random"> <x>(15*sin(t/20.0))+(2*sin(t/2.0))</x> <y>227-(t/120.0)+2*cos(t/1.5)</y> <z>(15*cos(t/20.0))+(2*cos(t/2.0))</z> </Parametric> <DrawingDecorator> <DrawBlock x="0" y="2" z="0" type="skull"/> </DrawingDecorator> </AnimationDecorator>''' sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # flush print output immediately recordingsDirectory="AnimationRecordings" try: os.makedirs(recordingsDirectory) except OSError as exception: if exception.errno != errno.EEXIST: # ignore error if already existed raise validate = True my_mission = MalmoPython.MissionSpec(GetMissionXML(),validate) agent_host = MalmoPython.AgentHost() try: agent_host.parse( sys.argv ) except RuntimeError as e: print 'ERROR:',e print agent_host.getUsage() exit(1) if agent_host.receivedArgument("help"): print agent_host.getUsage() exit(0) my_client_pool = MalmoPython.ClientPool() my_client_pool.add(MalmoPython.ClientInfo("127.0.0.1", 10000)) if agent_host.receivedArgument("test"): num_reps = 1 else: num_reps = 30000 for iRepeat in range(num_reps): # Set up a recording my_mission_record = MalmoPython.MissionRecordSpec(recordingsDirectory + "//" + "Mission_" + str(iRepeat) + ".tgz") my_mission_record.recordRewards() my_mission_record.recordMP4(24,400000) max_retries = 3 for retry in range(max_retries): try: # Attempt to start the mission: agent_host.startMission( my_mission, my_client_pool, my_mission_record, 0, "missionEndTestExperiment" ) break except RuntimeError as e: if retry == max_retries - 1: print "Error starting mission",e print "Is the game running?" exit(1) else: time.sleep(2) world_state = agent_host.getWorldState() while not world_state.has_mission_begun: time.sleep(0.1) world_state = agent_host.getWorldState() reward = 0.0 # keep track of reward for this mission. # start running: agent_host.sendCommand("move 1") agent_host.sendCommand("turn 0.1") # main loop: while world_state.is_mission_running: world_state = agent_host.getWorldState() if world_state.number_of_rewards_since_last_state > 0: # A reward signal has come in - see what it is: delta = world_state.rewards[0].getValue() if delta != 0: print "New reward: " + str(delta) reward += delta time.sleep(0.1) # mission has ended. print "Mission " + str(iRepeat+1) + ": Reward = " + str(reward) time.sleep(0.5) # Give the mod a little time to prepare for the next mission.
Yarichi/Proyecto-DASI
Malmo/Python_Examples/animation_test.py
Python
gpl-2.0
8,932
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Person.slug' db.delete_column(u'aldryn_people_person', 'slug') # Deleting field 'Person.name' db.delete_column(u'aldryn_people_person', 'name') def backwards(self, orm): # Adding field 'Person.slug' db.add_column(u'aldryn_people_person', 'slug', self.gf('django.db.models.fields.CharField')(unique=True, max_length=255, null=True, blank=True), keep_default=False) # Adding field 'Person.name' db.add_column(u'aldryn_people_person', 'name', self.gf('django.db.models.fields.CharField')(default='', max_length=255), keep_default=False) models = { u'aldryn_people.group': { 'Meta': {'object_name': 'Group'}, 'address': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'default': "u''", 'max_length': '75', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'postal_code': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, u'aldryn_people.grouptranslation': { 'Meta': {'unique_together': "[(u'language_code', u'master')]", 'object_name': 'GroupTranslation', 'db_table': "u'aldryn_people_group_translation'"}, 'description': ('djangocms_text_ckeditor.fields.HTMLField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language_code': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), u'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'translations'", 'null': 'True', 'to': u"orm['aldryn_people.Group']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'slug': ('django.db.models.fields.SlugField', [], {'default': "u''", 'max_length': '255'}) }, u'aldryn_people.peopleplugin': { 'Meta': {'object_name': 'PeoplePlugin'}, u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}), 'group_by_group': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'people': ('aldryn_common.admin_fields.sortedm2m.SortedM2MModelField', [], {'symmetrical': 'False', 'to': u"orm['aldryn_people.Person']", 'null': 'True', 'blank': 'True'}), 'show_links': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'show_vcard': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'style': ('django.db.models.fields.CharField', [], {'default': "u'standard'", 'max_length': '50'}) }, u'aldryn_people.person': { 'Meta': {'object_name': 'Person'}, 'email': ('django.db.models.fields.EmailField', [], {'default': "u''", 'max_length': '75', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'groups': ('sortedm2m.fields.SortedManyToManyField', [], {'default': 'None', 'related_name': "u'people'", 'blank': 'True', 'symmetrical': 'False', 'to': u"orm['aldryn_people.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'mobile': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'persons'", 'unique': 'True', 'null': 'True', 'to': u"orm['auth.User']"}), 'vcard_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'visual': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['filer.Image']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, u'aldryn_people.persontranslation': { 'Meta': {'unique_together': "[(u'language_code', u'master')]", 'object_name': 'PersonTranslation', 'db_table': "u'aldryn_people_person_translation'"}, 'description': ('djangocms_text_ckeditor.fields.HTMLField', [], {'default': "u''", 'blank': 'True'}), 'function': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language_code': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), u'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'translations'", 'null': 'True', 'to': u"orm['aldryn_people.Person']"}), 'name': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255'}), 'slug': ('django.db.models.fields.SlugField', [], {'default': "u''", 'max_length': '255'}) }, u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'cms.cmsplugin': { 'Meta': {'object_name': 'CMSPlugin'}, 'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'depth': ('django.db.models.fields.PositiveIntegerField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'numchild': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}), 'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}), 'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'cms.placeholder': { 'Meta': {'object_name': 'Placeholder'}, 'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slot': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'filer.file': { 'Meta': {'object_name': 'File'}, '_file_size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'folder': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'all_files'", 'null': 'True', 'to': u"orm['filer.Folder']"}), 'has_all_mandatory_data': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}), 'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'owned_files'", 'null': 'True', 'to': u"orm['auth.User']"}), 'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'polymorphic_filer.file_set+'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}), 'sha1': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '40', 'blank': 'True'}), 'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, u'filer.folder': { 'Meta': {'ordering': "(u'name',)", 'unique_together': "((u'parent', u'name'),)", 'object_name': 'Folder'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'filer_owned_folders'", 'null': 'True', 'to': u"orm['auth.User']"}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'children'", 'null': 'True', 'to': u"orm['filer.Folder']"}), u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'filer.image': { 'Meta': {'object_name': 'Image'}, '_height': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), '_width': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'author': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'date_taken': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'default_alt_text': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'default_caption': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), u'file_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['filer.File']", 'unique': 'True', 'primary_key': 'True'}), 'must_always_publish_author_credit': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'must_always_publish_copyright': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'subject_location': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '64', 'null': 'True', 'blank': 'True'}) } } complete_apps = ['aldryn_people']
Venturi/cms
env/lib/python2.7/site-packages/aldryn_people/south_migrations/0026_auto__del_field_person_slug__del_field_person_name.py
Python
gpl-2.0
15,554
""" file: gitissuetracker.py author: Christoffer Rosen <cbr4830@rit.edu> date: December, 2013 description: Represents a Github Issue tracker object used for getting the dates issues were opened. 12/12/13: Doesn't currently support private repos """ import requests, json, dateutil.parser, time from caslogging import logging class GithubIssueTracker: """ GitIssueTracker() Represents a Github Issue Tracker Object """ owner = None # Owner of the github repo repo = None # The repo name request_repos = "https://api.github.com/repos" # Request url to get issue info request_auth = "https://api.github.com/authorizations" # Request url for auth def __init__(self, owner, repo): """ Constructor """ self.owner = owner self.repo = repo self.auth_token = None self.authenticate() # Authenticate our app def authenticate(self): """ authenticate() Authenticates this application to github using the cas-user git user credentials. This is temporary! """ s = requests.Session() s.auth = ("cas-user", "riskykiwi1") payload = {"scopes": ["repo"]} r = s.get(self.request_auth, params=payload) if r.headers.get('x-ratelimit-remaining') == '0': logging.info("Github quota limit hit -- waiting") # Wait up to a hour until we can continue.. while r.headers.get('x-ratelimit-remaining') == '0': time.sleep(600) # Wait 10 minutes and try again r = s.get(self.request_auth, params=payload) data = r.json() data = r.json()[0] if r.status_code >= 400: msg = data.get('message') logging.error("Failed to authenticate issue tracker: \n" +msg) return # Exit else: self.auth_token = data.get("token") requests_left = r.headers.get('x-ratelimit-remaining') logging.info("Analyzer has " + requests_left + " issue tracker calls left this hour") def getDateOpened(self, issueNumber): """ getDateOpened() Gets the date the issue number was opened in unix time If issue cannot be found for whichever reason, returns null. """ header = {'Authorization': 'token ' + self.auth_token} r = requests.get(self.request_repos + "/" + self.owner + "/" + self.repo + "/issues/" + issueNumber, headers=header) data = r.json() # If forbidden if r.status_code == 403: # Check the api quota if r.headers.get('x-ratelimit-remaining') == '0': logging.info("Github quota limit hit -- waiting") # Wait up to a hour until we can continue.. while r.headers.get('x-ratelimit-remaining') == '0': time.sleep(600) # Wait 10 minutes and try again r = requests.get(self.request_repos + "/" + self.owner + "/" + self.repo + "/issues/" + issueNumber, headers=header) data = r.json() # Check for other error codes elif r.status_code >= 400: msg = data.get('message') logging.error("ISSUE TRACKER FAILURE: \n" + msg) return None else: try: date = (dateutil.parser.parse(data.get('created_at'))).timestamp() return date except: logging.error("ISSUE TRACKER FAILURE: Could not get created_at from github issues API") return None
CommitAnalyzingService/CAS_Analyzer
githubissuetracker.py
Python
gpl-2.0
3,106
# -*- coding: utf-8 -*- """ *************************************************************************** DensifyGeometriesInterval.py by Anita Graser, Dec 2012 based on DensifyGeometries.py --------------------- Date : October 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot 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. * * * *************************************************************************** """ from builtins import range __author__ = 'Anita Graser' __date__ = 'Dec 2012' __copyright__ = '(C) 2012, Anita Graser' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from qgis.core import (QgsProcessingParameterNumber) from processing.algs.qgis.QgisAlgorithm import QgisFeatureBasedAlgorithm class DensifyGeometriesInterval(QgisFeatureBasedAlgorithm): INTERVAL = 'INTERVAL' def group(self): return self.tr('Vector geometry') def __init__(self): super().__init__() self.interval = None def initParameters(self, config=None): self.addParameter(QgsProcessingParameterNumber(self.INTERVAL, self.tr('Interval between vertices to add'), QgsProcessingParameterNumber.Double, 1, False, 0, 10000000)) def name(self): return 'densifygeometriesgivenaninterval' def displayName(self): return self.tr('Densify geometries given an interval') def outputName(self): return self.tr('Densified') def prepareAlgorithm(self, parameters, context, feedback): interval = self.parameterAsDouble(parameters, self.INTERVAL, context) return True def processFeature(self, feature, feedback): if feature.hasGeometry(): new_geometry = feature.geometry().densifyByDistance(float(interval)) feature.setGeometry(new_geometry) return feature
GeoCat/QGIS
python/plugins/processing/algs/qgis/DensifyGeometriesInterval.py
Python
gpl-2.0
2,510
""" Use reentrant functions. Do not use not reentrant functions.(ctime, strtok, toupper) == Violation == void A() { k = ctime(); <== Violation. ctime() is not the reenterant function. j = strok(blar blar); <== Violation. strok() is not the reenterant function. } == Good == void A() { k = t.ctime(); <== Correct. It may be the reentrant function. } void A() { k = ctime; <== Correct. It may be the reentrant function. } """ from nsiqunittest.nsiqcppstyle_unittestbase import * from nsiqcppstyle_rulehelper import * from nsiqcppstyle_reporter import * from nsiqcppstyle_rulemanager import * no_reenterant_functions = ( 'ctime', 'strtok', 'toupper', ) def RunRule(lexer, contextStack): """ Use reenterant keyword. """ t = lexer.GetCurToken() if t.type == "ID": if t.value in no_reenterant_functions: t2 = lexer.PeekNextTokenSkipWhiteSpaceAndComment() t3 = lexer.PeekPrevTokenSkipWhiteSpaceAndComment() if t2 is not None and t2.type == "LPAREN": if t3 is None or t3.type != "PERIOD": if t.value == "toupper" and nsiqcppstyle_state._nsiqcppstyle_state.GetVar( "ignore_toupper", "false") == "true": return nsiqcppstyle_reporter.Error(t, __name__, "Do not use not reentrant function(%s)." % t.value) ruleManager.AddFunctionScopeRule(RunRule) ########################################################################## # Unit Test ########################################################################## class testRule(nct): def setUpRule(self): ruleManager.AddFunctionScopeRule(RunRule) def test1(self): self.Analyze("thisfile.c", """ void func1() { k = ctime() } """) self.ExpectError(__name__) def test2(self): self.Analyze("thisfile.c", """ void func1() { #define ctime() k } """) self.ExpectSuccess(__name__) def test3(self): self.Analyze("thisfile.c", """ void ctime() { } """) self.ExpectSuccess(__name__) def test4(self): self.Analyze("thisfile.c", """ void ctime () { } """) self.ExpectSuccess(__name__) def test5(self): self.Analyze("thisfile.c", """ void func1() { k = help.ctime () } """) self.ExpectSuccess(__name__) def test6(self): self.Analyze("thisfile.c", """ void func1() { k = toupper() } """) self.ExpectError(__name__) def test7(self): nsiqcppstyle_state._nsiqcppstyle_state.varMap["ignore_toupper"] = "true" self.Analyze("thisfile.c", """ void func1() { k = toupper() } """) self.ExpectSuccess(__name__)
kunaltyagi/nsiqcppstyle
rules/RULE_9_2_D_use_reentrant_function.py
Python
gpl-2.0
3,067
# encoding: utf-8 # # FRETBursts - A single-molecule FRET burst analysis toolkit. # # Copyright (C) 2013-2016 The Regents of the University of California, # Antonino Ingargiola <tritemio@gmail.com> # """ This module defines all the plotting functions for the :class:`fretbursts.burstlib.Data` object. The main plot function is `dplot()` that takes, as parameters, a `Data()` object and a 1-ch-plot-function and creates a subplot for each channel. The 1-ch plot functions are usually called through `dplot` but can also be called directly to make a single channel plot. The 1-ch plot functions names all start with the plot type (`timetrace`, `ratetrace`, `hist` or `scatter`). **Example 1** - Plot the timetrace for all ch:: dplot(d, timetrace, scroll=True) **Example 2** - Plot a FRET histogramm for each ch with a fit overlay:: dplot(d, hist_fret, show_model=True) For more examples refer to `FRETBurst notebooks <http://nbviewer.ipython.org/github/tritemio/FRETBursts_notebooks/tree/master/notebooks/>`_. """ from __future__ import division, print_function, absolute_import from builtins import range import warnings from itertools import cycle # Numeric imports import numpy as np from numpy import arange, r_ from matplotlib.mlab import normpdf from scipy.stats import erlang from scipy.interpolate import UnivariateSpline # Graphics imports import matplotlib.pyplot as plt from matplotlib.pyplot import (plot, hist, xlabel, ylabel, grid, title, legend, gca, gcf) from matplotlib.patches import Rectangle, Ellipse from matplotlib.collections import PatchCollection, PolyCollection import seaborn as sns # Local imports from .ph_sel import Ph_sel from . import burstlib as bl from .phtools import phrates from . import burstlib_ext as bext from . import background as bg from .utils.misc import HistData, _is_list_of_arrays from .scroll_gui import ScrollingToolQT from . import gui_selection as gs ## # Globals # blue = '#0055d4' green = '#2ca02c' red = '#e74c3c' # '#E41A1C' purple = '#9b59b6' _ph_sel_color_dict = {Ph_sel('all'): blue, Ph_sel(Dex='Dem'): green, Ph_sel(Dex='Aem'): red, Ph_sel(Aex='Aem'): purple, Ph_sel(Aex='Dem'): 'c', } _ph_sel_label_dict = {Ph_sel('all'): 'All-ph', Ph_sel(Dex='Dem'): 'DexDem', Ph_sel(Dex='Aem'): 'DexAem', Ph_sel(Aex='Aem'): 'AexAem', Ph_sel(Aex='Dem'): 'AexDem'} # Global store for plot status _plot_status = {} # Global store for GUI handlers gui_status = {'first_plot_in_figure': True} ## # Utility functions # def _normalize_kwargs(kwargs, kind='patch'): """Convert matplotlib keywords from short to long form.""" if kwargs is None: return {} if kind == 'line2d': long_names = dict(c='color', ls='linestyle', lw='linewidth', mec='markeredgecolor', mew='markeredgewidth', mfc='markerfacecolor', ms='markersize',) elif kind == 'patch': long_names = dict(c='color', ls='linestyle', lw='linewidth', ec='edgecolor', fc='facecolor',) for short_name in long_names: if short_name in kwargs: kwargs[long_names[short_name]] = kwargs.pop(short_name) return kwargs def bsavefig(d, s): """Save current figure with name in `d`, appending the string `s`.""" plt.savefig(d.Name() + s) ## # Multi-channel plot functions # def mch_plot_bg(d, **kwargs): """Plot background vs channel for DA, D and A photons.""" bg = d.bg_from(Ph_sel('all')) bg_dd = d.bg_from(Ph_sel(Dex='Dem')) bg_ad = d.bg_from(Ph_sel(Dex='Aem')) plot(r_[1:d.nch+1], [b.mean()*1e-3 for b in bg], lw=2, color=blue, label=' T', **kwargs) plot(r_[1:d.nch+1], [b.mean()*1e-3 for b in bg_dd], color=green, lw=2, label=' D', **kwargs) plot(r_[1:d.nch+1], [b.mean()*1e-3 for b in bg_ad], color=red, lw=2, label=' A', **kwargs) xlabel("CH"); ylabel("kcps"); grid(True); legend(loc='best') title(d.name) def mch_plot_bg_ratio(d): """Plot ratio of A over D background vs channel.""" bg_dd = d.bg_from(Ph_sel(Dex='Dem')) bg_ad = d.bg_from(Ph_sel(Dex='Aem')) plot(r_[1:d.nch+1], [ba.mean()/bd.mean() for bd, ba in zip(bg_dd, bg_ad)], color=green, lw=2, label='A/D') xlabel("CH"); ylabel("BG Ratio A/D"); grid(True) title("BG Ratio A/D "+d.name) def mch_plot_bsize(d): """Plot mean burst size vs channel.""" CH = np.arange(1, d.nch+1) plot(CH, [b.mean() for b in d.nt], color=blue, lw=2, label=' T') plot(CH, [b.mean() for b in d.nd], color=green, lw=2, label=' D') plot(CH, [b.mean() for b in d.na], color=red, lw=2, label=' A') xlabel("CH"); ylabel("Mean burst size") grid(True) legend(loc='best') title(d.name) ## # ALEX alternation period plots # def plot_alternation_hist(d, bins=None, ax=None, **kwargs): """Plot the ALEX alternation histogram for the variable `d`. This function works both for us-ALEX and ns-ALEX data. This function must be called on ALEX data **before** calling :func:`fretbursts.loader.alex_apply_period`. """ assert d.alternated if d.lifetime: plot_alternation = plot_alternation_hist_nsalex else: plot_alternation = plot_alternation_hist_usalex plot_alternation(d, bins=bins, ax=ax, **kwargs) def plot_alternation_hist_usalex(d, bins=None, ax=None, ich=0, hist_style={}, span_style={}): """Plot the us-ALEX alternation histogram for the variable `d`. This function must be called on us-ALEX data **before** calling :func:`fretbursts.loader.alex_apply_period`. """ if ax is None: _, ax = plt.subplots() if bins is None: bins = 100 D_ON, A_ON = d._D_ON_multich[ich], d._A_ON_multich[ich] d_ch, a_ch = d._det_donor_accept_multich[ich] offset = d.get('offset', 0) ph_times_t, det_t = d.ph_times_t[ich][:], d.det_t[ich][:] period = d.alex_period d_em_t = (det_t == d_ch) hist_style_ = dict(bins=bins, histtype='step', lw=2, alpha=0.9, zorder=2) hist_style_.update(hist_style) span_style_ = dict(alpha=0.2, zorder=1) span_style_.update(span_style) D_label = 'Donor: %d-%d' % (D_ON[0], D_ON[1]) A_label = 'Accept: %d-%d' % (A_ON[0], A_ON[1]) ax.hist((ph_times_t[d_em_t] - offset) % period, color=green, label=D_label, **hist_style_) ax.hist((ph_times_t[~d_em_t] - offset) % period, color=red, label=A_label, **hist_style_) ax.set_xlabel('Timestamp MODULO Alternation period') if D_ON[0] < D_ON[1]: ax.axvspan(D_ON[0], D_ON[1], color=green, **span_style_) else: ax.axvspan(0, D_ON[1], color=green, **span_style_) ax.axvspan(D_ON[0], period, color=green, **span_style_) if A_ON[0] < A_ON[1]: ax.axvspan(A_ON[0], A_ON[1], color=red, **span_style_) else: ax.axvspan(0, A_ON[1], color=red, **span_style_) ax.axvspan(A_ON[0], period, color=red, **span_style_) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), frameon=False) def plot_alternation_hist_nsalex(d, bins=None, ax=None, ich=0, hist_style={}, span_style={}): """Plot the ns-ALEX alternation histogram for the variable `d`. This function must be called on ns-ALEX data **before** calling :func:`fretbursts.loader.alex_apply_period`. """ if ax is None: _, ax = plt.subplots() if bins is None: bins = np.arange(d.nanotimes_params[ich]['tcspc_num_bins']) D_ON_multi, A_ON_multi = d._D_ON_multich[ich], d._A_ON_multich[ich] D_ON = [(D_ON_multi[i], D_ON_multi[i+1]) for i in range(0, len(D_ON_multi), 2)] A_ON = [(A_ON_multi[i], A_ON_multi[i+1]) for i in range(0, len(A_ON_multi), 2)] d_ch, a_ch = d._det_donor_accept_multich[ich] hist_style_ = dict(bins=bins, histtype='step', lw=1.3, alpha=0.9, zorder=2) hist_style_.update(hist_style) span_style_ = dict(alpha=0.2, zorder=1) span_style_.update(span_style) D_label = 'Donor: ' for d_on in D_ON: D_label += '%d-%d' % (d_on[0], d_on[1]) A_label = 'Accept: ' for a_on in A_ON: A_label += '%d-%d' % (a_on[0], a_on[1]) nanotimes_d = d.nanotimes_t[ich][d.det_t[ich] == d_ch] nanotimes_a = d.nanotimes_t[ich][d.det_t[ich] == a_ch] ax.hist(nanotimes_d, label=D_label, color=green, **hist_style_) ax.hist(nanotimes_a, label=A_label, color=red, **hist_style_) ax.set_xlabel('Nanotime bin') ax.set_yscale('log') for d_on in D_ON: ax.axvspan(d_on[0], d_on[1], color=green, **span_style_) for a_on in A_ON: ax.axvspan(a_on[0], a_on[1], color=red, **span_style_) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), frameon=False) ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ## Multi-channel plots ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ## # Timetrace plots # def _burst_info(d, ich, burst_index): burst = d.mburst[ich][burst_index] params = dict( b_index=burst_index, start_ms=float(burst.start) * d.clk_p * 1e3, width_ms=float(burst.width) * d.clk_p * 1e3, nt=d.nt[ich][burst_index], nd=d.nd[ich][burst_index], na=d.na[ich][burst_index], E=d.E[ich][burst_index]) msg = ("[{b_index}]: w={width_ms:4.2f} ms\n" "size=(T{nt:3.0f}, D{nd:3.0f}, A{na:3.0f}") if d.alternated: msg += ", AA{naa:3.0f}" params['naa'] = d.naa[ich][burst_index] msg += ")\n E={E:4.2%}" if d.alternated: msg += " S={S:4.2%}" params['S'] = d.S[ich][burst_index] return msg.format(**params) def _plot_bursts(d, i, tmin_clk, tmax_clk, pmax=1e3, pmin=0, color="#999999", ytext=20): """Highlights bursts in a timetrace plot.""" b = d.mburst[i] if b.num_bursts == 0: return burst_mask = (tmin_clk < b.start) * (b.start < tmax_clk) bs = b[burst_mask] burst_indices = np.where(burst_mask)[0] start = bs.start * d.clk_p end = bs.stop * d.clk_p R = [] width = end - start ax = gca() for b, bidx, s, w, sign, va in zip(bs, burst_indices, start, width, cycle([-1, 1]), cycle(['top', 'bottom'])): r = Rectangle(xy=(s, pmin), height=pmax - pmin, width=w) r.set_clip_box(ax.bbox) r.set_zorder(0) R.append(r) ax.text(s, sign * ytext, _burst_info(d, i, bidx), fontsize=6, rotation=45, horizontalalignment='center', va=va) ax.add_artist(PatchCollection(R, lw=0, color=color)) def _plot_rate_th(d, i, F, ph_sel, invert=False, scale=1, plot_style_={}, rate_th_style={}): """Plots background_rate*F as a function of time. `plot_style_` is the style of a timetrace/ratetrace plot used as starting style. Linestyle and label are changed. Finally, `rate_th_style` is applied and can override any style property. If rate_th_style_['label'] is 'auto' the label is generated from plot_style_['label'] and F. """ if F is None: F = d.F if F in d else 6 rate_th_style_ = dict(plot_style_) rate_th_style_.update(linestyle='--', label='auto') rate_th_style_.update(_normalize_kwargs(rate_th_style, kind='line2d')) if rate_th_style_['label'] is 'auto': rate_th_style_['label'] = 'bg_rate*%d %s' % \ (F, plot_style_['label']) x_rate = np.hstack(d.Ph_p[i]) * d.clk_p y_rate = F * np.hstack([(rate, rate) for rate in d.bg_from(ph_sel)[i]]) y_rate *= scale if invert: y_rate *= -1 plot(x_rate, y_rate, **rate_th_style_) def _gui_timetrace_burst_sel(d, fig, ax): """Add GUI burst selector via mouse click to the current plot.""" global gui_status if gui_status['first_plot_in_figure']: gui_status['burst_sel'] = gs.MultiAxPointSelection(fig, ax, d) else: gui_status['burst_sel'].ax_list.append(ax) def _gui_timetrace_scroll(fig): """Add GUI to scroll a timetrace wi a slider.""" global gui_status if gui_status['first_plot_in_figure']: gui_status['scroll_gui'] = ScrollingToolQT(fig) def timetrace_single(d, i=0, binwidth=1e-3, bins=None, tmin=0, tmax=200, ph_sel=Ph_sel('all'), invert=False, bursts=False, burst_picker=True, scroll=False, cache_bins=True, plot_style=None, show_rate_th=True, F=None, rate_th_style={}, set_ax_limits=True, burst_color='#BBBBBB'): """Plot the timetrace (histogram) of timestamps for a photon selection. See :func:`timetrace` to plot multiple photon selections (i.e. Donor and Acceptor photons) in one step. """ if tmax is None or tmax < 0 or tmax > d.time_max: tmax = d.time_max def _get_cache(): return (timetrace_single.bins, timetrace_single.x, timetrace_single.binwidth, timetrace_single.tmin, timetrace_single.tmax) def _set_cache(bins, x, binwidth, tmin, tmax): cache = dict(bins=bins, x=x, binwidth=binwidth, tmin=tmin, tmax=tmax) for name, value in cache.items(): setattr(timetrace_single, name, value) def _del_cache(): names = ['bins', 'x', 'binwidth', 'tmin', 'tmax'] for name in names: delattr(timetrace_single, name) def _has_cache(): return hasattr(timetrace_single, 'bins') def _has_cache_for(binwidth, tmin, tmax): if _has_cache(): return (binwidth, tmin, tmax) == _get_cache()[2:] return False # If cache_bins is False delete any previously saved attribute if not cache_bins and _has_cache: _del_cache() tmin_clk, tmax_clk = tmin / d.clk_p, tmax / d.clk_p binwidth_clk = binwidth / d.clk_p # If bins is not passed try to use the cached one if bins is None: if cache_bins and _has_cache_for(binwidth, tmin, tmax): bins, x = timetrace_single.bins, timetrace_single.x else: bins = np.arange(tmin_clk, tmax_clk + 1, binwidth_clk) x = bins[:-1] * d.clk_p + 0.5 * binwidth if cache_bins: _set_cache(bins, x, binwidth, tmin, tmax) # Compute histogram ph_times = d.get_ph_times(i, ph_sel=ph_sel) timetrace, _ = np.histogram(ph_times, bins=bins) if invert: timetrace *= -1 # Plot bursts if bursts: _plot_bursts(d, i, tmin_clk, tmax_clk, pmax=500, pmin=-500, color=burst_color) # Plot timetrace plot_style_ = dict(linestyle='-', linewidth=1.2, marker=None) if ph_sel in _ph_sel_color_dict: plot_style_['color'] = _ph_sel_color_dict[ph_sel] plot_style_['label'] = _ph_sel_label_dict[ph_sel] else: plot_style_['label'] = str(ph_sel) plot_style_.update(_normalize_kwargs(plot_style, kind='line2d')) plot(x, timetrace, **plot_style_) # Plot burst-search rate-threshold if show_rate_th and 'bg' in d: _plot_rate_th(d, i, F=F, ph_sel=ph_sel, invert=invert, scale=binwidth, plot_style_=plot_style_, rate_th_style=rate_th_style) plt.xlabel('Time (s)') plt.ylabel('# ph') if burst_picker and 'mburst' in d: _gui_timetrace_burst_sel(d, gcf(), gca()) if scroll: _gui_timetrace_scroll(gcf()) if set_ax_limits: plt.xlim(tmin, tmin + 1) if not invert: plt.ylim(ymax=100) else: plt.ylim(ymin=-100) _plot_status['timetrace_single'] = {'autoscale': False} def timetrace(d, i=0, binwidth=1e-3, bins=None, tmin=0, tmax=200, bursts=False, burst_picker=True, scroll=False, show_rate_th=True, F=None, rate_th_style={'label': None}, show_aa=True, legend=False, set_ax_limits=True, burst_color='#BBBBBB', plot_style=None, #dd_plot_style={}, ad_plot_style={}, aa_plot_style={} ): """Plot the timetraces (histogram) of photon timestamps. Arguments: d (Data object): the measurement's data to plot. i (int): the channel to plot. Default 0. binwidth (float): the bin width (seconds) of the timetrace histogram. bins (array or None): If not None, defines the bin edges for the timetrace (overriding `binwidth`). If None, `binwidth` is use to generate uniform bins. tmin, tmax (float): min and max time (seconds) to include in the timetrace. Note that a long time range and a small `binwidth` can require a significant amount of memory. bursts (bool): if True, plot the burst start-stop times. burst_picker (bool): if True, enable the ability to click on bursts to obtain burst info. This function requires the matplotlib's QT backend. scroll (bool): if True, activate a scrolling bar to quickly scroll through the timetrace. This function requires the matplotlib's QT backend. show_rate_th (bool): if True, plot the burst search threshold rate. F (bool): if `show_rate` is True, show a rate `F` times larger than the background rate. rate_th_style (dict): matplotlib style for the rate line. show_aa (bool): if True, plot a timetrace for the AexAem photons. If False (default), plot timetraces only for DexDem and DexAem streams. legend (bool): whether to show the legend or not. set_ax_limits (bool): if True, set the xlim to zoom on a small portion of timetrace. If False, do not set the xlim, display the full timetrace. burst_color (string): string containing the the HEX RGB color to use to highlight the burst regions. plot_style (dict): matplotlib's style for the timetrace lines. """ # Plot bursts if bursts: tmin_clk, tmax_clk = tmin / d.clk_p, tmax / d.clk_p _plot_bursts(d, i, tmin_clk, tmax_clk, pmax=500, pmin=-500, color=burst_color) # Plot multiple timetraces ph_sel_list = [Ph_sel(Dex='Dem'), Ph_sel(Dex='Aem')] invert_list = [False, True] burst_picker_list = [burst_picker, False] scroll_list = [scroll, False] if d.alternated and show_aa: ph_sel_list.append(Ph_sel(Aex='Aem')) invert_list.append(True) burst_picker_list.append(False) scroll_list.append(False) for ix, (ph_sel, invert) in enumerate(zip(ph_sel_list, invert_list)): if not bl.mask_empty(d.get_ph_mask(i, ph_sel=ph_sel)): timetrace_single( d, i, binwidth=binwidth, bins=bins, tmin=tmin, tmax=tmax, ph_sel=ph_sel, invert=invert, bursts=False, burst_picker=burst_picker_list[ix], scroll=scroll_list[ix], cache_bins=True, show_rate_th=show_rate_th, F=F, rate_th_style=rate_th_style, set_ax_limits=set_ax_limits, plot_style=plot_style) if legend: plt.legend(loc='best', fancybox=True) def ratetrace_single(d, i=0, m=None, max_num_ph=1e6, tmin=0, tmax=200, ph_sel=Ph_sel('all'), invert=False, bursts=False, burst_picker=True, scroll=False, plot_style={}, show_rate_th=True, F=None, rate_th_style={}, set_ax_limits=True, burst_color='#BBBBBB'): """Plot the ratetrace of timestamps for a photon selection. See :func:`ratetrace` to plot multiple photon selections (i.e. Donor and Acceptor photons) in one step. """ if tmax is None or tmax < 0: tmax = d.time_max if m is None: m = d.m if m in d else 10 tmin_clk, tmax_clk = tmin / d.clk_p, tmax / d.clk_p # Plot bursts if bursts: _plot_bursts(d, i, tmin_clk, tmax_clk, pmax=500, pmin=-500, color=burst_color) # Compute ratetrace ph_times = d.get_ph_times(i, ph_sel=ph_sel) iph1 = np.searchsorted(ph_times, tmin_clk) iph2 = np.searchsorted(ph_times, tmax_clk) if iph2 - iph1 > max_num_ph: iph2 = iph1 + max_num_ph tmax = ph_times[iph2] * d.clk_p warnings.warn(('Max number of photons reached in ratetrace_single().' '\n tmax is reduced to %ds. To plot a wider ' 'time range increase `max_num_ph`.') % tmax, UserWarning) ph_times = ph_times[iph1:iph2] rates = 1e-3 * phrates.mtuple_rates(ph_times, m) / d.clk_p if invert: rates *= -1 times = phrates.mtuple_rates_t(ph_times, m) * d.clk_p # Plot ratetrace plot_style_ = dict(linestyle='-', linewidth=1.2, marker=None) if ph_sel in _ph_sel_color_dict: plot_style_['color'] = _ph_sel_color_dict[ph_sel] plot_style_['label'] = _ph_sel_label_dict[ph_sel] plot_style_.update(_normalize_kwargs(plot_style, kind='line2d')) plot(times, rates, **plot_style_) # Plot burst-search rate-threshold if show_rate_th and 'bg' in d: _plot_rate_th(d, i, F=F, scale=1e-3, ph_sel=ph_sel, invert=invert, plot_style_=plot_style_, rate_th_style=rate_th_style) plt.xlabel('Time (s)') plt.ylabel('Rate (kcps)') if burst_picker: _gui_timetrace_burst_sel(d, gcf(), gca()) if scroll: _gui_timetrace_scroll(gcf()) if set_ax_limits: plt.xlim(tmin, tmin + 1) if not invert: plt.ylim(ymax=100) else: plt.ylim(ymin=-100) _plot_status['ratetrace_single'] = {'autoscale': False} def ratetrace(d, i=0, m=None, max_num_ph=1e6, tmin=0, tmax=200, bursts=False, burst_picker=True, scroll=False, show_rate_th=True, F=None, rate_th_style={'label': None}, show_aa=True, legend=False, set_ax_limits=True, #dd_plot_style={}, ad_plot_style={}, aa_plot_style={} burst_color='#BBBBBB'): """Plot the rate timetraces of photon timestamps. Arguments: d (Data object): the measurement's data to plot. i (int): the channel to plot. Default 0. max_num_ph (int): Clip the rate timetrace after the max number of photons `max_num_ph` is reached. tmin, tmax (float): min and max time (seconds) to include in the timetrace. Note that a long time range and a small `binwidth` can require a significant amount of memory. bursts (bool): if True, plot the burst start-stop times. burst_picker (bool): if True, enable the ability to click on bursts to obtain burst info. This function requires the matplotlib's QT backend. scroll (bool): if True, activate a scrolling bar to quickly scroll through the timetrace. This function requires the matplotlib's QT backend. show_rate_th (bool): if True, plot the burst search threshold rate. F (bool): if `show_rate` is True, show a rate `F` times larger than the background rate. rate_th_style (dict): matplotlib style for the rate line. show_aa (bool): if True, plot a timetrace for the AexAem photons. If False (default), plot timetraces only for DexDem and DexAem streams. legend (bool): whether to show the legend or not. set_ax_limits (bool): if True, set the xlim to zoom on a small portion of timetrace. If False, do not set the xlim, display the full timetrace. burst_color (string): string containing the the HEX RGB color to use to highlight the burst regions. """ # Plot bursts if bursts: tmin_clk, tmax_clk = tmin / d.clk_p, tmax / d.clk_p _plot_bursts(d, i, tmin_clk, tmax_clk, pmax=500, pmin=-500, color=burst_color) # Plot multiple timetraces ph_sel_list = [Ph_sel(Dex='Dem'), Ph_sel(Dex='Aem')] invert_list = [False, True] burst_picker_list = [burst_picker, False] scroll_list = [scroll, False] if d.alternated and show_aa: ph_sel_list.append(Ph_sel(Aex='Aem')) invert_list.append(True) burst_picker_list.append(False) scroll_list.append(False) for ix, (ph_sel, invert) in enumerate(zip(ph_sel_list, invert_list)): if not bl.mask_empty(d.get_ph_mask(i, ph_sel=ph_sel)): ratetrace_single( d, i, m=m, max_num_ph=max_num_ph, tmin=tmin, tmax=tmax, ph_sel=ph_sel, invert=invert, bursts=False, burst_picker=burst_picker_list[ix], scroll=scroll_list[ix], show_rate_th=show_rate_th, F=F, rate_th_style=rate_th_style, set_ax_limits=set_ax_limits) if legend: plt.legend(loc='best', fancybox=True) def sort_burst_sizes(sizes, levels=np.arange(1, 102, 20)): """Return a list of masks that split `sizes` in levels. Used by timetrace_fret to select burst based on size groups. """ masks = [] for level1, level2 in zip(levels[:-1], levels[1:]): masks.append((sizes >= level1)*(sizes < level2)) masks.append(sizes >= level2) return masks def timetrace_fret(d, i=0, gamma=1., **kwargs): """Timetrace of burst FRET vs time. Uses `plot`.""" b = d.mburst[i] bsizes = bl.select_bursts.get_burst_size(d, ich=i, gamma=gamma) style_kwargs = dict(marker='o', mew=0.5, color=blue, mec='grey', alpha=0.4, ls='') style_kwargs.update(**kwargs) t, E = b.start*d.clk_p, d.E[i] levels = sort_burst_sizes(bsizes) for ilev, level in enumerate(levels): plt.plot(t[level], E[level], ms=np.sqrt((ilev+1)*15), **style_kwargs) plt.plot(b.start*d.clk_p, d.E[i], '-k', alpha=0.1, lw=1) xlabel('Time (s)'); ylabel('E') _gui_timetrace_burst_sel(d, i, timetrace_fret, gcf(), gca()) def timetrace_fret_scatter(d, i=0, gamma=1., **kwargs): """Timetrace of burst FRET vs time. Uses `scatter` (slow).""" b = d.mburst[i] bsizes = d.burst_sizes_ich(d, ich=i, gamma=gamma) style_kwargs = dict(s=bsizes, marker='o', alpha=0.5) style_kwargs.update(**kwargs) plt.scatter(b.start*d.clk_p, d.E[i], **style_kwargs) xlabel('Time (s)'); ylabel('E') def timetrace_bg(d, i=0, nolegend=False, ncol=2, plot_style={}, show_da=False): """Timetrace of background rates.""" bg = d.bg_from(Ph_sel('all')) bg_dd = d.bg_from(Ph_sel(Dex='Dem')) bg_ad = d.bg_from(Ph_sel(Dex='Aem')) t = arange(bg[i].size) * d.bg_time_s plot_style_ = dict(linewidth=2, marker='o', markersize=6) plot_style_.update(_normalize_kwargs(plot_style, kind='line2d')) label = "T: %d cps" % d.bg_mean[Ph_sel('all')][i] plot(t, 1e-3 * bg[i], color='k', label=label, **plot_style_) label = "DD: %d cps" % d.bg_mean[Ph_sel(Dex='Dem')][i] plot(t, 1e-3 * bg_dd[i], color=green, label=label, **plot_style_) label = "AD: %d cps" % d.bg_mean[Ph_sel(Dex='Aem')][i] plot(t, 1e-3 * bg_ad[i], color=red, label=label, **plot_style_) if d.alternated: bg_aa = d.bg_from(Ph_sel(Aex='Aem')) label = "AA: %d cps" % d.bg_mean[Ph_sel(Aex='Aem')][i] plot(t, 1e-3 * bg_aa[i], label=label, color=purple, **plot_style_) if show_da: bg_da = d.bg_from(Ph_sel(Aex='Dem')) label = "DA: %d cps" % d.bg_mean[Ph_sel(Aex='Dem')][i] plot(t, 1e-3 * bg_da[i], label=label, color=_ph_sel_color_dict[Ph_sel(Aex='Dem')], **plot_style_) if not nolegend: legend(loc='best', frameon=False, ncol=ncol) plt.xlabel("Time (s)") plt.ylabel("BG rate (kcps)") plt.grid(True) plt.ylim(ymin=0) def timetrace_b_rate(d, i=0): """Timetrace of bursts-per-second in each period.""" t = arange(d.bg[i].size)*d.bg_time_s b_rate = r_[[(d.bp[i] == p).sum() for p in range(d.bp[i].max()+1)]] b_rate /= d.bg_time_s if t.size == b_rate.size+1: t = t[:-1] # assuming last period without bursts else: assert t.size == b_rate.size plot(t, b_rate, lw=2, label="CH%d" % (i+1)) legend(loc='best', fancybox=True, frameon=False, ncol=3) xlabel("Time (s)"); ylabel("Burst per second"); grid(True) plt.ylim(ymin=0) def time_ph(d, i=0, num_ph=1e4, ph_istart=0): """Plot 'num_ph' ph starting at 'ph_istart' marking burst start/end. TODO: Update to use the new matplotlib eventplot. """ b = d.mburst[i] SLICE = slice(ph_istart, ph_istart+num_ph) ph_d = d.ph_times_m[i][SLICE][~d.A_em[i][SLICE]] ph_a = d.ph_times_m[i][SLICE][d.A_em[i][SLICE]] BSLICE = (b.stop < ph_a[-1]) start, end = b[BSLICE].start, b[BSLICE].stop u = d.clk_p # time scale plt.vlines(ph_d*u, 0, 1, color='k', alpha=0.02) plt.vlines(ph_a*u, 0, 1, color='k', alpha=0.02) plt.vlines(start*u, -0.5, 1.5, lw=3, color=green, alpha=0.5) plt.vlines(end*u, -0.5, 1.5, lw=3, color=red, alpha=0.5) xlabel("Time (s)") ## # Histogram plots # def _bins_array(bins): """When `bins` is a 3-element sequence returns an array of bin edges. Otherwise returns the `bins` unchaged. """ if np.size(bins) == 3: bins = np.arange(*bins) return bins def _hist_burst_taildist(data, bins, pdf, weights=None, yscale='log', color=None, label=None, plot_style=None, vline=None): hist = HistData(*np.histogram(data[~np.isnan(data)], bins=_bins_array(bins), weights=weights)) ydata = hist.pdf if pdf else hist.counts default_plot_style = dict(marker='o') if plot_style is None: plot_style = {} if color is not None: plot_style['color'] = color if label is not None: plot_style['label'] = label default_plot_style.update(_normalize_kwargs(plot_style, kind='line2d')) plt.plot(hist.bincenters, ydata, **default_plot_style) if vline is not None: plt.axvline(vline, ls='--') plt.yscale(yscale) if pdf: plt.ylabel('PDF') else: plt.ylabel('# Bursts') def hist_width(d, i=0, bins=(0, 10, 0.025), pdf=True, weights=None, yscale='log', color=None, plot_style=None, vline=None): """Plot histogram of burst durations. Parameters: d (Data): Data object i (int): channel index bins (array or None): array of bin edges. If len(bins) == 3 then is interpreted as (start, stop, step) values. pdf (bool): if True, normalize the histogram to obtain a PDF. color (string or tuple or None): matplotlib color used for the plot. yscale (string): 'log' or 'linear', sets the plot y scale. plot_style (dict): dict of matplotlib line style passed to `plot`. vline (float): If not None, plot vertical line at the specified x position. """ weights = weights[i] if weights is not None else None burst_widths = d.mburst[i].width * d.clk_p * 1e3 _hist_burst_taildist(burst_widths, bins, pdf, weights=weights, vline=vline, yscale=yscale, color=color, plot_style=plot_style) plt.xlabel('Burst width (ms)') plt.xlim(xmin=0) def hist_brightness(d, i=0, bins=(0, 60, 1), pdf=True, weights=None, yscale='log', gamma=1, add_naa=False, beta=1., donor_ref=True, add_aex=True, aex_corr=True, label_prefix=None, color=None, plot_style=None, vline=None): """Plot histogram of burst brightness, i.e. burst size / duration. Parameters: d (Data): Data object i (int): channel index bins (array or None): array of bin edges. If len(bins) == 3 then is interpreted as (start, stop, step) values. gamma, beta (floats): factors used to compute the corrected burst size. See :meth:`fretbursts.burstlib.Data.burst_sizes_ich`. add_naa (bool): if True, include `naa` to the total burst size. donor_ref (bool): convention used for corrected burst size computation. See :meth:`fretbursts.burstlib.Data.burst_sizes_ich` for details. add_aex (bool): *PAX-only*. Whether to add signal from Aex laser period to the burst size. Default True. See :meth:`fretbursts.burstlib.Data.burst_sizes_pax_ich`. aex_corr (bool): *PAX-only*. If True, do duty-cycle correction when adding the DAexAem term `naa`. See :meth:`fretbursts.burstlib.Data.burst_sizes_pax_ich`. label_prefix (string or None): a custom prefix for the legend label. color (string or tuple or None): matplotlib color used for the plot. pdf (bool): if True, normalize the histogram to obtain a PDF. yscale (string): 'log' or 'linear', sets the plot y scale. plot_style (dict): dict of matplotlib line style passed to `plot`. vline (float): If not None, plot vertical line at the specified x position. """ weights = weights[i] if weights is not None else None if plot_style is None: plot_style = {} burst_widths = d.mburst[i].width * d.clk_p * 1e3 sizes, label = _get_sizes_and_formula( d=d, ich=i, gamma=gamma, beta=beta, donor_ref=donor_ref, add_naa=add_naa, add_aex=add_aex, aex_corr=aex_corr) brightness = sizes / burst_widths label = '$(' + label[1:-1] + ') / w$' if label_prefix is not None: label = label_prefix + ' ' + label # Use default label (with optional prefix) only if not explicitly # specified in `plot_style` if 'label' not in plot_style: plot_style['label'] = label _hist_burst_taildist(brightness, bins, pdf, weights=weights, vline=vline, yscale=yscale, color=color, plot_style=plot_style) plt.xlabel('Burst brightness (kHz)') plt.legend(loc='best') def _get_sizes_and_formula(d, ich, gamma, beta, donor_ref, add_naa, ph_sel, naa_aexonly, naa_comp, na_comp): label = ('${FD} + {FA}/\\gamma$' if donor_ref else '$\\gamma {FD} + {FA}$') kws = dict(gamma=gamma, beta=beta, donor_ref=donor_ref) if 'PAX' in d.meas_type and ph_sel is not None: kws_pax = dict(ph_sel=ph_sel, naa_aexonly=naa_aexonly, naa_comp=naa_comp, na_comp=na_comp) sizes = d.burst_sizes_pax_ich(ich=ich, **dict(kws, **kws_pax)) label = '$ %s $' % d._burst_sizes_pax_formula(**dict(kws, **kws_pax)) else: sizes = d.burst_sizes_ich(ich=ich, add_naa=add_naa, **kws) label = label.format(FD='n_d', FA='n_a') if add_naa: corr = '(\\gamma\\beta) ' if donor_ref else '\\beta ' label = label[:-1] + ' + n_{aa} / %s$' % corr return sizes, label def hist_size(d, i=0, which='all', bins=(0, 600, 4), pdf=False, weights=None, yscale='log', gamma=1, beta=1, donor_ref=True, add_naa=False, ph_sel=None, naa_aexonly=False, naa_comp=False, na_comp=False, vline=None, label_prefix=None, legend=True, color=None, plot_style=None): """Plot histogram of "burst sizes", according to different definitions. Arguments: d (Data): Data object i (int): channel index bins (array or None): array of bin edges. If len(bins) == 3 then is interpreted as (start, stop, step) values. which (string): what photons to include in "size". Valid values are 'all', 'nd', 'na', 'naa'. When 'all', sizes are computed with `d.burst_sizes()` (by default nd + na); 'nd', 'na', 'naa' get counts from `d.nd`, `d.na`, `d.naa` (respectively Dex-Dem, Dex-Aem, Aex-Aem). gamma, beta (floats): factors used to compute the corrected burst size. Ignored when `which` != 'all'. See :meth:`fretbursts.burstlib.Data.burst_sizes_ich`. add_naa (bool): if True, include `naa` to the total burst size. donor_ref (bool): convention used for corrected burst size computation. See :meth:`fretbursts.burstlib.Data.burst_sizes_ich` for details. na_comp (bool): **[PAX-only]** If True, multiply the `na` term by `(1 + Wa/Wd)`, where Wa and Wd are the D and A alternation durations (typically Wa/Wd = 1). naa_aexonly (bool): **[PAX-only]** if True, the `naa` term is corrected to include only A emission due to A excitation. If False, the `naa` term includes all the counts in DAexAem. The `naa` term also depends on the `naa_comp` argument. naa_comp (bool): **[PAX-only]** If True, multiply the `naa` term by `(1 + Wa/Wd)` where Wa and Wd are the D and A alternation durations (typically Wa/Wd = 1). The `naa` term also depends on the `naa_aexonly` argument. label_prefix (string or None): a custom prefix for the legend label. color (string or tuple or None): matplotlib color used for the plot. pdf (bool): if True, normalize the histogram to obtain a PDF. yscale (string): 'log' or 'linear', sets the plot y scale. legend (bool): if True add legend to plot plot_style (dict): dict of matplotlib line style passed to `plot`. vline (float): If not None, plot vertical line at the specified x position. See also: - :meth:`fretbursts.burstlib.Data.burst_sizes_ich`. - :meth:`fretbursts.burstlib.Data.burst_sizes_pax_ich`. """ weights = weights[i] if weights is not None else None if plot_style is None: plot_style = {} which_dict = {'all': 'k', 'nd': green, 'na': red, 'naa': purple, 'nar': red, 'nda': 'C0'} assert which in which_dict if which == 'all': sizes, label = _get_sizes_and_formula( d=d, ich=i, gamma=gamma, beta=beta, donor_ref=donor_ref, add_naa=add_naa, ph_sel=ph_sel, naa_aexonly=naa_aexonly, naa_comp=naa_comp, na_comp=na_comp) else: sizes = d[which][i] label = which # Use default label (with optional prefix) only if not explicitly # specified in `plot_style` if 'label' not in plot_style: if label_prefix is not None: label = label_prefix + ' ' + label plot_style['label'] = label # Use default color only if not specified in `color` or `plot_style` if color is None and 'color' not in plot_style: plot_style['color'] = which_dict[which] elif color is not None: plot_style['color'] = color _hist_burst_taildist(sizes, bins, pdf, weights=weights, yscale=yscale, plot_style=plot_style, vline=vline) plt.xlabel('Burst size') if legend: plt.legend(loc='upper right') def hist_size_all(d, i=0, **kwargs): """Plot burst sizes for all the combinations of photons. Calls :func:`hist_size` multiple times with different `which` parameters. """ fields = ['nd', 'na'] if d.ALEX: fields.append('naa') elif 'PAX' in d.meas_type: fields += ['nda', 'naa'] for which in fields: hist_size(d, i, which=which, **kwargs) def _fitted_E_plot(d, i=0, F=1, no_E=False, ax=None, show_model=True, verbose=False, two_gauss_model=False, lw=2.5, color='k', alpha=0.5, fillcolor=None): """Plot a fitted model overlay on a FRET histogram.""" if ax is None: ax2 = gca() else: ax2 = plt.twinx(ax=ax) ax2.grid(False) if d.fit_E_curve and show_model: x = r_[-0.2:1.21:0.002] y = d.fit_E_model(x, d.fit_E_res[i, :]) scale = F*d.fit_E_model_F[i] if two_gauss_model: assert d.fit_E_res.shape[1] > 2 if d.fit_E_res.shape[1] == 5: m1, s1, m2, s2, a1 = d.fit_E_res[i, :] a2 = (1-a1) elif d.fit_E_res.shape[1] == 6: m1, s1, a1, m2, s2, a2 = d.fit_E_res[i, :] y1 = a1*normpdf(x, m1, s1) y2 = a2*normpdf(x, m2, s2) ax2.plot(x, scale*y1, ls='--', lw=lw, alpha=alpha, color=color) ax2.plot(x, scale*y2, ls='--', lw=lw, alpha=alpha, color=color) if fillcolor is None: ax2.plot(x, scale*y, lw=lw, alpha=alpha, color=color) else: ax2.fill_between(x, scale*y, lw=lw, alpha=alpha, edgecolor=color, facecolor=fillcolor, zorder=10) if verbose: print('Fit Integral:', np.trapz(scale*y, x)) ax2.axvline(d.E_fit[i], lw=3, color=red, ls='--', alpha=0.6) xtext = 0.6 if d.E_fit[i] < 0.6 else 0.2 if d.nch > 1 and not no_E: ax2.text(xtext, 0.81, "CH%d: $E_{fit} = %.3f$" % (i+1, d.E_fit[i]), transform=gca().transAxes, fontsize=16, bbox=dict(boxstyle='round', facecolor='#dedede', alpha=0.5)) def hist_burst_data( d, i=0, data_name='E', ax=None, binwidth=0.03, bins=None, vertical=False, pdf=False, hist_style='bar', weights=None, gamma=1., add_naa=False, # weights args show_fit_stats=False, show_fit_value=False, fit_from='kde', show_kde=False, bandwidth=0.03, show_kde_peak=False, # kde args show_model=False, show_model_peaks=True, hist_bar_style=None, hist_plot_style=None, model_plot_style=None, kde_plot_style=None, verbose=False): """Plot burst_data (i.e. E, S, etc...) histogram and KDE. This a generic function to plot histograms for any burst data. In particular this function is called by :func:`hist_fret` and :func:`hist_S` to make E and S histograms respectively. Histograms and KDE can be plotted on any `Data` variable after burst search. To show a model, a model must be fitted first by calling `d.E_fitter.fit_histogram()`. To show the KDE peaks position, they must be computed first with `d.E_fitter.find_kde_max()`. The arguments are shown below grouped in logical sections. **Generic arguments** Args: data_name (string): name of the burst data (i.e. 'E' or 'S') ax (None or matplotlib axis): optional axis instance to plot in. vertical (bool): if True the x axis is oriented vertically. verbose (bool): if False, suppress any printed output. **Histogram arguments**: control the histogram appearance Args: hist_style (string): if 'bar' use a classical bar histogram, otherwise do a normal line plot of bin counts vs bin centers bins (None or array): if None the bins are computed according to `binwidth`. If not None contains the arrays of bin edges and overrides `binwidth`. binwidth (float): bin width for the histogram. pdf (bool): if True, normalize the histogram to obtain a PDF. hist_bar_style (dict): style dict for the histogram when `hist_style == 'bar'`. hist_plot_style (dict): style dict for the histogram when `hist_style != 'bar'`. **Model arguments**: control the model plot Args: show_model (bool): if True shows the model fitted to the histogram model (lmfit.Model object or None): lmfit Model used for histogram fitting. If None the histogram is not fitted. show_model_peaks (bool): if True marks the position of model peaks model_plot_style (dict): style dict for the model plot **KDE arguments**: control the KDE plot Args: show_kde (bool): if True shows the KDE curve show_kde_peak (bool): if True marks the position of the KDE peak bandwidth (float or None): bandwidth used to compute the KDE If None the KDE is not computed. kde_plot_style (dict): style dict for the KDE curve **Weights arguments** (weights are used to weight bursts according to their size, affecting histograms and KDEs). Args: weights (string or None): kind of burst-size weights. See :func:`fretbursts.fret_fit.get_weights`. gamma (float): gamma factor passed to `get_weights()`. add_naa (bool): if True adds `naa` to the burst size. **Fit text arguments**: control how to print annotation with fit information. Args: fit_from (string): determines how to obtain the fit value. If 'kde' the fit value is the KDE peak. Otherwise it must be the name of a model parameter that will be used as fit value. show_fit_value (bool): if True annotate the plot with fit value. show_fit_stats (bool): if True annotate the figure with mean fit value and max deviation across the channels (for multi-spot). """ assert data_name in d fitter_name = data_name + '_fitter' if ax is None: ax = gca() ax.set_axisbelow(True) pline = ax.axhline if vertical else ax.axvline bar = ax.barh if vertical else ax.bar xlabel, ylabel = ax.set_xlabel, ax.set_ylabel xlim, ylim = ax.set_xlim, ax.set_ylim if vertical: xlabel, ylabel = ylabel, xlabel xlim, ylim = ylim, xlim weights_tuple = (weights, float(gamma), add_naa) if not hasattr(d, fitter_name) or _is_list_of_arrays(weights) \ or getattr(d, data_name+'_weights') != weights_tuple: if hasattr(d, fitter_name): print(' - Overwriting the old %s object with the new weights.' % fitter_name) if verbose: print(' Old weights:', getattr(d, data_name+'_weights')) print(' New weights:', weights_tuple) bext.bursts_fitter(d, burst_data=data_name, weights=weights, gamma=gamma, add_naa=add_naa) # fitter_name is only an attribute of Data, not a key in the dictionary fitter = getattr(d, fitter_name) fitter.histogram(binwidth=binwidth, bins=bins, verbose=verbose) if pdf: ylabel('PDF') hist_vals = fitter.hist_pdf[i] else: ylabel('# Bursts') hist_vals = fitter.hist_counts[i] xlabel(data_name) if data_name in ['E', 'S']: xlim(-0.19, 1.19) hist_bar_style_ = dict(facecolor='#74a9cf', edgecolor='k', alpha=1, linewidth=0.15, label='E Histogram') hist_bar_style_.update(**_normalize_kwargs(hist_bar_style)) hist_plot_style_ = dict(linestyle='-', marker='o', markersize=6, linewidth=2, alpha=0.6, label='E Histogram') hist_plot_style_.update(_normalize_kwargs(hist_plot_style, kind='line2d')) if hist_style == 'bar': bar(fitter.hist_bins[:-1], hist_vals, fitter.hist_binwidth, align='edge', **hist_bar_style_) else: if vertical: ax.plot(hist_vals, fitter.hist_axis, **hist_plot_style_) else: ax.plot(fitter.hist_axis, hist_vals, **hist_plot_style_) if show_model or show_kde: if pdf: scale = 1 else: scale = fitter.hist_binwidth * d.num_bursts[i] if show_model: model_plot_style_ = dict(color='k', alpha=0.8, label='Model') model_plot_style_.update(_normalize_kwargs(model_plot_style, kind='line2d')) fit_res = fitter.fit_res[i] x = fitter.x_axis y = fit_res.model.eval(x=x, **fit_res.values) xx, yy = (y, x) if vertical else (x, y) ax.plot(xx, yy, **model_plot_style_) if fit_res.model.components is not None: for component in fit_res.model.components: model_plot_style_.update(ls='--', label='Model component') y = component.eval(x=x, **fit_res.values) xx, yy = (y, x) if vertical else (x, y) ax.plot(xx, yy, **model_plot_style_) if show_model_peaks: for param in fitter.params: if param.endswith('center'): pline(fitter.params[param][i], ls='--', color=red) if show_kde: x = fitter.x_axis fitter.calc_kde(bandwidth=bandwidth) kde_plot_style_ = dict(linewidth=1.5, color='k', alpha=0.8, label='KDE') kde_plot_style_.update(_normalize_kwargs(kde_plot_style, kind='line2d')) y = scale * fitter.kde[i](x) xx, yy = (y, x) if vertical else (x, y) ax.plot(xx, yy, **kde_plot_style_) if show_kde_peak: pline(fitter.kde_max_pos[i], ls='--', color='orange') if show_fit_value or show_fit_stats: if fit_from == 'kde': fit_arr = fitter.kde_max_pos else: assert fit_from in fitter.params fit_arr = fitter.params[fit_from] if i == 0: if show_fit_stats: plt.figtext(0.4, 0.01, _get_fit_text_stats(fit_arr), fontsize=16) if show_fit_value: _plot_fit_text_ch(fit_arr, i, ax=ax) def hist_fret( d, i=0, ax=None, binwidth=0.03, bins=None, pdf=True, hist_style='bar', weights=None, gamma=1., add_naa=False, # weights args show_fit_stats=False, show_fit_value=False, fit_from='kde', show_kde=False, bandwidth=0.03, show_kde_peak=False, # kde args show_model=False, show_model_peaks=True, hist_bar_style=None, hist_plot_style=None, model_plot_style=None, kde_plot_style=None, verbose=False): """Plot FRET histogram and KDE. The most used argument is `binwidth` that sets the histogram bin width. For detailed documentation see :func:`hist_burst_data`. """ hist_burst_data( d, i, data_name='E', ax=ax, binwidth=binwidth, bins=bins, pdf=pdf, weights=weights, gamma=gamma, add_naa=add_naa, hist_style=hist_style, show_fit_stats=show_fit_stats, show_fit_value=show_fit_value, fit_from=fit_from, show_kde=show_kde, bandwidth=bandwidth, show_kde_peak=show_kde_peak, # kde args show_model=show_model, show_model_peaks=show_model_peaks, hist_bar_style=hist_bar_style, hist_plot_style=hist_plot_style, model_plot_style=model_plot_style, kde_plot_style=kde_plot_style, verbose=verbose) def hist_S( d, i=0, ax=None, binwidth=0.03, bins=None, pdf=True, hist_style='bar', weights=None, gamma=1., add_naa=False, # weights args show_fit_stats=False, show_fit_value=False, fit_from='kde', show_kde=False, bandwidth=0.03, show_kde_peak=False, # kde args show_model=False, show_model_peaks=True, hist_bar_style=None, hist_plot_style=None, model_plot_style=None, kde_plot_style=None, verbose=False): """Plot S histogram and KDE. The most used argument is `binwidth` that sets the histogram bin width. For detailed documentation see :func:`hist_burst_data`. """ hist_burst_data( d, i, data_name='S', ax=ax, binwidth=binwidth, bins=bins, pdf=pdf, weights=weights, gamma=gamma, add_naa=add_naa, hist_style=hist_style, show_fit_stats=show_fit_stats, show_fit_value=show_fit_value, fit_from=fit_from, show_kde=show_kde, bandwidth=bandwidth, show_kde_peak=show_kde_peak, # kde args show_model=show_model, show_model_peaks=show_model_peaks, hist_bar_style=hist_bar_style, hist_plot_style=hist_plot_style, model_plot_style=model_plot_style, kde_plot_style=kde_plot_style, verbose=verbose) def _get_fit_text_stats(fit_arr, pylab=True): """Return a formatted string for mean E and max delta-E.""" delta = (fit_arr.max() - fit_arr.min())*100 fit_text = r'\langle{E}_{fit}\rangle = %.3f \qquad ' % fit_arr.mean() fit_text += r'\Delta E_{fit} = %.2f \%%' % delta if pylab: fit_text = r'$'+fit_text+r'$' return fit_text def _plot_fit_text_ch( fit_arr, ich, fmt_str="CH%d: $E_{fit} = %.3f$", ax=None, bbox=dict(boxstyle='round', facecolor='#dedede', alpha=0.5), xtext_low=0.2, xtext_high=0.6, fontsize=16): """Plot a text box with ch and fit value.""" if ax is None: ax = gca() xtext = xtext_high if fit_arr[ich] < xtext_high else xtext_low ax.text(xtext, 0.81, fmt_str % (ich+1, fit_arr[ich]), transform=ax.transAxes, fontsize=fontsize, bbox=bbox) def hist2d_alex(d, i=0, vmin=2, vmax=0, binwidth=0.05, S_max_norm=0.8, interp='bicubic', cmap='hot', under_color='white', over_color='white', scatter=True, scatter_ms=3, scatter_color='orange', scatter_alpha=0.2, gui_sel=False, cbar_ax=None, grid_color='#D0D0D0'): """Plot 2-D E-S ALEX histogram with a scatterplot overlay. """ ax = plt.gca() d._calc_alex_hist(binwidth) ES_hist, E_bins, S_bins, S_ax = d.ES_hist[i], d.E_bins, d.S_bins, d.S_ax colormap = plt.get_cmap(cmap) # Heuristic for colormap range if vmax <= vmin: S_range = (S_ax < S_max_norm) vmax = ES_hist[:, S_range].max() if vmax <= vmin: vmax = 10*vmin if scatter: ax.plot(d.E[i], d.S[i], 'o', mew=0, ms=scatter_ms, alpha=scatter_alpha, color=scatter_color) im = ax.imshow(ES_hist[:, ::-1].T, interpolation=interp, extent=(E_bins[0], E_bins[-1], S_bins[0], S_bins[-1]), vmin=vmin, vmax=vmax, cmap=colormap) im.cmap.set_under(under_color) im.cmap.set_over(over_color) if cbar_ax is None: gcf().colorbar(im) else: cbar_ax.colorbar(im) ax.set_xlim(-0.2, 1.2) ax.set_ylim(-0.2, 1.2) ax.set_xlabel('E') ax.set_ylabel('S') ax.grid(color=grid_color) if gui_sel: # the selection object must be saved (otherwise will be destroyed) hist2d_alex.gui_sel = gs.rectSelection(gcf(), gca()) def hexbin_alex(d, i=0, vmin=1, vmax=None, gridsize=80, cmap='Spectral_r', E_name='E', S_name='S', **hexbin_kwargs): """Plot an hexbin 2D histogram for E-S. """ if d.num_bursts[i] < 1: return hexbin_kwargs_ = dict(edgecolor='none', linewidth=0.2, gridsize=gridsize, cmap=cmap, extent=(-0.2, 1.2, -0.2, 1.2), mincnt=1) if hexbin_kwargs is not None: hexbin_kwargs_.update(_normalize_kwargs(hexbin_kwargs)) poly = plt.hexbin(d[E_name][i], d[S_name][i], **hexbin_kwargs_) poly.set_clim(vmin, vmax) plt.xlabel('E') plt.ylabel('S') def plot_ES_selection(ax, E1, E2, S1, S2, rect=True, **kwargs): """Plot an overlay ROI on top of an E-S plot (i.e. ALEX histogram). This function plots a rectangle and inscribed ellipsis with x-axis limits (E1, E2) and y-axis limits (S1, S2). Note that, a dict with keys (E1, E2, S1, S2, rect) can be also passed to :func:`fretbursts.select_bursts.ES` to apply a selection. Parameters: ax (matplotlib axis): the axis where the rectangle is plotted. Typically you pass the axis of a previous E-S scatter plot or histogram. E1, E2, S1, S2 (floats): limits for E and S (X and Y axis respectively) used to plot the rectangle. rect (bool): if True, the rectangle is highlighted and the ellipsis is grey. The color are swapped otherwise. **kwargs: other keywords passed to both matplotlib's `Rectangle` and `Ellipse`. See also: For selecting bursts according to (`E1`, `E2`, `S1`, `S2`, `rect`) see: - :func:`fretbursts.select_bursts.ES` """ if rect: rect_color, ellips_color = blue, 'gray' else: rect_color, ellips_color = 'gray', blue patch_style = dict(fill=False, lw=1.5, alpha=0.5) patch_style.update(**kwargs) rect = Rectangle(xy=(E1, S1), height=(S2 - S1), width=(E2 - E1), color=rect_color, **patch_style) ellips = Ellipse(xy=(0.5*(E1 + E2), 0.5*(S1 + S2)), height=(S2 - S1), width=(E2 - E1), color=ellips_color, **patch_style) ax.add_patch(rect) ax.add_patch(ellips) return rect, ellips def get_ES_range(): """Get the range of ES histogram selected via GUI. Prints E1, E2, S1, S2 and return a dict containig these values. """ sel = None if hasattr(hist2d_alex.gui_sel, 'selection'): sel = hist2d_alex.gui_sel.selection print('E1={E1:.3}, E2={E2:.3}, S1={S1:.3}, S2={S2:.3}'.format(**sel)) return sel def hist_interphoton_single(d, i=0, binwidth=1e-4, tmax=None, bins=None, ph_sel=Ph_sel('all'), period=None, yscale='log', xscale='linear', xunit='ms', plot_style=None): """Plot histogram of interphoton delays for a single photon streams. Arguments: d (Data object): the input data. i (int): the channel for which the plot must be done. Default is 0. For single-spot data the only valid value is 0. binwidth (float): histogram bin width in seconds. tmax (float or None): max timestamp delay in the histogram (seconds). If None (default), uses the the max timestamp delay in the stream. If not None, the plotted histogram may be further trimmed to the smallest delay with counts > 0 if this delay happens to be smaller than `tmax`. bins (array or None): specifies the bin edged (in seconds). When `bins` is not None then the arguments `binwidth` and `tmax` are ignored. When `bins` is None, the bin edges are computed from the `binwidth` and `tmax` arguments. ph_sel (Ph_sel object): photon stream for which plotting the histogram period (int): the background period to use for plotting the histogram. The background period is a time-slice of the measurement from which timestamps are taken. If `period` is None (default) the time-windows is the full measurement. yscale (string): scale for the y-axis. Valid values include 'log' and 'linear'. Default 'log'. xscale (string): scale for the x-axis. Valid values include 'log' and 'linear'. Default 'linear'. xunit (string): unit used for the x-axis. Valid values are 's', 'ms', 'us', 'ns'. Default 'ms'. plot_style (dict): keyword arguments to be passed to matplotlib's `plot` function. Used to customize the plot style. """ unit_dict = {'s': 1, 'ms': 1e3, 'us': 1e6, 'ns': 1e9} assert xunit in unit_dict scalex = unit_dict[xunit] # Compute interphoton delays if period is None: ph_times = d.get_ph_times(ich=i, ph_sel=ph_sel) else: ph_times = d.get_ph_times_period(ich=i, period=period, ph_sel=ph_sel) delta_ph_t = np.diff(ph_times) * d.clk_p if tmax is None: tmax = delta_ph_t.max() # Compute bin edges if not passed in if bins is None: # Shift by half clk_p to avoid "beatings" in the distribution # due to floating point inaccuracies. bins = np.arange(0, tmax + binwidth, binwidth) - 0.5 * d.clk_p else: warnings.warn('Using `bins` and ignoring `tmax` and `binwidth`.') t_ax = bins[:-1] + 0.5 * binwidth # Compute interphoton histogram counts, _ = np.histogram(delta_ph_t, bins=bins) # Max index with counts > 0 n_trim = np.trim_zeros(counts).size + 1 # Plot histograms plot_style_ = dict(marker='o', markersize=5, linestyle='none', alpha=0.6) if ph_sel in _ph_sel_color_dict: plot_style_['color'] = _ph_sel_color_dict[ph_sel] plot_style_['label'] = _ph_sel_label_dict[ph_sel] plot_style_.update(_normalize_kwargs(plot_style, kind='line2d')) plot(t_ax[:n_trim] * scalex, counts[:n_trim], **plot_style_) if yscale == 'log': gca().set_yscale(yscale) plt.ylim(1) _plot_status['hist_interphoton_single'] = {'autoscale': False} if xscale == 'log': gca().set_xscale(yscale) plt.xlim(0.5 * binwidth) _plot_status['hist_interphoton_single'] = {'autoscale': False} plt.xlabel('Inter-photon delays (%s)' % xunit.replace('us', 'μs')) plt.ylabel('# Delays') # Return interal variables so that other functions can extend the plot return dict(counts=counts, n_trim=n_trim, plot_style_=plot_style_, t_ax=t_ax, scalex=scalex) def hist_interphoton(d, i=0, binwidth=1e-4, tmax=None, bins=None, period=None, yscale='log', xscale='linear', xunit='ms', plot_style=None, show_da=False, legend=True): """Plot histogram of photon interval for different photon streams. Arguments: d (Data object): the input data. i (int): the channel for which the plot must be done. Default is 0. For single-spot data the only valid value is 0. binwidth (float): histogram bin width in seconds. tmax (float or None): max timestamp delay in the histogram (seconds). If None (default), uses the the max timestamp delay in the stream. If not None, the plotted histogram may be further trimmed to the smallest delay with counts > 0 if this delay happens to be smaller than `tmax`. bins (array or None): specifies the bin edged (in seconds). When `bins` is not None then the arguments `binwidth` and `tmax` are ignored. When `bins` is None, the bin edges are computed from the `binwidth` and `tmax` arguments. period (int): the background period to use for plotting the histogram. The background period is a time-slice of the measurement from which timestamps are taken. If `period` is None (default) the time-windows is the full measurement. yscale (string): scale for the y-axis. Valid values include 'log' and 'linear'. Default 'log'. xscale (string): scale for the x-axis. Valid values include 'log' and 'linear'. Default 'linear'. xunit (string): unit used for the x-axis. Valid values are 's', 'ms', 'us', 'ns'. Default 'ms'. plot_style (dict): keyword arguments to be passed to matplotlib's `plot` function. Used to customize the plot style. show_da (bool): If False (default) do not plot the AexDem photon stream. Ignored when the measurement is not ALEX. legend (bool): If True (default) plot a legend. """ # Plot multiple timetraces ph_sel_list = [Ph_sel('all'), Ph_sel(Dex='Dem'), Ph_sel(Dex='Aem')] if d.alternated: ph_sel_list.append(Ph_sel(Aex='Aem')) if show_da: ph_sel_list.append(Ph_sel(Aex='Dem')) for ix, ph_sel in enumerate(ph_sel_list): if not bl.mask_empty(d.get_ph_mask(i, ph_sel=ph_sel)): hist_interphoton_single(d, i=i, binwidth=binwidth, tmax=tmax, bins=bins, period=period, ph_sel=ph_sel, yscale=yscale, xscale=xscale, xunit=xunit, plot_style=plot_style) if legend: plt.legend(loc='best', fancybox=True) if yscale == 'log' or xscale == 'log': _plot_status['hist_interphoton'] = {'autoscale': False} def hist_bg_single(d, i=0, binwidth=1e-4, tmax=0.01, bins=None, ph_sel=Ph_sel('all'), period=0, yscale='log', xscale='linear', xunit='ms', plot_style=None, show_fit=True, fit_style=None, manual_rate=None): """Plot histogram of photon interval for a single photon streams. Optionally plots the fitted background as an exponential curve. Most arguments are described in :func:`hist_interphoton_single`. In the following we document only the additional arguments. Arguments: show_fit (bool): If True shows the fitted background rate as an exponential distribution. manual_rate (float or None): When not None use this value as background rate (ignoring the value saved in Data). fit_style (dict): arguments passed to matplotlib's `plot` for for plotting the exponential curve. For a description of all the other arguments see :func:`hist_interphoton_single`. """ hist = hist_interphoton_single(d, i=i, binwidth=binwidth, tmax=tmax, bins=bins, ph_sel=ph_sel, period=period, yscale=yscale, xscale=xscale, xunit=xunit, plot_style=None) if show_fit or manual_rate is not None: # Compute the fit function if manual_rate is not None: bg_rate = manual_rate else: bg_rate = d.bg_from(ph_sel)[i][period] i_max = np.nonzero(hist['counts'] > 0)[0][-1] tau_th = hist['t_ax'][i_max] / 3 i_tau_th = np.searchsorted(hist['t_ax'], tau_th) counts_integral = hist['counts'][i_tau_th:].sum() y_fit = np.exp(- hist['t_ax'] * bg_rate) y_fit *= counts_integral / y_fit[i_tau_th:].sum() # Plot fit_style_ = dict(hist['plot_style_']) fit_style_.update(linestyle='-', marker='', label='auto') fit_style_.update(_normalize_kwargs(fit_style, kind='line2d')) if fit_style_['label'] is 'auto': plt_label = hist['plot_style_'].get('label', None) label = str(ph_sel) if plt_label is None else plt_label fit_style_['label'] = '%s, %.2f kcps' % (label, bg_rate * 1e-3) n_trim = hist['n_trim'] plot(hist['t_ax'][:n_trim] * hist['scalex'], y_fit[:n_trim], **fit_style_) def hist_bg(d, i=0, binwidth=1e-4, tmax=0.01, bins=None, period=0, yscale='log', xscale='linear', xunit='ms', plot_style=None, show_da=False, legend=True, show_fit=True, fit_style=None): """Plot histogram of photon interval for different photon streams. Optionally plots the fitted background. Most arguments are described in :func:`hist_interphoton`. In the following we document only the additional arguments. Arguments: show_fit (bool): If True shows the fitted background rate as an exponential distribution. fit_style (dict): arguments passed to matplotlib's `plot` for for plotting the exponential curve. For a description of all the other arguments see :func:`hist_interphoton`. """ # Plot multiple timetraces ph_sel_list = [Ph_sel('all'), Ph_sel(Dex='Dem'), Ph_sel(Dex='Aem')] if d.alternated: ph_sel_list.append(Ph_sel(Aex='Aem')) if show_da: ph_sel_list.append(Ph_sel(Aex='Dem')) for ix, ph_sel in enumerate(ph_sel_list): if not bl.mask_empty(d.get_ph_mask(i, ph_sel=ph_sel)): hist_bg_single(d, i=i, period=period, binwidth=binwidth, bins=bins, tmax=tmax, ph_sel=ph_sel, xunit=xunit, show_fit=show_fit, yscale=yscale, xscale=xscale, plot_style=plot_style, fit_style=fit_style) if legend: plt.legend(loc='best', fancybox=True) if yscale == 'log' or xscale == 'log': _plot_status['hist_bg'] = {'autoscale': False} def hist_ph_delays( d, i=0, time_min_s=0, time_max_s=30, bin_width_us=10, mask=None, yscale='log', hfit_bin_ms=1, efit_tail_min_us=1000, **kwargs): """Histog. of ph delays and comparison with 3 BG fitting functions. """ ph = d.ph_times_m[i].copy() if mask is not None: ph = ph[mask[i]] ph = ph[(ph < time_max_s/d.clk_p)*(ph > time_min_s/d.clk_p)] dph = np.diff(ph)*d.clk_p H = hist(dph*1e6, bins=r_[0:1200:bin_width_us], histtype='step', **kwargs) gca().set_yscale('log') xlabel(u'Ph delay time (μs)'); ylabel("# Ph") efun = lambda t, r: np.exp(-r*t)*r re = bg.exp_fit(ph, tail_min_us=efit_tail_min_us) rg = bg.exp_hist_fit(ph, tail_min_us=efit_tail_min_us, binw=hfit_bin_ms*1e3) rc = bg.exp_cdf_fit(ph, tail_min_us=efit_tail_min_us) t = r_[0:1200]*1e-6 F = 1 if 'normed' in kwargs else H[0].sum()*(bin_width_us) plot(t*1e6, 0.65*F*efun(t, rc)*1e-6, lw=3, alpha=0.5, color=purple, label="%d cps - Exp CDF (tail_min_p=%.2f)" % (rc, efit_tail_min_us)) plot(t*1e6, 0.65*F*efun(t, re)*1e-6, lw=3, alpha=0.5, color=red, label="%d cps - Exp ML (tail_min_p=%.2f)" % (re, efit_tail_min_us)) plot(t*1e6, 0.68*F*efun(t, rg)*1e-6, lw=3, alpha=0.5, color=green, label=u"%d cps - Hist (bin_ms=%d) [Δ=%d%%]" % (hfit_bin_ms, rg, 100*(rg-re)/re)) plt.legend(loc='best', fancybox=True) def hist_mdelays(d, i=0, m=10, bins_s=(0, 10, 0.02), period=0, hold=False, bg_ppf=0.01, ph_sel=Ph_sel('all'), spline=True, s=1., bg_fit=True, bg_F=0.8): """Histogram of m-photons delays (all-ph vs in-burst ph). """ ax = gca() if not hold: #ax.clear() for _ind in range(len(ax.lines)): ax.lines.pop() results = bext.calc_mdelays_hist( d=d, ich=i, m=m, period=period, bins_s=bins_s, ph_sel=ph_sel, bursts=True, bg_fit=bg_fit, bg_F=bg_F) bin_x, histog_y = results[:2] bg_dist = results[2] rate_ch_kcps = 1./bg_dist.kwds['scale'] # extract the rate if bg_fit: a, rate_kcps = results[3:5] mdelays_hist_y = histog_y[0] mdelays_b_hist_y = histog_y[1] # Center of mass (COM) binw = bins_s[2] com = np.sum(bin_x*mdelays_hist_y)*binw com_b = np.sum(bin_x*mdelays_b_hist_y)*binw #print(com, com_b) # Compute a spline smoothing of the PDF mdelays_spline = UnivariateSpline(bin_x, mdelays_hist_y, s=s*com) mdelays_b_spline = UnivariateSpline(bin_x, mdelays_b_hist_y, s=s*com_b) mdelays_spline_y = mdelays_spline(bin_x) mdelays_b_spline_y = mdelays_b_spline(bin_x) if spline: mdelays_pdf_y = mdelays_spline_y mdelays_b_pdf_y = mdelays_b_spline_y else: mdelays_pdf_y = mdelays_hist_y mdelays_b_pdf_y = mdelays_b_hist_y # Thresholds and integrals max_delay_th_P = bg_dist.ppf(bg_ppf) max_delay_th_F = m/rate_ch_kcps/d.F burst_domain = bin_x < max_delay_th_F burst_integral = np.trapz(x=bin_x[burst_domain], y=mdelays_hist_y[burst_domain]) title("I = %.1f %%" % (burst_integral*100), fontsize='small') #text(0.8,0.8,"I = %.1f %%" % (integr*100), transform = gca().transAxes) ## MDelays plot plot(bin_x, mdelays_pdf_y, lw=2, color=blue, alpha=0.5, label="Delays dist.") plot(bin_x, mdelays_b_pdf_y, lw=2, color=red, alpha=0.5, label="Delays dist. (in burst)") plt.axvline(max_delay_th_P, color='k', label="BG ML dist. @ %.1f%%" % (bg_ppf*100)) plt.axvline(max_delay_th_F, color=purple, label="BS threshold (F=%d)" % d.F) ## Bg distribution plots bg_dist_y = bg_dist.pdf(bin_x) ibin_x_bg_mean = np.abs(bin_x - bg_dist.mean()).argmin() bg_dist_y *= mdelays_pdf_y[ibin_x_bg_mean]/bg_dist_y[ibin_x_bg_mean] plot(bin_x, bg_dist_y, '--k', alpha=1., label='BG ML dist.') plt.axvline(bg_dist.mean(), color='k', ls='--', label="BG mean") if bg_fit: bg_y = a*erlang.pdf(bin_x, a=m, scale=1./rate_kcps) plot(bin_x, bg_y, '--k', alpha=1.) plt.legend(ncol=2, frameon=False) xlabel("Time (ms)") def hist_mrates(d, i=0, m=10, bins=(0, 4000, 100), yscale='log', pdf=False, dense=True, plot_style=None): """Histogram of m-photons rates. See also :func:`hist_mdelays`. """ ph = d.get_ph_times(ich=i) if dense: ph_mrates = 1.*m/((ph[m-1:]-ph[:ph.size-m+1])*d.clk_p*1e3) else: ph_mrates = 1.*m/(np.diff(ph[::m])*d.clk_p*1e3) hist = HistData(*np.histogram(ph_mrates, bins=_bins_array(bins))) ydata = hist.pdf if pdf else hist.counts plot_style_ = dict(marker='o') plot_style_.update(_normalize_kwargs(plot_style, kind='line2d')) plot(hist.bincenters, ydata, **plot_style_) gca().set_yscale(yscale) xlabel("Rates (kcps)") ## Bursts stats def hist_sbr(d, i=0, bins=(0, 30, 1), pdf=True, weights=None, color=None, plot_style=None): """Histogram of per-burst Signal-to-Background Ratio (SBR). """ weights = weights[i] if weights is not None else None if 'sbr' not in d: d.calc_sbr() _hist_burst_taildist(d.sbr[i], bins, pdf, weights=weights, color=color, plot_style=plot_style) plt.xlabel('SBR') def hist_burst_phrate(d, i=0, bins=(0, 1000, 20), pdf=True, weights=None, color=None, plot_style=None, vline=None): """Histogram of max photon rate in each burst. """ weights = weights[i] if weights is not None else None if hasattr(d, '__array__'): max_rate = d else: if 'max_rate' not in d: d.calc_max_rate(m=10) max_rate = d.max_rate _hist_burst_taildist(max_rate[i] * 1e-3, bins, pdf, weights=weights, color=color, plot_style=plot_style, vline=vline) plt.xlabel('Peak rate (kcps)') def hist_burst_delays(d, i=0, bins=(0, 10, 0.2), pdf=False, weights=None, color=None, plot_style=None): """Histogram of waiting times between bursts. """ weights = weights[i] if weights is not None else None bdelays = np.diff(d.mburst[i].start*d.clk_p) _hist_burst_taildist(bdelays, bins, pdf, weights=weights, color=color, plot_style=plot_style) plt.xlabel('Delays between bursts (s)') ## Burst internal "symmetry" def hist_asymmetry(d, i=0, bin_max=2, binwidth=0.1, stat_func=np.median): burst_asym = bext.asymmetry(d, ich=i, func=stat_func) bins_pos = np.arange(0, bin_max+binwidth, binwidth) bins = np.hstack([-bins_pos[1:][::-1], bins_pos]) izero = (bins.size - 1)/2. assert izero == np.where(np.abs(bins) < 1e-8)[0] counts, _ = np.histogram(burst_asym, bins=bins) asym_counts_neg = counts[:izero] - counts[izero:][::-1] asym_counts_pos = counts[izero:] - counts[:izero][::-1] asym_counts = np.hstack([asym_counts_neg, asym_counts_pos]) plt.bar(bins[:-1], width=binwidth, height=counts, fc=blue, alpha=0.5) plt.bar(bins[:-1], width=binwidth, height=asym_counts, fc=red, alpha=0.5) plt.grid(True) plt.xlabel('Time (ms)') plt.ylabel('# Bursts') plt.legend(['{func}$(t_D)$ - {func}$(t_A)$'.format(func=stat_func.__name__), 'positive half - negative half'], frameon=False, loc='best') skew_abs = asym_counts_neg.sum() skew_rel = 100.*skew_abs/counts.sum() print('Skew: %d bursts, (%.1f %%)' % (skew_abs, skew_rel)) ## # Scatter plots # def scatter_width_size(d, i=0): """Scatterplot of burst width versus size.""" b = d.mburst[i] plot(b.width*d.clk_p*1e3, d.nt[i], 'o', mew=0, ms=3, alpha=0.7, color='blue') t_ms = arange(0, 50) plot(t_ms, ((d.m)/(d.T[i]))*t_ms*1e-3, '--', lw=2, color='k', label='Slope = m/T = min. rate = %1.0f cps' % (d.m/d.T[i])) plot(t_ms, d.bg_mean[Ph_sel('all')][i]*t_ms*1e-3, '--', lw=2, color=red, label='Noise rate: BG*t') xlabel('Burst width (ms)'); ylabel('Burst size (# ph.)') plt.xlim(0, 10); plt.ylim(0, 300) legend(frameon=False) def scatter_rate_da(d, i=0): """Scatter of nd rate vs na rate (rates for each burst).""" b = d.mburst[i] Rate = lambda nX: nX[i]/b.width/d.clk_p*1e-3 plot(Rate(d.nd), Rate(d.na), 'o', mew=0, ms=3, alpha=0.1, color='blue') xlabel('D burst rate (kcps)'); ylabel('A burst rate (kcps)') plt.xlim(-20, 100); plt.ylim(-20, 100) legend(frameon=False) def scatter_fret_size(d, i=0, which='all', gamma=1, add_naa=False, plot_style=None): """Scatterplot of FRET efficiency versus burst size. """ if which == 'all': size = d.burst_sizes_ich(ich=i, gamma=gamma, add_naa=add_naa) else: assert which in d size = d[which][i] plot_style_ = dict(linestyle='', alpha=0.1, color=blue, marker='o', markeredgewidth=0, markersize=3) plot_style_.update(_normalize_kwargs(plot_style, kind='line2d')) plot(d.E[i], size, **plot_style_) xlabel("FRET Efficiency (E)") ylabel("Corrected Burst size (#ph)") def scatter_fret_nd_na(d, i=0, show_fit=False, no_text=False, gamma=1., **kwargs): """Scatterplot of FRET versus gamma-corrected burst size.""" default_kwargs = dict(mew=0, ms=3, alpha=0.3, color=blue) default_kwargs.update(**kwargs) plot(d.E[i], gamma*d.nd[i]+d.na[i], 'o', **default_kwargs) xlabel("FRET Efficiency (E)") ylabel("Burst size (#ph)") if show_fit: _fitted_E_plot(d, i, F=1., no_E=no_text, ax=gca()) if i == 0 and not no_text: plt.figtext(0.4, 0.01, _get_fit_E_text(d), fontsize=14) def scatter_fret_width(d, i=0): """Scatterplot of FRET versus burst width.""" b = d.mburst[i] plot(d.E[i], (b[:, 1]*d.clk_p)*1e3, 'o', mew=0, ms=3, alpha=0.1, color="blue") xlabel("FRET Efficiency (E)") ylabel("Burst width (ms)") def scatter_da(d, i=0, alpha=0.3): """Scatterplot of donor vs acceptor photons (nd, vs na) in each burst.""" plot(d.nd[i], d.na[i], 'o', mew=0, ms=3, alpha=alpha, color='blue') xlabel('# donor ph.'); ylabel('# acceptor ph.') plt.xlim(-5, 200); plt.ylim(-5, 120) def scatter_naa_nt(d, i=0, alpha=0.5): """Scatterplot of nt versus naa.""" plot(d.nt[i], d.naa[i], 'o', mew=0, ms=3, alpha=alpha, color='blue') plot(arange(200), color='k', lw=2) xlabel('Total burst size (nd+na+naa)'); ylabel('Accept em-ex BS (naa)') plt.xlim(-5, 200); plt.ylim(-5, 120) def scatter_alex(d, i=0, **kwargs): """Scatterplot of E vs S. Keyword arguments passed to `plot`.""" plot_style = dict(mew=1, ms=4, mec='black', color='purple', alpha=0.1) plot_style = _normalize_kwargs(plot_style, 'line2d') plot_style.update(_normalize_kwargs(kwargs)) plot(d.E[i], d.S[i], 'o', **plot_style) xlabel("E"); ylabel('S') plt.xlim(-0.2, 1.2); plt.ylim(-0.2, 1.2) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # High-level plot wrappers # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def _iter_plot(d, func, kwargs, iter_ch, nrows, ncols, figsize, AX, sharex, sharey, suptitle, grid, scale, skip_ch=None, title='out', title_ch=True, title_bg=True, title_nbursts=True, title_kws=None, top=0.95, bottom=None, hspace=0.15, wspace=None, left=0.08, right=0.96, xrotation=0): if AX is None: fig, AX = plt.subplots(nrows, ncols, figsize=figsize, sharex=sharex, sharey=sharey, squeeze=False) old_ax = False else: fig = AX[0, 0].figure old_ax = True if skip_ch is None: skip_ch = [] for i, ich in enumerate(iter_ch): ax = AX.ravel()[i] ax.grid(grid) plt.setp(ax.get_xticklabels(), rotation=xrotation) if ich in skip_ch: continue b = d.mburst[ich] if 'mburst' in d else None if suptitle and i == 0 and hasattr(d, 'status') and callable(d.status): fig.suptitle(d.status()) if title: # no title if None of False if title_kws is None: title_kws = {} s = '' if title_ch: s += '[%d]' % ich if title_bg and 'bg_mean' in d: s += (' BG=%.1fk' % (d.bg_mean[Ph_sel('all')][ich] * 1e-3)) if title_nbursts and b is not None: s += (' #B=%d' % b.num_bursts) if title is True or 'out' in title.lower(): ax.set_title(s, **title_kws) else: titley, va = 0.95, 'top' if 'bottom' in str(title): titley, va = 1 - titley, 'baseline' titlex, ha = 0.95, 'right' if 'left' in str(title): titlex, ha = 1 - titlex, 'left' ax.text(titlex, titley, s, transform=ax.transAxes, ha=ha, va=va, **title_kws) plt.sca(ax) gui_status['first_plot_in_figure'] = (i == 0) func(d, ich, **kwargs) if ax.legend_ is not None: ax.legend_.remove() [a.set_xlabel('') for a in AX[:-1, :].ravel()] [a.set_ylabel('') for a in AX[:, 1:].ravel()] if sharex: plt.setp([a.get_xticklabels() for a in AX[:-1, :].ravel()], visible=False) [a.set_xlabel('') for a in AX[:-1, :].ravel()] if sharey: if AX.shape[1] > 1: plt.setp([a.get_yticklabels() for a in AX[:, 1]], visible=False) if wspace is None: wspace = 0.08 func_allows_autoscale = True if func.__name__ in _plot_status: func_allows_autoscale = _plot_status[func.__name__]['autoscale'] if scale and func_allows_autoscale: ax.autoscale(enable=True, axis='y') if not old_ax: fig.subplots_adjust(hspace=hspace, wspace=wspace, left=left, right=right, top=top, bottom=bottom) return AX def dplot_48ch(d, func, sharex=True, sharey=True, layout='horiz', grid=True, figsize=None, AX=None, scale=True, skip_ch=None, suptitle=True, title=True, title_ch=True, title_bg=True, title_nbursts=True, title_kws=None, xrotation=0, top=0.93, bottom=None, hspace=0.18, wspace=None, left=0.08, right=0.96, dec=1, **kwargs): """Plot wrapper for 48-spot measurements. Use `dplot` instead.""" msg = "Wrong layout '%s'. Valid values: 'horiz', 'vert', '8x6'." assert (layout.startswith('vert') or layout.startswith('horiz') or layout == '8x6'), (msg % layout) if dec > 1: assert dec == 2 or dec == 4 assert layout.startswith('horiz') global gui_status ch_map = np.arange(48).reshape(4, 12)[::dec, ::dec] iter_ch = ch_map.ravel() if layout == '8x6': nrows, ncols = 6, 8 if figsize is None: figsize = (18, 6) else: nrows, ncols = 4 // dec, 12 // dec if layout.startswith('vert'): nrows, ncols = ncols, nrows iter_ch = ch_map.T.ravel() if figsize is None: figsize = (1.5 * ncols + 2, 1.5 * nrows + 1) if layout.startswith('vert'): figsize = figsize[1], figsize[0] return _iter_plot(d, func, kwargs, iter_ch, nrows, ncols, figsize, AX, sharex, sharey, suptitle, grid, scale, skip_ch=skip_ch, top=top, bottom=bottom, hspace=hspace, wspace=wspace, left=left, right=right, xrotation=xrotation, title=title, title_ch=title_ch, title_bg=title_bg, title_nbursts=title_nbursts, title_kws=title_kws) def dplot_16ch(d, func, sharex=True, sharey=True, ncols=8, pgrid=True, figsize=None, AX=None, suptitle=True, scale=True, skip_ch=None, top=0.93, bottom=None, hspace=0.15, wspace=None, left=0.08, right=0.96, **kwargs): """Plot wrapper for 16-spot measurements. Use `dplot` instead.""" assert (ncols <= 16), '`ncols` needs to be <= 16.' global gui_status iter_ch = range(16) nrows = int(np.ceil(d.nch / ncols)) if figsize is None: subplotsize = (3, 3) figsize = (subplotsize[0] * ncols, subplotsize[1] * nrows) return _iter_plot(d, func, kwargs, iter_ch, nrows, ncols, figsize, AX, sharex, sharey, suptitle, grid, scale, skip_ch=skip_ch, top=top, bottom=bottom, hspace=hspace, wspace=wspace, left=left, right=right) def dplot_8ch(d, func, sharex=True, sharey=True, pgrid=True, figsize=(12, 9), nosuptitle=False, AX=None, scale=True, **kwargs): """Plot wrapper for 8-spot measurements. Use `dplot` instead.""" global gui_status if AX is None: fig, AX = plt.subplots(4, 2, figsize=figsize, sharex=sharex, sharey=sharey) fig.subplots_adjust(left=0.08, right=0.96, top=0.93, bottom=0.07, wspace=0.05) old_ax = False else: fig = AX[0, 0].figure old_ax = True for i in range(d.nch): b = d.mburst[i] if 'mburst' in d else None if (func not in [timetrace, ratetrace, timetrace_single, ratetrace_single, hist_bg_single, hist_bg, timetrace_bg]) and np.size(b) == 0: continue ax = AX.ravel()[i] if i == 0 and not nosuptitle: fig.suptitle(d.status()) s = u'[%d]' % (i+1) if 'bg_mean' in d: s += (' BG=%.1fk' % (d.bg_mean[Ph_sel('all')][i]*1e-3)) if 'T' in d: s += (u', T=%dμs' % (d.T[i]*1e6)) if b is not None: s += (', #bu=%d' % b.num_bursts) ax.set_title(s, fontsize=12) ax.grid(pgrid) plt.sca(ax) gui_status['first_plot_in_figure'] = (i == 0) func(d, i, **kwargs) if i % 2 == 1: ax.yaxis.tick_right() [a.set_xlabel('') for a in AX[:-1, :].ravel()] [a.set_ylabel('') for a in AX[:, 1:].ravel()] if sharex: plt.setp([a.get_xticklabels() for a in AX[:-1, :].ravel()], visible=False) [a.set_xlabel('') for a in AX[:-1, :].ravel()] if not old_ax: fig.subplots_adjust(hspace=0.15) if sharey: plt.setp([a.get_yticklabels() for a in AX[:, 1]], visible=False) fig.subplots_adjust(wspace=0.08) func_allows_autoscale = True if func.__name__ in _plot_status: func_allows_autoscale = _plot_status[func.__name__]['autoscale'] if scale and func_allows_autoscale: ax.autoscale(enable=True, axis='y') return AX def dplot_1ch(d, func, pgrid=True, ax=None, figsize=(9, 4.5), fignum=None, nosuptitle=False, **kwargs): """Plot wrapper for single-spot measurements. Use `dplot` instead.""" global gui_status if ax is None: fig = plt.figure(num=fignum, figsize=figsize) ax = fig.add_subplot(111) else: fig = ax.figure s = d.name if 'bg_mean' in d: s += (' BG=%.1fk' % (d.bg_mean[Ph_sel('all')][0] * 1e-3)) if 'T' in d: s += (u', T=%dμs' % (d.T[0] * 1e6)) if 'mburst' in d: s += (', #bu=%d' % d.num_bursts[0]) if not nosuptitle: ax.set_title(s, fontsize=12) ax.grid(pgrid) plt.sca(ax) gui_status['first_plot_in_figure'] = True func(d, **kwargs) return ax def dplot(d, func, **kwargs): """Main plot wrapper for single and multi-spot measurements.""" if hasattr(d, '__array__'): nch = d.shape[1] else: nch = d.nch if nch == 1: return dplot_1ch(d=d, func=func, **kwargs) elif nch == 8: return dplot_8ch(d=d, func=func, **kwargs) elif nch == 16: return dplot_16ch(d=d, func=func, **kwargs) elif nch == 48: return dplot_48ch(d=d, func=func, **kwargs) ## # ALEX join-plot using seaborn # def _alex_plot_style(g, colorbar=True): """Set plot style and colorbar for an ALEX joint plot. """ g.set_axis_labels(xlabel="E", ylabel="S") g.ax_marg_x.grid(True) g.ax_marg_y.grid(True) g.ax_marg_x.set_xlabel('') g.ax_marg_y.set_ylabel('') plt.setp(g.ax_marg_y.get_xticklabels(), visible=True) plt.setp(g.ax_marg_x.get_yticklabels(), visible=True) g.ax_marg_x.locator_params(axis='y', tight=True, nbins=3) g.ax_marg_y.locator_params(axis='x', tight=True, nbins=3) if colorbar: pos = g.ax_joint.get_position().get_points() X, Y = pos[:, 0], pos[:, 1] cax = plt.axes([1., Y[0], (X[1] - X[0]) * 0.045, Y[1] - Y[0]]) plt.colorbar(cax=cax) def _hist_bursts_marg(arr, dx, i, E_name='E', S_name='S', **kwargs): """Wrapper to call hist_burst_data() from seaborn plot_marginals(). """ vertical = kwargs.get('vertical', False) data_name = S_name if vertical else E_name hist_burst_data(dx, i=i, data_name=data_name, **kwargs) def _alex_hexbin_vmax(patches, vmax_fret=True, Smax=0.8): """Return the max counts in the E-S hexbin histogram in `patches`. When `vmax_fret` is True, returns the max count for S < Smax. Otherwise returns the max count in all the histogram. """ counts = patches.get_array() if vmax_fret: offset = patches.get_offsets() xoffset, yoffset = offset[:, 0], offset[:, 1] mask = yoffset < Smax vmax = counts[mask].max() else: vmax = counts.max() return vmax def alex_jointplot(d, i=0, gridsize=50, cmap='Spectral_r', kind='hex', vmax_fret=True, vmin=1, vmax=None, joint_kws=None, marginal_kws=None, marginal_color=10, rightside_text=False, E_name='E', S_name='S'): """Plot an ALEX join plot: an E-S 2D histograms with marginal E and S. This function plots a jointplot: an inner 2D E-S distribution plot and the marginal distributions for E and S separately. By default, the inner plot is an hexbin plot, i.e. the bin shape is hexagonal. Hexagonal bins reduce artifacts due to discretization. The marginal plots are histograms with a KDE overlay. Arguments: d (Data object): the variable containing the bursts to plot i (int): the channel number. Default 0. gridsize (int): the grid size for the 2D histogram (hexbin) C (1D array or None): array of weights, it must have size equal to the number of bursts in channel `i` (d.num_bursts[i]). Passed to matplotlib hexbin(). cmap (string): name of the colormap for the 2D histogram. In addition to matplotlib colormaps, FRETbursts defines these custom colormaps: 'alex_light', 'alex_dark' and 'alex_lv'. Default 'alex_light'. kind (string): kind of plot for the 2-D distribution. Valid values: 'hex' for hexbin plots, 'kde' for kernel density estimation, 'scatter' for scatter plot. vmax_fret (bool): if True, the colormap max value is equal to the max bin counts in the FRET region (S < 0.8). If False the colormap max is equal to the max bin counts. vmin (int): min value in the histogram mapped by the colormap. Default 0, the colormap lowest color represents bins with 0 counts. vmax (int or None): max value in the histogram mapped by the colormap. When None, vmax is computed automatically from the data and dependes on the argument `vmax_fret`. Default `None`. joint_kws (dict): keyword arguments passed to the function with plots the inner 2-D distribution (i.e matplotlib scatter or hexbin or seaborn kdeplot). and hence to matplolib hexbin to customize the plot style. marginal_kws (dict) : keyword arguments passed to the function :func:`hist_burst_data` used to plot the maginal distributions. marginal_color (int or color): color to be used for the marginal histograms. It can be an integer or any color accepted by matplotlib. If integer, it represents a color in the colormap `cmap` from 0 (lowest cmap color) to 99 (highest cmap color). rightside_text (bool): when True, print the measurement name on the right side of the figure. When False (default) no additional text is printed. E_name, S_name (string): name of the `Data` attribute to be used for E and S. The default is 'E' and 'S' respectively. These arguments are used when adding your own cutom E or S attributes to Data using `Data.add`. In this case, you can specify the name of these custom attributes so that they can be plotted as an E-S histogram. Returns: A ``seaborn.JointGrid`` object that can be used for tweaking the plot. .. seealso:: The `Seaborn documentation <https://seaborn.pydata.org/>`__ has more info on plot customization: * https://seaborn.pydata.org/generated/seaborn.JointGrid.html """ g = sns.JointGrid(x=d[E_name][i], y=d[S_name][i], ratio=3, space=0.2, xlim=(-0.2, 1.2), ylim=(-0.2, 1.2)) if isinstance(marginal_color, int): histcolor = sns.color_palette(cmap, 100)[marginal_color] else: histcolor = marginal_color marginal_kws_ = dict( show_kde=True, bandwidth=0.03, binwidth=0.03, hist_bar_style={'facecolor': histcolor, 'edgecolor': 'k', 'linewidth': 0.15, 'alpha': 1}) if marginal_kws is not None: marginal_kws_.update(_normalize_kwargs(marginal_kws)) if kind == "scatter": joint_kws_ = dict(s=40, color=histcolor, alpha=0.1, linewidths=0) if joint_kws is not None: joint_kws_.update(_normalize_kwargs(joint_kws)) jplot = g.plot_joint(plt.scatter, **joint_kws_) elif kind.startswith('hex'): joint_kws_ = dict(edgecolor='none', linewidth=0.2, gridsize=gridsize, cmap=cmap, extent=(-0.2, 1.2, -0.2, 1.2), mincnt=1) if joint_kws is not None: joint_kws_.update(_normalize_kwargs(joint_kws)) jplot = g.plot_joint(plt.hexbin, **joint_kws_) # Set the vmin and vmax values for the colormap polyc = [c for c in jplot.ax_joint.get_children() if isinstance(c, PolyCollection)][0] if vmax is None: vmax = _alex_hexbin_vmax(polyc, vmax_fret=vmax_fret) polyc.set_clim(vmin, vmax) elif kind.startswith("kde"): joint_kws_ = dict(shade=True, shade_lowest=False, n_levels=30, cmap=cmap, clip=(-0.4, 1.4), bw=0.03) if joint_kws is not None: joint_kws_.update(_normalize_kwargs(joint_kws)) jplot = g.plot_joint(sns.kdeplot, **joint_kws_) g.ax_joint.set_xlim(-0.19, 1.19) g.ax_joint.set_xlim(-0.19, 1.19) g.plot_marginals(_hist_bursts_marg, dx=d, i=i, E_name=E_name, S_name=S_name, **marginal_kws_) g.annotate(lambda x, y: x.size, stat='# Bursts', template='{stat}: {val}', frameon=False) colorbar = kind.startswith('hex') _alex_plot_style(g, colorbar=colorbar) if rightside_text: plt.text(1.15, 0.6, d.name, transform=g.fig.transFigure, fontsize=14, bbox=dict(edgecolor='r', facecolor='none', lw=1.3, alpha=0.5)) return g def _register_colormaps(): import matplotlib as mpl import seaborn as sns c = sns.color_palette('nipy_spectral', 64)[2:43] cmap = mpl.colors.LinearSegmentedColormap.from_list('alex_lv', c) cmap.set_under(alpha=0) mpl.cm.register_cmap(name='alex_lv', cmap=cmap) c = sns.color_palette('YlGnBu', 64)[16:] cmap = mpl.colors.LinearSegmentedColormap.from_list('alex', c) cmap.set_under(alpha=0) mpl.cm.register_cmap(name='alex_light', cmap=cmap) mpl.cm.register_cmap(name='YlGnBu_crop', cmap=cmap) mpl.cm.register_cmap(name='alex_dark', cmap=mpl.cm.GnBu_r) # Temporary hack to workaround issue # https://github.com/mwaskom/seaborn/issues/855 mpl.cm.alex_light = mpl.cm.get_cmap('alex_light') mpl.cm.alex_dark = mpl.cm.get_cmap('alex_dark') # Register colormaps on import if not mocking if not hasattr(sns, '_mock'): _register_colormaps()
tritemio/FRETBursts
fretbursts/burst_plot.py
Python
gpl-2.0
96,452
from lib.flowchart.nodes.generalNode import NodeWithCtrlWidget class myNode(NodeWithCtrlWidget): '''This is test docstring''' nodeName = 'myTestNode' uiTemplate = [{'name': 'HNO3', 'type': 'list', 'value': 'Closest Time'}, {'name': 'C2H5OH', 'type': 'bool', 'value': 0}, {'name': 'H20', 'type': 'str', 'value': '?/?'}] def __init__(self, name, **kwargs): super(myNode, self).__init__(name, terminals={'In': {'io': 'in'}, 'Out': {'io': 'out'}}, **kwargs) def process(self, In): print ('processing')
cdd1969/pygwa
lib/flowchart/nodes/n000_testnode/myNode.py
Python
gpl-2.0
578
#!/usr/bin/python """ gui -- The main wicd GUI module. Module containing the code for the main wicd GUI. """ # # Copyright (C) 2007-2009 Adam Blackburn # Copyright (C) 2007-2009 Dan O'Reilly # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License Version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import os import sys import time import gobject import pango import gtk from itertools import chain from dbus import DBusException from wicd import misc from wicd import wpath from wicd import dbusmanager from wicd.misc import noneToString import prefs from prefs import PreferencesDialog import netentry from netentry import WiredNetworkEntry, WirelessNetworkEntry from guiutil import error, LabelEntry from wicd.translations import language if __name__ == '__main__': wpath.chdir(__file__) proxy_obj = daemon = wireless = wired = bus = None DBUS_AVAIL = False def setup_dbus(force=True): global bus, daemon, wireless, wired, DBUS_AVAIL try: dbusmanager.connect_to_dbus() except DBusException: if force: print "Can't connect to the daemon, trying to start it automatically..." if not misc.PromptToStartDaemon(): print "Failed to find a graphical sudo program, cannot continue." return False try: dbusmanager.connect_to_dbus() except DBusException: error(None, "Could not connect to wicd's D-Bus interface. " + "Check the wicd log for error messages.") return False else: return False prefs.setup_dbus() netentry.setup_dbus() bus = dbusmanager.get_bus() dbus_ifaces = dbusmanager.get_dbus_ifaces() daemon = dbus_ifaces['daemon'] wireless = dbus_ifaces['wireless'] wired = dbus_ifaces['wired'] DBUS_AVAIL = True return True def handle_no_dbus(from_tray=False): global DBUS_AVAIL DBUS_AVAIL = False if from_tray: return False print "Wicd daemon is shutting down!" error(None, language['lost_dbus'], block=False) return False class WiredProfileChooser: """ Class for displaying the wired profile chooser. """ def __init__(self): """ Initializes and runs the wired profile chooser. """ # Import and init WiredNetworkEntry to steal some of the # functions and widgets it uses. wired_net_entry = WiredNetworkEntry() dialog = gtk.Dialog(title = language['wired_network_found'], flags = gtk.DIALOG_MODAL, buttons = (gtk.STOCK_CONNECT, 1, gtk.STOCK_CANCEL, 2)) dialog.set_has_separator(False) dialog.set_size_request(400, 150) instruct_label = gtk.Label(language['choose_wired_profile'] + ':\n') stoppopcheckbox = gtk.CheckButton(language['stop_showing_chooser']) wired_net_entry.is_full_gui = False instruct_label.set_alignment(0, 0) stoppopcheckbox.set_active(False) # Remove widgets that were added to the normal WiredNetworkEntry # so that they can be added to the pop-up wizard. wired_net_entry.vbox_top.remove(wired_net_entry.hbox_temp) wired_net_entry.vbox_top.remove(wired_net_entry.profile_help) dialog.vbox.pack_start(instruct_label, fill=False, expand=False) dialog.vbox.pack_start(wired_net_entry.profile_help, False, False) dialog.vbox.pack_start(wired_net_entry.hbox_temp, False, False) dialog.vbox.pack_start(stoppopcheckbox, False, False) dialog.show_all() wired_profiles = wired_net_entry.combo_profile_names wired_net_entry.profile_help.hide() if wired_net_entry.profile_list != None: wired_profiles.set_active(0) print "wired profiles found" else: print "no wired profiles found" wired_net_entry.profile_help.show() response = dialog.run() if response == 1: print 'reading profile ', wired_profiles.get_active_text() wired.ReadWiredNetworkProfile(wired_profiles.get_active_text()) wired.ConnectWired() else: if stoppopcheckbox.get_active(): daemon.SetForcedDisconnect(True) dialog.destroy() class appGui(object): """ The main wicd GUI class. """ def __init__(self, standalone=False, tray=None): """ Initializes everything needed for the GUI. """ setup_dbus() self.tray = tray gladefile = os.path.join(wpath.gtk, "wicd.ui") self.wTree = gtk.Builder() self.wTree.add_from_file(gladefile) self.window = self.wTree.get_object("window1") width = int(gtk.gdk.screen_width() / 2) if width > 530: width = 530 self.window.resize(width, int(gtk.gdk.screen_height() / 1.7)) dic = { "refresh_clicked" : self.refresh_clicked, "quit_clicked" : self.exit, "rfkill_clicked" : self.switch_rfkill, "disconnect_clicked" : self.disconnect_all, "main_exit" : self.exit, "cancel_clicked" : self.cancel_connect, "hidden_clicked" : self.connect_hidden, "preferences_clicked" : self.settings_dialog, "about_clicked" : self.about_dialog, "create_adhoc_clicked" : self.create_adhoc_network, } self.wTree.connect_signals(dic) # Set some strings in the GUI - they may be translated label_instruct = self.wTree.get_object("label_instructions") label_instruct.set_label(language['select_a_network']) probar = self.wTree.get_object("progressbar") probar.set_text(language['connecting']) self.rfkill_button = self.wTree.get_object("rfkill_button") self.all_network_list = self.wTree.get_object("network_list_vbox") self.all_network_list.show_all() self.wired_network_box = gtk.VBox(False, 0) self.wired_network_box.show_all() self.network_list = gtk.VBox(False, 0) self.all_network_list.pack_start(self.wired_network_box, False, False) self.all_network_list.pack_start(self.network_list, True, True) self.network_list.show_all() self.status_area = self.wTree.get_object("connecting_hbox") self.status_bar = self.wTree.get_object("statusbar") menu = self.wTree.get_object("menu1") self.status_area.hide_all() if os.path.exists(os.path.join(wpath.images, "wicd.png")): self.window.set_icon_from_file(os.path.join(wpath.images, "wicd.png")) self.statusID = None self.first_dialog_load = True self.is_visible = True self.pulse_active = False self.pref = None self.standalone = standalone self.wpadrivercombo = None self.connecting = False self.refreshing = False self.prev_state = None self.update_cb = None self.network_list.set_sensitive(False) label = gtk.Label("%s..." % language['scanning']) self.network_list.pack_start(label) label.show() self.wait_for_events(0.2) self.window.connect('delete_event', self.exit) self.window.connect('key-release-event', self.key_event) daemon.SetGUIOpen(True) bus.add_signal_receiver(self.dbus_scan_finished, 'SendEndScanSignal', 'org.wicd.daemon.wireless') bus.add_signal_receiver(self.dbus_scan_started, 'SendStartScanSignal', 'org.wicd.daemon.wireless') bus.add_signal_receiver(self.update_connect_buttons, 'StatusChanged', 'org.wicd.daemon') bus.add_signal_receiver(self.handle_connection_results, 'ConnectResultsSent', 'org.wicd.daemon') bus.add_signal_receiver(lambda: setup_dbus(force=False), "DaemonStarting", "org.wicd.daemon") bus.add_signal_receiver(self._do_statusbar_update, 'StatusChanged', 'org.wicd.daemon') if standalone: bus.add_signal_receiver(handle_no_dbus, "DaemonClosing", "org.wicd.daemon") self._do_statusbar_update(*daemon.GetConnectionStatus()) self.wait_for_events(0.1) self.update_cb = misc.timeout_add(2, self.update_statusbar) self.refresh_clicked() def handle_connection_results(self, results): if results not in ['Success', 'aborted'] and self.is_visible: error(self.window, language[results], block=False) def create_adhoc_network(self, widget=None): """ Shows a dialog that creates a new adhoc network. """ print "Starting the Ad-Hoc Network Creation Process..." dialog = gtk.Dialog(title = language['create_adhoc_network'], flags = gtk.DIALOG_MODAL, buttons=(gtk.STOCK_CANCEL, 2, gtk.STOCK_OK, 1)) dialog.set_has_separator(False) dialog.set_size_request(400, -1) self.chkbox_use_encryption = gtk.CheckButton(language['use_wep_encryption']) self.chkbox_use_encryption.set_active(False) ip_entry = LabelEntry(language['ip'] + ':') essid_entry = LabelEntry(language['essid'] + ':') channel_entry = LabelEntry(language['channel'] + ':') self.key_entry = LabelEntry(language['key'] + ':') self.key_entry.set_auto_hidden(True) self.key_entry.set_sensitive(False) chkbox_use_ics = gtk.CheckButton(language['use_ics']) self.chkbox_use_encryption.connect("toggled", self.toggle_encrypt_check) channel_entry.entry.set_text('3') essid_entry.entry.set_text('My_Adhoc_Network') ip_entry.entry.set_text('169.254.12.10') # Just a random IP vbox_ah = gtk.VBox(False, 0) self.wired_network_box = gtk.VBox(False, 0) vbox_ah.pack_start(self.chkbox_use_encryption, False, False) vbox_ah.pack_start(self.key_entry, False, False) vbox_ah.show() dialog.vbox.pack_start(essid_entry) dialog.vbox.pack_start(ip_entry) dialog.vbox.pack_start(channel_entry) dialog.vbox.pack_start(chkbox_use_ics) dialog.vbox.pack_start(vbox_ah) dialog.vbox.set_spacing(5) dialog.show_all() response = dialog.run() if response == 1: wireless.CreateAdHocNetwork(essid_entry.entry.get_text(), channel_entry.entry.get_text(), ip_entry.entry.get_text().strip(), "WEP", self.key_entry.entry.get_text(), self.chkbox_use_encryption.get_active(), False) #chkbox_use_ics.get_active()) dialog.destroy() def toggle_encrypt_check(self, widget=None): """ Toggles the encryption key entry box for the ad-hoc dialog. """ self.key_entry.set_sensitive(self.chkbox_use_encryption.get_active()) def switch_rfkill(self, widget=None): """ Switches wifi card on/off. """ wireless.SwitchRfKill() if wireless.GetRfKillEnabled(): self.rfkill_button.set_stock_id(gtk.STOCK_MEDIA_PLAY) self.rfkill_button.set_label(language['switch_on_wifi']) else: self.rfkill_button.set_stock_id(gtk.STOCK_MEDIA_STOP) self.rfkill_button.set_label(language['switch_off_wifi']) def disconnect_all(self, widget=None): """ Disconnects from any active network. """ def handler(*args): gobject.idle_add(self.all_network_list.set_sensitive, True) self.all_network_list.set_sensitive(False) daemon.Disconnect(reply_handler=handler, error_handler=handler) def about_dialog(self, widget, event=None): """ Displays an about dialog. """ dialog = gtk.AboutDialog() dialog.set_name("Wicd") dialog.set_version(daemon.Hello()) dialog.set_authors([ "Adam Blackburn", "Dan O'Reilly", "Andrew Psaltis" ]) dialog.set_website("http://wicd.sourceforge.net") dialog.run() dialog.destroy() def key_event (self, widget, event=None): """ Handle key-release-events. """ if event.state & gtk.gdk.CONTROL_MASK and \ gtk.gdk.keyval_name(event.keyval) in ["w", "q"]: self.exit() def settings_dialog(self, widget, event=None): """ Displays a general settings dialog. """ if not self.pref: self.pref = PreferencesDialog(self, self.wTree) else: self.pref.load_preferences_diag() if self.pref.run() == 1: self.pref.save_results() self.pref.hide() def connect_hidden(self, widget): """ Prompts the user for a hidden network, then scans for it. """ dialog = gtk.Dialog(title=language['hidden_network'], flags=gtk.DIALOG_MODAL, buttons=(gtk.STOCK_CONNECT, 1, gtk.STOCK_CANCEL, 2)) dialog.set_has_separator(False) lbl = gtk.Label(language['hidden_network_essid']) textbox = gtk.Entry() dialog.vbox.pack_start(lbl) dialog.vbox.pack_start(textbox) dialog.show_all() button = dialog.run() if button == 1: answer = textbox.get_text() dialog.destroy() self.refresh_networks(None, True, answer) else: dialog.destroy() def cancel_connect(self, widget): """ Alerts the daemon to cancel the connection process. """ #should cancel a connection if there #is one in progress cancel_button = self.wTree.get_object("cancel_button") cancel_button.set_sensitive(False) daemon.CancelConnect() # Prevents automatic reconnecting if that option is enabled daemon.SetForcedDisconnect(True) def pulse_progress_bar(self): """ Pulses the progress bar while connecting to a network. """ if not self.pulse_active: return False if not self.is_visible: return True try: gobject.idle_add(self.wTree.get_object("progressbar").pulse) except: pass return True def update_statusbar(self): """ Triggers a status update in wicd-monitor. """ if not self.is_visible: return True daemon.UpdateState() if self.connecting: # If we're connecting, don't wait for the monitor to send # us a signal, since it won't until the connection is made. self._do_statusbar_update(*daemon.GetConnectionStatus()) return True def _do_statusbar_update(self, state, info): if not self.is_visible: return True if state == misc.WIRED: return self.set_wired_state(info) elif state == misc.WIRELESS: return self.set_wireless_state(info) elif state == misc.CONNECTING: return self.set_connecting_state(info) elif state in (misc.SUSPENDED, misc.NOT_CONNECTED): return self.set_not_connected_state(info) return True def set_wired_state(self, info): if self.connecting: # Adjust our state from connecting->connected. self._set_not_connecting_state() self.set_status(language['connected_to_wired'].replace('$A', info[0])) return True def set_wireless_state(self, info): if self.connecting: # Adjust our state from connecting->connected. self._set_not_connecting_state() self.set_status(language['connected_to_wireless'].replace ('$A', info[1]).replace ('$B', daemon.FormatSignalForPrinting(info[2])).replace ('$C', info[0])) return True def set_not_connected_state(self, info): if self.connecting: # Adjust our state from connecting->not-connected. self._set_not_connecting_state() self.set_status(language['not_connected']) return True def _set_not_connecting_state(self): if self.connecting: if self.update_cb: gobject.source_remove(self.update_cb) self.update_cb = misc.timeout_add(2, self.update_statusbar) self.connecting = False if self.pulse_active: self.pulse_active = False gobject.idle_add(self.all_network_list.set_sensitive, True) gobject.idle_add(self.status_area.hide_all) if self.statusID: gobject.idle_add(self.status_bar.remove_message, 1, self.statusID) def set_connecting_state(self, info): if not self.connecting: if self.update_cb: gobject.source_remove(self.update_cb) self.update_cb = misc.timeout_add(500, self.update_statusbar, milli=True) self.connecting = True if not self.pulse_active: self.pulse_active = True misc.timeout_add(100, self.pulse_progress_bar, milli=True) gobject.idle_add(self.all_network_list.set_sensitive, False) gobject.idle_add(self.status_area.show_all) if self.statusID: gobject.idle_add(self.status_bar.remove_message, 1, self.statusID) if info[0] == "wireless": essid, stat = wireless.CheckWirelessConnectingMessage() gobject.idle_add(self.set_status, "%s: %s" % (essid, language[str(stat)])) elif info[0] == "wired": gobject.idle_add(self.set_status, language['wired_network'] + ': ' + language[str(wired.CheckWiredConnectingMessage())]) return True def update_connect_buttons(self, state=None, x=None, force_check=False): """ Updates the connect/disconnect buttons for each network entry. If force_check is given, update the buttons even if the current network state is the same as the previous. """ if not DBUS_AVAIL: return if not state: state, x = daemon.GetConnectionStatus() if self.prev_state != state or force_check: apbssid = wireless.GetApBssid() for entry in chain(self.network_list, self.wired_network_box): if hasattr(entry, "update_connect_button"): entry.update_connect_button(state, apbssid) self.prev_state = state def set_status(self, msg): """ Sets the status bar message for the GUI. """ self.statusID = self.status_bar.push(1, msg) def dbus_scan_finished(self): """ Calls for a non-fresh update of the gui window. This method is called after a wireless scan is completed. """ if not DBUS_AVAIL: return gobject.idle_add(self.refresh_networks, None, False, None) def dbus_scan_started(self): """ Called when a wireless scan starts. """ if not DBUS_AVAIL: return self.network_list.set_sensitive(False) def _remove_items_from_vbox(self, vbox): for z in vbox: vbox.remove(z) z.destroy() del z def refresh_clicked(self, widget=None): """ Kick off an asynchronous wireless scan. """ if not DBUS_AVAIL or self.connecting: return self.refreshing = True # Remove stuff already in there. self._remove_items_from_vbox(self.wired_network_box) self._remove_items_from_vbox(self.network_list) label = gtk.Label("%s..." % language['scanning']) self.network_list.pack_start(label) self.network_list.show_all() if wired.CheckPluggedIn() or daemon.GetAlwaysShowWiredInterface(): printLine = True # In this case we print a separator. wirednet = WiredNetworkEntry() self.wired_network_box.pack_start(wirednet, False, False) wirednet.connect_button.connect("clicked", self.connect, "wired", 0, wirednet) wirednet.disconnect_button.connect("clicked", self.disconnect, "wired", 0, wirednet) wirednet.advanced_button.connect("clicked", self.edit_advanced, "wired", 0, wirednet) state, x = daemon.GetConnectionStatus() wirednet.update_connect_button(state) self._wired_showing = True else: self._wired_showing = False wireless.Scan(False) def refresh_networks(self, widget=None, fresh=True, hidden=None): """ Refreshes the network list. If fresh=True, scans for wireless networks and displays the results. If a ethernet connection is available, or the user has chosen to, displays a Wired Network entry as well. If hidden isn't None, will scan for networks after running iwconfig <wireless interface> essid <hidden>. """ if fresh: if hidden: wireless.SetHiddenNetworkESSID(noneToString(hidden)) self.refresh_clicked() return print "refreshing..." self.network_list.set_sensitive(False) self._remove_items_from_vbox(self.network_list) self.wait_for_events() printLine = False # We don't print a separator by default. if self._wired_showing: printLine = True num_networks = wireless.GetNumberOfNetworks() instruct_label = self.wTree.get_object("label_instructions") if num_networks > 0: instruct_label.show() for x in range(0, num_networks): if printLine: sep = gtk.HSeparator() self.network_list.pack_start(sep, padding=10, fill=False, expand=False) sep.show() else: printLine = True tempnet = WirelessNetworkEntry(x) self.network_list.pack_start(tempnet, False, False) tempnet.connect_button.connect("clicked", self.connect, "wireless", x, tempnet) tempnet.disconnect_button.connect("clicked", self.disconnect, "wireless", x, tempnet) tempnet.advanced_button.connect("clicked", self.edit_advanced, "wireless", x, tempnet) else: instruct_label.hide() if wireless.GetKillSwitchEnabled(): label = gtk.Label(language['killswitch_enabled'] + ".") else: label = gtk.Label(language['no_wireless_networks_found']) self.network_list.pack_start(label) label.show() self.update_connect_buttons(force_check=True) self.network_list.set_sensitive(True) self.refreshing = False def save_settings(self, nettype, networkid, networkentry): """ Verifies and saves the settings for the network entry. """ entry = networkentry.advanced_dialog opt_entlist = [] req_entlist = [] # First make sure all the Addresses entered are valid. if entry.chkbox_static_ip.get_active(): req_entlist = [entry.txt_ip, entry.txt_netmask] opt_entlist = [entry.txt_gateway] if entry.chkbox_static_dns.get_active() and \ not entry.chkbox_global_dns.get_active(): for ent in [entry.txt_dns_1, entry.txt_dns_2, entry.txt_dns_3]: opt_entlist.append(ent) # Required entries. for lblent in req_entlist: lblent.set_text(lblent.get_text().strip()) if not misc.IsValidIP(lblent.get_text()): error(self.window, language['invalid_address']. replace('$A', lblent.label.get_label())) return False # Optional entries, only check for validity if they're entered. for lblent in opt_entlist: lblent.set_text(lblent.get_text().strip()) if lblent.get_text() and not misc.IsValidIP(lblent.get_text()): error(self.window, language['invalid_address']. replace('$A', lblent.label.get_label())) return False # Now save the settings. if nettype == "wireless": if not networkentry.save_wireless_settings(networkid): return False elif nettype == "wired": if not networkentry.save_wired_settings(): return False return True def edit_advanced(self, widget, ttype, networkid, networkentry): """ Display the advanced settings dialog. Displays the advanced settings dialog and saves any changes made. If errors occur in the settings, an error message will be displayed and the user won't be able to save the changes until the errors are fixed. """ dialog = networkentry.advanced_dialog dialog.set_values() dialog.show_all() while True: if self.run_settings_dialog(dialog, ttype, networkid, networkentry): break dialog.hide() def run_settings_dialog(self, dialog, nettype, networkid, networkentry): """ Runs the settings dialog. Runs the settings dialog and returns True if settings are saved successfully, and false otherwise. """ result = dialog.run() if result == gtk.RESPONSE_ACCEPT: if self.save_settings(nettype, networkid, networkentry): return True else: return False return True def check_encryption_valid(self, networkid, entry): """ Make sure that encryption settings are properly filled in. """ # Make sure no entries are left blank if entry.chkbox_encryption.get_active(): encryption_info = entry.encryption_info for entry_info in encryption_info.itervalues(): if entry_info[0].entry.get_text() == "" and \ entry_info[1] == 'required': error(self.window, "%s (%s)" % (language['encrypt_info_missing'], entry_info[0].label.get_label()) ) return False # Make sure the checkbox is checked when it should be elif not entry.chkbox_encryption.get_active() and \ wireless.GetWirelessProperty(networkid, "encryption"): error(self.window, language['enable_encryption']) return False return True def _wait_for_connect_thread_start(self): self.wTree.get_object("progressbar").pulse() if not self._connect_thread_started: return True else: misc.timeout_add(2, self.update_statusbar) self.update_statusbar() return False def connect(self, widget, nettype, networkid, networkentry): """ Initiates the connection process in the daemon. """ def handler(*args): self._connect_thread_started = True def setup_interface_for_connection(): cancel_button = self.wTree.get_object("cancel_button") cancel_button.set_sensitive(True) self.all_network_list.set_sensitive(False) if self.statusID: gobject.idle_add(self.status_bar.remove_message, 1, self.statusID) gobject.idle_add(self.set_status, language["disconnecting_active"]) gobject.idle_add(self.status_area.show_all) self.wait_for_events() self._connect_thread_started = False if nettype == "wireless": if not self.check_encryption_valid(networkid, networkentry.advanced_dialog): self.edit_advanced(None, nettype, networkid, networkentry) return False setup_interface_for_connection() wireless.ConnectWireless(networkid, reply_handler=handler, error_handler=handler) elif nettype == "wired": setup_interface_for_connection() wired.ConnectWired(reply_handler=handler, error_handler=handler) gobject.source_remove(self.update_cb) misc.timeout_add(100, self._wait_for_connect_thread_start, milli=True) def disconnect(self, widget, nettype, networkid, networkentry): """ Disconnects from the given network. Keyword arguments: widget -- The disconnect button that was pressed. event -- unused nettype -- "wired" or "wireless", depending on the network entry type. networkid -- unused networkentry -- The NetworkEntry containing the disconnect button. """ def handler(*args): gobject.idle_add(self.all_network_list.set_sensitive, True) gobject.idle_add(self.network_list.set_sensitive, True) widget.hide() networkentry.connect_button.show() daemon.SetForcedDisconnect(True) self.network_list.set_sensitive(False) if nettype == "wired": wired.DisconnectWired(reply_handler=handler, error_handler=handler) else: wireless.DisconnectWireless(reply_handler=handler, error_handler=handler) def wait_for_events(self, amt=0): """ Wait for any pending gtk events to finish before moving on. Keyword arguments: amt -- a number specifying the number of ms to wait before checking for pending events. """ time.sleep(amt) while gtk.events_pending(): gtk.main_iteration() def exit(self, widget=None, event=None): """ Hide the wicd GUI. This method hides the wicd GUI and writes the current window size to disc for later use. This method normally does NOT actually destroy the GUI, it just hides it. """ self.window.hide() gobject.source_remove(self.update_cb) bus.remove_signal_receiver(self._do_statusbar_update, 'StatusChanged', 'org.wicd.daemon') [width, height] = self.window.get_size() try: daemon.SetGUIOpen(False) except DBusException: pass if self.standalone: sys.exit(0) self.is_visible = False return True def show_win(self): """ Brings the GUI out of the hidden state. Method to show the wicd GUI, alert the daemon that it is open, and refresh the network list. """ self.window.present() self.window.deiconify() self.wait_for_events() self.is_visible = True daemon.SetGUIOpen(True) self.wait_for_events(0.1) gobject.idle_add(self.refresh_clicked) self._do_statusbar_update(*daemon.GetConnectionStatus()) bus.add_signal_receiver(self._do_statusbar_update, 'StatusChanged', 'org.wicd.daemon') self.update_cb = misc.timeout_add(2, self.update_statusbar) if __name__ == '__main__': setup_dbus() app = appGui(standalone=True) mainloop = gobject.MainLoop() mainloop.run()
cbxbiker61/wicd
gtk/gui.py
Python
gpl-2.0
33,021
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2003-2006 Donald N. Allingham # Copyright (C) 2009-2010 Gary Burton # Copyright (C) 2010 Nick Hall # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # $Id$ #------------------------------------------------------------------------- # # internationalization # #------------------------------------------------------------------------- from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.get_translation().gettext #------------------------------------------------------------------------- # # gramps modules # #------------------------------------------------------------------------- from ..views.treemodels.placemodel import PlaceListModel from .baseselector import BaseSelector #------------------------------------------------------------------------- # # SelectPlace # #------------------------------------------------------------------------- class SelectPlace(BaseSelector): def _local_init(self): """ Perform local initialisation for this class """ self.width_key = 'interface.place-sel-width' self.height_key = 'interface.place-sel-height' def get_window_title(self): return _("Select Place") def get_model_class(self): return PlaceListModel def get_column_titles(self): return [ (_('Title'), 350, BaseSelector.TEXT, 0), (_('ID'), 75, BaseSelector.TEXT, 1), (_('Street'), 75, BaseSelector.TEXT, 2), (_('Locality'), 75, BaseSelector.TEXT, 3), (_('City'), 75, BaseSelector.TEXT, 4), (_('County'), 75, BaseSelector.TEXT, 5), (_('State'), 75, BaseSelector.TEXT, 6), (_('Country'), 75, BaseSelector.TEXT, 7), (_('Parish'), 75, BaseSelector.TEXT, 9), ] def get_from_handle_func(self): return self.db.get_place_from_handle
Forage/Gramps
gramps/gui/selectors/selectplace.py
Python
gpl-2.0
2,617
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright © 2010 University of Zürich # Author: Rico Sennrich <sennrich@cl.uzh.ch> # For licensing information, see LICENSE from __future__ import division,print_function,unicode_literals import sys import time import math from operator import itemgetter from bleualign.gale_church import align_texts import bleualign.score as bleu from bleualign.utils import evaluate, finalevaluation import io import platform if sys.version_info >= (2,6) and platform.system() != "Windows": import multiprocessing multiprocessing_enabled = 1 else: multiprocessing_enabled = 0 def collect_article(src,srctotarget,target,targettosrc,options): EOF = False while not EOF: all_texts = [] all_translations = [] for text,translations in [(src,srctotarget),(target,targettosrc)]: textlist = [] translist = [[] for i in translations] for line in text: if line.rstrip() == options['end_of_article_marker']: for f in translations: f.readline() break for i,f in enumerate(translations): translist[i].append(f.readline().rstrip()) if options['factored']: rawline = ' '.join(word.split('|')[0] for word in line.split()) textlist.append((rawline,line.rstrip())) else: textlist.append(line.rstrip()) else: EOF = True all_texts.append(textlist) all_translations.append(translist) sourcelist, targetlist = all_texts translist1, translist2 = all_translations yield sourcelist,targetlist,translist1,translist2 #takes a queue as argument and puts all articles to be aligned in it. #best call this in a separate process because we limit the queue size for memory reasons def tasks_producer(tasks,num_tasks,data,num_processes): for i,task in enumerate(collect_article(*data)): num_tasks.value += 1 tasks.put((i,task),True) #poison pills for i in range(num_processes): tasks.put((None,None)) num_tasks.value -= 1 # only if this point is reached, process finishes when all tasks are done. class Aligner: default_options = { #source and target files needed by Aligner #they can be filenames, arrays of strings or io objects. 'srcfile':None, 'targetfile': None, #the format of srcfile and targetfile #False for normal text, True for 'text | other information', seprating by '|' 'factored': False, #translations of srcfile and targetfile, not influenced by 'factored' #they can be filenames, arrays of strings or io objects, too. 'srctotarget': [], 'targettosrc': [], #run aligner without srctotarget and targettosrc 'no_translation_override':False, #only consider target sentences for bleu-based alignment that are among top N alternatives for a given source sentence 'maxalternatives':3, #bleu scoring algorithm works with 4-grams by default. We got better results when using 2-grams (since there are less 0 scores then) 'bleu_ngrams' : 2, #BLEU is word-based by default, but character-level BLEU is more suitable for some languages, e.g. continuous script languages without space. #it is a good idea to also increase bleu_ngrams when switching to character-level BLEU 'bleu_charlevel' : False, #consider N to 1 (and 1 to N) alignment in gapfilling (complexity is size_of_gap*value^2, so don't turn this unnecessarily high) #also, there are potential precision issues. #set to 1 to disable bleu-based 1 to N alignments and let gale & church fill the gaps 'Nto1' : 2, #do only gale-church, no bleualign 'galechurch': None, #gapfillheuristics: what to do with sentences that aren't aligned one-to-one by the first BLEU pass, nor have a 1 to N alignment validated by BLEU? #possible members are: bleu1to1, galechurch #what they do is commented in the source code 'gapfillheuristics' : ["bleu1to1","galechurch"], #defines string that identifies hard boundaries (articles, chapters etc.) #string needs to be on a line of its own (see examples in eval directory) #must be reliable (article i in the source text needs to correspond to article i in the target text) 'end_of_article_marker' : ".EOA", #filtering out bad alignments by bleuscore #filter has sentences or articles type #filterthreshold means choosing the best X% of alignments (according to BLEU) #bleuthreshold requires a sentence pair to achieve a certain BLEU score to be included in the output #set filterlang True, whose when you want to filter alignemts which src is similar to target than translation 'filter': None, 'filterthreshold': 90, 'bleuthreshold': 0, 'filterlang': None, #it will print unalignemt pair(zero to one or one to zero pair) 'printempty': False, #setting output for four output filenames, it will add suffixes automatically #or passing filenames or io object for them in respectly. #if not passing anything or assigning None, they will use StringIO to save results. 'output': None, 'output-src': None, 'output-target': None, 'output-src-bad': None, 'output-target-bad': None, #the best alignment of corpus for evaluation 'eval': None, #defines amount of debugging output. 'verbosity': 1, 'log_to':sys.stdout, #number of parallel processes 'num_processes': 1 } def __init__(self,options): self.src, self.target = None,None self.srctotarget, self.targettosrc= [],[] self.out1, self.out2, self.out_bad1, self.out_bad2 = None,None,None,None self.sources_out,self.targets_out = [],[] self.finalbleu = [] self.bleualign = [] self.close_src, self.close_target = False, False self.close_srctotarget, self.close_targettosrc = [], [] self.close_out1, self.close_out2 = False, False self.close_out_bad1, self.close_out_bad2 = False, False self.options = self.default_options.copy() self.options.update(options) if not self.options['srcfile']: raise ValueError('Source file not specified.') if not self.options['targetfile']: raise ValueError('Target file not specified.') if not self.options['srctotarget'] and not self.options['targettosrc']\ and not self.options['no_translation_override']: raise ValueError("ERROR: no translation available: BLEU scores can be computed between the source and target text, but this is not the intended usage of Bleualign and may result in poor performance! If you're *really* sure that this is what you want, set 'galechurch' for the options.") self.src, self.close_src = \ self._inputObjectFromParameter(self.options['srcfile']) self.target, self.close_target = \ self._inputObjectFromParameter(self.options['targetfile']) for f in self.options['srctotarget']: obj, close_obj = \ self._inputObjectFromParameter(f) self.srctotarget.append(obj) self.close_srctotarget.append(close_obj) for f in self.options['targettosrc']: obj, close_obj = \ self._inputObjectFromParameter(f) self.targettosrc.append(obj) self.close_targettosrc.append(close_obj) self.out1,self.close_out1=self._outputObjectFromParameter( self.options['output-src'], self.options['output'], '-s') self.out2,self.close_out2=self._outputObjectFromParameter( self.options['output-target'], self.options['output'], '-t') if self.options['filter']: self.out_bad1,self.close_out_bad1=self._outputObjectFromParameter( self.options['output-src-bad'], self.options['output'], '-bad-s') self.out_bad2,self.close_out_bad2=self._outputObjectFromParameter( self.options['output-target-bad'], self.options['output'], '-bad-t') # for passing by string array def _stringArray2stringIo(self, stringArray): return io.StringIO('\n'.join([line.rstrip() for line in stringArray])) # parameter may be filename, IO object or string array def _inputObjectFromParameter(self, parameter): try: inputObject = io.open(parameter, 'r', encoding='UTF-8') close_object = True except: if isinstance(parameter, io.TextIOBase): inputObject = parameter else: inputObject = self._stringArray2stringIo(parameter) close_object = False return inputObject, close_object # parameter may be filename, IO object or string array def _outputObjectFromParameter(self, parameter, filename, suffix): close_object = False if parameter: try: outputObject = io.open(parameter, 'w', encoding='UTF-8') close_object = True except: outputObject = parameter elif filename: outputObject = io.open(filename + suffix, 'w', encoding='UTF-8') else: outputObject = io.StringIO() return outputObject, close_object #takes care of multiprocessing; calls process() function for each article def mainloop(self): results = {} if multiprocessing_enabled and self.options['num_processes'] > 1: tasks = multiprocessing.Queue(self.options['num_processes']+1) manager = multiprocessing.Manager() scores = manager.dict() num_tasks = manager.Value('i',1) scorers = [AlignMultiprocessed(tasks,self.options,scores,self.log) for i in range(self.options['num_processes'])] for p in scorers: p.start() #this function produces the alignment tasks for the consumers in scorers producer = multiprocessing.Process(target=tasks_producer,args=(tasks,num_tasks,(self.src,self.srctotarget,self.target,self.targettosrc,self.options),self.options['num_processes'])) producer.start() i = 0 #get results from processed and call printout function while i < num_tasks.value: #wait till result #i is populated while True: try: data,multialign,bleualign,scoredict = scores[i] break except: time.sleep(0.1) for p in scorers: if p.exitcode == 1: for p in scorers: p.terminate() producer.terminate() raise RuntimeError("Multiprocessing error") continue (sourcelist,targetlist,translist1,translist2) = data self.scoredict = scoredict self.multialign = multialign self.bleualign = bleualign #normal case: translation from source to target exists if translist1: translist = translist1[0] #no translation provided. we copy source sentences for further processing else: if self.options['factored']: translist = [item[0] for item in sourcelist] else: translist = sourcelist self.printout(sourcelist, translist, targetlist) if self.options['eval']: self.log('evaluation ' + str(i)) results[i] = evaluate(self.options,self.multialign,self.options['eval'][i],self.log) del(scores[i]) i += 1 else: for i,(sourcelist,targetlist,translist1,translist2) in enumerate(collect_article(self.src,self.srctotarget,self.target,self.targettosrc,self.options)): self.log('reading in article ' + str(i) + ': ',1) self.multialign = self.process(sourcelist,targetlist,translist1,translist2) if translist1: translist = translist1[0] else: if self.options['factored']: translist = [item[0] for item in sourcelist] else: translist = sourcelist self.printout(sourcelist, translist, targetlist) if self.options['eval']: self.log('evaluation ' + str(i)) results[i] = evaluate(self.options, self.multialign,self.options['eval'][i],self.log) if self.out1: self.out1.flush() if self.out2: self.out2.flush() if self.options['eval']: finalevaluation(results, self.log) if self.options['filter']: self.write_filtered() self.close_file_streams() return self.out1,self.out2 #results of alignment or good aligment if filtering def results(self): return self.out1,self.out2 #bad aligment for filtering. Otherwise, None def results_bad(self): return self.out_bad1,self.out_bad2 #Start different alignment runs depending on which and how many translations are sent to program; intersect results. def process(self,sourcelist,targetlist,translist1,translist2): multialign = [] phase1 = [] phase2 = [] #do nothing if last line in file is .EOA or file is empty. if not targetlist or not sourcelist: self.log('WARNING: article is empty. Skipping.',0) return [] self.log('processing',1) if self.options['factored']: raw_sourcelist = [item[0] for item in sourcelist] raw_targetlist = [item[0] for item in targetlist] else: raw_sourcelist = sourcelist raw_targetlist = targetlist for i,translist in enumerate(translist1): self.log("computing alignment between srctotarget (file " + str(i) + ") and target text",1) phase1.append(self.align(translist, raw_targetlist)) for i,translist in enumerate(translist2): self.log("computing alignment between targettosrc (file " + str(i) + ") and source text",1) phase2.append(self.align(translist, raw_sourcelist)) if not (translist1 or translist2): if self.options['no_translation_override'] or self.options['galechurch']: phase1 = [self.align(raw_sourcelist, raw_targetlist)] else: self.log("ERROR: no translation available", 1) if multiprocessing_enabled and self.options['num_processes'] > 1: sys.exit(1) else: raise RuntimeError("ERROR: no translation available") if len(phase1) > 1: self.log("intersecting all srctotarget alignments",1) phase1 = sorted(set(phase1[0]).intersection(*[set(x) for x in phase1[1:]])) elif phase1: phase1 = phase1[0] if len(phase2) > 1: self.log("intersecting all targettosrc alignments",1) phase2 = sorted(set(phase2[0]).intersection(*[set(x) for x in phase2[1:]])) elif phase2: phase2 = phase2[0] if phase1 and phase2: self.log("intersecting both directions",1) phase3 = [] phase2mirror = [(j,k) for ((k,j),t) in phase2] for pair,t in phase1: if pair in phase2mirror: phase3.append((pair,'INTERSECT: ' + t + ' - ' + phase2[phase2mirror.index(pair)][1])) multialign = phase3 elif phase1: multialign = phase1 elif phase2: multialign = [((j,k),t) for ((k,j),t) in phase2] return multialign #Compute alignment for one article and one automatic translation. def align(self, translist, targetlist): if self.options["galechurch"]: self.multialign,self.bleualign,self.scoredict = [],[],{} translist = [item for item in enumerate(translist)] targetlist = [item for item in enumerate(targetlist)] churchaligns = self.gale_church(translist,targetlist) for src,target in churchaligns: self.addtoAlignments((src,target),'GALECHURCH') return self.multialign else: self.log('Evaluating sentences with bleu',1) self.scoredict = self.eval_sents(translist,targetlist) self.log('finished',1) self.log('searching for longest path of good alignments',1) self.pathfinder(translist, targetlist) self.log('finished',1) self.log(time.asctime(),2) self.log('filling gaps',1) self.gapfinder(translist, targetlist) self.log('finished',1) self.log(time.asctime(),2) return self.multialign #use this if you want to implement your own similarity score def eval_sents_dummy(self,translist,targetlist): scoredict = {} for testID,testSent in enumerate(translist): scores = [] for refID,refSent in enumerate(targetlist): score = 100-abs(len(testSent)-len(refSent)) #replace this with your own similarity score if score > 0: scores.append((score,refID,score)) scoredict[testID] = sorted(scores,key=itemgetter(0),reverse=True)[:self.options['maxalternatives']] return scoredict # given list of test sentences and list of reference sentences, calculate bleu scores #if you want to replace bleu with your own similarity measure, use eval_sents_dummy def eval_sents(self,translist,targetlist): scoredict = {} cooked_test = {} cooked_test2 = {} ngrams = self.options['bleu_ngrams'] charlevel = self.options['bleu_charlevel'] cooktarget_cache = {} cooktarget = [] for idx, item in enumerate(targetlist): if charlevel: item = tuple(item) if item in cooktarget_cache: cooktarget.append((idx, cooktarget_cache[item])) else: cooked = (idx, bleu.cook_ref_set(item, ngrams)) cooktarget.append(cooked) cooktarget_cache[item] = cooked[1] for testID,testSent in enumerate(translist): if charlevel: testSent = tuple(testSent) #copied over from bleu.py to minimize redundancy test_normalized = bleu.normalize(testSent) cooked_test["testlen"] = len(test_normalized) cooked_test["guess"] = [max(len(test_normalized)-k+1,0) for k in range(1,self.options['bleu_ngrams']+1)] counts = bleu.count_ngrams(test_normalized, self.options['bleu_ngrams']) #separate by n-gram length. if we have no matching bigrams, we don't have to compare unigrams ngrams_sorted = dict([(x,set()) for x in range(self.options['bleu_ngrams'])]) for ngram in counts: ngrams_sorted[len(ngram)-1].add(ngram) scorelist = [] scorelist_cache = {} for (refID,(reflen, refmaxcounts, refset)) in cooktarget: if refset in scorelist_cache: if scorelist_cache[refset] is not None: m, c = scorelist_cache[refset] scorelist.append((m, refID, c)) continue ngrams_filtered = ngrams_sorted[self.options['bleu_ngrams']-1].intersection(refset) if ngrams_filtered: cooked_test["reflen"] = reflen cooked_test['correct'] = [0]*self.options['bleu_ngrams'] for ngram in ngrams_filtered: cooked_test["correct"][self.options['bleu_ngrams']-1] += min(refmaxcounts[ngram], counts[ngram]) for order in range(self.options['bleu_ngrams']-1): for ngram in ngrams_sorted[order].intersection(refset): cooked_test["correct"][order] += min(refmaxcounts[ngram], counts[ngram]) #copied over from bleu.py to minimize redundancy logbleu = 0.0 for k in range(self.options['bleu_ngrams']): logbleu += math.log(cooked_test['correct'][k])-math.log(cooked_test['guess'][k]) logbleu /= self.options['bleu_ngrams'] logbleu += min(0,1-float(cooked_test['reflen'])/cooked_test['testlen']) score = math.exp(logbleu) if score > 0: #calculate bleu score in reverse direction cooked_test2["guess"] = [max(cooked_test['reflen']-k+1,0) for k in range(1,self.options['bleu_ngrams']+1)] logbleu = 0.0 for k in range(self.options['bleu_ngrams']): logbleu += math.log(cooked_test['correct'][k])-math.log(cooked_test2['guess'][k]) logbleu /= self.options['bleu_ngrams'] logbleu += min(0,1-float(cooked_test['testlen'])/cooked_test['reflen']) score2 = math.exp(logbleu) meanscore = (2*score*score2)/(score+score2) scorelist.append((meanscore,refID,cooked_test['correct'])) scorelist_cache[refset] = (meanscore, cooked_test['correct']) else: scorelist_cache[refset] = None else: scorelist_cache[refset] = None scoredict[testID] = sorted(scorelist,key=itemgetter(0),reverse=True)[:self.options['maxalternatives']] return scoredict #follow the backpointers in score matrix to extract best path of 1-to-1 alignments def extract_best_path(self,pointers): i = len(pointers)-1 j = len(pointers[0])-1 pointer = '' best_path = [] while i >= 0 and j >= 0: pointer = pointers[i][j] if pointer == '^': i -= 1 elif pointer == '<': j -= 1 elif pointer == 'match': best_path.append((i,j)) i -= 1 j -= 1 best_path.reverse() return best_path #dynamic programming search for best path of alignments (maximal score) def pathfinder(self, translist, targetlist): # add an extra row/column to the matrix and start filling it from 1,1 (to avoid exceptions for first row/column) matrix = [[0 for column in range(len(targetlist)+1)] for row in range(len(translist)+1)] pointers = [['' for column in range(len(targetlist))] for row in range(len(translist))] for i in range(len(translist)): alignments = dict([(target, score) for (score, target, correct) in self.scoredict[i]]) for j in range(len(targetlist)): best_score = matrix[i][j+1] best_pointer = '^' score = matrix[i+1][j] if score > best_score: best_score = score best_pointer = '<' if j in alignments: score = alignments[j] + matrix[i][j] if score > best_score: best_score = score best_pointer = 'match' matrix[i+1][j+1] = best_score pointers[i][j] = best_pointer self.bleualign = self.extract_best_path(pointers) #find unaligned sentences and create work packets for gapfiller() #gapfiller() takes two sentence pairs and all unaligned sentences in between as arguments; gapfinder() extracts these. def gapfinder(self, translist, targetlist): self.multialign = [] #find gaps: lastpair is considered pre-gap, pair is post-gap lastpair = ((),()) src, target = None, None for src,target in self.bleualign: oldsrc, oldtarget = lastpair #in first iteration, gap will start at 0 if not oldsrc: oldsrc = (-1,) if not oldtarget: oldtarget = (-1,) #identify gap sizes sourcegap = list(range(oldsrc[-1]+1,src)) targetgap = list(range(oldtarget[-1]+1,target)) if targetgap or sourcegap: lastpair = self.gapfiller(sourcegap, targetgap, lastpair, ((src,),(target,)), translist, targetlist) else: self.addtoAlignments(lastpair) lastpair = ((src,),(target,)) #if self.bleualign is empty, gap will start at 0 if src is None: src = -1 if target is None: target = -1 #search for gap after last alignment pair sourcegap = list(range(src+1, len(translist))) targetgap = list(range(target+1, len(targetlist))) if targetgap or sourcegap: lastpair = self.gapfiller(sourcegap, targetgap, lastpair, ((),()), translist, targetlist) self.addtoAlignments(lastpair) #apply heuristics to align all sentences that remain unaligned after finding best path of 1-to-1 alignments #heuristics include bleu-based 1-to-n alignment and length-based alignment def gapfiller(self, sourcegap, targetgap, pregap, postgap, translist, targetlist): evalsrc = [] evaltarget = [] #compile list of sentences in gap that will be considered for BLEU comparison if self.options['Nto1'] > 1 or "bleu1to1" in self.options['gapfillheuristics']: #concatenate all sentences in pregap alignment pair tmpstr = ' '.join([translist[i] for i in pregap[0]]) evalsrc.append((pregap[0],tmpstr)) #concatenate all sentences in pregap alignment pair tmpstr = ' '.join([targetlist[i] for i in pregap[1]]) evaltarget.append((pregap[1],tmpstr)) #search will be pruned to this window if "bleu1to1" in self.options['gapfillheuristics']: window = 10 + self.options['Nto1'] else: window = self.options['Nto1'] for src in [j for i,j in enumerate(sourcegap) if (i < window or len(sourcegap)-i <= window)]: Sent = translist[src] evalsrc.append(((src,),Sent)) for target in [j for i,j in enumerate(targetgap) if (i < window or len(targetgap)-i <= window)]: Sent = targetlist[target] evaltarget.append(((target,),Sent)) #concatenate all sentences in postgap alignment pair tmpstr = ' '.join([translist[i] for i in postgap[0]]) evalsrc.append((postgap[0],tmpstr)) #concatenate all sentences in postgap alignment pair tmpstr = ' '.join([targetlist[i] for i in postgap[1]]) evaltarget.append((postgap[1],tmpstr)) nSrc = {} for n in range(2,self.options['Nto1']+1): nSrc[n] = self.createNSents(evalsrc,n) for n in range(2,self.options['Nto1']+1): evalsrc += nSrc[n] nTar = {} for n in range(2,self.options['Nto1']+1): nTar[n] = self.createNSents(evaltarget,n) for n in range(2,self.options['Nto1']+1): evaltarget += nTar[n] evalsrc_raw = [item[1] for item in evalsrc] evaltarget_raw = [item[1] for item in evaltarget] scoredict_raw = self.eval_sents(evalsrc_raw,evaltarget_raw) scoredict = {} for src,value in list(scoredict_raw.items()): src = evalsrc[src][0] if value: newlist = [] for item in value: score,target,score2 = item target = evaltarget[target][0] newlist.append((score,target,score2)) scoredict[src] = newlist else: scoredict[src] = [] while sourcegap or targetgap: pregapsrc,pregaptarget = pregap postgapsrc,postgaptarget = postgap if sourcegap and self.options['Nto1'] > 1: #try if concatenating source sentences together improves bleu score (beginning of gap) if pregapsrc: oldscore,oldtarget,oldcorrect = scoredict[pregapsrc][0] combinedID = tuple(list(pregapsrc)+[sourcegap[0]]) if combinedID in scoredict: newscore,newtarget,newcorrect = scoredict[combinedID][0] if newscore > oldscore and newcorrect > oldcorrect and newtarget == pregaptarget: #print('\nsource side: ' + str(combinedID) + ' better than ' + str(pregapsrc)) pregap = (combinedID,pregaptarget) sourcegap.pop(0) continue #try if concatenating source sentences together improves bleu score (end of gap) if postgapsrc: oldscore,oldtarget,oldcorrect = scoredict[postgapsrc][0] combinedID = tuple([sourcegap[-1]] + list(postgapsrc)) if combinedID in scoredict: newscore,newtarget, newcorrect = scoredict[combinedID][0] if newscore > oldscore and newcorrect > oldcorrect and newtarget == postgaptarget: #print('\nsource side: ' + str(combinedID) + ' better than ' + str(postgapsrc)) postgap = (combinedID,postgaptarget) sourcegap.pop() continue if targetgap and self.options['Nto1'] > 1: #try if concatenating target sentences together improves bleu score (beginning of gap) if pregapsrc: newscore,newtarget,newcorrect = scoredict[pregapsrc][0] if newtarget != pregaptarget and newtarget != postgaptarget: #print('\ntarget side: ' + str(newtarget) + ' better than ' + str(pregaptarget)) pregap = (pregapsrc,newtarget) for i in newtarget: if i in targetgap: del(targetgap[targetgap.index(i)]) continue #try if concatenating target sentences together improves bleu score (end of gap) if postgapsrc: newscore,newtarget,newcorrect = scoredict[postgapsrc][0] if newtarget != postgaptarget and newtarget != pregaptarget: #print('\ntarget side: ' + str(newtarget) + ' better than ' + str(postgaptarget)) postgap = (postgapsrc,newtarget) for i in newtarget: if i in targetgap: del(targetgap[targetgap.index(i)]) continue #concatenation didn't help, and we still have possible one-to-one alignments if sourcegap and targetgap: #align first two sentences if BLEU validates this if "bleu1to1" in self.options['gapfillheuristics']: try: besttarget = scoredict[(sourcegap[0],)][0][1] except: besttarget = 0 if besttarget == (targetgap[0],): self.addtoAlignments(pregap) #print('\none-to-one: ' + str((sourcegap[0],)) + ' to' + str((targetgap[0],))) pregap = ((sourcegap[0],),besttarget) del(sourcegap[0]) del(targetgap[0]) continue #Alternative approach: use Gale & Church. if "galechurch" in self.options['gapfillheuristics'] and (max(len(targetgap),len(sourcegap))<4 or max(len(targetgap),len(sourcegap))/min(len(targetgap),len(sourcegap)) < 2): tempsrcgap = [] for src in sourcegap: tempsrcgap.append((src,translist[src])) temptargetgap = [] for target in targetgap: temptargetgap.append((target,targetlist[target])) churchaligns = self.gale_church(tempsrcgap,temptargetgap) for src,target in churchaligns: self.addtoAlignments((src,target),'GALECHURCH') break #no valid gapfiller left. break loop and ignore remaining gap break break if not pregap in [i[0] for i in self.multialign]: self.addtoAlignments(pregap) return postgap #Take list of (ID,Sentence) tuples for two language pairs and calculate Church & Gale alignment #Then transform it into this program's alignment format def gale_church(self,tempsrcgap,temptargetgap): #get sentence lengths in characters srclengths = [[len(i[1].strip()) for i in tempsrcgap]] targetlengths = [[len(i[1].strip()) for i in temptargetgap]] #call gale & church algorithm pairs = sorted(list((align_texts(srclengths, targetlengths)[0])), key=itemgetter(0)) idict = {} jdict = {} newpairs = [] #store 1-to-n alignments in single pairs of tuples (instead of using multiple pairs of ints) for i,j in pairs: if i in idict and j in jdict: done = 0 for iold1, jold1 in newpairs: if done: break if i in iold1: for iold2, jold2 in newpairs: if done: break if j in jold2: if not (iold1,jold1) == (iold2,jold2): del(newpairs[newpairs.index((iold1,jold1))]) del(newpairs[newpairs.index((iold2,jold2))]) inew = tuple(sorted(list(iold1)+list(iold2))) jnew = tuple(sorted(list(jold1)+list(jold2))) newpairs.append((inew,jnew)) done = 1 break elif i in idict: for iold, jold in newpairs: if i in iold: jnew = tuple(sorted(list(jold)+[j])) newpairs[newpairs.index((iold,jold))] = (iold,jnew) jdict[j] = 0 break elif j in jdict: for iold, jold in newpairs: if j in jold: inew = tuple(sorted(list(iold)+[i])) newpairs[newpairs.index((iold,jold))] = (inew,jold) idict[i] = 0 break else: idict[i] = 0 jdict[j] = 0 newpairs.append(((i,),(j,))) #Go from Church & Gale's numbering to our IDs outpairs = [] for i,j in newpairs: srcID = [] targetID = [] for src in i: srcID.append(tempsrcgap[src][0]) for target in j: targetID.append(temptargetgap[target][0]) #print('\nChurch & Gale: ' + str(tuple(srcID)) + ' to ' + str(tuple(targetID))) outpairs.append((tuple(srcID),tuple(targetID))) return outpairs #get a list of (ID,Sentence) tuples and generate bi- or tri-sentence tuples def createNSents(self,l,n=2): out = [] for i in range(len(l)-n+1): IDs = tuple([k for sublist in l[i:i+n] for k in sublist[0]]) Sents = " ".join([k[1] for k in l[i:i+n]]) out.append((IDs,Sents)) return out def addtoAlignments(self,pair,aligntype=None): if not (pair[0] and pair[1]): return if aligntype: self.multialign.append((pair,aligntype)) else: src,target = pair if len(src) == 1 and len(target) == 1 and (src[0],target[0]) in self.bleualign: self.multialign.append((pair,"BLEU")) else: self.multialign.append((pair,"GAPFILLER")) def print_alignment_statistics(self, source_len, target_len): multialignsrccount = sum([len(i[0][0]) for i in self.multialign]) multialigntargetcount = sum([len(i[0][1]) for i in self.multialign]) self.log("Results of BLEU 1-to-1 alignment",2) if self.options['verbosity'] >= 2: bleualignsrc = list(map(itemgetter(0),self.bleualign)) for sourceid in range(source_len): if sourceid in bleualignsrc: self.log('\033[92m' + str(sourceid) + ": " + str(self.bleualign[bleualignsrc.index(sourceid)][1]) + '\033[1;m') else: bestcand = self.scoredict.get(sourceid,[]) if bestcand: bestcand = bestcand[0][1] self.log('\033[1;31m'+str(sourceid) + ": unaligned. best cand " + str(bestcand)+'\033[1;m') if source_len and target_len: self.log("\n" + str(len(self.bleualign)) + ' out of ' + str(source_len) + ' source sentences aligned by BLEU ' + str(100*len(self.bleualign)/float(source_len)) + '%',2) self.log("after gap filling, " + str(multialignsrccount) + ' out of '+ str(source_len) + ' source sentences aligned ' + str(100*multialignsrccount/float(source_len)) + '%',2) self.log("after gap filling, " + str(multialigntargetcount) + ' out of '+ str(target_len) + ' target sentences aligned ' + str(100*multialigntargetcount/float(target_len)) + '%',2) #print out some debugging info, and print output to file def printout(self, sourcelist, translist, targetlist): self.print_alignment_statistics(len(sourcelist), len(targetlist)) sources = [] translations = [] targets = [] sources_factored = [] targets_factored = [] if self.options['factored']: sources_output = sources_factored targets_output = targets_factored else: sources_output = sources targets_output = targets self.multialign = sorted(self.multialign,key=itemgetter(0)) sentscores = {} lastsrc,lasttarget = 0,0 for j,(src,target) in enumerate([i[0] for i in self.multialign]): self.log("alignment: {0} - {1}".format(",".join(map(str,src)), ",".join(map(str,target))),2) if self.options['printempty']: if src[0] != lastsrc + 1: sources.extend([sourcelist[ID] for ID in range(lastsrc+1,src[0])]) targets.extend(['' for ID in range(lastsrc+1,src[0])]) translations.extend(['' for ID in range(lastsrc+1,src[0])]) if target[0] != lasttarget + 1: sources.extend(['' for ID in range(lasttarget+1,target[0])]) targets.extend([targetlist[ID] for ID in range(lasttarget+1,target[0])]) translations.extend(['' for ID in range(lasttarget+1,target[0])]) lastsrc = src[-1] lasttarget = target[-1] translations.append(' '.join([translist[ID] for ID in src])) if self.options['factored']: sources.append(' '.join([sourcelist[ID][0] for ID in src])) targets.append(' '.join([targetlist[ID][0] for ID in target])) sources_factored.append(' '.join([sourcelist[ID][1] for ID in src])) targets_factored.append(' '.join([targetlist[ID][1] for ID in target])) else: sources.append(' '.join([sourcelist[ID] for ID in src])) targets.append(' '.join([targetlist[ID] for ID in target])) if self.options['filter'] == 'sentences': self.check_sentence_pair(j, sources[-1], translations[-1], targets[-1], sources_output[-1], targets_output[-1], sentscores) if self.options['filter'] == 'sentences': self.filter_sentence_pairs(sentscores, sources_output, targets_output) if self.options['filter'] == 'articles': self.filter_article_pairs(sources, translations, targets, sources_output, targets_output) self.log("\nfinished with article",1) self.log("\n====================\n",1) if self.out1 and self.out2 and not self.options['filter']: if self.options['factored']: self.out1.write('\n'.join(sources_factored) + '\n') self.out2.write('\n'.join(targets_factored) + '\n') else: self.out1.write('\n'.join(sources) + '\n') self.out2.write('\n'.join(targets) + '\n') #get BLEU score of sentence pair (for filtering) def check_sentence_pair(self, j, src, trans, target, source_out, target_out, sentscores): sentscore = self.score_article([trans],[target]) sentscore2 = self.score_article([src],[target]) if sentscore2 > sentscore and self.options['filterlang']: self.out_bad1.write(source_out + '\n') self.out_bad2.write(target_out + '\n') else: if sentscore > 0: sentscorex = self.score_article([target],[trans]) newsentscore = (2*sentscore*sentscorex)/(sentscore+sentscorex) else: newsentscore = 0 sentscores[j]=newsentscore # get BLEU score for article pair def score_article(self,test,ref): refs = [bleu.cook_refs([refSent],self.options['bleu_ngrams']) for refSent in ref] testcook = [] for i,line in enumerate(test): testcook.append(bleu.cook_test(line,refs[i],self.options['bleu_ngrams'])) score = bleu.score_cooked(testcook,self.options['bleu_ngrams']) return score # store BLEU score for each sentence pair (used for filtering at the very end) def filter_sentence_pairs(self, sentscores, sources_output, targets_output): before = len(self.sources_out) for j,(src,target) in enumerate([i[0] for i in self.multialign]): if j in sentscores: # false if sentence pair has been filtered out by language filter confidence = sentscores[j] self.finalbleu.append((confidence,sentscores.get(j),before,before+1)) before += 1 self.sources_out.append(sources_output[j]) self.targets_out.append(targets_output[j]) # store BLEU score for each article pair (used for filtering at the very end) def filter_article_pairs(self, sources, translations, targets, sources_output, targets_output): articlescore = self.score_article(translations,targets) articlescore2 = self.score_article(sources,targets) self.log('\nBLEU score for article: ' + str(articlescore) + ' / ' + str(articlescore2),1) if articlescore2 > articlescore and self.options['filterlang']: if self.options['factored']: sources,targets = sources_factored,targets_factored for i,line in enumerate(sources): self.out_bad1.write(line + '\n') self.out_bad2.write(targets[i] + '\n') else: articlescorex = self.score_article(targets,translations) if articlescore > 0: articlescore = (articlescore*articlescorex*2)/(articlescore+articlescorex) before = len(self.sources_out) after = before + len(self.multialign) self.finalbleu.append((articlescore,articlescore2,before,after)) self.sources_out += sources_output self.targets_out += targets_output #filter bad sentence pairs / article pairs def write_filtered(self): self.finalbleu = sorted(self.finalbleu,key=itemgetter(0),reverse=True) self.log(self.finalbleu,2) totallength=0 totalscore=0 for (articlescore,articlescore2,before,after) in self.finalbleu: length = after-before totallength += length totalscore += articlescore*length if totallength != 0: averagescore = totalscore/totallength self.log("The average BLEU score is: " + str(averagescore),1) goodlength = totallength*self.options['filterthreshold']/float(100) totallength = 0 bad_percentiles = [] for i,(articlescore,articlescore2,before,after) in enumerate(self.finalbleu): length = after-before totallength += length if totallength > goodlength: bad_percentiles = self.finalbleu[i+1:] self.log("\nDiscarding the following " + self.options['filter'] + " based on relative BLEU\n",2) self.log(bad_percentiles,2) if self.options['verbosity'] >= 3: for score,score2,start,end in bad_percentiles: for i in range(start,end): self.log(score,3) self.log(self.sources_out[i],3) self.log(self.targets_out[i],3) self.log('-----------------',3) break stopwrite = set([i[2] for i in bad_percentiles]) resumewrite = set([i[3] for i in bad_percentiles]) stopped = 0 #absolute BLEU threshold if self.options['bleuthreshold']: bad_sentences = [] for i,(articlescore,articlescore2,before,after) in enumerate(self.finalbleu): if articlescore < self.options['bleuthreshold']: bad_sentences.append((articlescore,articlescore2,before,after)) stopwrite.add(before) resumewrite.add(after) self.log("\nDiscarding the following " + self.options['filter'] + " based on absolute BLEU\n",2) self.log(bad_sentences,2) if self.options['verbosity'] >= 3: for score,score2,start,end in bad_sentences: for i in range(start,end): self.log(score,3) self.log(self.sources_out[i],3) self.log(self.targets_out[i],3) self.log('-----------------',3) if self.out1 and self.out2 and self.out_bad1 and self.out_bad2: for i,line in enumerate(self.sources_out): if i in resumewrite: stopped = 0 if i in stopwrite: stopped = 1 if stopped: self.out_bad1.write(line + '\n') self.out_bad2.write(self.targets_out[i] + '\n') else: self.out1.write(line + '\n') self.out2.write(self.targets_out[i] + '\n') #close all files opened by __init__ def close_file_streams(self): if self.close_src: self.src.close() if self.close_target: self.target.close() if self.close_out1: self.out1.close() if self.close_out2: self.out2.close() if self.close_out_bad1: self.out_bad1.close() if self.close_out_bad2: self.out_bad2.close() for should_be_closed,output_stream\ in zip(self.close_srctotarget,self.srctotarget): if should_be_closed: output_stream.close() for should_be_closed,output_stream\ in zip(self.close_targettosrc,self.targettosrc): if should_be_closed: output_stream.close() def log(self, msg, level = 1, end='\n'): if level <= self.options['verbosity']: print(msg, end=end, file = self.options['log_to']) #Allows parallelizing of alignment if multiprocessing_enabled: class AlignMultiprocessed(multiprocessing.Process,Aligner): def __init__(self,tasks,options,scores,log): multiprocessing.Process.__init__(self) self.options = options self.tasks = tasks self.scores = scores self.log = log self.bleualign = [] self.scoredict = None def run(self): i,data = self.tasks.get() while i != None: self.log('reading in article ' + str(i) + ': ',1) sourcelist,targetlist,translist1,translist2 = data self.multialign = self.process(sourcelist,targetlist,translist1,translist2) self.scores[i] = (data,self.multialign,self.bleualign,self.scoredict) i,data = self.tasks.get()
rsennrich/Bleualign
bleualign/align.py
Python
gpl-2.0
47,568
# -*- encoding: utf-8 -*- # Copyright (C) 2015 Alejandro López Espinosa (kudrom) import datetime import random class Date(object): """ Descriptor for a date datum """ def __init__(self, variance, **kwargs): """ @param variance is the maximum variance of time allowed for the generation of random data. """ self.variance = variance def generate(self): """ Generates random data for the descriptor. This is called by the DataSchemaManager.generate """ now = datetime.datetime.now().strftime("%s") return int(now) + random.randrange(0, self.variance) def validate(self, data): """ Validates @param data against the descriptor. This is called by the DataSchemaManager.validate """ return True
kudrom/lupulo
lupulo/descriptors/date.py
Python
gpl-2.0
883
#1strand Bushing Tool #Standalone program for minimized cruft import math print "This program is for printing the best possible circular bushings" print "Printer config values are hardcoded for ease of use (for me)" xpath = [] #These are initialized and default values ypath = [] zpath = [] step = [] epath = [] xstart = 10.0 ystart = 10.0 zstart = 0.5 height = 0.0 LayerHeight = 0.3 ExtrusionWidth = 0.6 FilamentDiameter=3 FilamentArea = FilamentDiameter * FilamentDiameter * 3.14159 / 4.0 GooCoefficient = LayerHeight * ExtrusionWidth / FilamentArea configlist = [LayerHeight, ExtrusionWidth, FilamentDiameter, GooCoefficient] BrimDiameter = 0.0 OuterDiameter = 0.0 InnerDiameter = 0.0 N = 1 ActualExtrusionWidth = ExtrusionWidth print "Current values are:" print "LayerHeight =", configlist[0] #This assignment is super important print "ExtrusionWidth=", configlist[1] #and needs to be consistent with print "FilamentDiameter=", configlist[2] #with other code blocks related print "GooCoefficient=", configlist[3] #to these options. BrimDiameter = float(raw_input("Enter brim diameter in mm:")) OuterDiameter = float(raw_input("Enter Outer Diameter in mm:")) InnerDiameter = float(raw_input("Enter Inner Diameter in mm:")) N = int(raw_input("Enter number of line segments in your alleged circles")) anglestep = 2 * math.pi / N print "Angular step is ", anglestep, " radians." height = float(raw_input("Enter Height")) centerx = (BrimDiameter / 2.0)+5 #Center is chosen so brim is 5mm from edge centery = (BrimDiameter / 2.0)+5 #Center is chosen so brim is 5mm from edge thickness = (OuterDiameter-InnerDiameter)/2 perimeters = thickness/ExtrusionWidth print "Thickness = ", thickness print "Needed perimeters = ", perimeters perimeters = int(perimeters) ActualExtrusionWidth = thickness/perimeters print "Revised perimeters = ", perimeters print "Revised extrusion width = ", ActualExtrusionWidth BrimThickness = (BrimDiameter-InnerDiameter)/2 BrimPerimeters = int(BrimThickness/ActualExtrusionWidth) print "Brim Thickness = ", BrimThickness print "Brim Perimeters = ", BrimPerimeters #Brim layer is first, and treated separately. j=0 i=0 radius = BrimDiameter/2 - (j+0.5)*ActualExtrusionWidth xpath.append(centerx+radius) ypath.append(centery) zpath.append(LayerHeight) while (j<BrimPerimeters): radius = BrimDiameter/2 - (j+0.5)*ActualExtrusionWidth j=j+1 i=0 while (i<N): i=i+1 #print "i=", i, "j=", j, "radius=", radius xpath.append(centerx+radius*math.cos(i*anglestep)) ypath.append(centery+radius*math.sin(i*anglestep)) zpath.append(LayerHeight) # # # #Now the actual bushing begins printing. # # # CurrentLayer=1 CurrentHeight=LayerHeight*CurrentLayer #Technically should be earlier but wutev # # # #Now the actual bushing begins printing. # # # #k=0 ##Even layers (1st bushing layer is 2) are inside to outside ##odd layers are outside to inside, to maintain strand continuity #j=0 #i=0 #radius = InnerDiameter/2 + (j-0.5)*ActualExtrusionWidth #xpath.append(centerx+radius) #ypath.append(centery) #zpath.append(CurrentHeight) #while (j<=perimeters): # radius = InnerDiameter/2 + (j-0.5)*ActualExtrusionWidth # j=j+1 # i=0 # while (i<N): # i=i+1 # #print "i=", i, "j=", j, "radius=", radius # xpath.append(centerx+radius*math.cos(i*anglestep)) # ypath.append(centery+radius*math.sin(i*anglestep)) # zpath.append(CurrentHeight) ##odd layers are outside to inside, to maintain strand continuity #CurrentLayer=3 #CurrentHeight=LayerHeight*CurrentLayer #j=0 #i=0 #radius = OuterDiameter/2 - (j+0.5)*ActualExtrusionWidth #xpath.append(centerx+radius) #ypath.append(centery) #zpath.append(CurrentHeight) #while (j<perimeters): # radius = OuterDiameter/2 - (j+0.5)*ActualExtrusionWidth # j=j+1 # i=0 # while (i<N): # i=i+1 # #print "i=", i, "j=", j, "radius=", radius # xpath.append(centerx+radius*math.cos(i*anglestep)) # ypath.append(centery+radius*math.sin(i*anglestep)) # zpath.append(CurrentHeight) while (CurrentLayer*LayerHeight < height): CurrentLayer=CurrentLayer+1 CurrentHeight=LayerHeight*CurrentLayer #Even layers (1st bushing layer is 2) are inside to outside #odd layers are outside to inside, to maintain strand continuity j=1 i=0 radius = InnerDiameter/2 + (j-0.5)*ActualExtrusionWidth xpath.append(centerx+radius) ypath.append(centery) zpath.append(CurrentHeight-LayerHeight*0.75) while (j<=perimeters): radius = InnerDiameter/2 + (j-0.5)*ActualExtrusionWidth j=j+1 i=0 while (i<(N-1)): #kludge i=i+1 #print "i=", i, "j=", j, "layer=", CurrentLayer, "radius=", radius xpath.append(centerx+radius*math.cos(i*anglestep)) ypath.append(centery+radius*math.sin(i*anglestep)) if (i==1 and j==1): zpath.append(CurrentHeight-LayerHeight*.25) else: zpath.append(CurrentHeight) #odd layers are outside to inside, to maintain strand continuity CurrentLayer=CurrentLayer+1 CurrentHeight=LayerHeight*CurrentLayer j=0 i=0 radius = OuterDiameter/2 - (j+0.5)*ActualExtrusionWidth xpath.append(centerx+radius) ypath.append(centery) zpath.append(CurrentHeight-LayerHeight*.75) while (j<perimeters): radius = OuterDiameter/2 - (j+0.5)*ActualExtrusionWidth j=j+1 i=0 while (i<(N-1)): #Same kludge as the even layers. i=i+1 #print "i=", i, "j=", j, "layer=", CurrentLayer, "radius=", radius xpath.append(centerx+radius*math.cos(i*anglestep)) ypath.append(centery+radius*math.sin(i*anglestep)) if (i==1 and j==1): zpath.append(CurrentHeight-LayerHeight*.25) else: zpath.append(CurrentHeight) #Extrusion is only handled here temporarily for testing for x in xrange(len(xpath)): # This initializes the arrays so I can step.append(0.0) #avoid that append() bullshit where I dont epath.append(0.0) #know where I'm writing. for x in xrange(2, len(xpath)): # This calculates how much extruder movement per step distance=((xpath[x]-xpath[x-1])**2+(ypath[x]-ypath[x-1])**2)**0.5 step[x]=distance*GooCoefficient epath[x]=epath[x-1]+step[x] #for x in range(len(xpath)): #Human readable raw output # print xpath[x-1], ypath[x-1], zpath[x-1], step[x-1], epath[x-1] goutput = open("output1.gcode", "wb") #Now save to output1.gcode goutput.write("G28 \nG21 \nG90 \nG92 E0 \nM82") x=0 for x in range(len(xpath)): goutput.write("G1 X" ); goutput.write( str(xpath[x]) ); goutput.write( " Y" ); goutput.write( str(ypath[x]) ); goutput.write( " Z" ); goutput.write( str(zpath[x]) ); goutput.write( " E" ); goutput.write( str(epath[x]) ); goutput.write( " F2000 \n" ); goutput.close()
kanethemediocre/1strand
1strandbushinga002.py
Python
gpl-2.0
6,978
# Portions Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # scmutil.py - Mercurial core utility functions # # Copyright Matt Mackall <mpm@selenic.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from __future__ import absolute_import import errno import glob import hashlib import os import re import socket import subprocess import time import traceback import weakref from . import ( encoding, error, match as matchmod, pathutil, phases, pycompat, revsetlang, similar, smartset, url, util, vfs, visibility, winutil, ) from .i18n import _ from .node import hex, nullid, short, wdirid, wdirrev from .pycompat import basestring, encodeutf8, isint if pycompat.iswindows: from . import scmwindows as scmplatform else: from . import scmposix as scmplatform termsize = scmplatform.termsize # pyre-fixme[39]: `Tuple[Any, ...]` is not a valid parent class. class status(tuple): """Named tuple with a list of files per status. The 'deleted', 'unknown' and 'ignored' properties are only relevant to the working copy. """ __slots__ = () def __new__(cls, modified, added, removed, deleted, unknown, ignored, clean): assert all(isinstance(f, str) for f in modified) assert all(isinstance(f, str) for f in added) assert all(isinstance(f, str) for f in removed) assert all(isinstance(f, str) for f in deleted) assert all(isinstance(f, str) for f in unknown) assert all(isinstance(f, str) for f in ignored) assert all(isinstance(f, str) for f in clean) return tuple.__new__( cls, (modified, added, removed, deleted, unknown, ignored, clean) ) @property def modified(self): """files that have been modified""" return self[0] @property def added(self): """files that have been added""" return self[1] @property def removed(self): """files that have been removed""" return self[2] @property def deleted(self): """files that are in the dirstate, but have been deleted from the working copy (aka "missing") """ return self[3] @property def unknown(self): """files not in the dirstate that are not ignored""" return self[4] @property def ignored(self): """files not in the dirstate that are ignored (by _dirignore())""" return self[5] @property def clean(self): """files that have not been modified""" return self[6] def __repr__(self, *args, **kwargs): return ( "<status modified=%r, added=%r, removed=%r, deleted=%r, " "unknown=%r, ignored=%r, clean=%r>" ) % self def nochangesfound(ui, repo, excluded=None): """Report no changes for push/pull, excluded is None or a list of nodes excluded from the push/pull. """ secretlist = [] if excluded: for n in excluded: ctx = repo[n] if ctx.phase() >= phases.secret: secretlist.append(n) if secretlist: ui.status( _("no changes found (ignored %d secret changesets)\n") % len(secretlist) ) else: ui.status(_("no changes found\n")) def callcatch(ui, func): """call func() with global exception handling return func() if no exception happens. otherwise do some error handling and return an exit code accordingly. does not handle all exceptions. """ try: try: return func() except Exception as ex: # re-raises ui.traceback() # Log error info for all non-zero exits. _uploadtraceback(ui, str(ex), util.smartformatexc()) raise finally: # Print 'remote:' messages before 'abort:' messages. # This also avoids sshpeer.__del__ during Py_Finalize -> GC # on Python 3, which can cause deadlocks waiting for the # stderr reading thread. from . import sshpeer sshpeer.cleanupall() # Global exception handling, alphabetically # Mercurial-specific first, followed by built-in and library exceptions except error.LockHeld as inst: if inst.errno == errno.ETIMEDOUT: reason = _("timed out waiting for lock held by %s") % inst.lockinfo else: reason = _("lock held by %r") % inst.lockinfo ui.warn(_("%s: %s\n") % (inst.desc or inst.filename, reason), error=_("abort")) if not inst.lockinfo: ui.warn(_("(lock might be very busy)\n")) except error.LockUnavailable as inst: ui.warn( _("could not lock %s: %s\n") % (inst.desc or inst.filename, encoding.strtolocal(inst.strerror)), error=_("abort"), ) except error.OutOfBandError as inst: if inst.args: msg = _("remote error:\n") else: msg = _("remote error\n") ui.warn(msg, error=_("abort")) if inst.args: ui.warn("".join(inst.args)) if inst.hint: ui.warn("(%s)\n" % inst.hint) except error.RepoError as inst: ui.warn(_("%s!\n") % inst, error=_("abort")) inst.printcontext(ui) if inst.hint: ui.warn(_("(%s)\n") % inst.hint) except error.ResponseError as inst: ui.warn(inst.args[0], error=_("abort")) if not isinstance(inst.args[1], basestring): ui.warn(" %r\n" % (inst.args[1],)) elif not inst.args[1]: ui.warn(_(" empty string\n")) else: ui.warn("\n%r\n" % util.ellipsis(inst.args[1])) except error.CensoredNodeError as inst: ui.warn(_("file censored %s!\n") % inst, error=_("abort")) except error.CommitLookupError as inst: ui.warn(_("%s!\n") % inst.args[0], error=_("abort")) except error.CertificateError as inst: # This error is definitively due to a problem with the user's client # certificate, so print the configured remediation message. helptext = ui.config("help", "tlsauthhelp") if helptext is None: helptext = _("(run 'hg config auth' to see configured certificates)") ui.warn( _("%s!\n\n%s\n") % (inst.args[0], helptext), error=_("certificate error"), ) except error.TlsError as inst: # This is a generic TLS error that may or may not be due to the user's # client certificate, so print a more generic message about TLS errors. helptext = ui.config("help", "tlshelp") if helptext is None: helptext = _("(is your client certificate valid?)") ui.warn( _("%s!\n\n%s\n") % (inst.args[0], helptext), error=_("tls error"), ) except error.RevlogError as inst: ui.warn(_("%s!\n") % inst, error=_("abort")) inst.printcontext(ui) except error.InterventionRequired as inst: ui.warn("%s\n" % inst) if inst.hint: ui.warn(_("(%s)\n") % inst.hint) return 1 except error.WdirUnsupported: ui.warn(_("working directory revision cannot be specified\n"), error=_("abort")) except error.Abort as inst: ui.warn(_("%s\n") % inst, error=_("abort"), component=inst.component) inst.printcontext(ui) if inst.hint: ui.warn(_("(%s)\n") % inst.hint) return inst.exitcode except (error.IndexedLogError, error.MetaLogError) as inst: ui.warn(_("internal storage is corrupted\n"), error=_("abort")) ui.warn(_(" %s\n\n") % str(inst).replace("\n", "\n ")) ui.warn(_("(this usually happens after hard reboot or system crash)\n")) ui.warn(_("(try '@prog@ doctor' to attempt to fix it)\n")) except error.RustError as inst: if ui.config("ui", "traceback") and inst.args[0].has_metadata(): fault = inst.args[0].fault() transience = inst.args[0].transience() category = inst.args[0].category() typename = inst.args[0].typename() ui.warn( _("error has type name %s, category %s, transience %s, and fault %s\n") % (typename, category, transience, fault) ) raise except error.RevisionstoreError as inst: ui.warn(_("%s\n") % inst, error=_("abort")) except error.NonUTF8PathError as inst: ui.warn(_("%s\n") % str(inst), error=_("abort")) except ImportError as inst: ui.warn(_("%s!\n") % inst, error=_("abort")) m = str(inst).split()[-1] if m in "mpatch bdiff".split(): ui.warn(_("(did you forget to compile extensions?)\n")) elif m in "zlib".split(): ui.warn(_("(is your Python install correct?)\n")) except IOError as inst: if util.safehasattr(inst, "code"): ui.warn(_("%s\n") % inst, error=_("abort")) elif util.safehasattr(inst, "reason"): try: # usually it is in the form (errno, strerror) reason = inst.reason.args[1] except (AttributeError, IndexError): # it might be anything, for example a string reason = inst.reason if isinstance(reason, pycompat.unicode): # SSLError of Python 2.7.9 contains a unicode reason = encoding.unitolocal(reason) ui.warn(_("error: %s\n") % reason, error=_("abort")) elif ( util.safehasattr(inst, "args") and inst.args and inst.args[0] == errno.EPIPE ): pass elif getattr(inst, "strerror", None): filename = getattr(inst, "filename", None) if filename: ui.warn( _("%s: %s\n") % (encoding.strtolocal(inst.strerror), inst.filename), error=_("abort"), ) else: ui.warn( _("%s\n") % encoding.strtolocal(inst.strerror), error=_("abort") ) if not pycompat.iswindows: # For permission errors on POSIX. Show more information about the # current user, group, and stat results. num = getattr(inst, "errno", None) if filename is not None and num in {errno.EACCES, errno.EPERM}: if util.istest(): uid = 42 else: uid = os.getuid() ui.warn(_("(current process runs with uid %s)\n") % uid) _printstat(ui, filename) _printstat(ui, os.path.dirname(filename)) else: ui.warn(_("%s\n") % inst, error=_("abort")) except OSError as inst: if getattr(inst, "filename", None) is not None: ui.warn( _("%s: %s\n") % (encoding.strtolocal(inst.strerror), inst.filename), error=_("abort"), ) else: ui.warn(_("%s\n") % encoding.strtolocal(inst.strerror), error=_("abort")) except MemoryError: ui.warn(_("out of memory\n"), error=_("abort")) except SystemExit as inst: # Commands shouldn't sys.exit directly, but give a return code. # Just in case catch this and pass exit code to caller. return inst.code except socket.error as inst: ui.warn(_("%s\n") % inst.args[-1], error=_("abort")) except Exception as e: if type(e).__name__ == "TApplicationException": ui.warn(_("ThriftError: %s\n") % e, error=_("abort")) ui.warn(_("(try 'eden doctor' to diagnose this issue)\n")) else: raise return -1 def _uploadtraceback(ui, message, trace): key = "flat/errortrace-%(host)s-%(pid)s-%(time)s" % { "host": socket.gethostname(), "pid": os.getpid(), "time": time.time(), } payload = message + "\n\n" + trace # TODO: Move this into a background task that renders from # blackbox instead. ui.log("errortrace", "Trace:\n%s\n", trace, key=key, payload=payload) ui.log("errortracekey", "Trace key:%s\n", key, errortracekey=key) def _printstat(ui, path): """Attempt to print filesystem stat information on path""" if util.istest(): mode = uid = gid = 42 else: try: st = os.stat(path) mode = st.st_mode uid = st.st_uid gid = st.st_gid except Exception: return ui.warn(_("(%s: mode 0o%o, uid %s, gid %s)\n") % (path, mode, uid, gid)) def checknewlabel(repo, lbl, kind): # Do not use the "kind" parameter in ui output. # It makes strings difficult to translate. if lbl in ["tip", ".", "null"]: raise error.Abort(_("the name '%s' is reserved") % lbl) for c in (":", "\0", "\n", "\r"): if c in lbl: raise error.Abort(_("%r cannot be used in a name") % c) try: int(lbl) raise error.Abort(_("cannot use an integer as a name")) except ValueError: pass def checkfilename(f): """Check that the filename f is an acceptable filename for a tracked file""" if "\r" in f or "\n" in f: raise error.Abort(_("'\\n' and '\\r' disallowed in filenames: %r") % f) def checkportable(ui, f): """Check if filename f is portable and warn or abort depending on config""" checkfilename(f) abort, warn = checkportabilityalert(ui) if abort or warn: msg = winutil.checkwinfilename(f) if msg: msg = "%s: %s" % (msg, util.shellquote(f)) if abort: raise error.Abort(msg) ui.warn(_("%s\n") % msg, notice=_("warning")) def checkportabilityalert(ui): """check if the user's config requests nothing, a warning, or abort for non-portable filenames""" val = ui.config("ui", "portablefilenames") lval = val.lower() bval = util.parsebool(val) abort = lval == "abort" warn = bval or lval == "warn" if bval is None and not (warn or abort or lval == "ignore"): raise error.ConfigError(_("ui.portablefilenames value is invalid ('%s')") % val) return abort, warn class casecollisionauditor(object): def __init__(self, ui, abort, dirstate): self._ui = ui self._abort = abort if not dirstate._istreestate and not dirstate._istreedirstate: allfiles = "\0".join(dirstate._map) self._loweredfiles = set(encoding.lower(allfiles).split("\0")) else: # Still need an in-memory set to collect files being tested, but # haven't been added to treestate yet. self._loweredfiles = set() self._dirstate = dirstate # The purpose of _newfiles is so that we don't complain about # case collisions if someone were to call this object with the # same filename twice. self._newfiles = set() def __call__(self, f): if f in self._newfiles: return fl = encoding.lower(f) ds = self._dirstate shouldwarn = False if ds._istreestate or ds._istreedirstate: dmap = ds._map candidates = dmap.getfiltered(fl, encoding.lower) # Note: fl might be outside dirstate, but got "tested" here. In # that case, the next "if" would catch it. shouldwarn = any(f not in ds and candidate != f for candidate in candidates) if not shouldwarn: shouldwarn = fl in self._loweredfiles and f not in ds self._loweredfiles.add(fl) if shouldwarn: msg = _("possible case-folding collision for %s") % f if self._abort: raise error.Abort(msg) self._ui.warn(_("%s\n") % msg, notice=_("warning")) self._newfiles.add(f) def walkrepos(path, followsym=False, seen_dirs=None, recurse=False): """yield every hg repository under path, always recursively. The recurse flag will only control recursion into repo working dirs""" def errhandler(err): if err.filename == path: raise err samestat = getattr(os.path, "samestat", None) if followsym and samestat is not None: def adddir(dirlst, dirname): match = False dirstat = util.stat(dirname) for lstdirstat in dirlst: if samestat(dirstat, lstdirstat): match = True break if not match: dirlst.append(dirstat) return not match else: followsym = False if (seen_dirs is None) and followsym: seen_dirs = [] adddir(seen_dirs, path) for root, dirs, files in os.walk(path, topdown=True, onerror=errhandler): dirs.sort() if ".hg" in dirs: yield root # found a repository qroot = os.path.join(root, ".hg", "patches") if os.path.isdir(os.path.join(qroot, ".hg")): yield qroot # we have a patch queue repo here if recurse: # avoid recursing inside the .hg directory dirs.remove(".hg") else: dirs[:] = [] # don't descend further elif followsym: newdirs = [] for d in dirs: fname = os.path.join(root, d) if adddir(seen_dirs, fname): if os.path.islink(fname): for hgname in walkrepos(fname, True, seen_dirs): yield hgname else: newdirs.append(d) dirs[:] = newdirs def binnode(ctx): """Return binary node id for a given basectx""" node = ctx.node() if node is None: return wdirid return node def intrev(ctx): """Return integer for a given basectx that can be used in comparison or arithmetic operation""" rev = ctx.rev() if rev is None: return wdirrev return rev def formatchangeid(ctx): """Format changectx as '{node|formatnode}', which is the default template provided by cmdutil.changeset_templater """ repo = ctx.repo() ui = repo.ui if ui.debugflag: hexfunc = hex else: hexfunc = short return hexfunc(binnode(ctx)) def revsingle(repo, revspec, default=".", localalias=None): """Resolve a single revset with user-defined revset aliases. This should only be used for resolving user-provided command-line flags or arguments. For internal code paths not interacting with user-provided arguments, use repo.revs (ignores user-defined revset aliases) or repo.anyrevs (respects user-defined revset aliases) instead. """ if not revspec and revspec != 0: return repo[default] # Used by amend/common calling rebase.rebase with non-string opts. if isint(revspec): return repo[revspec] l = revrange(repo, [revspec], localalias=localalias) if not l: raise error.Abort(_("empty revision set")) return repo[l.last()] def _pairspec(revspec): tree = revsetlang.parse(revspec) return tree and tree[0] in ("range", "rangepre", "rangepost", "rangeall") def revpair(repo, revs): if not revs: return repo.dirstate.p1(), None l = revrange(repo, revs) if not l: first = second = None elif l.isascending(): first = l.min() second = l.max() elif l.isdescending(): first = l.max() second = l.min() else: first = l.first() second = l.last() if first is None: raise error.Abort(_("empty revision range")) if ( first == second and len(revs) >= 2 and not all(revrange(repo, [r]) for r in revs) ): raise error.Abort(_("empty revision on one side of range")) # if top-level is range expression, the result must always be a pair if first == second and len(revs) == 1 and not _pairspec(revs[0]): return repo.lookup(first), None return repo.lookup(first), repo.lookup(second) def revrange(repo, specs, localalias=None): """Execute 1 to many revsets and return the union. This is the preferred mechanism for executing revsets using user-specified config options, such as revset aliases. The revsets specified by ``specs`` will be executed via a chained ``OR`` expression. If ``specs`` is empty, an empty result is returned. ``specs`` can contain integers, in which case they are assumed to be revision numbers. It is assumed the revsets are already formatted. If you have arguments that need to be expanded in the revset, call ``revsetlang.formatspec()`` and pass the result as an element of ``specs``. Specifying a single revset is allowed. Returns a ``revset.abstractsmartset`` which is a list-like interface over integer revisions. This should only be used for resolving user-provided command-line flags or arguments. For internal code paths not interacting with user-provided arguments, use repo.revs (ignores user-defined revset aliases) or repo.anyrevs (respects user-defined revset aliases) instead. """ # Used by amend/common calling rebase.rebase with non-string opts. if isinstance(specs, smartset.abstractsmartset): return specs allspecs = [] for spec in specs: if isint(spec): # specs are usually strings. int means legacy code using rev # numbers. revsetlang no longer accepts int revs. Wrap it before # passing to revsetlang. spec = revsetlang.formatspec("%d", spec) allspecs.append(spec) legacyrevnum = repo.ui.config("devel", "legacy.revnum") with repo.ui.configoverride({("devel", "legacy.revnum:real"): legacyrevnum}): return repo.anyrevs(allspecs, user=True, localalias=localalias) def expandpats(pats): """Expand bare globs when running on windows. On posix we assume it already has already been done by sh.""" if not util.expandglobs: return list(pats) ret = [] for kindpat in pats: kind, pat = matchmod._patsplit(kindpat, None) if kind is None: try: globbed = glob.glob(pat) except re.error: globbed = [pat] if globbed: ret.extend(globbed) continue ret.append(kindpat) return ret def matchandpats( ctx, pats=(), opts=None, globbed=False, default="relpath", badfn=None, emptyalways=True, ): """Return a matcher and the patterns that were used. The matcher will warn about bad matches, unless an alternate badfn callback is provided.""" if pats == ("",): pats = [] if opts is None: opts = {} if not globbed and default == "relpath": pats = expandpats(pats or []) def bad(f, msg): ctx.repo().ui.warn("%s: %s\n" % (m.rel(f), msg)) if badfn is None: badfn = bad m = ctx.match( pats, opts.get("include"), opts.get("exclude"), default, badfn=badfn, emptyalways=emptyalways, ) if m.always(): pats = [] return m, pats def match( ctx, pats=(), opts=None, globbed=False, default="relpath", badfn=None, emptyalways=True, ): """Return a matcher that will warn about bad matches.""" return matchandpats( ctx, pats, opts, globbed, default, badfn=badfn, emptyalways=emptyalways )[0] def matchall(repo): """Return a matcher that will efficiently match everything.""" return matchmod.always(repo.root, repo.getcwd()) def matchfiles(repo, files, badfn=None): """Return a matcher that will efficiently match exactly these files.""" return matchmod.exact(repo.root, repo.getcwd(), files, badfn=badfn) def parsefollowlinespattern(repo, rev, pat, msg): """Return a file name from `pat` pattern suitable for usage in followlines logic. """ if not matchmod.patkind(pat): return pathutil.canonpath(repo.root, repo.getcwd(), pat) else: ctx = repo[rev] m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=ctx) files = [f for f in ctx if m(f)] if len(files) != 1: raise error.ParseError(msg) return files[0] def origpath(ui, repo, filepath): """customize where .orig files are created Fetch user defined path from config file: [ui] origbackuppath = <path> Fall back to default (filepath with .orig suffix) if not specified """ origbackuppath = ui.config("ui", "origbackuppath") if not origbackuppath: return filepath + ".orig" # Convert filepath from an absolute path into a path inside the repo. filepathfromroot = util.normpath(os.path.relpath(filepath, start=repo.root)) origvfs = vfs.vfs(repo.wjoin(origbackuppath)) origbackupdir = origvfs.dirname(filepathfromroot) if not origvfs.isdir(origbackupdir) or origvfs.islink(origbackupdir): ui.note(_("creating directory: %s\n") % origvfs.join(origbackupdir)) # Remove any files that conflict with the backup file's path for f in reversed(list(util.finddirs(filepathfromroot))): if origvfs.isfileorlink(f): ui.note(_("removing conflicting file: %s\n") % origvfs.join(f)) origvfs.unlink(f) break origvfs.makedirs(origbackupdir) if origvfs.isdir(filepathfromroot) and not origvfs.islink(filepathfromroot): ui.note( _("removing conflicting directory: %s\n") % origvfs.join(filepathfromroot) ) origvfs.rmtree(filepathfromroot, forcibly=True) return origvfs.join(filepathfromroot) class _containsnode(object): """proxy __contains__(node) to container.__contains__ which accepts revs""" def __init__(self, repo, revcontainer): self._torev = repo.changelog.rev self._revcontains = revcontainer.__contains__ def __contains__(self, node): return self._revcontains(self._torev(node)) def cleanupnodes(repo, replacements, operation, moves=None, metadata=None): """do common cleanups when old nodes are replaced by new nodes That includes writing obsmarkers or stripping nodes, and moving bookmarks. (we might also want to move working directory parent in the future) By default, bookmark moves are calculated automatically from 'replacements', but 'moves' can be used to override that. Also, 'moves' may include additional bookmark moves that should not have associated obsmarkers. replacements is {oldnode: [newnode]} or a iterable of nodes if they do not have replacements. operation is a string, like "rebase". metadata is dictionary containing metadata to be stored in obsmarker if obsolescence is enabled. Return the calculated 'moves' mapping that is from a single old node to a single new node. """ if not replacements and not moves: return {} # translate mapping's other forms if not util.safehasattr(replacements, "items"): replacements = {n: () for n in replacements} # Calculate bookmark movements if moves is None: moves = {} # Unfiltered repo is needed since nodes in replacements might be hidden. unfi = repo for oldnode, newnodes in replacements.items(): if oldnode in moves: continue if len(newnodes) > 1: # usually a split, take the one with biggest rev number newnode = next(unfi.set("max(%ln)", newnodes)).node() elif len(newnodes) == 0: # Handle them in a second loop continue else: newnode = newnodes[0] moves[oldnode] = newnode # Move bookmarks pointing to stripped commits backwards. # If hit a replaced node, use the replacement. def movebackwards(node): p1 = unfi.changelog.parents(node)[0] if p1 == nullid: return p1 elif p1 in moves: return moves[p1] elif p1 in replacements: return movebackwards(p1) else: return p1 for oldnode, newnodes in replacements.items(): if oldnode in moves: continue assert len(newnodes) == 0 moves[oldnode] = movebackwards(oldnode) with repo.transaction("cleanup") as tr: # Move bookmarks bmarks = repo._bookmarks bmarkchanges = [] allnewnodes = [n for ns in replacements.values() for n in ns] for oldnode, newnode in moves.items(): oldbmarks = repo.nodebookmarks(oldnode) if not oldbmarks: continue from . import bookmarks # avoid import cycle repo.ui.debug( "moving bookmarks %r from %s to %s\n" % (oldbmarks, hex(oldnode), hex(newnode)) ) # Delete divergent bookmarks being parents of related newnodes deleterevs = repo.revs( "parents(roots(%ln & (::%n))) - parents(%n)", allnewnodes, newnode, oldnode, ) deletenodes = _containsnode(repo, deleterevs) for name in oldbmarks: bmarkchanges.append((name, newnode)) for b in bookmarks.divergent2delete(repo, deletenodes, name): bmarkchanges.append((b, None)) if bmarkchanges: bmarks.applychanges(repo, tr, bmarkchanges) # adjust visibility, or strip nodes strip = True if visibility.tracking(repo): visibility.remove(repo, replacements.keys()) strip = False if strip: from . import repair # avoid import cycle tostrip = list(replacements) if tostrip: repair.delayedstrip(repo.ui, repo, tostrip, operation) return moves def addremove(repo, matcher, prefix, opts=None, dry_run=None, similarity=None): if opts is None: opts = {} m = matcher if dry_run is None: dry_run = opts.get("dry_run") if similarity is None: similarity = float(opts.get("similarity") or 0) ret = 0 rejected = [] def badfn(f, msg): if f in m.files(): m.bad(f, msg) rejected.append(f) badmatch = matchmod.badmatch(m, badfn) added, unknown, deleted, removed, forgotten = _interestingfiles(repo, badmatch) unknownset = set(unknown + forgotten) toprint = unknownset.copy() toprint.update(deleted) for abs in sorted(toprint): if repo.ui.verbose or not m.exact(abs): if abs in unknownset: status = _("adding %s\n") % m.uipath(abs) else: status = _("removing %s\n") % m.uipath(abs) repo.ui.status(status) renames = _findrenames(repo, m, added + unknown, removed + deleted, similarity) if not dry_run: _markchanges(repo, unknown + forgotten, deleted, renames) for f in rejected: if f in m.files(): return 1 return ret def marktouched(repo, files, similarity=0.0): """Assert that files have somehow been operated upon. files are relative to the repo root.""" m = matchfiles(repo, files, badfn=lambda x, y: rejected.append(x)) rejected = [] added, unknown, deleted, removed, forgotten = _interestingfiles(repo, m) if repo.ui.verbose: unknownset = set(unknown + forgotten) toprint = unknownset.copy() toprint.update(deleted) for abs in sorted(toprint): if abs in unknownset: status = _("adding %s\n") % abs else: status = _("removing %s\n") % abs repo.ui.status(status) renames = _findrenames(repo, m, added + unknown, removed + deleted, similarity) _markchanges(repo, unknown + forgotten, deleted, renames) for f in rejected: if f in m.files(): return 1 return 0 def _interestingfiles(repo, matcher): """Walk dirstate with matcher, looking for files that addremove would care about. This is different from dirstate.status because it doesn't care about whether files are modified or clean.""" removed, forgotten = [], [] audit_path = pathutil.pathauditor(repo.root, cached=True) dirstate = repo.dirstate exists = repo.wvfs.isfileorlink status = dirstate.status(matcher, False, False, True) unknown = [file for file in status.unknown if audit_path.check(file)] for file in status.removed: # audit here to make sure "file" hasn't reappeared behind a symlink if exists(file) and audit_path.check(file): if dirstate.normalize(file) == file: forgotten.append(file) else: removed.append(file) else: removed.append(file) # The user may have specified ignored files. It's expensive to compute them # via status, so let's manually add them here. ignored = repo.dirstate._ignore unknown.extend( file for file in matcher.files() if ignored(file) and repo.wvfs.isfileorlink(file) and audit_path.check(file) ) return status.added, unknown, status.deleted, removed, forgotten def _findrenames(repo, matcher, added, removed, similarity): """Find renames from removed files to added ones.""" renames = {} if similarity > 0: for old, new, score in similar.findrenames(repo, added, removed, similarity): if repo.ui.verbose or not matcher.exact(old) or not matcher.exact(new): repo.ui.status( _("recording removal of %s as rename to %s " "(%d%% similar)\n") % (matcher.rel(old), matcher.rel(new), score * 100) ) renames[new] = old return renames def _markchanges(repo, unknown, deleted, renames): """Marks the files in unknown as added, the files in deleted as removed, and the files in renames as copied.""" wctx = repo[None] with repo.wlock(): wctx.forget(deleted) wctx.add(unknown) for new, old in pycompat.iteritems(renames): wctx.copy(old, new) def dirstatecopy(ui, repo, wctx, src, dst, dryrun=False, cwd=None): """Update the dirstate to reflect the intent of copying src to dst. For different reasons it might not end with dst being marked as copied from src. """ origsrc = repo.dirstate.copied(src) or src if dst == origsrc: # copying back a copy? if repo.dirstate[dst] not in "mn" and not dryrun: repo.dirstate.normallookup(dst) else: if repo.dirstate[origsrc] == "a" and origsrc == src: if not ui.quiet: ui.warn( _( "%s has not been committed yet, so no copy " "data will be stored for %s.\n" ) % (repo.pathto(origsrc, cwd), repo.pathto(dst, cwd)) ) if repo.dirstate[dst] in "?r" and not dryrun: wctx.add([dst]) elif not dryrun: wctx.copy(origsrc, dst) def readrequires(opener, supported=None): """Reads and parses .hg/requires or .hg/store/requires and checks if all entries found are in the list of supported features. If supported is None, read all features without checking. """ requirements = set(opener.readutf8("requires").splitlines()) missings = [] if supported: for r in requirements: if r not in supported: if not r or not r[0].isalnum(): raise error.RequirementError( _("%s file is corrupt") % opener.join("requires") ) missings.append(r) missings.sort() if missings: raise error.RequirementError( _("repository requires features unknown to this Mercurial: %s") % " ".join(missings), hint=_( "see https://mercurial-scm.org/wiki/MissingRequirement" " for more information" ), ) return requirements def writerequires(opener, requirements): content = "".join("%s\n" % r for r in sorted(requirements)) opener.writeutf8("requires", content) class filecachesubentry(object): def __init__(self, path, stat): self.path = path self.cachestat = None if stat: path = self.path else: path = None self.cachestat = filecachesubentry.stat(path) def refresh(self): self.cachestat = filecachesubentry.stat(self.path) def changed(self): newstat = filecachesubentry.stat(self.path) if self.cachestat != newstat: self.cachestat = newstat return True else: return False @staticmethod def stat(path): return util.cachestat(path) class filecacheentry(object): def __init__(self, paths, stat=True): self._entries = [] for path in paths: self._entries.append(filecachesubentry(path, stat)) def changed(self): """true if any entry has changed""" for entry in self._entries: if entry.changed(): return True return False def refresh(self): for entry in self._entries: entry.refresh() class filecache(object): """A property like decorator that tracks files under .hg/ for updates. Records stat info when called in _filecache. On subsequent calls, compares old stat info with new info, and recreates the object when any of the files changes, updating the new stat info in _filecache. Mercurial either atomic renames or appends for files under .hg, so to ensure the cache is reliable we need the filesystem to be able to tell us if a file has been replaced. If it can't, we fallback to recreating the object on every call (essentially the same behavior as propertycache). """ def __init__(self, *paths): self.paths = [ path if isinstance(path, tuple) else (path, self.join) for path in paths ] def join(self, obj, fname): """Used to compute the runtime path of a cached file. Users should subclass filecache and provide their own version of this function to call the appropriate join function on 'obj' (an instance of the class that its member function was decorated). """ raise NotImplementedError def __call__(self, func): self.func = func self.name = func.__name__ return self def __get__(self, obj, type=None): # if accessed on the class, return the descriptor itself. if obj is None: return self # do we need to check if the file changed? if self.name in obj.__dict__: assert self.name in obj._filecache, self.name return obj.__dict__[self.name] entry = obj._filecache.get(self.name) if entry: if entry.changed(): entry.obj = self.func(obj) else: paths = [joiner(obj, path) for (path, joiner) in self.paths] # We stat -before- creating the object so our cache doesn't lie if # a writer modified between the time we read and stat entry = filecacheentry(paths, True) entry.obj = self.func(obj) obj._filecache[self.name] = entry obj.__dict__[self.name] = entry.obj return entry.obj def __set__(self, obj, value): if self.name not in obj._filecache: # we add an entry for the missing value because X in __dict__ # implies X in _filecache paths = [joiner(obj, path) for (path, joiner) in self.paths] ce = filecacheentry(paths, False) obj._filecache[self.name] = ce else: ce = obj._filecache[self.name] ce.obj = value # update cached copy obj.__dict__[self.name] = value # update copy returned by obj.x def __delete__(self, obj): try: del obj.__dict__[self.name] except KeyError: raise AttributeError(self.name) def extdatasource(repo, source): """Gather a map of rev -> value dict from the specified source A source spec is treated as a URL, with a special case shell: type for parsing the output from a shell command. The data is parsed as a series of newline-separated records where each record is a revision specifier optionally followed by a space and a freeform string value. If the revision is known locally, it is converted to a rev, otherwise the record is skipped. Note that both key and value are treated as UTF-8 and converted to the local encoding. This allows uniformity between local and remote data sources. """ spec = repo.ui.config("extdata", source) if not spec: raise error.Abort(_("unknown extdata source '%s'") % source) data = {} src = proc = None try: if spec.startswith("shell:"): # external commands should be run relative to the repo root cmd = spec[6:] proc = subprocess.Popen( cmd, shell=True, bufsize=-1, close_fds=util.closefds, stdout=subprocess.PIPE, cwd=repo.root, ) src = proc.stdout else: # treat as a URL or file src = url.open(repo.ui, spec) for l in src: if b" " in l: k, v = l.strip().split(b" ", 1) else: k, v = l.strip(), b"" k = k.decode("utf8") try: data[repo[k].rev()] = v.decode("utf8") except (error.LookupError, error.RepoLookupError): pass # we ignore data for nodes that don't exist locally finally: if proc: proc.communicate() if src: src.close() if proc and proc.returncode != 0: raise error.Abort( _("extdata command '%s' failed: %s") % (cmd, util.explainexit(proc.returncode)[0]) ) return data def gdinitconfig(ui): """helper function to know if a repo should be created as general delta""" # experimental config: format.generaldelta return ui.configbool("format", "generaldelta") or ui.configbool( "format", "usegeneraldelta" ) def gddeltaconfig(ui): """helper function to know if incoming delta should be optimised""" # experimental config: format.generaldelta return ui.configbool("format", "generaldelta") class simplekeyvaluefile(object): """A simple file with key=value lines Keys must be alphanumerics and start with a letter, values must not contain '\n' characters""" firstlinekey = "__firstline" def __init__(self, vfs, path, keys=None): self.vfs = vfs self.path = path def read(self, firstlinenonkeyval=False): """Read the contents of a simple key-value file 'firstlinenonkeyval' indicates whether the first line of file should be treated as a key-value pair or reuturned fully under the __firstline key.""" lines = self.vfs.readutf8(self.path).splitlines(True) d = {} if firstlinenonkeyval: if not lines: e = _("empty simplekeyvalue file") raise error.CorruptedState(e) # we don't want to include '\n' in the __firstline d[self.firstlinekey] = lines[0][:-1] del lines[0] try: # the 'if line.strip()' part prevents us from failing on empty # lines which only contain '\n' therefore are not skipped # by 'if line' updatedict = dict(line[:-1].split("=", 1) for line in lines if line.strip()) if self.firstlinekey in updatedict: e = _("%r can't be used as a key") raise error.CorruptedState(e % self.firstlinekey) d.update(updatedict) except ValueError as e: raise error.CorruptedState(str(e)) return d def write(self, data, firstline=None): """Write key=>value mapping to a file data is a dict. Keys must be alphanumerical and start with a letter. Values must not contain newline characters. If 'firstline' is not None, it is written to file before everything else, as it is, not in a key=value form""" lines = [] if firstline is not None: lines.append("%s\n" % firstline) for k, v in data.items(): if k == self.firstlinekey: e = "key name '%s' is reserved" % self.firstlinekey raise error.ProgrammingError(e) if not k[0].isalpha(): e = "keys must start with a letter in a key-value file" raise error.ProgrammingError(e) if not k.isalnum(): e = "invalid key name in a simple key-value file" raise error.ProgrammingError(e) if "\n" in v: e = "invalid value in a simple key-value file" raise error.ProgrammingError(e) lines.append("%s=%s\n" % (k, v)) with self.vfs(self.path, mode="wb", atomictemp=True) as fp: fp.write("".join(lines).encode("utf-8")) def nodesummaries(repo, nodes, maxnumnodes=4): if len(nodes) <= maxnumnodes or repo.ui.verbose: return " ".join(short(h) for h in nodes) first = " ".join(short(h) for h in nodes[:maxnumnodes]) return _("%s and %d others") % (first, len(nodes) - maxnumnodes) def wrapconvertsink(sink): """Allow extensions to wrap the sink returned by convcmd.convertsink() before it is used, whether or not the convert extension was formally loaded. """ return sink def contextnodesupportingwdir(ctx): """Returns `ctx`'s node, or `wdirid` if it is a `workingctx`. Alas, `workingxtx.node()` normally returns None, necessitating this convinience function for when you need to serialize the workingxctx. `repo[wdirid]` works fine so there's no need the reverse function. """ from edenscm.mercurial import context if isinstance(ctx, context.workingctx): return wdirid # Neither `None` nor `wdirid` feels right here: if isinstance(ctx, context.overlayworkingctx): raise error.ProgrammingError( "contextnodesupportingwdir doesn't support " "overlayworkingctx" ) return ctx.node() def trackrevnumfortests(repo, specs): """Attempt to collect information to replace revision number with revset expressions in tests. This works with the TESTFILE and TESTLINE environment variable set by run-tests.py. Information will be written to $TESTDIR/.testrevnum. """ if not util.istest(): return trackrevnum = encoding.environ.get("TRACKREVNUM") testline = encoding.environ.get("TESTLINE") testfile = encoding.environ.get("TESTFILE") testdir = encoding.environ.get("TESTDIR") if not trackrevnum or not testline or not testfile or not testdir: return for spec in specs: # 'spec' should be in sys.argv if not any(spec in a for a in pycompat.sysargv): continue # Consider 'spec' as a revision number. rev = int(spec) if rev < -1: continue ctx = repo[rev] if not ctx: return # Check candidate revset expressions. candidates = [] if rev == -1: candidates.append("null") desc = ctx.description() if desc: candidates.append("desc(%s)" % desc.split()[0]) candidates.append("max(desc(%s))" % desc.split()[0]) candidates.append("%s" % ctx.hex()) for candidate in candidates: try: nodes = list(repo.nodes(candidate)) except Exception: continue if nodes == [ctx.node()]: with open(testdir + "/.testrevnum", "ab") as f: f.write( "fix(%r, %s, %r, %r)\n" % (testfile, testline, spec, candidate) ) break def revf64encode(rev): """Convert rev to within f64 "safe" range. This avoids issues that JSON cannot represent the revs precisely. """ if rev is not None and rev >= 0x100000000000000: rev -= 0xFF000000000000 return rev def revf64decode(rev): """Convert rev encoded by revf64encode back to the original rev >>> revs = [i + j for i in [0, 1 << 56] for j in range(2)] + [None] >>> encoded = [revf64encode(i) for i in revs] >>> decoded = [revf64decode(i) for i in encoded] >>> revs == decoded True """ if rev is not None and 0x1000000000000 <= rev < 0x100000000000000: rev += 0xFF000000000000 return rev def setup(ui): if not ui.configbool("experimental", "revf64compat"): # Disable f64 compatibility global revf64encode def revf64encode(rev): return rev
facebookexperimental/eden
eden/scm/edenscm/mercurial/scmutil.py
Python
gpl-2.0
49,777
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014, 2015 CERN. # # Invenio 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. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ Test unit for the miscutil/mailutils module. """ from invenio_ext.registry import DictModuleAutoDiscoverySubRegistry from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite from flask_registry import ImportPathRegistry, RegistryError class TestDictModuleAutoDiscoverySubRegistry(InvenioTestCase): def test_registration(self): r = self.app.extensions['registry'] r['testpkgs'] = ImportPathRegistry( initial=['invenio.testsuite.test_apps'] ) assert len(r['testpkgs']) == 1 r['myns'] = \ DictModuleAutoDiscoverySubRegistry( 'last', keygetter=lambda k, v, new_v: k if k else v.__name__, app=self.app, registry_namespace='testpkgs' ) assert len(r['myns']) == 1 from invenio.testsuite.test_apps.last import views assert r['myns']['invenio.testsuite.test_apps.last.views'] == \ views self.assertRaises( RegistryError, DictModuleAutoDiscoverySubRegistry, 'last', app=self.app, registry_namespace='testpkgs' ) # Register simple object class TestObject(object): pass r['myns'].register(TestObject) # Identical keys raises RegistryError self.assertRaises( RegistryError, r['myns'].register, TestObject ) r['myns'].unregister('TestObject') assert 'TestObject' not in r['myns'] r['myns']['mykey'] = TestObject assert TestObject == r['myns']['mykey'] assert len(r['myns'].items()) == 2 TEST_SUITE = make_test_suite(TestDictModuleAutoDiscoverySubRegistry) if __name__ == "__main__": run_test_suite(TEST_SUITE)
jirikuncar/invenio-ext
tests/test_ext_registry.py
Python
gpl-2.0
2,613
""" The MIT License Copyright (c) 2007 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import urllib import time import random import urlparse import hmac import binascii import httplib2 try: from urlparse import parse_qs, parse_qsl except ImportError: from cgi import parse_qs, parse_qsl VERSION = '1.0' # Hi Blaine! HTTP_METHOD = 'GET' SIGNATURE_METHOD = 'PLAINTEXT' class Error(RuntimeError): """Generic exception class.""" def __init__(self, message='OAuth error occured.'): self._message = message @property def message(self): """A hack to get around the deprecation errors in 2.6.""" return self._message def __str__(self): return self._message class MissingSignature(Error): pass def build_authenticate_header(realm=''): """Optional WWW-Authenticate header (401 error)""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def escape(s): """Escape a URL including any /.""" return urllib.quote(s, safe='~') def generate_timestamp(): """Get seconds since epoch (UTC).""" return int(time.time()) def generate_nonce(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) def generate_verifier(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) class Consumer(object): """A consumer of OAuth-protected services. The OAuth consumer is a "third-party" service that wants to access protected resources from an OAuth service provider on behalf of an end user. It's kind of the OAuth client. Usually a consumer must be registered with the service provider by the developer of the consumer software. As part of that process, the service provider gives the consumer a *key* and a *secret* with which the consumer software can identify itself to the service. The consumer will include its key in each request to identify itself, but will use its secret only when signing requests, to prove that the request is from that particular registered consumer. Once registered, the consumer can then use its consumer credentials to ask the service provider for a request token, kicking off the OAuth authorization process. """ key = None secret = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def __str__(self): data = { 'oauth_consumer_key': self.key, 'oauth_consumer_secret': self.secret } return urllib.urlencode(data) class Token(object): """An OAuth credential used to request authorization or a protected resource. Tokens in OAuth comprise a *key* and a *secret*. The key is included in requests to identify the token being used, but the secret is used only in the signature, to prove that the requester is who the server gave the token to. When first negotiating the authorization, the consumer asks for a *request token* that the live user authorizes with the service provider. The consumer then exchanges the request token for an *access token* that can be used to access protected resources. """ key = None secret = None callback = None callback_confirmed = None verifier = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def set_callback(self, callback): self.callback = callback self.callback_confirmed = 'true' def set_verifier(self, verifier=None): if verifier is not None: self.verifier = verifier else: self.verifier = generate_verifier() def get_callback_url(self): if self.callback and self.verifier: # Append the oauth_verifier. parts = urlparse.urlparse(self.callback) scheme, netloc, path, params, query, fragment = parts[:6] if query: query = '%s&oauth_verifier=%s' % (query, self.verifier) else: query = 'oauth_verifier=%s' % self.verifier return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) return self.callback def to_string(self): """Returns this token as a plain string, suitable for storage. The resulting string includes the token's secret, so you should never send or store this string where a third party can read it. """ data = { 'oauth_token': self.key, 'oauth_token_secret': self.secret, } if self.callback_confirmed is not None: data['oauth_callback_confirmed'] = self.callback_confirmed return urllib.urlencode(data) @staticmethod def from_string(s): """Deserializes a token from a string like one returned by `to_string()`.""" if not len(s): raise ValueError("Invalid parameter string.") params = parse_qs(s, keep_blank_values=False) if not len(params): raise ValueError("Invalid parameter string.") try: key = params['oauth_token'][0] except Exception: raise ValueError("'oauth_token' not found in OAuth request.") try: secret = params['oauth_token_secret'][0] except Exception: raise ValueError("'oauth_token_secret' not found in " "OAuth request.") token = Token(key, secret) try: token.callback_confirmed = params['oauth_callback_confirmed'][0] except KeyError: pass # 1.0, no callback confirmed. return token def __str__(self): return self.to_string() def setter(attr): name = attr.__name__ def getter(self): try: return self.__dict__[name] except KeyError: raise AttributeError(name) def deleter(self): del self.__dict__[name] return property(getter, attr, deleter) class Request(dict): """The parameters and information for an HTTP request, suitable for authorizing with OAuth credentials. When a consumer wants to access a service's protected resources, it does so using a signed HTTP request identifying itself (the consumer) with its key, and providing an access token authorized by the end user to access those resources. """ http_method = HTTP_METHOD http_url = None version = VERSION def __init__(self, method=HTTP_METHOD, url=None, parameters=None): if method is not None: self.method = method if url is not None: self.url = url if parameters is not None: self.update(parameters) @setter def url(self, value): parts = urlparse.urlparse(value) scheme, netloc, path = parts[:3] # Exclude default port numbers. if scheme == 'http' and netloc[-3:] == ':80': netloc = netloc[:-3] elif scheme == 'https' and netloc[-4:] == ':443': netloc = netloc[:-4] if scheme != 'http' and scheme != 'https': raise ValueError("Unsupported URL %s (%s)." % (value, scheme)) value = '%s://%s%s' % (scheme, netloc, path) self.__dict__['url'] = value @setter def method(self, value): self.__dict__['method'] = value.upper() def _get_timestamp_nonce(self): return self['oauth_timestamp'], self['oauth_nonce'] def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" return dict([(k, v) for k, v in self.iteritems() if not k.startswith('oauth_')]) def to_header(self, realm=''): """Serialize as a header for an HTTPAuth request.""" oauth_params = ((k, v) for k, v in self.items() if k.startswith('oauth_')) stringy_params = ((k, escape(str(v))) for k, v in oauth_params) header_params = ('%s="%s"' % (k, v) for k, v in stringy_params) params_header = ', '.join(header_params) auth_header = 'OAuth realm="%s"' % realm if params_header: auth_header = "%s, %s" % (auth_header, params_header) return {'Authorization': auth_header} def to_postdata(self): """Serialize as post data for a POST request.""" return self.encode_postdata(self) def encode_postdata(self, data): # tell urlencode to deal with sequence values and map them correctly # to resulting querystring. for example self["k"] = ["v1", "v2"] will # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D return urllib.urlencode(data, True) def to_url(self): """Serialize as a URL for a GET request.""" return '%s?%s' % (self.url, self.to_postdata()) def get_parameter(self, parameter): ret = self.get(parameter) if ret is None: raise Error('Parameter not found: %s' % parameter) return ret def get_normalized_parameters(self): """Return a string that contains the parameters that must be signed.""" items = [(k, v) for k, v in self.items() if k != 'oauth_signature'] encoded_str = urllib.urlencode(sorted(items), True) # Encode signature parameters per Oauth Core 1.0 protocol # spec draft 7, section 3.6 # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6) # Spaces must be encoded with "%20" instead of "+" return encoded_str.replace('+', '%20') def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token) @classmethod def make_timestamp(cls): """Get seconds since epoch (UTC).""" return str(int(time.time())) @classmethod def make_nonce(cls): """Generate pseudorandom number.""" return str(random.randint(0, 100000000)) @classmethod def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None): """Combines multiple parameter sources.""" if parameters is None: parameters = {} # Headers if headers and 'Authorization' in headers: auth_header = headers['Authorization'] # Check that the authorization header is OAuth. if auth_header[:6] == 'OAuth ': auth_header = auth_header[6:] try: # Get the parameters from the header. header_params = cls._split_header(auth_header) parameters.update(header_params) except: raise Error('Unable to parse OAuth parameters from ' 'Authorization header.') # GET or POST query string. if query_string: query_params = cls._split_url_string(query_string) parameters.update(query_params) # URL parameters. param_str = urlparse.urlparse(http_url)[4] # query url_params = cls._split_url_string(param_str) parameters.update(url_params) if parameters: return cls(http_method, http_url, parameters) return None @classmethod def from_consumer_and_token(cls, consumer, token=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} defaults = { 'oauth_consumer_key': consumer.key, 'oauth_timestamp': cls.make_timestamp(), 'oauth_nonce': cls.make_nonce(), 'oauth_version': cls.version, } defaults.update(parameters) parameters = defaults if token: parameters['oauth_token'] = token.key return Request(http_method, http_url, parameters) @classmethod def from_token_and_callback(cls, token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} parameters['oauth_token'] = token.key if callback: parameters['oauth_callback'] = callback return cls(http_method, http_url, parameters) @staticmethod def _split_header(header): """Turn Authorization: header into parameters.""" params = {} parts = header.split(',') for param in parts: # Ignore realm parameter. if param.find('realm') > -1: continue # Remove whitespace. param = param.strip() # Split key-value. param_parts = param.split('=', 1) # Remove quotes and unescape the value. params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) return params @staticmethod def _split_url_string(param_str): """Turn URL string into parameters.""" parameters = parse_qs(param_str, keep_blank_values=False) for k, v in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters class Server(object): """A skeletal implementation of a service provider, providing protected resources to requests from authorized consumers. This class implements the logic to check requests for authorization. You can use it with your web server or web framework to protect certain resources with OAuth. """ timestamp_threshold = 300 # In seconds, five minutes. version = VERSION signature_methods = None def __init__(self, signature_methods=None): self.signature_methods = signature_methods or {} def add_signature_method(self, signature_method): self.signature_methods[signature_method.name] = signature_method return self.signature_methods def verify_request(self, request, consumer, token): """Verifies an api call and checks all the parameters.""" version = self._get_version(request) self._check_signature(request, consumer, token) parameters = request.get_nonoauth_parameters() return parameters def build_authenticate_header(self, realm=''): """Optional support for the authenticate header.""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def _get_version(self, request): """Verify the correct version request for this server.""" try: version = request.get_parameter('oauth_version') except: version = VERSION if version and version != self.version: raise Error('OAuth version %s not supported.' % str(version)) return version def _get_signature_method(self, request): """Figure out the signature with some defaults.""" try: signature_method = request.get_parameter('oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: # Get the signature method object. signature_method = self.signature_methods[signature_method] except: signature_method_names = ', '.join(self.signature_methods.keys()) raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names)) return signature_method def _get_verifier(self, request): return request.get_parameter('oauth_verifier') def _check_signature(self, request, consumer, token): timestamp, nonce = request._get_timestamp_nonce() self._check_timestamp(timestamp) signature_method = self._get_signature_method(request) try: signature = request.get_parameter('oauth_signature') except: raise MissingSignature('Missing oauth_signature.') # Validate the signature. valid = signature_method.check(request, consumer, token, signature) if not valid: key, base = signature_method.signing_base(request, consumer, token) raise Error('Invalid signature. Expected signature base ' 'string: %s' % base) built = signature_method.sign(request, consumer, token) def _check_timestamp(self, timestamp): """Verify that timestamp is recentish.""" timestamp = int(timestamp) now = int(time.time()) lapsed = now - timestamp if lapsed > self.timestamp_threshold: raise Error('Expired timestamp: given %d and now %s has a ' 'greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold)) class Client(httplib2.Http): """OAuthClient is a worker to attempt to execute a request.""" def __init__(self, consumer, token=None, cache=None, timeout=None, proxy_info=None): if consumer is not None and not isinstance(consumer, Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, Token): raise ValueError("Invalid token.") self.consumer = consumer self.token = token self.method = SignatureMethod_HMAC_SHA1() httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info) def set_signature_method(self, method): if not isinstance(method, SignatureMethod): raise ValueError("Invalid signature method.") self.method = method def request(self, uri, method="GET", body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None, force_auth_header=False): if not isinstance(headers, dict): headers = {} if body and method == "POST": parameters = dict(parse_qsl(body)) elif method == "GET": parsed = urlparse.urlparse(uri) parameters = parse_qs(parsed.query) else: parameters = None req = Request.from_consumer_and_token(self.consumer, token=self.token, http_method=method, http_url=uri, parameters=parameters) req.sign_request(self.method, self.consumer, self.token) if force_auth_header: # ensure we always send Authorization headers.update(req.to_header()) if method == "POST": if not force_auth_header: body = req.to_postdata() else: body = req.encode_postdata(req.get_nonoauth_parameters()) headers['Content-Type'] = 'application/x-www-form-urlencoded' elif method == "GET": if not force_auth_header: uri = req.to_url() else: if not force_auth_header: # don't call update twice. headers.update(req.to_header()) return httplib2.Http.request(self, uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type) class SignatureMethod(object): """A way of signing requests. The OAuth protocol lets consumers and service providers pick a way to sign requests. This interface shows the methods expected by the other `oauth` modules for signing requests. Subclass it and implement its methods to provide a new way to sign requests. """ def signing_base(self, request, consumer, token): """Calculates the string that needs to be signed. This method returns a 2-tuple containing the starting key for the signing and the message to be signed. The latter may be used in error messages to help clients debug their software. """ raise NotImplementedError def sign(self, request, consumer, token): """Returns the signature for the given request, based on the consumer and token also provided. You should use your implementation of `signing_base()` to build the message to sign. Otherwise it may be less useful for debugging. """ raise NotImplementedError def check(self, request, consumer, token, signature): """Returns whether the given signature is the correct signature for the given consumer and token signing the given request.""" built = self.sign(request, consumer, token) return built == signature class SignatureMethod_HMAC_SHA1(SignatureMethod): name = 'HMAC-SHA1' def signing_base(self, request, consumer, token): sig = ( escape(request.method), escape(request.url), escape(request.get_normalized_parameters()), ) key = '%s&' % escape(consumer.secret) if token: key += escape(token.secret) raw = '&'.join(sig) return key, raw def sign(self, request, consumer, token): """Builds the base signature string.""" key, raw = self.signing_base(request, consumer, token) # HMAC object. try: import hashlib # 2.5 hashed = hmac.new(key, raw, hashlib.sha1) except ImportError: import sha # Deprecated hashed = hmac.new(key, raw, sha) # Calculate the digest base 64. return binascii.b2a_base64(hashed.digest())[:-1] class SignatureMethod_PLAINTEXT(SignatureMethod): name = 'PLAINTEXT' def signing_base(self, request, consumer, token): """Concatenates the consumer key and secret with the token's secret.""" sig = '%s&' % escape(consumer.secret) if token: sig = sig + escape(token.secret) return sig, sig def sign(self, request, consumer, token): key, raw = self.signing_base(request, consumer, token) return raw
b0nk/botxxy
src/oauth2.py
Python
gpl-2.0
23,431
#! /usr/bin/python try: import requirements except ImportError: pass import time import random import logging import sys import os import inspect from optparse import OptionParser import tp.client.threads from tp.netlib.client import url2bits from tp.netlib import Connection from tp.netlib import failed, constants, objects from tp.client.cache import Cache import daneel from daneel.rulesystem import RuleSystem, BoundConstraint import picklegamestate import cPickle version = (0, 0, 3) mods = [] if hasattr(sys, "frozen"): installpath = os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( ))) else: installpath = os.path.realpath(os.path.dirname(__file__)) def callback(mode, state, message="", todownload=None, total=None, amount=None): logging.getLogger("daneel").debug("Downloading %s %s Message:%s", mode, state, message) def connect(uri='tp://daneel-ai:cannonfodder@localhost/tp'): debug = False host, username, game, password = url2bits(uri) print host, username, game, password if not game is None: username = "%s@%s" % (username, game) connection = Connection() # Download the entire universe try: connection.setup(host=host, debug=debug) except Exception,e: #TODO make the exception more specific print "Unable to connect to the host." return if failed(connection.connect("daneel-ai/%i.%i.%i" % version)): print "Unable to connect to the host." return if failed(connection.login(username, password)): # Try creating the user.. print "User did not exist, trying to create user." if failed(connection.account(username, password, "", "daneel-ai bot")): print "Username / Password incorrect." return if failed(connection.login(username, password)): print "Created username, but still couldn't login :/" return games = connection.games() if failed(games): print "Getting the game object failed!" return cache = Cache(Cache.key(host, games[0], username)) return connection, cache def getDataDir(): if hasattr(sys, "frozen"): return os.path.join(installpath, "share", "daneel-ai") if "site-packages" in daneel.__file__: datadir = os.path.join(os.path.dirname(daneel.__file__), "..", "..", "..", "..", "share", "daneel-ai") else: datadir = os.path.join(os.path.dirname(daneel.__file__), "..") return datadir def createRuleSystem(rulesfile,verbosity,cache,connection): global mods cons,rules = [],[] funcs = {} rf = open(os.path.join(getDataDir(), 'rules', rulesfile)) l = stripline(rf.readline()) while l != "[Modules]": l = stripline(rf.readline()) l = stripline(rf.readline()) while l != "[Constraints]": if l != "": m = getattr(__import__("daneel."+l), l) print l, m mods.append(m) try: cons.extend(m.constraints) except AttributeError: pass try: rules.extend(m.rules) except AttributeError: pass try: exec("".join(m.functions),funcs) except AttributeError: pass l = stripline(rf.readline()) l = stripline(rf.readline()) while l != "[Rules]": if l != "": cons.append(l) l = stripline(rf.readline()) l = stripline(rf.readline()) while l != "[Functions]": if l != "": rules.append(l) l = stripline(rf.readline()) exec("".join(rf.readlines()),funcs) funcs['cache'] = cache if connection != None: funcs['connection'] = connection return RuleSystem(cons,rules,funcs,verbosity) def stripline(line): if line[0] == "#": return "" return line.strip() def startTurn(cache,store, delta): for m in mods: #call startTurn if it exists in m if "startTurn" in [x[0] for x in inspect.getmembers(m)]: m.startTurn(cache,store, delta) def endTurn(cache,rulesystem,connection): for m in mods: #call endTurn if it exists in m if "endTurn" in [x[0] for x in inspect.getmembers(m)]: m.endTurn(cache,rulesystem,connection) def saveGame(cache): root_dir = getDataDir() save_dir = root_dir + "/states/" writeable = checkSaveFolderWriteable(root_dir, save_dir) # NB assumes there is enough space to write if not writeable: logging.getLogger("daneel").error("Cannot save information") else: cache.file = save_dir + time.time().__str__() + ".gamestate" cache.save() def checkSaveFolderWriteable(root_dir, save_dir): dir_exists = os.access(save_dir, os.F_OK) dir_writeable = os.access(save_dir, os.W_OK) dir_root_writeable = os.access(root_dir, os.W_OK) if dir_exists and dir_writeable: return True if dir_exists and not dir_writeable: return False if dir_root_writeable: os.mkdir(save_dir) return True else: return False def init(cache,rulesystem,connection): for m in mods: #call init if it exists in m if "init" in [x[0] for x in inspect.getmembers(m)]: m.init(cache,rulesystem,connection) #this is for optimisation if "optimisationValues" in [x[0] for x in inspect.getmembers(m)]: m.optimisationValues(optimiseValue) def pickle(variable, file_name): file = open(file_name, 'wb') cPickle.dump(variable, file) file.close() return def gameLoop(rulesfile,turns=-1,uri='tp://daneel-ai:cannonfodder@localhost/tp',verbosity=0,benchmark=0): try: level = {0:logging.WARNING,1:logging.INFO,2:logging.DEBUG}[verbosity] except KeyError: level = 1 fmt = "%(asctime)s [%(levelname)s] %(name)s:%(message)s" logging.basicConfig(level=level,stream=sys.stdout,format=fmt) try: connection, cache = connect(uri) except Exception, e: #TODO Null make the exception more specific import traceback traceback.print_exc() print "Connection failed." print e return # state = picklegamestate.GameState(rulesfile,turns,None,None,verbosity) # state.pickle("./states/" + time.time().__str__() + ".gamestate") gameLoopWrapped(rulesfile,turns,connection,cache,verbosity,benchmark) def gameLoopWrapped(rulesfile,turns,connection,cache,verbosity,benchmark): rulesystem = createRuleSystem(rulesfile,verbosity,cache,connection) logging.getLogger("daneel").info("Downloading all data") cache.update(connection,callback) # state = picklegamestate.GameState(rulesfile,turns,None,cache,verbosity) # state.pickle("./states/" + time.time().__str__() + ".gamestate") init(cache,rulesystem,connection) delta = True while turns != 0: turns = turns - 1 logging.getLogger("daneel").info("Downloading updates") cache.update(connection,callback) # store the cache #saveGame(cache) lastturn = connection.time().turn_num startTurn(cache,rulesystem,delta) rulesystem.addConstraint("cacheentered") endTurn(cache,rulesystem,connection) rulesystem.clearStore() connection.turnfinished() waitfor = connection.time() logging.getLogger("daneel").info("Awaiting end of turn %s est: (%s s)..." % (lastturn,waitfor.time)) try: while lastturn == connection.get_objects(0)[0].Informational[0][0]: waitfor = connection.time() time.sleep(max(1, min(10, waitfor.time / 100))) except IOError: print "Connection lost" exit(2) def gameLoopBenchMark(rulesfile,turns,connection,cache,verbosity): rulesystem = createRuleSystem(rulesfile,verbosity,cache,connection) logging.getLogger("daneel").info("Downloading all data") init(cache,rulesystem,connection) delta = False startTurn(cache,rulesystem,delta) rulesystem.addConstraint("cacheentered") endTurn(cache,rulesystem,None) rulesystem.clearStore() return optimiseValue = None if __name__ == "__main__": parser = OptionParser(version="%prog " + ("%i.%i.%i" % version)) parser.add_option("-f", "--file", dest="filename", default="rfts", help="read rules from FILENAME [default: %default]") parser.add_option("-n", "--numturns", dest="numturns", type="int", default=-1, help="run for NUMTURNS turns [default: unlimited]") parser.add_option("-u", "--uri", dest="uri", default='tp://daneel-ai:cannonfodder@localhost/tp', help="Connect to specified URI [default %default]") parser.add_option("-v", action="count", dest="verbosity", default=1, help="More verbose output. -vv and -vvv increase output even more.") parser.add_option("-b", dest="benchmark", default=0, help="Runs the program in benchmarking mode.") parser.add_option("-o", dest="optimise", default=0, help="Runs the program in benchmarking mode.") (options, args) = parser.parse_args() optimiseValue = options.optimise gameLoop(options.filename,turns=options.numturns,uri=options.uri,verbosity=options.verbosity,benchmark=options.benchmark)
thousandparsec/daneel-ai
daneel-ai.py
Python
gpl-2.0
9,338
import numpy as np __all__ = ['compute_penalties'] def compute_penalty(kk, clusters): '''Takes kk.clusters (clusters currently assigned) and computes the penalty''' if clusters is None: clusters = kk.clusters #print(clusters) num_cluster_membs = np.array(np.bincount(clusters), dtype=int) alive = num_cluster_membs>0 num_clusters = np.sum(alive) #print('num_cluster_members', num_cluster_membs) # print('num_clusters', num_clusters) # #This now only depends on the number of clusters # #cluster_penalty = np.zeros(num_clusters) num_spikes = kk.num_spikes #D_k = kk.D_k num_kkruns = kk.num_KKruns num_bern_params = kk.num_bern_params #This was determined in the previous M-step num_bern_params_used = num_bern_params[np.nonzero(num_cluster_membs>0)] #print('num_bern_params_used = ', num_bern_params_used) #num_bern_params = [70 71 63 63 64 62 83 79] for 8 clusters penalty_k = kk.penalty_k penalty_k_log_n = kk.penalty_k_log_n #mean_params = (np.sum(D_k)-num_kkruns)*num_clusters - 1 #effective_params = bernoulli params + mixture weight effective_params = np.sum(num_bern_params_used)-num_kkruns*num_clusters + (num_clusters -1) penalty = (2*penalty_k*effective_params + penalty_k_log_n*effective_params*np.log(num_spikes)/2) #print('penalty = ', penalty) #do_compute_penalty(cluster_penalty, num_spikes, clusters, # penalty_k, penalty_k_log_n) #may not need to import return penalty
kwikteam/global_superclustering
global_code/compute_penalty.py
Python
gpl-2.0
1,609
from datetime import datetime from mongoengine import * from mongoengine.django.auth import User from django.core.urlresolvers import reverse import mongoengine.fields # Create your models here. class Evento(Document): titulo = StringField(max_length=200, required=True) descricao = StringField(required=True) data_modificacao = DateTimeField(default=datetime.now) publicado = BooleanField() local = PointField(auto_index=False) def __unicode__(self): return self.titulo def save(self, *args, **kwargs): return super(Evento, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('evento-detail', args=[self.id]) def get_edit_url(self): return reverse('evento-update', args=[self.id]) def get_delete_url(self): return reverse('evento-delete', args=[self.id]) # meta = { # 'indexes': [[("local", "2dsphere"), ("data_modificacao", 1)]] # }
tomadasocial/tomada-social
evento/models.py
Python
gpl-2.0
899
import copy, getpass, logging, pprint, re, urllib, urlparse import httplib2 from django.utils import datastructures, simplejson from autotest_lib.frontend.afe import rpc_client_lib from autotest_lib.client.common_lib import utils _request_headers = {} def _get_request_headers(uri): server = urlparse.urlparse(uri)[0:2] if server in _request_headers: return _request_headers[server] headers = rpc_client_lib.authorization_headers(getpass.getuser(), uri) headers['Content-Type'] = 'application/json' _request_headers[server] = headers return headers def _clear_request_headers(uri): server = urlparse.urlparse(uri)[0:2] if server in _request_headers: del _request_headers[server] def _site_verify_response_default(headers, response_body): return headers['status'] != '401' class RestClientError(Exception): pass class ClientError(Exception): pass class ServerError(Exception): pass class Response(object): def __init__(self, httplib_response, httplib_content): self.status = int(httplib_response['status']) self.headers = httplib_response self.entity_body = httplib_content def decoded_body(self): return simplejson.loads(self.entity_body) def __str__(self): return '\n'.join([str(self.status), self.entity_body]) class Resource(object): def __init__(self, representation_dict, http): self._http = http assert 'href' in representation_dict for key, value in representation_dict.iteritems(): setattr(self, str(key), value) def __repr__(self): return 'Resource(%r)' % self._representation() def pprint(self): # pretty-print support for debugging/interactive use pprint.pprint(self._representation()) @classmethod def load(cls, uri, http=None): if not http: http = httplib2.Http() directory = cls({'href': uri}, http) return directory.get() def _read_representation(self, value): # recursively convert representation dicts to Resource objects if isinstance(value, list): return [self._read_representation(element) for element in value] if isinstance(value, dict): converted_dict = dict((key, self._read_representation(sub_value)) for key, sub_value in value.iteritems()) if 'href' in converted_dict: return type(self)(converted_dict, http=self._http) return converted_dict return value def _write_representation(self, value): # recursively convert Resource objects to representation dicts if isinstance(value, list): return [self._write_representation(element) for element in value] if isinstance(value, dict): return dict((key, self._write_representation(sub_value)) for key, sub_value in value.iteritems()) if isinstance(value, Resource): return value._representation() return value def _representation(self): return dict((key, self._write_representation(value)) for key, value in self.__dict__.iteritems() if not key.startswith('_') and not callable(value)) def _do_request(self, method, uri, query_parameters, encoded_body): uri_parts = [uri] if query_parameters: if '?' in uri: uri_parts += '&' else: uri_parts += '?' uri_parts += urllib.urlencode(query_parameters, doseq=True) full_uri = ''.join(uri_parts) if encoded_body: entity_body = simplejson.dumps(encoded_body) else: entity_body = None logging.debug('%s %s', method, full_uri) if entity_body: logging.debug(entity_body) site_verify = utils.import_site_function( __file__, 'autotest_lib.frontend.shared.site_rest_client', 'site_verify_response', _site_verify_response_default) headers, response_body = self._http.request( full_uri, method, body=entity_body, headers=_get_request_headers(uri)) if not site_verify(headers, response_body): logging.debug('Response verification failed, clearing headers and ' 'trying again:\n%s', response_body) _clear_request_headers(uri) headers, response_body = _http.request( full_uri, method, body=entity_body, headers=_get_request_headers(uri)) logging.debug('Response: %s', headers['status']) return Response(headers, response_body) def _request(self, method, query_parameters=None, encoded_body=None): if query_parameters is None: query_parameters = {} response = self._do_request(method, self.href, query_parameters, encoded_body) if 300 <= response.status < 400: # redirection return self._do_request(method, response.headers['location'], query_parameters, encoded_body) if 400 <= response.status < 500: raise ClientError(str(response)) if 500 <= response.status < 600: raise ServerError(str(response)) return response def _stringify_query_parameter(self, value): if isinstance(value, (list, tuple)): return ','.join(self._stringify_query_parameter(item) for item in value) return str(value) def _iterlists(self, mapping): """This effectively lets us treat dicts as MultiValueDicts.""" if hasattr(mapping, 'iterlists'): # mapping is already a MultiValueDict return mapping.iterlists() return ((key, (value,)) for key, value in mapping.iteritems()) def get(self, query_parameters=None, **kwarg_query_parameters): """ @param query_parameters: a dict or MultiValueDict """ query_parameters = copy.copy(query_parameters) # avoid mutating original if query_parameters is None: query_parameters = {} query_parameters.update(kwarg_query_parameters) string_parameters = datastructures.MultiValueDict() for key, values in self._iterlists(query_parameters): string_parameters.setlist( key, [self._stringify_query_parameter(value) for value in values]) response = self._request('GET', query_parameters=string_parameters.lists()) assert response.status == 200 return self._read_representation(response.decoded_body()) def get_full(self, results_limit, query_parameters=None, **kwarg_query_parameters): """ Like get() for collections, when the full collection is expected. @param results_limit: maxmimum number of results to allow @raises ClientError if there are more than results_limit results. """ result = self.get(query_parameters=query_parameters, items_per_page=results_limit, **kwarg_query_parameters) if result.total_results > results_limit: raise ClientError( 'Too many results (%s > %s) for request %s (%s %s)' % (result.total_results, results_limit, self.href, query_parameters, kwarg_query_parameters)) return result def put(self): response = self._request('PUT', encoded_body=self._representation()) assert response.status == 200 return self._read_representation(response.decoded_body()) def delete(self): response = self._request('DELETE') assert response.status == 204 # no content def post(self, request_dict): # request_dict may still have resources in it request_dict = self._write_representation(request_dict) response = self._request('POST', encoded_body=request_dict) assert response.status == 201 # created return self._read_representation({'href': response.headers['location']})
ceph/autotest
frontend/shared/rest_client.py
Python
gpl-2.0
8,328
from setuptools import setup, Extension #from distutils.core import setup, Extension module1 = Extension('giscup15', sources = ['giscup15.cpp'], extra_compile_args=['-std=c++11'], libraries=['shp']) setup (name = 'giscup15', version = '1.0', description = 'This is a wrapper around the shortest path engine from GIS Cup 2015 (Dijkstra, A*, ALT supported)', ext_modules = [module1])
mwernerds/giscup2015
python/setup.py
Python
gpl-2.0
465
# Copyright (c) Facebook, Inc. and its affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. """make status give a bit more context This extension will wrap the status command to make it show more context about the state of the repo """ import math import os from edenscm.mercurial import ( commands, hbisect, merge as mergemod, node as nodeutil, pycompat, registrar, scmutil, ) from edenscm.mercurial.error import Abort from edenscm.mercurial.extensions import wrapcommand from edenscm.mercurial.i18n import _ UPDATEARGS = "updateargs" configtable = {} configitem = registrar.configitem(configtable) configitem("morestatus", "show", default=False) def prefixlines(raw): """Surround lineswith a comment char and a new line""" lines = raw.splitlines() commentedlines = ["# %s" % line for line in lines] return "\n".join(commentedlines) + "\n" def conflictsmsg(repo, ui): mergestate = mergemod.mergestate.read(repo) if not mergestate.active(): return m = scmutil.match(repo[None]) unresolvedlist = [f for f in mergestate if m(f) and mergestate[f] == "u"] if unresolvedlist: mergeliststr = "\n".join( [ " %s" % os.path.relpath(os.path.join(repo.root, path), pycompat.getcwd()) for path in unresolvedlist ] ) msg = ( _( """Unresolved merge conflicts: %s To mark files as resolved: hg resolve --mark FILE""" ) % mergeliststr ) else: msg = _("No unresolved merge conflicts.") ui.warn(prefixlines(msg)) def helpmessage(ui, continuecmd, abortcmd): msg = _("To continue: %s\n" "To abort: %s") % ( continuecmd, abortcmd, ) ui.warn(prefixlines(msg)) def rebasemsg(repo, ui): helpmessage(ui, "hg rebase --continue", "hg rebase --abort") def histeditmsg(repo, ui): helpmessage(ui, "hg histedit --continue", "hg histedit --abort") def unshelvemsg(repo, ui): helpmessage(ui, "hg unshelve --continue", "hg unshelve --abort") def updatecleanmsg(dest=None): warning = _("warning: this will discard uncommitted changes") return "hg update --clean %s (%s)" % (dest or ".", warning) def graftmsg(repo, ui): # tweakdefaults requires `update` to have a rev hence the `.` helpmessage(ui, "hg graft --continue", updatecleanmsg()) def updatemsg(repo, ui): previousargs = repo.localvfs.tryreadutf8(UPDATEARGS) if previousargs: continuecmd = "hg " + previousargs else: continuecmd = "hg update " + repo.localvfs.readutf8("updatestate")[:12] abortcmd = updatecleanmsg(repo._activebookmark) helpmessage(ui, continuecmd, abortcmd) def updatemergemsg(repo, ui): helpmessage(ui, "hg update --continue", updatecleanmsg()) def mergemsg(repo, ui): # tweakdefaults requires `update` to have a rev hence the `.` helpmessage(ui, "hg commit", updatecleanmsg()) def bisectmsg(repo, ui): msg = _( "To mark the changeset good: hg bisect --good\n" "To mark the changeset bad: hg bisect --bad\n" "To abort: hg bisect --reset\n" ) state = hbisect.load_state(repo) bisectstatus = _( """Current bisect state: {} good commit(s), {} bad commit(s), {} skip commit(s)""" ).format(len(state["good"]), len(state["bad"]), len(state["skip"])) ui.write_err(prefixlines(bisectstatus)) if len(state["good"]) > 0 and len(state["bad"]) > 0: try: nodes, commitsremaining, searching, badnode, goodnode = hbisect.bisect( repo, state ) searchesremaining = ( int(math.ceil(math.log(commitsremaining, 2))) if commitsremaining > 0 else 0 ) bisectstatus = _( """ Current Tracker: bad commit current good commit {}...{}...{} Commits remaining: {} Estimated bisects remaining: {} """ ).format( nodeutil.short(badnode), nodeutil.short(nodes[0]), nodeutil.short(goodnode), commitsremaining, searchesremaining, ) ui.write_err(prefixlines(bisectstatus)) except Abort: # ignore the output if bisect() fails pass ui.warn(prefixlines(msg)) def fileexistspredicate(filename): return lambda repo: repo.localvfs.exists(filename) def mergepredicate(repo): return len(repo[None].parents()) > 1 STATES = ( # (state, predicate to detect states, helpful message function) ("histedit", fileexistspredicate("histedit-state"), histeditmsg), ("bisect", fileexistspredicate("bisect.state"), bisectmsg), ("graft", fileexistspredicate("graftstate"), graftmsg), ("unshelve", fileexistspredicate("unshelverebasestate"), unshelvemsg), ("rebase", fileexistspredicate("rebasestate"), rebasemsg), # 'update --merge'. Unlike the 'update' state below, this can be # continued. ("update", fileexistspredicate("updatemergestate"), updatemergemsg), # The merge and update states are part of a list that will be iterated over. # They need to be last because some of the other unfinished states may also # be in a merge or update state (eg. rebase, histedit, graft, etc). # We want those to have priority. ("merge", mergepredicate, mergemsg), # Sometimes you end up in a merge state when update completes, because you # ran `hg update --merge`. We should inform you that you can still use the # full suite of resolve tools to deal with conflicts in this state. ("merge", fileexistspredicate("merge/state"), None), # If there were no conflicts, you may still be in an interrupted update # state. Ideally, we should expand this update state to include the merge # updates mentioned above, so there's a way to "continue" and finish the # update. ("update", fileexistspredicate("updatestate"), updatemsg), ) def extsetup(ui): if ui.configbool("morestatus", "show") and not ui.plain(): wrapcommand(commands.table, "status", statuscmd) # Write down `hg update` args to show the continue command in # interrupted update state. ui.setconfig("hooks", "pre-update.morestatus", saveupdateargs) ui.setconfig("hooks", "post-update.morestatus", cleanupdateargs) def saveupdateargs(repo, args, **kwargs): # args is a string containing all flags and arguments with repo.wlock(): repo.localvfs.writeutf8(UPDATEARGS, args) def cleanupdateargs(repo, **kwargs): with repo.wlock(): repo.localvfs.tryunlink(UPDATEARGS) def statuscmd(orig, ui, repo, *pats, **opts): """ Wrap the status command to barf out the state of the repository. States being mid histediting, mid bisecting, grafting, merging, etc. Output is to stderr to avoid breaking scripts. """ ret = orig(ui, repo, *pats, **opts) statetuple = getrepostate(repo) if statetuple: state, statedetectionpredicate, helpfulmsg = statetuple statemsg = _("The repository is in an unfinished *%s* state.") % state ui.warn("\n" + prefixlines(statemsg)) conflictsmsg(repo, ui) if helpfulmsg: helpfulmsg(repo, ui) # TODO(cdelahousse): check to see if current bookmark needs updating. See # scmprompt. return ret def getrepostate(repo): # experimental config: morestatus.skipstates skip = set(repo.ui.configlist("morestatus", "skipstates", [])) for state, statedetectionpredicate, msgfn in STATES: if state in skip: continue if statedetectionpredicate(repo): return (state, statedetectionpredicate, msgfn)
facebookexperimental/eden
eden/hg-server/edenscm/hgext/morestatus.py
Python
gpl-2.0
7,991
"""Author: Ben Johnstone""" #TODO # 1 Do argparse for main # 3 Figure out what statistics should be reported # 4 set up logger # 5 winnings calculator??? # 6 Speed benchmarking?? # 7 Get drawings file from internet # 8 Graph count of each ball # Database def Main(): parser = argparse.ArgumentParser(description="") parser.add_argument("--file", "-f", required=True, help="Name of the file containing the historical powerball drawings") parser.add_argument("--jackpot", "-j", help="Optional excel file containing the number of " \ + "jackpot winners for each drawing") parser.add_argument("--leastRecent", "-l", help="Display the white and red numbers in order " \ + "from least to most recently drawn", action="store_true") parser.add_argument("--mostCommon", "-m", help="Display the white and red numbers in order " \ + "of commonality in the results from most to least common", action="store_true") args = parser.parse_args() if not (args.leastRecent or args.mostCommon): print("Must use at least one of --leastRecent or --mostCommon") return drawings = ParseDrawingsFile(args.file) if args.jackpot: ParseJackpotFile(args.jackpot) if args.leastRecent: print("Least recent white balls:") print(LeastRecentWhites(drawings)) print("Least recent red balls:") print(LeastRecentReds(drawings)) if args.mostCommon: print("Most common white balls:") print(MostCommonWhites(drawings)) print("Most common red balls:") print(MostCommonReds(drawings)) if __name__ == "__main__": Main()
Dreamcatcher5/Powerball
src/powerball/powerball.py
Python
gpl-3.0
1,747
# Xandikos # Copyright (C) 2017 Jelmer Vernooij <jelmer@jelmer.uk>, et al. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; version 3 # of the License or (at your option) any later version of # the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. """VCard file handling. """ from .store import File, InvalidFileContents class VCardFile(File): content_type = "text/vcard" def __init__(self, content, content_type): super(VCardFile, self).__init__(content, content_type) self._addressbook = None def validate(self): c = b"".join(self.content).strip() # TODO(jelmer): Do more extensive checking of VCards if not c.startswith((b"BEGIN:VCARD\r\n", b"BEGIN:VCARD\n")) or not c.endswith( b"\nEND:VCARD" ): raise InvalidFileContents( self.content_type, self.content, "Missing header and trailer lines", ) if not self.addressbook.validate(): # TODO(jelmer): Get data about what is invalid raise InvalidFileContents( self.content_type, self.content, "Invalid VCard file") @property def addressbook(self): if self._addressbook is None: import vobject text = b"".join(self.content).decode('utf-8', 'surrogateescape') try: self._addressbook = vobject.readOne(text) except vobject.base.ParseError as e: raise InvalidFileContents(self.content_type, self.content, str(e)) return self._addressbook
jelmer/xandikos
xandikos/vcard.py
Python
gpl-3.0
2,165
"""order name not unique Revision ID: 1139f0b4c9e3 Revises: 220436d6dcdc Create Date: 2016-05-31 08:59:21.225314 """ # revision identifiers, used by Alembic. revision = '1139f0b4c9e3' down_revision = '220436d6dcdc' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint('orders_name_key', 'orders', type_='unique') ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_unique_constraint('orders_name_key', 'orders', ['name']) ### end Alembic commands ###
Adverpol/eco-basket
migrations/versions/1139f0b4c9e3_order_name_not_unique.py
Python
gpl-3.0
635
#!/usr/bin/python # # Created on Aug 25, 2016 # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # Avi Version: 17.1.1 # # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: avi_role author: Gaurav Rastogi (grastogi@avinetworks.com) short_description: Module for setup of Role Avi RESTful Object description: - This module is used to configure Role object - more examples at U(https://github.com/avinetworks/devops) requirements: [ avisdk ] version_added: "2.3" options: state: description: - The state that should be applied on the entity. default: present choices: ["absent", "present"] avi_api_update_method: description: - Default method for object update is HTTP PUT. - Setting to patch will override that behavior to use HTTP PATCH. version_added: "2.5" default: put choices: ["put", "patch"] avi_api_patch_op: description: - Patch operation to use when using avi_api_update_method as patch. version_added: "2.5" choices: ["add", "replace", "delete"] name: description: - Name of the object. required: true privileges: description: - List of permission. tenant_ref: description: - It is a reference to an object of type tenant. url: description: - Avi controller URL of the object. uuid: description: - Unique object identifier of the object. extends_documentation_fragment: - avi ''' EXAMPLES = """ - name: Example to create Role object avi_role: controller: 10.10.25.42 username: admin password: something state: present name: sample_role """ RETURN = ''' obj: description: Role (api/role) object returned: success, changed type: dict ''' from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.network.avi.avi import ( avi_common_argument_spec, HAS_AVI, avi_ansible_api) except ImportError: HAS_AVI = False def main(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), avi_api_update_method=dict(default='put', choices=['put', 'patch']), avi_api_patch_op=dict(choices=['add', 'replace', 'delete']), name=dict(type='str', required=True), privileges=dict(type='list',), tenant_ref=dict(type='str',), url=dict(type='str',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'role', set([])) if __name__ == '__main__': main()
le9i0nx/ansible
lib/ansible/modules/network/avi/avi_role.py
Python
gpl-3.0
3,902
from django.contrib.auth.models import Group from django.core import mail from django.urls import reverse from django.test import TestCase from django.conf import settings from zds.member.factories import ProfileFactory from zds.mp.models import PrivateTopic class MpUtilTest(TestCase): def setUp(self): self.user1 = ProfileFactory().user self.user1.profile.email_for_answer = True self.user1.profile.email_for_new_mp = False self.user1.profile.save() self.user2 = ProfileFactory().user self.user2.profile.email_for_answer = True self.user2.profile.email_for_new_mp = False self.user2.profile.save() self.user3 = ProfileFactory().user self.user3.profile.email_for_answer = True self.user3.profile.email_for_new_mp = True self.user3.profile.save() self.user4 = ProfileFactory().user self.user4.profile.email_for_answer = False self.user4.profile.email_for_new_mp = False self.user4.profile.save() self.user5 = ProfileFactory().user self.user5.profile.email_for_answer = False self.user5.profile.email_for_new_mp = True self.user5.profile.save() # Login as profile1 self.client.force_login(self.user1) # Save bot group bot = Group(name=settings.ZDS_APP["member"]["bot_group"]) bot.save() def test_new_mp_email(self): response = self.client.post( reverse("mp-new"), { "participants": self.user2.username + ", " + self.user3.username + ", " + self.user4.username + ", " + self.user5.username, "title": "title", "subtitle": "subtitle", "text": "text", }, follow=True, ) # Assert MP have been sent self.assertEqual(200, response.status_code) self.assertEqual(1, PrivateTopic.objects.all().count()) should_receive_response = [self.user2.email, self.user3.email, self.user5.email] # Check everyone receive a MP, except op self.assertEqual(len(mail.outbox), len(should_receive_response)) for response in mail.outbox: self.assertTrue(self.user1.username in response.body) self.assertIn(response.to[0], should_receive_response) PrivateTopic.objects.all().delete() def test_answer_mp_email(self): # Create a MP self.client.post( reverse("mp-new"), { "participants": self.user2.username + ", " + self.user3.username + ", " + self.user4.username + ", " + self.user5.username, "title": "title", "subtitle": "subtitle", "text": "text", }, follow=True, ) mail.outbox = [] self.client.logout() self.client.force_login(self.user2) # Add an answer topic1 = PrivateTopic.objects.get() self.client.post( reverse("private-posts-new", args=[topic1.pk, topic1.slug]), {"text": "answer", "last_post": topic1.last_message.pk}, follow=True, ) # Check user1 receive mails should_receive_response = [self.user1.email] # Check user5 does not receive mails should_not_receive_response = [self.user5.email] self.assertEqual(len(mail.outbox), len(should_receive_response)) for response in mail.outbox: self.assertTrue(self.user2.username in response.body) self.assertIn(response.to[0], should_receive_response) self.assertFalse(response.to[0] in should_not_receive_response) PrivateTopic.objects.all().delete() self.client.logout() self.client.force_login(self.user1)
ChantyTaguan/zds-site
zds/mp/tests/tests_utils.py
Python
gpl-3.0
4,013
#! /usr/bin/env python # Copyright (C) 2012 Club Capra - capra.etsmtl.ca # # This file is part of CapraVision. # # CapraVision 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/>. import cv2 import cv2.cv as cv import numpy as np from CapraVision.server.filters.parameter import Parameter from CapraVision.server.filters.dataextract import DataExtractor class MTI880(DataExtractor): def __init__(self): DataExtractor.__init__(self) self.hue_min = 113 self.hue_max = 255 self.area_min = 600 self.normal_hand = 0 self.extended_hand = 0 self.closed_hand = 0 self.amplitude = 0 self._capture_normal_hand = False self._capture_extended_hand = False self._capture_closed_hand = False self._calibrate_hue = False self.accumulate = [] self.observers = [] def add_observer(self, observer): self.observers.append(observer) def remove_observer(self, observer): self.observers.remove(observer) def notify_observers(self): for obs in self.observers: obs() def execute(self, image): image = cv2.cvtColor(image, cv2.cv.CV_BGR2HSV) h, _, _ = cv2.split(image) image[h < self.hue_min] *= 0 image[h > self.hue_max] *= 0 #image[image > 0] = 255 gray = cv2.cvtColor(image, cv.CV_BGR2GRAY) cnt, _ = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) image *= 0 area, c = self.detect_biggest_area(gray) if self._calibrate_hue and c is not None and area > self.area_min: self.hue_min += 1 #self.notify_observers() elif self._calibrate_hue and self.hue_min > 0: print self.hue_min self.notify_observers() self._calibrate_hue = False self.calibrate_closed_hand(area) self.calibrate_extended_hand(area) self.calibrate_normal_hand(area) if c is not None and area >= self.area_min: hull = cv2.convexHull(c) cv2.drawContours(image, [hull],-1, (255,255,255), -1) self.notify_output_observers(str(self.calc_return_value(area)) + "\n") else: self.notify_output_observers('0\n') return image def detect_biggest_area(self, gray): cnt, _ = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) maxarea = 0 maxcnt = None for c in cnt: approx = cv2.approxPolyDP(c, 0, False) area = np.abs(cv2.contourArea(c)) if area > maxarea: maxarea = area maxcnt = c return (maxarea, maxcnt) def calibrate_normal_hand(self, area): if self._capture_normal_hand: self.accumulate.append(area) if len(self.accumulate) == 10: total = 0 for val in self.accumulate: total += val self._capture_normal_hand = False self.normal_hand = total / 10 self.accumulate = [] self.notify_observers() def calibrate_extended_hand(self, area): if self._capture_extended_hand: self.accumulate.append(area) if len(self.accumulate) == 10: total = 0 for val in self.accumulate: total += val self._capture_extended_hand = False self.extended_hand = total / 10 self.accumulate = [] self.notify_observers() def calibrate_closed_hand(self, area): if self._capture_closed_hand: self.accumulate.append(area) if len(self.accumulate) == 10: total = 0 for val in self.accumulate: total += val self._capture_closed_hand = False self.closed_hand = total / 10 self.accumulate = [] self.notify_observers() def calc_return_value(self, area): if area > self.normal_hand: diff = (self.extended_hand - self.normal_hand) * (self.amplitude / 100.0) if area > (self.normal_hand + diff): return area else: return 0 else: diff = (self.normal_hand - self.closed_hand) * (self.amplitude / 100.0) if area < (self.normal_hand - diff): return -area else: return 0
clubcapra/Ibex
src/seagoatvision_ros/scripts/CapraVision/server/filters/implementation/mti880.py
Python
gpl-3.0
5,241
from random import randint from yapsy.IPlugin import IPlugin class PortCheckerPlugin(IPlugin): """ Mocked Version: Return random 0 or 1 as exit_code Takes an ip address and a port as inputs and trys to make a TCP connection to that port. Output is success 0 or failure > 0 """ def execute(self, info): val = randint(0, 10) if val != 0: val = 1 info.output_values['exit_code'] = randint(0, 1)
neil-davis/penfold
src/plugins/PortCheckerPluginMock.py
Python
gpl-3.0
470
# -*- coding: utf-8 -*- # Copyright 2010 Trever Fischer <tdfischer@fedoraproject.org> # # This file is part of modulation. # # modulation 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. # # modulation is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with modulation. If not, see <http://www.gnu.org/licenses/>. from modulation import Packet, Plugin import threading class ControlPacket(Packet): """A ControlPacket gives some kind of control signal to a child plugin, such as "STOP", "PLAY", "SEARCH", "VOLUME", etc If a plugin handles the packet according to its intent (eg stopping playback on a stop packet), then the original packet must be forwarded with send(). If a plugin then does other actions (such as switching to a different stream and then playing), a new packet must be sent as well. If a plugin does something of its own accord (eg nobody told it to stop, but it is out of data so it must stop anyways), a new packet must be sent. """ def __init__(self, origin=None, data=None): Packet.__init__(self, origin) self.__data = data def getData(self): return self.__data data = property(getData, None, None, "The data associated with this specific control packet type.") class Start(ControlPacket): """Start some operation""" pass class Stop(ControlPacket): """Stop doing some operation""" pass class Pause(ControlPacket): """Pause something that can be continued later""" pass class Next(ControlPacket): """Skip the current operation""" pass class Prev(ControlPacket): """Go back to the previous operation""" pass class Enqueue(ControlPacket): """Passes along a source to enqueue""" pass class Load(ControlPacket): """Uses the 'uri' data element to indicate loading of data""" pass class Seek(ControlPacket): """Uses the 'location' data element""" pass class Exit(ControlPacket): """Indicates a plugin upstream has exited and is no longer part of the graph""" pass class PacketDelay(Plugin): """PacketDelays are used to wait until a packet of some type has been recieved""" def __init__(self, packetType): Plugin.__init__(self) self.__type = packetType self.__lock = threading.Event() def handlePacket(self, pkt): super(PacketDelay, self).handlePacket(pkt) if (isinstance(pkt, self.__type)): self.__lock.set() def wait(): self.__lock.wait()
tdfischer/modulation
modulation/controls.py
Python
gpl-3.0
2,941
# ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # 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/>. # ----------------------------------------------------------------------------- from gi.repository import Gtk from gettext import gettext as _ from GTG.gtk.backends.parameters_ui import ParametersUI from GTG.backends.backend_signals import BackendSignals class ConfigurePanel(Gtk.Box): """ A vertical Box that lets you configure a backend """ def __init__(self, backends): """ Constructor, creating all the gtk widgets @param backends: a reference to the dialog in which this is loaded """ super().__init__(orientation=Gtk.Orientation.VERTICAL) self.dialog = backends self.should_spinner_be_shown = False self.task_deleted_handle = None self.task_added_handle = None self.req = backends.get_requester() self._create_widgets() self._connect_signals() def _connect_signals(self): """ Connects the backends generated signals """ _signals = BackendSignals() _signals.connect(_signals.BACKEND_RENAMED, self.refresh_title) _signals.connect(_signals.BACKEND_STATE_TOGGLED, self.refresh_sync_status) _signals.connect(_signals.BACKEND_SYNC_STARTED, self.on_sync_started) _signals.connect(_signals.BACKEND_SYNC_ENDED, self.on_sync_ended) def _create_widgets(self): """ This function fills this box with widgets """ # Division of the available space in three segments: # top, middle and bottom (parameters_ui) top = Gtk.Box() top.set_spacing(6) middle = Gtk.Box() middle.set_spacing(6) self._fill_top_box(top) self._fill_middle_box(middle) self.pack_start(top, False, True, 0) self.pack_start(middle, False, True, 0) align = Gtk.Alignment.new(0, 0, 1, 0) align.set_padding(10, 0, 0, 0) self.parameters_ui = ParametersUI(self.req) align.add(self.parameters_ui) self.pack_start(align, False, True, 0) def _fill_top_box(self, box): """ Fill header with service's icon, name, and a spinner for inidcation of work. """ box.set_spacing(10) self.image_icon = Gtk.Image() self.image_icon.set_size_request(48, 48) self.human_name_label = Gtk.Label() self.human_name_label.set_alignment(xalign=0, yalign=0.5) # FIXME in the newer versions of GTK3 there always be Spinner! try: self.spinner = Gtk.Spinner() except AttributeError: # worarkound for archlinux: bug #624204 self.spinner = Gtk.Box() self.spinner.connect("show", self.on_spinner_show) self.spinner.set_size_request(32, 32) align_spin = Gtk.Alignment.new(1, 0, 0, 0) align_spin.add(self.spinner) box.pack_start(self.image_icon, False, True, 0) box.pack_start(self.human_name_label, True, True, 0) box.pack_start(align_spin, False, True, 0) def _fill_middle_box(self, box): """ Helper function to fill an box with a label and a button @param box: the Gtk.Box to fill """ self.sync_status_label = Gtk.Label() self.sync_status_label.set_alignment(xalign=0.8, yalign=0.5) self.sync_button = Gtk.Button() self.sync_button.connect("clicked", self.on_sync_button_clicked) box.pack_start(self.sync_status_label, True, True, 0) box.pack_start(self.sync_button, True, True, 0) def set_backend(self, backend_id): """Changes the backend to configure, refreshing this view. @param backend_id: the id of the backend to configure """ self.backend = self.dialog.get_requester().get_backend(backend_id) self.refresh_title() self.refresh_sync_status() self.parameters_ui.refresh(self.backend) self.image_icon.set_from_pixbuf(self.dialog.get_pixbuf_from_icon_name( self.backend.get_icon(), 48)) def refresh_title(self, sender=None, data=None): """ Callback for the signal that notifies backends name changes. It changes the title of this view @param sender: not used, here only for signal callback compatibility @param data: not used, here only for signal callback compatibility """ markup = "<big><big><big><b>%s</b></big></big></big>" % \ self.backend.get_human_name() self.human_name_label.set_markup(markup) def refresh_sync_button(self): """ Refreshes the state of the button that enables the backend """ self.sync_button.set_sensitive(not self.backend.is_default()) if self.backend.is_enabled(): label = _("Disable syncing") else: label = _("Enable syncing") self.sync_button.set_label(label) def refresh_sync_status_label(self): """ Refreshes the Gtk.Label that shows the current state of this backend """ if self.backend.is_default(): label = _("This is the default synchronization service") else: if self.backend.is_enabled(): label = _("Syncing is enabled.") else: label = _('Syncing is <span color="red">disabled</span>.') self.sync_status_label.set_markup(label) def refresh_sync_status(self, sender=False, data=False): """Signal callback function, called when a backend state (enabled/disabled) changes. Refreshes this view. @param sender: not used, here only for signal callback compatibility @param data: not used, here only for signal callback compatibility """ self.refresh_sync_button() self.refresh_sync_status_label() def on_sync_button_clicked(self, sender): """ Signal callback when a backend is enabled/disabled via the UI button @param sender: not used, here only for signal callback compatibility """ self.parameters_ui.commit_changes() self.req.set_backend_enabled(self.backend.get_id(), not self.backend.is_enabled()) def on_sync_started(self, sender, backend_id): """ If the backend has started syncing tasks, update the state of the Gtk.Spinner @param sender: not used, here only for signal callback compatibility @param backend_id: the id of the backend that emitted this signal """ if backend_id == self.backend.get_id(): self.spinner_set_active(True) def on_sync_ended(self, sender, backend_id): """ If the backend has stopped syncing tasks, update the state of the Gtk.Spinner @param sender: not used, here only for signal callback compatibility @param backend_id: the id of the backend that emitted this signal """ if backend_id == self.backend.get_id(): self.spinner_set_active(False) def on_spinner_show(self, sender): """This signal callback hides the spinner if it's not supposed to be seen. It's a workaround to let us call show_all on the whole window while keeping this hidden (it's the only widget that requires special attention) @param sender: not used, here only for signal callback compatibility """ if not self.should_spinner_be_shown: self.spinner.hide() def spinner_set_active(self, active): """ Enables/disables the Gtk.Spinner, while showing/hiding it at the same time @param active: True if the spinner should spin """ self.should_spinner_be_shown = active if active: if isinstance(self.spinner, Gtk.Spinner): self.spinner.start() self.spinner.show() else: self.spinner.hide() if isinstance(self.spinner, Gtk.Spinner): self.spinner.stop()
getting-things-gnome/gtg
GTG/gtk/backends/configurepanel.py
Python
gpl-3.0
8,882
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from module.plugins.Hoster import Hoster from module.plugins.internal.CaptchaService import ReCaptcha class FreakshareCom(Hoster): __name__ = "FreakshareCom" __type__ = "hoster" __pattern__ = r"http://(?:www\.)?freakshare\.(net|com)/files/\S*?/" __version__ = "0.38" __description__ = """Freakshare.com Download Hoster""" __author_name__ = ("sitacuisses", "spoob", "mkaay", "Toilal") __author_mail__ = ("sitacuisses@yahoo.de", "spoob@pyload.org", "mkaay@mkaay.de", "toilal.dev@gmail.com") def setup(self): self.multiDL = False self.req_opts = [] def process(self, pyfile): self.pyfile = pyfile pyfile.url = pyfile.url.replace("freakshare.net/", "freakshare.com/") if self.account: self.html = self.load(pyfile.url, cookies=False) pyfile.name = self.get_file_name() self.download(pyfile.url) else: self.prepare() self.get_file_url() self.download(self.pyfile.url, post=self.req_opts) check = self.checkDownload({"bad": "bad try", "paralell": "> Sorry, you cant download more then 1 files at time. <", "empty": "Warning: Unknown: Filename cannot be empty", "wrong_captcha": "Wrong Captcha!", "downloadserver": "No Downloadserver. Please try again later!"}) if check == "bad": self.fail("Bad Try.") elif check == "paralell": self.setWait(300, True) self.wait() self.retry() elif check == "empty": self.fail("File not downloadable") elif check == "wrong_captcha": self.invalidCaptcha() self.retry() elif check == "downloadserver": self.retry(5, 900, 'No Download server') def prepare(self): pyfile = self.pyfile self.wantReconnect = False self.download_html() if not self.file_exists(): self.offline() self.setWait(self.get_waiting_time()) pyfile.name = self.get_file_name() pyfile.size = self.get_file_size() self.wait() return True def download_html(self): self.load("http://freakshare.com/index.php", {"language": "EN"}) # Set english language in server session self.html = self.load(self.pyfile.url) def get_file_url(self): """ returns the absolute downloadable filepath """ if self.html is None: self.download_html() if not self.wantReconnect: self.req_opts = self.get_download_options() # get the Post options for the Request #file_url = self.pyfile.url #return file_url else: self.offline() def get_file_name(self): if self.html is None: self.download_html() if not self.wantReconnect: file_name = re.search(r"<h1\sclass=\"box_heading\"\sstyle=\"text-align:center;\">([^ ]+)", self.html) if file_name is not None: file_name = file_name.group(1) else: file_name = self.pyfile.url return file_name else: return self.pyfile.url def get_file_size(self): size = 0 if self.html is None: self.download_html() if not self.wantReconnect: file_size_check = re.search( r"<h1\sclass=\"box_heading\"\sstyle=\"text-align:center;\">[^ ]+ - ([^ ]+) (\w\w)yte", self.html) if file_size_check is not None: units = float(file_size_check.group(1).replace(",", "")) pow = {'KB': 1, 'MB': 2, 'GB': 3}[file_size_check.group(2)] size = int(units * 1024 ** pow) return size def get_waiting_time(self): if self.html is None: self.download_html() if "Your Traffic is used up for today" in self.html: self.wantReconnect = True return 24 * 3600 timestring = re.search('\s*var\s(?:downloadWait|time)\s=\s(\d*)[.\d]*;', self.html) if timestring: return int(timestring.group(1)) + 1 # add 1 sec as tenths of seconds are cut off else: return 60 def file_exists(self): """ returns True or False """ if self.html is None: self.download_html() if re.search(r"This file does not exist!", self.html) is not None: return False else: return True def get_download_options(self): re_envelope = re.search(r".*?value=\"Free\sDownload\".*?\n*?(.*?<.*?>\n*)*?\n*\s*?</form>", self.html).group(0) # get the whole request to_sort = re.findall(r"<input\stype=\"hidden\"\svalue=\"(.*?)\"\sname=\"(.*?)\"\s\/>", re_envelope) request_options = dict((n, v) for (v, n) in to_sort) herewego = self.load(self.pyfile.url, None, request_options) # the actual download-Page # comment this in, when it doesnt work # with open("DUMP__FS_.HTML", "w") as fp: # fp.write(herewego) to_sort = re.findall(r"<input\stype=\".*?\"\svalue=\"(\S*?)\".*?name=\"(\S*?)\"\s.*?\/>", herewego) request_options = dict((n, v) for (v, n) in to_sort) # comment this in, when it doesnt work as well #print "\n\n%s\n\n" % ";".join(["%s=%s" % x for x in to_sort]) challenge = re.search(r"http://api\.recaptcha\.net/challenge\?k=([0-9A-Za-z]+)", herewego) if challenge: re_captcha = ReCaptcha(self) (request_options["recaptcha_challenge_field"], request_options["recaptcha_response_field"]) = re_captcha.challenge(challenge.group(1)) return request_options
wangjun/pyload
module/plugins/hoster/FreakshareCom.py
Python
gpl-3.0
6,038
class ListNode: def __init__(self, x): self.val = x self.next = None def display(self): node = self while node is not None: print(node.val, end="->") node = node.next print() """ class SLinkedList: def __init__(self): self.head = None def addAtBeginning(self, aNode): if self.head: print("adding node: ", aNode.val) aNode.next = self.head self.head = aNode else: print("adding first node: ", aNode.val) self.head = aNode def display(self): print("displaying list") node = self.head while node is not None: print(node.val, "->") node = node.next """ class Solution: def addTwoNumbers(self, l1, l2): result = ListNode(0) result_tail = result carry = 0 while l1 or l2 or carry: a = (l1.val if l1 else 0) b = (l2.val if l2 else 0) carry, out = divmod(a + b + carry, 10) result_tail.next = ListNode(out) result_tail = result_tail.next l1 = (l1.next if l1 else None) l2 = (l2.next if l2 else None) return result.next if __name__ == "__main__": l1 = ListNode(9) l1.next = ListNode(6) l1.next.next = ListNode(6) l1.display() l2 = ListNode(5) l2.next = ListNode(6) l2.next.next = ListNode(4) l2.display() s = Solution() result = s.addTwoNumbers(l1, l2) print() while result: print(result.val, end="->") result = result.next
NeerajM999/recap-python
LearnPython/addLists.py
Python
gpl-3.0
1,639
# _ GraphGrammar.py __________________________________________________ # This class implements a graph grammar, that is basically an ordered # collecttion of GGrule's # ____________________________________________________________________ from GGrule import * class GraphGrammar: def __init__(self, GGrules = None): "Constructor, it receives GGrules, that is a list of GGrule elements" self.GGrules = [] # We'll insert rules by order of execution self.rewritingSystem = None # No rewriting system assigned yet while len(self.GGrules) < len(GGrules): # iterate until each rule is inserted min = 30000 # set mininum number to a very high number minRule = None # pointer to rule to be inserted for rule in GGrules: # search for the minimum execution order that is not inserted if rule.executionOrder < min and not rule in self.GGrules: min = rule.executionOrder minRule = rule self.GGrules.append(minRule) def setGraphRewritingSystem(self, rs): "Sets the attribute rewritingSystem to rs and also calls the same method for each rule" self.rewritingSystem = rs for rule in self.GGrules: rule.setGraphGrammar(self) rule.setGraphRewritingSystem(rs) def initialAction(self, graph): # , atom3i = None): "action to be performed before the graph grammar starts its execution (must be overriden)" pass def finalAction(self, graph): #, atom3i = None): "action to be performed after the graph grammar starts its execution (must be overriden)" pass
Balannen/LSMASOMM
atom3/Kernel/GraphGrammar/GraphGrammar.py
Python
gpl-3.0
1,680