How to use actual_duration method in Kiwi

Best Python code snippet using Kiwi_python

tale_of_zenith.py

Source:tale_of_zenith.py Github

copy

Full Screen

1import datetime2from tale_of_zenith_header import *3from fabaki_menu import *4import random5import pygame6screen = pygame.display.set_mode((SCREEN_SIZE[WIDTH], SCREEN_SIZE[HEIGHT]))7pygame.display.set_caption(GAME_CAPTION)8pygame.display.set_icon(TEXTURE_ICON)9random_object = random.Random()10class OnScreen:11 def __init__(self, x, y, texture):12 self.x = x13 self.y = y14 self.texture = texture15 self.mask = pygame.mask.from_surface(self.texture)16 self.width = texture.get_rect().width17 self.height = texture.get_rect().height18 self.x_texture = x19 self.y_texture = y20 def coords(self):21 return self.x, self.y22 def draw(self):23 self.x_texture = self.x - self.width / 224 self.y_texture = self.y - self.height / 225 screen.blit(self.texture, (self.x_texture, self.y_texture))26class Power:27 def __init__(self, entity, duration, cooldown):28 self.entity = entity29 self.duration = duration30 self.actual_duration = duration31 self.cooldown = cooldown32 self.active = False33class Effect:34 def __init__(self, entity, duration):35 self.entity = entity36 self.duration = duration37 self.actual_duration = duration38 self.active = False39 def start_effect(self):40 return41 def stop_effect(self):42 return43 def tick(self):44 return45class Regeneratable(OnScreen):46 def __init__(self, texture, regen_cooldown, effects=None, random_loc=True, x=-1, y=-1,47 kill_conditions=None, kill_conditions_all=True): # Kill conditions is {Effect: Immunity duration}48 OnScreen.__init__(self, x, y, texture)49 self.regen_cooldown = regen_cooldown50 self.random_loc = random_loc51 self.cooldown = 052 self.alive = True53 if self.random_loc or x < 0 or y < 0:54 self.generate_random_loc()55 self.kill_conditions = kill_conditions56 if kill_conditions is None:57 self.kill_conditions = {}58 if type(kill_conditions) == tuple or type(kill_conditions) == list:59 self.kill_conditions = {kill_cond: None for kill_cond in self.kill_conditions}60 self.kill_conditions_all = kill_conditions_all61 if type(effects) == tuple:62 self.effects = effects63 else:64 self.effects = (effects, )65 def generate_random_loc(self):66 self.x, self.y = random_object.randint(SCREEN_PADDING, SCREEN_SIZE[WIDTH] - self.width - SCREEN_PADDING), \67 random_object.randint(SCREEN_PADDING, SCREEN_SIZE[HEIGHT] - self.height - SCREEN_PADDING)68 def tick(self):69 if not self.cooldown:70 self.alive = True71 else:72 self.cooldown -= 173 if self.alive:74 self.draw()75 def on_collide(self, entity):76 if self.kill_conditions_all:77 for cond, immunity in self.kill_conditions.items():78 if type(cond) == type and issubclass(cond, Effect):79 for effect in entity.effects:80 if cond != type(effect):81 continue82 if not effect.active:83 return ()84 if immunity is not None:85 if effect.duration - effect.actual_duration > immunity:86 return ()87 elif not cond.active:88 return ()89 elif cond.active and immunity is not None:90 if cond.duration - cond.actual_duration > immunity:91 return ()92 else:93 kill_conditions_met = False94 for cond, immunity in self.kill_conditions.items():95 if type(cond) == type and issubclass(cond, Effect):96 for effect in entity.effects:97 if cond != type(effect):98 continue99 if effect.active:100 if immunity is not None:101 if effect.duration - effect.actual_duration > immunity:102 kill_conditions_met = True103 else:104 kill_conditions_met = True105 break106 if kill_conditions_met:107 break108 elif cond.active:109 if immunity is not None:110 if cond.duration - cond.actual_duration > immunity:111 kill_conditions_met = True112 else:113 kill_conditions_met = True114 break115 if not kill_conditions_met:116 return ()117 if type(self.regen_cooldown) == tuple and len(self.regen_cooldown) == 2:118 self.cooldown = random_object.randint(*self.regen_cooldown)119 else:120 self.cooldown = self.regen_cooldown121 if self.random_loc:122 self.generate_random_loc()123 self.alive = False124 return self.effects125class RandomTeleportEffect(Effect):126 def __init__(self, entity, animation_duration=EFFECT_TELESHROOM_ANIMATION_DURATION):127 Effect.__init__(self, entity, animation_duration)128 self.changed_textures = []129 def start_effect(self):130 self.actual_duration = self.duration131 self.entity.x = random_object.randint(1, SCREEN_SIZE[WIDTH] - 2)132 self.entity.y = random_object.randint(1, SCREEN_SIZE[HEIGHT] - 2)133 self.entity.fix_location()134 def stop_effect(self):135 for changed_texture in self.changed_textures:136 load_direction_texture_match(changed_texture)137 def tick(self): # Returns whether to stop138 for changed_texture in self.changed_textures:139 load_direction_texture_match(changed_texture)140 self.changed_textures.remove(changed_texture)141 if self.actual_duration % 6 <= 2:142 DIRECTION_TEXTURE_MATCH[self.entity.direction].fill((0, 0, 190, 100), special_flags=pygame.BLEND_SUB)143 else:144 DIRECTION_TEXTURE_MATCH[self.entity.direction].fill((190, 0, 0, 100), special_flags=pygame.BLEND_SUB)145 self.changed_textures.append(self.entity.direction)146 self.actual_duration -= 1147 if self.actual_duration <= 0:148 self.stop_effect()149 return True150 return False151class SpeedUpEffect(Effect):152 def __init__(self, entity, duration, power):153 Effect.__init__(self, entity, duration)154 self.power = power155 self.actual_duration = duration156 self.changed_textures = []157 self.active = False158 def start_effect(self):159 self.active = True160 self.actual_duration = self.duration161 self.entity.stats[STATS_VELOCITY] *= self.power162 def stop_effect(self):163 self.active = False164 self.entity.stats[STATS_VELOCITY] /= self.power165 for changed_texture in self.changed_textures:166 load_direction_texture_match(changed_texture)167 def tick(self): # Returns whether to stop168 DIRECTION_TEXTURE_MATCH[self.entity.direction]\169 .fill((0, 190, 0, 100), special_flags=pygame.BLEND_SUB)170 self.changed_textures.append(self.entity.direction)171 self.actual_duration -= 1172 if self.actual_duration <= 0:173 self.stop_effect()174 return True175 return False176class ScoreUpEffect(Effect):177 def __init__(self, entity, power):178 Effect.__init__(self, entity, -1)179 self.power = power180 def start_effect(self):181 self.entity.stats[STATS_SCORE] += self.power182class DashPower(Power):183 def __init__(self, entity, direction):184 Power.__init__(self, entity, -1, -1)185 self.direction = direction186 self.power = -1187 self.ready = True188 def start_dash(self, direction, duration=DASH_DURATION, cooldown=DASH_COOLDOWN, power=DASH_POWER):189 if not self.ready:190 return False191 self.direction = direction192 self.duration = duration193 self.actual_duration = duration194 self.cooldown = cooldown195 self.power = power196 self.ready = False197 self.active = True198 self.entity.stats[STATS_MOVABLE] = False199 self.entity.texture.fill((190, 0, 0, 100), special_flags=pygame.BLEND_SUB)200 self.entity.stats[STATS_VELOCITY] *= self.power201 return True202 def stop_dash(self):203 self.duration = -1204 self.actual_duration = -1205 self.active = False206 self.entity.stats[STATS_MOVABLE] = True207 load_direction_texture_match(MOVE_DIRECTION_MATCH[tuple(self.direction)])208 self.entity.stats[STATS_VELOCITY] /= self.power209 def set_cooldown(self, cooldown): # Can't stop dash! only to set the cooldown again when dash is un active210 if cooldown <= self.cooldown:211 return212 self.ready = False213 self.cooldown = cooldown214 def tick(self):215 if not self.active and self.cooldown > 0:216 self.cooldown -= 1217 return218 if self.actual_duration > 0:219 self.actual_duration -= 1220 self.entity.move_vector = self.direction221 if self.cooldown == 0:222 pygame.mixer.Channel(0).play(SOUND_TING)223 self.ready = True224 self.cooldown = -1225 if self.actual_duration == 0:226 self.stop_dash()227 self.actual_duration = -1228class SwordPowers:229 def __init__(self, sword):230 self.dash_effect = DashPower(sword, [0, 0])231class Sword(OnScreen):232 def __init__(self, x, y):233 OnScreen.__init__(self, x, y, DIRECTION_TEXTURE_MATCH[DIRECTION_NORTH])234 self.direction = DIRECTION_NORTH235 self.move_vector = [0, 0] # By means of top-left, aka [1, 1] is South-East236 self.stats = {STATS_VELOCITY: SWORD_SPEED, STATS_SCORE: 0, STATS_MOVABLE: True}237 self.powers = SwordPowers(self)238 self.effects = []239 self.current_tick = 0240 def change_dir(self, new_dir):241 self.direction = new_dir242 self.texture = DIRECTION_TEXTURE_MATCH[new_dir]243 self.mask = TEXTURE_MASK_MATCH[new_dir]244 def draw(self):245 if self.direction == DIRECTION_NORTH or self.direction == DIRECTION_SOUTH:246 self.x_texture = self.x - TEXTURE_PERP_VERT_SIZE[WIDTH] / 2247 self.y_texture = self.y - TEXTURE_PERP_VERT_SIZE[HEIGHT] / 2248 elif self.direction == DIRECTION_EAST or self.direction == DIRECTION_WEST:249 self.x_texture = self.x - TEXTURE_PERP_HORZ_SIZE[WIDTH] / 2250 self.y_texture = self.y - TEXTURE_PERP_HORZ_SIZE[HEIGHT] / 2251 else: # Diagonal252 self.x_texture = self.x - TEXTURE_DIAG_SIZE[WIDTH] / 2253 self.y_texture = self.y - TEXTURE_DIAG_SIZE[HEIGHT] / 2254 screen.blit(self.texture, (self.x_texture, self.y_texture))255 def next_direction(self):256 index = DIRECTION_ORDER.index(self.direction)257 index += 1258 if index == len(DIRECTION_ORDER):259 index = 0260 self.change_dir(DIRECTION_ORDER[index])261 def fix_location(self):262 if self.x < 0:263 self.x = SCREEN_SIZE[WIDTH] + self.x264 elif self.x >= SCREEN_SIZE[WIDTH]:265 self.x = self.x - SCREEN_SIZE[WIDTH]266 if self.y < 0:267 self.y = SCREEN_SIZE[HEIGHT] + self.y268 elif self.y >= SCREEN_SIZE[HEIGHT]:269 self.y = self.y - SCREEN_SIZE[HEIGHT]270 def tick(self, keys):271 self.current_tick += 1272 if not self.powers.dash_effect.active and self.current_tick % SWORD_ANIMATION_DELAY == 0:273 self.next_direction()274 if self.current_tick == SWORD_ANIMATION_DELAY * 2:275 self.current_tick = 1276 self.move_vector = [0, 0]277 self.keys_handler(keys)278 self.powers.dash_effect.tick()279 for effect in self.effects:280 if effect.tick():281 self.effects.remove(effect)282 self.move()283 self.draw()284 def keys_handler(self, keys):285 if self.stats[STATS_MOVABLE]:286 self.move_keys(keys)287 if self.move_vector == [0, 0]: # We didn't move, so we can dash288 if self.powers.dash_effect.ready and keys[pygame.K_SPACE]:289 self.powers.dash_effect.start_dash(list(DIRECTION_MOVE_MATCH[self.direction]))290 else:291 self.change_dir(MOVE_DIRECTION_MATCH[tuple(self.move_vector)])292 self.powers.dash_effect.set_cooldown(DASH_MOVE_COOLDOWN)293 def move_keys(self, keys):294 if keys[pygame.K_a] or keys[pygame.K_LEFT]:295 self.move_vector[0] -= 1296 if keys[pygame.K_d] or keys[pygame.K_RIGHT]:297 self.move_vector[0] += 1298 if keys[pygame.K_w] or keys[pygame.K_UP]:299 self.move_vector[1] -= 1300 if keys[pygame.K_s] or keys[pygame.K_DOWN]:301 self.move_vector[1] += 1302 def move(self):303 self.x += self.move_vector[0] * self.stats[STATS_VELOCITY]304 self.y += self.move_vector[1] * self.stats[STATS_VELOCITY]305 self.fix_location()306 def apply_effect(self, object_effects):307 for effect in object_effects:308 effect.start_effect()309 self.effects.append(effect)310 def colliding(self, obj):311 offset_x = int(obj.x_texture - self.x_texture)312 offset_y = int(obj.y_texture - self.y_texture)313 return self.mask.overlap(obj.mask, (offset_x, offset_y))314current_song = random_object.randint(0, len(BACKGROUND_SONGS) - 1)315changed = datetime.datetime.utcnow() - datetime.timedelta(seconds=2)316def flip_sound():317 global changed318 global current_song319 if datetime.datetime.utcnow() - changed < datetime.timedelta(seconds=1):320 return # prevent spamming, I have when 'e' is pressed it calls this like 4-5 times321 changed = datetime.datetime.utcnow()322 pygame.mixer.Channel(1).stop()323 current_song = (current_song + 1) % len(BACKGROUND_SONGS)324 pygame.mixer.Channel(1).play(BACKGROUND_SONGS[current_song], loops=-1)325def pause_menu():326 menu = Menu(screen, auto=True, background=(100, 100, 100), menu_width=500, menu_height=500)327 comic_sans = pygame.font.SysFont("Arial", 30)328 menu.add_element([TextElement("paused!", comic_sans), TextElement("homo", comic_sans)])329 menu.add_element(TextElement("continue?", comic_sans))330 menu.add_element(ButtonElement("Continue", (130, 0, 130), comic_sans, onclick_kill=True))331 return menu.menu_loop() # We pressed on close button332def global_keys_handler(keys):333 if keys[pygame.K_ESCAPE]:334 if pause_menu():335 return True336 if keys[pygame.K_e]:337 flip_sound()338def game_loop():339 player = Sword(SCREEN_SIZE[WIDTH] / 2, SCREEN_SIZE[HEIGHT] / 2)340 entities = [Regeneratable(TEXTURE_SLIME, 10, effects=ScoreUpEffect(player, EFFECT_SLIME_SCORE)),341 Regeneratable(TEXTURE_SLIME, 10, effects=ScoreUpEffect(player, EFFECT_SLIME_SCORE)),342 Regeneratable(TEXTURE_SLIME, 10, effects=ScoreUpEffect(player, EFFECT_SLIME_SCORE)),343 Regeneratable(TEXTURE_GOLDEN_SLIME, (100, 300),344 kill_conditions={player.powers.dash_effect: EFFECT_GOLDEN_SLIME_DASH_IMMUNITY,345 SpeedUpEffect: None}, kill_conditions_all=False,346 effects=ScoreUpEffect(player, EFFECT_GOLDEN_SLIME_SCORE)),347 Regeneratable(TEXTURE_SPEED_MUSH, 50,348 effects=SpeedUpEffect(player, EFFECT_SPEED_MUSH_DURATION, EFFECT_SPEED_MUSH_POWER)),349 Regeneratable(TEXTURE_TELESHROOM, 50, effects=RandomTeleportEffect(player))]350 clock = pygame.time.Clock()351 start_time = datetime.datetime.utcnow()352 text_font = pygame.font.SysFont("comicsansms", 16)353 progress_width = 10354 progress_height = 150355 game_settings = {SETTINGS_TICK_RATE: TICK_RATE}356 while True:357 clock.tick(game_settings[SETTINGS_TICK_RATE])358 keys = pygame.key.get_pressed()359 screen.blit(TEXTURE_BACKGROUND, (0, 0))360 for event in pygame.event.get():361 if event.type == pygame.QUIT:362 return363 if global_keys_handler(keys):364 return365 player.tick(keys)366 for enemy in entities:367 if enemy.alive and player.colliding(enemy):368 player.apply_effect(enemy.on_collide(player))369 enemy.tick()370 player.draw()371 fps_text = text_font.render(f"fps: {round(clock.get_fps())}", False, (255, 255, 255))372 time_elapsed = datetime.datetime.utcnow() - start_time373 time_text = text_font.render(f"Time: {str(time_elapsed.seconds // 3600).zfill(2)}:"374 f"{str(time_elapsed.seconds % 3600 // 60).zfill(2)}:"375 f"{str(time_elapsed.seconds % 60).zfill(2)}", False, (255, 255, 255))376 score_text = text_font.render(f"Score: {player.stats[STATS_SCORE]}", False, (255, 255, 255))377 if player.powers.dash_effect.ready:378 pygame.draw.rect(screen, (100, 30, 255), (SCREEN_SIZE[WIDTH] - 10 - progress_width, 10, progress_width,379 progress_height))380 pygame.draw.rect(screen, (100, 20, 110), (SCREEN_SIZE[WIDTH] - 10 - progress_width, 10, progress_width,381 progress_height), 2)382 else:383 pygame.draw.rect(screen, (0, 200, 255), (SCREEN_SIZE[WIDTH] - 10 - progress_width, 10, progress_width,384 round(((DASH_COOLDOWN - player.powers.dash_effect.cooldown)385 * progress_height / DASH_COOLDOWN))))386 pygame.draw.rect(screen, (0, 110, 110), (SCREEN_SIZE[WIDTH] - 10 - progress_width, 10, progress_width,387 progress_height), 2)388 screen.blit(fps_text, (0, 0))389 screen.blit(time_text, (SCREEN_SIZE[WIDTH] / 2 - time_text.get_rect().width / 2, 0))390 screen.blit(score_text, (SCREEN_SIZE[WIDTH] / 2 - score_text.get_rect().width / 2, time_text.get_rect().height))391 pygame.display.update()392def main():393 pygame.init()394 pygame.mixer.music.set_volume(0.5)395 pygame.mixer.Channel(1).set_volume(0.1)396 flip_sound()397 game_loop()398 pygame.quit()399if __name__ == '__main__':...

