def _connect(self):
try:
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if self._broadcast:
# self._sock.bind((self._broadcast_interface, self._port))
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
return self._sock
except socket.gaierror:
error = "Unable to connect to or resolve host: {}".format(
self._host)
log.error(error)
raise IOError(error)
# Push new data to strand
python类error()的实例源码
def update(self, data):
try:
self._fixData(data)
data = self._buf
s = self._connect()
count = self.bufByteCount
packet = self._generateHeader(CMDTYPE.PIXEL_DATA, count)
packet.extend(data)
s.sendto(packet, (self._host, self._port))
s.close()
except Exception as e:
log.exception(e)
error = "Problem communicating with network receiver!"
log.error(error)
raise IOError(error)
def update(self, data):
try:
s = self._connect()
count = self.bufByteCount
packet = self._generateHeader(CMDTYPE.PIXEL_DATA, count)
packet.extend(data)
s.sendall(packet)
resp = ord(s.recv(1))
if not self.persist:
s.close()
if resp != RETURN_CODES.SUCCESS:
log.warning("Bytecount mismatch! %s", resp)
except Exception as e:
log.exception(e)
error = "Problem communicating with network receiver!"
log.error(error)
raise IOError(error)
def getKeys(self):
bits = 0
try:
packet = SerialGamePad._generateHeader(CMDTYPE.GET_BTNS, 0)
self._com.write(packet)
resp = self._com.read(1)
if len(resp) == 0:
SerialGamePad._comError()
elif ord(resp) != RETURN_CODES.SUCCESS:
SerialGamePad._printError(ord(resp))
resp = self._com.read(2)
if len(resp) != 2:
SerialGamePad._comError()
bits = ord(resp[0]) + (ord(resp[1]) << 8)
except IOError:
log.error("IO Error Communicatng With Game Pad!")
index = 0
result = {}
for m in self._map:
result[m] = (bits & (1 << index) > 0)
index += 1
return d(result)
def run_proc(self, body):
try:
if body.has_key('client_os_type'):
pack_id = None
query_param = ''
if body.has_key('pack_id'):
pack_id = body['pack_id']
if body.has_key('query_param'):
query_param = body['query_param']
resp = Himalaya().get_recommendation(body['client_os_type'], pack_id, query_param)
self.finish(resp)
else:
tmp_dict = {'code': -1, "error": "need clent os type param"}
self.finish(json.dumps(tmp_dict))
except Exception, Argument:
log.error(Argument)
self.finish(Argument)
def get_recommendation(self, os_type, pack_id, query_param = ''):
recommendation = {'code': 0}
if "luogic_show" in query_param:
return self.get_sound_by_album_id(os_type, pack_id, 239463, 1)
else:
#"""
res = self.tracks_hot(os_type, pack_id, 18, "???")
#res = self.tracks_hot(os_type, pack_id, 1, "??")
if (res is not None) and res.has_key('tracks'):
recommendation['recommendation'] = []
tmp_list = res['tracks']
for track in tmp_list:
recommendation['recommendation'].append(self.__set_recommendation(track))
else:
recommendation['code'] = -1
recommendation['error'] = 'no data'
return json.dumps(recommendation, ensure_ascii = False).encode('utf-8')
#"""
#return self.find_track(os_type, pack_id, "?? ??")
def delete_product(product_infos):
PRODUCT_ID = product_infos["id"]
try :
PRODUCT_NAME = product_infos["name"]
except KeyError:
PRODUCT_NAME = "Inconnu"
log.error("Ref incwo not found for product {} (id {})".format(PRODUCT_NAME, PRODUCT_ID))
url = "https://www.incwo.com/"+str(ID_USER)+"/customer_products/"+str(PRODUCT_ID)+".xml";
send_request("delete", url)
# TODO
return 0
# Args :
# product_infos : contient toutes les infos sur le produit picata
# product_id : id du produit, necessaire pour change_stock_value (fct qui va envoyer la requete ainsi que l'xml correspondant au nouveau stock)
# cat_id_src : vaux None en cas de creation d'un nouveau produit.
# pour l'update, contient l'id de la category selon incwo (la ou sont stocke les infos de la precedente synchro)
def _connect(self):
if self.persist and self._sock:
return self._sock
try:
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.connect((self._host, self._port))
return self._sock
except socket.gaierror:
error = "Unable to connect to or resolve host: {}".format(
self._host)
log.error(error)
raise IOError(error)
# Push new data to strand
def _printError(error):
msg = "Unknown error occured."
if error == RETURN_CODES.ERROR_SIZE:
msg = "Data packet size incorrect."
elif error == RETURN_CODES.ERROR_UNSUPPORTED:
msg = "Unsupported configuration attempted."
elif error == RETURN_CODES.ERROR_BAD_CMD:
msg = "Unsupported protocol command. Check your device version."
log.error("%s: %s", error, msg)
raise SerialPadError(msg)
def _connect(self):
try:
if(self.dev == ""):
SerialGamePad.findSerialDevices(self._hardwareID)
if len(SerialGamePad.foundDevices) > 0:
self.dev = SerialGamePad.foundDevices[0]
log.info("Using COM Port: %s", self.dev)
try:
self._com = serial.Serial(self.dev, timeout=5)
except serial.SerialException as e:
ports = SerialGamePad.findSerialDevices(self._hardwareID)
error = "Invalid port specified. No COM ports available."
if len(ports) > 0:
error = "Invalid port specified. Try using one of: \n" + \
"\n".join(ports)
log.info(error)
raise SerialPadError(error)
packet = SerialGamePad._generateHeader(CMDTYPE.INIT, 0)
self._com.write(packet)
resp = self._com.read(1)
if len(resp) == 0:
SerialGamePad._comError()
return ord(resp)
except serial.SerialException as e:
error = "Unable to connect to the device. Please check that it is connected and the correct port is selected."
log.exception(e)
log.error(error)
raise e
def broadcast(self, input_, norm, classifier=None, aif_scale=1):
"""
Used for high level broadcast, in which the input is processed in bulk instead of per-component, i.e., per byte.
input_ of len 1-256 (for proper CM1K emulation, otherwise unlimited)
norm: A DistNorm enum
classifier: A Classifier enum
aif_scale: Modify the aif when determining whether the fire. The aif can also be permanently scaled via
CM1KEmulator.scale_all_aifs(), but this parameter enables the same behavior without altering the neuron.
"""
# Called from CM1KEmulator.broadcast()
log.trace("Neuron.broadcast()")
# This shouldn't be necessary. This function should only be called on committed and the rtl neurons.
if self.state == NeuronState.idle:
log.error("Neuron.broadcast() called on idle neuron")
return
self.dist = 0 # NOTE: Not sure this is necessary. Also, undecided whether this should simply call reset_dist().
if norm == cm1k.CM1KDistNorm.l1:
for i, comp in enumerate(input_):
self.dist += abs(comp - self.pattern[i])
elif norm == cm1k.CM1KDistNorm.lsup:
for i, comp in enumerate(input_):
self.dist = max(abs(comp - self.pattern[i]), self.dist)
elif norm == cm1k.CM1KDistNorm.euc:
for i, comp in enumerate(input_):
self.dist += (comp - self.pattern[i]) * (comp - self.pattern[i])
self.dist = int(round(math.sqrt(self.dist)))
log.log("Single neuron cat{} dist: {:>5} < {:>5} ?".format(self.cat, self.dist, self.aif))
# TODO: Use the minimum and maximum AIFs of each neuron (i.e., of each context)
aif = self.aif if aif_scale == 1 else min(max(int(round(self.aif * aif_scale)), 0), 0xFFFF)
if (classifier == cm1k.CM1KClassifier.rbf and self.dist < aif) or classifier == cm1k.CM1KClassifier.knn:
# The neuron has fired
log.log("Fire with dist{} aif{} cat{}".format(self.dist, aif, self.cat))
self.chip.store_firing_neuron(self)
def shrink_if_necessary(self, cat, new_aif, minif):
"""
Shrink if the AIF if categories don't match and error-compensating AIF < currently held AIF.
"""
log.trace("Neuron.shrink_if_necessary()")
# TODO: create unit test where misfiring neuron has exactly the same distance as the best neuron.
if cat != self.cat and new_aif < self.aif:
self.shrink_aif(new_aif, minif)
def on_error(self, event, irc):
log.error(" ".join(event.arguments))
if " ".join(event.arguments).startswith("Closing Link"):
self.bot.web.stop()
self.userdb.flush()
self.bot.db_job.stop()
sys.exit(1)
# Numeric events
def on_unavailresource(self, event, irc):
log.error("Nick unavailable, trying alternative")
irc.nick(self.config['nickname'] + "_")
self.config['nickname'] = self.config['nickname'] + "_"
def on_nicknameinuse(self, event, irc):
log.error("Nick already in use, trying alternative")
irc.nick(self.config['nickname'] + "_")
self.config['nickname'] = self.config['nickname'] + "_"
def get(self):
try:
webData = self.request.body
#print "Handle Get webdata is ", webData
log.debug("Handle Get webdata is %s" % (webData))
signature = self.get_argument('signature', '')
timestamp = self.get_argument('timestamp', '')
nonce = self.get_argument('nonce', '')
echostr = self.get_argument('echostr', '')
token = test_weixin_token
if len(signature) == 0 or len(timestamp) == 0 or \
len(nonce) == 0 or len(echostr) == 0:
self.write('')
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
map(sha1.update, list)
hashcode = sha1.hexdigest()
#print "handle/GET func: hashcode, signature: ", hashcode, signature
log.debug("handle/GET func: hashcode, signature: %s, %s"%(hashcode, signature))
if hashcode == signature:
self.write(echostr)
else:
self.write('')
except Exception, Argument:
log.error(Argument)
self.write(Argument)
def post(self):
body = json.loads(self.request.body)
response = {'code': 0}
if body.has_key('songId'):
search_result = BaiduMusicSearch().search_song_byid(body['songId'])
response['searchResult'] = search_result
else:
response['code'] = -1
response['error'] = "not found song id."
json_data = json.dumps(response, ensure_ascii=False)
log.info(json_data)
self.write(json_data)
def http_post(self, url, data, header_type):
header = {'Content-Type': header_type}
try:
request = urllib2.Request(url=url, headers=header, data=data)
resp = urllib2.urlopen(request, timeout=self.__timeout).read()
return json.loads(resp)
except Exception, Argument:
log.error(Argument)
return None
def get_sound_by_album_id(self, os_type, pack_id, id, count = 20, sort = "asc", page = 1):
recommendation = {'code': 0}
res = self.album_browse(os_type, pack_id, id, count, sort, page)
if (res is not None) and res.has_key('tracks'):
recommendation['recommendation'] = []
track_list = res['tracks']
for track in track_list:
recommendation['recommendation'].append(self.__set_recommendation(track))
else:
recommendation = {'code': -1}
recommendation['error'] = 'no data'
#log.debug(json.dumps(recommendation, ensure_ascii = False).encode('utf-8'))
print json.dumps(recommendation, ensure_ascii = False).encode('utf-8')
return json.dumps(recommendation, ensure_ascii = False).encode('utf-8')
def find_track(self, os_type, pack_id, param):
recommendation = {'code': 0}
res = self.search_tracks(os_type, pack_id, param)
if (res is not None) and res.has_key('tracks'):
recommendation['recommendation'] = []
for track in res['tracks']:
recommendation['recommendation'].append(self.__set_recommendation(track))
else:
recommendation = {'code': -1}
recommendation['error'] = 'no data'
return json.dumps(recommendation, ensure_ascii = False).encode('utf-8')
def update_product(fournisseur_product_infos, incwo_product_infos):
update_infos = {}
try:
PRODUCT_ID = incwo_product_infos["id"]
PRODUCT_REF = fournisseur_product_infos["reference"]
except KeyError:
log.error("Incwo product with no ID or ref associated")
raise ValueError()
try:
# Si produit considere comme vitrine : on annule la comparaison prix et category en mettant les champs aux memes valeurs
if not compareValues(incwo_product_infos["product_category_id"],VITRINE_CATEGORY_ID):
log.warning("Pas de mise a jour du prix du produit {} (Produit categorisé comme en vitrine)".format(PRODUCT_REF))
incwo_product_infos["product_category_id"] = fournisseur_product_infos["product_category_id"]
fournisseur_product_infos["price"] = incwo_product_infos["price"]
except KeyError:
log.error("Incwo product with no category_ID associated")
raise ValueError()
for key in INCWO_PARAMS:
if not key in fournisseur_product_infos:
log.error("Product "+fournisseur_product_infos["name"]+" : fournisseur info incomplete! Missing "+key)
raise ValueError()
elif not key in incwo_product_infos:
if key != 'barcode':
log.debug("incwo info incomplete, updating "+key)
update_infos[key]=fournisseur_product_infos[key]
elif (compareValues(fournisseur_product_infos[key],incwo_product_infos[key])):
log.debug("incwo info outdated, updating {}".format(key))
log.debug("Picata {} ; incwo_product_infos {}".format(fournisseur_product_infos[key], incwo_product_infos[key]))
update_infos[key]=fournisseur_product_infos[key]
if len(update_infos) > 0 :
log.debug("Update needed for product "+str(PRODUCT_ID))
xml = prepare_xml_product(update_infos)
url = "https://www.incwo.com/"+str(ID_USER)+"/customer_products/"+str(PRODUCT_ID)+".xml";
send_request('put', url, xml)
# else :
# log.debug("Product {} (id {}) infos up to date".format(fournisseur_product_infos["name"],PRODUCT_ID))
manage_stock_movement(fournisseur_product_infos, PRODUCT_ID, incwo_product_infos["product_category_id"])
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 run_sql_proc(self, body, funcname):
try:
content = {'code': 0}
if funcname == 'notread':
if(body.has_key('userid')):
userid = body['userid']
res_list = DataCenter().get_not_read_id_from_xdata(userid)
list_dict = []
for i in range(len(res_list)):
tmp = {}
tmp['id'] = res_list[i]['id']
list_dict.append(tmp)
content['collections'] = list_dict
else:
content['code'] = -1
content['error'] = 'userid is needed.'
elif funcname == 'content':
if (body.has_key('userid') and body.has_key('id')):
userid = body['userid']
id = body['id']
res_list = DataCenter().get_content_from_xdata(userid, id)
content['id'] = res_list[0]['id']
content['title'] = res_list[0]['title']
content['author'] = res_list[0]['author']
content['source'] = res_list[0]['datasource']
content['subject'] = res_list[0]['aidata'].split(lingx_split_str)
content['original'] = res_list[0]['originaldata'].split(lingx_split_str)
#??accesstime
#DataCenter().update_xdata(id, 'accesstime', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
else:
content['code'] = -1
content['error'] = 'userid and id are needed.'
elif funcname == 'status':
if (body.has_key('article_list')):
for item in body['article_list']:
#??accesstime
DataCenter().update_xdata(item['id'], 'accesstime', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
else:
content['code'] = -1
content['error'] = 'article_list is empty.'
else:
pass
#print content
log.debug(content)
self.write(tornado.escape.json_encode(content))
self.finish()
except Exception, Argument:
log.error(Argument)
self.finish(Argument)
def get_recommendation_tmp(self, os_type, pack_id):
recommendation = {'code': 0}
#??????
res = self.categories_human_recommend(os_type, pack_id)
for item in res:
#print "===>> category:", item['category_name'].encode("utf-8"), item['id']
if item['id'] != 8:
continue
category_id = item['id']
category_name = item['category_name']
print "====>>>> categor name, id:", category_name, category_id
#log.info("category_name:%s, category_id:%d"%(category_name, category_id))
#????tag
res = self.tags_list(os_type, pack_id, 0, category_id)
tag_names = []
for item in res:
tag_names.append(item['tag_name'])
# category + tag ????
recommendation['recommendation'] = []
recommendation['code'] = 0
cnt = 0
for item in tag_names:
"""
if cmp(item, u"????"):
#print "===>>> tag_name:", item.encode('utf-8')
print "===>>> tag_name:", item
continue
"""
print "===>>> tag_name:", item
res = self.albums_list(os_type, pack_id, category_id, item, 3)
if res.has_key('albums'):
tmp_list = res['albums']
for track in tmp_list:
print "==>>>album: ", track['album_title']
else:
pass
else:
recommendation = {'code': 0}
recommendation['error'] = 'no data'
return json.dumps(recommendation, ensure_ascii = False).encode('utf-8')