class Checker(Thread): def __init__(self): Thread.__init__(self) self.daemon = True def run(self): db = getDB() db.execute('SELECT CHECKTIME FROM VERSION') vt, = db.getone() while True: #--开始检查-- #1. 先检查已经提交的是否完成了(这个在前面) try: getdata(db) except Exception, msg: print msg #2. 检查是否有需要提交的 try: submit(db) except Exception, msg: print msg #3. 检查新版本 if now() - vt > 1000 * 3600 * 12: #1天检查2次 try: checkversion(db) vt = now() except Exception, msg: print msg
def index(serverpin, in_): wantsin = (in_ == 'true') wantsout = not wantsin cursor = utils.get_cursor() isin = _server_is_in(serverpin) isout = not isin if wantsin and isin: resp = 'already clocked in' elif wantsin and isout: tip_share = server_tip_share(serverpin) sqlin = 'INSERT INTO hours VALUES(null, %(serverpin)s, NOW(), 0, %(tip_share)s, null)' % locals() utils.execute(sqlin, cursor) resp = 'Clocked in at ' + utils.now() elif wantsout and isin: sqlout = 'UPDATE hours SET outtime = NOW() WHERE person_id = %(serverpin)s AND outtime = 0' % locals() res = utils.execute(sqlout, cursor) resp = 'Clocked out at ' + utils.now() elif wantsout and isout: resp = 'already clocked out' else: resp = 'programming error' cursor.close() return json.dumps(resp)
def update_chats(request): data = json.loads(request.body) username, password = retrieve_username_password_from_authorization(request) if username != Opentok.get_api_key(): return error_response('Unauthorized Access', 401) chat_id = data.get('chat_id', None) if chat_id: Chats.objects.filter(id=chat_id).delete() return JsonResponse({"status": "deleted"}) if data['usera_uuid'] == data['userb_uuid']: return error_response("Cannot schedule call between same users") userA = Users.objects.get(user_uuid=data['usera_uuid']) userB = Users.objects.get(user_uuid=data['userb_uuid']) next_seconds = int(data['next_seconds']) chat_time = now() + timedelta(0, next_seconds) call_possible = check_call_schedule_compatiblity(userA, userB, chat_time) if call_possible is False: return error_response("Chat schedule not possible, check times") q1 = Q(userA=userA) & Q(userB=userB) q2 = Q(userA=userB) & Q(userB=userA) from_time = now() - timedelta(1, 0) q3 = Q(chat_time__gte=from_time) q = Q(Q(q1 | q2) & q3) if Chats.objects.filter(q).exists(): return error_response( "You cannot schedule a call, u already have a chat scheduled since past day" ) chat = Chats(userB=userB, userA=userA, chat_time=chat_time) chat.save() GCMNotificaiton().send_chat_scheduled_notificaiton(chat.id) return JsonResponse({"status": "created"})
def create_annotation(): """ 创建annotation.txt文件 :return: """ start = time.time() label_map = { 'bus': 0, 'family_sedan': 1, 'fire_engine': 2, 'heavy_truck': 3, 'jeep': 4, 'minibus': 5, 'racing_car': 6, 'SUV': 7, 'taxi': 8, 'truck': 9 } logging.info('{} Create annotation.txt'.format(now())) with open('annotation.txt', 'w', encoding='utf8') as f: for classes in os.listdir(cfg.IMAGE_DIR): logging.info('{} Class: {}'.format(now(), classes)) pbr = tqdm.tqdm(os.listdir(os.path.join(cfg.IMAGE_DIR, classes))) try: for file_name in pbr: f.write( "{} {}\n".format(os.path.join(cfg.IMAGE_DIR, classes, file_name), label_map[classes])) except Exception as e: logging.error('{} {}'.format(now(), e)) pbr.close() logging.info('{} Create annotation.txt completed, cost {}'.format(now(), time.time() - start))
def nFunc(*args, **kwargs): start = utils.now() result = oFunc(*args, **kwargs) delta = utils.now() - start if isinstance(result, bottle.BaseResponse): result.set_header("X-Exec-Time", str(delta)) # If result is [or is based on BaseResponse], use it's .set_header. else: response.set_header("X-Exec-Time", str(delta)) # Else, use the globally available bottle.response's .set_header. return result
class UserFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = UserModel sqlalchemy_session = db.session id = factory.Sequence(lambda n: n + 1) email = factory.fuzzy.FuzzyText(length=20, suffix="@example.com") icloud = None password_hash = b"" date_joined = utils.now() date_last_activity = utils.now()
async def _calc_stats(self): dt = now() - self.last_health_check if dt > Worker.HEALTH_CHECK_INTERVAL: tps = int(self.ticks / Worker.HEALTH_CHECK_INTERVAL.total_seconds()) self.logger.debug('Current TPS: {} ({} ticks)'.format( tps, self.ticks, )) self.health = [tps, self.ticks] self.last_health_check = now() self.ticks = 0 if tps <= Universe.LAG_TPS: await self._solar_flare()
def signin(db): """ 登陆 """ passwd = request.POST.get('passwd','') db.execute('SELECT PASSWD FROM USER') v, = db.getone() if v != passwd: return template("error",msg="密码错误") #-设定cookie token = md5sum('%s-%s' % (now(),random.random()*now())) db.execute('INSERT INTO COOKIE(TOKEN) VALUES(%s)',token) d = urlparse.urlparse(CFG.domain).netloc.split(':')[0] response.set_cookie('token',token,path="/",expires=int(now()/1000)+3600*24*365,domain=d) redirect("/",301)
def update_feed(feed): log.debug('Updating feed %d (%s)', feed['id'], feed['url']) feed_fields_updates = {'lastcheck': utils.now()} selectors = str(feed['selector']).splitlines() res = htmlproc.get_prepared_html(feed['url'], selectors) if 'error' in res: if feed['lasterror'] == res['error']: log.warn('Repeated error getting page content" %s', res['error']) else: log.warn('New error getting page content: %s', res['error']) feed_fields_updates['lasterror'] = res['error'] model.add_feed_change(feed['id'], summary='Error getting page', details=res['error'], is_error=True) else: changes = htmlproc.get_web_safe_diff(feed['lastcontent'], res['txt']) feed_fields_updates['lasterror'] = None if not changes: log.debug('Page not changed') if feed['lasterror']: model.add_feed_change(feed['id'], summary='Fixed getting page', details='Page retreiving now works fine, no changes detected', is_error=True) else: log.debug('Page changed') details = changes summary = get_summary_from_diff(changes) model.add_feed_change(feed['id'], details=details, is_error=False, summary=summary) feed_fields_updates['lastcontent'] = res['txt'] model.update_feed(feed['id'], feed_fields_updates)
def _meta(activity: ap.BaseActivity) -> _NewMeta: visibility = ap.get_visibility(activity) is_public = False if visibility in [ap.Visibility.PUBLIC, ap.Visibility.UNLISTED]: is_public = True object_id = None try: object_id = activity.get_object_id() except Exception: # TODO(tsileo): should be ValueError, but replies trigger a KeyError on object pass object_visibility = None if activity.has_type( [ap.ActivityType.CREATE, ap.ActivityType.ANNOUNCE, ap.ActivityType.LIKE] ): object_visibility = ap.get_visibility(activity.get_object()).name actor_id = activity.get_actor().id return { MetaKey.UNDO.value: False, MetaKey.DELETED.value: False, MetaKey.PUBLIC.value: is_public, MetaKey.SERVER.value: urlparse(activity.id).netloc, MetaKey.VISIBILITY.value: visibility.name, MetaKey.ACTOR_ID.value: actor_id, MetaKey.OBJECT_ID.value: object_id, MetaKey.OBJECT_VISIBILITY.value: object_visibility, MetaKey.POLL_ANSWER.value: False, MetaKey.PUBLISHED.value: activity.published if activity.published else now(), }
def _on_message(self, client, userdata, msg): """ Defines the on_message callback for the MQTT client """ ts_reception = utils.now() # maybe we could use msg.timestamp? logging.getLogger(__name__).debug(msg.topic + " " + str(msg.payload)) self.message_handler.handle_message(ts_reception, msg.payload)
def historicalData(self, reqId, date, open, high, low, close, volume, count, WAP, hasGaps): msg = {'type': 'historicalData', 'reqId': reqId, 'date': date, 'open': open, 'high': high, 'low': low, 'close': close, 'volume': volume, 'count': count, 'WAP': WAP, 'hasGaps': hasGaps, 'ts': now()} self.msgs.put(msg)
def save(doc, index='data_objects'): """ save the body in the index, ensure version and id set """ version = doc.get('version', None) if not version: doc['version'] = now() if not doc.get('id', None): temp_id = str(uuid.uuid4()) doc['id'] = temp_id if _is_duplicate(doc, index): raise Exception("duplicate document") # create index, use index name singular as doc type # do not wait for search available See # https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-refresh.html result = client.index(index=index, body=doc, doc_type=index[:-1], timeout='120s', request_timeout=120, op_type='index', refresh=ES_REFRESH_ON_PERSIST ) return doc
def _wait_for_steps(self, num_of_steps_to_wait): self.log.info("Waiting for steps...") self._clear_camera_queue() timestamp = utils.now() while num_of_steps_to_wait > 0: data = self.db.fetch_data(sid=FOOT_SENSOR_ID, since=timestamp) timestamp = data[-1][0] for data_pt in [x[2] for x in data]: if self.sc.detect_step(data_pt) and GPIO.input(GPIO_OVERRIDE_PIN): num_of_steps_to_wait -= 2 self.log.info("Step to go: %d", num_of_steps_to_wait) if num_of_steps_to_wait < 6: self.audio.prompt_step(num_of_steps_to_wait) else: self.audio.prompt_step() if num_of_steps_to_wait <= 0: break try: node_id = QUEUE.get_nowait() if str(node_id) in self.path: self.log.info("Captured node %s", node_id) self.log.info("Resetting steps to 2") num_of_steps_to_wait = 2 self.next_node_idx = self.path.index(str(node_id)) self.audio.prompt_camera() except Empty: continue self.log.info("Completed steps")
def new_note(self, user): now = utils.now() key = self._gen_unique_key() note = Note() note.user = user note.key = key note.deleted = 0 note.modify = now note.create = now note.syncnum = 1 note.version = 1 note.minversion = 1 note.sharekey = None note.tags = [] note.content = '' note.pinned = 0 note.unread = 0 note.markdown = 0 note.islist = 0 return note
def all_indicators(db, update_local_db=False): metrics = {} for row in wb.get_indicator(): assert isinstance(row, dict) assert isinstance(row['sourceNote'], str) assert isinstance(row['topics'], list) assert isinstance(row['sourceOrganization'], str) assert isinstance(row['name'], str) #print(row) d = { 'last_updated': now(), 'wb_id': row['id'], 'source_note': row['sourceNote'], 'name': row['name'], 'unit': row['unit'], 'source_organisation': row['sourceOrganization'], 'topics': row['topics'] } if update_local_db: db.world_bank_indicators.update_one({'wb_id': d['wb_id']}, {"$set": d}, upsert=True) metrics[d['wb_id']] = d print("Found {} datasets from wbdata".format(len(metrics.keys()))) return metrics
def fit_datasets(): """Fit datasets :returns: google fit datasets """ service = fit_client() datasets = service.users().dataset().aggregate( userId='me', body={ 'aggregateBy': [{ 'dataSourceId': app.config['GOOGLE_FIT_SOURCE'], }], 'startTimeMillis': yesterday_millis(), 'endTimeMillis': now(), 'bucketByTime': { 'durationMillis': 86400000, 'period': 'day' }, # 1 day = 86400000, 1hr = 3600000 } ).execute() return datasets
def add_group(self, title): """ Creates a new group and adds it to this group. `title` is the title for the new group. It can't be None or empty string. Returns the created group. """ if not title: raise ValueError("title is not set.") now = utils.now() initargs = { 'group_id': groupid.generate(), 'title': title, 'creation': now, 'last_mod': now, 'last_access': now, 'image': 1, 'level': self.level + 1, 'parent': self, } group = Group(**initargs) self._children.append(group) return group
def add_tag_to_face(face_id, tag_id, user): # check if user already tagged with same tag global TaggedFace global FacePictures if TaggedFace.find({'from': user.get('ident'), _FACE_ID: face_id, 'tag': tag_id}).count(): return False # create tag object TaggedFace.insert({'from': user.get('ident'), 'from_type': user.get('type'), _FACE_ID: face_id, 'tag': tag_id, 'datetime': now()}) face = get_face_from(face_id) # update face tags list face.update({'tags': face_tags_dict_for(face=face)}) # maybe update main tag of face face.update({'tag': main_tag_for(face=face)}) # save face FacePictures.save(face) # maybe update winner cache update_winner_cache_if_winner(face)
def execute_download_and_extraction(config_filename): config = ReceptionConfiguration(config_filename) if config.is_valid: print('running') organizer = Organizer(config.serial_path, config.unidentified_path) while config.status() == 'ON': sleep = 0 if str(datetime.today().weekday()) in config.weekdays: h = int(utils.now()[1][0:2]) if config.start_hour <= h <= config.end_hour: receive_and_organize(config, organizer) sleep = 60*config.frequency elif h < config.start_hour: sleep = 60*60*(config.start_hour - h) elif h > config.end_hour: sleep = 60*60*(24 - h + config.start_hour) else: # volta em 24h sleep = 60*60*24 if sleep > 0: print(sleep) time.sleep(sleep) print('stopped') else: print('configuration problem')
def generate_markdown_report(self, loop_start): """ Separate from the others as this logs to a sidebar rather than a file """ s = self.session land_report = StatusCommand.lands_status_for(s, self.config) hq = self.reddit.get_subreddit(self.config.headquarters) cur = now() elapsed = (cur - loop_start) + self.config["bot"]["sleep"] version_str = version(self.config) bot_report = ("Bot Status:\n\n" "* Last run at %s\n\n" "* Seconds per Frame: %d\n\n" "* Version: %s") % ( timestr(cur), elapsed, version_str, ) report = "%s\n\n%s" % (land_report, bot_report) # This is apparently not immediately done, or there's some caching. # Keep an eye on it. hq.update_settings(description=report)
def test_got_moved(self): """Make sure you can't finish moving if you're warped""" started = self.alice.region londo = self.get_region("Orange Londo") # For testing purposes, londo is now alice's londo.owner = self.alice.team # But she's at the fight self.alice.region = self.get_region('sapphire') order = self.alice.move(100, londo, 60 * 60 * 24)[0] n = self.sess.query(db.MarchingOrder).count() self.assertEqual(n, 1) # The sapphire battle ends poorly for alice's team, and she gets # booted out self.alice.region = self.get_region('oraistedarg') # Invoke the update routine to set everyone's location order.arrival = now() arrived = MarchingOrder.update_all(self.sess) self.assert_(arrived) # Alice should be back where she started, as the move isn't valid self.assertEqual(started, self.alice.region) n = self.sess.query(db.MarchingOrder).count() self.assertEqual(n, 0)
def test_situation_changes(self): """Can't move somewhere that changes hands while you're moving""" started = self.alice.region londo = self.get_region("Orange Londo") # For testing purposes, londo is now alice's londo.owner = self.alice.team order = self.alice.move(100, londo, 60 * 60 * 24)[0] n = self.sess.query(db.MarchingOrder).count() self.assertEqual(n, 1) # BUT WAIT! Londo's government is overthrown! londo.owner = self.bob.team # Push back arrival time order.arrival = now() self.sess.commit() # Invoke the update routine to set everyone's location arrived = MarchingOrder.update_all(self.sess) self.assert_(arrived) # Alice should be back where she started, as she can't be in londo self.assertEqual(started, self.alice.region) n = self.sess.query(db.MarchingOrder).count() self.assertEqual(n, 0)
def friend_time(seconds): diff = now() - seconds days = diff / 86400 if days > 730: return '%s years ago' % (days / 365) if days > 365: return '1 year ago' if days > 60: return '%s months ago' % (days / 30) if days > 30: return '1 month ago' if days > 14: return '%s weeks ago' % (days / 7) if days > 7: return '1 week ago' if days > 1: return '%s days ago' % days if diff > 7200: return '%s hours ago' % (diff / 3600) if diff > 3600: return '1 hour ago' if diff > 120: return '%s minutes ago' % (diff / 60) if diff > 60: return '1 minute ago' if diff > 1: return '%s seconds ago' % diff return '%s second ago' % diff
def print(self) -> str: s = max(self._bet_ref['finish_time'] - utils.now(), 0) time_remaining_str = utils.print_time(self._lang.get(), s) lines = [tr(self._lang.get(), 'BET.TIME', time=time_remaining_str)] if self._info_changed: self._stored_info = [] # Sort bet data total_bet = self.get_bet_sum() + self._bot.get_bet() bets = list(self._bet_ref['bets'].values()) bets.append((self._bot.icon, self._bot.get_bet())) bets.sort(key=lambda x: x[1], reverse=True) # Jackpot a: str = tr(self._lang.get(), 'BET.JACKPOT', EMOJI_SPARKLE=Emoji.SPARKLE, money=utils.print_money(self._lang.get(), total_bet)) b: str = tr(self._lang.get(), 'BET.MAX_BET', money=utils.print_money(self._lang.get(), self._limit)) self._stored_info.append(f"{a}\n{b}") # Player+bot bets for single_bet in bets: money_str = utils.print_money(self._lang.get(), single_bet[1]) pct = single_bet[1] / total_bet self._stored_info.append( f"{single_bet[0]}: {money_str} ({pct:.0%})") self._info_changed = False return '\n'.join(lines + self._stored_info)
def object_from_config(cfg): phase = math.radians(cfg['phase']) Ph = normalize_height(cfg.get('height', 0)) pos = Point(Ph * math.sin(phase), Ph * math.cos(phase)) speed = math.sqrt(Universe.MU / Ph) vel = Point( speed * math.sin(phase + math.pi / 2), speed * math.cos(phase + math.pi / 2), ) ant_a = Universe.DROP_ORBIT_H_MAX * 2 if Ph >= Universe.DROP_ORBIT_H_MID: ant_a = 0 ant_b = 0 else: ant_angl = min(Universe.ANT_MAX_ANGLE, math.radians(cfg['antenna_focus'])) ant_b = ant_a * math.sin(ant_angl) obj = Object( idx=str(uuid.uuid4()), position=pos, velocity=vel, mass=cfg['mass'], refreshed_at=now(), narrow_beam_response=cfg['narrow_beam_response'], antenna=Point(ant_a, ant_b), ) return obj
def kill(self): self.lives -= 1 self.ship.momentum = three.Vector3(0, 0, 0) self.ship.position = three.Vector3(0, 0, 0) self.ship.geo.setRotationFromEuler(three.Euler(0, 0, 0)) self.keyboard.clear('spin') self.keyboard.clear('thrust') self.keyboard.clear('fire') self.ship.visible = False self.audio.fail.play() can_reappear = now() + 3.0 def reappear(t): if now() < can_reappear: return True, "waiting" for a in self.asteroids: if a.bbox.contains(self.ship.position): return True, "can't spawn" return False, "OK" def clear_resetter(): self.ship.visible = True self.resetter = None reset = coroutine(reappear, clear_resetter) next(reset) return reset
def insert_location(self, x, y, heading, altitude, is_reset=False): self._open_conn() query = 'INSERT INTO user_location values(?, ?, ?, ?, ?)' if is_reset: self.conn.execute('UPDATE reset_state SET is_reset = 1') self.conn.execute(query, [now(), x, y, heading, altitude]) self._close_conn()
def reappear(t): if now() < can_reappear: return True, "waiting" for a in self.asteroids: if a.bbox.contains(self.ship.position): return True, "can't spawn" return False, "OK"
def __init__(self, canvas, fullscreen=True): self.keyboard = Keyboard() if fullscreen: self.graphics = Graphics(window.innerWidth, window.innerHeight, canvas) else: self.graphics = Graphics(canvas.offsetWidth, (3 * canvas.offsetWidth) / 4, canvas) self.extents = self.graphics.extent() set_limits(*self.extents) self.create_controls() self.ship = None self.bullets = [] self.asteroids = [] self.helptext = None self.resetter = None self.setup() self.last_frame = now() self.audio = Audio() self.lives = 3 self.score = 0 self.score_display = document.getElementById('score') self.fps_counter = FPSCounter(document.getElementById("FPS")) # adjust the position of the game over div v_center = canvas.offsetHeight / 3 title = document.getElementById("game_over") title.style.top = v_center hud = document.getElementById('hud') hud.style.width = canvas.offsetWidth hud.style.height = canvas.offsetHeight frame = document.getElementById('game_frame') frame.style.min_height = canvas.offsetHeight
def _report_event(self, event_m): events = [] current = now() for (k, v) in event_m.iteritems(): events.append(Event(timestamp=current, category=self._event_category, key=[k, self._hostname], value=v)) if events: self._reporter.add_events(events)
def authenticate_token(self, email, token): user = self.session.query(User).filter_by(email=email).first() if user and user.token and user.tokendate: if user.token == token and \ (utils.now()-user.tokendate) <= cfg.token_max_age: return user return None
def api_follow() -> _Response: actor = _user_api_arg("actor") q = { "box": Box.OUTBOX.value, "type": ap.ActivityType.FOLLOW.value, "meta.undo": False, "activity.object": actor, } existing = DB.activities.find_one(q) if existing: return _user_api_response(activity=existing["activity"]["id"]) follow = ap.Follow( actor=MY_PERSON.id, object=actor, to=[actor], cc=[ap.AS_PUBLIC], published=now(), context=new_context(), ) follow_id = post_to_outbox(follow) return _user_api_response(activity=follow_id)
async def reroll_all(ctx, value: int = None): if await bot.is_owner(ctx.author): desc = f"Reroll **all** totems ?\n\nType **yes** to proceed, or **no** to cancel." embed = discord.Embed(description=desc, color=Color.red()) embed.set_footer(text=f"Requested by {ctx.author}") await ctx.send(embed=embed) check = lambda m: m.author == ctx.author and m.channel == ctx.channel and utils.yes_or_no( m.content) try: reply = await bot.wait_for("message", check=check, timeout=5) except asyncio.TimeoutError: pass else: if reply.content.lower() == "yes": settings = db.get_settings() if value is not None: count = value elif settings: count = settings['global_rc'] + 1 else: count = 101 db.update_settings(global_rc=count, last_update=utils.now()) else: m = await ctx.send("**Nice try**") await asyncio.sleep(2) await ctx.channel.delete_messages((ctx.message, m))
def create_favorite_for(user, face_id): global Favorites global Users if face_id in user.get('favorites', []): return False if user.get('nb_favorited') >= NB_MAX_FAVORITES: return False # create favorite object Favorites.insert({_FACE_ID: face_id, 'user_id': user.get('ident'), 'datetime': now()}) # update facepicture counter for favorites face = get_face_from(face_id) update_face(face, {'nb_favorited': face.get('nb_favorited', 0) + 1}) # update user counter + list of favs user.update({'favorites': user.get('favorites', []) + [face_id, ]}) Users.save(user) # maybe update winner cache update_winner_cache_if_winner(face)
def parse(sensor,data): measures = [] measure = {} # load the file data = json.loads(data) # for each line for line in data: entry = line.split(',') measure = {} # if a filter is defined, ignore the line if the filter is not found if "filter" in sensor["plugin"] and entry[sensor["plugin"]["filter_position"+1]] != sensor["plugin"]["filter"]: continue # if a prefix is defined, filter based on it if "prefix" in sensor["plugin"] and not entry[sensor["plugin"]["value_position"+1]].startswith(sensor['plugin']['prefix']): continue # generate the timestamp if "date_position" in sensor["plugin"]: date = datetime.datetime.strptime(entry[sensor["plugin"]["date_position"+1]],sensor["plugin"]["date_format"]) measure["timestamp"] = utils.timezone(utils.timezone(int(time.mktime(date.timetuple())))) else: measure["timestamp"] = utils.now() # set the key as the sensor_id measure["key"] = sensor["sensor_id"] # strip out the measure from the value value = entry[sensor["plugin"]["value_position"+1]] # if a measure prefix was defined, remove it if "prefix" in sensor["plugin"]: value.replace(sensor['plugin']['prefix'],"") # set the value measure["value"] = utils.normalize(value,conf["constants"]["formats"][sensor["format"]]["formatter"]) measures.append(measure) return measures
def activity_to_todo(method, get, post, user, id): '''activity 转 todo''' id = int(id) assert method == 'PUT' Todo.activities.filter(id=id, user=user).update(done=False, catlog='T', created=now())
def log_step(step_type, device, step, tracker=None, metrics_debug=False): msg = '{}/ {}, device {}, step {}'.format(step_type, utils.now(), device, step) if tracker: rates = tracker.rate(), tracker.global_rate() msg += ', Rate={:.2f}, Global Rate={:.2f}'.format(*rates) return msg
def system_event(etype, ptype, payload=None, time=None): d = dict(event_type=EVENT_TYPE[etype], \ payload_type=PAYLOAD_TYPE[ptype]) if payload is not None: d['payload'] = payload time = now() if time is None else time return Event(1, time, d)
def OnSave(self, evt): # -----------------校验输入值start------------------------------ catagory_name = self.tc_catagoryname.GetValue().strip() if catagory_name == '': self.info.ShowMessage('物品类别不能为空!', flags=wx.ICON_WARNING) return if catagoryservice.exists(catagory_name, self.catagory_id): msg = '[{}]该物品类别已经存在,请重新输入!'.format(catagory_name) self.info.ShowMessage(msg, wx.ICON_WARNING) return catagory_order = self.tc_order.GetValue().strip() if catagory_order == '': self.info.ShowMessage('显示顺序不能为空!', flags=wx.ICON_WARNING) return pattern = re.compile('^[0-9]+$') if re.match(pattern, catagory_order) is None: self.info.ShowMessage('显示顺序必须是整数数字!', flags=wx.ICON_WARNING) return # -----------------校验输入值end------------------------------ catagory_dict = { 'catagory_id': self.catagory_id, 'catagory_name': catagory_name, 'catagory_order': catagory_order, 'catagory_desc': self.tc_catagorydesc.GetValue().strip(), 'save_time': utils.now() } catagoryservice.add_or_update_catagory(catagory_dict) wx.MessageBox(self.msg, '温馨提示', wx.OK_DEFAULT | wx.ICON_INFORMATION) # 重新加载物品树 model.goodsListModel.set(current=catagory_name) self.Destroy()
def api_undo() -> _Response: oid = _user_api_arg("id") doc = DB.activities.find_one( { "box": Box.OUTBOX.value, "$or": [{"remote_id": activity_url(oid)}, {"remote_id": oid}], } ) if not doc: raise ActivityNotFoundError(f"cannot found {oid}") obj = ap.parse_activity(doc.get("activity")) undo = ap.Undo( actor=MY_PERSON.id, context=new_context(obj), object=obj.to_dict(embed=True, embed_object_id_only=True), published=now(), to=obj.to, cc=obj.cc, ) # FIXME(tsileo): detect already undo-ed and make this API call idempotent undo_id = post_to_outbox(undo) return _user_api_response(activity=undo_id)
def api_like() -> _Response: note = _user_api_get_note() to: List[str] = [] cc: List[str] = [] note_visibility = ap.get_visibility(note) if note_visibility == ap.Visibility.PUBLIC: to = [ap.AS_PUBLIC] cc = [ID + "/followers", note.get_actor().id] elif note_visibility == ap.Visibility.UNLISTED: to = [ID + "/followers", note.get_actor().id] cc = [ap.AS_PUBLIC] else: to = [note.get_actor().id] like = ap.Like( object=note.id, actor=MY_PERSON.id, to=to, cc=cc, published=now(), context=new_context(note), ) like_id = post_to_outbox(like) return _user_api_response(activity=like_id)
def f(uuid, features): if (uuid in models_dict and 'date' in models_dict[uuid] and 'features' in models_dict[uuid] and (utils.now() - models_dict[uuid]['date']).seconds < seconds and models_dict[uuid]['features'] == features): return models_dict[uuid]['model'] else: models_dict[uuid] = { 'model': get_model(uuid, features), 'date': utils.now(), 'features': features } return models_dict[uuid]['model']
def validate_subset(args, trainers, task, epoch_itr, subset): print('Validating the subset "{}"'.format(subset)) # Initialize data iterator itr = task.get_batch_iterator( dataset=task.dataset(subset), max_tokens=args.max_tokens, max_sentences=args.max_sentences_valid, max_positions=utils.resolve_max_positions( task.max_positions(), list(trainers.values())[0].get_model().max_positions(), ), ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test, required_batch_size_multiple=args.required_batch_size_multiple, seed=args.seed, num_workers=args.num_workers).next_epoch_itr(shuffle=False) progress = progress_bar.build_progress_bar( args, itr, epoch_itr.epoch, prefix='valid on \'{}\' subset'.format(subset), no_progress_bar='simple') stats_per_device = model_parallel(valid_loop_fn, progress) valid_losses = [stats['loss'].avg for stats in stats_per_device] print('validation stats on subset "{}" - {}'.format(subset, utils.now())) for stats in stats_per_device: progress.print(stats, tag=subset, step=trainer.get_num_updates()) return valid_losses
def __init__(self, **kw): self.id = kw.get('id', utils.get_id()) self.etag = kw.get('etag', "ETAG-%s" % self.id) self.title = kw.get('title', '') self.updated = kw.get('updated', utils.now()) self.selfLink = kw.get('selfLink', "self_link_url_not_implemented") self.tasks = {} self.kind = "tasks#taskList"
def _report_timeline(self, timeline_m): current = now() time_slices = [] for (k, v) in timeline_m.iteritems(): points = self._compute_timeline_sample_point(v) time_slices.append(TimeSlice(timestamp=current, category=self._timeline_category, key=k, points=points)) if time_slices: self._reporter.add_time_slices(time_slices)
def fortified(cls, expiration=None): """Fortified - region can't be invaded""" if expiration is None: expiration = 3600 * 24 * 7 expires = now() + expiration return cls(name="Fortified", internal="fortified", expires=expires)
def _report_alarm(self, alarm_l): alarms = [] current = now() for (level, category, key, reason) in alarm_l: alarms.append(Alarm(timestamp=current, category=category, key=key, reason=reason, level=level, host=self._hostname)) if alarms: self._reporter.add_alarms(alarms)
def orderStatus(self, orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeId): msg = {'type': 'orderStatus', 'orderId': orderId, 'status': status, 'filled': filled, 'remaining': remaining, 'avgFillPrice': avgfillPrice, 'permId': permId, 'parentId': parentId, 'lastFillPrice': lastFillPrice, 'clientId': clientId, 'whyHeId': whyHeId, 'ts': now()} self.msgs.put(msg)
def write_abdatapoint(uuid, features, result): """Given an uuid and a sequence of features, it writes the point in the db""" data = {'uuid': uuid, 'features': features, 'result': result, 'time': utils.now()} return db['abdatapoints'].insert(data)
def test_no_rookies_react(self): self.bob.recruited = now() + 6000 # No responses, either s1 = self.battle.create_skirmish(self.alice, 1) with self.assertRaises(db.TimingException): s1.react(self.bob, 1) self.assertEqual(self.sess.query(db.SkirmishAction).count(), 1)
def update_all(cls, sess): expired = [] for buff in sess.query(cls).all(): if buff.expires and now() > buff.expires: expired.append(buff) for buff in expired: sess.delete(buff) sess.commit()
def first_strike(self, context, skirm): """Returns true if this skirmish is eligible for first strike""" fftb = context.config['game'].get('fftb_time', 0) if fftb: pre = (context.session.query(SkirmishAction). filter_by(battle=skirm.battle, participant=skirm.participant)).count() cutoff = skirm.battle.begins + fftb if now() <= cutoff and pre <= 1: return True
def otd(cls, expiration=None): """On the Defensive - 10% VP for a week on capturing""" # With no expiration, this expires in a week if expiration is None: expiration = 3600 * 24 * 7 expires = now() + expiration return cls(name="On the Defensive", internal="otd", value=0.1, expires=expires)
def process_synthetic_info(i): if 'error' in i: return print u"合成等级%d 经验%d/%d 队列最大长度%d" % (i['synth_level'], i['remain_exp'], i['next_exp'], i['max_queue']) t = 0 # some_time ^_^ tmax = 0 # calculate all time here for f in i.get('synth_list', []): if f['synth_status']== 1: tmax += f['rest_time'] elif f['synth_status']== 0: tmax += f['need_time'] else: pass for num, f in enumerate(i.get('synth_list', [])): # print f print_synth_item(f) if f['synth_status']== 2: # 2=完成 1=正在抓 0=队列 res = syntheticService.compeleteSynthesizeAMF(uid, f['synth_id']) if res['result']: # success print u"获得%s %d经验" % (res['fish_name'], res['get_exp']) else: print u"合成失败, 渔民杯具了" print u"设置合成 公式#3:", res = req_safe(syntheticService, "addSynthesizeAMF", uid, formula_id) if res.get('synth_list', []): fid = res['synth_list'][-1]['synth_id'] # must be new time_line[now()+tmax+res['synth_list'][-1]['need_time']+10] = ('SYNTH', (fid,)) # maybe fixed print u"成功 [EVENT Registered]" else: print u"失败", res elif f['synth_status']== 1: t+= f['rest_time']+ 10 time_line[now()+t] = ('SYNTH', (f['synth_id'],)) # later is not problem print "[EVENT Registered]" elif f['synth_status']== 0: t+= f['need_time']+ 10 time_line[now()+t] = ('SYNTH', (f['synth_id'],)) # later is not problem print "[EVENT Registered]" else: # noting pass