def queueRecvData(self, data): self.recvLock.acquire() self.frameBuffer.append(data) log(self, "received data from %s" % self.sid, 3) #log(self, "buffered frame: %s" % repr(data), 4) self.recvLock.release() self.waitLock.set()
def addBlog(self, title, cover_img_url, content, category, tag, user_id): ''' :param title: :param content: :param category: :param tag: :return: ''' title = title.replace('\'', '"') content = content.replace('\'', '"') if type(tag) is list: tag = ','.join(tag) sql = '''insert into blog(title, cover_img_url, content, category, tag, manager_id) values(%s, %s, %s, %s, %s, %s)''' try: self.cursor.execute( sql, (title, cover_img_url, content, category, tag, user_id)) self.db.commit() # tag_id = self.cursor.lastrowid return True except Exception as e: msg = 'On line {} - {}'.format(sys.exc_info()[2].tb_lineno, e) log('mysqlModel.addBlog').logger.error(msg) self.db.rollback() return False
def updateBlog(self, id, title, cover_img_url, content, category, tag, user_id): ''' :param id: :param title: :param cover_img_url: :param content: :param category: :param tag: :return: ''' title = title.replace('\'', '"') content = content.replace('\'', '"') sql = '''update blog set title='{title}', content='{content}', cover_img_url='{cover_img_url}', category='{category}', tag='{tag}' where id={id} and manager_id={user_id} '''.format( id=id, title=title, cover_img_url=cover_img_url, category=category, tag=tag, content=content, user_id=user_id) try: self.cursor.execute(sql) self.db.commit() return True except Exception as e: msg = 'On line {} - {}'.format(sys.exc_info()[2].tb_lineno, e) log('mysqlModel.updateBlog').logger.error(msg) self.db.rollback() return False
def deleteCategory(self, category_id, user_id): ''' @description: @param {type} @return: ''' sql = '''delete from category where id=%s and manager_id=%s ''' % ( category_id, user_id) sql_tag = '''delete from tag where category_id=%s and manager_id=%s ''' % ( category_id, user_id) sql_category_name = '''select name from category where id={category_id} '''.format( category_id=category_id) sql_blog = '''update blog set visible=0 where category='%s' and manager_id={user_id} '''.format( category_id=category_id, user_id=user_id) try: self.cursor.execute(sql_category_name) one = self.cursor.fetchone() category_name = one[0] self.cursor.execute(sql) self.db.commit() self.cursor.execute(sql_tag) self.db.commit() self.cursor.execute(sql_blog % category_name) self.db.commit() return True except Exception as e: msg = 'On line {} - {}'.format(sys.exc_info()[2].tb_lineno, e) log('mysqlModel.deleteCategory').logger.error(msg) self.db.rollback() return False
def deactivateCB(self, msg, source): log("deactivating") for track in LiveUtils.getTracks(): for slot in track.clip_slots: if slot.clip != None: slot.clip.muted = True log("deactivated")
def getNextExecutedTrade(self, direction, tcond=tradeCondition.REGULAR.value): emptyOrderBookSide = False tradeVolume = self.getTradeSize() if (direction == Direction.DOWN): tradePrice = self.bid if (tradeVolume > self.bidSize): # Cleared out the book on this side - need to generate a new quote line. emptyOrderBookSide = True else: # Reduce the available shares on this side of the book. self.bidSize = self.bidSize - tradeVolume else: tradePrice = self.ask if (tradeVolume > self.askSize): # Cleared out the book on this side - need to generate a new quote line. emptyOrderBookSide = True else: # Reduce the available shares on this side of the book. self.askSize = self.askSize - tradeVolume log( "trading %s at $%s for %s shares" % (self.ticker, tradePrice, tradeVolume), LogLevel.DEBUG) self.lastPrice = tradePrice self.lastSize = tradeVolume self.lastTradeCondition = tcond return (tradeVolume, tradePrice, emptyOrderBookSide)
def refresh_state(self): log("Refreshing state") self.add_clip_listeners() self.add_mixer_listeners() self.add_scene_listeners() self.add_tempo_listener() self.add_overdub_listener() self.add_tracks_listener() self.add_device_listeners() self.add_transport_listener() trackNumber = 0 clipNumber = 0 for track in self.song().tracks: bundle = OSC.OSCBundle() bundle.append("/live/name/track", (trackNumber, str(track.name))) for clipSlot in track.clip_slots: if clipSlot.clip != None: bundle.append("/live/name/clip", (trackNumber, clipNumber, str(clipSlot.clip.name), clipSlot.clip.color)) clipNumber = clipNumber + 1 clipNumber = 0 trackNumber = trackNumber + 1 self.oscEndpoint.sendMessage(bundle) self.trBlock(0, len(self.song().tracks))
def process_(message): try: temp = message.getContent() # 判断第一个字是否是“绑” if temp[0] == u"绑": fromQQ = str(message.getPersonQQ()) # msg为一卡通账号 msg = temp[2:] log(moduleName=BindCardModule.name, level="info", content=str(fromQQ) + " " + msg) # 判断当前QQ账号是否已经绑定过 if getinfo(fromQQ)[0] == 0: # 判断当前一卡通是否在all_info.txt内 if insertinfo(fromQQ, msg): message.setContent(u"绑定成功!") send(message, True) else: message.setContent(u"请检查您的一卡通账号!") send(message, True) else: message.setContent(u"您已注册!") send(message, True) else: return except Exception as e: if isinstance(e, Block): raise Block() log(moduleName=BindCardModule.name, level="error", content=e.message) return
def slot_changed(self): slot_index = self.track.playing_slot_index self.playing_scene_index = slot_index #if slot_index == -2: #no slot playing #log("Playing Slot Index: " + str(slot_index)) # CLEAN UP ANY OLD LISTENERS if len(self.clip_listener) > 0: for old_clip in self.clip_listener: if old_clip.playing_position_has_listener( self.clip_listener[old_clip]) == 1: old_clip.remove_playing_position_listener( self.clip_listener[old_clip]) self.clip_listener = {} #MAKE SURE WE HAVE A CLIP AND ASSIGN A PLAYING POSITION LISTENER TO IT slot = self.track.clip_slots[slot_index] if slot.has_clip: clip = slot.clip callback = lambda: self.playing_position() dir(clip) if self.clip_listener.has_key(clip) != 1: self.clip_listener[clip] = callback clip.add_playing_position_listener(callback) log(str(clip.name)) #copy the triggers onto the clip we're watching self.active_triggers = triggers.copy() else: log("No Clip Playing in Track " + str(self.trackID)) self.clip_listener = {}
def eval_alone(config): data = model_data.read_data(config.data, config, read_train=False) data = data.test seq_rnn_model = SequenceRNNModel(config.n_input_fc, config.num_views, config.n_hidden, config.decoder_embedding_size, config.num_classes+1, config.n_hidden, batch_size=data.size(), is_training=False, use_lstm=config.use_lstm, use_attention=config.use_attention, use_embedding=config.use_embedding, num_heads=config.num_heads) seq_rnn_model.build_model("train") tf_config = tf.ConfigProto() tf_config.gpu_options.allow_growth = True with tf.Session(config=tf_config) as sess: #config.gpu_options.per_process_gpu_memory_fraction = 0.3 saver = tf.train.Saver() saver.restore(sess, get_modelpath(config.weights)) acc, loss, predictions, labels = _test(data, seq_rnn_model, sess) log(config.log_file, "TESTING ACCURACY {}".format(acc)) predictions = [x-1 for x in predictions] labels = [x-1 for x in labels] import Evaluation_tools as et eval_file = os.path.join(config.log_dir, '{}.txt'.format(config.name)) et.write_eval_file(config.data, eval_file, predictions, labels, config.name) et.make_matrix(config.data, eval_file, config.log_dir)
def checkPump(): log("checking if time to recycle pump") now_time = datetime.datetime.now().strftime('%H:%M') if now_time == morning or now_time == lunch or now_time == afternoon or now_time == dinner or now_time == night: pump(True) sleep(runtime) pump(False)
def open_pavucontrol(): ''' Uses subprocess to open the PulseAudio Volume Control application. :return: No return value. ''' log(INFO, "open_pavucontrol", "Opening pavucontrol") returned_value = sp.Popen("pavucontrol", shell=True, stdout=sp.PIPE)
def is_mounted(self, mount_point): log(6, "is_mounted") # TODO: we should cache this once we start # looking for mount errors try: fh = open("/proc/mounts", "r") for line in fh: test_mount_point = line.split()[1] try: if os.path.samefile(mount_point, test_mount_point) == True: return True except OSError, ex: # Permission denied. Happens if we compare the file # with a mountpoint we don't have permission to. # The only instance I know where this is possible # is with fuse mountpoints where allow_root is not # enabled # 13 = Permission denied if ex.errno != 13: # reraise the error raise finally: fh.close() return False
def process_module_list(input_list): ''' This function is passed a string input from "pactl list modules short" and organizes it as needed. :param input_list: A string with at least 1 line, and at least 2 different items separated by tabs. :return: A list of shortened names of applicable modules. ''' processed_list = process_list(input_list) devices = [] for item in processed_list: if len(item) < 2: log(WARNING, "process_module_list", "Module with less than 2 items found: \"" + str(item) + "\"") # If the item is some sort of null sink (because it could be made via this program): elif item[1] == "module-null-sink": temp = process_module(item, "sink_name") devices.append(temp) # If the item is some sort of loopback (because it could be made via this program): elif item[1] == "module-loopback": temp = process_module(item, "sink", "source") devices.append(temp) # If the item is some sort of null source (because it could be made via this program): elif item[1] == "module-null-source": temp = process_module(item, "source_name") devices.append(temp) # If the item is some sort of remapped source (because it could be made via this program): elif item[1] == "module-remap-source": temp = process_module(item, "source_name", "master") devices.append(temp) else: # If its not any of the modules listed above, this program doesnt care about it. pass return devices
def test(config): is_training = False with tf.device('/gpu:0'): pointclouds_pl, labels_pl = MODEL.placeholder_inputs( config.batch_size, config.num_points) is_training_pl = tf.placeholder(tf.bool, shape=()) # simple model pred, end_points = MODEL.get_model(pointclouds_pl, is_training_pl, NUM_CLASSES=config.num_classes) loss = MODEL.get_loss(pred, labels_pl, end_points) # Add ops to save and restore all the variables. saver = tf.train.Saver() # Create a session tf_config = tf.ConfigProto() tf_config.gpu_options.allow_growth = True tf_config.allow_soft_placement = True tf_config.log_device_placement = True sess = tf.Session(config=tf_config) ld = config.log_dir ckptfile = os.path.join(ld, config.snapshot_prefix + str(config.weights)) saver.restore(sess, ckptfile) log(config.log_file, "Model restored.") ops = { 'pointclouds_pl': pointclouds_pl, 'labels_pl': labels_pl, 'is_training_pl': is_training_pl, 'pred': pred, 'loss': loss } eval_one_epoch(config, sess, ops)
def add_object(self, instance): # find all the functions in the object for member in inspect.getmembers(instance): if inspect.ismethod(member[1]): log(6, "XMLRPC Server Registered %s.%s" % \ (instance.__class__.__name__, member[0])) self.functions[member[0]] = member[1]
def process(message): session = Session() try: if SendBlessingModule.checkTime(): waitqq = redisConnection.lpop(REDIS_BLESSING_WAITING_QUEUE) if not waitqq: return blessQuery = session.query(BlessingModal).order_by(func.rand()).limit(1).first() if blessQuery: log(moduleName=SendBlessingModule.name,content=message.getContent()) renderblessing = renderBlessing.RenderBlessing(int(waitqq[1:]), blessQuery.fromqq, blessQuery.content) url = renderblessing.render().get_url() message = Message() if waitqq[0]=="0": message.setTargetQQ(SMALLWEI_QQ) else: message.setTargetQQ(SMALLWEI2016_QQ) message.setSubType(1) message.setPersonQQ(int(waitqq[1:])) message.setContent(SendBlessingModule.BLESSING_REPLY.format(url, SendBlessingModule.BLESSING_TITLE, SendBlessingModule.BLESSING_CONTENT, SendBlessingModule.BLESSING_LOGO)) send(message,True) else: return else: return except Exception as e: if isinstance(e,Block): raise Block() log(moduleName=SendBlessingModule.name,level="error",content=e.message) return finally: session.close()
def handleMsg(self, connection, cmd, msg): if(cmd == 30 and connection.authLevel > 0): # send chat log(self, "relaying chat from from %s to skype: %s" % (connection, msg[2:]), 2) self.chat.SendMessage(msg[2:]) return # break here so that we don't get echo # messages that we don't handle get passed to the usual handler CC_Server.handleMsg(self, connection, cmd, msg)
def propose_wall(self, game, player): best_total = -99 game_event = GameEvent("SPACE") for x in range(9): for y in range(9): side = "TOP" log("propose_wall ", x, y, side) placed = game.place_wall(player, x, y, side) if placed: total = self.evaluate_game(game, player) player.unplayed_wall_count = player.unplayed_wall_count + 1 game.unset_wall(game.board, x, y, side) if total > best_total: best_total = total game_event.x = x game_event.y = y game_event.section = side game_event.move_mode = "WALL" side = "BOTTOM" log("propose_wall ", x, y, side) placed = game.place_wall(player, x, y, side) if placed: total = self.evaluate_game(game, player) player.unplayed_wall_count = player.unplayed_wall_count + 1 game.unset_wall(game.board, x, y, side) if total > best_total: best_total = total game_event.x = x game_event.y = y game_event.section = side game_event.move_mode = "WALL" side = "LEFT" log("propose_wall ", x, y, side) placed = game.place_wall(player, x, y, side) if placed: total = self.evaluate_game(game, player) player.unplayed_wall_count = player.unplayed_wall_count + 1 game.unset_wall(game.board, x, y, side) if total > best_total: best_total = total game_event.x = x game_event.y = y game_event.section = side game_event.move_mode = "WALL" side = "RIGHT" log("propose_wall ", x, y, side) placed = game.place_wall(player, x, y, side) if placed: total = self.evaluate_game(game, player) player.unplayed_wall_count = player.unplayed_wall_count + 1 game.unset_wall(game.board, x, y, side) if total > best_total: best_total = total game_event.x = x game_event.y = y game_event.section = side game_event.move_mode = "WALL" log("propose_wall event=", game_event) return (best_total, game_event)
def addReply(self, comment_id, user_id, content, manager_id, blog_id, replied_id=None, replied_user_id=None): ''' ''' sql = '''insert into reply(comment_id, user_id, content, replied_id, replied_user_id) values(%s, %s, %s, %s, %s)''' try: self.cursor.execute( sql, (comment_id, user_id, content, replied_id, replied_user_id)) self.db.commit() reply_id = self.cursor.lastrowid reply_message = self.getReply(reply_id=reply_id, manager_id=manager_id) if self.updateCommentReplyCount( manager_id=manager_id, comment_id=comment_id, method='add') and self.updateBlogCommentCount( manager_id=manager_id, blog_id=blog_id): if reply_message is not None: return reply_message else: return None except Exception as e: msg = 'On line {} - {}'.format(sys.exc_info()[2].tb_lineno, e) log('mysqlModel.addReply').logger.error(msg) self.db.rollback() return None
def _run(self, testId=None): self.id = testId setUpTestId = (testId or 'root') + '-setUp' if not self.isRoot(): self.setLog("setUp") if self.children: for kid in self.children: self.test(0, kid) else: try: try: self.setUp() except: desc = self.classDesc() + ' - setUp' xInfo = self.__excInfo() log( 2, 'test %s setUp: error ====================================' % desc) self.info.result.addSetUpError(setUpTestId, desc, xInfo) self.setUpFailed = True try: self.run() finally: # KeyboardInterrupt must only be here... if not self.isRoot(): self.setLog('tearDown') self.tearDown() except: print 'Error running test suite' traceback.print_exc() xInfo = self.__excInfo() self.logStack(xInfo)
async def display_prefix(self, channel, new_prefix=False): description = f"**{self.name}'s {'New ' if new_prefix else ''}Prefix:** `{self.prefix}`\n\n" description += f"`{self.prefix} prefix <new_prefix>`" if not new_prefix else '' await simple_bot_response(channel, description=description) log("prefix", f"{'New Prefix: ' if new_prefix else ''}{vars(self)}")
def getReplyList(self, manager_id, sort_by='update_time'): ''' ''' sql = '''select a.id, a.comment_id, a.replied_id, a.replied_user_id, a.user_id, a.content, b.nickname as reply_nickname, c.nickname as user_nickname, a.like_count, e.title, a.update_time, d.content as comment_content, e.id as blog_id, c.picture as picture, c.author as user_admin from reply a left join user b on a.replied_user_id = b.id join user c on a.user_id = c.id join comment d on a.comment_id = d.id join blog e on d.blog_id = e.id where e.manager_id = {manager_id}; '''.format( manager_id=manager_id) try: self.cursor.execute(sql) results = self.cursor.fetchall() if not results or len(results) <= 0: return None reply_list = [] for res in results: temp = {} temp['id'] = res[0] temp['comment_id'] = res[1] temp['replied_id'] = res[2] if res[6] == None: temp['reply_nickname'] = '' else: temp['reply_nickname'] = res[6] temp['user_id'] = res[4] temp['user_nickname'] = res[7] temp['content'] = res[5] temp['like_count'] = res[8] temp['title'] = res[9] temp['update_time'] = res[10].strftime('%Y-%m-%d %H:%M:%S') temp['comment_content'] = res[11] temp['blog_id'] = res[12] temp['user_picture'] = res[13] temp['user_admin'] = res[14] reply_list.append(temp) if sort_by == 'update_time': reply_list = sorted(reply_list, key=lambda x: x['update_time']) reply_list.reverse() elif sort_by == 'id': reply_list = sorted(reply_list, key=lambda x: x['id']) reply_list.reverse() elif sort_by == 'like_count': reply_list = sorted(reply_list, key=lambda x: x['like_count']) reply_list.reverse() return reply_list except Exception as e: msg = 'On line {} - {}'.format(sys.exc_info()[2].tb_lineno, e) log('mysqlModel.getReplyList').logger.error(msg) self.db.rollback() return None
def __get_web_page(url): resp = requests.get(url, cookies={'over18': '1'}, verify=True) if resp.status_code != 200: log(getframeinfo(currentframe()), 'Invalid url:', resp.url) return None else: return resp.text
def getComment(self, comment_id, manager_id): ''' sort_by: 'update_time', 'blog_id', 'id' ''' sql = '''select a.id, a.blog_id, a.user_id, c.nickname, a.content, a.like_count, a.reply_count, a.update_time, b.title, c.picture as user_picture, c.author as user_admin from comment a join blog b on a.blog_id=b.id join user c on a.user_id=c.id where b.manager_id={manager_id} and a.id={comment_id} '''.format( manager_id=manager_id, comment_id=comment_id) try: self.cursor.execute(sql) res = self.cursor.fetchone() if not res: return None temp = {} temp['id'] = res[0] temp['blog_id'] = res[1] temp['user_id'] = res[2] temp['nickname'] = res[3] temp['content'] = res[4] temp['like_count'] = res[5] temp['reply_count'] = res[6] temp['update_time'] = res[7].strftime('%Y-%m-%d %H:%M:%S') temp['blog_title'] = res[8] temp['user_picture'] = res[9] temp['user_admin'] = res[10] temp['reply_list'] = [] return temp except Exception as e: msg = 'On line {} - {}'.format(sys.exc_info()[2].tb_lineno, e) log('mysqlModel.getComments').logger.error(msg) self.db.rollback() return None
def deleteBlog(self, blog_id, user_id): ''' :param blog_id: :param user_id: :return: ''' sql_exist = 'select * from blog where id=%s and manager_id=%s ' % ( blog_id, user_id) sql = '''delete from blog where id=%s and manager_id=%s ''' % (blog_id, user_id) try: self.cursor.execute(sql_exist) one = self.cursor.fetchone() if one and len(one) > 0: self.cursor.execute(sql) self.db.commit() return True else: return False except Exception as e: msg = 'On line {} - {}'.format(sys.exc_info()[2].tb_lineno, e) log('mysqlModel.deleteBlog').logger.error(msg) self.db.rollback() return False
def on_request(self, ch, method, props, body): validRequestTypes = ['shutdown', 'change_frequency'] request = json.loads(body) if (request['type'] in validRequestTypes): response = {'status': 'true'} else: response = {'status': 'false'} return ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties( correlation_id=props.correlation_id), body=json.dumps(response)) ch.basic_ack(delivery_tag=method.delivery_tag) if (request['type'] == 'shutdown'): log("Received RPC shutdown instruction", LogLevel.INFO) self.onExit() self.stop_callback() if (request['type'] == 'change_frequency'): log("Received Frequency change to %s" % (request['frequency'])) frequency = request['frequency'] self.change_freq_callback(frequency) else: pass
def update_display(self): """ This function is run every 100ms, so we use it to initiate our Song.current_song_time listener to allow us to process incoming OSC commands as quickly as possible under the current listener scheme. """ ###################################################### # START OSC LISTENER SETUP if self.basicAPI == 0: # By default we have set basicAPI to 0 so that we can assign it after # initialization. We try to get the current song and if we can we'll # connect our basicAPI callbacks to the listener allowing us to # respond to incoming OSC every 60ms. # # Since this method is called every 100ms regardless of the song time # changing, we use both methods for processing incoming UDP requests # so that from a resting state you can initiate play/clip triggering. try: doc = self.song() except: log('could not get song handle') return try: self.basicAPI = LiveOSCCallbacks.LiveOSCCallbacks(self._LiveOSC__c_instance, self.oscEndpoint) # Commented for stability self.time = 0 doc.add_current_song_time_listener(self.current_song_time_changed) except Exception, e: self.oscEndpoint.send('/remix/echo', 'setting up basicAPI failed: %s' % e) log('setting up basicAPI failed: %s' % e); return
def deleteComment(self, comment_id, user_id, blog_id, manager_id): ''' ''' ###删除评论 ###删除该评论下的回复 sql = '''delete from comment where id={comment_id} and blog_id={blog_id} and user_id={user_id} '''.format( comment_id=comment_id, blog_id=blog_id, user_id=user_id) sql_reply = '''delete from reply where comment_id={comment_id} '''.format( comment_id=comment_id) try: self.cursor.execute(sql) self.db.commit() self.cursor.execute(sql_reply) self.db.commit() ###更新博客评论数 if self.updateBlogCommentCount(manager_id=manager_id, blog_id=blog_id): return True else: return False except Exception as e: msg = 'On line {} - {}'.format(sys.exc_info()[2].tb_lineno, e) log('mysqlModel.deleteComment').logger.error(msg) self.db.rollback() return False
def addTag(self, category, tag, user_id): ''' :param category: :param tag: :return: ''' category_id = self.getCategoryId(category=category, user_id=user_id) if category_id is None: return False sql_exist = '''select * from tag where tag='{tag}' and category_id={category_id} and manager_id={user_id}; '''.format( tag=tag, category_id=category_id, user_id=user_id) self.cursor.execute(sql_exist) one = self.cursor.fetchone() if one is not None: return True sql = '''insert into tag(tag, category_id, manager_id) VALUES(%s, %s, %s) ''' try: self.cursor.execute(sql, (tag, category_id, user_id)) self.db.commit() # tag_id = self.cursor.lastrowid return True except Exception as e: msg = 'On line {} - {}'.format(sys.exc_info()[2].tb_lineno, e) log('mysqlModel.addTag').logger.error(msg) self.db.rollback() return False
def configure_by_ssh(ips): ports = ([ 8888, 8889, 29000, 28000, 28500, 22000, 25000, 21100, 28600, 25123, 27501 ] + [ 9000 + i for i in range(nb_cws_per_instance * nb_cws_instances) ] + [26000 + shard for shard in range(20)] + [21000 + shard for shard in range(20)]) public_ip = ips['public'] private_ip = ips['private'] log('success', 'Configuring instance %s by SSH...' % ip) command_1 = 'ssh -o "StrictHostKeyChecking no" -i "{pem}.pem" ec2-user@{ip} "{command}"'.format( pem=self.state_dict['keypair_name'], ip=public_ip, command=("sudo yum update -y && " + "sudo yum install -y docker && " + "sudo service docker start && " + "sudo usermod -a -G docker ec2-user && " + "exit")) command_2 = 'ssh -o "StrictHostKeyChecking no" -i "{pem}.pem" ec2-user@{ip} "{command}"'.format( pem=self.state_dict['keypair_name'], ip=public_ip, command=( 'docker login -u \\"{u}\\" -p \\"{p}\\"'.format( u=docker_login, p=docker_password) + " && " + "docker run -d --privileged --net=host " + " ".join("-p {p}:{p}".format(ip=private_ip, p=port) for port in ports) + " " + "-e CMS_contest=%d " % cms_contest + "totorigolo/cms_cb")) os.system(command_1) os.system(command_2) log('success', 'Instance %s configured by SSH.' % public_ip)
def checkWaterQuality(): ser.flushInput() ser.flushOutput() log("check water quality time") now_time = datetime.datetime.now().strftime('%H:%M') time_list = now_time.split(':') time_list = [int(i) for i in time_list] if time_list[0] == int(morning.split(':')[0]) - 2 or time_list[0] == int( dinner.split(':')[0]) - 2: log("adjust water quality", "debug") checkSensors() sleep(5) ec = getEC() sleep(5) if EC_MIN < ec < EC_MAX: log("ec value is in range") result = True elif ec < EC_MIN: log("ec value is below range") addA() sleep(30) addB() sleep(30) elif ec > EC_MAX: log("ec value is above range") addWater(True) sleep(30) addWater(False) sleep(120)
def addWater(switch): if switch: log("send add water START to serial") writeToSerial('won') else: log("send add water STOP to serial") writeToSerial('wof')
def send(self, data): self.sendLock.acquire() self.sendBuffer.write(data) if(self.sendSock): self.flush() else: log(self, "buffered send to: %s" % self.sid, 3) self.sendLock.release()
def add_track_device_listeners(self,tid,track): cbt = lambda :self.track_device_listener(tid,track) if self.mlisten["devices"].has_key(track) != 1: self.mlisten["devices"][track] = cbt track.add_devices_listener(cbt) log("Added device listener in track " + str(tid));
def find_connected_spaces(self, graph, victory_row): log("find_connected_spaces for row ", victory_row) if victory_row == 8: space_distances = self.space_distances_p1 else: space_distances = self.space_distances_p2 connected_spaces = space_distances.keys() return connected_spaces
def csi_dispatch(self): if(self.privateMarker in privateMarkers \ and self.char in privateMarkers[self.privateMarker]): params = [int(i) if len(i) > 0 else 0 for i in self.paramStr.split(';')] cmdName = privateMarkers[self.privateMarker][self.char] self.putCommand(Command(cmdName, params)) else: log(self, 'Unrecognized CSI code: %r' % self.debugStr)
def output_graph(self, graph): for x in range(9): for y in range(9): space = self.get(x, y) if graph.has_key(space): log(x, y, "->", graph[space]) else: log(x, y, "->", None)
def handleOutput(self, stream): parser = CommandParser(stream) while True: command = parser.getCommand() if(command == None): return log(self, "cmd: %r" % command, 4) self.terminal.handleCmd(command)
def esc_dispatch(self): cmd = self.privateMarker + self.char if(cmd in escapeCodeStrings): self.putCommand(Command(escapeCodeStrings[cmd], None)) elif(cmd[0] in escapeCodeStrings): self.putCommand(Command(escapeCodeStrings[cmd[0]], [cmd[1]])) else: log(self, 'Unrecognized ESC code: %r' % self.debugStr)
def find_shortest_path(self, player, board): log("find_shortest_path for " + str(player)) graph = board.create_graph() start = player.position end = board.get(0, player.win_row) path = [] shortest_path = self.find_shortest_path2(graph, start, end, path) return shortest_path
def setSendSock(self, sock): self.sendLock.acquire() self.sendSock = sock log(self, "got send sock for %s" % self.sid, 3) if(self.sendBuffer.tell()): self.flush() self.lastResponseTime = time.time() self.sendLock.release()
def sendUserData(self, target): self.accessLock.acquire() log(self, "sending user data to %s" % target.msg(), 3) message = "200" # user data list msg for connection in self.connections: message += "|%s|%s|%s" % (connection.addr[1], connection.font, connection.avatar) target.send(message) self.accessLock.release()
def update_one(self, col_name: str, _id: str, segments, pos) -> None: result = self.db[col_name].update_one( {'_id': _id}, {'$set': { 'segments': segments, 'pos': pos }}) log(getframeinfo(currentframe()), 'Update result : ', result.matched_count)
def __call__(self, *args, **kwargs): args[0].stop() args[0].start() log(moduleName=RemoteTerminalModule.name, content="[stop]" + args[0].name) log(moduleName=RemoteTerminalModule.name, content="[start]" + args[0].name) return True
def send(message, blocked=False): log(moduleName="Sender", content=message.getJsonStr()) redisConnection.rpush(switchoutqueue(message.getTargetQQ()), message.getDataStream()) if blocked: raise Block() else: return
def handleInput(self, sock, stream): self.terminal.sendInit(sock) while True: char = chr(int(sock.recvFrame())) if(char == '\r'): char = '\n' log(self, "recvd: %r" % char, 4) stream.write(char) stream.flush()
def flush(self): self.sendBuffer.seek(0) try: HTTP_Server.writeHTTP(self.sendSock, 200, {}, "%s\r\n%s" % (self.sid, self.sendBuffer.read())) except: log(self, "error flushing http send: %s" % self.sid) self.sendBuffer = StringIO() self.sendSock = None log(self, "sent data to: %s" % self.sid, 3)
def is_connected(self, space, victory_row): log("is_connected") connected = False graph = self.graph connected_spaces = self.find_connected_spaces(graph, victory_row) if space in connected_spaces: connected = True del connected_spaces[:] return connected
def dispatch(self, message, source): """Sends decoded OSC data to an appropriate calback""" address = message[0] try: self.callbacks[address](message, source) except Exception, e: log("Callback failed: %s" % e) import traceback trace = traceback.format_exc() log(trace)
def broadcast(self, msg): lost = [] for sock in self.connections: try: sock.send(msg) except: lost.append(sock) for sock in lost: self.connections.remove(sock) log(self, "Removed connection: %r" % sock)
def sendChanMsg(s, chan, message): try: messageTemp = ("PRIVMSG #" + str(chan.strip()) + " :" + message) s.send(messageTemp.strip() + "\r\n") sleep(0.5) time = datetime.now().strftime('%d-%m-%Y %H:%M:%S') toLog = "Forcebotti: " + message.decode('utf8') log(toLog, chan) except: print "sendmessage error"
def sendMessage(s, message): try: sleep(0.1) messageTemp = "PRIVMSG #" + str(CHANNEL) + " :" + str(message) s.send(messageTemp + "\r\n") time = datetime.now().strftime('%d-%m-%Y %H:%M:%S') toLog = "Forcebotti: " + message.decode('utf8') log(toLog, CHANNEL) except: print "sendmessage error"
def build_midi_map(self, midi_map_handle): #self.refresh_state() """parameter=InputControlElement(MIDI_CC_TYPE,1,8)""" """self.parameter=self.song().tracks[0].devices[0].parameters[5].value channel=0 cc=8 Live.MidiMap.map_midi_cc(midi_map_handle, parameter, channel, cc, Live.MidiMap.MapMode.absolute, True) Live.MidiMap.forward_midi_cc(self._LiveOSC__c_instance.handle(), midi_map_handle, channel, cc)""" log("entro a build midi map") self.add_device_listeners()
def __init__(self): CC_Server.__init__(self) skypePrefs = { "room_id": '#mattwitkowski/$cbd88fa129f3d1f0', \ } self.prefs.update(skypePrefs) self.skype = Skype4Py.Skype(Events=self) for chat in self.skype.Chats: if(chat.Name == self.prefs["room_id"]): self.chat = chat log(self, "listening to %s" % self.prefs["room_id"])
def recv(self, count): data = '' while(len(data) < count): chunk = self.sock.recv(count) if(not chunk): return '' data += chunk data = data.replace('\x00', '') data = data.replace('\xFF', '') log(self, "recieved data from WebSocket: %r" % data, 4) return data
def newSession(self, sock, addr): self.accessLock.acquire() newSID = addr[1] newSession = HTTP_Server.HTTP_Session(newSID) self.sessions.append(newSession) pingThread = threading.Thread(None, self.pingLoop, "pingLoop", (newSession,)) pingThread.setDaemon(1) pingThread.start() self.accessLock.release() log(self, "new http session: %s" % newSID, 3) return newSession
def __init__(self, c_instance): self._LiveOSC__c_instance = c_instance self.basicAPI = 0 self.oscEndpoint = RemixNet.OSCEndpoint() self.oscEndpoint.send('/remix/oscserver/startup', 1) log("LiveOSC initialized") # Visible tracks listener if self.song().tracks_has_listener(self.refresh_state) != 1: self.song().add_tracks_listener(self.refresh_state)
def add_clip_listeners(self): self.rem_clip_listeners() tracks = self.getslots() for track in range(len(tracks)): for clip in range(len(tracks[track])): c = tracks[track][clip] if c.clip != None: self.add_cliplistener(c.clip, track, clip) log("ClipLauncher: added clip listener tr: " + str(track) + " clip: " + str(clip)); self.add_slotlistener(c, track, clip)
def clip_changestate(self, clip, x, y): log("Listener: x: " + str(x) + " y: " + str(y)); playing = 1 if clip.is_playing == 1: playing = 2 if clip.is_triggered == 1: playing = 3 self.oscEndpoint.send('/live/clip/info', (x, y, playing))