I learn Python and as a practice decided to write a server for a network game "Backgammon". The question arose as to make sure that found in the queue apponet still online? How to send a ping and accept the answer? I'm trying to do it on line 71, but this is incorrect.
import pymongo, socket, threading, string, json, MySQLdb, random, time
stat = True
conn = {}
#gamers = {}
games = {}
diceroll = []
tempconn = {}
c = pymongo.Connection()
db = c.nardy
nru = db.notregusers
uwait = db.userwait
class ClientThread(threading.Thread):
def __init__(self, channel, details):
self.channel = channel
self.details = details
threading.Thread.__init__(self)
def getUserId(self, data):
json_data = json.loads(data)
if json_data['t'] == 'n':
print ' - User not register'
if nru.find({'identuser':json_data['i'], 'platform':json_data['p']}).count() == 0:
print ' - New user'
count = nru.find().count();
newid = count + 1;
nru.save({'id':newid, 'identuser':json_data['i'], 'platform':json_data['p'], 'level':1})
return nru.find_one({'id':newid})
else:
print ' - Old user'
return nru.find_one({'identuser':json_data['i'], 'platform':json_data['p']})
elif json_data['t'] == 'r':
return 9999
def mySQLConnect(self):
db = MySQLdb.connect(host="localhost", user="", passwd="", db="", charset='utf8')
return db
def run(self):
while True:
data = self.channel.recv(1024)
try:
json_data = json.loads(data)
comm = json_data['c']
if comm == 'x':
if conn.has_key(gamer['level']) and self in conn[gamer['level']]:
conn[gamer['level']].remove(self)
self.channel.close()
break
elif comm == 'h':
gamer = self.getUserId(data)
self.gamer = gamer
elif comm == 'f':
lev = 0
findenemy = 1
while findenemy == 1:
if conn.has_key(gamer['level']):
lev = gamer['level']
elif conn.has_key((gamer['level'] - 1)):
lev = (gamer['level'] - 1)
elif conn.has_key((gamer['level'] + 1)):
lev = (gamer['level'] + 1)
if lev != 0:
if len(conn[lev]) > 0:
enemy = conn[lev].pop(0)
firsttime = time.time()
enemy.channel.send('{"o":"p"}')
while (firsttime + 30) > time.time() and findenemy == 1:
if comm == 'k':
findenemy = 0
print ' - Ping enemy: ok'
if findenemy == 0:
self.enemy = enemy
gameid = str(self.gamer['id']) + '_' + str(self.enemy.gamer['id'])
games[gameid] = {'dice':[], 'nextstep':0}
vrag = self.enemy
a = random.sample(range(1,7),2)
self.channel.send('{"o":"s", "u":"' + str(a[0]) + '", "e":"' + str(a[1]) + '"}')
vrag.channel.send('{"o":"s", "u":"' + str(a[1]) + '", "e":"' + str(a[0]) + '"}')
if a[0] > a[1]:
step = 1
games[gameid]['nextstep'] = self.gamer['id']
self.channel.send('{"o":"u"}')
vrag.channel.send('{"o":"w"}')
else:
step = 2
games[gameid]['nextstep'] = self.enemy.gamer['id']
self.channel.send('{"o":"w"}')
vrag.channel.send('{"o":"u"}')
tempconn[self.enemy] = self
else:
conn[lev].append(self)
findenemy = 0
self.channel.send('{"o":"q"}')
else:
conn[gamer['level']] = [self]
self.channel.send('{"o":"q"}')
elif comm == 'w':
if not hasattr(self, 'enemy'):
self.enemy = tempconn[self]
vrag = self.enemy
gameid = str(self.enemy.gamer['id']) + '_' + str(self.gamer['id'])
self.channel.send('{"o":"o"}')
elif comm == 'r' and games[gameid]['nextstep'] == self.gamer['id']:
dice = []
dice.append(self.gamer['id'])
dice.append(random.randint(1,6))
dice.append(random.randint(1,6))
games[gameid]['dice'].append(dice)
self.channel.send('{"o":"r", "f":"' + str(dice[1]) + '", "s":"' + str(dice[2]) + '"}')
vrag.channel.send('{"o":"r", "f":"' + str(dice[1]) + '", "s":"' + str(dice[2]) + '"}')
games[gameid]['nextstep'] = self.enemy.gamer['id']
elif comm == 'r' and games[gameid]['nextstep'] != self.gamer['id']:
self.channel.send('{"o":"w"}')
elif comm == 'm' and 't' in json_data:
self.channel.send('{"o":"y", "t":"' + str(json_data['text']) + '"}')
vrag.channel.send('{"o":"e", "t":"' + str(json_data['text']) + '"}')
elif comm == 's':
self.channel.send('{"o":"g", "countgame":"' + str(len(games)) + '"}')
elif comm == 'q' and 's' in json_data and 'e' in json_data:
print " - Player step"
elif comm == 'b' and self in conn[gamer['level']]:
conn[gamer['level']].remove(self)
except ValueError:
continue
print 'Closed connection:', self.details[0]
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 8088))
server.listen(5)
while stat:
channel, details = server.accept()
ClientThread(channel, details).start()
Perhaps, in addition to answering the question, you give me some recommendations ...
There are two options for you to send out a ping and get response.
Use scapy. Use sendp function to send a ping and get response.
Use os.system to invoke command line to send a ping and get response. Like os.system('ping 127.0.0.1')
Hope it helps.:)
Related
So I have been working on a quizzing application for some time now (about 4 days). I managed to make all the logical part of the code (the quiz taking, the quiz question handling, score outputting, etc.) I know that this code is neither the best nor the most efficient as it can be but I'm just a beginner. Anyways, the get() function for the entry function for tkinter does not return anything. I am aware that there is a way to fix it however I'm not sure how to implement the solution with an external loop. Please help me. Here is my code:
import random
from time import sleep
import tkinter as tk
from tkinter import *
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
#label = tk.Label(self.root, text="Hello World")
#label.pack()
#Button(self.root, text = "Choose", command=btnPressed).pack()
tk.Label(self.root, text="Answer: ").grid(row=0,column=0)
#answerField_get = StringVar()
answerField = tk.Entry(self.root)
answerField.grid(row=0, column=1)
#Button(self.root, text='Show').grid(row=3, column=1, sticky=tk.W, pady=4)
print(str(answerField.get()))
Button(self.root, text='Show', command = lambda arg1=answerField.get():btnPressed("<"+str(arg1)+">")).grid(row=3, column=1, sticky=tk.W, pady=4)
self.root.mainloop()
def sendTMP(self, sendStr):
btnPressed(sendStr)
SCORE_SET = []
qasTmp = {}
qas = {}
qasSequenced = {}
incorrectResponses = []
incorrectResponses_replies = []
quiztaker_name = ""
attachAnsCode = "%% Fun fact: rgb computer parts lovers are somewhat weird hehe %%********^^&&^^&&^^&&"
qasQsSequenced = False
qasQsL = 0
qasQsL_divisionFactor = 2
qasINDEX = 0
err_noCode = "<!>NO_CODE<!>"
codes_answerCorrect = "A_C"
codes_answerIncorrect = "A_I"
answerCode = err_noCode
score = 0
randQs = False
# File
# the metadata will corrupt the reading from the file, a separate file, created in the targeted system, must be used to properly read the data.
# comment out the file name that is not being used.
filename_windows = "qas-windows"
filename_rpi = "qas-rpi"
filename = filename_windows
fileformat = "txt"
file_name_format = filename + "." + fileformat
spaceIndicator = "|"
char_commentLine_qasFile = "*"
char_newline = "`"
print("Information about modes: ")
print(" *Easy: No point deductions for an incorrect response")
print(" *Hard: One point deducted for every incorrect response")
modes_err = "0"
modes_ez = "1"
modes_hard = "2"
gameOn = False
selectedMode = modes_err
askReplay = True
data_prev = []
with open("SCORES.txt", 'r') as scores_prev:
data_prev = scores_prev.readlines()
scores_prev.close()
for i in range(0, len(data_prev)):
SCORE_SET.append(data_prev[i])
def btnPressInform():
print("A button has been pressed!")
def importAndClean():
# import questions from qas-windows.txt
with open(file_name_format, 'r') as document:
for line in document:
if line.strip():
key, value = line.split(None, 1)
if key[0] != char_commentLine_qasFile: # Custom comments for the txt file
qasTmp[key] = value.split()
# Clean up dictionary input from the txt file
for i in range(0, len(qasTmp)): # FIVE FOR LOOPS!!!! (FOUR IN THIS ONE)
for ii in qasTmp:
output = ""
output_ans = ""
for iii in range(0, len(ii)):
if ii[iii] != spaceIndicator:
output += ii[iii]
else:
output += " "
for iiii in range(0, len(qasTmp[ii])):
TEMP = str(qasTmp[ii])
for iiiii in range(2, len(TEMP) - 2): # IGNORE [' and ']
# print(TEMP[iiiii])
if TEMP[iiiii] != spaceIndicator:
output_ans += TEMP[iiiii]
else:
output_ans += " "
# print(output + " : " + output_ans) #Output question: answer
qas[output] = output_ans
importAndClean()
def getL():
qasQsL = len(qas) / qasQsL_divisionFactor # only ask 1/qasQsL_divisionFactor the questions
qasQsL = int(qasQsL) # round to an integer as odd numbers will end in .5 after division
if qasQsL < 1:
qasQsL = 1 # Have atleast ONE question
return qasQsL
def debug1(keys, vals, index, i):
print(str(index) + "/" + str((len(keys) - 1)))
print(keys)
print(vals)
print()
print(keys[index] + " : " + vals[index] + "\n")
print("Sorting original index " + str(i) + " at random index " + str(index))
def debug2(keys, vals, index):
print(keys)
print(vals)
print("\n")
def debugFinal():
print("Temp (OG reading): ")
print(qasTmp)
print("\nQAS (Non-sequenced, cleaned): ")
print(qas)
print("\nQAS Sequenced (Randomly sequenced, cleaned): ")
print(qasSequenced)
def randomize(qasQsL_tmp):
qas_keys = list(qas.keys())
qas_vals = list(qas.values())
if randQs == False:
qasQsL_tmp = len(qas_keys) # all questions
print("You will be asked all " + str(qasQsL_tmp) + " questions")
else:
qasQsL_tmp = getL() # random question
print("You will be asked " + str(qasQsL_tmp) + " questions out of " + str(len(qas)) + " possible questions!")
print("\n\nRandomly sequencing questions...")
for i in range(0, qasQsL_tmp):
INDEX = random.randint(0, qasQsL_tmp - 1)
# debug1(qas_keys, qas_vals, INDEX, i)
qasSequenced[qas_keys[INDEX]] = qas_vals[INDEX]
qas_keys.pop(INDEX)
qas_vals.pop(INDEX)
qasQsL_tmp -= 1
# debug2(qas_keys, qas_vals, INDEX)
sleep(0.05)
# debugFinal()
print("Done sequencing! Starting quiz now! \n\n")
return "0"
def quizController(index):
qas_keys = list(qasSequenced.keys())
qas_vals = list(qasSequenced.values())
# print(qas_keys)
# print(qas_vals)
lines = []
lines_index = 0
tmp = ""
# Splitter
for i in range(0, len(qas_keys[index])):
if lines_index < len(qas_keys[index]) - 1:
if qas_keys[index][i] != char_newline:
tmp += qas_keys[index][i]
else:
lines.append(tmp)
tmp = ""
lines.append(tmp)
# Multiple choice
mChoiceQ = False
mChoice_startBrackets = 0
mChoice_endBrackets = 0
mChoice_options = []
mChoice_numOptions = 0
mChoice_seperatorsAt = []
for i in range(0, len(qas_keys[index])):
if qas_keys[index][i] == "[":
mChoice_startBrackets = i
mChoiceQ = True
elif qas_keys[index][i] == "]":
mChoice_endBrackets = i
elif qas_keys[index][i] == "/":
mChoice_seperatorsAt.append(i)
if mChoiceQ == True:
TEMP = ""
for i in range(mChoice_startBrackets, mChoice_endBrackets + 1):
if qas_keys[index][i] != "[":
if qas_keys[index][i] != "/" and qas_keys[index][i] != "]":
TEMP += qas_keys[index][i]
else:
mChoice_options.append(TEMP)
TEMP = ""
mChoice_numOptions = len(mChoice_seperatorsAt) + 1
# Default options (yes, no) full names
for i in range(0, len(mChoice_options)):
if mChoice_options[i].lower() == "y":
mChoice_options.append("yes")
elif mChoice_options[i].lower() == "n":
mChoice_options.append("no")
# if mChoiceQ == True:
# print("It is a multiple choice question! There are " + str(mChoice_numOptions) + " options. They are: ")
# print(mChoice_options)
print("\nQuestion " + str(index + 1) + "/" + str(qasQsL) + ":")
for i in range(0, len(lines)):
print(lines[i])
# answer = ""
answer = input(">")
# answer = input(qas_keys[index]+ ": ")
if mChoiceQ == False:
if len(answer) > 0:
if answer.lower() == str(qas_vals[index]).lower():
return codes_answerCorrect
else:
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
# print("DEBUG: Incorrect response! Expected '" + str(qas_vals[index]).lower() + "', received " + answer.lower())
return codes_answerIncorrect
else:
print("Please insert an answer!")
else:
allowedResponse = False
for i in range(0, len(mChoice_options)):
if answer.lower() == mChoice_options[i].lower():
allowedResponse = True
if allowedResponse == True:
ans = qas_vals[index].lower()
yn = False
ans_yesno = ""
if ans.lower() == "y" or ans.lower() == "n":
yn = True
else:
yn = False
if yn == True:
if ans == "y":
ans_yesno = "yes"
elif ans == "n":
ans_yesno = "no"
if len(answer) > 0:
if yn == True:
if answer.lower() == ans.lower() or answer.lower() == ans_yesno.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
if answer.lower() == ans.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
print("Please insert an answer!")
else:
print("Invalid response! You may only enter the following: " + str(mChoice_options))
def saveScore():
# Clear file!
score_file_CLEAR = open("SCORES.txt", "wt")
score_file_CLEAR.close()
# Save contents
score_file = open("SCORES.txt", "wt")
for i in range(0, len(SCORE_SET)):
score_file.write(SCORE_SET[i])
print("Done saving!")
def btnPressed(tmp):
print(tmp)
app = App()
while True:
qasQsL = len(qasSequenced)
if gameOn == True and selectedMode != modes_err:
if qasQsSequenced == True:
if qasINDEX < qasQsL:
answerCode = quizController(qasINDEX)
else:
output = randomize(qasQsL)
if output == "0":
qasQsSequenced = True
if qasINDEX < qasQsL:
if answerCode == codes_answerCorrect:
score += 1
qasINDEX += 1
# print("DEBUG: Correct! Score set to: " + str(score))
elif answerCode == codes_answerIncorrect:
if selectedMode == modes_hard:
score -= 1
qasINDEX += 1
# print("Score set to: " + str(score))
else:
print("")
if qasQsL != 0:
score_per = score / qasQsL
if score_per < 0:
score_per = 0
if score < 0:
score = 0
print("You score was lower than 0, therefore it was set to 0")
# print("Your score: " + str(score) + "/" + str(len(qasSequenced)) + " (" + str(int(score_per*100)) + "%)")
# if score != qasQsL:
# print("You responded to the following questions incorrectly:")
# print(incorrectResponses)
if score / qasQsL == 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + "(" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + "\n")
if score / qasQsL != 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + " (" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + " They got the following questions wrong: \n")
for i in range(0, len(incorrectResponses)):
SCORE_SET.append(" " + str(i + 1) + ") " + incorrectResponses[i] + " --RESPONSE-- " +
incorrectResponses_replies[i] + "\n")
SCORE_SET.append("\n")
saveScore()
qasQsSequenced = False
gameOn = False
print("\nGame over!")
askReplay = True
else:
continue
elif askReplay == False:
TEMP = input("What mode would you like? (E = Easy, H = Hard): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "e":
selectedMode = modes_ez
gameOn = True
print("Set mode to: NO POINT DEDUCTIONS")
elif str(TEMP).lower() == "h":
selectedMode = modes_hard
gameOn = True
print("Set mode to: POINT DEDUCTIONS ALLOWED")
else:
print("Error: Undefined response. Please try again!")
elif askReplay == True:
TEMP = input("Would you like to (re)do the quiz? (Y/N): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "y":
askReplay = False
qasQsSequenced = False
qasQsL = 0
qas.clear()
qasSequenced.clear()
qasTmp.clear()
qasINDEX = 0
incorrectResponses.clear()
answerCode = err_noCode
score = 0
selectedMode = modes_err
importAndClean()
randQs = False
USER_TEMP = input("Please enter your name >")
if len(USER_TEMP) > 0:
quiztaker_name = str(USER_TEMP)
print("Welcome " + quiztaker_name + "!")
USER_TEMP = input("Would you like all questions (a) or a part of the questions(p)? (A/P) > ")
if len(USER_TEMP) > 0:
if USER_TEMP.lower() == "a":
print("Set to all questions!")
randQs = False
elif USER_TEMP.lower() == "p":
print("Set to 1/" + str(qasQsL_divisionFactor) + " questions (pre-set variable)")
randQs = True
else:
print("Undefined response! Setting to default value (ALL)")
randQs = False
gameOn = False
askReplay = False
elif str(TEMP).lower() == "n":
selectedMode = modes_hard
gameOn = False
print("Exiting now!")
saveScore()
sleep(2)
exit(0)
else:
print("Error: Undefined response. Please try again!")
Entry() doesn't work like input(). It doesn't wait for your data but it only informs tkitner that you want to display Entry widget (and mainloop() will display it) and Python goes to next lines of code and it runs print(str(answerField.get())) before it even displays window - so you try to get from empty Entry.
You should get it in function assigned to Button which you will press after you put some text in Entry.
The same problem is with
lambda arg1=self.answerField.get():print(arg1)
it assigns to args value from Entry only once when lambda is defined at start - so it get empty string. You should use it inside function
command=lambda:print(self.answerField.get())
or create normal function and assign to button.
Minimal working code
import tkinter as tk
import threading
class App(threading.Thread):
def run(self):
self.root = tk.Tk()
#self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.answerField = tk.Entry(self.root)
self.answerField.grid(row=0, column=1)
#b = tk.Button(self.root, text='Show', command=lambda:print(self.answerField.get()))
b = tk.Button(self.root, text='Show', command=self.on_click)
b.grid(row=1, column=1)
self.root.mainloop()
def on_click(self):
print(self.answerField.get())
#def on_close(self):
# self.root.destroy()
App().start()
#App().run()
So I have a file that works as a socket server and I need it to be in a class structure. I would like to know how you would do it. There are some global vars and non global vars so for example which type of those will be self. or be private.
The class should be Server with an init and all the methods should be included in the class. After the class is written the code needs to create Server object and run the essential methods
i.e:
server_socket.bind(('0.0.0.0', 2303))
server_socket.listen(5)
handle_new_connection()
handle_receive_data()
handle_sending_msgs()
del public_msgs[:]
del private_msgs[:]
public_msgs.append((None, "bye"))
handle_sending_msgs()
server_socket.close()
Here's the code:
import socket
import select
import datetime
def get_current_time():
"""Returns hh:mm"""
now = datetime.datetime.now()
time = str(now.hour) + ":" + str(now.minute)
return time
def get_name(user_socket):
"""Returns the name of the user_socket, if he is an admin he gets # before his name"""
name = sockets_names[user_socket]
if len(admins) != 0:
if user_socket in admins:
name = "#" + name
return name
def get_data_length(data):
"""Returns the length of the data as string with length 3"""
length = str(len(data))
while len(length) < 3:
length = "0" + length
return length
def get_socket_by_name(name):
"""Returns the socket with the name, if none exists return None"""
if len(sockets_names) != 0:
for socket_pair, socket_name in sockets_names.items():
if name == socket_name:
return socket_pair
return None
def get_admins_as_string():
admins_names_lst = []
for admin_socket in admins:
admins_names_lst.append(sockets_names[admin_socket])
return str(admins_names_lst)[1:-1]
def remove_socket(removed_socket):
open_sockets.remove(removed_socket)
if removed_socket in admins:
admins.remove(removed_socket)
del sockets_names[removed_socket]
def handle_new_connection():
for new_connection in rlist:
if new_connection is server_socket:
(new_socket, address) = server_socket.accept()
open_sockets.append(new_socket)
sockets_names[new_socket] = "Anonymous"
if len(admins) == 0:
admins.append(new_socket)
print("New Connection And Admin")
else:
print("New Connection")
def handle_receive_data():
for current_socket in rlist:
if current_socket is not server_socket:
data_length = int(current_socket.recv(3).decode('utf-8'))
data = current_socket.recv(data_length).decode('utf-8')
if data[0] == '/':
handle_commands(current_socket, data[1:])
else:
private_msgs.append((current_socket, "You: " + data))
if current_socket in muted_sockets:
private_msgs.append((current_socket, """"You are muted and so can't send msgs to everyone. You can
ask one of the admins to unmute you in a private msg"""))
else:
public_msgs.append((current_socket, get_name(current_socket) + ": " + data))
def handle_sending_msgs():
for message in public_msgs:
(sender_socket, data) = message
data = get_current_time() + " " + data
for receiver_socket in wlist:
if receiver_socket is not sender_socket:
receiver_socket.send(bytes(get_data_length(data), 'utf8'))
receiver_socket.send(bytes(data, 'utf8'))
if message in public_msgs:
public_msgs.remove(message)
for message in private_msgs:
(receiver_socket, data) = message
data = get_current_time() + " " + data
if receiver_socket in wlist:
receiver_socket.send(get_data_length(data).encode('utf-8'))
receiver_socket.send(data.encode('utf-8'))
if message in private_msgs:
private_msgs.remove(message)
if data.split(' ')[1] == "bye":
remove_socket(receiver_socket)
def handle_commands(current_socket, data):
command = data.split(' ')[0].lower()
data = ' '.join(data.split(' ')[1:])
if command == "exit":
public_msgs.append((current_socket, get_name(current_socket) + " left the chat."))
private_msgs.append((current_socket, "bye"))
print("Connection with " + get_name(current_socket) + " closed.")
elif command == 'rename' or command == 'setname':
if data not in sockets_names.values():
if data.lower() != "you" and data.lower() != "server" and data.lower()[0] != "#":
sockets_names[current_socket] = data
private_msgs.append((current_socket, "Your name has been successfully changed to " + data + "."))
else:
private_msgs.append((current_socket, data + " is not a valid name."))
else:
private_msgs.append((current_socket, "This name is already taken."))
elif command == 'setadmin' or command == "promote":
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
new_admin_socket = get_socket_by_name(data)
admins.append(new_admin_socket)
private_msgs.append((current_socket, data + " has been promoted to admin."))
public_msgs.append((current_socket, get_name(current_socket) + " promoted " + data + " to admin."))
else:
private_msgs.append((current_socket, "You don't have access to this command."))
elif command == 'kick' or command == 'remove':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
kicked_socket = get_socket_by_name(data)
private_msgs.append((current_socket, data + " has been successfully kicked and removed."))
public_msgs.append((current_socket, get_name(current_socket) + " kicked and removed " + data))
private_msgs.append((kicked_socket, get_name(current_socket) + " kicked you."))
private_msgs.append((kicked_socket, "bye"))
elif command == 'mute':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
muted_socket = get_socket_by_name(data)
muted_sockets.append(muted_socket)
private_msgs.append((current_socket, data + " has been successfully muted."))
public_msgs.append((current_socket, get_name(current_socket) + " muted " + data))
private_msgs.append((muted_socket, get_name(current_socket) + " muted you."))
else:
private_msgs.append((current_socket, "You are not an admin and so you have no such permissions."))
elif command == 'unmute':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
unmute_socket = get_socket_by_name(data)
if unmute_socket not in muted_sockets:
private_msgs.append((current_socket, "This user isn't muted."))
else:
muted_sockets.remove(unmute_socket)
private_msgs.append((current_socket, data + " has been successfully unmuted."))
public_msgs.append((current_socket, get_name(current_socket) + " unmuted " + data))
private_msgs.append((unmute_socket, get_name(current_socket) + " unmuted you."))
else:
private_msgs.append((current_socket, "You are not an admin and so you have no such permissions."))
elif command == 'msg' or command == 'message' or command == "prvmsg" or command == "privatemessage":
send_to_name = data.split(' ')[0]
data = ' '.join(data.split(' ')[1:])
if send_to_name not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
send_to_socket = get_socket_by_name(send_to_name)
private_msgs.append(
(current_socket, "You -> " + send_to_name + ": " + data))
private_msgs.append((send_to_socket, get_name(current_socket) + " -> " + send_to_name + ": " + data))
elif command == 'admin' or command == "admins" or command == "adminlist" or command == "adminslist":
private_msgs.append((current_socket, "Admins: " + get_admins_as_string()))
elif command == 'users' or command == "userslist" or command == 'user' or command == "userlist":
private_msgs.append((current_socket, "Users: " + str(sockets_names.values())[1:-1]))
elif command == 'help' or command == '?':
commands = """/rename <name> - change your name.\n/msg <user> <msg> - will send <msg> as a private massage that only <user>
can see.\n/users - returns the names of all the connected users.\n/admins - returns the names of all the connected admins.\n/exit -
will disconnect you.\n\nAdmins' Commends Only:\n/kick <user> - kick the <user> from the server.\n/promote <user> - will ser <user> to
be an admin.\nmute <user> - will no let him send public msgs, only privates.\nunmute <user> - will cancel the mute on this user."""
private_msgs.append((current_socket, "\nCommands:\n" + commands + "\n"))
else:
private_msgs.append((current_socket, command + " is not a valid command."))
def main():
global server_socket, open_sockets, sockets_names, admins, muted_sockets, public_msgs, private_msgs
global rlist, wlist, xlist
server_socket = socket.socket()
try:
server_socket.bind(('0.0.0.0', 2303))
server_socket.listen(5)
open_sockets = []
sockets_names = {}
admins = []
muted_sockets = []
public_msgs = []
private_msgs = []
while True:
rlist, wlist, xlist = select.select([server_socket] + open_sockets, open_sockets, [])
handle_new_connection()
handle_receive_data()
handle_sending_msgs()
finally:
del public_msgs[:]
del private_msgs[:]
public_msgs.append((None, "bye"))
handle_sending_msgs()
server_socket.close()
if __name__ == '__main__':
main()
Here is the solution:
import socket
import select
import datetime
open_sockets=[]
sockets_names= {}
admins = []
muted_sockets = []
public_msgs = []
private_msgs = []
global server_socket
global rlist, wlist, xlist
class Server:
def __init__(self):
server_socket = socket.socket()
try:
server_socket.bind(('0.0.0.0', 2303))
server_socket.listen(5)
while True:
rlist, wlist, xlist = select.select([server_socket] + open_sockets, open_sockets, [])
self.handle_new_connection()
self.handle_receive_data()
self.handle_sending_msgs()
finally:
del public_msgs[:]
del private_msgs[:]
public_msgs.append((None, "bye"))
self.handle_sending_msgs()
server_socket.close()
def get_current_time(self):
"""Returns hh:mm"""
now = datetime.datetime.now()
time = str(now.hour) + ":" + str(now.minute)
return time
def get_name(self,user_socket):
"""Returns the name of the user_socket, if he is an admin he gets # before his name"""
name = sockets_names[user_socket]
if len(admins) != 0:
if user_socket in admins:
name = "#" + name
return name
def get_data_length(self,data):
"""Returns the length of the data as string with length 3"""
length = str(len(data))
while len(length) < 3:
length = "0" + length
return length
def get_socket_by_name(self,name):
"""Returns the socket with the name, if none exists return None"""
if len(sockets_names) != 0:
for socket_pair, socket_name in sockets_names.items():
if name == socket_name:
return socket_pair
return None
def get_admins_as_string(self):
admins_names_lst = []
for admin_socket in admins:
admins_names_lst.append(sockets_names[admin_socket])
return str(admins_names_lst)[1:-1]
def remove_socket(self,removed_socket):
open_sockets.remove(removed_socket)
if removed_socket in admins:
admins.remove(removed_socket)
del sockets_names[removed_socket]
def handle_new_connection(self):
for new_connection in rlist:
if new_connection is server_socket:
(new_socket, address) = server_socket.accept()
open_sockets.append(new_socket)
sockets_names[new_socket] = "Anonymous"
if len(admins) == 0:
admins.append(new_socket)
print("New Connection And Admin")
else:
print("New Connection")
def handle_receive_data(self):
for current_socket in rlist:
if current_socket is not server_socket:
data_length = int(current_socket.recv(3).decode('utf-8'))
data = current_socket.recv(data_length).decode('utf-8')
if data[0] == '/':
self.handle_commands(current_socket, data[1:])
else:
private_msgs.append((current_socket, "You: " + data))
if current_socket in muted_sockets:
private_msgs.append((current_socket, """"You are muted and so can't send msgs to everyone. You can
ask one of the admins to unmute you in a private msg"""))
else:
public_msgs.append((current_socket, self.get_name(current_socket) + ": " + data))
def handle_sending_msgs(self):
for message in public_msgs:
(sender_socket, data) = message
data = self.get_current_time() + " " + data
for receiver_socket in wlist:
if receiver_socket is not sender_socket:
receiver_socket.send(bytes(self.get_data_length(data), 'utf8'))
receiver_socket.send(bytes(data, 'utf8'))
if message in public_msgs:
public_msgs.remove(message)
for message in private_msgs:
(receiver_socket, data) = message
data = self.get_current_time() + " " + data
if receiver_socket in wlist:
receiver_socket.send(self.get_data_length(data).encode('utf-8'))
receiver_socket.send(data.encode('utf-8'))
if message in private_msgs:
private_msgs.remove(message)
if data.split(' ')[1] == "bye":
self.remove_socket(receiver_socket)
def handle_commands(self,current_socket, data):
command = data.split(' ')[0].lower()
data = ' '.join(data.split(' ')[1:])
if command == "exit":
public_msgs.append((current_socket, self.get_name(current_socket) + " left the chat."))
private_msgs.append((current_socket, "bye"))
print("Connection with " + self.get_name(current_socket) + " closed.")
elif command == 'rename' or command == 'setname':
if data not in sockets_names.values():
if data.lower() != "you" and data.lower() != "server" and data.lower()[0] != "#":
sockets_names[current_socket] = data
private_msgs.append((current_socket, "Your name has been successfully changed to " + data + "."))
else:
private_msgs.append((current_socket, data + " is not a valid name."))
else:
private_msgs.append((current_socket, "This name is already taken."))
elif command == 'setadmin' or command == "promote":
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
new_admin_socket = self.get_socket_by_name(data)
admins.append(new_admin_socket)
private_msgs.append((current_socket, data + " has been promoted to admin."))
public_msgs.append((current_socket, self.get_name(current_socket) + " promoted " + data + " to admin."))
else:
private_msgs.append((current_socket, "You don't have access to this command."))
elif command == 'kick' or command == 'remove':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
kicked_socket = self.get_socket_by_name(data)
private_msgs.append((current_socket, data + " has been successfully kicked and removed."))
public_msgs.append((current_socket, self.get_name(current_socket) + " kicked and removed " + data))
private_msgs.append((kicked_socket, self.get_name(current_socket) + " kicked you."))
private_msgs.append((kicked_socket, "bye"))
elif command == 'mute':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
muted_socket = self.get_socket_by_name(data)
muted_sockets.append(muted_socket)
private_msgs.append((current_socket, data + " has been successfully muted."))
public_msgs.append((current_socket, self.get_name(current_socket) + " muted " + data))
private_msgs.append((muted_socket, self.get_name(current_socket) + " muted you."))
else:
private_msgs.append((current_socket, "You are not an admin and so you have no such permissions."))
elif command == 'unmute':
if current_socket in admins:
if data not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
unmute_socket = self.get_socket_by_name(data)
if unmute_socket not in muted_sockets:
private_msgs.append((current_socket, "This user isn't muted."))
else:
muted_sockets.remove(unmute_socket)
private_msgs.append((current_socket, data + " has been successfully unmuted."))
public_msgs.append((current_socket, self.get_name(current_socket) + " unmuted " + data))
private_msgs.append((unmute_socket, self.get_name(current_socket) + " unmuted you."))
else:
private_msgs.append((current_socket, "You are not an admin and so you have no such permissions."))
elif command == 'msg' or command == 'message' or command == "prvmsg" or command == "privatemessage":
send_to_name = data.split(' ')[0]
data = ' '.join(data.split(' ')[1:])
if send_to_name not in sockets_names.values():
private_msgs.append((current_socket, "This name doesn't exist in this server."))
else:
send_to_socket = self.get_socket_by_name(send_to_name)
private_msgs.append(
(current_socket, "You -> " + send_to_name + ": " + data))
private_msgs.append((send_to_socket, self.get_name(current_socket) + " -> " + send_to_name + ": " + data))
elif command == 'admin' or command == "admins" or command == "adminlist" or command == "adminslist":
private_msgs.append((current_socket, "Admins: " + self.get_admins_as_string()))
elif command == 'users' or command == "userslist" or command == 'user' or command == "userlist":
private_msgs.append((current_socket, "Users: " + str(sockets_names.values())[1:-1]))
elif command == 'help' or command == '?':
commands = """/rename <name> - change your name.\n/msg <user> <msg> - will send <msg> as a private massage that only <user>
can see.\n/users - returns the names of all the connected users.\n/admins - returns the names of all the connected admins.\n/exit -
will disconnect you.\n\nAdmins' Commends Only:\n/kick <user> - kick the <user> from the server.\n/promote <user> - will ser <user> to
be an admin.\nmute <user> - will no let him send public msgs, only privates.\nunmute <user> - will cancel the mute on this user."""
private_msgs.append((current_socket, "\nCommands:\n" + commands + "\n"))
else:
private_msgs.append((current_socket, command + " is not a valid command."))
Just call the class:
ServerClass()
There is something wrong with my python code. I am a beginner in python.
def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""
if len(acc_id) == 15:
pp_acc_id = "0315" + acc_id
elif acc_id.length() == 13:
pp_acc_id = "0213" + acc_id
elif acc_id.length() == 10:
pp_acc_id = "01130066" + acc_id.substring(1)
else:
return "null"
if not amount:
pp_amount = format("54%02d%s", amount.length(), amount)
pp_str = "00020101021129370016A000000677010111"
+ pp_acc_id
+ "5303764"
+ pp_amount
+ "5802TH"
+ "6304"
pp_chksum = crc16.checksum(pp_str);
pp_str += pp_chksum;
return pp_str
Error says it's SyntaxError: 'return' outside function. What's the problem with this code. By the way i convert the code from java to python. Is that everything okey in my code? I edit my code here but still there are some error
You need to properly indent your code. From your question I'm guessing this would resolve your issue:
import crc16
def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""
if len(acc_id) == 15:
pp_acc_id = "0315" + acc_id
elif acc_id.length() == 13:
pp_acc_id = "0213" + acc_id
elif acc_id.length() == 10:
pp_acc_id = "01130066" + acc_id.substring(1)
else:
return "null"
if not amount:
pp_amount = format("54%02d%s", amount.length(), amount)
pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" + pp_amount + "5802TH" + "6304"
pp_chksum = crc16.checksum(pp_str);
pp_str += pp_chksum;
return pp_str
Python is what is called "whitespace-sensitive": it matters how stuff is indented. For example, it expects the contents inside an if-clause to be indented below that statement:
if True or False:
execute_this_function()
This will not work:
if True or False:
execute_this_function()
The same applies to return statements: they should be inside the function they apply to, i.e. that you are returning from:
def my_method():
return True
Again, this will not work and raise the error you are getting:
def my_method():
return True
Thus, the solution is to make sure your returns are indented correctly. Of course, the same applies to the rest of the code!
Edit Based on the modification of your OP, this is the indentation you require; I also fixed the .length() you copied over from Java, it seems:
def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""
if len(acc_id) == 15:
pp_acc_id = "0315" + acc_id
elif len(acc_id) == 13:
pp_acc_id = "0213" + acc_id
elif len(acc_id) == 10:
pp_acc_id = "01130066" + acc_id.substring(1)
else:
return "null"
if not amount:
pp_amount = format("54%02d%s", len(amount), amount)
pp_str = "00020101021129370016A000000677010111"
+ pp_acc_id
+ "5303764"
+ pp_amount
+ "5802TH"
+ "6304"
pp_chksum = crc16.checksum(pp_str);
pp_str += pp_chksum;
return pp_str
from informedSearch import *
from search import *
class EightPuzzleProblem(InformedProblemState):
"""
Inherited from the InformedProblemState class. To solve
the eight puzzle problem.
"""
def __init__(self, myList, list = {}, operator = None):
self.myList = list
self.operator = operator
def __str__(self):
## Method returns a string representation of the state.
result = ""
if self.operator != None:
result += "Operator: " + self.operator + ""
result += " " + ' '.join(self.myList[0:3]) + "\n"
result += " " + ' '.join(self.myList[3:6]) + "\n"
result += " " + ' '.join(self.myList[6:9]) + "\n"
return result
def illegal(self):
## Tests whether the state is illegal.
if self.myList < 0 or self.myList > 9: return 1
return 0
def equals(self, state):
## Method to determine whether the state instance
## and the given state are equal.
return ' '.join(self.myList) == ' '.join(state.myList)
## The five methods below perform the tree traversing
def move(self, value):
nList = self.myList[:] # make copy of the current state
position = nList.index('P') # P acts as the key
val = nList.pop(position + value)
nList.insert(position + value, 'P')
nList.pop(position)
nList.insert(position, val)
return nList
def moveleft(self):
n = self.move(-1)
return EightPuzzleProblem(n, "moveleft")
def moveright(self):
n = self.move(1)
return EightPuzzleProblem(n, "moveright")
def moveup(self):
n = self.move(-3)
return EightPuzzleProblem(n, "moveup")
def movedown(self):
n = self.move(+3)
return EightPuzzleProblem(n, "movedown")
def operatorNames(self):
return ["moveleft", "moveright", "moveup", "movedown"]
def enqueue(self):
q = []
if (self.myList.index('P') != 0) and (self.myList.index('P') != 3) and (self.myList.index('P') != 6):
q.append(self.moveleft())
if (self.myList.index('P') != 2) and (self.myList.index('P') != 5) and (self.myList.index('P') != 8):
q.append(self.moveright())
if self.myList.index('P') >= 3:
q.append(self.moveup())
if self.myList.index('P') >= 5:
q.append(self.movedown())
def applyOperators(self):
return [self.moveleft(), self.moveright(), self.moveup(), self.movedown()]
def heuristic():
counter = 0
for i in range(len(self.myList)):
if ((self.myList[i] != goal.myList[i]) and self.myList[i] != 'P'):
## Position of current:
current = goal.myList.index(self.myList[i])
if current < 3: goalRow = 0
elif current < 6: goalRow = 1
else: goalRow = 2
if i < 3: initRow = 0
elif i < 6: initRow = 1
else: startRow = 2
initColumn = i % 3
goalColumn = current % 3
counter += (abs(goalColumn - initColumn) + abs(goalRow - initRow))
return counter
#Uncomment to test the starting states:
init = ['1','3','P','8','2','4','7','6','5'] #A
#init = ['1','3','4','8','6','2','P','7','5'] #B
#init = ['P','1','3','4','2','5','8','7','6'] #C
#init = ['7','1','2','8','P','3','6','5','4'] #D
#init = ['8','1','2','7','P','4','6','5','3'] #E
#init = ['2','6','3','4','P','5','1','8','7'] #F
#init = ['7','3','4','6','1','5','8','P','2'] #G
#init = ['7','4','5','6','P','3','8','1','2'] #H
goal = ['1','2','3','8','P','4','7','6','5'] #goal state
InformedSearch(EightPuzzleProblem(init), EightPuzzleProblem(goal))
I run it and it shows error
line 34, in __str__ result += " " + ' '.join(self.myList[0:3]) + "\n"
TypeError: unhashable type: 'slice'
Any Ideas?
You're setting the "list" to a dictionary as a default value: list = {} in:
def __init__(self, myList, list = {}, operator = None):
and then assigning it to myList with:
self.myList = list
A dictionary cannot be sliced like a list. So when you try to slice it:
self.myList[0:3]
it fails.
This is the basic.py file for a programming language I am making. At the moment it is throwing an error.
from sys import *
tokens = []
def open_file(filename):
data = open(filename, "r").read()
data += "<EOF>"
return data
def lex(filecontents):
tok = ""
state = 0
isexpr = 0
string = ""
expr = ""
n = ""
filecontents = list(filecontents)
for char in filecontents:
tok += char
if tok == " ":
if state == 0:
tok = ""
else:
tok = " "
elif tok == "\n" or tok == "<EOF>":
if expr != "" and isexpr == 1:
#print(expr + "EXPR")
tokens.append("EXPR:" + expr)
expr = ""
elif expr != "" and isexpr == 0:
#print(expr + "NUM")
tokens.append("NUM:" + expr)
expr = ""
tok = ""
elif tok.lower() == "print":
tokens.append("PRINT")
tok = ""
elif tok.isnumeric():
expr += tok
tok = ""
elif tok == "+":
isexpr = 1
expr += tok
tok = ""
elif tok == "\"":
if state == 0:
state = 1
elif state == 1:
tokens.append("STRING:" + string + "\"")
string = ""
state = 0
tok = ""
elif state == 1:
string += tok
tok = ""
print(tokens)
return tokens
def parse(toks):
i = 0
while(i < len(toks)):
if toks[i] + " " + toks[i+1][0:6] == "PRINT STRING" or toks[i] + " " + toks[i+1][0:3] == "PRINT NUM" or toks[i] + " " + toks[i+1][0:4] == "PRINT EXPR":
if toks[i+1][0:6] == "STRING":
print(toks[i+1][7:])
elif toks[i+1][0:3] == "NUM":
print(toks[i+1][4:])
elif toks[i+1][0:4] == "EXPR":
print(toks[i+1][5:])
i+=2
def run():
data = open_file(argv[1])
toks = lex(data)
parse(toks)
run()
here is the test.vil file(my programming language is called villar) that I am passing data through:
STRING "HELLO WORLD"
string "Hey world!"
17 + 3
As a result, I get an IndexError: List index out of range in line 62.
Can you anyone help me help here? I'd love advice on how to improve it to if its allowed here.
You've got the line:
while(i < len(toks)):
in the parse function. However, within this while loop, you access toks[i+1] element, which'll be out of bounds on the final iteration of the while loop (as i == len(toks)-1 and i+1 == len(toks) which is out of bounds and throwing an error). You need to change that above line to:
while(i < len(toks)-1):
so that on the final iteration i == len(toks) - 2 and i+1 == len(toks) - 1 which are both in bounds.