def get(self): ''' the import handle ''' try: webData = self.request.body #print "WxShowHandler Get webdata is ", webData log.info("WxShowHandler Get webdata is %s" % (webData)) id = self.get_argument('id', '') showidstr = self.get_argument('showid', '') if len(id) == 0 or len(showidstr) == 0: self.write('parameter error!') # get sign ticket for weixin jsapisdk ticket = DataCenter().get_jsapi_ticket() urlall = self.request.uri #print self.request.path /wx/show #print self.request.uri /wx/show?id=oLN9QxI-YpdNJkSIXQkppJDHuvZM&showid=15 sign = Sign(ticket, test_urlhead + urlall) sign_data = sign.sign() #print 'weixin_JSAPI_ticket: ' #print sign_data log.info('weixin_JSAPI_ticket: %s'%(sign_data)) timestamp = sign_data['timestamp'] nonceStr = sign_data['nonceStr'] signature = sign_data['signature'] # get_param id showid = long(showidstr) userdata = DataCenter().get_data_by_id(showid) if len(userdata) == 0: self.write("no data") return data_dict = userdata[0] #print data_dict log.debug(data_dict) title_info = data_dict['title'] sub_info = data_dict['aidata'].split(test_split_str) all_info = data_dict['originaldata'].split(test_split_str) createtime = data_dict['createtime'].strftime('%Y-%m-%d %H:%M:%S') author = '' authorinfo = data_dict['author'] datasource = data_dict['datasource'] _userid = data_dict['userid'] if authorinfo == '': author = datasource elif datasource == '': author = authorinfo else : author = authorinfo + ' | ' + datasource self.render("index.html", title=title_info, allinfo=all_info, subjects=sub_info, author=author, \ createtime=createtime, appid=test_weixin_appid, timestamp=timestamp, nonceStr=nonceStr, \ userid=_userid, signature=signature) except Exception, Argument: log.error(Argument) self.write(Argument)
def config(): print '********************************' ticket = token_mngr.get_ticket() print ticket print 'token' + token_mngr.get_token() sign = Sign(ticket, request.form['url']) return make_response(jsonify(sign.sign()), 200)
def build_req_inter(self, action, params, req_inter): _params = copy.deepcopy(params) _params['Action'] = action[0].upper() + action[1:] _params['RequestClient'] = self.version if (_params.has_key('SecretId') != True): _params['SecretId'] = self.secretId if (_params.has_key('Nonce') != True): _params['Nonce'] = random.randint(1, sys.maxint) if (_params.has_key('Timestamp') != True): _params['Timestamp'] = int(time.time()) if (_params.has_key('SignatureMethod') != True): if self.sign_method == 'sha256': _params['SignatureMethod'] = 'HmacSHA256' else: _params['SignatureMethod'] = 'HmacSHA1' sign = Sign(self.secretId, self.secretKey) _params['Signature'] = sign.make(self.host, req_inter.uri, _params, req_inter.method, self.sign_method) req_inter.data = urllib.urlencode(_params) self.build_header(req_inter)
def send(self, requestHost, requestUri, params, files={}, method='GET', debug=0): requests.packages.urllib3.disable_warnings() params['RequestClient'] = Request.version sign = Sign(self.secretId, self.secretKey) params['Signature'] = sign.make(requestHost, requestUri, params, method) url = 'https://%s%s' % (requestHost, requestUri) if (method.upper() == 'GET'): req = requests.get(url, params=params, timeout=Request.timeout, verify=False) if (debug): print 'url:', req.url, '\n' else: req = requests.post(url, data=params, files=files, timeout=Request.timeout, verify=False) if (debug): print 'url:', req.url, '\n' if req.status_code != requests.codes.ok: req.raise_for_status() return req.text
class CTASign(object): def __init__(self, logger=None): self.busTime = CTA() self.matrix = Sign() self.pages = 0 self.buses = [] self.running = True if logger: self.logger = logger else: self.logger = logging def runOnce(self): self.updateBuses() if self.pages == 1: self.updateDisplay(self.buses) time.sleep(60) elif self.pages == 2: self.updateDisplay(self.buses[:2]) time.sleep(30) self.updateDisplay(self.buses[2:]) time.sleep(30) else: time.sleep(60) self.display() def run(self): while (True): try: self.runOnce() except: self.stop() break def updateBuses(self): self.logger.info('Updating Buses') resp = self.busTime.getPredictions(RT, STOP, '4') print resp if u'error' in resp[u'bustime-response']: self.logger.info('No Busses Running') else: self.buses = resp[u'bustime-response'][u'prd'] self.pages = int(math.ceil(len(self.buses) / 2.)) self.logger.info('got {} buses'.format(str(len(self.buses)))) def updateDisplay(self, buses): if len(buses) == 1: self.matrix.makeBus(buses[0], None) elif len(buses) == 2: self.matrix.makeBus(buses[0], buses[1]) else: self.matrix.makeBus(None, None) self.matrix.display() def handleSignal(self, signum, frame): self.running = False def stop(self): self.matrix.blankDisplay()
def get(self): ticket = DataCenter().get_jsapi_ticket() sign = Sign(ticket, 'http://www.test.com/wx/getjsapiticket') sign_str = sign.sign() #print 'weixin_JSAPI_ticket: ' #print sign_str log.info('weixin_JSAPI_ticket: %s'%(sign_str)) self.write(sign_str)
def generateUrl(self, requestHost, requestUri, params, method = 'GET'): params['RequestClient'] = Request.version sign = Sign(self.secretId, self.secretKey) params['Signature'] = sign.make(requestHost, requestUri, params, method) params = urllib.urlencode(params) url = 'https://%s%s' % (requestHost, requestUri) if (method.upper() == 'GET'): url += '?' + params return url
def __init__(self, logger=None): self.busTime = CTA() self.matrix = Sign() self.pages = 0 self.buses = [] self.running = True if logger: self.logger = logger else: self.logger = logging
def testjs(request): c = {} wechat = WechatBasic(token=WEIXIN_TOKEN, appid=APPID, appsecret=APPSECRET) ticket = getJsApiTicket(wechat) sign = Sign(ticket, "http://" + request.get_host() + request.get_full_path()) c['sign'] = sign.sign() c['appid'] = APPID return render_to_response("weixin/testjs.html", c, context_instance=RequestContext(request))
def __init__(self, *signs): self.callbacks = { "playerOneWins": [], "playerTwoWins": [], "nobodyWins": [] } self.signs = {} for s in signs: sign = Sign(s) sign.draws(sign) self.signs[sign.name] = sign
def _create_reg(self, el_pix, col, row): digits = [] sign = Sign(self, el_pix) sign.move(col, row + 6) for i in range(5): ss = SevenSegment(self, el_pix) ss.move(col + 18 + 30 * i, row) digits.append(ss) return sign, digits
def getSignups(self): self.connect() try: c = self.connection.cursor() c.execute('select * from POSHEA1."SIGNS"') a = [] for row in c: temp = Sign('', '', '', '') temp.adapt(row) a.append(temp.dictify()) self.disconnect() return json.dumps(a) except: self.disconnect() return json.dumps([])
def execute_sign(self, sign): self.bad_def = False # if DX & SX data = self.data[sign] if self.is_good_defined(sign): sign_dx = [None] * 6 sign_dx[3] = [None] sign_sx = [None] * 6 sign_sx[3] = [None] if data[0] is not None: for i in range(0, 5): sign_dx[i] = data[0][self.params[i]] sign_dx[5] = data[0].keys() if data[1] is not None: for i in range(0, 5): sign_sx[i] = data[1][self.params[i]] sign_sx[5] = data[1].keys() print("Performing \"" + sign + "\"...\n") Sign(self, [[sign_dx[0]], [sign_sx[0]]], [[sign_dx[1]], [sign_sx[1]]], [[sign_dx[2]], [sign_sx[2]]], [sign_dx[3], sign_sx[3]], [[sign_dx[4]], [sign_sx[4]]], [sign_dx[5], sign_sx[5]]).perform_sign() if not self.bad_def and self.old_sign is None: self.printHelp()
def __mul__(self, other): shape = self.shape * other.shape sign = Sign.mul(self.sign, self.shape.size, other.sign, other.shape.size) curvature = Curvature.sign_mul(self.sign, self.shape.size, other.curvature, other.shape.size) return DCPAttr(sign, curvature, shape)
def user_detail(user_id): url, extra_params = api.user(user_id=user_id) params = dict(common_params, **extra_params) # 参数加签(* 要对全部参数加签 *) sign = Sign().getSign(token, params) params["mas"] = sign['mas'] params["as"] = sign['as'] params["ts"] = sign['ts'] resp = requests.get(url, params=params, headers=CONFIG['HEADER']).json() # print(json.dumps(resp)) data = resp['user'] out_data = { 'user_id': data['uid'], 'nickname': data['nickname'], 'signature': data['signature'], 'sex': data['gender'], 'address': data['country'] + data['city'] + data['district'], 'constellation': data['constellation'], 'avatar': data['avatar_larger']['url_list'], 'url': data['share_info']['share_url'], 'follower_count': data['follower_count'], # 粉丝数 'total_favorited': data['total_favorited'], # 获赞数 'following_count': data['following_count'], # 关注数 'aweme_count': data['aweme_count'], # 作品数 'dongtai_count': data['dongtai_count'], # 动态数 } return json.dumps(out_data)
def get_out_data(max_time=int(time.time())): url, extra_params = api.following(user_id=target_user_id, count=20, max_time=max_time) params = dict(common_params, **extra_params) # 参数加签(* 要对全部参数加签 *) sign = Sign().getSign(token, params) params["mas"] = sign['mas'] params["as"] = sign['as'] params["ts"] = sign['ts'] resp = requests.get(url, params=params, headers=CONFIG['HEADER']).json() # print(json.dumps(resp)) data = resp['followings'] for item in list(data): item_data = {'user_id': item['uid'], 'nickname': item['nickname']} if item_data not in out_data['followings']: out_data['followings'].append(item_data) print('%s/%s' % (len(out_data['followings']), resp['total'])) if resp['has_more'] == False or len(resp['followings']) == 0 or len( out_data['followings']) >= target_count: return # 默认30s。如果丢失数据可缩小秒数。如果数据重复可增加秒数。 next_max_time = resp.get('min_time', int(time.time())) - 30 get_out_data(next_max_time)
def get_wx_config(): url = request.form.get('url') cgi_bin_access_token = redis.get('cgi_bin_access_token') jsapi_ticket = redis.get('jsapi_ticket') print('------>', cgi_bin_access_token, jsapi_ticket) if cgi_bin_access_token is None or jsapi_ticket is None: # 第一步:获取 “普通access_token” source_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}' cgi_bin_url = source_url.format(APPID=config.APPID, APPSECRET=config.APPSECRET) resp = requests.get(cgi_bin_url) # 请求api data = eval(resp.text) # 将字符串转为字典 print(data) cgi_bin_access_token = data['access_token'] redis.set('cgi_bin_access_token', cgi_bin_access_token, ex=data['expires_in']) # 第二步:获取 jsapi_ticket source_url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={ACCESS_TOKEN}&type=jsapi' ticket_url = source_url.format(ACCESS_TOKEN=cgi_bin_access_token) resp = requests.get(ticket_url) # 请求api data = eval(resp.text) # 将字符串转为字典 print(data) jsapi_ticket = data['ticket'] redis.set('jsapi_ticket', jsapi_ticket, ex=data['expires_in']) # 第三步:签名算法 # noncestr=Wm3WZYTPz0wzccnW # jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg # timestamp=1414587457 # url=http://mp.weixin.qq.com?params=value sign = Sign(jsapi_ticket, url) ret = sign.sign() return jsonify({ 'status_code': config.SUCCESS, 'msg': 'success', 'data': { 'appId': config.APPID, 'timestamp': ret['timestamp'], 'nonceStr': ret['nonceStr'], 'signature': ret['signature'], } })
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.ip = self.get_ip() self.socket_1 = Monitor(self.ip, self.ui_scroll_area) self.socket_2 = Monitor(self.ip, self.ui_scroll_area) self.socket_3 = Monitor(self.ip, self.ui_scroll_area) self.socket_4 = Monitor(self.ip, self.ui_scroll_area) self.ports = Queue() self.find_device = QUdpSocket() self.set_find_device_bind() self.add_monitor() self.add_ports() self.set_connect() self.current_device_num = 0 self.sign_in = Sign(mainwindow=self) self.sign_in.show()
def __init__(self, name, ship, printer, game): """Stores the information regarding the fire planet.""" super(Fireplanet, self).__init__(name, "Bracing yourself against the heat, you squint out at the blackened landscape, dotted with pools of lava.", ship, game) self.crater = Location("10", "there is a path that leads back to where you left your spaceship. You hope it's still there and the crater hasn't eaten it.", "Your spaceship sits behind you, hanging on the edge of a large crater, which glows mysteriously due to the magma inside.", printer, [Event(EventName.on_arrival, 'self.game.printer.pprint("You had to be careful as you landed on Paxak, as the surface is mostly covered in seething lava. Even the ground you can walk on is inhospitible and dangerous. You are glad that you weren\'t born here.")', "10"), Event(EventName.on_sign_read, 'self.game.printer.pprint("The words on the sign are written in a language that speaks of crackling embers and barely controlled aggression. Though the language is not your own, you can read it, albeit with some difficutly. You wish you understood why.")', "1-")]) ship_item = Item(False, True, False, ["ship", "spaceship", "craft"], "Your spaceship is still there, thank goodness.", "The plating on the bottom looks a little blackened after the descent through the hot atmosphere.", printer) crater = Item(False, True, False, ["crater"], "The crater behind the spaceship glows ominously.", "It looks pretty deep. The bottom, far below you, has what looks like a lava spring filling it. You wish you'd spotted a better patch of ground to land on, but this was the closest place to the signs of life you spotted from the air. It'll do for now.", printer) sign1 = Sign(self.get_sign_list()[1]["first_sign"], "A metal board attached to a section of small girder protrudes from the ground. You guess that this is the Paxak version of signs.", printer) npc1 = NPC(["man1"], "Man1 stands before you.", "As you look at man1, you see man1.", False, False, self.get_npc_speeches(1,0), printer, [], game) self.crater.objects = [ship_item, crater, sign1, npc1] self.base_of_volcano = Location("11", "you see a constant stream of smoke and a hazy glow from the top of a large mountain.", "You look up at the peak of the smoking volcano. You decide not to risk your life venturing up.", printer, []) volcano = Item(False, True, False, ["mountain", "volcano"], "The volcano stands in front of you like a lightly sleeping giant.", "You reason that going to the top would be a pretty quick way to end your life.", printer) sign2 = Sign(self.get_sign_list()[1]["second_sign"], "Facing away from the volcano is a second sign, almost red hot from the heated ground.", printer) self.npc2 = NPC(["man2"], "Man2 stands before you.", "Perhaps she could get into the volcano?", True, False, self.get_npc_speeches(1,1), printer, [Event(EventName.on_talking, 'self.game.fireplanet.npc2.state = NPCState.task_complete', "11", NPCState.during_task), Event(EventName.on_talking, 'self.game.fireplanet.npc5.state = NPCState.task_complete; self.game.player.get("The deepest heat", "the volcano"); self.game.printer.pprint("You got the deepest heat from the volcano!")', "11", NPCState.after_task)], game) self.base_of_volcano.objects = [volcano, sign2, self.npc2] self.village = Location("12", "you can just see what could be the remains of a settlement.", "You are surrounded by tumbledown houses, broken and split. Debris is strewn from the doorways, as if they were hurriedly deserted.", printer, [Event(EventName.on_arrival, 'self.game.fireplanet.set_path(self.game.fireplanet.village, ("forwards", "forward"), self.game.fireplanet.crater)', "12")]) buildings = Item(False, True, False, ["buildings", "houses"], "You realise the houses are glittering slightly in the light of the everpresent lava.", "The houses appear to have been made from a glass like substance, now shattered. It's terrible, but it's also beautiful.", printer) sign3 = Sign(self.get_sign_list()[1]["third_sign"], "Just outside the village is another sign, telling more of the story.", printer) npc3 = NPC(["man3"], "Man3 stands before you.", "Man3 is a house husband.", False, False, self.get_npc_speeches(1,2), printer, [], game) self.village.objects = [buildings, sign3, npc3] self.lava_pool_edge = Location("13", "you can see a large expanse of lava.", "You go as close to the lava pool as you dare. It is hot.", printer, []) pool = Item(False, True, False, ["pool", "lava"], "The pool of lava is constantly in motion, as if being stirred from within.", "The heat of the molten rock is making bubbles in the liquid, and whenever they burst you have to be careful not to get burned.", printer) sign4 = Sign(self.get_sign_list()[1]["fourth_sign"], "In danger of being consumed by the spitting lava is a sign.", printer) npc4 = NPC(["man4"], "Man4 stands before you.", "Man4 will in fact be a child.", False, False, self.get_npc_speeches(1,3), printer, [], game) self.lava_pool_edge.objects = [pool, sign4, npc4] self.workshop = Location("14", "you spot a small building all on its own.", "The building is the least damaged of all the ones you have seen here, but then it's not made of the same material as the others.", printer, [Event(EventName.on_arrival, 'self.game.fireplanet.set_path(self.game.fireplanet.workshop, ("left",), self.game.fireplanet.crater)', "14"), Event(EventName.on_arrival, 'EventName.planets_visited_before_npcs += "A"', "14")]) building = Item(False, True, False, ["building", "workshop"], "The small building looks solid and heavily fireproofed, and as if it has had to be rebuilt multiple times.", "The substance the building is made of reminds you of the hardened black rocks you have seen floating within the lava. Inside the building you see a furnace, an anvil, and an iron bucket filled with tools of a blacksmith. This must be the workshop of Paxak.", printer) sign5 = Sign(self.get_sign_list()[1]["fifth_sign"], "Stuck on the door is the sign that completes the story.", printer) self.npc5 = NPC(["man5"], "Man5 stands before you.", "Man5 owns the forge.", True, True, self.get_npc_speeches(1,4), printer, [Event(EventName.on_talking, 'self.game.fireplanet.npc2.state = NPCState.during_task; self.game.player.karma += 1', "14", NPCState.during_task), Event(EventName.on_talking, 'self.game.player.get("Explosive power", "Paxak"); self.game.player.gun_pieces += 1; self.game.printer.pprint("You got the Explosive Power part of the Ultimate Weapon!"); del(self.game.player.inventory["The deepest heat"]); self.game.printer.pprint("The deepest heat of the volcano was taken away.")', "14", NPCState.after_task)], game) self.workshop.objects = [building, sign5, self.npc5] self.landing_location = self.crater self.current_location = self.ship for loc in [self.crater, self.base_of_volcano, self.village, self.lava_pool_edge, self.workshop, self.ship]: self.add_location(loc) self.set_path(self.crater, ("left",), self.base_of_volcano) self.set_path(self.base_of_volcano, ("left",), self.village) self.set_path(self.village, ("left",), self.lava_pool_edge) self.set_path(self.lava_pool_edge, ("left",), self.workshop)
def __init__(self, value): if value > 0: sign_str = Sign.POSITIVE_KEY elif value == 0: sign_str = Sign.ZERO_KEY else: sign_str = Sign.NEGATIVE_KEY super(Constant, self).__init__(Curvature.CONSTANT, Sign(sign_str), str(value))
def detectSign(self, image, color): #image = cv2.resize(image, None, fx=0.25, fy=0.25, interpolation=cv2.INTER_AREA) #print "sign image h/w " + str(image.shape[:2]) center, area = self.imageAnalysis(image, color) print "area " + str(area) print color[1] + "area " + str(area) # cv2.circle(image, center, 5, (0, 0, 255), -1) # cv2.imshow(color[1]+ ' Camera', image) # cv2.waitKey(1) return Sign(center, area)
def send(self, requestHost, requestUri, params, files = {}, method = 'GET', debug = 0): params['RequestClient'] = Request.version sign = Sign(self.secretId, self.secretKey) params['Signature'] = sign.make(requestHost, requestUri, params, method) url = 'https://%s%s' % (requestHost, requestUri) if (method.upper() == 'GET'): req = requests.get(url, params=params, timeout=Request.timeout) if (debug): print 'url:', req.url, '\n' else: req = requests.post(url, data=params, files=files, timeout=Request.timeout) if (debug): print 'url:', req.url, '\n' if req.status_code != requests.codes.ok: req.raise_for_status() return req.text
def redefinition_rectangles_coords(self): for rectangle in self.objects_coords_to_delete: self.objects_coords.remove(rectangle) for rectangle in self.objects_coords_to_append: self.objects_coords.append(rectangle) for obj_coord in self.objects_coords: sign = Sign(x=obj_coord.most_left, y=obj_coord.most_top, width=obj_coord.most_right - obj_coord.most_left, height=obj_coord.most_bottom - obj_coord.most_top) self.signs.append(sign)
def loop(): sign = Sign() while not stop.is_set(): try: pop = queue.get_nowait() command = pop[0] args = pop[1:] do_command(sign, command, args) except Empty: pass if sign.mode != 'noop': sign.tick() time.sleep(0.01) print('End of loop')
def get(self): ''' lst = ["python","www.itdiffer.com","*****@*****.**"] self.render("index.html", info=lst) ''' # get userid by id body = self.request.body print "============>>>>>>>>>>>>>>>>>>>>start" print body print "============>>>>>>>>>>>>>>>>>>>>end." res = DataCenter().get_data_by_id(int(body['id'])) _userid = res[0]['userid'] # get sign ticket for weixin jsapisdk ticket = DataCenter().get_jsapi_ticket() urlall = self.request.uri #print self.request.path /wx/show #print self.request.uri /wx/show?id=oLN9QxI-YpdNJkSIXQkppJDHuvZM&showid=15 sign = Sign(ticket, test_urlhead + urlall) sign_data = sign.sign() #print 'weixin_JSAPI_ticket: ' #print sign_data log.info('weixin_JSAPI_ticket: %s'%(sign_data)) timestamp = sign_data['timestamp'] nonceStr = sign_data['nonceStr'] signature = sign_data['signature'] # get_param id title_info = '标题:人工智能的未来在哪里' all_info = ["先看一下这个情况,中国出口到全球,其中英国占中国出口的3%左右,但是退欧之后,我们看到整个的英镑是狂跌。", "另外大家现在寻求一个避险的港湾,避险的港湾在哪里呢?美元是第一,其次是日元,然后是黄金,最后就是美国的国债,其他一些资产有很大风险性。", "不过很多分析是有错误的,这么多专家、这么多经济学家、这么多非常能干的交易员,他们的分析判断在这个事件发生之前是不靠谱的。", "所以如果人工智能在未来的15年能帮助人类分析、判断,规避风险,我觉得这会是一个突破。", "我在美国的硕士学位就是和机器人有关的,我们学的是简单的控制,是你控制一个机器手,或者机器做的事情,和现在谈的人工智能概念差别还是很大的。", "另外一方面,我们现在看的人工智能,有人尖叫,有人担忧。其实还不到这个程度,因为我们现在看到的人工智能,无论是AlphaGo还是其他的人工智能,我觉得还是属于第一智能的状态。", "文章全文到此结束"] sub_info = ["主题1:人工智能的新时代即将到来", "主题2:人工智能到底能做什么", "主题3:人工智能的道路还很漫长"] self.render("index.html", title=title_info, allinfo=all_info, subjects=sub_info, author="", \ createtime="2017-03-01 00:00:00", appid=test_weixin_appid, timestamp=timestamp, nonceStr=nonceStr, signature=signature, userid=_userid)
def read_data(self): info_dic = self.salon.get_salon_info_dic() #[date, time, isCross] f = open(self.data_path, "r", encoding='utf-8') lines = csv.reader(f) csv_lines = 0 for item in lines: csv_lines += 1 if csv_lines == 1: pass else: sign_new = Sign() sign_new.load_data(item, info_dic) self.signs.append(sign_new) index = -1 temp = None for item in self.signs: if item.salon_status != '已删除' and item.salon_status != '管理员删除' and item.user_status != '已退出': if item.salon_id == temp: self.salon_user_list[index][1].append(item.user_id) else: temp = item.salon_id index += 1 self.salon_user_list.append([temp, [item.user_id]])
def sp(self): for retry in range(10): try: headers = {'User-Agent': self.ua} r = requests.get(self.url, headers=headers) data = r.json()['data'] canRead = data['can_read'] if canRead != True: Sign(self.randomUA()).sp() continue # print(data) self.data = data return data except Exception as e: print(e) return None
def T(self): """Determines the DCP attributes of a transpose. Returns: The DCPAttr of the transpose of the matrix expression. """ rows, cols = self.shape.size shape = Shape(cols, rows) neg_mat = self.sign.neg_mat.T pos_mat = self.sign.pos_mat.T cvx_mat = self.curvature.cvx_mat.T conc_mat = self.curvature.conc_mat.T nonconst_mat = self.curvature.nonconst_mat.T return DCPAttr(Sign(neg_mat, pos_mat), Curvature(cvx_mat, conc_mat, nonconst_mat), shape)
def __init__(self, screen, screen_size): self.screen = screen self.screen_size = screen_size self.events = [] self.background_sign_in = pygame.image.load( "images/background.jpg").convert() self.background_game = pygame.image.load( "images/background.jpg").convert() self.state = 'signin' self.done = False self.db = Db() self.user_id = '' self.max_score = 0 self.asd = 0 self.player_image = 'helis/ZF0.png' # self.user_id = 'Ryan' self.sign = Sign(self) self.restart()
def base_interface(no, url): data = no.get('data') if "password" in data: data["password"] = Md5().md5(data["password"]) header['token'] = '' elif "code" in data: try: data["code"] = r.get(url + 'code').decode() header['token'] = '' except Exception as e: logging.warning("redis中不存在对应的code", e) else: try: header['token'] = r.get(url + 'token').decode() except Exception as e: logging.warning('redis中不存在token', e) param = Sign( ParamFix(data, Conf().url().get('appkey'), no.get('name')).param(), Conf().url().get('secret')).get_param() result = InterfaceRequests(url + no.get('path'), param, header).doc_interface().json() if no.get('name') == 'passport.login.security': try: code = result['value'].split('cncode=')[1] r.set(url + 'code', code, px=6000000) except AttributeError as e: logging.warning(url, result, e) elif no.get('name') == 'passport.userinfo.bycode': try: token = result.get('value').get('token') r.set(url + 'token', token, px=6000000) except AttributeError as e: logging.warning(result, e) else: pass return result
def __getitem__(self, key): """Determines the DCP attributes of an index/slice. Args: key: A (slice, slice) tuple. Returns: The DCPAttr of the index/slice into the matrix expression. """ shape = Shape(*ku.size(key, self.shape)) # Reduce 1x1 matrices to scalars. neg_mat = bu.to_scalar(bu.index(self.sign.neg_mat, key)) pos_mat = bu.to_scalar(bu.index(self.sign.pos_mat, key)) cvx_mat = bu.to_scalar(bu.index(self.curvature.cvx_mat, key)) conc_mat = bu.to_scalar(bu.index(self.curvature.conc_mat, key)) nonconst_mat = bu.to_scalar(bu.index(self.curvature.nonconst_mat, key)) return DCPAttr(Sign(neg_mat, pos_mat), Curvature(cvx_mat, conc_mat, nonconst_mat), shape)
def __init__(self, speaker, passive_stt_engine, active_stt_engine): """ Initiates the pocketsphinx instance. Arguments: speaker -- handles platform-independent audio output passive_stt_engine -- performs STT while Jasper is in passive listen mode acive_stt_engine -- performs STT while Jasper is in active listen mode """ self._logger = logging.getLogger(__name__) self.speaker = speaker self.passive_stt_engine = passive_stt_engine self.active_stt_engine = active_stt_engine self._logger.info("Initializing PyAudio. ALSA/Jack error messages " + "that pop up during this process are normal and " + "can usually be safely ignored.") self._audio = pyaudio.PyAudio() self._logger.info("Initialization of PyAudio completed.") self.signs = Sign()
def interpretSigns(self, left, right): shortcut, stop = False, False lShortcutSign, lStopSign = left rShortcutSign, rStopSign = right shortcutSignCenter = (lShortcutSign.getCenter()[0] + rShortcutSign.getCenter()[0]) / 2, ( lShortcutSign.getCenter()[1] + rShortcutSign.getCenter()[1]) / 2 shortcutSignArea = (lShortcutSign.getArea() + rShortcutSign.getArea()) / 2 shortcutSign = Sign(shortcutSignCenter, shortcutSignArea) stopSignCenter = (lStopSign.getCenter()[0] + rStopSign.getCenter()[0] ) / 2, (lStopSign.getCenter()[1] + rStopSign.getCenter()[1]) / 2 stopSignArea = (lStopSign.getArea() + rStopSign.getArea()) / 2 stopSign = Sign(stopSignCenter, stopSignArea) if shortcutSign.getArea() > 200: shortcut = True if stopSign.getArea() > 200: stop = True return (shortcut, stop), (shortcutSign, stopSign)
""" A simple guestbook flask application. """ import flask from flask.views import MethodView from index import Index from sign import Sign application = flask.Flask(__name__) # our Flask app application.add_url_rule('/', view_func=Index.as_view('index'), methods=["GET"]) application.add_url_rule('/sign/', view_func=Sign.as_view('sign'), methods=['GET', 'POST']) if __name__ == '__main__': application.run(host='0.0.0.0', debug=True)
class Mic: speechRec = None speechRec_persona = None def __init__(self, speaker, passive_stt_engine, active_stt_engine): """ Initiates the pocketsphinx instance. Arguments: speaker -- handles platform-independent audio output passive_stt_engine -- performs STT while Jasper is in passive listen mode acive_stt_engine -- performs STT while Jasper is in active listen mode """ self._logger = logging.getLogger(__name__) self.speaker = speaker self.passive_stt_engine = passive_stt_engine self.active_stt_engine = active_stt_engine self._logger.info("Initializing PyAudio. ALSA/Jack error messages " + "that pop up during this process are normal and " + "can usually be safely ignored.") self._audio = pyaudio.PyAudio() self._logger.info("Initialization of PyAudio completed.") self.signs = Sign() def __del__(self): self._audio.terminate() def getScore(self, data): rms = audioop.rms(data, 2) score = rms / 3 return score def fetchThreshold(self): # TODO: Consolidate variables from the next three functions THRESHOLD_MULTIPLIER = 1.8 RATE = 16000 CHUNK = 1024 # number of seconds to allow to establish threshold THRESHOLD_TIME = 1 # prepare recording stream stream = self._audio.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK) # stores the audio data frames = [] # stores the lastN score values lastN = [i for i in range(20)] # calculate the long run average, and thereby the proper threshold for i in range(0, RATE / CHUNK * THRESHOLD_TIME): data = stream.read(CHUNK) frames.append(data) # save this data point as a score lastN.pop(0) lastN.append(self.getScore(data)) average = sum(lastN) / len(lastN) stream.stop_stream() stream.close() # this will be the benchmark to cause a disturbance over! THRESHOLD = average * THRESHOLD_MULTIPLIER return THRESHOLD def passiveListen(self, PERSONA): """ Listens for PERSONA in everyday sound. Times out after LISTEN_TIME, so needs to be restarted. """ THRESHOLD_MULTIPLIER = 1.8 RATE = 16000 CHUNK = 1024 # number of seconds to allow to establish threshold THRESHOLD_TIME = 1 # number of seconds to listen before forcing restart LISTEN_TIME = 10 # prepare recording stream stream = self._audio.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK) # stores the audio data frames = [] # stores the lastN score values lastN = [i for i in range(30)] # calculate the long run average, and thereby the proper threshold for i in range(0, RATE / CHUNK * THRESHOLD_TIME): data = stream.read(CHUNK) frames.append(data) # save this data point as a score lastN.pop(0) lastN.append(self.getScore(data)) average = sum(lastN) / len(lastN) # this will be the benchmark to cause a disturbance over! THRESHOLD = average * THRESHOLD_MULTIPLIER # save some memory for sound data frames = [] # flag raised when sound disturbance detected didDetect = False # start passively listening for disturbance above threshold for i in range(0, RATE / CHUNK * LISTEN_TIME): data = stream.read(CHUNK) frames.append(data) score = self.getScore(data) if score > THRESHOLD: didDetect = True break # no use continuing if no flag raised if not didDetect: print "No disturbance detected" stream.stop_stream() stream.close() return (None, None) # cutoff any recording before this disturbance was detected frames = frames[-20:] # otherwise, let's keep recording for few seconds and save the file DELAY_MULTIPLIER = 1 for i in range(0, RATE / CHUNK * DELAY_MULTIPLIER): data = stream.read(CHUNK) frames.append(data) # save the audio data stream.stop_stream() stream.close() with tempfile.NamedTemporaryFile(mode='w+b') as f: wav_fp = wave.open(f, 'wb') wav_fp.setnchannels(1) wav_fp.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16)) wav_fp.setframerate(RATE) wav_fp.writeframes(''.join(frames)) wav_fp.close() f.seek(0) # check if PERSONA was said transcribed = self.passive_stt_engine.transcribe(f) if any(PERSONA in phrase for phrase in transcribed): return (THRESHOLD, PERSONA) return (False, transcribed) def activeListen(self, THRESHOLD=None, LISTEN=True, MUSIC=False): """ Records until a second of silence or times out after 12 seconds Returns the first matching string or None """ options = self.activeListenToAllOptions(THRESHOLD, LISTEN, MUSIC) if options: return options[0] def activeListenToAllOptions(self, THRESHOLD=None, LISTEN=True, MUSIC=False): """ Records until a second of silence or times out after 12 seconds Returns a list of the matching options or None """ RATE = 16000 CHUNK = 1024 LISTEN_TIME = 12 # check if no threshold provided if THRESHOLD is None: THRESHOLD = self.fetchThreshold() self.speaker.play(jasperpath.data('audio', 'beep_hi.wav')) # prepare recording stream stream = self._audio.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK) frames = [] # increasing the range # results in longer pause after command # generation lastN = [THRESHOLD * 1.2 for i in range(30)] for i in range(0, RATE / CHUNK * LISTEN_TIME): data = stream.read(CHUNK) frames.append(data) score = self.getScore(data) lastN.pop(0) lastN.append(score) average = sum(lastN) / float(len(lastN)) # TODO: 0.8 should not be a MAGIC NUMBER! if average < THRESHOLD * 0.8: break self.speaker.play(jasperpath.data('audio', 'beep_lo.wav')) # save the audio data stream.stop_stream() stream.close() with tempfile.SpooledTemporaryFile(mode='w+b') as f: wav_fp = wave.open(f, 'wb') wav_fp.setnchannels(1) wav_fp.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16)) wav_fp.setframerate(RATE) wav_fp.writeframes(''.join(frames)) wav_fp.close() f.seek(0) return self.active_stt_engine.transcribe(f) def say(self, phrase, OPTIONS=" -vdefault+m3 -p 40 -s 160 --stdout > say.wav"): # alter phrase before speaking print(phrase) signphrase = phrase.encode('ascii', errors='backslashreplace') self.signs.display(signphrase) phrase = alteration.clean(phrase) self.speaker.say(phrase)
def GET(self): # guard code, back step if web.ctx.session.webpage=="receipt": return web.seeother("\menus") i = web.input() oid_list = i.oids.split("_") shopping_list=[] global access_token global jsapi_ticket global token_timestamp js_api = JsApi_pub() openid = web.ctx.session.openid #print openid if (not access_token.strip()) or (int(time.time())-token_timestamp > 7200): access_token = sign.get_token() jsapi_ticket = sign.get_ticket(access_token) token_timestamp = int(time.time()) total_fee = 0.0 for oid in oid_list: # oid = session.pay_oid # print oid order_it = model.get_order(oid) order = list(order_it) total_fee += order[0].Price shopping_list.append(oid) if len(oid_list) > 1: out_trade_no = str(int(oid_list[0])/1000) else: out_trade_no = str(int(oid_list[0])) js_sign = Sign(jsapi_ticket, web.ctx.home+web.ctx.fullpath) sign_data = js_sign.sign() nonceStr = sign_data['nonceStr'] signature = sign_data['signature'] timestamp = sign_data['timestamp'] url = sign_data['url'] #print url #total_fee = web.cookies().get('total_price') #total_fee = str(int(order[0].Price)*100) #TODO:dup orderid unify_pay = UnifiedOrder_pub() #print oid #print total_fee #print openid unify_pay.setParameter('out_trade_no', out_trade_no) unify_pay.setParameter('body','准时开饭 套餐') unify_pay.setParameter('total_fee',str(int(total_fee)*100)) unify_pay.setParameter('notify_url','http://x.zhunshikaifan.com/') unify_pay.setParameter('trade_type','JSAPI') unify_pay.setParameter('openid',openid) prepay_id = unify_pay.getPrepayId() #print prepay_id js_api.setPrepayId(prepay_id) pay_data = js_api.getParameters() if not web.ctx.session.shoppinglist: web.ctx.session.shoppinglist = shopping_list web.ctx.session.webpage="webchatpay" return render.webchatpay(signature,nonceStr,timestamp,json.loads(pay_data))