Best Python code snippet using fMBT_python
rmdSimple.py
Source:rmdSimple.py
1#/*********************************************************************************2#* gtk-recordMyDesktop *3#**********************************************************************************4#* *5#* Copyright (C) 2006 John Varouhakis *6#* *7#* *8#* This program is free software; you can redistribute it and/or modify *9#* it under the terms of the GNU General Public License as published by *10#* the Free Software Foundation; either version 2 of the License, or *11#* (at your option) any later version. *12#* *13#* This program is distributed in the hope that it will be useful, *14#* but WITHOUT ANY WARRANTY; without even the implied warranty of *15#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *16#* GNU General Public License for more details. *17#* *18#* You should have received a copy of the GNU General Public License *19#* along with this program; if not, write to the Free Software *20#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *21#* *22#* *23#* *24#* For further information contact me at johnvarouhakis@gmail.com *25#**********************************************************************************/26import pygtk27pygtk.require('2.0')28import gtk29import locale, gettext30import rmdConfig31_ = gettext.gettext32gettext.textdomain('gtk-recordMyDesktop')33gettext.bindtextdomain('gtk-recordMyDesktop',rmdConfig.locale_install_dir)34import os35from rmdPrefsWidget import *36from rmdTrayIcon import *37import gtk.gdk38import gobject39import gc40import sys41import re42from subprocess import Popen,PIPE43import rmdPrefsWidget as pW44import rmdSelectThumb as sT45from rmdStrings import *46class simpleWidget(object):47 hidden=[0]48 options=None49 optionsOpen=[0]50 def __subWidgets__(self):51 self.labelbox=gtk.VBox(homogeneous=False, spacing=20)52 #self.labelbox.set_size_request(400,272)53 self.NBox=gtk.HBox(homogeneous=False, spacing=20)54 self.NEBox=gtk.VBox(homogeneous=False, spacing=0)55 self.NEVQBox=gtk.HBox(homogeneous=False, spacing=10)56 self.NESQBox=gtk.HBox(homogeneous=False, spacing=10)57 self.NETABox=gtk.VBox(homogeneous=False, spacing=10)58 self.NWBox=gtk.VBox(homogeneous=False, spacing=0)59 self.NBox.pack_start(self.NWBox,expand=False,fill=False)60 self.NBox.pack_start(self.NEBox,expand=True,fill=True)61 self.NEBox.pack_start(self.NEVQBox,expand=False,fill=False)62 self.NEBox.pack_start(self.NESQBox,expand=False,fill=False)63 self.NEBox.pack_start(self.NETABox,expand=False,fill=False)64 self.SBox=gtk.HBox(homogeneous=True, spacing=0)65 self.SEBox=gtk.HBox(homogeneous=False, spacing=10)66 self.SWBox=gtk.HBox(homogeneous=False, spacing=10)67 self.SBox.pack_start(self.SWBox,expand=True,fill=True)68 self.SBox.pack_start(self.SEBox,expand=True,fill=True)69 self.labelbox.pack_start(self.NBox,expand=False,fill=False)70 self.labelbox.pack_end(self.SBox,expand=False,fill=False)71 self.wroot = gtk.gdk.get_default_root_window()72 (self.wwidth, self.wheight) = self.wroot.get_size()73 self.factor=1;74 twidth=self.wwidth75 while twidth>320 or self.factor<4:76 twidth/=277 self.factor*=278 self.image=sT.GtkThumbSelector(self,self.values[5],self.hidden,2000)79 self.image.show()80 self.NWBox.pack_start(self.image,False,False)81 #quality82 self.v_adj=gtk.Adjustment(value=int(round((float(self.values[10])*100.0)/63.0)), lower=0, upper=100, step_incr=1, page_incr=10, page_size=0)83 self.v_quality=gtk.HScale(self.v_adj)84 self.v_quality.set_value_pos(gtk.POS_LEFT)85 self.v_quality.set_digits(0)86 self.s_button= gtk.CheckButton(label=None)87 self.s_adj=gtk.Adjustment(value=int(round(float(self.values[11])*10.0)), lower=0, upper=100, step_incr=1, page_incr=10, page_size=0)88 #print (self.values[11]*10)89 self.s_quality=gtk.HScale(self.s_adj)90 self.s_quality.set_value_pos(gtk.POS_LEFT)91 self.s_quality.set_digits(0)92 self.v_label=gtk.Label(" "+smplLabelStrings[0])93 self.s_label=gtk.Label(smplLabelStrings[1])94 self.advanced_button=gtk.Button(smplButtonStrings[0])95 self.tipLabel=gtk.Label(smplTipLabelStrings[0])96 self.NEVQBox.pack_start(self.v_label,expand=False,fill=False)97 self.NEVQBox.pack_start(self.v_quality,expand=True,fill=True)98 self.NESQBox.pack_start(self.s_button,expand=False,fill=False)99 self.NESQBox.pack_start(self.s_label,expand=False,fill=False)100 self.NESQBox.pack_start(self.s_quality,expand=True,fill=True)101 self.NETABox.pack_start(self.advanced_button,expand=False,fill=False)102 self.NETABox.pack_start(self.tipLabel,expand=False,fill=False)103 self.win_button=gtk.Button(smplButtonStrings[1])104 self.start_button=gtk.Button(None,gtk.STOCK_MEDIA_RECORD)105 self.file_button=gtk.Button(None,gtk.STOCK_SAVE_AS)106 self.quit_button=gtk.Button(None,gtk.STOCK_QUIT)107 self.SWBox.pack_start(self.win_button,False,False)108 self.SWBox.pack_start(self.start_button,False,False)109 self.SEBox.pack_end(self.quit_button,False,False)110 self.SEBox.pack_end(self.file_button,False,False)111 self.win_button.show()112 self.start_button.show()113 self.file_button.show()114 self.quit_button.show()115 self.v_quality.show()116 self.s_button.show()117 self.s_quality.show()118 self.v_label.show()119 self.s_label.show()120 self.tipLabel.show()121 self.advanced_button.show()122 self.NEVQBox.show()123 self.NESQBox.show()124 self.NETABox.show()125 self.NEBox.show()126 self.NWBox.show()127 self.NBox.show()128 self.SEBox.show()129 self.SWBox.show()130 self.SBox.show()131 self.labelbox.show()132 self.window.add(self.labelbox)133 def __tooltips__(self):134 self.tooltips=gtk.Tooltips()135 self.tooltips.set_tip(self.win_button,smplTooltipLabels[0])136 self.tooltips.set_tip(self.start_button,smplTooltipLabels[1])137 self.tooltips.set_tip(self.file_button,smplTooltipLabels[2])138 self.tooltips.set_tip(self.quit_button,smplTooltipLabels[3])139 self.tooltips.set_tip(self.v_quality,smplTooltipLabels[4])140 self.tooltips.set_tip(self.v_label,smplTooltipLabels[4])141 self.tooltips.set_tip(self.s_button,smplTooltipLabels[5])142 self.tooltips.set_tip(self.s_quality,smplTooltipLabels[6])143 self.tooltips.set_tip(self.s_label,smplTooltipLabels[6])144 self.tooltips.set_tip(self.advanced_button,smplTooltipLabels[7])145 def __exit__(self,Event=None):146 if self.exited==0:147 self.update()148 self.exited=1149 gtk.main_quit()150 #self.values[0]=-1151 self.optionsOpen[0]=0152 self.window.destroy()153 if self.save_prefs()==False:154 print "Warning!!!Couldn't save preferences"155 def hide(self,Event=None):156 if self.image.realFrame != None and self.values[25]==0:157 self.image.realFrame.window.hide()158 self.window.hide()159 self.hidden[0]=1160 def show(self,Event=None):161 if self.image.realFrame != None and self.values[25]==0:162 self.image.realFrame.window.show()163 self.window.show()164 self.hidden[0]=0165 def __swap_visibility__(self,widget=None,event=None):166 if event.changed_mask==gtk.gdk.WINDOW_STATE_ICONIFIED:167 if self.minimized==0:168 self.hidden[0]=self.minimized=1169 else:170 self.hidden[0]=self.minimized=0171 def advanced(self,button=None):172 if self.optionsOpen[0] ==0:173 self.optionsOpen[0]=1174 self.options=pW.prefsWidget(self,self.values,self.optionsOpen)175 #self.parent.show()176 else:177 if self.options != None:178 self.options.window.destroy()179 self.optionsOpen[0]=0180 def close_advanced(self):181 if self.options != None:182 if self.optionsOpen[0] ==1:183 self.options.window.destroy()184 self.optionsOpen[0]=0185 def __fileSelQuit__(self,Event=None):186 self.fileSel.destroy()187 def __fileSelOk__(self,Event=None):188 self.values[4]=self.fileSel.get_filename()189 #self.pathEntry.set_text(self.fileSel.get_filename())190 def __fileSelect__(self,Event=None):191 self.fileSel = gtk.FileChooserDialog(title=None,192 action=gtk.FILE_CHOOSER_ACTION_SAVE,193 buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,194 gtk.STOCK_SAVE,gtk.RESPONSE_OK))195 self.fileSel.set_filename(self.values[4])196 self.fileSel.show()197 if self.fileSel.run() == gtk.RESPONSE_OK:198 self.__fileSelOk__()199 self.__fileSelQuit__()200 def __select_window__(self,button):201 # check user has not disabled capture of window decoration202 if self.values[21]!=1:203 # else work out the size including decoration (also taking into account compiz)204 p = Popen(['xwininfo','-frame'],stdout=PIPE)205 pattern = re.compile('^xwininfo: Window id: (0x[0-9a-fA-F]+)')206 while True:207 o = p.stdout.readline()208 if o == '' and p.poll() != None: break209 match = pattern.search(o)210 if match:211 fid = match.group(1)212 break213 p = Popen(['xprop','-id',fid,'_NET_FRAME_WINDOW'],stdout=PIPE)214 pattern = re.compile('^_NET_FRAME_WINDOW\(WINDOW\): window id # (0x[0-9a-fA-F]+)')215 while True:216 o = p.stdout.readline()217 if o == '' and p.poll() != None: break218 match = pattern.search(o)219 if match:220 wid = match.group(1)221 break222 else:223 print pattern224 print o225 if wid: xwininfo_com = ['xwininfo','-id',wid]226 else: xwininfo_com = ['xwininfo']227 p = Popen(xwininfo_com,stdout=PIPE)228 wid=p.stdout.readlines()229 x=y=width=height=None230 for i in wid:231 if i.lstrip().startswith('Absolute upper-left X:'):232 x=int(i.split(' ')[len(i.split(' '))-1])233 elif i.lstrip().startswith('Absolute upper-left Y'):234 y=int(i.split(' ')[len(i.split(' '))-1])235 elif i.lstrip().startswith('Width:'):236 width=int(i.split(' ')[len(i.split(' '))-1])237 elif i.lstrip().startswith('Height:'):238 height=int(i.split(' ')[len(i.split(' '))-1])239 if x<0:240 width+=x241 x=0242 if y<0:243 height+=y244 y=0245 if width+x>self.wwidth: width=self.wwidth-x246 if height+y>self.wheight: height=self.wheight-y247 self.values[5][0]=x248 self.values[5][1]=y249 self.values[5][2]=width+x250 self.values[5][3]=height+y251 self.image.update_image()252 def __makeCons__(self):253 self.advanced_button.connect("clicked",self.advanced)254 self.file_button.connect("clicked",self.__fileSelect__)255 self.quit_button.connect("clicked",self.__exit__)256 self.start_button.connect("clicked",self.trayIcon.record_ext)257 self.s_button.connect("clicked",self.__sound_check__)258 self.win_button.connect("clicked",self.__select_window__)259 self.window.connect("window-state-event",self.__swap_visibility__)260 def __register_shortcuts__(self):261 self.advanced_button.add_accelerator("clicked",self.accel_group,262 ord('P'), gtk.gdk.CONTROL_MASK,263 gtk.ACCEL_VISIBLE)264 self.file_button.add_accelerator("clicked",self.accel_group,265 ord('S'), gtk.gdk.CONTROL_MASK,266 gtk.ACCEL_VISIBLE)267 self.quit_button.add_accelerator("clicked",self.accel_group,268 ord('Q'), gtk.gdk.CONTROL_MASK,269 gtk.ACCEL_VISIBLE)270 self.start_button.add_accelerator("clicked",self.accel_group,271 ord('R'), gtk.gdk.CONTROL_MASK,272 gtk.ACCEL_VISIBLE)273 self.trayIcon.tray_popup.popupmenu_prefs_widget.add_accelerator(274 "activate",self.accel_group,275 ord('H'), gtk.gdk.CONTROL_MASK,276 gtk.ACCEL_VISIBLE277 )278 self.trayIcon.tray_popup.popupmenu_prefs_widget.add_accelerator(279 "activate",self.accel_group,280 gtk.gdk.keyval_from_name("Escape"),0,281 gtk.ACCEL_VISIBLE282 )283 def __sound_check__(self,widget):284 self.s_quality.set_sensitive(widget.get_active())285 self.values[2]=widget.get_active()286 def update(self) :287 self.values[10]=int(round((float(self.v_quality.get_value())*63.0)/100.0))288 self.values[11]=int(round(float(self.s_quality.get_value())/10.0))289 if self.values[10]>63:290 self.values[10]=63291 if self.values[11]>10:292 self.values[11]=10293 def load_prefs(self):294 path=os.path.join(os.getenv("HOME"),".gtk-recordmydesktop")295 try:296 self.values=[]297 savefile=open(path,"r")298 #the header299 savefile.readline()300 savefile.readline()301 #the options,each has a coment above302 for i in range(2):303 savefile.readline()304 self.values.append(int(savefile.readline()))305 savefile.readline()306 self.values.append(int(savefile.readline())==1)307 savefile.readline()308 self.values.append(int(savefile.readline()))309 savefile.readline()310 self.values.append(savefile.readline().replace("\n",""))311 #recording area is not saved312 self.values.append([])313 for i in range(3):314 savefile.readline()315 self.values.append(int(savefile.readline()))316 savefile.readline()317 self.values.append(savefile.readline().replace("\n",""))318 for i in range(2):319 savefile.readline()320 self.values.append(int(savefile.readline()))321 savefile.readline()322 self.values.append(savefile.readline().replace("\n",""))323 for i in range(2):324 savefile.readline()325 self.values.append(int(savefile.readline()))326 savefile.readline()327 areastring=savefile.readline()328 try:329 as1=areastring.replace('\n','').split(',')330 for i in range(4):331 self.values[5].append(int(as1[i]))332 except:333 self.values[5]=[]334 for i in rmdConfig.default_values[5]:335 self.values[5].append(i)336 #loaded further bellow337 self.values.append(0)338 savefile.readline()339 self.values.append(int(savefile.readline()))340 savefile.readline()341 self.values.append(savefile.readline().replace("\n",""))342 for i in range(2):343 savefile.readline()344 self.values.append(int(savefile.readline()))345 savefile.readline()346 self.values.append(int(savefile.readline())==1)347 #new options for 0.3.3348 p=savefile.readline()349 if p=='':350 self.values.append(rmdConfig.default_values[21])351 else:352 self.values.append(int(savefile.readline()))353 p=savefile.readline()354 if p=='':355 self.values.append(rmdConfig.default_values[22])356 self.values.append(rmdConfig.default_values[23])357 else:358 self.values.append(int(savefile.readline())==1)359 p=savefile.readline()360 if p=='':361 self.values.append(rmdConfig.default_values[23])362 else:363 ports_t=savefile.readline().split(' ')364 #get rid of the trailing \n365 ports_t.pop()366 self.values.append(ports_t)367 p=savefile.readline()368 if p=='':369 self.values.append(rmdConfig.default_values[24])370 else:371 self.values.append(int(savefile.readline()))372 p=savefile.readline()373 if p=='':374 self.values.append(rmdConfig.default_values[25])375 else:376 self.values.append(int(savefile.readline()))377 p=savefile.readline()378 if p=='':379 self.values.append(rmdConfig.default_values[26])380 else:381 self.values.append(savefile.readline().replace("\n",""))382 p=savefile.readline()383 if p=='':384 self.values[15]=rmdConfig.default_values[15]385 else:386 t_followmouse=int(savefile.readline())387 if t_followmouse>1: t_followmouse=1388 self.values[15]=t_followmouse389 return True390 except:391 return False392 def save_prefs(self):393 try:394 path=os.path.join(os.getenv("HOME"),".gtk-recordmydesktop")395 savefile=open(path,"w")396 savefile.write("#Order and overall number of lines must be preserved\n")397 savefile.write("#For this file to be read correctly\n")398 savefile.write("#Framerate\n")399 savefile.write("%d\n"%self.values[0])400 savefile.write("#Cursor(0 xfixes,1 white,2 black,3 none)\n")401 savefile.write("%d\n"%self.values[1])402 savefile.write("#Sound,0 disabled 1 enabled\n")403 savefile.write("%d\n"%self.values[2])404 savefile.write("#Full shots,1 disabled 0 enabled\n")405 savefile.write("%d\n"%self.values[3])406 savefile.write("#Filename\n")407 savefile.write("%s\n"%self.values[4])408 savefile.write("#Delay,seconds\n")409 savefile.write("%d\n"%self.values[6])410 savefile.write("#Number of channels\n")411 savefile.write("%d\n"%self.values[7])412 savefile.write("#Frequency\n")413 savefile.write("%d\n"%self.values[8])414 savefile.write("#Sound-device\n")415 savefile.write("%s\n"%self.values[9])416 savefile.write("#Video quality(0-63)\n")417 savefile.write("%d\n"%self.values[10])418 savefile.write("#Audio quality(0-10)\n")419 savefile.write("%d\n"%self.values[11])420 savefile.write("#Display\n")421 savefile.write("%s\n"%self.values[12])422 savefile.write("#Shared memory,1 disabled 0 enabled\n")423 savefile.write("%d\n"%self.values[13])424 savefile.write("#Reset capture area,1 disabled 0 enabled\n")425 savefile.write("%d\n"%self.values[14])426 savefile.write("#Recording area\n")427 if(self.values[14]):428 savefile.write("%d,%d,%d,%d\n"%(self.values[5][0],self.values[5][1],self.values[5][2],self.values[5][3]))429 else:430 savefile.write("%d,%d,%d,%d\n"%(rmdConfig.default_values[5][0],rmdConfig.default_values[5][1],rmdConfig.default_values[5][2],rmdConfig.default_values[5][3]))431 savefile.write("#Quick subsampling,1 disabled 0 enabled\n")432 savefile.write("%d\n"%self.values[16])433 savefile.write("#Working directory(temporary files)\n")434 savefile.write("%s\n"%self.values[17])435 savefile.write("#On the fly encoding,1 disabled 0 enabled\n")436 savefile.write("%d\n"%self.values[18])437 savefile.write("#Zero compression,1 disabled 0 enabled\n")438 savefile.write("%d\n"%self.values[19])439 savefile.write("#overwrite existing files,0 disabled 1 enabled\n")440 savefile.write("%d\n"%self.values[20])441 savefile.write("#Include window decorations,1 disabled 0 enabled\n")442 savefile.write("%d\n"%self.values[21])443 savefile.write("#Use jack\n")444 savefile.write("%d\n"%self.values[22])445 savefile.write("#last used jack ports\n")446 for i in self.values[23]:447 savefile.write("%s "%i)448 savefile.write("\n")449 savefile.write("#Tooltips,1 disabled 0 enabled\n")450 savefile.write("%d\n"%self.values[24])451 savefile.write("#draw an on-screen frame, surrounding the capture area\n")452 savefile.write("%d\n"%self.values[25])453 savefile.write("#Extra options\n")454 savefile.write("%s\n"%self.values[26])455 savefile.write("#Follow mouse,1 disabled 0 enabled\n")456 savefile.write("%d\n"%self.values[15])457 savefile.flush()458 savefile.close()459 return True460 except:461 return False462 def __init__(self):463 if self.load_prefs()==False:464 self.values= rmdConfig.default_values465 self.optionsOpen=[0]466 self.minimized=0467 self.exited=0468 self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)469 self.window.connect("destroy", self.__exit__)470 self.window.set_border_width(10)471 self.window.set_title("recordMyDesktop")472 self.__subWidgets__()473 self.accel_group = gtk.AccelGroup()474 self.window.add_accel_group(self.accel_group)475 #self.timed_id=gobject.timeout_add(2000,self.__update_image__)476 #if resolution is low let it decide size on it's own477 #if self.wwidth>640:478 #self.window.set_size_request(int(self.wwidth/self.factor*2.3),-1)479 #self.window.set_resizable(False)480 self.trayIcon=trayIcon(self)481 self.__makeCons__()482 self.__register_shortcuts__()483 if self.values[24]==0:484 self.__tooltips__()485 self.s_quality.set_sensitive(self.values[2])486 self.s_button.set_active(self.values[2])487 self.window.show()488# wh=self.window.size_request()489# self.window.set_size_request(wh[0],wh[1])...
assetsreport.py
Source:assetsreport.py
1from PyQt5.QtCore import QObject, QTime, QCoreApplication, QEventLoop2from datetime import datetime, date3from officegenerator import ODT4from os import makedirs5from xulpymoney.datetime_functions import days2string, dtnaive2string6from xulpymoney.version import __version__7from xulpymoney.objects.assets import Assets8from xulpymoney.objects.annualtarget import AnnualTarget9from xulpymoney.objects.percentage import Percentage10from xulpymoney.package_resources import package_filename11class AssetsReport(ODT, QObject):12 def __init__(self, mem, filename):13 ODT.__init__(self, filename, package_filename("xulpymoney", "templates/AssetsReport.odt"))14 QObject.__init__(self)15 self.mem=mem16 self.datetime=datetime.now()17 self.dir='/tmp/AssetsReport-{}'.format(dtnaive2string(datetime.now(), "%Y%m%d%H%M"))18 makedirs(self.dir, exist_ok=True)19 20 def generate(self):21 self.setMetadata( self.tr("Assets report"), self.tr("This is an automatic generated report from Xulpymoney"), "Xulpymoney-{}".format(__version__))22 self.variables()23 self.cover()24 self.body()25 self.save() 26 27 def variables(self):28 self.vTotalLastYear=Assets(self.mem).saldo_total(self.mem.data.investments, date(date.today().year-1, 12, 31))29 self.vTotal=Assets(self.mem).saldo_total(self.mem.data.investments, date.today())30 def cover(self):31 self.search_and_replace("__TITLE__", self.tr("Assets Report"), type_="P")32 self.search_and_replace("__SUBTITLE__", self.tr("Generated by Xulpymoney-{}".format(__version__)), type_="P")33 self.search_and_replace("__DATETIME__", str(self.datetime), type_="P")34 self.pageBreak()35 36 def body(self):37 # About38 self.header(self.tr("About Xulpymoney"), 1)39 40 # Assets41 self.header(self.tr("Assets"), 1)42 self.simpleParagraph(self.tr("Total assets of the user are {}.").format(self.vTotal))43 if self.vTotalLastYear.isZero()==False:44 moreorless=self.tr("more")45 if (self.vTotal-self.vTotalLastYear).isLTZero():46 moreorless=self.tr("less")47 self.simpleParagraph(self.tr("It's a {} {} of the total assets at the end of the last year.").format(Percentage(self.vTotal-self.vTotalLastYear, self.vTotalLastYear), moreorless))48 49 # Assets by bank50 self.header(self.tr("Assets by bank"), 2)51 self.mem.frmMain.on_actionBanks_triggered()52 53 model=self.mem.frmMain.w.mqtwBanks.officegeneratorModel()54 model.removeColumns([1,])55 model.odt_table(self, 10, 8 )56 self.simpleParagraph(self.tr("Sum of all bank balances is {}").format(self.mem.frmMain.w.banks.balance()))57 self.pageBreak(True)58 # Assests current year59 self.header(self.tr("Assets current year evolution"), 2)60 61 #wdgTotal62 self.mem.frmMain.on_actionTotalReport_triggered()63 model=self.mem.frmMain.w.mqtw.officegeneratorModel("mqtwTotal")64 model.odt_table(self, 26, 6)65 66 ## Target67 target=AnnualTarget(self.mem).init__from_db(date.today().year)68 self.simpleParagraph(self.tr("The investment system has established a {} year target.").format(target.percentage)+" " +69 self.tr("With this target you will gain {} at the end of the year.").format(self.mem.localmoney(target.annual_balance())) +" " +70 self.tr("Up to date you have got {} (gains + dividends) what represents a {} of the target.").format(self.mem.frmMain.w.tmm.dividends()+self.mem.frmMain.w.tmm.gains(), Percentage(self.mem.frmMain.w.tmm.gains()+self.mem.frmMain.w.tmm.dividends(), target.annual_balance())))71 self.pageBreak(True)72 73 ### Assets evolution graphic74 self.header(self.tr("Assets graphical evolution"), 2)75 76 self.mem.frmMain.w.load_graphic(animations=False)77 self.mem.frmMain.w.tab.setCurrentIndex(1)78 savefile="{}/wdgTotal.png".format(self.dir)79 self.mem.frmMain.w.wdgTS.ts.save(savefile)80 self.addImage(savefile, savefile)81 self.illustration([savefile, ], 25, 13, savefile)82 self.pageBreak()83 84 85 ### Current year investment gains by product type86 self.header(self.tr("Current year investment gains group by product type"), 2)87 self.mem.frmMain.w.on_actionGainsByProductType_triggered()88 model=self.mem.frmMain.w.tab.currentWidget().children()[1].officegeneratorModel("mqtwTotal")#Widget generated dinamically. mqtw is childre[1]89 model.odt_table(self, 18, 9)90 self.pageBreak()91 ## Accounts92 self.header(self.tr("Current Accounts"), 1)93 data=[]94 self.mem.data.accounts_active().order_by_name()95 for account in self.mem.data.accounts_active().arr:96 data.append((account.name, account.bank.name, account.balance()))97 self.table( [self.tr("Account"), self.tr("Bank"), self.tr("Balance")], data, [6, 6, 3], 9) 98 99 self.simpleParagraph(self.tr("Sum of all account balances is {}").format(self.mem.data.accounts_active().balance()))100 101 self.pageBreak(True)102 103 ## Investments104 self.header(self.tr("Current investments"), 1)105 106 self.header(self.tr("Investments list"), 2)107 self.simpleParagraph(self.tr("Next list is sorted by the distance in percent to the selling point."))108 self.mem.frmMain.on_actionInvestments_triggered()109 110 model=self.mem.frmMain.w.mqtwInvestments.officegeneratorModel()111 model.removeColumns([1, 2, 3, 4])112 model.odt_table(self, 26, 8 )113 114 suminvertido=self.mem.data.investments_active().invested()115 sumpendiente=self.mem.data.investments_active().pendiente()116 if suminvertido.isZero()==False:117 self.simpleParagraph(self.tr("Sum of all invested assets is {}.").format(suminvertido))118 self.simpleParagraph(self.tr("Investment gains (positive minus negative results): {} - {} are {}, what represents a {} of total assets.").format(self.mem.data.investments_active().pendiente_positivo(), self.mem.data.investments_active().pendiente_negativo(), sumpendiente, Percentage(sumpendiente, suminvertido)))119 self.simpleParagraph(self.tr(" Assets average age: {}").format( days2string(self.mem.data.investments_active().average_age())))120 else:121 self.simpleParagraph(self.tr("There aren't invested assets"))122 self.pageBreak(True)123 124 125 ### Current Investment Operations list126 self.header(self.tr("Current investment operations"), 2)127 self.mem.frmMain.on_actionInvestmentsOperations_triggered()128 model=self.mem.frmMain.w.mqtwCurrent.officegeneratorModel(self.tr("CurrentInvestmentOperations"))129 model.removeColumns([8, 9, 11]) 130 model.odt_table(self, 26, 6) 131 self.pageBreak(True)132 133 ### Graphics wdgInvestments clases134 self.mem.frmMain.on_actionInvestmentsClasses_triggered()135 self.mem.frmMain.w.open_all_tabs()#Load tabs to finish animations136 self.mem.frmMain.w.viewTPC.on_actionShowData_triggered()137 self.mem.frmMain.w.viewTipo.on_actionShowData_triggered()138 self.mem.frmMain.w.viewApalancado.on_actionShowData_triggered()139 self.mem.frmMain.w.viewProduct.on_actionShowData_triggered()140 self.mem.frmMain.w.viewCountry.on_actionShowData_triggered()141 self.mem.frmMain.w.viewPCI.on_actionShowData_triggered()142 143 self.header(self.tr("Investments group by variable percentage"), 2)144 savefile="{}/wdgInvestmentsClasses_canvasTPC_legend.png".format(self.dir)145 self.mem.frmMain.w.tab.setCurrentIndex(0)146 self.sleep(2)147 self.mem.frmMain.w.viewTPC.pie.save(savefile)148 self.addImage(savefile, savefile)149 self.illustration([savefile, ], 25, 13, savefile)150 self.pageBreak(True)151 152 self.header(self.tr("Investments group by investment type"), 2)153 savefile="{}/wdgInvestmentsClasses_canvasTipo_legend.png".format(self.dir)154 self.mem.frmMain.w.tab.setCurrentIndex(2)155 self.sleep(2)156 self.mem.frmMain.w.viewTipo.pie.save(savefile)157 self.addImage(savefile, savefile)158 self.illustration([savefile, ], 25, 13, savefile)159 self.pageBreak(True)160 161 self.header(self.tr("Investments group by leverage"), 2) 162 savefile="{}/wdgInvestmentsClasses_canvasApalancado_legend.png".format(self.dir)163 self.mem.frmMain.w.tab.setCurrentIndex(3)164 self.sleep(2)165 self.mem.frmMain.w.viewApalancado.pie.save(savefile)166 self.addImage(savefile, savefile)167 self.illustration([savefile, ], 25, 13, savefile)168 self.pageBreak(True)169 170 self.header(self.tr("Investments group by investment product"), 2)171 savefile="{}/wdgInvestmentsClasses_canvasProduct_legend.png".format(self.dir)172 self.mem.frmMain.w.tab.setCurrentIndex(5)173 self.sleep(2)174 self.mem.frmMain.w.viewProduct.pie.save(savefile)175 self.addImage(savefile, savefile)176 self.illustration([savefile, ], 25, 13, savefile)177 self.pageBreak(True)178 179 self.header(self.tr("Investments group by country"), 2)180 savefile="{}/wdgInvestmentsClasses_canvasCountry_legend.png".format(self.dir)181 self.mem.frmMain.w.tab.setCurrentIndex(4)182 self.sleep(2)183 self.mem.frmMain.w.viewCountry.pie.save(savefile)184 self.addImage(savefile, savefile)185 self.illustration([savefile, ], 25, 13, savefile)186 self.pageBreak(True)187 188 self.header(self.tr("Investments group by Call/Put/Inline"), 2)189 savefile="{}/wdgInvestmentsClasses_canvasPCI_legend.png".format(self.dir)190 self.mem.frmMain.w.tab.setCurrentIndex(1)191 self.sleep(2)192 self.mem.frmMain.w.viewPCI.pie.save(savefile)193 self.addImage(savefile, savefile)194 self.illustration([savefile, ], 25, 13, savefile)195 196 self.mem.frmMain.showMaximized()197 self.pageBreak(True)198 199 #Orders report200 self.header(self.tr("Investments orders"), 1)201 self.mem.frmMain.on_actionOrders_triggered() 202 self.simpleParagraph(self.tr("These are the current investment orders that have been set in your banks"))203 model=self.mem.frmMain.w.mqtwOrders.officegeneratorModel("mqtwOrders")204 model.odt_table(self, 26, 8)205 self.pageBreak(True)206 207 #Dividend report208 self.header(self.tr("Dividend estimations report"), 1)209 self.mem.frmMain.on_actionDividendsReport_triggered()210 model=self.mem.frmMain.w.mqtw.officegeneratorModel("mqtwDividendsReport")211 model.odt_table(self, 26, 8)212 self.simpleParagraph(self.tr("If I keep this investment during a year, I'll get {0}").format(Assets(self.mem).dividends_estimated()))213 self.pageBreak(True)214 215 # Ranking de investments216 self.header(self.tr("Historical investments ranking"), 1) 217 self.mem.frmMain.on_actionInvestmentRanking_triggered()218 model=self.mem.frmMain.w.mqtwCurrentOperations.officegeneratorModel("mqtwCurrentOperations")219 model.vh=list(range(1, len(model.data)+1))220 model.odt_table(self, 26, 8) 221 def sleep(self, seconds):222 dieTime= QTime.currentTime().addSecs(seconds);223 while (QTime.currentTime() < dieTime):...
FILEIO.PY
Source:FILEIO.PY
1import json23'''4savefile.txt è¨é總è³æ5lendout.txt è¨éååºä¸è³æ67'''89def updateItem(name, content):10 try:11 f = open("storage//savefile.txt", "r")12 json.loads(f.read())13 except (FileNotFoundError, ValueError) as e:14 print("File not exist or invalid JSON, recreating savefile.txt...")15 print(e)16 f = open("storage//savefile.txt", "w")17 f.write("{}")18 fr = open("storage//savefile.txt", "r")19 savefile = json.loads(fr.read())20 savefile[name] = content21 fw = open("storage//savefile.txt", "w")22 fw.write(json.dumps(savefile, indent=4))23 24def removeItem(name):25 try:26 f = open("storage//savefile.txt", "r")27 json.loads(f.read())28 except (FileNotFoundError, ValueError) as e:29 print("File not exist or invalid JSON, recreating savefile.txt...")30 print(e)31 f = open("storage//savefile.txt", "w")32 f.write("{}")33 fr = open("storage//savefile.txt", "r")34 savefile = json.loads(fr.read())35 del savefile[name]36 fw = open("storage//savefile.txt", "w")37 fw.write(json.dumps(savefile, indent=4))38 39def saveAll(data):40 try:41 f = open("storage//savefile.txt", "r")42 json.loads(f.read())43 except (FileNotFoundError, ValueError) as e:44 print("File not exist or invalid JSON, recreating savefile.txt...")45 print(e)46 f = open("storage//savefile.txt", "w")47 f.write("{}")48 fw = open("storage//savefile.txt", "w")49 fw.write(json.dumps(data, indent=4))50 51def readAll():52 try:53 f = open("storage//savefile.txt", "r")54 json.loads(f.read())55 except (FileNotFoundError, ValueError) as e:56 print("Cannot find file or file corrupted.")57 f = open("storage//savefile.txt", "w")58 f.write("{}")59 return {}60 fr = open("storage//savefile.txt", "r")61 savefile = json.loads(fr.read())62 return savefile6364def clearAll():65 f = open("storage//savefile.txt", "w")66 f.write("{}")67 clearLend()686970def saveLend(data):71 try:72 f = open("storage//lendout.txt", "r")73 json.loads(f.read())74 except (FileNotFoundError, ValueError) as e:75 print("File not exist or invalid JSON, recreating savefile.txt...")76 print(e)77 f = open("storage//savefile.txt", "w")78 f.write("[]")79 fr = open("storage//lendout.txt", "r")80 savefile = json.loads(fr.read())81 savefile.append(data)82 fw = open("storage//lendout.txt", "w")83 fw.write(json.dumps(savefile, indent=4))84 85def giveBack(data):86 try:87 f = open("storage//lendout.txt", "r")88 json.loads(f.read())89 except (FileNotFoundError, ValueError) as e:90 print("File not exist or invalid JSON, recreating savefile.txt...")91 print(e)92 f = open("storage//savefile.txt", "w")93 f.write("[]")94 fr = open("storage//lendout.txt", "r")95 savefile = json.loads(fr.read())96 savefile.remove(data)97 fw = open("storage//lendout.txt", "w")98 fw.write(json.dumps(savefile, indent=4))99 100101def readLend():102 try:103 f = open("storage//lendout.txt", "r")104 json.loads(f.read())105 except (FileNotFoundError, ValueError) as e:106 print("Cannot find file or file corrupted.")107 f = open("storage//lendout.txt", "w")108 f.write("[]")109 fr = open("storage//lendout.txt", "r")110 savefile = json.loads(fr.read())111 return savefile112113def clearLend():114 f = open("storage//lendout.txt", "w")115 f.write("[]")
...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!