Error Using Datanitro/VBA to Turn Off Screen Updating - datanitro

I am using Datanitro to build a program that gathers data from a number of workbooks and dumps it into a master workbook.
The program is working fine, although it runs slower than I would prefer and every time I run close_wkbk() excel asks me if I want to save the workbook (I do not).
To solve this using VBA, I would bracket the program with the following snippets of code:
With Application
.DisplayAlerts = False
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
It did not seem as though Datanitro supported this functionality, so I created the following two VBA subroutines in a module within the workbook from which I was running the script:
Sub RemoveAlerts()
With Application
.DisplayAlerts = False
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
End Sub
Sub DisplayAlerts()
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
End Sub
I then bracketed my python script with the following code:
VBA("RemoveAlerts")
VBA("DisplayAlerts")
RemoveAlerts appears to execute correctly, but DisplayAlerts threw the following error message
, line 48, in grab_all_intrinsic_values
VBA("DisplayAlerts")
File "27/basic_io.py", line 1850, in VBA
File "27/iron.py", line 305, in runExcelMacro
File "27/dnparser.py", line 95, in checkForErrors
dntypes.NitroException: The object invoked has disconnected from its clients.
(Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED))
Any idea what is causing this error?
BELOW EDIT INCLUDED WHEN ANSWER WAS FOUND:
Turns out that the problem was my active_workbook had changed to a workbook that did not contain the DisplayAlerts subroutine. I made sure to set my active_workbook back to the one that did contain the subroutine and it worked correctly.

Related

RuntimeError: run loop already started in pyttsx

I am creating a DIY virtual assistant for fun and exercise in python. I run into a problem when trying to use engine.say in a thread and then use it again in my main program.
I already tried to use engine.endLoop() and other possible solutions from pyttsx docs (engine.stop(), engine.endLoop() etc) but still i didn't make it work. I have seen in some answers about asyncio. But with pip i can't install it and i am not very certain that it will solve my problem.
The Functions:
def portport():
ser = serial.Serial('COM4',9600)
raw_data = ser.read(9)
msg = str(raw_data[3:8])
print msg
ser.close()
return msg
def Comm_Connection():
print("CommConns started")
while True:
global conn
try:
conn, addr = SERVER.accept()
Live_Conns.append(conn)
Server_Send = "Connection established successfully"
Server_Send = pickle.dumps(Server_Send)
Live_Conns[-1].send(Server_Send)
temp = conn.recv(1024)
Server_Receive = pickle.loads(temp)
Live_Name.append(Server_Receive)
Connections = (Live_Name[-1], "Connected")
engine.say(Connections)
engine.runAndWait()
except socket.error as socketerror:
continue
except socket.timeout:
continue
The "Main" program:
Server_Up = threading.Thread(target = Comm_Connection)
Server_Up.start()
while True:
engine = pyttsx.init()
time.sleep(7)
engine.say("Goodmorning")
engine.runAndWait()
And the error i get:
raise RuntimeError('run loop already started')
RuntimeError: run loop already started
It looks like your while True loop is trying to start and run the pyttsx engine at the same time it's being operated inside the Comm_Connection loop.
Note that pyttsx uses its own internal engine that supports callbacks and manual iteration, so you might consider rewriting your app more along the lines of the following example modified from the docs:
engine = pyttsx3.init()
engine.say('The quick brown fox jumped over the lazy dog.', 'fox')
engine.startLoop(False)
# engine.iterate() must be called inside Server_Up.start()
Server_Up = threading.Thread(target = Comm_Connection)
Server_Up.start()
engine.endLoop()
Disclaimer: I've played around enough with this library to know that the manual iteration approach does work, but not enough to understand your particular needs, so YMMV.
As this is a common question and I figured out a solution for this for my program. To use a private variable to judge if the loop is already started and then end it if it is using engine._inLoop -
while True:
engine = pyttsx.init()
time.sleep(7)
engine.say("Goodmorning")
engine.runAndWait()
if engine._inLoop:
engine.endLoop()
first of all install pyttsx3 with pip uninstall pyttsx pip install pyttsx3 and then try this
while True:
engine = pyttsx3.init()
time.sleep(7)
engine.say("Goodmorning")
engine.runAndWait()
engine = None
you are defining engine = pyttsx.init()in the loop every time
so it will say that the loop is already started
but if you define engine = None for every iteration it will work at least it did for me

