def analyse(self): if not self.authenticated: raise NotAuthenticatedError() if self.todo == "upload": with open(path,"r") as f: data = f.read() network_info = self.dbInterface.getNetworkInfo(self.__network) c, d, f = fileManager.exploder(data, network_info) for ip in list(d.keys()): tosend = { "network_id": self.__network, "password": self.__networkPassword, "todo": "write_file", "password": self.__networkPassword, "data": d[ip] } client.send(ip, tosend) if self.todo == "retrieve": name, hash, nodecode = self.code.split(":") #51152b82-7d5e-42bc-a43e-9897fc5e2eb9:700071f878c6ea354072564be2131b0c:A0-A1-A2-A3-A4-A5-A6-A7-A8 nodeislist = nodecode.split("-") iplist = self.dbInterface.getInfoFromCode(nodelist, self.__network) tosend = { "network_id": self.__network, "password": self.__networkPassword, "todo": "read_file", "filename": name }
def on_frame(self, controller): # Get the most recent frame and report some basic information frame = controller.frame() for gesture in frame.gestures(): if gesture.type == Leap.Gesture.TYPE_SWIPE: swipe = SwipeGesture(gesture) position = swipe.position ''' print "Swipe id: %d, state: %s, position: %s, direction: %s, speed: %f" % ( gesture.id, self.state_string(gesture.state), swipe.position, swipe.direction, swipe.speed) ''' globalvar.swipetimes += 1 if globalvar.swipetimes > 5 and globalvar.started == False: # send data position = swipe.position direction = swipe.direction data = { 'type': gesture.type, 'speed': swipe.speed, 'position': (position.x, position.y, position.z), 'direction': (direction.x, direction.y, direction.z), } client.send(client.swipe_address, data) globalvar.started = True if not (frame.hands.empty and frame.gestures().empty): print ""
def on_frame(self, controller): # Get the most recent frame and report some basic information frame = controller.frame() if len(frame.hands): # Get the first hand left_hand = frame.hands[0] right_hand = frame.hands[1] # Check if the hand has any fingers left_fingers = len(left_hand.fingers) right_fingers = len(right_hand.fingers) def _hand_type(finger_count): # 0:拳头,2:剪刀, 5:布 res = 0 if finger_count == 0: res = 0 elif finger_count >= 1 and finger_count <= 3: res = 2 elif finger_count >= 4: res = 5 return res # move and not grasp data = { 'type': 201, 'left': left_fingers,#_hand_type(left_fingers), 'right': right_fingers,#_hand_type(right_fingers), } client.send(client.hands_address, data)
def report(self, event): ip_split = self.ip_local.split(".") ip_split[3] = str(int(ip_split[3]) ^ config.IP_RAND) ip_anonymous = ".".join(ip_split) # Generate JSON s = json.dumps( { "Type": "Stream", "Event": event, "Time": self.latest_packet_time, "UserAgent": self.http_user_agent, "LocalIP": ip_anonymous, "ForeignIP": self.ip_foreign, "LocalPorts": ",".join(str(l) for l in self.local_ports), "ForeignPorts": ",".join(str(l) for l in self.foreign_ports), "Counts": { "Total": self.tcp_packet_count, "Incoming": self.tcp_in_pkt_count, "Outgoing": self.tcp_out_pkt_count, }, "MaxSizes": {"Incoming": self.tcp_max_in_pkt_size, "Outgoing": self.tcp_max_out_pkt_size}, }, sort_keys=True, ) # print s client.send(s) return s
def testSendDataMultipleClients(self): global server mClients = self.createEightClients() counter = 0 for client in mClients: counter += 1 client.send("server_recieve", "test" + str(counter)) self.assertTrue(len(server.events) == 8)
def on_frame(self, controller): # Get the most recent frame and report some basic information frame = controller.frame() if not frame.hands.empty: # Get the first hand hand = frame.hands[0] # Check if the hand has any fingers fingers = hand.fingers count = len(fingers) halm_pos = hand.palm_position if fingers.empty: if self.grasping == False: # a grasp event data = { 'type': 102, 'count': count, 'position': (halm_pos.x, halm_pos.y, halm_pos.z) } client.send(client.grasp_address, data) self.grasping = True else: # grasping and move data = { 'type': 103, 'count': count, 'position': (halm_pos.x, halm_pos.y, halm_pos.z) } client.send(client.grasp_address, data) else: # only change to True while count > 1; when count == 1, do not change; # and when count is 0, it will not run into here if self.grasping == True and count > 1: # a loosen action data = { 'type': 104, 'count': count, 'position': (halm_pos.x, halm_pos.y, halm_pos.z) } client.send(client.grasp_address, data) self.grasping = False elif self.grasping == True and count == 1: # grasping and move data = { 'type': 103, 'count': count, 'position': (halm_pos.x, halm_pos.y, halm_pos.z) } client.send(client.grasp_address, data) elif self.grasping == False: # move and not grasp data = { 'type': 101, 'count': count, 'position': (halm_pos.x, halm_pos.y, halm_pos.z) } client.send(client.grasp_address, data)
def on_frame(self, controller): # Get the most recent frame and report some basic information frame = controller.frame() print "Frame id: %d, timestamp: %d, hands: %d, fingers: %d, tools: %d, gestures: %d" % ( frame.id, frame.timestamp, len(frame.hands), len(frame.fingers), len(frame.tools), len(frame.gestures())) if not frame.hands.empty: # Get the first hand hand = frame.hands[0] # Check if the hand has any fingers fingers = hand.fingers if not fingers.empty: # Calculate the hand's average finger tip position ''' avg_pos = Leap.Vector() for finger in fingers: avg_pos += finger.tip_position avg_pos /= len(fingers) print "Hand has %d fingers, average finger tip position: %s" % ( len(fingers), avg_pos) ''' halm_pos = hand.palm_position data = { 'type': 101, 'state': len(fingers), 'position': (halm_pos.x, halm_pos.y, halm_pos.z) } client.send(client.finger_address, data) ''' # Get the hand's sphere radius and palm position print "Hand sphere radius: %f mm, palm position: %s" % ( hand.sphere_radius, hand.palm_position) # Get the hand's normal vector and direction normal = hand.palm_normal direction = hand.direction # Calculate the hand's pitch, roll, and yaw angles print "Hand pitch: %f degrees, roll: %f degrees, yaw: %f degrees" % ( direction.pitch * Leap.RAD_TO_DEG, normal.roll * Leap.RAD_TO_DEG, direction.yaw * Leap.RAD_TO_DEG) ''' if not (frame.hands.empty and frame.gestures().empty): print ""
def list_files(): data = { "method": "LIST_FILES", "type": "REQUEST" } try: response = send(TRACKER, TRACKER_PORT, data) print response except: msg = 'Tracker {}:{} is unreachable'.format(TRACKER, TRACKER_PORT) logging.error(msg)
def on_frame(self, controller): # Get the most recent frame and report some basic information frame = controller.frame() current_time = time.time() if len(frame.hands) >= 2 and globalvar.restart == False and (current_time - self.last_time) > 2: hand = frame.hands[0] # send data position = hand.palm_position data = { 'type': 110, 'state': 1, 'position': (position.x, position.y, position.z) } index = 0 while index < 20: index += 1 client.send(client.hands_address, data) # set restart globalvar.restart = True
def ping_request(host, port): data = { "method": "PING", "type": "REQUEST" } try: response = send(host, port, data) if response["method"] == "PING" and response["type"] == "RESPONSE": return True except: return False
def _login(self, body): url = '%s/oauth2/token' % self.context.url client = self.context.newClient() client.method = "POST" client.url = url client.setContentType('application/json') client.setKiiHeaders(self.context, False) (code, body) = client.send(body) if code != 200: raise CloudException(code, body) self.context.access_token = body['access_token'] id = body['id'] return KiiUser(id)
def report(self, event): ip_split = self.ip_local.split(".") ip_split[3] = str(int(ip_split[3]) ^ config.IP_RAND) ip_anonymous = ".".join(ip_split) # Generate JSON s = json.dumps( { "Type": "Peer", "Event": event, "Time": self.latest_packet_time, "LocalIP": ip_anonymous, "TcpStats": { "ActiveStreamCount": len(self.tcp_streams), # 'ActiveStreams': ','.join(str(l) for l in self.tcp_streams), "OpenStreamCount": len(self.tcp_stream_list), "Counts": { "Total": self.tcp_packet_count, "Incoming": self.tcp_in_pkt_count, "Outgoing": self.tcp_out_pkt_count, }, "MaxSizes": {"Incoming": self.tcp_max_in_pkt_size, "Outgoing": self.tcp_max_out_pkt_size}, }, "UdpStats": { # 'ActiveStreams': ','.join(str(l) for l in self.udp_streams), "ActiveStreamCount": len(self.udp_streams), "Counts": { "Total": self.udp_packet_count, "Incoming": self.udp_in_pkt_count, "Outgoing": self.udp_out_pkt_count, }, "MaxSizes": {"Incoming": self.udp_max_in_pkt_size, "Outgoing": self.udp_max_out_pkt_size}, }, }, sort_keys=True, ) # print s client.send(s) return s
def main(): pinMode(0, IN) while True: client.send("quit") value1 = customRead(0) print value1 client.send("water: " + value1) value2 = customRead(1) print value2 client.send("temp: " + value2) value3 = customRead(2) print value3 client.send("humidity: " + value3) sleep(0.5)
def report(self, event): anon_peer_list = list() for p in self.peer_list.keys(): psplit = p.split(".") psplit[3] = str(int(psplit[3]) ^ config.IP_RAND) anon_peer_list.append(".".join(psplit)) # Generate JSON s = json.dumps( { "Type": "Router", "Event": event, "Time": self.latest_packet_time, "Peers": ",".join(anon_peer_list), "PeerCount": len(self.peer_list), "ActivePeers": len(self.active_peers), "TcpStats": { "Counts": { "Total": self.tcp_packet_count, "Incoming": self.tcp_in_pkt_count, "Outgoing": self.tcp_out_pkt_count, }, "MaxSizes": {"Incoming": self.tcp_max_in_pkt_size, "Outgoing": self.tcp_max_out_pkt_size}, }, "UdpStats": { "Counts": { "Total": self.udp_packet_count, "Incoming": self.udp_in_pkt_count, "Outgoing": self.udp_out_pkt_count, }, "MaxSizes": {"Incoming": self.udp_max_in_pkt_size, "Outgoing": self.udp_max_out_pkt_size}, }, }, sort_keys=True, ) # print(s) client.send(s) return s
def update(timer): global is_button_down, is_open, ticks_until_locked, is_request_pending button_state = BUTTON.value() if button_state == PRESSED: # button is currently down if not is_button_down: print('Button Pressed') # button wasn't down: change event # send the button signal to the server is_button_down = True client.send('button') # turn on the indicator (momentarily) # while the button is down INDICATOR.high() else: # button is currently up if is_button_down: print('Button Released') # button was down: change event is_button_down = False is_request_pending = False INDICATOR.low() if is_open: LOCK.high() # Lock is open, the timer will close it if ticks_until_locked == 0: is_open = False LOCK.low() # lock the cabinet else: ticks_until_locked -= 1 if is_request_pending: INDICATOR.high()
def test_addEvent01(self): '''正向添加''' # url = 'http://139.199.132.220:9000/event/api/add_event/' title = 'sy2' address = 'bejing' add_hour = datetime.datetime.now() + datetime.timedelta(hours=1) time = add_hour.strftime('%Y-%m-%d %H:%M:%S') sign = self.client.get( 'token' ) + 'para=address=' + address + '&time=' + time + '&title=' + title sign = hashlib.md5(sign.encode(encoding='UTF-8')).hexdigest() data = {'title': title, 'address': address, 'time': time, 'sign': sign} self.client.headers['Cookie'] = 'token=%s;uid=%s' % ( self.client.get('token'), self.client.get('uid')) client = self.client client.data = data client.send() client.equal(client.status_code, 200) client.less_then(client.times, 200) client.equal(client.json.get('error_code'), 0) client.db_execute("delete from api_event where title = 'sy2'")
def client_thread(client, username): print("Running client_thread") client.send(bytes(room_name, "utf-8")) for message in messages: print(message) client.send(bytes(message, "utf-8")) print("Type of username: "******"", username.decode("utf-8") + " has entered the chat \n") while True: try: message = client.recv(2000).decode("utf-8") print(message) print("message received") if message: if message[0:3] == "***": print("command received") action_handler(message[3:]) elif username not in mute_list: print("broadcasting message") broadcast_message(username.decode("utf-8"), message) else: print("poo poo") else: print("Client closed:(") client.close() remove(username) except: continue
def action_query(): if request.method == 'POST': print request.form para = ("loc1", "loc2", "date", "catalog", "transfer") command = {} for item in para: value = request.form.get(item, "") if value: command[item] = value else: return "" if request.form["transfer"] == u"true": command["type"] = "query_transfer" raw_result = client.send(encode_query_transfer(command)) raw_result = unicode(raw_result, "utf-8") result = decode_query_transfer(raw_result) else: command["type"] = "query_ticket" raw_result = client.send(encode_query_ticket(command)) raw_result = unicode(raw_result, "utf-8") result = decode_query_ticket(raw_result) return render_template('query_result.html', data=result) else: return ""
def handle_my_custom_event(json): global currentuser x = json[u'x'] y = json[u'y'] theta = json[u'theta'] if (json[u'user'] == currentuser): print x,y,theta client.send("SetRobotSpeed Vx "+str(int(x))) client.send("SetRobotSpeed Vy "+str(int(y))) client.send("SetRobotSpeed Omega "+str(int(theta)))
def action_query_user(): current_user = session.get('userid', '') userid = request.args.get("id", "") if not userid: return "" if get_privilege(current_user) != 2 and current_user != userid: return u"权限不足" command = {"type": "query_profile", "id": userid} raw_result = client.send(encode_query_profile(command)) #print encode_query_profile(command) raw_result = unicode(raw_result, "utf-8") result = decode_query_profile(raw_result) #print result if not result["success"]: return u"未找到该用户" return render_template('query_user_result.html', id=userid, **result)
def mainloop(self): # Solution 1: 因两传感器之间间隔很短,故不考虑“无->m0->无->m1->无”和"无->m1->无->m0->无"的情况 state = [0, 0] # 空闲状态 enter = [False, False] # 在空闲状态,谁先被遮住 leave = [False, False] # 在繁忙状态,谁先被释放 while True: # 状态转移 nxstate = [myio.get(self.monitor[0]), myio.get(self.monitor[1])] # 次态 if state == [0, 0]: enter = [nxstate[0] == 1, nxstate[1] == 1] elif state == [0, 1]: leave[1] = (not leave[0] and nxstate[1] == 0) elif state == [1, 0]: leave[0] = (not leave[1] and nxstate[0] == 0) elif state == [1, 1]: leave = [nxstate[0] == 0, nxstate[1] == 0] print "st =", state, "nx =", nxstate, "enter =", enter, "leave =", leave state = nxstate flag = False # reset flag if enter != [False, False]: if enter == [True, False]: # 0首先被遮住 client.send(self.clientcode+'+') flag = True print "----->" elif enter == [False, True]: # 1首先被遮住 client.send(self.clientcode+'-') flag = True print "<-----" elif enter == [True, True]: # 同时在空闲状态被遮住 if leave == [True, False]: # 0首先被释放 client.send(self.clientcode+'+') flag = True print "----->" elif leave == [False, True]: # 1首先被释放 client.send(self.clientcode+'-') flag = True print "----->" if flag: enter = [False, False] leave = [False, False] # 其余情况,无法判断方向,直接忽略 sleep(0.1)
def action_query_order(): para = ("date", "id", "catalog") command = {} for item in para: value = request.args.get(item, "") if value: command[item] = value else: return "" current_user = session.get('userid', '') if current_user != request.args["id"] and get_privilege(current_user) != 2: return u"权限不足" command["type"] = "query_order" raw_result = client.send(encode_query_order(command)) raw_result = unicode(raw_result, "utf-8") result = decode_query_ticket(raw_result) return render_template('query_order_result.html', userid=request.args["id"], data=result)
def signup(self, username, password, **extFields): url = '%s/apps/%s/users' % (self.context.url, self.context.app_id) body = {'password': password} if extFields != None: for k, v in extFields.items(): body[k] = v if username != None: body['loginName'] = username client = self.context.newClient() client.method = "POST" client.url = url client.setContentType('application/json') client.setKiiHeaders(self.context, False) (code, body) = client.send(body) if code != 201: raise CloudException(code, body) id = body['userID'] return KiiUser(userID=id, loginName=username, **extFields)
def action_modify_profile(): current_user = session.get('userid', '') if request.method == 'POST': para = ("userid", "name", "password", "password2", "email", "phone") for item in para: if not request.form.has_key(item): return "0" userid = request.form['userid'] if (request.form['password'] != request.form['password2']): return "0" if request.form['password']: result = client.modify_profile(request.form['userid'], request.form['name'], request.form['password'], request.form['email'], request.form['phone']) else: result = client.modify_profile2(request.form['userid'], request.form['name'], request.form['email'], request.form['phone']) if result == "0\n": return "0" privilege_input = request.form.get("privilege", "false") if (privilege_input == "true") != (get_privilege(userid) == 2): command = { "type": "modify_privilege", "id1": current_user, "id2": userid, "privilege": { "true": 2, "false": 1 }[privilege_input] } raw_result = client.send(encode_modify_privilege(command)) raw_result = unicode(raw_result, "utf-8") result = decode_modify_privilege(raw_result) if (not result["success"]): return "0" return "1" return "0"
def signup(self, username, password, **extFields): url = '%s/apps/%s/users' % (self.context.url, self.context.app_id) body = { 'password' : password } if extFields != None: for k, v in extFields.items(): body[k] = v if username != None: body['loginName'] = username client = self.context.newClient() client.method = "POST" client.url = url client.setContentType('application/json') client.setKiiHeaders(self.context, False) (code, body) = client.send(body) if code != 201: raise CloudException(code, body) id = body['userID'] return KiiUser(userID=id, loginName=username, **extFields)
def action_sale_train(): current_user = session.get('userid', '') if get_privilege(current_user) != 2: return render_template("warning.html", admin=get_privilege(current_user), message="权限不足", user=current_user) train_id = request.args.get("train_id", "") if not train_id: return render_template("warning.html", admin=get_privilege(current_user), message="缺少参数", user=current_user) command = {"type": "sale_train", "train_id": train_id} raw_result = client.send(encode_sale_train(command)) raw_result = unicode(raw_result, "utf-8") result = decode_sale_train(raw_result) if (result.get("success", False)): return u"发售成功" else: return u"发售失败"
def register_as_owner(file_name, part_completed=None): data = {'method': 'REGISTER_AS_OWNER', 'type': 'REQUEST', 'file': file_name, 'part_number': part_completed, 'IP': MY_IP, 'port_number': UPLOADER_PORT_NUMBER } # registering the file when starting the client if part_completed is None: f = open('files/' + file_name) md5_code = md5.new(f.read()).digest() data['MD5'] = base64.b64encode(md5_code) data['part_number'] = [0, 1, 2] # registering the file after downloading one part else: data['part_number'] = [part_completed] response = send(TRACKER, TRACKER_PORT, data) logging.info('Response: {}'.format(response))
def _get_tracker(filename): #from the protocol data = { "method": "GET_TRACKER", "type": "REQUEST", "file": filename } #sends the request try: response = send(TRACKER, TRACKER_PORT, data) except: return "Tracker is unreachable" #if the tracker does not have the file, raise an Exception if "error" in response: raise ValueError("File not available at tracker") #returns the .tracker info return { "filename": filename, "MD5": base64.b64decode(response["MD5"]), "pieces": response["pieces_list"] }
def _download_file_part(host, port, filename, part): request = { "method": "DOWNLOAD_FILE", "type": "REQUEST", "file": filename, "part_number": part } try: #logs the action print "Downloading file {} from host {}, at port {}. Request is: {}".format( filename, host, port, request) #sends the request to the host and gets the response response = send(host, port, request) except Exception as e: print e return "host is unreachable" #saves the file part with open('{}.part{}'.format(filename, part), 'wb') as f: f.write(response["file"]) #sends message to the tracker saying that we've got the part we just downloaded register_as_owner(filename, part_completed=part)
diff = [0] * 3 for i in range(1000): sum1 += adc.read_adc(0, gain=GAIN) sum2 += adc.read_adc(1, gain=GAIN) sum3 += adc.read_adc(2, gain=GAIN) diff[0] = sum1 / 1000 diff[1] = sum2 / 1000 diff[2] = sum3 / 1000 # Connecting to the server ip = "138.197.235.123" print("Connecting to " + ip) client = socket.socket() client.connect((ip, 80)) print("Pinging server:") client.send("ping".encode()) print("Server says: " + client.recv(1024).decode()) # Main loop. while True: # Read all the ADC channel values in a list. values = [0] * 3 for i in range(3): # Read the specified ADC channel using the previously set gain value. values[i] = adc.read_adc(i, gain=GAIN) - diff[i] # Note you can also pass in an optional data_rate parameter that controls # the ADC conversion time (in samples/second). Each chip has a different # set of allowed data rate values, see datasheet Table 9 config register # DR bit values. # values[i] = adc.read_adc(i, gain=GAIN, data_rate=128) # Each value will be a 12 or 16 bit signed integer value depending on the
theOdom.twist.twist.linear.x = Vx theOdom.twist.twist.linear.y = Vy theOdom.twist.twist.angular.z = Wz # theStr = "%s \n Odom x:%f y:%f th:%f | \n %s | Vx:%f Vy:%f Wz:%f \n " % ( current_time , theOdom.pose.pose.position.x , theOdom.pose.pose.position.y ,th , theOdom.child_frame_id , theOdom.twist.twist.linear.x , theOdom.twist.twist.linear.y , theOdom.twist.twist.angular.z) # rospy.loginfo(theStr) pub.publish(theOdom) #BLOCK II: send velocity to the base with PID calibration if isVelocityValid() == True: # client.send("RobotSpeedSet Vx " + str(vToBase('Vx',global_vel.linear.x))) # client.send("RobotSpeedSet Vy " + str(vToBase('Vy',global_vel.linear.y))) # client.send("RobotSpeedSet Omega " + str(vToBase('Vz',global_vel.angular.z))) rospy.loginfo("the base number is" + str(global_vel.linear.x)) client.send("SetRobotSpeed Vx " + str(global_vel.linear.x)) client.send("SetRobotSpeed Vy " + str(global_vel.linear.y)) client.send("SetRobotSpeed Omega " + str(global_vel.angular.z)) client.send("EnableSystem") # judge = False else: # judge = True # rospy.loginfo(rospy.get_caller_id() + "\n Set Vx:%f Vy:%f Wz:%f", global_vel.linear.x, global_vel.linear.y, global_vel.angular.z) timer = (timer + 1) % 6 # if(timer == 1): # a = os.system('clear') rate.sleep() # except: # print("socket timeout check if the wifi is live and the UDP link is ok")
router_rep.start() peer_rep.start() stream_rep.start() while True: # Check if input exists, wait up to timeout_s seconds rlist, wlist, xlist = select.select([sys.stdin], [], [], config.INPUT_TIMEOUT_S) if len(rlist) == 0: sys.exit('Error: Input Timeout: ' + str(datetime.datetime.now())) # Get and parse input line = sys.stdin.readline() start_time = datetime.datetime.now() while len(line) < 1: if (datetime.datetime.now() - start_time).seconds > config.INPUT_TIMEOUT_S: client.send('Input Timeout ' + str(datetime.datetime.now())) sys.exit('Error: Input Timeout ' + str(datetime.datetime.now())) line = sys.stdin.readline() ret = line_parser.parse(line) protocol = ret[0] # Skip bad lines if protocol == '': continue packet = ret[1] # Skip local -> local connections # print 'Protocol: ', protocol # if re.match(re_local_ip, packet.ip_source) and re.match(re_local_ip, packet.ip_dest): if config.localIP(packet.ip_source) and config.localIP(packet.ip_dest):
from client import c, send from .basic import eqbal from .state import s # cleric battlerage battlerage_aliases = [ ( "^at(?: (.+))?$", "angel torment t/[]", lambda matches: send("angel torment {matches[0] or '&tar'}"), ), ( "^cr(?: (.+))?$", "crack t/[]", lambda matches: send("crack {matches[0] or '&tar'}"), ), ( "^deso(?: (.+))?$", "perform rite of desolation on t/[]", lambda matches: send( "perform rite of desolation on {matches[0] or '&tar'}"), ), ( "^ham(?: (.+))?$", "hammer t/[]", lambda matches: send("hammer {matches[0] or '&tar'}"), ), ] c.add_aliases("ab_battlerage", battlerage_aliases) """
import client from template import Template if __name__ == '__main__': payload = Template().parse() client.send(payload)
from client import c, echo, send from ..basic import eqbal from ..state import s artificing_aliases = [ ( "^gcreate$", "golem create egg pentagon cube cylinder torus polyhedron disc spiral", lambda matches: send( f"stand;golem create egg pentagon cube cylinder torus polyhedron disc spiral" ), ), ( "^club(?: (.+))?$", "golem club []/t (egg) - dmg", lambda matches: send(f"stand;golem club {matches[0] or s.target}"), ), ( "^smasha(?: (.+))?$", "golem smash []/t arms (pentagon) - break arm", lambda matches: send(f"stand;golem smash {matches[0] or s.target} arms" ), ), ( "^smashl(?: (.+))?$", "golem smash []/t legs (pentagon) - break leg", lambda matches: send(f"stand;golem smash {matches[0] or s.target} legs" ), ), (
def eat_herb(herb, mud=None, matches=None): send(f"outr {herb};eat {herb}")
def giveLivraison(biker_num, liv_code): client.send("DELIVER|" + str(biker_num) + "|" + str(liv_code)) return not checkEndTurn(client.receive())
def takeLivraison(biker_num, liv_code): client.send("TAKE|" + str(biker_num) + "|" + str(liv_code)) return not checkEndTurn(client.receive())
name = raw_input("Enter name :") client.connect(settings.host,settings.port,name) while True: board=c4board.Board() print " Your options are \n", \ " g XXX game with XXX they move first\n",\ " G XXX game with XXX you move first\n",\ " L list who is logged on \n",\ " q quit \n",\ " W wait for a challenge " cmd = raw_input(" command:") client.send(cmd) if len(cmd) == 0: continue if cmd[0] == 'W': my_col=client.wait_for_game() state=client.play_a_game(my_col,board,get_human_move) brag(state,my_col) elif cmd[0] == 'g': mess=client.get_message() print mess if mess[0] == '!':
def update(self): client.send(IP, self.edge.getCommand()) client.send(IP, self.pupille.getCommand()) client.send(IP, self.eyebrow.getCommand())
def update(self): client.send(IP, self.mouth.getCommand())
def test_send(): c.to_send.clear() send("hello") assert c.to_send[0] == "hello"
def classbal(msg): send(f"queue add class {msg}")
#!/usr/bin/env python3 import client import time client.connect("127.0.0.1", 8080) client.send( "Client" ) # The unique ID will be implemented. This is just so we can quickly test this now client.send("Hello") print(client.receive()) client.send("How are you") print(client.receive()) client.send("That's good") print(client.receive())
def curebal(cure): send(f"curing queue add {cure}")
import client import json configfile = open('config.json') config = json.loads(configfile.read()) configfile.close() while True: new_messages = client.check() for message in new_messages: if message['content'].lower().startswith(config['prefix'] + 'python'): client.send(message['channel'], 'This is a python plugin!')
def move(direction): remember_path = getattr(s, "remember_path", False) if remember_path: s.path_to_remember.append(direction) send(f"queue prepend eqbal {direction}")
def send_to_server(temp): print(temp) result=client.send(temp) return result
# bullets for bullet in bullets: bullet.move() screen.blit(bullet.obj, bullet.rect) # enemy bullets for bullet in enemy_bullets: bullet.move(enemy=True) screen.blit(bullet.obj, bullet.rect) # check collision if bullet.rect.colliderect(tank): enemy_bullets.remove(bullet) if tank.life > 0: tank.life -= 1 else: client.send('game:dead=true;') # render players screen.blit(tank.obj, tank.rect) screen.blit(enemy.obj, enemy.rect) # render chat # render conversation font = pygame.font.Font(None, 20) last_message_y = 0 for message in reversed(chat.conversation): font_render = font.render(message, 1, (255, 255, 255)) screen.blit(font_render, (20, 200 + last_message_y))
def send(): data = text.get() text.delete(0, END) client.send(data)
def send(line): print line words = line.split() if not words: return lines.append("$ " + line) was_byp = False was_found = False for class_name, class_commands in commands.items(): if words[0].lower() in class_commands: if len(words) < 2: lines.append("You need to specify a target") elif client.my("class", None) == class_name: client.send("attack", (words[0], words[1])) else: was_byp = True continue was_found = True return if was_byp and not was_found: lines.append("Your class can't do that.") elif words[0].lower() == "enter": client.send("enter", None) elif words[0].lower() == "name": if len(words) < 2: lines.append("You need to specify a username as a second parameter") else: username = words[1] client.send("name", username) elif words[0].lower() == "say": if len(words) < 2: lines.append("Sure, what are you going to say?") else: client.send("chat", " ".join(words[1:])) elif words[0].lower() == "class": if len(words) < 2: lines.append("You need to specify a class as a second parameter") else: classname = words[1] client.send("class", classname.lower()) elif words[0].lower() == "exit": sys.exit() elif words[0].lower() == "wait": client.send("wait", None) elif client.my("class", None) != None and words[0].lower() == ("commands"): for command in commands[client.my("class")]: lines.append(command) lines.append("wait") elif words[0].lower() == "help": lines.append("") lines.append("") lines.append("") lines.append("YELLOW~------------------------------") lines.append("YELLOW~Choose your name!") lines.append("YELLOW~ Type '~RED~name~YELLOW~' then your choice of name.") lines.append("YELLOW~Choose your class!") lines.append("YELLOW~ You may pick between a ~RED~Wizard~YELLOW~, ~RED~Ranger~YELLOW~, ~RED~Soldier~YELLOW~, or ~RED~Robot.") lines.append("YELLOW~ Choose by typing '~RED~class~YELLOW~' then your choice.") lines.append("YELLOW~Try to be the last man standing!") lines.append("YELLOW~ Use your moves to injure your enemies.") lines.append("YELLOW~ See your list of moves by typing '~RED~commands~YELLOW~'.") lines.append("YELLOW~To attack, type your move and the specified target, either '~RED~boss~YELLOW~' or a player's name.") lines.append("YELLOW~To chat, type '~RED~say~YELLOW~' then your message.") lines.append("YELLOW~Start the game by typing '~RED~enter~YELLOW~'.") lines.append("YELLOW~") lines.append("YELLOW~Have fun!") lines.append("YELLOW~------------------------------") lines.append("") lines.append("") lines.append("") else: lines.append("------Unrecognizable Command------")
def someone_died(matches): victim = matches[0] killer = matches[1] echo(f"{killer} killed {victim}!") fighting(f"{killer} killed {victim}!") send("queue prepend eqbal grab body")
if (event.type is MOUSEBUTTONDOWN): pos = pygame.mouse.get_pos() if (event.type is MOUSEBUTTONUP): pos = pygame.mouse.get_pos() x, y = pos #functions of main level if (not matched): if x < 240: if y < 120: print "Recognize Face button is pressed" '''TO DO''' recognized = classify.classify(model, model1) if recognized: #print"Unlock!" confirmation = client.send() print "Remote confirmation" print confirmation if confirmation == "Yes": if locked == True: print "Unlock" servo.unlock() locked = False print "The door is unlocked" level = "unlocked" else: level = "denied" print "Entrance not allowed" #'''Remote Confirmation''' #'''Servo control'''
# username = data['username'] # #room = data['room'] # room = '407' # leave_room(room) # send(username + ' has left the room.', room=room) @socketio.on('my event') def handle_my_custom_event(json): global currentuser x = json[u'x'] y = json[u'y'] theta = json[u'theta'] if (json[u'user'] == currentuser): print x,y,theta client.send("SetRobotSpeed Vx "+str(int(x))) client.send("SetRobotSpeed Vy "+str(int(y))) client.send("SetRobotSpeed Omega "+str(int(theta))) @socketio.on('user') def handle_user_event(json): print json[u'user'] , json[u'data'] if json[u'data'] == "A user connected!": global currentuser currentuser = json[u'user'] print 'current user is ', currentuser if __name__ == '__main__': client.send("EnableSystem") socketio.run(app,host='0.0.0.0')
sendDict = {} for direction in directions: print(direction.direction) sendDict[direction.direction] = direction.readDirection() for button in buttons: print(button.collor) sendDict[button.collor] = button.pressButton() return sendDict while True: detectedvalue = round(Pot.value, 2) if detectedvalue != previouspotvalue: client.send("tacPot1" + str(detectedvalue)) previouspotvalue = detectedvalue if not input_state1: client.send("tacinput1") if not input_state2: client.send("tacinput2") if not input_state3: client.send("tacinput3") if not input_state4: client.send("tacinput4") input_state1 = gpio.input(21) input_state2 = gpio.input(20) input_state3 = gpio.input(16) input_state4 = gpio.input(12)
"u", lambda _: move("u"), ), ( "^d$", "d", lambda _: move("d"), ), ( "^in$", "in", lambda _: move("in"), ), #( # "^out$", # "out", # lambda _: move("out"), #), ( "^sout$", "simple out", lambda _: send("out"), ), ( "^rdir$", "rdir", lambda _: random_move(), ), ] c.add_aliases("moving", direction_aliases)
engineminstate = False engine -= 1 if healing > 3: healing = 3 if healing < 0: healing = 0 if damage > 3: damage = 3 if damage < 0: damage = 0 if engine > 3: engine = 3 if engine < 0: engine = 0 ## print("healing" + str(healing)) ## print("damage" + str(damage)) ## print("engine" + str(engine)) setlights(healing, healred, healyellow, healgreen) setlights(damage, damagered, damageyellow, damagegreen) setlights(engine, enginered, engineyellow, enginegreen) if previoushealing != healing: client.send("he" + str(healing)) if previousdamage != damage: client.send("da" + str(damage)) if previousengine != engine: client.send("en" + str(engine))
detection_score = output_dict['detection_scores'][i] if detection_score > 0.95: # Define bounding box h, w, c = img.shape box = output_dict['detection_boxes'][i] * np.array( \ [h, w, h, w]) box = box.astype(np.int) distance = (output_dict['detection_boxes'][i][2] - output_dict['detection_boxes'][i][0]) \ + (output_dict['detection_boxes'][i][3] - output_dict['detection_boxes'][i][1]) freq = 440 / 7 + (distance * 5) * (distance * 5) #with open('freq.txt', mode='w') as f: # f.write(str(freq)) client.send(freq) speed_info = '%s: %f' % ('speed=', elapsed_time) cv2.putText(img, speed_info, (10,50), \ cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, cv2.LINE_AA) # Draw bounding box cv2.rectangle(img, \ (box[1], box[0]), (box[3], box[2]), (0, 0, 255), 3) # Put label near bounding box information = '%s: %f' % ( 'hand', output_dict['detection_scores'][i]) cv2.putText(img, information, (box[1], box[2]), \ cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, cv2.LINE_AA)