Full Screen

Full Screen

measure_distance.py

Source:measure_distance.py Github

copy

Full Screen

1# Now let's calculate the travel time & distance between the origin (school) & students home address2import pandas as pd3import googlemaps4import requests5import logging6import time7log = logging.getLogger("root")8log.setLevel(logging.DEBUG)9# create console handler10cons = logging.StreamHandler()11cons.setLevel(logging.DEBUG)12log.addHandler(cons)13api_key = 'your api key'14BACKOFF_TIME = 3015input_filename = "your csv file with geocoded addresses"16address_column_name = "address_edited"17RETURN_FULL_RESULTS = False18data = pd.read_csv(input_filename, encoding='utf8')19if address_column_name not in data.columns:20 raise ValueError("Missing Address column in input data")21data = pd.read_csv(input_filename, encoding='utf8')22gmaps=googlemaps.Client(api_key)23schools=data["school"].tolist()24destinations = (data["formatted_address"]+' ,Pakistan').tolist()25actual_distance=[]26actual_duration=[]27for destination in destinations:28 if destination is None:29 result= "NA"30 resulta= "NA"31 actual_distance.append(resulta)32 actual_duration.append(result)33 continue34 for school in schools:35 if school == 'SMB':36 origin= "SMB Fatima Jinnah Girls School Karachi Pakistan"37 #if you have a list of many schools you can add them to a list and loop through them. I have two schools in my data so I use if/else statement38 else:39 origin= "Khatoon-e-Pakistan Government Degree College For Women Karachi Pakistan"40 try:41 lala = gmaps.distance_matrix(origin, destination, mode='driving')42 status= lala["rows"][0]['elements'][0]['status']43 if status== 'OK':44 result=lala["rows"][0]['elements'][0]['duration']['value']45 result=result/360046 resulta=lala["rows"][0]['elements'][0]['distance']['value']47 resulta=resulta/100048 actual_duration.append(result)49 actual_distance.append(resulta)50 print('done')51 else:52 result= "NA"53 resulta= "NA"54 actual_distance.append(resulta)55 actual_duration.append(result)56 except:57 result= "NA"58 resulta= "NA"59 actual_distance.append(resulta)60 actual_duration.append(result)61data['duration']= actual_duration62data['distance']= actual_distance63df=pd.DataFrame(data)...

