post#1 Learning python.
Using IDLE shell and script, both experience this issue.
Successfully importing "string" module, but calling a function from it returns an error:
from string import *
find("atgacatgcacaagtatgcat","atg")
error:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
find("atgacatgcacaagtatgcat","atgc")
NameError: name 'find' is not defined
find is a method of the class string. You have to use .find
try below example:
str1 = "atgacatgcacaagtatgcat"
str2 = "atg"
str1.find(str2)
Related
I have created a custom python sync block for use in a gnuradio flowgraph. The block tests for invalid input and, if found, raises a ValueError exception. I would like to create a unit test to verify that the exception is raised when the block indeed receives invalid input data.
As part of the python-based qa test for this block, I created a flowgraph such that the block receives invalid data. When I run the test, the block does appear to raise the exception but then hangs.
What is the appropriate way to test for this? Here is a minimal working example:
#!/usr/bin/env python
import numpy as np
from gnuradio import gr, gr_unittest, blocks
class validate_input(gr.sync_block):
def __init__(self):
gr.sync_block.__init__(self,
name="validate_input",
in_sig=[np.float32],
out_sig=[np.float32])
self.max_input = 100
def work(self, input_items, output_items):
in0 = input_items[0]
if (np.max(in0) > self.max_input):
raise ValueError('input exceeds max.')
validated_in = output_items[0]
validated_in[:] = in0
return len(output_items[0])
class qa_validate_input (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_check_valid_data(self):
src_data = (0, 201, 92)
src = blocks.vector_source_f(src_data)
validate = validate_input()
snk = blocks.vector_sink_f()
self.tb.connect (src, validate)
self.tb.connect (validate, snk)
self.assertRaises(ValueError, self.tb.run)
if __name__ == '__main__':
gr_unittest.run(qa_validate_input, "qa_validate_input.xml")
which produces:
DEPRECATED: Using filename with gr_unittest does no longer have any effect.
handler caught exception: input exceeds max.
Traceback (most recent call last):
File "/home/xxx/devel/gnuradio3_8/lib/python3.6/dist-packages/gnuradio/gr/gateway.py", line 60, in eval
try: self._callback()
File "/home/xxx/devel/gnuradio3_8/lib/python3.6/dist-packages/gnuradio/gr/gateway.py", line 230, in __gr_block_handle
) for i in range(noutputs)],
File "qa_validate_input.py", line 21, in work
raise ValueError('input exceeds max.')
ValueError: input exceeds max.
thread[thread-per-block[1]: <block validate_input(2)>]: SWIG director method error. Error detected when calling 'feval_ll.eval'
^CF
======================================================================
FAIL: test_check_valid_data (__main__.qa_validate_input)
----------------------------------------------------------------------
Traceback (most recent call last):
File "qa_validate_input.py", line 47, in test_check_valid_data
self.assertRaises(ValueError, self.tb.run)
AssertionError: ValueError not raised by run
----------------------------------------------------------------------
Ran 1 test in 1.634s
FAILED (failures=1)
The top_block's run() function does not call the block's work() function directly but starts the internal task scheduler and its threads and waits them to finish.
One way to unit test the error handling in your block is to call the work() function directly
def test_check_valid_data(self):
src_data = [[0, 201, 92]]
output_items = [[]]
validate = validate_input()
self.assertRaises(ValueError, lambda: validate.work(src_data, output_items))
I Create a thread inside the __main__ function by creating an object that inherits from threading.Thread. Inside its run method i open multiprocessing.Process with a target function that is in global namespace of the module but i get the error:
from multiprocessing import Process, Queue
import threading
def executeTests(ScriptName, Params, MsgQueue, ResultQueue):
...
class TestRunner(threading.Thread):
def __init__(self, tests):
threading.Thread.__init__(self)
...
def run(self):
MsgQueue = Queue()
ResultQueue = Queue()
TestProcess = Process(target=executeTests, args=(ScriptName, Params, MsgQueue, ResultQueue))
TestProcess.start()
...
if __name__ == "__main__":
TestRunner(...).start()
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 105, in sp
awn_main
exitcode = _main(fd)
File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 115, in _m
ain
self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'executeTests' on <module '__main__' (built-
in)>
I solved it myself.
A join() was missing in main.
When running the PySide Diagram Scene example (circa 2010), I get the error below. Is there a more current example of a basic diagram editor available?
C:\Python34\python.exe C:/Users/dle/Documents/Programming/Python/diagramscene.py
Traceback (most recent call last):
File "C:/Users/dle/Documents/Programming/Python/diagramscene.py", line 11, in <module>
import diagramscene_rc
File "C:\Users\dle\Documents\Programming\Python\diagramscene_rc.py", line 404, in <module>
qInitResources()
File "C:\Users\dle\Documents\Programming\Python\diagramscene_rc.py", line 399, in qInitResources
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
TypeError: 'qRegisterResourceData' called with wrong argument types:
qRegisterResourceData(int, str, str, str)
Supported signatures:
qRegisterResourceData(int, unicode, unicode, unicode)
The problem is that the file diagramscene_rc.py has been generated for python2, to solve it you must recompile that file for it opens a terminal in the folder and executes the following command:
pyside-rcc diagramscene.qrc -o diagramscene_rc.py -py3
Or, place the letter b before assigning the variable as shown below:
qt_resource_data = "\
\x00\x00\x01\x12\
...
qt_resource_name = "\
\x00\x06\
...
qt_resource_struct = "\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
....
to:
qt_resource_data = b"\
\x00\x00\x01\x12\
...
qt_resource_name = b"\
\x00\x06\
...
qt_resource_struct = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
....
have query on following code which is working on django 1.6
from django import template register = template.Library()
#register.filter def lt(a,b): return float(a) < float(b); #register.filter def gt(a,b): return float(a) > float(b);
template.builtins.append(register)
but same code is not working on django 1.8 and throwing below error
template.builtins.append(register) Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'builtins'
why it is throwing error? if any one has already got this issue ,provide your input?
Based on this java example, I made the following servlet filter in jython (exact code):
from javax.servlet import Filter
from javax.servlet.http import HttpServletRequest
class HttpServletRequestWrapper(HttpServletRequest):
def init(self, request):
self.originalURL = self.getRequestURL()
pathi = self.originalURL.find('/', 10) # find start of path
qsi = self.originalURL.find('?', pathi) # find start of qs if any
qs = self.originalURL[qsi:] if qsi > -1 else ''
self.newURL = self.originalURL[:pathi] + '/ccc/jope.py' + qs
def getRequestURL(self):
return self.newURL
class Route2Jope(Filter):
def init(self, config):
pass
def doFilter(self, request, response, chain):
wrapped = HttpServletRequestWrapper(request)
chain.doFilter(wrapped, response)
However, I am getting the error message:
Traceback (most recent call last):
File "c:\CCC\webapps\ccc\WEB-INF\pyfilter\Route2Jope.py", line 24, in doFilter
wrapped = HttpServletRequestWrapper(request)
TypeError: org.python.proxies.__main__$HttpServletRequestWrapper$2(): expected 0 args; got 1
org.python.core.Py.TypeError(Py.java:259)
org.python.core.PyReflectedFunction.throwError(PyReflectedFunction.java:209)
org.python.core.PyReflectedFunction.throwArgCountError(PyReflectedFunction.java:262)
org.python.core.PyReflectedFunction.throwError(PyReflectedFunction.java:319)
org.python.core.PyReflectedConstructor.__call__(PyReflectedConstructor.java:177)
org.python.core.PyObject.__call__(PyObject.java:419)
org.python.core.PyMethod.instancemethod___call__(PyMethod.java:237)
org.python.core.PyMethod.__call__(PyMethod.java:228)
org.python.core.PyMethod.__call__(PyMethod.java:223)
org.python.core.Deriveds.dispatch__init__(Deriveds.java:19)
org.python.core.PyObjectDerived.dispatch__init__(PyObjectDerived.java:1112)
org.python.core.PyType.type___call__(PyType.java:1713)
org.python.core.PyType.__call__(PyType.java:1696)
org.python.core.PyObject.__call__(PyObject.java:461)
org.python.core.PyObject.__call__(PyObject.java:465)
org.python.pycode._pyx1.doFilter$6(c:\CCC\webapps\ccc\WEB-INF\pyfilter\Route2Jope.py:25)
org.python.pycode._pyx1.call_function(c:\CCC\webapps\ccc\WEB-INF\pyfilter\Route2Jope.py)
org.python.core.PyTableCode.call(PyTableCode.java:167)
org.python.core.PyBaseCode.call(PyBaseCode.java:307)
org.python.core.PyBaseCode.call(PyBaseCode.java:198)
org.python.core.PyFunction.__call__(PyFunction.java:482)
org.python.core.PyMethod.instancemethod___call__(PyMethod.java:237)
org.python.core.PyMethod.__call__(PyMethod.java:228)
org.python.core.PyMethod.__call__(PyMethod.java:218)
org.python.core.PyMethod.__call__(PyMethod.java:213)
org.python.core.PyObject._jcallexc(PyObject.java:3626)
org.python.proxies.__main__$Route2Jope$3.doFilter(Unknown Source)
org.python.util.PyFilter.doFilter(PyFilter.java:80)
I think it's telling me I should not pass the parameter 'request', but it does not make sense to me. Maybe I am overlooking some mapping issue between python ad java classes? Suggestions?
The name of your constructor must be __init__, not init. :)