I declared a global variable in python and still i'm facing error saying that variable is not defined. Can someone please please help me.
def _pick_server (self, key, inport):
global scount1
global scount2
global scount3
server1wt = 4
server2wt = 1
server3wt = 2
liveservers = sorted(self.live_servers.keys())
for i in liveservers:
print(i)
if (scount1 < server1wt):
scount1 += scount1
print(scount1)
print (liveservers[0])
return liveservers[0]
elif (scount2 < server3wt):
scount2 += scount2
print (liveservers[1])
return liveservers[1]
elif (scount3 < server3wt):
scount3 += scount3
print (liveservers[2])
return liverservers[2]
else:
scount1 = 1
scount2 = 0
scount3 = 0
liveservers[0]
The error i'm getting is as below:
Traceback (most recent call last):
File "/home/mininet/pox/pox/lib/revent/revent.py", line 231, in
raiseEventNoErrors
return self.raiseEvent(event, *args, **kw)
File "/home/mininet/pox/pox/lib/revent/revent.py", line 278, in raiseEvent
rv = event._invoke(handler, *args, **kw)
File "/home/mininet/pox/pox/lib/revent/revent.py", line 156, in _invoke
return handler(self, *args, **kw)
File "/home/mininet/pox/ext/ents_loadbalancer.py", line 307, in
_handle_PacketIn
server = self._pick_server(key, inport)
File "/home/mininet/pox/ext/ents_loadbalancer.py", line 203, in _pick_server
if (scount1 < server1wt):
NameError: global name 'scount1' is not defined
your using scount1 before defining it
how can you test its value when it is unknown?
Solution
scount1 = 1
before
if (scount1 < server1wt)
Related
I'm new to coding in general (little experience from Javascript before) and python to be specific. Tried out Leetcode, but now am stuck as I get an error. I compiled the script first in VS Code, and there it runs fine. But in Leetcode i get the following error:
`
TypeError: Parameters to generic types must be types. Got 0.
raise TypeError(f"{msg} Got {arg!r:.100}.")
Line 175 in _type_check (/usr/lib/python3.10/typing.py)
params = tuple(_type_check(p, msg) for p in params)
Line 1126 in <genexpr> (/usr/lib/python3.10/typing.py)
params = tuple(_type_check(p, msg) for p in params)
Line 1126 in __getitem__ (/usr/lib/python3.10/typing.py)
return func(*args, **kwds)
Line 311 in inner (/usr/lib/python3.10/typing.py)
shortestWord = min(filter(None, List), key=len)
Line 4 in longestCommonPrefix (Solution.py)
ret = Solution().longestCommonPrefix(param_1)
Line 41 in _driver (Solution.py)
_driver()
Line 52 in <module> (Solution.py)
Also line 4 is highlighted in red and with exclamation mark:
shortestWord = min(filter(None, List), key=len)
This is my code in Leetcode. It differs from the one I use in VS Code only in that I don't have the class Solution and def includes only (List) as a parameter:
`class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
testCharacter = []
shortestWord = min(filter(None, List), key=len)
length = len(shortestWord)
result = ""
for i in range(0,length):
testCharacter.append(i)
testCharacter[i] = ""
for words in List:
counter = 0
for index, char in enumerate(words):
testCharacter[index] += char
counter += 1
if counter == length:
break
for i in range(0,length):
if testCharacter[i] == testCharacter[i][0]*len(List):
result += testCharacter[i][0]
else:
break
return result
The task at hand is to return the longest common prefix for a list of strings. For example, ["bull", "bully", "but"] should return "bu".
EDIT: I wonder if you think the issue might be that I'm trying to store an entire dictionary row returned from database in a session variable?
Here's the error (full error printout is at bottom of this post):
TypeError: Object of type User is not JSON serializable
FYI: I'm not using JSON anywhere in my code.
Here's the relevant parts of my code (main.py):
class User():
def __init__(self, t_id_user=None, t_email=None):
self.t_id_user = t_id_user
self.t_email = t_email
def create_or_update(self, t_create_or_edit="Edit"):
#How necessary are the "=None" below?
#self.t_id_user = userCreate(self, t_id_user=None, t_email=None):
#How necessary are the "=None" above?
if t_create_or_edit == "Create":
self.t_id_user = userCreate(
self.t_email
)
else:
self.t_id_user = userUpdate(
self.t_id_user_edit,
self.t_email
)
def get_from_id(self, t_id_user):
# logic to retrieve your user's data from your database of choice
myData = usersGet(
t_id_user="0",
t_email=""
)
self.t_id_user = myData["t_id_user"]
self.t_email = myData["t_email"]
return self
def userClearSession(t_which="user_current"):
logging.debug("Start of userClearSession()")
t_id_user = "0"
t_email = ""
user_instance = User(t_id_user, t_email)
if t_which == "user_current":
session["user_current"] = user_instance
else:
session["user_edit"] = user_instance
return
#app.route('/', methods=['GET', 'POST'])
#app.route('/userRegister', methods=['GET', 'POST'])
def index(t_title="Login or Register", t_message=""):
if "user_current" not in session:
userClearSession(t_which="user_current")
return render_template(
"userRegister.html",
t_message=t_message,
t_js="userRegister.js",
t_title=t_title
)
def userCreate(t_which="current"):
id_user = 0
db_cursor = data_cursor()
q = ""
q += "INSERT INTO tbl_users "
q += " ( "
q += " i_security_level"
q += ", t_email"
q += " ) "
q += " VALUES "
q += " ( "
q += " %(t_security_level)s"
q += ", '%(t_email)s'"
q += " ) "
try:
if t_which == "current":
user_instance = session["user_current"]
else:
user_instance = session["user_edit"]
vars = {
't_security_level': int(session["user_instance"].t_security_level),
't_email': AsIs(session["user_instance"].t_email)
}
db_cursor.execute(q,vars)
except Exception as e:
t_message = "Error"
else:
id_found = userIsInDB(session["user_instance"].t_email)
if id_found >= 1:
t_id_user = id_found
if t_which == "current":
session["user_current"].t_id_user = t_id_user
else:
session["user_edit"].t_id_user = t_id_user
t_message = "User Created"
db_cursor.close()
db_conn.close()
The full error message:
I'm having a hard time getting any meaning out of this error message and need help. It doesn't appear to point to any parts of main.py, though I know the error is somewhere in there and I'm pretty sure I narrowed it down to the code you see above:
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1970, in finalize_request
response = self.process_response(response)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2269, in process_response
self.session_interface.save_session(self, ctx.session, response)
File "C:\Python\Python38\Lib\site-packages\flask\sessions.py", line 378, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "C:\Python\Python38\Lib\site-packages\itsdangerous\serializer.py", line 166, in dumps
payload = want_bytes(self.dump_payload(obj))
File "C:\Python\Python38\Lib\site-packages\itsdangerous\url_safe.py", line 42, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "C:\Python\Python38\Lib\site-packages\itsdangerous\serializer.py", line 133, in dump_payload
return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
File "C:\Python\Python38\Lib\site-packages\flask\json\tag.py", line 305, in dumps
return dumps(self.tag(value), separators=(",", ":"))
File "C:\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 211, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Python\Python38\Lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Python\Python38\Lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python\Python38\Lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 100, in default
return _json.JSONEncoder.default(self, o)
File "C:\Python\Python38\Lib\json\encoder.py", line 179, in default
Open an interactive python shell in this frameraise TypeError(f'Object of type {o.__class__.__name__}
I am trying to execute the codes from this link
https://zulko.github.io/blog/2014/06/21/some-more-videogreping-with-python/
import re # module for regular expressions
def convert_time(timestring):
""" Converts a string into seconds """
nums = map(float, re.findall(r'\d+', timestring))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
with open("Identity_2003.srt") as f:
lines = f.readlines()
times_texts = []
current_times , current_text = None, ""
for line in lines:
times = re.findall("[0-9]*:[0-9]*:[0-9]*,[0-9]*", line)
if times != []:
current_times = map(convert_time, times)
elif line == '\n':
times_texts.append((current_times, current_text))
current_times, current_text = None, ""
elif current_times is not None:
current_text = current_text + line.replace("\n"," ")
print (times_texts)
from collections import Counter
whole_text = " ".join([text for (time, text) in times_texts])
all_words = re.findall("\w+", whole_text)
counter = Counter([w.lower() for w in all_words if len(w)>5])
print (counter.most_common(10))
cuts = [times for (times,text) in times_texts
if (re.findall("please",text) != [])]
from moviepy.editor import VideoFileClip, concatenate
video = VideoFileClip("Identity_2003.mp4")
def assemble_cuts(cuts, outputfile):
""" Concatenate cuts and generate a video file. """
final = concatenate([video.subclip(start, end)
for (start,end) in cuts])
final.to_videofile(outputfile)
assemble_cuts(cuts, "please.mp4")
But the assemble_cuts function is not working . I am using python3.x
it is giving me an error
Traceback (most recent call last):
File "<ipython-input-64-939ee3d73a4a>", line 47, in <module>
assemble_cuts(cuts, "please.mp4")
File "<ipython-input-64-939ee3d73a4a>", line 44, in assemble_cuts
for (start,end) in cuts])
File "<ipython-input-64-939ee3d73a4a>", line 43, in <listcomp>
final = concatenate([video.subclip(start, end)
File "<ipython-input-64-939ee3d73a4a>", line 6, in convert_time
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
TypeError: 'map' object is not subscriptable
Could you help me to solve this problem?
Fixed it.
def convert_time(timestring):
""" Converts a string into seconds """
nums = list(map(float, re.findall(r'\d+', timestring)))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
I am making a code that makes a map (not visible), and you can move in it.
I have been working on this code for a week now.
It has a TypeError.
import map
def basicRealm():
player=[0,0]#this is you
Home=[0,0]
Shops=[2,7]
Park=[8,2]
locations = [Home, Shops, Park]
desternation=Park
RealmSize = grid(10)
choice = input("Move north, south, east, or west?[north/south/east/west]")
no = int(input("Number of spaces to move: "))
if choice=='north':
axis=y
elif choice=='south':
axis=y
elif choice=='east':
axis==x
elif choice=='west':
axis=x
else:
pass
nothing=''
if choice=='south' or choice=='east':
no = 0 - no
else:
pass
you_are_here = move(no, player, axis)
basicRealm()
And my map module to run it is :
def atDesternation(location):
global desternation
if desternation==location:
return True
else:
return False
def atLocation(Object,locations):
pos = position(Object)
for i in locations:
if pos==i:
return i
else:
return None
def position(Object):
pos = (Object[0], Object[1])
return pos
def grid(size):
size = ListRange(0, size)
return size
def move(spaces, thing, axis):
here= position(thing)
pos = here[axis] + spaces
return pos
The Output is as follows:
Move north, south, east, or west?[north/south/east/west]north
Number of spaces to move: 1
Traceback (most recent call last):
File "C:\Users\lewis\Desktop\Map1.py", line 35, in <module>
basicRealm()
File "C:\Users\lewis\Desktop\Map1.py", line 29, in basicRealm
print(position(you_are_here))
File "C:\Users\lewis\Desktop\map.py", line 13, in position
pos = (Object[0], Object[1])
TypeError: 'int' object is not subscriptable
>>>
How do I solve this error? Please help.
I am newish to Python and find it very hard to slove Errors.
I recently got a raspberry pi and a book to go along with it(Raspberry Pi Cookbook). One of the projects is controlling the GPIO pins on the RPi via a webpage. When I first ran the code after typing it out, I received a bunch of errors so, I tried running the code listed on the books github page:
from bottle import route, run
import RPi.GPIO as GPIO
host = '192.168.1.8'
GPIO.setmode(GPIO.BCM)
led_pins = [18, 23, 24]
led_states = [0, 0, 0]
switch_pin = 25
GPIO.setup(led_pins[0], GPIO.OUT)
GPIO.setup(led_pins[1], GPIO.OUT)
GPIO.setup(led_pins[2], GPIO.OUT)
GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def switch_status():
state = GPIO.input(switch_pin)
if state:
return 'Up'
else:
return 'Down'
def html_for_led(led):
l = str(led)
result = " <input type='button' onClick='changed(" + l + ")' value='LED " + l + "'/>"
return result
def update_leds():
for i, value in enumerate(led_states):
GPIO.output(led_pins[i], value)
#route('/')
#route('/<led>')
def index(led="n"):
print(led)
if led != "n":
led_num = int(led)
led_states[led_num] = not led_states[led_num]
update_leds()
response = "<script>"
response += "function changed(led)"
response += "{"
response += " window.location.href='/' + led"
response += "}"
response += "</script>"
response += '<h1>GPIO Control</h1>'
response += '<h2>Button=' + switch_status() + '</h2>'
response += '<h2>LEDs</h2>'
response += html_for_led(0)
response += html_for_led(1)
response += html_for_led(2)
return response
run(host=host, port=80)
When I run the code(sudo python web_control.py) I get a invalid literal for int() with base 10: 'favicon.ico' error. Here is the traceback:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/bottle.py", line 744, in _handle
return route.call(**args)
File "/usr/lib/python2.7/dist-packages/bottle.py", line 1480, in wrapper
rv = callback(*a, **ka)
File "web_control.py", line 42, in index
response += " window.location.href='/' + led"
UnboundLocalError: local variable 'response' referenced before assignment
192.168.0.108 - - [29/Dec/2014 21:31:46] "GET / HTTP/1.1" 500 740
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/bottle.py", line 744, in _handle
return route.call(**args)
File "/usr/lib/python2.7/dist-packages/bottle.py", line 1480, in wrapper
rv = callback(*a, **ka)
File "web_control.py", line 36, in index
led_num = int(led)ValueError: invalid literal for int() with base 10: 'favicon.ico'
Any idea what is going on here? Any help is greatly appreciated.
what does your
print led
show ?
they say that led is not an int so the error could be from there