I'm trying to run the following script in VS Code, however I keep getting an indentation error, which is kinda self-explanatory, but I haven't been able to find the error? Is there a way auto-formatting in VS Code?
import logging
import uuid
import json
import azure.functions as func
def main(msg: func.QueueMessage, message: func.Out[func.Document]) -> None:
logging.info('Python queue trigger function processed a queue item: %s', msg_body)
data = json.dumps({
'id': msg.id,
'body': msg.get_body().decode('utf-8'),
'expiration_time': (msg.expiration_time.isoformat()
if msg.expiration_time else None),
'insertion_time': (msg.insertion_time.isoformat()
if msg.insertion_time else None),
'time_next_visible': (msg.time_next_visible.isoformat()
if msg.time_next_visible else None),
'pop_receipt': msg.pop_receipt,
'dequeue_count': msg.dequeue_count
})
message.set(func.Document.from_json(json.dumps(data)))
My error message when I run the script:
[Running] python -u "c:\Users\artem\Desktop\function\inspariqueuestore\__init__.py"
File "c:\Users\artem\Desktop\function\inspariqueuestore\__init__.py", line 12
data = json.dumps({
^
IndentationError: unexpected indent
[Done] exited with code=1 in 0.093 seconds
UPDATE
I mixed tabs and spaces apparently. Issue resolved.
I don't see any indentation errors in your file.
Yes, you can try to format your file using VS Code.
There is a shortcut named editor.action.formatDocument.
You can find the exact keys for your setup in settings.
In my case it is shift + option (alt) + F
Related
I am trying to decode CAN messages from a device using the manufacturer's provided dbc file. I am using Python 3.8.5. To load/set up the dbc file, I have:
import can
import cantools
self.bus = can.interface.Bus('slcan0', bustype='socketcan',bitrate=250000)
listener = can.Listener()
listener.on_message_received = self.callback
self.dbc = cantools.database.load_file(dbc_file_path,strict=False) #need strict=False or it raises errors for overlapping signals for some reason
in the callback function I have:
def callback(self, can_msg):
decoded = self.dbc.decode_message(can_msg.arbitration_id, can_msg.data)
The script runs, but as soon as it receives a CAN message from the device, it gives me the following error:
Traceback (most recent call last):
File "/home/.local/lib/python3.8/site-packages/cantools/database/can/database.py", line 385, in decode_message
message = self._frame_id_to_message[frame_id_or_name]
KeyError: 392
Any idea what might be going wrong? I have googled and found similar errors on stack overflow, but they don't seem to be exactly the same, and the solutions they propose don't fix my issue.
Thanks!
I figured it out. The device was sending CAN messages with arbitration_ids that were not listed in the dbc file, and thus giving a Key Error. A Key Error is where you try to reference a Key in a Dictionary that does not exist. 392 was the unrecognized ID. I worked around this by adding a try/exception statement around my
decoded = self.dbc.decode_message(can_msg.arbitration_id, can_msg.data) line, and then investigating why the dbc file wasn't prepared for this particular message id.
just found the following . running via notebook
import
.echo("test")
Output:
/home/user/anaconda3/envs/p36/lib/python3.6/site-packages//utils.py in echo(message, file, nl, err, color)
257
258 if message:
--> 259 file.write(message)
260 file.flush()
261
UnsupportedOperation: not writable
Has someone seen this before and knows how to work around? I have to use a lib via that uses . so not is not possible.
Update:
This commit to a jupyter branch of click solves the issue:
https://github.com/elgalu/click/commit/1cb7aaba8c9dd6ec760d3e7e414d0b4e5f788543#diff-d17772ee4f65879b69a53dbc4b3d42bd
I think that Jupyter hijacks and locks the STDOUT/STDERR (at least the one click is trying to use) and if you don't provide a stream to click.echo() it will attempt writing to the STDOUT/STDERR, hence the error.
You can work around it by passing an output stream like STDOUT yourself:
import click
import sys
click.echo("test", sys.stdout)
# test
In my case using Python 3 I wanted to preserve the click styling on my message both in the Jupyter notebook and when the code was run in the terminal. I handled it this way:
from io import UnsupportedOperation
import click
item = 'Your Name'
message = click.style('"{}"'.format(item), fg='red', bold=True)
try:
click.echo(message)
except UnsupportedOperation as err:
print('Error: "{}"'.format(err))
print(message)
The color is preserved in the notebook:
I'm trying to follow http://gregblogs.com/how-django-reactjs-and-browserify/.
I went through some hoops to get collectstatic working but it runs without error now. However when I try to load the page which contains my react component, another compilation process kicks in (I thought collectstatic will pre-process everything and nothing will have to compile run-time). It requires some hack to make it work right now (https://github.com/j0hnsmith/django-pipeline-browserify/issues/14). But even after that patch, unfortunately this compilation errors out. Although the command seems OK now: if I execute
C:\Users\JohnSmith\node_modules\.bin\browserify.cmd -t babelify --deps C:\Users\JohnSmith\Documents\test\company\static\dashboard\js\react_test_dashboard_widget.browserify.js
it runs without an error and produces a dependency JSON. When the same command is executed as a sub-process by Django/Pipeline, it errors out saying
Error: Cannot find module ' babelify' from 'C:\Users\JohnSmith\Documents\test\company
How to overcome that?
packages.json snippet
"dependencies": {
"babel-cli": "^6.6.5",
"babel-preset-es2015": "^6.6.0",
"yuglify": "^0.1.4",
"babelify": "^7.3.0",
"browserify": "^13.0.1",
"jquery": "^2.2.0",
"react": "^15.2.0"
},
"devDependencies": {
"babel-plugin-transform-class-properties": "^6.10.2",
"babel-plugin-transform-react-jsx": "^6.8.0",
"babel-preset-es2016": "^6.11.0",
"babel-preset-react": "^6.11.1"
}
requirements snippet:
...
django-pipeline==1.6.6
django-pipeline-browserify==0.4.1
futures==3.0.5
...
Some settings (BTW https://github.com/j0hnsmith/django-pipeline-browserify/issues/15):
PIPELINE["CSS_COMPRESSOR"] = "pipeline.compressors.NoopCompressor"
PIPELINE["JS_COMPRESSOR"] = "pipeline.compressors.NoopCompressor"
PIPELINE['SASS_BINARY'] = 'C:\\Ruby22-x64\\bin\\sass.bat'
PIPELINE['BABEL_BINARY'] = 'c:\\Users\\JohnSmith\\node_modules\\.bin\\babel.cmd'
PIPELINE['BROWSERIFY_BINARY'] = 'c:\\Users\\JohnSmith\\node_modules\\.bin\\browserify.cmd'
PIPELINE_BROWSERIFY_BINARY = PIPELINE['BROWSERIFY_BINARY']
if DEBUG:
PIPELINE["BROWSERIFY_ARGUMENTS"] = '-t babelify'
PIPELINE_BROWSERIFY_ARGUMENTS = PIPELINE["BROWSERIFY_ARGUMENTS"]
(last one was needed for compilers!)
My system: Win 10, Python 2.7, Django 1.8
Tell me what else should I specify
Update: the error message comes from Node itself. See the call stack below. Note, that here I tried to explicitly specify the transformation JS file instead of a module name (this also works well from the command line but not well in the app):
CompilerError: ['c:\\Users\\JohnSmith\\node_modules\\.bin\\browserify.cmd', '-t c:\\Users\\JohnSmith\\Documents\\test\\node_modules\\babelify\\index.js', u'--deps C:\\Users\\JohnSmith\\Documents\\test\\company\\static\\dashboard\\js\\react_test_dashboard_widget.browserify.js'] exit code 1
Error: Cannot find module ' c:\Users\JohnSmith\Documents\test\node_modules\babelify\index.js' from 'C:\Users\JohnSmith\Documents\test\company'
at c:\Users\JohnSmith\node_modules\resolve\lib\async.js:46:17
at process (c:\Users\JohnSmith\node_modules\resolve\lib\async.js:173:43)
at ondir (c:\Users\JohnSmith\node_modules\resolve\lib\async.js:188:17)
at load (c:\Users\JohnSmith\node_modules\resolve\lib\async.js:69:43)
at onex (c:\Users\JohnSmith\node_modules\resolve\lib\async.js:92:31)
at c:\Users\JohnSmith\node_modules\resolve\lib\async.js:22:47
at FSReqWrap.oncomplete (fs.js:82:15)
This advises me that maybe the problem is that Node itself captures the t parameter and doesn't pass it to browserify. For sure this issue might be crucial: https://github.com/j0hnsmith/django-pipeline-browserify/issues/14
I overrode the https://github.com/j0hnsmith/django-pipeline-browserify/blob/master/pipeline_browserify/compiler.py#L55
command = "%s %s %s --deps %s" % (
getattr(settings, 'PIPELINE_BROWSERIFY_VARS', ''),
getattr(settings, 'PIPELINE_BROWSERIFY_BINARY', '/usr/bin/env browserify'),
getattr(settings, 'PIPELINE_BROWSERIFY_ARGUMENTS', ''),
self.storage.path(infile),
)
with
command = (
getattr(settings, 'PIPELINE_BROWSERIFY_BINARY', '/usr/bin/env browserify'),
getattr(settings, 'PIPELINE_BROWSERIFY_ARGUMENTS', ''),
"--deps %s" % self.storage.path(infile),
)
'cause the pipeline compiler code expects tuples. By he original code it received one complete string, but then it dissected it to individual characters, thinking that all of them are arguments, see https://github.com/jazzband/django-pipeline/blob/master/pipeline/compilers/init.py#L108
argument_list = []
for flattening_arg in command:
if isinstance(flattening_arg, string_types):
argument_list.append(flattening_arg)
else:
argument_list.extend(flattening_arg)
This would lead to a disaster later:
CompilerError: [Error 87] The parameter is incorrect
My co-worker tried to get it working on OSX too, but we gave up. We just short-circuited the is_outdated to always return true. The is_outdated contains some info in the comments about that anyway (https://github.com/j0hnsmith/django-pipeline-browserify/blob/master/pipeline_browserify/compiler.py#L41):
"WARNING: It seems to me that just generating the dependencies may take just as long as actually compiling, which would mean we would be better off just forcing a compile every time."
The way to shortcircuit is to define your own compiler and register that one.
PIPELINE['COMPILERS'] = (
'pipeline.compilers.sass.SASSCompiler',
# 'pipeline_browserify.compiler.BrowserifyCompiler',
'company.utils.compilers.BrowserifyCompiler',
...
)
Where
class BrowserifyCompiler(BrowserifyCompiler):
def is_outdated(self, infile, outfile):
return True
Last comment and the sheer fact that noone complained about this before makes me wonder about the state of the project...
https://github.com/j0hnsmith/django-pipeline-browserify/issues/14
I have recently start learning how to make xbmc/kodi addons.
I am trying to create multiple directories but keep getting "error:script failed:" when i click the addon icon on video section.
Could anyone help me fix this error and create multiple directories so i could populate them with data later? I searched a lot to find a beginner tutorial on how to make directories but couldn't find one. Thanks in advance.
import urllib, urllib2, sys, re, os, unicodedata
import xbmc, xbmcgui, xbmcplugin, xbmcaddon, base64
plugin_handle = int(sys.argv[1])
def CATEGORIES():
add_dir("search",url,1,"")
add_dir( "AnimalS",url,1,"")
add_dir( "cars",url,1,"")
add_dir("Fruits",url,1,"")
url = None
name = None
mode = None
iconimage = None
if mode==None or url==None or len(url)<1:
print ""
CATEGORIES()
xbmcplugin.endOfDirectory(plugin_handle)
error on xbmc.log:
ERROR: EXCEPTION Thrown (PythonToCppException) :
-->Python callback/script returned the following error<--
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.IndentationError'>
Error Contents: ('unindent does not match any outer indentation level', ('C:\\.....addons\\plugin.video.populateDirectory\\addon.py', 12, 32, ' add_dir("Fruits",url,1,"")\n'))
IndentationError: ('unindent does not match any outer indentation level', ('C:\\....\\addons\\plugin.video.populateDirectory\\addon.py', 12, 32, ' add_dir("Fruits",url,1,"")\n'))
-->End of Python script error report<--
ERROR: XFILE::CDirectory::GetDirectory - Error getting plugin://plugin.video.test/
ERROR: CGUIMediaWindow::GetDirectory(plugin://plugin.video.test/) failed
NOTICE: Thread BackgroundLoader start, auto delete: false
I am using this code in openerp7 for directoly print from printer this code I was written in main.py, but when I start server it gives unhandled error on my browser console actually this error happen with importing win32print module.
import win32print
printer=OpenPrinter(win32print.GetDefaultPrinter())
hJob = win32print.StartDocPrinter (printer, 1, ("RVGI Print", None, "RAW"))
g=open('test3.txt','r')
raw_data = bytes ( open( 'test3.txt' , 'r').read ())
try:
win32print.StartPagePrinter (printer)
win32print.WritePrinter (printer, raw_data)
win32print.EndPagePrinter (printer)
finally:
win32print.EndDocPrinter (printer)
win32print.ClosePrinter (printer)
After looking at your code, I can find only problem that is undefined variable OpenPrinter which can be rectified by merely replacing OpenPrinter() with win32print.OpenPrinter()