Full Screen

Full Screen

tasks.py

Source:tasks.py Github

copy

Full Screen

1# Copyright (c) 2020-present, The Johann Plugin Example Authors. All Rights Reserved.2# Use of this source code is governed by a BSD-3-clause license that can3# be found in the LICENSE file. See the AUTHORS file for names of contributors.4import time5from typing import TYPE_CHECKING, Dict, Union6import numpy as np # now we're doing data science!7from johann.shared.config import JohannConfig, celery_app8from johann.shared.logger import JohannLogger9from johann.util import TaskState10from johann_plugin_example import config as example_config11if TYPE_CHECKING:12 from celery import Task13config = JohannConfig.get_config()14logger = JohannLogger(__name__).logger15@celery_app.task(bind=True)16def baby_nap(17 self: "Task", desired_duration: int, random_seed: int = example_config.RANDOM_SEED18) -> Dict[str, Union[float, str]]:19 logger.info(f"The baby will nap for up to {desired_duration} seconds")20 # set random seed21 np.random.seed(random_seed)22 # book-keeping23 start: float = time.time()24 stop: float = start + desired_duration25 now: float = start26 actual_duration: float = 0.027 while now < stop:28 time.sleep(1)29 now = time.time()30 actual_duration = now - start31 # 10% chance that she will wake up32 if np.random.randint(1, 10) == 3:33 logger.info(f"The baby is up! She slept for {actual_duration} seconds!")34 break35 # report incremental progress36 self.update_state(37 state=TaskState.PROGRESS,38 meta={"current": actual_duration, "total": desired_duration},39 )40 # return final progress41 return {42 "current": actual_duration,43 "total": desired_duration,44 "status": "The baby is up!",45 "result": actual_duration,...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kiwi automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful