def test_format_string(): say = Fmt() x = 33.123456789 assert say("{x} is floating point!") == '33.123456789 is floating point!' assert say("{x:0.2f} is shorter") == '33.12 is shorter' assert say("{x:8.3f} is in the middle") == ' 33.123 is in the middle'
def test_example_3(): say = Fmt() items = '1 2 3'.split() assert say('TITLE') == 'TITLE' for item in items: assert say(item, indent=1) == ' ' + str(item)
def test_numberer(): say = Fmt(end='\n', prefix=numberer()) assert say('this\nand\nthat') == ' 1: this\n 2: and\n 3: that\n' say = Fmt(end='\n', prefix=numberer(template='{n:>4d}: ', start=100)) assert say('this\nand\nthat') == ' 100: this\n 101: and\n 102: that\n'
def test_colored_output(): say = Fmt() with say.settings(prefix='\x1b[34m', suffix='\x1b[0m'): assert say('this is blue!') == '\x1b[34mthis is blue!\x1b[0m' assert say('not blue') == 'not blue' blue = say.clone(prefix='\x1b[34m', suffix='\x1b[0m') assert blue('BLUE') == '\x1b[34mBLUE\x1b[0m'
def __init__(self, constraintSystem): self.constraintSystem = constraintSystem self.form = FreeCADGui.PySideUic.loadUi( ':/assembly2/ui/degreesOfFreedomAnimation.ui' ) self.form.setWindowIcon(QtGui.QIcon( ':/assembly2/icons/degreesOfFreedomAnimation.svg' ) ) self.form.groupBox_DOF.setTitle('%i Degrees-of-freedom:' % len(constraintSystem.degreesOfFreedom)) FreeCAD.DOF=constraintSystem.degreesOfFreedom for i, d in enumerate(constraintSystem.degreesOfFreedom): item = QtGui.QListWidgetItem('%i. %s' % (i+1, str(d)[1:-1].replace('DegreeOfFreedom ','')), self.form.listWidget_DOF) if i == 0: item.setSelected(True) # hack start create animation tools import Animation from say import * import Placer for i, d in enumerate(constraintSystem.degreesOfFreedom): sayErr(i) say(d.__class__.__name__) say(d.objName) p=Placer.createPlacer("DOF_" + str(i) +"_") p.ViewObject.Visibility=False p.target=FreeCAD.ActiveDocument.getObject(d.objName) if d.__class__.__name__ == 'LinearMotionDegreeOfFreedom': p.x='x0+x1*(time-0.5)*50' p.y='y0+y1*(time-0.5)*50' p.z='z0+z1*(time-0.5)*50' b=p.target.Placement.Base p.x0=b.x p.y0=b.y p.z0=b.z p.x1=d.directionVector[0] p.y1=d.directionVector[1] p.z1=d.directionVector[2] p.RotAxis=p.target.Placement.Rotation.Axis p.arc=str(p.target.Placement.Rotation.Angle*180/np.pi) if d.__class__.__name__ == 'AxisRotationDegreeOfFreedom': p.prePlacement=p.target.Placement p.arc='360*time' p.x='0' p.y='0' p.z='0' p.arc0=d.getValue()*180/np.pi p.RotAxis=(d.axis[0],d.axis[1],d.axis[2]) p.RotCenter=p.target.Placement.Base # hack end self.form.pushButton_animateSelected.clicked.connect(self.animateSelected) self.form.pushButton_animateAll.clicked.connect(self.animateAll) self.form.pushButton_set_as_default.clicked.connect( self.setDefaults ) self.setIntialValues()
def test_with_indent(): say = Fmt() with say.settings(indent='+1'): assert say("I am indented!") == " I am indented!" with say.settings(indent='+1'): assert say("xyz") == " xyz" assert say('one back') == ' one back' assert say('back again') == 'back again'
def test_unicode(): say = Fmt() u = six.u('This\u2014is Unicode!') assert say(u) == u assert say("Hey! {u}") == six.u('Hey! This\u2014is Unicode!') too = "too" assert say(six.u("Unicode templates {too}")) == six.u("Unicode templates too")
def test_prefix_suffix(): say = Fmt() assert say('x', prefix='<', suffix='>') == '<x>' assert say('x', end='\n--') == 'x\n--' assert say('a\nb\nc', prefix='> ') == '> a\n> b\n> c' assert say('a\nb\nc', prefix='> ', suffix='\n') == '> a\n\n> b\n\n> c\n' quoter = say.clone(prefix='> ') assert quoter('a\nb\nc') == '> a\n> b\n> c'
def test_indent_special(): say = Fmt() say.set(indent_str='>>> ') assert say('something') == 'something' assert say('else', indent=1) == '>>> else' assert say('again', indent=2) == '>>> >>> again' say.set(indent_str='| ') assert say("some text") == 'some text' assert say("other", indent="+1") == '| other'
def test_localvar(): say = Fmt() m = "MIGHTY" assert say(m) == "MIGHTY" assert say("{m}") == "MIGHTY" globalvar = "tasty" # override global var assert say(globalvar) == "tasty" assert say("{globalvar}") == "tasty"
def temp(citi): url = 'https://danepubliczne.imgw.pl/api/data/synop' response = get(url) for row in loads(response.text): #print(row) if row['stacja'] in citi: t = row['temperatura'] say(t.replace(".", ",") + '°C')
def test_example_2(): say = Fmt() errors = [{'name': 'I/O Error', 'timestamp': 23489273}, {'name': 'Compute Error', 'timestamp': 349734289}] say.title('Errors') for i, e in enumerate(errors, start=1): say("{i:3}: {e['name'].upper()}")
def t2nt(self, time): a = self.obj2.a b = self.obj2.b c = self.obj2.c d = self.obj2.d m = self.obj2.m g = self.obj2.g newtime = eval(self.obj2.trafo) say(str(time) + " " + self.obj2.trafo + " " + str(newtime)) return newtime
def t2nt(self,time): a=self.obj2.a b=self.obj2.b c=self.obj2.c d=self.obj2.d m=self.obj2.m g=self.obj2.g newtime=eval(self.obj2.trafo) say(str(time) +" " +self.obj2.trafo +" " + str(newtime)) return newtime
def test_files(capsys, tmpdir): say = Say() tmpfile = tmpdir.join('test.txt') say.setfiles([sys.stdout, tmpfile]) text = "Yowza!" say(text) assert tmpfile.read() == text + "\n" assert capsys.readouterr()[0] == text + "\n"
def test_sep_end(): say = Fmt() assert say(1, 2, 3) == '1 2 3' assert say(1, 2, 3, sep=',') == '1,2,3' assert say(1, 2, 3, sep=', ') == '1, 2, 3' say('xyz', end='\n') == 'xyz\n' say('xyz', end='\n\n') == 'xyz\n\n' say('xyz', end='') == 'xyz'
def pogo(citi2): url = 'https://danepubliczne.imgw.pl/api/data/synop' response = get(url) for row in loads(response.text): #print(row) if row['stacja'] in citi2: s = row["suma_opadu"] a0 = ["0"] if s in a0: say("Jest tam słonecznie")
def test_fork(): say = Fmt() say = Fmt() assert say("this") == "this" sayf = say.fork(prefix="*") assert sayf("this") == "*this" say.set(indent="+1") assert say("this") == " this" assert sayf("this") == "*this"
def test_SayReturn(capsys, tmpdir): say = SayReturn() tmpfile = tmpdir.join('test.txt') say.setfiles([tmpfile]) text1 = "Yowza!" result1 = say(text1) assert result1 == text1 text2 = "This is the second test. {text1}" result2 = say(text2) assert result2 == "This is the second test. Yowza!"
def test_indent(): say = Fmt() assert say('no indent') == 'no indent' assert say('no indent', indent=0) == 'no indent' assert say('one indent', indent='1') == ' one indent' assert say('one indent', indent='+1') == ' one indent' assert say('two indent', indent=2) == ' two indent' say.set(indent=1) assert say('auto one indent') == ' auto one indent' assert say('one plus one indent', indent='+1') == ' one plus one indent' assert say('subtract indent', indent='-1') == 'subtract indent' assert say('force no indent', indent=0) == 'force no indent' say.set(indent=0) assert say('no indent again') == 'no indent again'
def attach(self,vobj): # items for edit dialog and contextmenue self.emenu=[['A',self.funA],['Diagram',self.diagram],] self.cmenu=self.emenu say("VO attach " + str(vobj.Object.Label)) vobj.Proxy = self self.Object = vobj.Object self.obj2=self.Object self.Object.Proxy.Lock=False self.Object.Proxy.Changed=False icon='/icons/animation.png' self.iconpath = __dir__ + icon self.vers=__vers__ return
def update(self): time=self.obj2.time try: say("update time=" + str(time) + ", "+ self.obj2.Label) except: say("update (ohne Label)") time==self.obj2.time a=self.obj2.a b=self.obj2.b c=self.obj2.c d=self.obj2.d newtime=eval(self.obj2.trafo) self.obj2.target.Proxy.step(newtime) self.obj2.target.Proxy.update()
def update(self): time = self.obj2.time try: say("update time=" + str(time) + ", " + self.obj2.Label) except: say("update (ohne Label)") time == self.obj2.time a = self.obj2.a b = self.obj2.b c = self.obj2.c d = self.obj2.d newtime = eval(self.obj2.trafo) self.obj2.target.Proxy.step(newtime) self.obj2.target.Proxy.update()
def test_clone(): say = Fmt() assert say("this") == "this" say1 = say.clone() assert say1("this") == "this" say2 = say.but() assert say2("this") == "this" say2a = say.but(indent="+1") assert say2a("this") == " this" say.set(prefix='|') assert say("this") == "|this" assert say2a("this") == "| this"
def execute(self,obj): #say(obj.Label) #say(obj.ViewObject.Visibility) try: self.Lock except: self.Lock= False self.obj2=obj if not obj.ViewObject.Visibility: return if not self.Lock: self.Lock=True try: self.findCollision() say("findCollision done\n") except: sayexc("except Fehler beim execute") self.Lock=False
def t2ntforce(self,time): a=self.obj2.a b=self.obj2.b c=self.obj2.c d=self.obj2.d m=self.obj2.m g=self.obj2.g newtime1=eval(self.obj2.trafo) time += 0.01 newtime2=eval(self.obj2.trafo) time -= 2*0.01 newtime0=eval(self.obj2.trafo) newtime=(newtime2-2*newtime1+newtime0)/0.01*g say(str(time) +" " +self.obj2.trafo +" force " + str(newtime)) return newtime
def t2ntforce(self, time): a = self.obj2.a b = self.obj2.b c = self.obj2.c d = self.obj2.d m = self.obj2.m g = self.obj2.g newtime1 = eval(self.obj2.trafo) time += 0.01 newtime2 = eval(self.obj2.trafo) time -= 2 * 0.01 newtime0 = eval(self.obj2.trafo) newtime = (newtime2 - 2 * newtime1 + newtime0) / 0.01 * g say(str(time) + " " + self.obj2.trafo + " force " + str(newtime)) return newtime
def execute(self, obj): #say(obj.Label) #say(obj.ViewObject.Visibility) try: self.Lock except: self.Lock = False self.obj2 = obj if not obj.ViewObject.Visibility: return if not self.Lock: self.Lock = True try: self.findCollision() say("findCollision done\n") except: sayexc("except Fehler beim execute") self.Lock = False
def attach(self, vobj): # items for edit dialog and contextmenue self.emenu = [ ['A', self.funA], ['Diagram', self.diagram], ] self.cmenu = self.emenu say("VO attach " + str(vobj.Object.Label)) vobj.Proxy = self self.Object = vobj.Object self.obj2 = self.Object self.Object.Proxy.Lock = False self.Object.Proxy.Changed = False icon = '/icons/animation.png' self.iconpath = __dir__ + icon self.vers = __vers__ return
def test_basic(param='Yo'): say = Fmt() greeting = "hello" assert say("{greeting}, world!") == "{0}, world!".format(greeting) assert say("'{greeting}' has {len(greeting)} characters") == "'{0}' has {1} characters".format(greeting, len(greeting)) assert say("{param}") == "{0}".format(param) assert say("{greeting:<10}") == "{0:<10}".format(greeting) assert say("{greeting:>20}") == "{0:>20}".format(greeting) assert say("{globalvar:3}") == " 99" assert say("{globalvar:4}") == " 99" assert say("{globalvar:<4}") == "99 "
def onChanged(self,obj,prop): if prop=='mode': say("onChanged mode" + str(self)) say(obj.mode) # hier formel tauschen if obj.mode== 'ping pong': obj.trafo="a*time/b if time <b else 2*a - a*time/b" elif obj.mode == 'forward': obj.trafo="a*time" elif obj.mode == 'backward': obj.trafo="a-a*time" elif obj.mode == "fade": obj.trafo="0 if time<b else a*(time-b)/(c-b) if time <c else a" elif obj.mode == 'sine wave': obj.trafo="a*math.sin(math.pi*b*time+c)" elif obj.mode == 'quadratic': obj.trafo="a*time**2+ b*time + c" elif obj.mode == 'expression': obj.trafo=obj.expressiontrafo else: FreeCAD.Console.PrintWarning("unknown mode for speeder " + str(obj.Label) +" :" + obj.mode) pass
def puppet_run(is_noop=True, tags='', extra_args=''): """Run puppet agent on remote host""" noop_arg = "--noop" if is_noop else "--no-noop" tags_arg = ("--tags %s" % tags) if tags else "" puppet_command = "sudo /usr/bin/puppet agent --test %s %s %s" % (noop_arg, tags_arg, extra_args) with settings( warn_only=True ): if exists ( '/var/lib/puppet/state/agent_catalog_run.lock' ): say ( 'Puppet is currently running on background - sleeping 10 secs' ) local ( 'sleep 10' ) result = run ( puppet_command ) if result.return_code == 0: say ( 'Puppet run - No changes performed' ) elif result.return_code == 1: say ( 'Puppet run - Error returned, but continuing this time...' ) elif result.return_code == 2: if is_noop: say ( 'Puppet run - PLEASE CHECK THIS, SHOULD NOT HAVE RETURNED 2!!!' ) else: say ( 'Puppet run - System has been updated' ) else: sys.exit( 'Puppet command returned unexpected error %s' % ( result.return_code ) )
def close2(self): sayErr("close2") self.hide() say("2") say(self.obj) FreeCAD.tt=self.obj self.obj.Object.ViewObject.Visibility=False say("done")
def close2(self): sayErr("close2") self.hide() say("2") say(self.obj) FreeCAD.tt = self.obj self.obj.Object.ViewObject.Visibility = False say("done")
def onChanged(self, obj, prop): if prop == 'mode': say("onChanged mode" + str(self)) say(obj.mode) # hier formel tauschen if obj.mode == 'ping pong': obj.trafo = "a*time/b if time <b else 2*a - a*time/b" elif obj.mode == 'forward': obj.trafo = "a*time" elif obj.mode == 'backward': obj.trafo = "a-a*time" elif obj.mode == "fade": obj.trafo = "0 if time<b else a*(time-b)/(c-b) if time <c else a" elif obj.mode == 'sine wave': obj.trafo = "a*math.sin(math.pi*b*time+c)" elif obj.mode == 'quadratic': obj.trafo = "a*time**2+ b*time + c" elif obj.mode == 'expression': obj.trafo = obj.expressiontrafo else: FreeCAD.Console.PrintWarning("unknown mode for speeder " + str(obj.Label) + " :" + obj.mode) pass
def test_files_unicode(capsys, tmpdir): say = Say() tmpfile = tmpdir.join('test.txt') say.setfiles([sys.stdout, tmpfile]) text = "Yowza!" say(text) assert tmpfile.read() == text + "\n" assert capsys.readouterr()[0] == text + "\n" text2 = six.u('Hello\u2012there') tmpfile2 = tmpdir.join('test2.txt') tfname = tmpfile2.strpath say.set(files=[sys.stdout, tfname]) say(text2) # BREAKS HERE - Could be a failure of Unicode handling mechanisms, or # just a faulty test. Believe to be a faulty test. Have seen some # similar issues before under the py.test harness. Functionality # manually tested produces no errors and correct results. Mark test as # skipped until identify more robust automated testing procedure. tf = say.options.files[1] tf.close() with io.open(tfname, 'r') as tf2: assert tf2.read() == text2 + "\n" assert capsys.readouterr()[0] == text2 + "\n" errfile = tmpdir.join('error.txt') errcode = 12 err = say.clone(files=[sys.stderr, errfile]) err("Failed with error {errcode}") # writes to stderr, error.txt assert capsys.readouterr()[1] == 'Failed with error 12\n' assert errfile.read() == 'Failed with error 12\n'
def test_Relative_indent(): say = Fmt() assert say('one indent', indent=Relative(1)) == ' one indent' say.set(indent=Relative(1)) assert say('auto one indent') == ' auto one indent' assert say('one plus one indent', indent=Relative(1)) == ' one plus one indent' assert say('subtract indent', indent=Relative(-1)) == 'subtract indent' assert say('more again', indent=Relative(+1)) == ' more again' say.set(indent=0) assert say('more again', indent=Relative(+1)) == ' more again'
def update(self): time = self.obj2.time try: say("update time=" + str(time) + ", " + self.obj2.Label) except: say("update (ohne Label)") time = self.obj2.time a = self.obj2.a b = self.obj2.b c = self.obj2.c d = self.obj2.d source = self.obj2.source source2 = self.obj2.source2 source3 = self.obj2.source3 source4 = self.obj2.source4 out = eval(self.obj2.trafo) out2 = eval(self.obj2.trafo2) out3 = eval(self.obj2.trafo3) out4 = eval(self.obj2.trafo4) say([time, out, out2, out3, out4]) self.obj2.out = out self.obj2.out2 = out2 self.obj2.out3 = out3 self.obj2.out4 = out4 tl = [ self.obj2.target, self.obj2.target2, self.obj2.target3, self.obj2.target4 ] outl = [out, out2, out3, out4] for t in range(4): try: tl[t].Proxy.step(outl[t]) tl[t].Proxy.update() say("combiner update " + str(tl[t].Label) + " wert: " + str(outl[t])) except: pass
def update(self): time=self.obj2.time try: say("update time=" + str(time) + ", "+ self.obj2.Label) except: say("update (ohne Label)") time=self.obj2.time a=self.obj2.a b=self.obj2.b c=self.obj2.c d=self.obj2.d source=self.obj2.source source2=self.obj2.source2 source3=self.obj2.source3 source4=self.obj2.source4 out=eval(self.obj2.trafo) out2=eval(self.obj2.trafo2) out3=eval(self.obj2.trafo3) out4=eval(self.obj2.trafo4) say([time,out,out2,out3,out4]) self.obj2.out=out self.obj2.out2=out2 self.obj2.out3=out3 self.obj2.out4=out4 tl=[self.obj2.target,self.obj2.target2,self.obj2.target3,self.obj2.target4] outl=[out,out2,out3,out4] for t in range(4): try: tl[t].Proxy.step(outl[t]) tl[t].Proxy.update() say("combiner update " + str(tl[t].Label) + " wert: " + str(outl[t])) except: pass
def t2ntderive(self,time): a=self.obj2.a b=self.obj2.b c=self.obj2.c d=self.obj2.d m=self.obj2.m g=self.obj2.g newtime1=eval(self.obj2.trafo) time += 0.01 newtime2=eval(self.obj2.trafo) newtime=(newtime2-newtime1)*m say(str(time) +" " +self.obj2.trafo +" derive " + str(newtime)) say(str(newtime1)) say(str(newtime2)) return newtime
def t2ntderive(self, time): a = self.obj2.a b = self.obj2.b c = self.obj2.c d = self.obj2.d m = self.obj2.m g = self.obj2.g newtime1 = eval(self.obj2.trafo) time += 0.01 newtime2 = eval(self.obj2.trafo) newtime = (newtime2 - newtime1) * m say(str(time) + " " + self.obj2.trafo + " derive " + str(newtime)) say(str(newtime1)) say(str(newtime2)) return newtime
def execute(self,obj): if obj.mode=='histogram': # self.edit() say("plot ------------------") try: app=obj.Proxy.app app.plot() except: sayW("Error for call obj.Proxy.app.plot()") say("plot ----------------done --") return if not obj.record: say(obj.Label+ " no recording") return try: t=self.vals except: self.vals={} src=obj.sourceObject vs='src.'+obj.sourceData v=eval(vs) self.vals[v]=v for i in range(obj.countSources): exec("src"+str(i+1)+"=obj.source"+str(i+1)+"Object") exec("ss=obj.source"+str(i+1)+"Object") if ss != None: vs2="obj.source"+str(i+1)+"Data" v2=eval(vs2) vs3="ss."+v2 v3=eval(vs3) tt=eval("self.vals"+str(i+1)) tt[v]=v3 return
def command(): while True: print(" ") audio = get_audio() # f1 = open("pliki/101.txt", "a+") if audio != None: ################################################################################ if len(czy(audio, ADMIN_COMMADN)): if len(czy(audio, PA_ADMIN)): say("pa") quit() exit() if len(czy(audio, RESTART_ADMIN)): os.system("cls") os.system("python Manfred.py") ################ if len(czy(audio, setupup)): say("ok") setupadd() if len(czy(audio, wyszukaj)): if len(czy(audio, z)): if len(czy(audio, pamieci)): say("ok") ################################################################################ if len(czy(audio, KLUCZ_COMMAND)): ################ if len(czy(audio, zart)): lossay(zartycommand) play(hahababy) ################ if len(czy(audio, jaka)): ################ if len(czy(audio, jest)): ################ if len(czy(audio, temperatura)): ################ if len(czy(audio, w)): ################ if len(czy(audio, BIAŁYSTOK)): temp("Białystok") ################ if len(czy(audio, WARSZAWA)): temp("Warszawa") ################ if len(czy(audio, bielskbiałej)): pogo("Bielsko Biała") ################ if len(czy(audio, BIELSK)): ################ if len(czy(audio, BIAŁE)): temp("Bielsko Biała") ################ if len(czy(audio, Chojnice)): temp("Chojnice") ################ if len(czy(audio, czestochowa)): temp("Częstochowa") ################ if len(czy(audio, wyszukaj)): g = audio.lower().split(' ' + czy(audio, wyszukaj)[0] + ' ')[1] say("Oto co mi się udało znaleść.") googleurl = "https://www.google.com/search?q=" + g.replace( " ", "+").replace("?", "%3F") webbrowser.open(googleurl) command() ################ if len(czy(audio, odpal)): ################ if len(czy(audio, spotif)): say("ok") webbrowser.open("https://open.spotify.com/") ################ if len(czy(audio, netflix)): say("ok") webbrowser.open("https://www.netflix.com/") ################ if len(czy(audio, instagram)): say("ok") webbrowser.open("https://www.instagram.com/") ################ if len(czy(audio, facebook)): say("ok") webbrowser.open("https://www.facebook.com/") ################ if len(czy(audio, gmail)): say("ok") webbrowser.open("https://mail.google.com/") ################ if len(czy(audio, PROSZE)): ################ if len(czy(audio, yt)): ytw = audio.lower().split(' ' + czy(audio, yt)[0] + ' ')[1] youtubeopen(ytw)
def showHelpBoxY(self): # self.run_sternwarte() say("showHelpBox called")
from gtts import gTTS from say import * from playsound import playsound import os """ x, nums, name = 12, list(range(4)), 'Fred' say("There are {x} things.") say("Nums has {len(nums)} items: {nums}") say("Name: {name!r}") """ myText = "Hello there, my name is Lettie, and I'm learning how to code" language = 'en' out = gTTS(text=myText, lang=language, slow=False) out.save("test.mp3") playsound("test.mp3") os.remove("test.mp3")
def update(self): time = self.obj2.time try: say("update time=" + str(time) + ", " + self.obj2.Label) except: say("update (ohne Label)") time = self.obj2.time a = self.obj2.a b = self.obj2.b c = self.obj2.c d = self.obj2.d source = self.obj2.source source2 = self.obj2.source2 source3 = self.obj2.source3 source4 = self.obj2.source4 if self.obj2.timeExpression != "": say(["eval time Expression", time]) time = eval(self.obj2.timeExpression) say(["time== ", time, self.obj2.timeExpression]) out = 0 out1 = 0 out2 = 0 out3 = 0 out4 = 0 out5 = 0 out6 = 0 out7 = 0 out8 = 0 out9 = 0 if self.obj2.trafo: out = eval(self.obj2.trafo) if self.obj2.trafo2: out2 = eval(self.obj2.trafo2) if self.obj2.trafo3: out3 = eval(self.obj2.trafo3) if self.obj2.trafo4: out4 = eval(self.obj2.trafo4) if self.obj2.trafo5: out5 = eval(self.obj2.trafo5) if self.obj2.trafo6: out6 = eval(self.obj2.trafo6) if self.obj2.trafo7: out7 = eval(self.obj2.trafo7) if self.obj2.trafo8: out8 = eval(self.obj2.trafo8) if self.obj2.trafo9: out9 = eval(self.obj2.trafo9) # say([time,out,out2,out3,out4]) self.obj2.out = out self.obj2.out2 = out2 self.obj2.out3 = out3 self.obj2.out4 = out4 self.obj2.out5 = out5 self.obj2.out6 = out6 self.obj2.out7 = out7 self.obj2.out8 = out8 self.obj2.out9 = out9 if self.obj2.trafo: self.register(time, self.data, out, self.obj2.graph) if self.obj2.trafo2: self.register(time, self.data2, out2, self.obj2.graph2) if self.obj2.trafo3: self.register(time, self.data3, out3, self.obj2.graph3) if self.obj2.trafo4: self.register(time, self.data4, out4, self.obj2.graph4) if self.obj2.trafo5: self.register(time, self.data5, out5, self.obj2.graph5) if self.obj2.trafo6: self.register(time, self.data6, out6, self.obj2.graph6) if self.obj2.trafo7: self.register(time, self.data7, out7, self.obj2.graph7) if self.obj2.trafo8: self.register(time, self.data8, out8, self.obj2.graph8) if self.obj2.trafo9: self.register(time, self.data9, out9, self.obj2.graph9)
import time import sys import random from say import * from logo import logo from time import sleep from pogoda import * from czy import * import webbrowser ################################################################################ Paseczek() cls() logo() say("Witaj, Jestem Manfred") ################################################################################ yt = ["youtube", "youtubie", "film"] ADMIN_COMMADN = ["admin"] PA_ADMIN = ["pa", "pa pa", "papa"] RESTART_ADMIN = ["restart"] KLUCZ_COMMAND = ["ok", "manfred", "bot", "okej", "żulu", "manfredi"] PROSZE = ["prosze", "proszę"] odpal = ["odpal"] google = ["google"] jaka = ["jaka"] jest = ["jest"] setupup = ["setup", "set up"] temperatura = ["temperatura"]
def funA(self): say("ich bin FunA touch target") FreeCAD.ActiveDocument.recompute() self.obj2.target.touch() FreeCAD.ActiveDocument.recompute() say("ich war FunA")
def import_osm2(b,l,bk,progressbar,status,elevation): dialog=False debug=False if progressbar: progressbar.setValue(0) if status: status.setText("get data from openstreetmap.org ...") FreeCADGui.updateGui() content='' bk=0.5*bk dn=FreeCAD.ConfigGet("UserAppData") + "/geodat/" fn=dn+str(b)+'-'+str(l)+'-'+str(bk) import os if not os.path.isdir(dn): print "create " + dn os.makedirs(dn) try: print "I try to read data from cache file ..." print fn f=open(fn,"r") content=f.read() print "successful read" # print content except: print "no cache file, so I connect to openstreetmap.org..." lk=bk # b1=b-bk/1113*10 l1=l-lk/713*10 b2=b+bk/1113*10 l2=l+lk/713*10 source='http://api.openstreetmap.org/api/0.6/map?bbox='+str(l1)+','+str(b1)+','+str(l2)+','+str(b2) print source try: response = urllib2.urlopen(source) first=True content='' f=open(fn,"w") l=0 z=0 ct=0 for line in response: if status: if z>5000: status.setText("read data ..." + str(l)) z=0 FreeCADGui.updateGui() l+=1 z+=1 if first: first=False else: content += line f.write(line) f.close() if status: status.setText("FILE CLOSED ..." + str(l)) FreeCADGui.updateGui() response.close() except: print "Fehler beim Lesen" if status: status.setText("got data from openstreetmap.org ...") FreeCADGui.updateGui() print "Beeenden - im zweiten versuch daten auswerten" return False if elevation: baseheight=getHeight(b,l) else: baseheight=0 if debug: print "-------Data---------" print content print "--------------------" if status: status.setText("parse data ...") FreeCADGui.updateGui() try: sd=parse(content) except: sayexc("Problem parsing data - abort") status.setText("Problem parsing data - aborted, for details see Report view") return if debug: print(json.dumps(sd, indent=4)) if status: status.setText("transform data ...") FreeCADGui.updateGui() bounds=sd['osm']['bounds'] nodes=sd['osm']['node'] ways=sd['osm']['way'] try: relations=sd['osm']['relation'] except: relations=[] # center of the scene bounds=sd['osm']['bounds'] minlat=float(bounds['@minlat']) minlon=float(bounds['@minlon']) maxlat=float(bounds['@maxlat']) maxlon=float(bounds['@maxlon']) tm=TransverseMercator() tm.lat=0.5*(minlat+maxlat) tm.lon=0.5*(minlon+maxlon) center=tm.fromGeographic(tm.lat,tm.lon) corner=tm.fromGeographic(minlat,minlon) size=[center[0]-corner[0],center[1]-corner[1]] # map all points to xy-plane points={} nodesbyid={} for n in nodes: nodesbyid[n['@id']]=n ll=tm.fromGeographic(float(n['@lat']),float(n['@lon'])) points[str(n['@id'])]=FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],0.0) # hack to catch deutsche umlaute def beaustring(string): res='' for tk in zz: try: res += str(tk) except: if ord(tk)==223: res += 'ß' elif ord(tk)==246: res += 'ö' elif ord(tk)==196: res += 'Ä' elif ord(tk)==228: res += 'ä' elif ord(tk)==242: res += 'ü' else: print ["error sign",tk,ord(tk),string] res +="#" return res if status: status.setText("create visualizations ...") FreeCADGui.updateGui() App.newDocument("OSM Map") say("Datei erzeugt") area=App.ActiveDocument.addObject("Part::Plane","area") obj = FreeCAD.ActiveDocument.ActiveObject say("grundflaeche erzeugt") try: viewprovider = obj.ViewObject root=viewprovider.RootNode myLight = coin.SoDirectionalLight() myLight.color.setValue(coin.SbColor(0,1,0)) root.insertChild(myLight, 0) say("beleuchtung auf grundobjekt eingeschaltet") except: sayexc("Beleuchtung 272") cam='''#Inventor V2.1 ascii OrthographicCamera { viewportMapping ADJUST_CAMERA orientation 0 0 -1.0001 0.001 nearDistance 0 farDistance 10000000000 aspectRatio 100 focalDistance 1 ''' x=0 y=0 height=1000000 height=200*bk*10000/0.6 cam += '\nposition ' +str(x) + ' ' + str(y) + ' 999\n ' cam += '\nheight ' + str(height) + '\n}\n\n' FreeCADGui.activeDocument().activeView().setCamera(cam) FreeCADGui.activeDocument().activeView().viewAxonometric() say("Kamera gesetzt") area.Length=size[0]*2 area.Width=size[1]*2 area.Placement=FreeCAD.Placement(FreeCAD.Vector(-size[0],-size[1],0.00),FreeCAD.Rotation(0.00,0.00,0.00,1.00)) say("Area skaliert") wn=-1 coways=len(ways) starttime=time.time() refresh=1000 for w in ways: # print w wid=w['@id'] # print wid building=False landuse=False highway=False wn += 1 # nur teile testen #if wn <2000: continue nowtime=time.time() if wn<>0 and (nowtime-starttime)/wn > 0.5: print "way ---- # " + str(wn) + "/" + str(coways) + " time per house: " + str(round((nowtime-starttime)/wn,2)) if progressbar: progressbar.setValue(int(0+100.0*wn/coways)) if debug: print "w=", w if debug: print "tags ..." st="" nr="" h=0 try: w['tag'] except: print "no tags found." continue for t in w['tag']: if t.__class__.__name__ == 'OrderedDict': try: if debug: print t if str(t['@k'])=='building': building=True st='building' if str(t['@k'])=='landuse': landuse=True st=w['tag']['@k'] nr=w['tag']['@v'] if str(t['@k'])=='highway': highway=True st=t['@k'] if str(t['@k'])=='name': zz=t['@v'] nr=beaustring(zz) if str(t['@k'])=='ref': zz=t['@v'] nr=beaustring(zz)+" /" if str(t['@k'])=='addr:street': zz=w['tag'][1]['@v'] st=beaustring(zz) if str(t['@k'])=='addr:housenumber': nr=str(t['@v']) if str(t['@k'])=='building:levels': if h==0: h=int(str(t['@v']))*1000*3 if str(t['@k'])=='building:height': h=int(str(t['@v']))*1000 except: print "unexpected error ################################################################" else: if debug: print [w['tag']['@k'],w['tag']['@v']] if str(w['tag']['@k'])=='building': building=True st='building' if str(w['tag']['@k'])=='building:levels': if h==0: h=int(str(w['tag']['@v']))*1000*3 if str(w['tag']['@k'])=='building:height': h=int(str(w['tag']['@v']))*1000 if str(w['tag']['@k'])=='landuse': landuse=True st=w['tag']['@k'] nr=w['tag']['@v'] if str(w['tag']['@k'])=='highway': highway=True st=w['tag']['@k'] nr=w['tag']['@v'] name=str(st) + " " + str(nr) if name==' ': name='landuse xyz' if debug: print "name ",name #generate pointlist of the way polis=[] height=None llpoints=[] for n in w['nd']: m=nodesbyid[n['@ref']] llpoints.append([n['@ref'],m['@lat'],m['@lon']]) if elevation: print "get heights for " + str(len(llpoints)) heights=getHeights(llpoints) for n in w['nd']: p=points[str(n['@ref'])] if building and elevation: if not height: try: height=heights[m['@lat']+' '+m['@lon']]*1000 - baseheight except: print "---no height avaiable for " + m['@lat']+' '+m['@lon'] height=0 p.z=height polis.append(p) #create 2D map pp=Part.makePolygon(polis) Part.show(pp) z=App.ActiveDocument.ActiveObject z.Label="w_"+wid if name==' ': g=App.ActiveDocument.addObject("Part::Extrusion",name) g.Base = z g.ViewObject.ShapeColor = (1.00,1.00,0.00) g.Dir = (0,0,10) g.Solid=True g.Label='way ex ' if building: g=App.ActiveDocument.addObject("Part::Extrusion",name) g.Base = z g.ViewObject.ShapeColor = (1.00,1.00,1.00) if h==0: h=10000 g.Dir = (0,0,h) g.Solid=True g.Label=name obj = FreeCAD.ActiveDocument.ActiveObject inventortools.setcolors2(obj) if landuse: g=App.ActiveDocument.addObject("Part::Extrusion",name) g.Base = z if nr == 'residential': g.ViewObject.ShapeColor = (1.00,.60,.60) elif nr == 'meadow': g.ViewObject.ShapeColor = (0.00,1.00,0.00) elif nr == 'farmland': g.ViewObject.ShapeColor = (.80,.80,.00) elif nr == 'forest': g.ViewObject.ShapeColor = (1.0,.40,.40) g.Dir = (0,0,0.1) g.Label=name g.Solid=True if highway: g=App.ActiveDocument.addObject("Part::Extrusion","highway") g.Base = z g.ViewObject.LineColor = (0.00,.00,1.00) g.ViewObject.LineWidth = 10 g.Dir = (0,0,0.2) g.Label=name refresh += 1 if os.path.exists("/tmp/stop"): print("notbremse gezogen") FreeCAD.w=w raise Exception("Notbremse Manager main loop") if refresh >3: FreeCADGui.updateGui() # FreeCADGui.SendMsgToActiveView("ViewFit") refresh=0 FreeCAD.activeDocument().recompute() FreeCADGui.updateGui() FreeCAD.activeDocument().recompute() if status: status.setText("import finished.") if progressbar: progressbar.setValue(100) organize() endtime=time.time() print "running time ", int(endtime-starttime), " count ways ", coways return True
def plot(self): if self.obj.mode=='histogram': self.mpl.figure.clf() self.mpl.canvas = FigureCanvas(self.mpl.figure) FigureCanvas.updateGeometry(self.mpl) self.mpl.axes = self.mpl.figure.add_subplot(111) self.mpl.draw() FreeCAD.mpl=self.mpl k=self.plot_histogram() # FreeCAD.k=k # self.mpl.axes.set_xlabel('length') # self.mpl.axes.set_ylabel('count') # self.mpl.axes.title=self.obj.Label return self.mpl.figure.clf() self.mpl.canvas = FigureCanvas(self.mpl.figure) FigureCanvas.updateGeometry(self.mpl) self.mpl.axes = self.mpl.figure.add_subplot(111) self.mpl.draw() vals=self.obj.Proxy.vals x=[] y=[] for k in vals: x.append(k) y.append(vals[k]) self.obj.sourceValues=y for i in range(self.obj.countSources): nr=str(i+1) ss=eval("self.obj.source"+nr+"Object") sf=eval("self.obj.source"+nr+"Off") if ss!=None and not sf: exec("vals=self.obj.Proxy.vals"+nr) x2=[k for k in vals] y1=[vals[k] for k in vals] exec("label=self.obj.source"+nr+"Object.Label + ': ' + self.obj.source"+nr+"Data") t=self.mpl.axes.plot(x,y1,label=label) exec("self.obj.source"+nr+"Values=y1") if ss== None and not sf and not self.obj.useNumpy: say("no sourcve .jijij") exec("vals=self.obj.source"+nr+"Values") # x2=[k for k in vals] # y1=[vals[k] for k in vals] # say(vals) y1=vals x=range(len(vals)) exec("label=self.obj.source"+nr+"Data") # label="Label for " + str(nr) + ": "+ label t=self.mpl.axes.plot(x,y1,label=label) # exec("self.obj.source"+nr+"Values=y1") say("DDone") if self.obj.useNumpy: self.obj.outTime=self.obj.sourceNumpy.outTime FreeCAD.activeDocument().recompute() for i in range(10): if eval("self.obj.useOut"+str(i)): try: y=self.obj.sourceNumpy.getPropertyByName('out'+str(i)) label=self.obj.sourceNumpy.getPropertyByName('label'+str(i)) if label=='': label="numpy " + str(i) # if x == []: x=range(len(y)) if self.obj.outTime!=[]: x=self.obj.outTime say(("lens",len(x),len(y))) t=self.mpl.axes.plot(x,y,label=label) exec("self.obj.out"+str(i)+"="+str(y)) except: sayexc("cannont calculate out"+str(i)) legend = self.mpl.axes.legend(loc='upper right', shadow=True) self.mpl.draw() self.mpl.figure.canvas.draw()