def too_long(n): bot.formatter.send_failure( uid, "Your {} text is too long, it must be shorter " "than {} characters. Please try again.".format( property_name, n)) util.wait(bot, update) return admin.edit_bot(bot, update, chat_data, to_edit)
def main(args): base_histos = [util.get_tobject(args, r) for r in args.base_histos] util.validate_hists(args.base_histos, base_histos) base_histos = [util.resize_histo(args, util.get_tobject(args, r)) for r in args.base_histos] cut_histos = [util.get_tobject(args, r) for r in args.cut_histos] util.validate_hists(args.cut_histos, cut_histos) cut_histos = [util.resize_histo(args, util.get_tobject(args, r)) for r in args.cut_histos] canvas = ROOT.TCanvas("canvas", "Canvas", 250,100,700,500) all_histos = [] for i, (base_histo,cut_histo) in enumerate(zip(base_histos,cut_histos)): ratio = cut_histo.Clone() ratio.Divide(base_histo) ratio.SetLineColor(util.fillcolors(i)) ratio.SetLineWidth(2) if i == 0: util.style(args, canvas, ratio) ratio.Draw("PE") else: ratio.Draw("PE SAME") all_histos.append(ratio) if args.names: name = args.names[i] ratio.SetTitle(name) legend = ROOT.gPad.BuildLegend(*(args.legend_position + [""])) if args.title is not None: all_histos[0].SetTitle(args.title) canvas.Update() util.wait(args) util.write(args, canvas)
def tick(self): # Retrieve unread messages print('\n\nRetrieving unread messages...', end="") messages = list(self.reddit.get_unread(limit=None)) print('[DONE]') # Check messages for ignorances message_count = messages.__len__() print('Unread messages: ' + str(message_count)) for i in range(0, message_count): message = messages[i] # Update percent counter pcent = i / float(message_count) * 100 print('\rReading unread messages: [%d%%]' % pcent, end="") time.sleep(0.1) # Read the message body = str(message.body.strip().lower()) if body == self.KEYWORD_IGNORE: self.ignore(message.author) elif body == self.KEYWORD_UNIGNORE: self.unignore(message.author) # Mark as read message.mark_as_read() # Sleep for 30 seconds print('') util.wait(30)
def validatePage(self): password1 = hashlib.sha256(self.passwordLineEdit.text().encode("utf-8")).hexdigest() password2 = hashlib.sha256(self.passwordCheckLineEdit.text().encode("utf-8")).hexdigest() if password1 != password2 : QtGui.QMessageBox.information(self, "Create account","Passwords don't match!") return False email = self.EmailLineEdit.text() if not self.validateEmail(email) : QtGui.QMessageBox.information(self, "Create account", "Invalid Email address!") return False # check if the login is okay login = self.loginLineEdit.text().strip() self.client.loginWriteToFaServer("CREATE_ACCOUNT", login, email, password1) # Wait for client state to change. util.wait(lambda: self.client.state) if self.client.state == ClientState.REJECTED: QtGui.QMessageBox.information(self, "Create account", "Sorry, this Login is not available, or the email address was already used.") return False else: self.client.login = login self.client.password = password1 return True
def add_favorite(bot, update, item: Bot, callback_alert=None): user = User.from_update(update) uid = util.uid_from_update(update) mid = util.mid_from_update(update) from components.basic import main_menu_buttons main_menu_markup = ReplyKeyboardMarkup(main_menu_buttons(uid in settings.MODERATORS)) fav, created = Favorite.add(user=user, item=item) if created: Statistic.of(user, 'add-favorite', item.username) text = mdformat.love("{} added to your {}favorites.".format(fav.bot, '' if callback_alert else '/')) if callback_alert: update.callback_query.answer(text=text, show_alert=False) else: msg = util.send_md_message(bot, uid, text, to_edit=mid, reply_markup=main_menu_markup) mid = msg.message_id util.wait(bot, update) send_favorites_list(bot, update, to_edit=mid) else: text = mdformat.none_action( "{} is already a favorite of yours.{}".format(fav.bot, '' if callback_alert else ' /favorites')) if callback_alert: update.callback_query.answer(text=text, show_alert=False) else: util.send_md_message(bot, uid, text, reply_markup=main_menu_markup) return ConversationHandler.END
def roll(self, ms=300, times=10): for __ in range(times): util.wait(ms) print(self.proximity()) # Reference: # https://github.com/ControlEverythingCommunity/VCNL4010/blob/master/Python/VCNL4010.py
def run(self): for i in range(len(self.schedule)): while True: if util.timeBetween(time.localtime(), self.schedule[i], self.timeDelta): green.on() util.wait(1000) break
def selenium(): with closing(Firefox()) as browser: # with closing(PhantomJS()) as browser: browser.get(BOOKIE_URL) util.waitAndClick(browser, "//li[@id='sportMenuItem_391']") util.waitAndClick(browser, "//li[@id='cId_2462']") util.waitAndClick(browser, "//li[@id='league_13945']") util.wait(browser, "//span[contains(text(), 'Basketball / USA / NBA - Player points (-/+)')]") return [browser.page_source]
def download(url, page, output_dir): output_file = '%s/page-%d.html' % (output_dir, page) if os.path.isfile(output_file) and not util.OVERWRITE_DOWNLOAD: print '%s exists and not overwritable' % output_file return output_file util.wait() cmd = '%s --post-data page=%d %s -O %s -q' % ( util.WGET, page, url, output_file) print 'running command: %s' % cmd assert os.system(cmd) == 0 return output_file
def selenium(): with closing(Firefox()) as browser: browser.get(BOOKIE_URL) util.wait(browser, "//div[@id='contentHead']") #elements = browser.find_elements_by_xpath("//div[@class='member-name nowrap ']") links = getMatchLinks(browser.page_source) htmls = [] for link in links: browser.get(link) util.waitAndClick(browser, "//span[@class='inside', matches(@text, '*Player Performance*')]") util.wait(browser, "//div[@class='marketHolderExpanded']") htmls.append(browser.page_source) return htmls
def subscribe(self, topic=None, callBack=setTime): tempTopic = topic or self.defaultTopic self.mqttClient.set_callback(callBack) self.mqttClient.connect() self.mqttClient.subscribe(tempTopic.encode('UTF-8')) global acquired acquired = False print('Waiting for timing packet...') for i in range(0, 21): # Blocking wait for message self.mqttClient.check_msg() util.wait(5000) print('.') self.mqttClient.disconnect()
def main(args): f = ROOT.TFile(args.input) effs = [] puritys = [] signal_base = get_integral(f, args.variable, args.base_cut, args.signal_names) background_base = get_integral(f, args.variable, args.base_cut, args.background_names) effs.append(1.) puritys.append(signal_base / (signal_base + background_base)) for cut in args.cuts: this_signal = get_integral(f, args.variable, cut, args.signal_names) this_background = get_integral(f, args.variable, cut, args.background_names) this_eff = this_signal / signal_base this_purity = this_signal / (this_signal + this_background) effs.append(this_eff) puritys.append(this_purity) effs = array('d', effs) puritys = array('d', puritys) xvals = array('d', range(len(effs))) g_eff = ROOT.TGraph(len(effs), xvals, effs) g_eff.SetName("Efficiency") g_eff.SetTitle("Efficiency") g_purity = ROOT.TGraph(len(puritys), xvals, puritys) g_purity.SetName("Purity") g_purity.SetTitle("Purity") canvas = ROOT.TCanvas("canvas", "Canvas", 250, 100, 700, 500) g_eff.Draw("AL") g_eff.SetLineColor(ROOT.kGreen) util.style(args, g_eff) for i in range(len(effs)): g_eff.GetXaxis().SetBinLabel(g_eff.GetXaxis().FindBin(i), args.names[i]) g_purity.Draw("SAME") g_purity.SetLineColor(ROOT.kRed) legend = ROOT.gPad.BuildLegend(0.75, 0.75, 0.95, 0.95, "") canvas.Update() util.wait(args) util.write(args, canvas)
def tick(self): """ Reads up to 1000 new comments from /r/all/. """ # Get new comments from /r/all print('\n\nRetrieving comments...', end="") comments = list(self.reddit.get_comments('all', limit=None)) print('[DONE]') comment_count = comments.__len__() print('Comments to read: ' + str(comment_count)) for i in range(0, comment_count): comment = comments[i] # Update percent counter pcent = i / float(comment_count) * 100 print('\rReading comments: [%d%%]' % pcent, end="") time.sleep(0.1) # Parse words words = comment.body.split() permalink = None for word in words: if word.startswith('/u/'): # Get the redditor redditor = self.parse_redditor(word) if redditor is None: continue # Check to see if we've parsed this comment already permalink = comment.permalink if permalink in self.already_done: print('Comment was already read.') break # Notify the mentioned redditor self.notify('comment', redditor, permalink, comment.body, comment.author.name) self.record_mention(redditor.name, 'comment') # permalink will not be None if a user was notified if permalink is not None: self.already_done.append(permalink) # Wait 30 seconds print('') util.wait(30)
def main(args): hists = [[util.get_tobject(args, h.lstrip("-")) for h in hlist] for hlist in args.hstack] util.validate_hists(args.hstack, hists) hists = [[util.resize_histo(args, h) for h in hlist] for hlist in hists] canvas = ROOT.TCanvas("canvas", "Canvas", 250, 100, 700, 500) hstack = ROOT.THStack() for i, (hlist, hnames) in enumerate(zip(hists, args.hstack)): h = hlist[0] if len(hlist) > 1: for hadd, hname in zip(hlist[1:], hnames[1:]): #if "InTime-" in hname: # h.Add(hadd, 10. / 1837.) if hname.startswith("-"): h.Add(hadd, -1) else: h.Add(hadd) if args.area_normalize and h.Integral() > 1e-4: h.Scale(1. / h.Integral()) color = util.namecolors(args.names[i] if args.names else hnames[0]) if args.stack: h.SetFillColor(color) else: h.SetLineColor(color) h.SetLineWidth(3) if args.names: name = args.names[i] if args.nevent_in_legend: name += " (%i)" % int(h.Integral()) h.SetTitle(name) hstack.Add(h) drawstr = "HIST" if args.stack else "NOSTACK HIST" hstack.Draw(drawstr) util.style(args, canvas, hstack) if args.legend_position: legend = ROOT.gPad.BuildLegend(*(args.legend_position + [""])) if args.logy: canvas.SetLogy() box = util.draw_text(args) canvas.Update() util.wait(args) util.write(args, canvas)
def start(self, timeout=None): self.delegate.start() self.thread.start() if not wait(self.condition, lambda: self.opened or self.failed, timeout): raise Timeout() if self.failed: raise ConnectionFailed(*self.close_code)
def selenium(): with closing(Firefox()) as browser: browser.get(BOOKIE_URL) util.wait(browser, "//div[@id='contentHead']") #elements = browser.find_elements_by_xpath("//div[@class='member-name nowrap ']") links = getMatchLinks(browser.page_source) htmls = [] for link in links: browser.get(link) util.waitAndClick( browser, "//span[@class='inside', matches(@text, '*Player Performance*')]" ) util.wait(browser, "//div[@class='marketHolderExpanded']") htmls.append(browser.page_source) return htmls
def validatePage(self): password = self.passwordLineEdit.text().encode("utf-8") confim_password = self.passwordCheckLineEdit.text().encode("utf-8") if password != confim_password: QtGui.QMessageBox.information(self, "Create account", "Passwords don't match!") return False # Hashing the password client-side is not an effective way of ensuring security, but now we # have a database full of sha256(password) we have to start considering sha256(password) to # _be_ the user's password, and enforce a saner policy atop this. # # Soon. We promise. Hopefully before large scale identity theft takes place. hashed_password = hashlib.sha256(password.encode("utf-8")).hexdigest() email = self.EmailLineEdit.text() if not self.validateEmail(email): QtGui.QMessageBox.information(self, "Create account", "Invalid Email address!") return False login = self.loginLineEdit.text().strip() self.client.send({ "command": "create_account", "login": login, "email": email, "password": hashed_password }) # Wait for client state to change. util.wait(lambda: self.client.auth_state == ClientState.CREATED or self .client.auth_state == ClientState.REJECTED) if self.client.auth_state == ClientState.REJECTED: QtGui.QMessageBox.information( self, "Create account", "Sorry, this Login is not available, or the email address was already used." ) return False elif self.client.auth_state == ClientState.CREATED: self.client.login = login self.client.password = hashed_password return True else: return False
def start(bot, update, chat_data, args): tg_user = update.message.from_user chat_id = tg_user.id # Get or create the user from/in database User.from_telegram_object(tg_user) if isinstance(args, list) and len(args) > 0: # CATEGORY BY ID try: cat = Category.get(Category.id == args[0]) from components.explore import send_category return send_category(bot, update, chat_data, cat) except (ValueError, Category.DoesNotExist): pass query = " ".join(args).lower() # SPECIFIC DEEP-LINKED QUERIES if query == const.DeepLinkingActions.CONTRIBUTING: return help.contributing(bot, update, quote=False) elif query == const.DeepLinkingActions.EXAMPLES: return help.examples(bot, update, quote=False) elif query == const.DeepLinkingActions.RULES: return help.rules(bot, update, quote=False) elif query == const.DeepLinkingActions.SEARCH: return search_handler(bot, update, chat_data) # SEARCH QUERY search_query(bot, update, chat_data, query) else: bot.sendSticker( chat_id, open( os.path.join(appglobals.ROOT_DIR, "assets", "sticker", "greetings-humanoids.webp"), "rb", ), ) help.help(bot, update) util.wait(bot, update) if util.is_private_message(update): main_menu(bot, update) return ConversationHandler.END
def main(args): f = ROOT.TFile(args.input) graph = f.Get(args.graph) canvas = ROOT.TCanvas("canvas", "Canvas", 250, 100, 700, 500) util.style(args, graph) graph.Draw("AC") util.resize_graph(args, graph) graph.Draw("AC") line = ROOT.TGraph(2, array('d', [0., 1.]), array('d', [1., 0.])) line.SetLineColor(ROOT.kRed) line.Draw("SAME") canvas.Update() util.wait(args) util.write(args, canvas)
def close(self, timeout=None): self.invoke_lock.acquire() try: self._closing = True self.channel.session_detach(self.name) finally: self.invoke_lock.release() if not wait(self.condition, lambda: self._closed, timeout): raise Timeout()
def start(self, timeout=None): self.delegate.start() self.thread.start() if not wait(self.condition, lambda: self.opened or self.failed, timeout): self.thread.join() raise Timeout() if self.failed: self.thread.join() raise ConnectionFailed(*self.close_code)
def validatePage(self): password = self.passwordLineEdit.text().encode("utf-8") confim_password = self.passwordCheckLineEdit.text().encode("utf-8") if password != confim_password: QtGui.QMessageBox.information(self, "Create account","Passwords don't match!") return False # Hashing the password client-side is not an effective way of ensuring security, but now we # have a database full of sha256(password) we have to start considering sha256(password) to # _be_ the user's password, and enforce a saner policy atop this. # # Soon. We promise. Hopefully before large scale identity theft takes place. hashed_password = hashlib.sha256(password.encode("utf-8")).hexdigest() email = self.EmailLineEdit.text() if not self.validateEmail(email) : QtGui.QMessageBox.information(self, "Create account", "Invalid Email address!") return False login = self.loginLineEdit.text().strip() self.client.send({ "command": "create_account", "login": login, "email": email, "password": hashed_password }) # Wait for client state to change. util.wait(lambda: self.client.auth_state == ClientState.CREATED or self.client.auth_state == ClientState.REJECTED) if self.client.auth_state == ClientState.REJECTED: QtGui.QMessageBox.information(self, "Create account", "Sorry, this Login is not available, or the email address was already used.") return False elif self.client.auth_state == ClientState.CREATED: self.client.login = login self.client.password = hashed_password return True else: return False
def sync(self, timeout=None): ch = self.channel if ch is not None and currentThread() == ch.connection.thread: raise SessionException("deadlock detected") if self.need_sync: self.execution_sync(sync=True) last = self.sender.next_id - 1 if not wait(self.condition, lambda: last in self.sender._completed or self.exceptions, timeout): raise Timeout() if self.exceptions: raise SessionException(self.error())
def session(self, name, timeout=None, delegate=session.client): self.lock.acquire() try: ch = Channel(self, self.__channel()) ssn = self.attach(name, ch, delegate) ssn.channel.session_attach(name) if wait(ssn.condition, lambda: ssn.channel is not None, timeout): return ssn else: self.detach(name, ch) raise Timeout() finally: self.lock.release()
def validatePage(self): password1 = hashlib.sha256( self.passwordLineEdit.text().encode("utf-8")).hexdigest() password2 = hashlib.sha256( self.passwordCheckLineEdit.text().encode("utf-8")).hexdigest() if password1 != password2: QtGui.QMessageBox.information(self, "Create account", "Passwords don't match!") return False email = self.EmailLineEdit.text() if not self.validateEmail(email): QtGui.QMessageBox.information(self, "Create account", "Invalid Email address!") return False # check if the login is okay login = self.loginLineEdit.text().strip() self.client.loginWriteToFaServer("CREATE_ACCOUNT", login, email, password1) # Wait for client state to change. util.wait(lambda: self.client.state) if self.client.state == ClientState.REJECTED: QtGui.QMessageBox.information( self, "Create account", "Sorry, this Login is not available, or the email address was already used." ) return False else: self.client.login = login self.client.password = password1 return True
def step_impl(ctx): pid, fd = pty.fork() if pid == pty.CHILD: tty = os.ttyname(0) sys.stdin = open(tty, 'r') sys.stdout = open(tty, 'w') sys.stderr = open(tty, 'w') try: dockerpty.start(ctx.client, ctx.container) except: os_.exit(1) os._exit(0) else: tty = os.ttyname(fd) ctx.pty = fd util.set_pty_size( ctx.pty, (ctx.rows, ctx.cols) ) ctx.pid = pid util.wait(ctx.pty)
def main(args): util.optstat(args) f = ROOT.TFile(args.input) hist = f.Get(args.hist) util.validate_hists([args.hist], [hist]) hist = util.resize_histo(args, hist, "") hstack = ROOT.THStack() canvas = ROOT.TCanvas("canvas", "Canvas", 250, 100, 700, 500) class ArgDict(dict): __getattr__ = dict.get hists = [] for i, (low, high) in enumerate(zip(args.lows, args.highs)): this_args = ArgDict({"y_min": low, "y_max": high, "projectionX": True}) h = util.resize_histo(this_args, hist.Clone(), str(i)) h.SetLineColor(util.fillcolors(i)) h.SetLineWidth(3) if args.names: name = args.names[i] h.SetTitle(name) hists.append(h) hstack.Add(h) hstack.Draw("NOSTACK HIST") legend = ROOT.gPad.BuildLegend(*(args.legend_position + [""])) if args.title is not None: hstack.SetTitle(args.title) util.style(args, canvas, hstack) box = util.draw_text(args) canvas.Update() util.wait(args) util.write(args, canvas)
def add_custom(bot, update, username): uid = util.uid_from_update(update) user = User.from_update(update) mid = util.mid_from_update(update) from components.basic import main_menu_buttons main_menu_markup = ReplyKeyboardMarkup(main_menu_buttons(uid in settings.MODERATORS)) try: fav = Favorite.get(custom_bot=username) util.send_or_edit_md_message( bot, uid, mdformat.none_action( "{} is already a favorite of yours. /favorites".format(fav.custom_bot)), to_edit=mid, reply_markup=main_menu_markup) except Favorite.DoesNotExist: fav = Favorite(user=user, custom_bot=username, date_added=datetime.date.today()) fav.save() msg = bot.formatter.send_or_edit(uid, mdformat.love("{} added to your /favorites.".format(fav.custom_bot)), to_edit=mid) mid = msg.message_id util.wait(bot, update) send_favorites_list(bot, update, to_edit=mid) return ConversationHandler.END
def close(self, timeout=None): if not self.opened: return Channel(self, 0).connection_close(200) if not wait(self.condition, lambda: not self.opened, timeout): raise Timeout() self.thread.join(timeout=timeout)
def main(args): util.optstat(args) hist = util.get_tobject(args, args.hist) util.validate_hists([args.hist], [hist]) hist = util.resize_histo(args, hist) if args.make_percentages: if isinstance(hist, ROOT.TH2D): for i in range(1, hist.GetNbinsX() + 1): this_norm = hist.Integral(i, i, 1, hist.GetNbinsY()) for j in range(1, hist.GetNbinsY() + 1): if this_norm < 1e-3: hist.SetBinContent(i, j, 0) else: hist.SetBinContent( i, j, hist.GetBinContent(i, j) / this_norm) else: for k in range(1, hist.GetNbinsZ() + 1): for i in range(1, hist.GetNbinsX() + 1): this_norm = hist.Integral(i, i, 1, hist.GetNbinsY(), k, k) for j in range(1, hist.GetNbinsY() + 1): if this_norm < 1e-3: hist.SetBinContent(i, j, k, 0) else: hist.SetBinContent( i, j, k, hist.GetBinContent(i, j, k) / this_norm) hist2 = None if args.meanY: hist2 = mean_and_err(hist) canvas = ROOT.TCanvas("canvas", "Canvas", 250, 100, 700, 500) drawstr = "" if args.drawstr is not None: drawstr = args.drawstr elif isinstance(hist, ROOT.TH2D): drawstr = "COLZ" if args.draw_text: drawstr += " TEXT" hist.SetMarkerSize(3) ROOT.gStyle.SetPaintTextFormat("1.3f") elif isinstance(hist, ROOT.TH1D): drawstr = "HIST" elif isinstance(hist, ROOT.TGraph): drawstr = "AL" hist.Draw(drawstr) if hist2: hist2.SetLineColor(ROOT.kRed) hist2.SetLineWidth(3) hist2.SetMarkerSize(1) hist2.SetMarkerStyle(21) hist2.SetMarkerColor(ROOT.kRed) hist2.Draw("P") if args.title is not None: hist.SetTitle(args.title) util.style(args, canvas, hist) if args.logy: canvas.SetLogy() if args.logz: canvas.SetLogz() box = util.draw_text(args) canvas.Update() util.wait(args) util.write(args, canvas)
}, "created": "{}Z".format(datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3]) }) if d_create_resp.ok: logger.info(ok + "Created device {}".format( stylize(device_name, colored.fg("green")))) else: logger.error(nok + "Failed to create the device {} ({} - {})".format( stylize(device_name, colored.fg("blue")), stylize(d_create_resp.status_code, colored.fg("yellow")), stylize(d_create_resp.content, colored.fg("red")))) abort() # give the system some time wait(5, "Waiting for the device to be created") else: logger.info(ok + "Device {} already exists".format( stylize(device_name, colored.fg("blue")))) # endregion # region sending an ordinary message logger.info(step + "Sending some ordinary messages to ubirch") def check_response(response, type): if response.ok: logger.info(ok + "{} - message successfully sent".format(type)) else: logger.error(nok + "{} - failed to send the message ({} - {})".format( type, stylize(response.status_code, colored.fg('yellow')),
def blink(self, times=5): for i in range(times): self.on() util.wait(300) self.off() util.wait(300)
break # Still within dosage time, checking if util.timeBetween(utime.localtime(), schedule[i], 3): print('ttt') green.on() red.off() if proxSensor.proximity() > 2100: msgDict = { 'time': utime.localtime(), 'id': 101, 'taken': True, 'temp': tempSensor.objTemp() } msg = jsonEncoder.pack(msgDict) esPub.publish(msg) print('Pill Taken!', msg) taken == True servoCtrl.next() break else: print('nttt') green.off() red.on() util.wait(100) #Embedded Sys topic: esys/TBC/drugDealer #Embedded Sys MQTT broker IP: 192.168.0.10 #broker.hivemq.com
def set_Face(): img_url = "face.jpg" img_url2 = "dica.jpg" img_url3 = "foo2.jpg" name = 'wonwoo' person_group_id = str(uuid.uuid1()) faceID = [] person_id = {} persisted_face_id = {} print(person_group_id) CF.person_group.create(person_group_id, name, user_data="펄슨 그룹 테스팅") faces = CF.face.detect(img_url2, face_id=True, landmarks=False, attributes='emotion') res = CF.person.create(person_group_id, '원우', user_data='원우') util.wait() print("creatPerson: ", res) person_id[0] = res['personId'] person_id[1] = CF.person.create(person_group_id, '디카프리오', user_data="디카프리오")['personId'] print(person_id[0]) print(res) res = CF.person.add_face(img_url, person_group_id, person_id[0], user_data="wonwoo") persisted_face_id[0] = res['persistedFaceId'] res = CF.person.add_face(img_url2, person_group_id, person_id[1], user_data="디카프리오") persisted_face_id[1] = res['persistedFaceId'] res = CF.person.update_face(person_group_id, person_id[0], persisted_face_id[0], 'TempUserData') res = CF.person.update_face(person_group_id, person_id[1], persisted_face_id[1], 'TempUserData') print(res) res = CF.person_group.train(person_group_id) util.wait() res = CF.person_group.update(person_group_id, 'wonwoo') for face in faces: print(face) print(face["faceId"]) faceID.append(face['faceId']) print(type(faces)) res = CF.face.identify(faceID, person_group_id=person_group_id) print(res) try: for identify in res: for candidates in identify["candidates"]: person = CF.person.get(person_group_id, candidates['personId']) print(person["name"]) #res=CF.person.get(person_group_id,person_id[1]) #print(res) CF.person_group.delete(person_group_id) except Exception as ex: print(ex) CF.person_group.delete(person_group_id)
def tick(self): """ Reads submissions from reddit.com/new and check the title and self text for user names. """ # Get new submissions print('\n\nRetrieve submissions...', end="") submissions = list(self.reddit.get_new(limit=None)) print('[DONE]') submission_count = submissions.__len__() print('Submissions to read: ' + str(submission_count)) for i in range(0, submission_count): submission = submissions[i] # Update percent counter pcent = i / float(submission_count) * 100 print('\rReading submissions: [%d%%]' % pcent, end="") time.sleep(0.1) # Check title title = submission.title words = title.split() sub_id = None for word in words: if word.startswith('/u/'): # Get the redditor redditor = self.parse_redditor(word) if redditor is None: continue # Check to see if we have parsed this submission already sub_id = submission.id if sub_id in self.already_done: print('Submission was already read.') break # notify the redditor author = submission.author if author is None: author = '[deleted]' else: author = author.name self.notify('submission title', redditor, submission.short_link, title, author) self.record_mention(redditor.name, 'title') # check self text body = submission.selftext words = body.split() for word in words: if word.startswith('/u/'): # Get the redditor redditor = self.parse_redditor(word) if redditor is None: continue # Check to see if we have parsed this submission already sub_id = submission.id if sub_id in self.already_done: print('Submission was already read.') break # notify the redditor self.notify('submission', redditor, submission.short_link, body, submission.author.name) self.record_mention(redditor.name, 'selftext') if sub_id is not None: self.already_done.append(sub_id) print('') util.wait(30)
def selenium(): with closing(Firefox()) as browser: browser.get(BOOKIE_URL) util.wait(browser, "//div[@class='date']") return [browser.page_source]
from array import array from multiprocessing import shared_memory from util import wait, signal mem = shared_memory.SharedMemory(name='prod_con_buffer') buff = mem.buf.cast('i') print(mem.name) try: while True: wait(buff, 2) wait(buff, 1) print("{0:-^50}".format("CONSUMER")) print("shared variable read: %d" % buff[0]) signal(buff, 1) except KeyboardInterrupt: pass del buff mem.close()
def add_to_calibre(f_name, info): pid_file = '{}/.pid'.format(os.path.realpath(os.path.dirname(os.path.realpath(sys.argv[0])))) wait(pid_file) #Get info to add to meta data name = info[0] series = info[1] tags = ', '.join(info[2]) pages = info[3] date = info[4] if info[0]: authors = info[5] else: authors = 'Unknown' if lib_path: path = ' --library-path \"{}\"'.format(lib_path) else: path = '' #The extra white space is to remove the previose message print('\r Adding to Calibre ') if args.debug: print(' {command} add -d -t \"{title}\" -T \"{tags}\" -a \"{aut}\" -s \"{ser}\" -S \"{index}\" \"{f}\" --dont-notify-gui{lib}'.format( command=calibredb_executable, title=re.sub('([\"$])', '\\\\\\1', name), tags=re.sub('([\"$])', '\\\\\\1', tags), f=re.sub('([\"$])', '\\\\\\1', f_name), ser=re.sub('([\"$])', '\\\\\\1', series), index=re.sub('([\"$])', '\\\\\\1', re.search('^.*?([\d]{2,3}\.\d+).*?$', name).group(1)), aut=re.sub('([\"$])', '\\\\\\1', authors), lib=path)) #Add file to calibre - at this point only add tags to the meta data book_id = os.popen('{command} add -d -t \"{title}\" -T \"{tags}\" -a \"{aut}\" -s \"{ser}\" -S \"{index}\" \"{f}\" --dont-notify-gui{lib}'.format( command=calibredb_executable, title=re.sub('([\"$])', '\\\\\\1', name), tags=re.sub('([\"$])', '\\\\\\1', tags), f=re.sub('([\"$])', '\\\\\\1', f_name), ser=re.sub('([\"$])', '\\\\\\1', series), index=re.sub('([\"$])', '\\\\\\1', re.search('^.*?([\d]{2,3}\.\d+).*?$', name).group(1)), aut=re.sub('([\"$])', '\\\\\\1', authors), lib=path)).read() book_id = re.search('ids:\\s*(\\d+)', book_id).group(1) if args.debug: print(' {command} set_metadata -f \"#read:false\" -f \"pubdate:{date}\" -f\"#aut:{aut}\" -f \"#pages:{pages}\" {bid} --dont-notify-gui{lib}'.format( command=calibredb_executable, date=date, pages=pages, bid=book_id, aut=re.sub('([\"$])', '\\\\\\1', authors), lib=path)) #Add all other meta data - authors, pages, characters(pururin only), and series verbose = os.popen('{command} set_metadata -f \"#read:false\" -f \"pubdate:{date}\" -f\"#aut:{aut}\" -f \"#pages:{pages}\" {bid} --dont-notify-gui{lib}'.format( command=calibredb_executable, date=date, pages=pages, bid=book_id, aut=re.sub('([\"$])', '\\\\\\1', authors), lib=path)).read() if args.debug or args.verbose: print(' Info:\n{}'.format(re.sub('(^|\n)', '\\1 ', verbose.strip()))) #Open up process for others os.remove(pid_file)
def flush(self, msg='TESTING_TESTING_TESTING', times=10): for _ in range(times): self.publish(msg) util.wait(300)