RSpec Mark Failed Tests as Skipped

We have a unit test suite, written in RSpec. We have some failed tests that is a lot actually.
What I am looking for is a script or a magic command, to mark all the failed tests as skipped, so I don't have to go over them one by one and mark them as skipped.
I found this awesome script that do exactly what I need:
https://gist.github.com/mcoms/77954d191bde31d4677872d2ab3d0cd5
Copying the contents here, in case the original gist is deleted:
# frozen_string_literal: true
class CustomFormatter
RSpec::Core::Formatters.register self, :example_failed
def initialize(output)
#output = output
end
def example_failed(notification)
tf = Tempfile.new
File.open(notification.example.metadata[:file_path]) do |f|
counter = 1
while (line = f.gets)
if counter == notification.example.metadata[:line_number]
line.sub!('it', 'skip')
line.sub!('scenario', 'skip')
#output << line
end
tf.write line
counter += 1
end
end
tf.close
FileUtils.mv tf.path, notification.example.metadata[:file_path]
end
end
Should be relatively straightforward. RSpec lists failing specs like this
rspec ./spec/models/user.rb:67 # User does this thing
rspec ./spec/models/post.rb:13 # Post does another thing
rspec ./spec/models/rating.rb:123 # Rating does something else entirely
File name and line number point to the opening line of the test, the one with it ... do.
Write a script that
extracts file names and line numbers from the failure output
opens those files, goes to the specified line
and replaces it with xit.

Recursive function not outputting intended value

I' m happy trouble understanding why the function below seems to be outputting None instead of 1 if the function doesn't have a vakud output on its first run through.
import win32com.client
BING_KEY = "XXXXXXXX"
import speech_recognition as sr
import win32com.client as wincl
s = sr.Recognizer()
def hey_pc():
print(" Hey PC = Command")
with sr.Microphone() as source:
audio = s.listen(source)
try:
x= (s.recognize_bing(audio, key=BING_KEY))
if x in ['hey PC']:
return 1
else: hey_pc()
except:
print('Try again')
hey_pc()
t = hey_pc()
print t
if the function outputs on its first run, I get the following output:
Hey PC == Command
1
But if it invokes its recursive property, I get a final output of None
Hey PC == Command
Hey PC == Command
Hey PC == Command
Hey PC == Command
None
or this
Hey PC == Command
Try again
Hey PC == Command
Hey PC == Command
None
I don't understand why I"m getting "None."
EDIT:
I've changed the second part of the code to this and played around more but still have the same problem:
t =hey_pc()
if t == 1:
speak = wincl.Dispatch("SAPI.SpVoice")
speak.Speak("This is the pc voice speaking")
import automation
automation.Apply_Command()
else:
hey_pc()
If my voice is recognized on its first attempt, the code under if t==1 is ran and there no problems, however if my voice is not recognized on its first attempt and recurvise portion of the code is activated, once my voice finally gets recognized, the program just ends (meaning the Python command prompt >>> pops up again). So I'm assuming it's the null value that's being passed on.
Still stumped. :(
Probably not the answer you're looking for, specifically, but it's generally because "if x in ['hey PC']" is NEVER true. The only condition where a number is returned (and thus setting a value) is your if statement. So, most likely, that if statement is never entered into.

kivy .bind results in AssertionError: '' is not callable

I am writing a GUI in Linux using Kivy and Python. The program should detect a USB device and using the device to program an image to a target. Here are a snippet of my code:
These are the codes I am trying to detect USB device. This is on a file, let's call it A.py.
busses = usb.busses()
for bus in busses:
devices = bus.devices
for dev in devices:
if (dev.idVendor == vendor and dev.idProduct == product):
obj = ProgJTAG.ProgJTAG(bus.dirname,dev.filename, dev.idVendor, dev.idProduct, dev)
break
When I ran the program, assertion error occured in creating an instance of ProgJTAG. This is defined in a separate file ProgJTAG.py as follows:
class ProgJTAG(BoxLayout):
usb_bus = StringProperty('')
usb_dev = StringProperty('')
usb_vendor = StringProperty('')
usb_product = StringProperty('')
def __init__(self, _usb_bus, _usb_dev, _usb_vendor, _usb_product, dev):
super(ProgJTAG, self).__init__()
self.usb_bus = _usb_bus
self.usb_dev = _usb_dev
self.usb_vendor = str(_usb_vendor)
self.usb_product = str(_usb_product)
self.bind(usb_bus=self.usb_bus)
self.bind(usb_dev=self.usb_bus)
self.bind(usb_vendor=self.usb_bus)
self.bind(usb_product=self.usb_bus)
The error occur from the line self.bind(usb_bus=self.usb_bus). The error message is File "_event.pyx", kivy._event.EventDispatcher.bind(kivy/_event.c:5536)
AssertionError: '' is not callable
Q1. Can anyone help what the assertion means?
Q2. I noticed that the _usb_bus and _usb_dev are empty string. Is this assertion caused by the fact that the _usb_bus and _usb_dev are empty string property hence not callable?
Yes, when you bind you must pass a function because the binding will try to call it later.

Reading and printing progress bar that is being updated on same line while it is still updating

So I'm using subprocess.Popen in order to load new OS onto multiple devices.
my script:
done = None
command = 'my loading command'
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
while proc.poll() is None:
line = proc.stdout.readline()
print line.strip()
if "Done" in line:
done = True
So the loading process should start off by detecting the device plugged into the system and then the loader/progress bar starts:
Connecting to Device:
Connected
[ Writing ] [ 0 ]
[ Writing ] [ 1 ]
[ Writing ] [ 2 ]
.
.
.
.
[ Writing ] [############## 100 ##############]
Done.
Now to be sure that the loading is completely done I use Popen with stdout=PIPE in order to check when the "Done." string is printed to stdout and then I print stdout onto the cmd window. Now my issue is that since proc.stdout.readline() is reading every line at a time, it prints the 1st 2 lines about detecting and connecting to device and then nothing for 10 min then it prints this line:
[ Writing ] [############## 100 ##############]
So my output on the cmd window looks like this:
Connecting to Device:
Connected
[ Writing ] [############## 100 ##############]
Done.
So it doesn't start from [Wrtiting 0] and then [Writing 1].... till it gets to [100]. this is because the loader is being updated on the same line so proc.stdout.readline() waits till the loading line is complete and then prints it out which pretty much defies the purpose of having the progress bar to show the progress made every coupe of seconds.
Can anyone help me solve this? I tried printing to both a file and the cmd window at same time to check for the "Done." string but no luck as it only prints '0' to the txt file.
alright So i found the answer t solve this problem:
In order to be able to check for the done string and print the progress bar as it progresses to 100% i use the same code except I have to specify the number of characters in readline(). So I did the loading and made it print it to a file and then copied the last line where the progress bar was full, entered it into a print len(str), got the length of the string and then added it as argument to the readline() command:
done = None
command = 'my loading command'
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
while proc.poll() is None:
line = proc.stdout.readline(77)
print line.strip()
if "Done" in line:
done = True
The issue is that a progress bar line ends with '\r' and not '\n'. If you change the code to the following it should work:
done = None
command = 'my loading command'
proc = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True)
while proc.poll() is None:
line = proc.stdout.readline()
print line.strip()
if "Done" in line:
done = True