row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
37,446
I wanna make a hacking / programming forum, i dont have any money right n ow, should I start off with mybb and then use xenforo later when i have a userbase?
470e4ed93fb29723e9cb7a94c3f7250f
{ "intermediate": 0.40746408700942993, "beginner": 0.20531432330608368, "expert": 0.3872215449810028 }
37,447
How would I add sliding to this if the user is holding s and hits a or d sending them in their respective direction. # Kirbo & Kerbo's Adventure v1.0 # v0.5 - Literally added a function player model. # v1.0 - Managed to fix some bugs with crouching and added a second player model. # v1.1 - Fixed crouching and moving at the same time. import pygame import sys import time # Set up display screen = pygame.display.set_mode((900, 700)) # Set up colors (RGB format) kirby_pink_color = (255, 105, 180) kirby_yellow_color = (255, 255, 0) ground_color = (0, 255, 0) # Kirby properties circle_radius1 = 25 # Initial radius circle_radius2 = 25 # Initial radius circle_y_offset1 = 25 # Offset from the top of Kirby1 circle_y_offset2 = 25 # Offset from the top of Kirby2 crouch_scale1 = 0.5 # Crouch scale for the Kirby1 crouch_scale2 = 0.5 # Crouch scale for the Kirby2 # Kirby1 position and velocity kirby1_x, kirby1_y = 425, 500 kirby1_x_speed, kirby1_y_speed = 0, 0 gravity1 = 1 jump_height1 = -15 # Set jump height for Kirby1 # Kirby2 position and velocity kirby2_x, kirby2_y = 425, 500 kirby2_x_speed, kirby2_y_speed = 0, 0 gravity2 = 1 jump_height2 = -15 # Set jump height for Kirby2 # Kirby1 crouching and in air states is_crouching1 = False in_air1 = False # Kirby2 crouching and in air states is_crouching2 = False in_air2 = False # Kirby1 movement flags is_moving_left1 = False is_moving_right1 = False is_floating1 = False # Kirby 2 movement flags is_moving_left2 = False is_moving_right2 = False is_floating2 = False # Load the Kirby face image kirby_face1 = pygame.image.load("kirby_face.png") kirby_face2 = pygame.image.load("kirby_face.png") # Game loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_s and not is_crouching1 and not is_moving_left1 and not is_moving_right1: is_crouching1 = True elif event.key == pygame.K_k and not is_crouching2 and not is_moving_left2 and not is_moving_right2: is_crouching2 = True elif event.key == pygame.K_w and not in_air1: kirby_y_speed1 = jump_height1 in_air1 = True elif event.key == pygame.K_i and not in_air2: kirby2_y_speed = jump_height2 in_air2 = True elif event.key == pygame.K_e and not is_crouching1: is_floating1 = True elif event.key == pygame.K_o and not is_crouching2: is_floating2 = True elif event.key == pygame.K_r: is_floating1 = False elif event.key == pygame.K_p: is_floating2 = False elif event.key == pygame.K_a and not is_crouching1: is_moving_left1 = True elif event.key == pygame.K_d and not is_crouching1: is_moving_right1 = True elif event.key == pygame.K_j: is_moving_left2 = True elif event.key == pygame.K_l: is_moving_right2 = True elif event.type == pygame.KEYUP: if event.key == pygame.K_s: is_crouching1 = False elif event.key == pygame.K_k: is_crouching2 = False elif event.key == pygame.K_a: is_moving_left1 = False elif event.key == pygame.K_j: is_moving_left2 = False elif event.key == pygame.K_d: is_moving_right1 = False elif event.key == pygame.K_l: is_moving_right2 = False # Kirby1 Floating set up if is_floating1: gravity1 = 0.3 jump_height1 = -6.5 in_air1 = False is_crouching1 = False circle_radius1 = 35 circle_y_offset1 = 35 else: gravity1 = 1 jump_height1 = -15 in_air1 = True circle_radius1 = 25 circle_y_offset1 = 25 # Kirby2 Floating set up if is_floating2: gravity2 = 0.3 jump_height2 = -6.5 in_air2 = False is_crouching2 = False circle_radius2 = 35 circle_y_offset2 = 35 else: gravity2 = 1 jump_height2 = -15 in_air2 = True circle_radius2 = 25 circle_y_offset2 = 25 # Apply gravity to Kirby1 kirby1_y_speed += gravity1 # Apply gravity to Kirby2 kirby2_y_speed += gravity2 # Apply horizontal motion for Kirby1 if is_moving_left1: kirby1_x_speed = -5 elif is_moving_right1: kirby1_x_speed = 5 else: kirby1_x_speed = 0 # Apply horizontal motion for Kirby 2 if is_moving_left2: kirby2_x_speed = -5 elif is_moving_right2: kirby2_x_speed = 5 else: kirby2_x_speed = 0 # Update Kirby1 position kirby1_x += kirby1_x_speed kirby1_y += kirby1_y_speed # Update Kirby2 position kirby2_x += kirby2_x_speed kirby2_y += kirby2_y_speed # Collision with the ground for Kirby1 if kirby1_y + circle_radius1 >= 575: kirby1_y = 575 - circle_radius1 kirby_y_speed1 = 0 gravity1 = 1 jump_height1 = -15 is_floating1 = False in_air1 = False # Kirby1 is on the ground # Collision with the ground for Kirby2 if kirby2_y + circle_radius2 >= 575: kirby2_y = 575 - circle_radius2 kirby2_y_speed = 0 gravity2 = 1 jump_height2 = -15 is_floating2 = False in_air2 = False # Kirby2 is on the ground # Collision with the sides of the screen for Kirby1 if kirby1_x < 0: kirby1_x = 0 elif kirby1_x > 900 - 2 * circle_radius1: kirby1_x = 900 - 2 * circle_radius1 # Collision with the sides of the screen for Kirby2 if kirby2_x < 0: kirby2_x = 0 elif kirby2_x > 900 - 2 * circle_radius2: kirby2_x = 900 - 2 * circle_radius2 # Draw background screen.fill((100, 100, 255)) # Blue background # Draw ground pygame.draw.rect(screen, ground_color, (0, 600, 900, 50)) # Draw Kirby1 if is_crouching1: pygame.draw.ellipse(screen, kirby_pink_color, (int(kirby1_x), int(kirby1_y + circle_radius1 * (1.5 - crouch_scale1)), int(2 * circle_radius1), int(crouch_scale1 * 2 * circle_radius1))) # Scale and draw the Kirby face when crouching kirby_face_scaled1 = pygame.transform.scale(kirby_face1, (int(2 * circle_radius1), int(2 * circle_radius1 * crouch_scale1))) screen.blit(kirby_face_scaled1, (int(kirby1_x), int(kirby1_y + circle_radius1 * (1.5 - crouch_scale1)))) else: pygame.draw.circle(screen, kirby_pink_color, (int(kirby1_x + circle_radius1), int(kirby1_y + circle_radius1)), circle_radius1) # Scale and draw the Kirby face when not crouching kirby_face_scaled1 = pygame.transform.scale(kirby_face1, (int(2 * circle_radius1), int(2 * circle_radius1))) screen.blit(kirby_face_scaled1, (int(kirby1_x), int(kirby1_y))) # Draw Kirby2 if is_crouching2: pygame.draw.ellipse(screen, kirby_yellow_color, (int(kirby2_x), int(kirby2_y + circle_radius2 * (1.5 - crouch_scale2)), int(2 * circle_radius2), int(crouch_scale2 * 2 * circle_radius2))) # Scale and draw the Kirby face when crouching kirby_face_scaled2 = pygame.transform.scale(kirby_face2, (int(2 * circle_radius2), int(2 * circle_radius2 * crouch_scale2))) screen.blit(kirby_face_scaled2, (int(kirby2_x), int(kirby2_y + circle_radius2 * (1.5 - crouch_scale2)))) else: pygame.draw.circle(screen, kirby_yellow_color, (int(kirby2_x + circle_radius2), int(kirby2_y + circle_radius2)), circle_radius2) # Scale and draw the Kirby face when not crouching kirby_face_scaled2 = pygame.transform.scale(kirby_face2, (int(2* circle_radius2), int(1.8 * circle_radius2))) # Different value here because the engine is being stupid and Kirby1 copies this value for some reason. screen.blit(kirby_face_scaled2, (int(kirby2_x), int(kirby2_y))) # Update the display pygame.display.flip() # Cap the frame rate pygame.time.Clock().tick(60)
90faf350c3a1bb1a4257047dd6720722
{ "intermediate": 0.38083311915397644, "beginner": 0.4155105948448181, "expert": 0.20365630090236664 }
37,448
Fix this error and give fully fixed code [ { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/AABBPool.java", "code": "java:S1068", "severity": 1, "message": "Remove this unused \"a\" private field.", "source": "sonarlint", "startLineNumber": 8, "startColumn": 23, "endLineNumber": 8, "endColumn": 24 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/AABBPool.java", "code": "java:S1068", "severity": 1, "message": "Remove this unused \"b\" private field.", "source": "sonarlint", "startLineNumber": 9, "startColumn": 23, "endLineNumber": 9, "endColumn": 24 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/AABBPool.java", "code": "java:S3740", "severity": 1, "message": "Provide the parametrized type for this generic.", "source": "sonarlint", "startLineNumber": 10, "startColumn": 19, "endLineNumber": 10, "endColumn": 23 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/AABBPool.java", "code": "java:S3740", "severity": 1, "message": "Provide the parametrized type for this generic.", "source": "sonarlint", "startLineNumber": 10, "startColumn": 35, "endLineNumber": 10, "endColumn": 44 } ]
7f5b0fd9363ac3ad239937abe6a2bc98
{ "intermediate": 0.3345145285129547, "beginner": 0.41386762261390686, "expert": 0.2516178786754608 }
37,449
Give me fixed code without comments, i need fulyl structed code [ { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1104”, “severity”: 1, “message”: “Make c a static final constant or non-public and provide accessors if needed.”, “source”: “sonarlint”, “startLineNumber”: 7, “startColumn”: 19, “endLineNumber”: 7, “endColumn”: 20 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1104”, “severity”: 1, “message”: “Make d a static final constant or non-public and provide accessors if needed.”, “source”: “sonarlint”, “startLineNumber”: 8, “startColumn”: 19, “endLineNumber”: 8, “endColumn”: 20 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1104”, “severity”: 1, “message”: “Make e a static final constant or non-public and provide accessors if needed.”, “source”: “sonarlint”, “startLineNumber”: 9, “startColumn”: 19, “endLineNumber”: 9, “endColumn”: 20 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1104”, “severity”: 1, “message”: “Make next a static final constant or non-public and provide accessors if needed.”, “source”: “sonarlint”, “startLineNumber”: 10, “startColumn”: 18, “endLineNumber”: 10, “endColumn”: 22 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1845”, “severity”: 1, “message”: “Rename method “a” to prevent any misunderstanding/clash with field “a”. [+1 location]”, “source”: “sonarlint”, “startLineNumber”: 12, “startColumn”: 25, “endLineNumber”: 12, “endColumn”: 26 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1845”, “severity”: 1, “message”: “Rename method “a” to prevent any misunderstanding/clash with field “a”. [+1 location]”, “source”: “sonarlint”, “startLineNumber”: 42, “startColumn”: 18, “endLineNumber”: 42, “endColumn”: 19 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1845”, “severity”: 1, “message”: “Rename method “b” to prevent any misunderstanding/clash with field “b”. [+1 location]”, “source”: “sonarlint”, “startLineNumber”: 48, “startColumn”: 19, “endLineNumber”: 48, “endColumn”: 20 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1845”, “severity”: 1, “message”: “Rename method “d” to prevent any misunderstanding/clash with field “d”. [+1 location]”, “source”: “sonarlint”, “startLineNumber”: 56, “startColumn”: 19, “endLineNumber”: 56, “endColumn”: 20 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1845”, “severity”: 1, “message”: “Rename method “d” to prevent any misunderstanding/clash with field “d”. [+1 location]”, “source”: “sonarlint”, “startLineNumber”: 72, “startColumn”: 19, “endLineNumber”: 72, “endColumn”: 20 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1845”, “severity”: 1, “message”: “Rename method “b” to prevent any misunderstanding/clash with field “b”. [+1 location]”, “source”: “sonarlint”, “startLineNumber”: 80, “startColumn”: 19, “endLineNumber”: 80, “endColumn”: 20 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1845”, “severity”: 1, “message”: “Rename method “b” to prevent any misunderstanding/clash with field “b”. [+1 location]”, “source”: “sonarlint”, “startLineNumber”: 84, “startColumn”: 18, “endLineNumber”: 84, “endColumn”: 19 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1845”, “severity”: 1, “message”: “Rename method “c” to prevent any misunderstanding/clash with field “c”. [+1 location]”, “source”: “sonarlint”, “startLineNumber”: 98, “startColumn”: 18, “endLineNumber”: 98, “endColumn”: 19 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1845”, “severity”: 1, “message”: “Rename method “d” to prevent any misunderstanding/clash with field “d”. [+1 location]”, “source”: “sonarlint”, “startLineNumber”: 112, “startColumn”: 18, “endLineNumber”: 112, “endColumn”: 19 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1845”, “severity”: 1, “message”: “Rename method “a” to prevent any misunderstanding/clash with field “a”. [+1 location]”, “source”: “sonarlint”, “startLineNumber”: 130, “startColumn”: 17, “endLineNumber”: 130, “endColumn”: 18 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1905”, “severity”: 1, “message”: “Remove this unnecessary cast to “double”.”, “source”: “sonarlint”, “startLineNumber”: 134, “startColumn”: 30, “endLineNumber”: 134, “endColumn”: 38 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1905”, “severity”: 1, “message”: “Remove this unnecessary cast to “double”.”, “source”: “sonarlint”, “startLineNumber”: 134, “startColumn”: 53, “endLineNumber”: 134, “endColumn”: 61 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1905”, “severity”: 1, “message”: “Remove this unnecessary cast to “double”.”, “source”: “sonarlint”, “startLineNumber”: 135, “startColumn”: 53, “endLineNumber”: 135, “endColumn”: 61 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1905”, “severity”: 1, “message”: “Remove this unnecessary cast to “double”.”, “source”: “sonarlint”, “startLineNumber”: 135, “startColumn”: 30, “endLineNumber”: 135, “endColumn”: 38 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1845”, “severity”: 1, “message”: “Rename method “b” to prevent any misunderstanding/clash with field “b”. [+1 location]”, “source”: “sonarlint”, “startLineNumber”: 142, “startColumn”: 17, “endLineNumber”: 142, “endColumn”: 18 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1905”, “severity”: 1, “message”: “Remove this unnecessary cast to “double”.”, “source”: “sonarlint”, “startLineNumber”: 145, “startColumn”: 30, “endLineNumber”: 145, “endColumn”: 38 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1905”, “severity”: 1, “message”: “Remove this unnecessary cast to “double”.”, “source”: “sonarlint”, “startLineNumber”: 145, “startColumn”: 53, “endLineNumber”: 145, “endColumn”: 61 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1905”, “severity”: 1, “message”: “Remove this unnecessary cast to “double”.”, “source”: “sonarlint”, “startLineNumber”: 147, “startColumn”: 53, “endLineNumber”: 147, “endColumn”: 61 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Vec3D.java”, “code”: “java:S1905”, “severity”: 1, “message”: “Remove this unnecessary cast to “double”.”, “source”: “sonarlint”, “startLineNumber”: 147, “startColumn”: 30, “endLineNumber”: 147, “endColumn”: 38 } ]
8db05187de1ba52e71b7d03c0d92f4f3
{ "intermediate": 0.2852897346019745, "beginner": 0.4315328001976013, "expert": 0.2831774353981018 }
37,450
Can you provide proper indentation? # Kirbo & Kerbo’s Adventure v1.0 # v0.5 - Literally added a function player model. # v1.0 - Managed to fix some bugs with crouching and added a second player model. # v1.1 - Fixed crouching and moving at the same time. import pygame import sys import time # Set up display screen = pygame.display.set_mode((900, 700)) # Set up colors (RGB format) kirby_pink_color = (255, 105, 180) kirby_yellow_color = (255, 255, 0) ground_color = (0, 255, 0) # Kirby properties circle_radius1 = 25 # Initial radius circle_radius2 = 25 # Initial radius circle_y_offset1 = 25 # Offset from the top of Kirby1 circle_y_offset2 = 25 # Offset from the top of Kirby2 crouch_scale1 = 0.5 # Crouch scale for the Kirby1 crouch_scale2 = 0.5 # Crouch scale for the Kirby2 # Kirby1 position and velocity kirby1_x, kirby1_y = 425, 500 kirby1_x_speed, kirby1_y_speed = 0, 0 gravity1 = 1 jump_height1 = -15 # Set jump height for Kirby1 # Kirby2 position and velocity kirby2_x, kirby2_y = 425, 500 kirby2_x_speed, kirby2_y_speed = 0, 0 gravity2 = 1 jump_height2 = -15 # Set jump height for Kirby2 # Kirby1 crouching and in air states is_crouching1 = False in_air1 = False # Kirby2 crouching and in air states is_crouching2 = False in_air2 = False # Kirby1 movement flags is_moving_left1 = False is_moving_right1 = False is_floating1 = False # Kirby 2 movement flags is_moving_left2 = False is_moving_right2 = False is_floating2 = False # Load the Kirby face image kirby_face1 = pygame.image.load(“kirby_face.png”) kirby_face2 = pygame.image.load(“kirby_face.png”) # Game loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_s and not is_crouching1 and not is_moving_left1 and not is_moving_right1: is_crouching1 = True elif event.key == pygame.K_k and not is_crouching2 and not is_moving_left2 and not is_moving_right2: is_crouching2 = True elif event.key == pygame.K_w and not in_air1: kirby_y_speed1 = jump_height1 in_air1 = True elif event.key == pygame.K_i and not in_air2: kirby2_y_speed = jump_height2 in_air2 = True elif event.key == pygame.K_e and not is_crouching1: is_floating1 = True elif event.key == pygame.K_o and not is_crouching2: is_floating2 = True elif event.key == pygame.K_r: is_floating1 = False elif event.key == pygame.K_p: is_floating2 = False elif event.key == pygame.K_a and not is_crouching1: is_moving_left1 = True elif event.key == pygame.K_d and not is_crouching1: is_moving_right1 = True elif event.key == pygame.K_j: is_moving_left2 = True elif event.key == pygame.K_l: is_moving_right2 = True elif event.type == pygame.KEYUP: if event.key == pygame.K_s: is_crouching1 = False elif event.key == pygame.K_k: is_crouching2 = False elif event.key == pygame.K_a: is_moving_left1 = False elif event.key == pygame.K_j: is_moving_left2 = False elif event.key == pygame.K_d: is_moving_right1 = False elif event.key == pygame.K_l: is_moving_right2 = False # Kirby1 Floating set up if is_floating1: gravity1 = 0.3 jump_height1 = -6.5 in_air1 = False is_crouching1 = False circle_radius1 = 35 circle_y_offset1 = 35 else: gravity1 = 1 jump_height1 = -15 in_air1 = True circle_radius1 = 25 circle_y_offset1 = 25 # Kirby2 Floating set up if is_floating2: gravity2 = 0.3 jump_height2 = -6.5 in_air2 = False is_crouching2 = False circle_radius2 = 35 circle_y_offset2 = 35 else: gravity2 = 1 jump_height2 = -15 in_air2 = True circle_radius2 = 25 circle_y_offset2 = 25 # Apply gravity to Kirby1 kirby1_y_speed += gravity1 # Apply gravity to Kirby2 kirby2_y_speed += gravity2 # Apply horizontal motion for Kirby1 if is_moving_left1: kirby1_x_speed = -5 elif is_moving_right1: kirby1_x_speed = 5 else: kirby1_x_speed = 0 # Apply horizontal motion for Kirby 2 if is_moving_left2: kirby2_x_speed = -5 elif is_moving_right2: kirby2_x_speed = 5 else: kirby2_x_speed = 0 # Update Kirby1 position kirby1_x += kirby1_x_speed kirby1_y += kirby1_y_speed # Update Kirby2 position kirby2_x += kirby2_x_speed kirby2_y += kirby2_y_speed # Collision with the ground for Kirby1 if kirby1_y + circle_radius1 >= 575: kirby1_y = 575 - circle_radius1 kirby_y_speed1 = 0 gravity1 = 1 jump_height1 = -15 is_floating1 = False in_air1 = False # Kirby1 is on the ground # Collision with the ground for Kirby2 if kirby2_y + circle_radius2 >= 575: kirby2_y = 575 - circle_radius2 kirby2_y_speed = 0 gravity2 = 1 jump_height2 = -15 is_floating2 = False in_air2 = False # Kirby2 is on the ground # Collision with the sides of the screen for Kirby1 if kirby1_x < 0: kirby1_x = 0 elif kirby1_x > 900 - 2 * circle_radius1: kirby1_x = 900 - 2 * circle_radius1 # Collision with the sides of the screen for Kirby2 if kirby2_x < 0: kirby2_x = 0 elif kirby2_x > 900 - 2 * circle_radius2: kirby2_x = 900 - 2 * circle_radius2 # Draw background screen.fill((100, 100, 255)) # Blue background # Draw ground pygame.draw.rect(screen, ground_color, (0, 600, 900, 50)) # Draw Kirby1 if is_crouching1: pygame.draw.ellipse(screen, kirby_pink_color, (int(kirby1_x), int(kirby1_y + circle_radius1 * (1.5 - crouch_scale1)), int(2 * circle_radius1), int(crouch_scale1 * 2 * circle_radius1))) # Scale and draw the Kirby face when crouching kirby_face_scaled1 = pygame.transform.scale(kirby_face1, (int(2 * circle_radius1), int(2 * circle_radius1 * crouch_scale1))) screen.blit(kirby_face_scaled1, (int(kirby1_x), int(kirby1_y + circle_radius1 * (1.5 - crouch_scale1)))) else: pygame.draw.circle(screen, kirby_pink_color, (int(kirby1_x + circle_radius1), int(kirby1_y + circle_radius1)), circle_radius1) # Scale and draw the Kirby face when not crouching kirby_face_scaled1 = pygame.transform.scale(kirby_face1, (int(2 * circle_radius1), int(2 * circle_radius1))) screen.blit(kirby_face_scaled1, (int(kirby1_x), int(kirby1_y))) # Draw Kirby2 if is_crouching2: pygame.draw.ellipse(screen, kirby_yellow_color, (int(kirby2_x), int(kirby2_y + circle_radius2 * (1.5 - crouch_scale2)), int(2 * circle_radius2), int(crouch_scale2 * 2 * circle_radius2))) # Scale and draw the Kirby face when crouching kirby_face_scaled2 = pygame.transform.scale(kirby_face2, (int(2 * circle_radius2), int(2 * circle_radius2 * crouch_scale2))) screen.blit(kirby_face_scaled2, (int(kirby2_x), int(kirby2_y + circle_radius2 * (1.5 - crouch_scale2)))) else: pygame.draw.circle(screen, kirby_yellow_color, (int(kirby2_x + circle_radius2), int(kirby2_y + circle_radius2)), circle_radius2) # Scale and draw the Kirby face when not crouching kirby_face_scaled2 = pygame.transform.scale(kirby_face2, (int(2* circle_radius2), int(1.8 * circle_radius2))) # Different value here because the engine is being stupid and Kirby1 copies this value for some reason. screen.blit(kirby_face_scaled2, (int(kirby2_x), int(kirby2_y))) # Update the display pygame.display.flip() # Cap the frame rate pygame.time.Clock().tick(60)
411ec7e15c2306cd65b5613d34bf2392
{ "intermediate": 0.28593116998672485, "beginner": 0.4880349636077881, "expert": 0.22603386640548706 }
37,451
Give fixed code without comments [ { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java", "code": "java:S2065", "severity": 1, "message": "Remove the \"transient\" modifier from this field.", "source": "sonarlint", "startLineNumber": 8, "startColumn": 13, "endLineNumber": 8, "endColumn": 22 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java", "code": "java:S2065", "severity": 1, "message": "Remove the \"transient\" modifier from this field.", "source": "sonarlint", "startLineNumber": 9, "startColumn": 13, "endLineNumber": 9, "endColumn": 22 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java", "code": "java:S1170", "severity": 1, "message": "Make this final field static too.", "source": "sonarlint", "startLineNumber": 11, "startColumn": 25, "endLineNumber": 11, "endColumn": 26 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java", "code": "java:S2065", "severity": 1, "message": "Remove the \"transient\" modifier from this field.", "source": "sonarlint", "startLineNumber": 12, "startColumn": 13, "endLineNumber": 12, "endColumn": 22 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java", "code": "java:S1186", "severity": 1, "message": "Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.", "source": "sonarlint", "startLineNumber": 15, "startColumn": 12, "endLineNumber": 15, "endColumn": 22 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java", "code": "java:S3078", "severity": 1, "message": "Use an \"AtomicInteger\" for this field; its operations are atomic.", "source": "sonarlint", "startLineNumber": 66, "startColumn": 9, "endLineNumber": 66, "endColumn": 17 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java", "code": "java:S2234", "severity": 1, "message": "Parameters to a have the same names but not the same order as the method arguments. [+2 locations]", "source": "sonarlint", "startLineNumber": 67, "startColumn": 15, "endLineNumber": 67, "endColumn": 32 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java", "code": "java:S1905", "severity": 1, "message": "Remove this unnecessary cast to \"float\".", "source": "sonarlint", "startLineNumber": 81, "startColumn": 29, "endLineNumber": 81, "endColumn": 36 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java", "code": "java:S3078", "severity": 1, "message": "Use an \"AtomicInteger\" for this field; its operations are atomic.", "source": "sonarlint", "startLineNumber": 127, "startColumn": 17, "endLineNumber": 127, "endColumn": 25 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java", "code": "java:S3078", "severity": 1, "message": "Use an \"AtomicInteger\" for this field; its operations are atomic.", "source": "sonarlint", "startLineNumber": 145, "startColumn": 9, "endLineNumber": 145, "endColumn": 17 } ]
ca146df515fad92c9f2be0bf3daf15f0
{ "intermediate": 0.33019641041755676, "beginner": 0.3839642107486725, "expert": 0.28583937883377075 }
37,452
Can you add a title screen where you can select 1 or 2 players? 1 for 1 player 2 for 2. If one is chosen then disable the second players controls and drawing.
8288ecabcba4108e601c40b224cacab8
{ "intermediate": 0.40548548102378845, "beginner": 0.2583902180194855, "expert": 0.3361242711544037 }
37,453
Give fixed code without comments [ { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java”, “code”: “java:S2065”, “severity”: 1, “message”: “Remove the “transient” modifier from this field.”, “source”: “sonarlint”, “startLineNumber”: 8, “startColumn”: 13, “endLineNumber”: 8, “endColumn”: 22 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java”, “code”: “java:S2065”, “severity”: 1, “message”: “Remove the “transient” modifier from this field.”, “source”: “sonarlint”, “startLineNumber”: 9, “startColumn”: 13, “endLineNumber”: 9, “endColumn”: 22 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java”, “code”: “java:S1170”, “severity”: 1, “message”: “Make this final field static too.”, “source”: “sonarlint”, “startLineNumber”: 11, “startColumn”: 25, “endLineNumber”: 11, “endColumn”: 26 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java”, “code”: “java:S2065”, “severity”: 1, “message”: “Remove the “transient” modifier from this field.”, “source”: “sonarlint”, “startLineNumber”: 12, “startColumn”: 13, “endLineNumber”: 12, “endColumn”: 22 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java”, “code”: “java:S1186”, “severity”: 1, “message”: “Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.”, “source”: “sonarlint”, “startLineNumber”: 15, “startColumn”: 12, “endLineNumber”: 15, “endColumn”: 22 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java”, “code”: “java:S3078”, “severity”: 1, “message”: “Use an “AtomicInteger” for this field; its operations are atomic.”, “source”: “sonarlint”, “startLineNumber”: 66, “startColumn”: 9, “endLineNumber”: 66, “endColumn”: 17 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java”, “code”: “java:S2234”, “severity”: 1, “message”: “Parameters to a have the same names but not the same order as the method arguments. [+2 locations]”, “source”: “sonarlint”, “startLineNumber”: 67, “startColumn”: 15, “endLineNumber”: 67, “endColumn”: 32 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java”, “code”: “java:S1905”, “severity”: 1, “message”: “Remove this unnecessary cast to “float”.”, “source”: “sonarlint”, “startLineNumber”: 81, “startColumn”: 29, “endLineNumber”: 81, “endColumn”: 36 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java”, “code”: “java:S3078”, “severity”: 1, “message”: “Use an “AtomicInteger” for this field; its operations are atomic.”, “source”: “sonarlint”, “startLineNumber”: 127, “startColumn”: 17, “endLineNumber”: 127, “endColumn”: 25 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/IntHashMap.java”, “code”: “java:S3078”, “severity”: 1, “message”: “Use an “AtomicInteger” for this field; its operations are atomic.”, “source”: “sonarlint”, “startLineNumber”: 145, “startColumn”: 9, “endLineNumber”: 145, “endColumn”: 17 } ]
ce9da4846937ded6db49f51183d60246
{ "intermediate": 0.3113439679145813, "beginner": 0.4039713740348816, "expert": 0.2846846282482147 }
37,454
Can you add a title screen where you can select 1 or 2 players? 1 for 1 player 2 for 2. If one is chosen then disable the second players controls and drawing. # Kirbo & Kerbo’s Adventure v1.11 #################################################################################################### # v0.5 - Literally added a functioning player model and grass. # v1.0 - Managed to fix some bugs with crouching and added a second player model. # v1.1 - Fixed crouching and moving at the same time. # v1.11 - Fixed the inconsistent face bug finally. import pygame import sys import time # Set up display screen = pygame.display.set_mode((900, 700)) # Set up colors (RGB format) kirby_pink_color = (255, 105, 180) kirby_yellow_color = (255, 255, 0) ground_color = (0, 255, 0) # Kirby properties circle_radius1 = 25 # Initial radius circle_radius2 = 25 # Initial radius circle_y_offset1 = 25 # Offset from the top of Kirby1 circle_y_offset2 = 25 # Offset from the top of Kirby2 crouch_scale1 = 0.5 # Crouch scale for the Kirby1 crouch_scale2 = 0.5 # Crouch scale for the Kirby2 # Kirby1 position and velocity kirby1_x, kirby1_y = 425, 500 kirby1_x_speed, kirby1_y_speed = 0, 0 gravity1 = 1 jump_height1 = -15 # Set jump height for Kirby1 # Kirby2 position and velocity kirby2_x, kirby2_y = 425, 500 kirby2_x_speed, kirby2_y_speed = 0, 0 gravity2 = 1 jump_height2 = -15 # Set jump height for Kirby2 # Kirby1 crouching and in air states is_crouching1 = False in_air1 = False inhale1 = False has_enemy1 = False # Kirby2 crouching and in air states is_crouching2 = False in_air2 = False inhale2 = False has_enemy2 = False # Kirby1 movement flags is_moving_left1 = False is_moving_right1 = False is_floating1 = False # Kirby2 movement flags is_moving_left2 = False is_moving_right2 = False is_floating2 = False # Load the Kirby face images kirby_face1 = pygame.image.load("kirby_face.png") kirby_face2 = pygame.image.load("kirby_face.png") # Game loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_s and not is_crouching1 and not is_moving_left1 and not is_moving_right1: is_crouching1 = True elif event.key == pygame.K_k and not is_crouching2 and not is_moving_left2 and not is_moving_right2: is_crouching2 = True elif event.key == pygame.K_w and not in_air1: kirby1_y_speed = jump_height1 in_air1 = True elif event.key == pygame.K_i and not in_air2: kirby2_y_speed = jump_height2 in_air2 = True elif event.key == pygame.K_e and not is_crouching1: is_floating1 = True elif event.key == pygame.K_o and not is_crouching2: is_floating2 = True elif event.key == pygame.K_r: is_floating1 = False elif event.key == pygame.K_p: is_floating2 = False elif event.key == pygame.K_a and not is_crouching1: is_moving_left1 = True elif event.key == pygame.K_d and not is_crouching1: is_moving_right1 = True elif event.key == pygame.K_j: is_moving_left2 = True elif event.key == pygame.K_l: is_moving_right2 = True elif event.type == pygame.KEYUP: if event.key == pygame.K_s: is_crouching1 = False elif event.key == pygame.K_k: is_crouching2 = False elif event.key == pygame.K_a: is_moving_left1 = False elif event.key == pygame.K_j: is_moving_left2 = False elif event.key == pygame.K_d: is_moving_right1 = False elif event.key == pygame.K_l: is_moving_right2 = False # Kirby1 Floating set up if is_floating1: gravity1 = 0.3 jump_height1 = -6.5 in_air1 = False is_crouching1 = False circle_radius1 = 35 circle_y_offset1 = 35 else: gravity1 = 1 jump_height1 = -15 in_air1 = True circle_radius1 = 25 circle_y_offset1 = 25 # Kirby2 Floating set up if is_floating2: gravity2 = 0.3 jump_height2 = -6.5 in_air2 = False is_crouching2 = False circle_radius2 = 35 circle_y_offset2 = 35 else: gravity2 = 1 jump_height2 = -15 in_air2 = True circle_radius2 = 25 circle_y_offset2 = 25 # Apply gravity to Kirby1 kirby1_y_speed += gravity1 # Apply gravity to Kirby2 kirby2_y_speed += gravity2 # Apply horizontal motion for Kirby1 if is_moving_left1: kirby1_x_speed = -5 elif is_moving_right1: kirby1_x_speed = 5 else: kirby1_x_speed = 0 # Apply horizontal motion for Kirby 2 if is_moving_left2: kirby2_x_speed = -5 elif is_moving_right2: kirby2_x_speed = 5 else: kirby2_x_speed = 0 # Update Kirby1 position kirby1_x += kirby1_x_speed kirby1_y += kirby1_y_speed # Update Kirby2 position kirby2_x += kirby2_x_speed kirby2_y += kirby2_y_speed # Collision with the ground for Kirby1 if kirby1_y + circle_radius1 >= 575: kirby1_y = 575 - circle_radius1 kirby1_y_speed = 0 gravity1 = 1 jump_height1 = -15 is_floating1 = False in_air1 = False # Kirby1 is on the ground # Collision with the ground for Kirby2 if kirby2_y + circle_radius2 >= 575: kirby2_y = 575 - circle_radius2 kirby2_y_speed = 0 gravity2 = 1 jump_height2 = -15 is_floating2 = False in_air2 = False # Kirby2 is on the ground # Collision with the sides of the screen for Kirby1 if kirby1_x < 0: kirby1_x = 0 elif kirby1_x > 900 - 2 * circle_radius1: kirby1_x = 900 - 2 * circle_radius1 # Collision with the sides of the screen for Kirby2 if kirby2_x < 0: kirby2_x = 0 elif kirby2_x > 900 - 2 * circle_radius2: kirby2_x = 900 - 2 * circle_radius2 # Draw background screen.fill((100, 100, 255)) # Blue background # Draw ground pygame.draw.rect(screen, ground_color, (0, 600, 900, 50)) # Draw Kirby1 if is_crouching1: pygame.draw.ellipse(screen, kirby_pink_color, (int(kirby1_x), int(kirby1_y + circle_radius1 * (1.5 - crouch_scale1)), int(2 * circle_radius1), int(crouch_scale1 * 2 * circle_radius1))) # Scale and draw the Kirby face when crouching kirby_face_scaled1 = pygame.transform.scale(kirby_face1, (int(2 * circle_radius1), int(2 * circle_radius1 * crouch_scale1))) screen.blit(kirby_face_scaled1, (int(kirby1_x), int(kirby1_y + circle_radius1 * (1.5 - crouch_scale1)))) else: pygame.draw.circle(screen, kirby_pink_color, (int(kirby1_x + circle_radius1), int(kirby1_y + circle_radius1)), circle_radius1) # Scale and draw the Kirby face when not crouching kirby_face_scaled1 = pygame.transform.scale(kirby_face1, (int(2 * circle_radius1), int(2 * circle_radius1))) screen.blit(kirby_face_scaled1, (int(kirby1_x), int(kirby1_y))) # Draw Kirby2 if is_crouching2: pygame.draw.ellipse(screen, kirby_yellow_color, (int(kirby2_x), int(kirby2_y + circle_radius2 * (1.5 - crouch_scale2)), int(2 * circle_radius2), int(crouch_scale2 * 2 * circle_radius2))) # Scale and draw the Kirby face when crouching kirby_face_scaled2 = pygame.transform.scale(kirby_face2, (int(2 * circle_radius2), int(2 * circle_radius2 * crouch_scale2))) screen.blit(kirby_face_scaled2, (int(kirby2_x), int(kirby2_y + circle_radius2 * (1.5 - crouch_scale2)))) else: pygame.draw.circle(screen, kirby_yellow_color, (int(kirby2_x + circle_radius2), int(kirby2_y + circle_radius2)), circle_radius2) # Scale and draw the Kirby face when not crouching kirby_face_scaled2 = pygame.transform.scale(kirby_face2, (int(2 * circle_radius2), int(2 * circle_radius2))) # Different value here because the engine is being stupid and Kirby1 copies this value for some reason. screen.blit(kirby_face_scaled2, (int(kirby2_x), int(kirby2_y))) # Update the display pygame.display.flip() # Cap the frame rate pygame.time.Clock().tick(60)
deab804526875aa0da9254124ad26bf4
{ "intermediate": 0.34362319111824036, "beginner": 0.4707443416118622, "expert": 0.18563255667686462 }
37,455
non inferiority z-test in R for two independent proportions in R
dac425fa8cf34e892d34c6e2036a3d16
{ "intermediate": 0.27944236993789673, "beginner": 0.21678732335567474, "expert": 0.5037702918052673 }
37,456
Fixed code without comments [ { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java", "code": "java:S3740", "severity": 1, "message": "Provide the parametrized type for this generic.", "source": "sonarlint", "startLineNumber": 8, "startColumn": 19, "endLineNumber": 8, "endColumn": 23 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java", "code": "java:S3740", "severity": 1, "message": "Provide the parametrized type for this generic.", "source": "sonarlint", "startLineNumber": 19, "startColumn": 22, "endLineNumber": 19, "endColumn": 31 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java", "code": "java:S1604", "severity": 1, "message": "Make this anonymous inner class a lambda (sonar.java.source not set. Assuming 8 or greater.)", "source": "sonarlint", "startLineNumber": 24, "startColumn": 69, "endLineNumber": 24, "endColumn": 77 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java", "code": "java:S1604", "severity": 1, "message": "Make this anonymous inner class a lambda (sonar.java.source not set. Assuming 8 or greater.)", "source": "sonarlint", "startLineNumber": 43, "startColumn": 110, "endLineNumber": 43, "endColumn": 118 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java", "code": "java:S3776", "severity": 1, "message": "Refactor this method to reduce its Cognitive Complexity from 35 to the 15 allowed. [+11 locations]", "source": "sonarlint", "startLineNumber": 100, "startColumn": 17, "endLineNumber": 100, "endColumn": 18 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java", "code": "java:S3740", "severity": 1, "message": "Provide the parametrized type for this generic.", "source": "sonarlint", "startLineNumber": 125, "startColumn": 29, "endLineNumber": 125, "endColumn": 33 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java", "code": "java:S3740", "severity": 1, "message": "Provide the parametrized type for this generic.", "source": "sonarlint", "startLineNumber": 165, "startColumn": 12, "endLineNumber": 165, "endColumn": 16 } ]
b2c6581e9de01e25eb053b963d698938
{ "intermediate": 0.3661482632160187, "beginner": 0.3729385435581207, "expert": 0.260913223028183 }
37,457
Fix code without comments and get fully fixed code [ { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java”, “code”: “java:S3740”, “severity”: 1, “message”: “Provide the parametrized type for this generic.”, “source”: “sonarlint”, “startLineNumber”: 8, “startColumn”: 19, “endLineNumber”: 8, “endColumn”: 23 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java”, “code”: “java:S3740”, “severity”: 1, “message”: “Provide the parametrized type for this generic.”, “source”: “sonarlint”, “startLineNumber”: 19, “startColumn”: 22, “endLineNumber”: 19, “endColumn”: 31 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java”, “code”: “java:S1604”, “severity”: 1, “message”: “Make this anonymous inner class a lambda (sonar.java.source not set. Assuming 8 or greater.)”, “source”: “sonarlint”, “startLineNumber”: 24, “startColumn”: 69, “endLineNumber”: 24, “endColumn”: 77 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java”, “code”: “java:S1604”, “severity”: 1, “message”: “Make this anonymous inner class a lambda (sonar.java.source not set. Assuming 8 or greater.)”, “source”: “sonarlint”, “startLineNumber”: 43, “startColumn”: 110, “endLineNumber”: 43, “endColumn”: 118 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java”, “code”: “java:S3776”, “severity”: 1, “message”: “Refactor this method to reduce its Cognitive Complexity from 35 to the 15 allowed. [+11 locations]”, “source”: “sonarlint”, “startLineNumber”: 100, “startColumn”: 17, “endLineNumber”: 100, “endColumn”: 18 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java”, “code”: “java:S3740”, “severity”: 1, “message”: “Provide the parametrized type for this generic.”, “source”: “sonarlint”, “startLineNumber”: 125, “startColumn”: 29, “endLineNumber”: 125, “endColumn”: 33 }, { “resource”: “/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/PlayerChunk.java”, “code”: “java:S3740”, “severity”: 1, “message”: “Provide the parametrized type for this generic.”, “source”: “sonarlint”, “startLineNumber”: 165, “startColumn”: 12, “endLineNumber”: 165, “endColumn”: 16 } ]
d5b760f27797f228c19f10b94153c1af
{ "intermediate": 0.30031126737594604, "beginner": 0.36067891120910645, "expert": 0.3390098214149475 }
37,458
move to higher analysis and next review this contract line by line and with depth understanding and higher analysis and apply are what you learn from found valid vulnerabilities and find every possible vulnerabilities that is present in the contract and can cause damage to and give their severity here is the contract // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; // ███████╗███████╗██████╗ ██████╗ // ╚══███╔╝██╔════╝██╔══██╗██╔═══██╗ // ███╔╝ █████╗ ██████╔╝██║ ██║ // ███╔╝ ██╔══╝ ██╔══██╗██║ ██║ // ███████╗███████╗██║ ██║╚██████╔╝ // ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═════╝ // Website: https://zerolend.xyz // Discord: https://discord.gg/zerolend // Twitter: https://twitter.com/zerolendxyz import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IFeeDistributor} from "./interfaces/IFeeDistributor.sol"; import {IZeroLocker} from "./interfaces/IZeroLocker.sol"; contract FeeDistributor is IFeeDistributor, ReentrancyGuard, Initializable { uint256 public WEEK; uint256 public TOKEN_CHECKPOINT_DEADLINE; uint256 public startTime; uint256 public timeCursor; mapping(uint256 => uint256) public timeCursorOf; mapping(uint256 => uint256) public userEpochOf; uint256 public lastTokenTime; uint256[1000000000000000] public tokensPerWeek; IZeroLocker public locker; IERC20 public token; uint256 public tokenLastBalance; uint256[1000000000000000] public veSupply; // VE total supply at week bounds // constructor() { // _disableInitializers(); // } function initialize( address _votingEscrow, address _token ) external initializer { WEEK = 7 * 86400; TOKEN_CHECKPOINT_DEADLINE = 86400; // round off the time uint256 t = (block.timestamp / WEEK) * WEEK; startTime = t; lastTokenTime = t; timeCursor = t; token = IERC20(_token); locker = IZeroLocker(_votingEscrow); } function _checkpointToken(uint256 timestamp) internal { uint256 tokenBalance = token.balanceOf(address(this)); uint256 toDistribute = tokenBalance - tokenLastBalance; tokenLastBalance = tokenBalance; uint256 t = lastTokenTime; uint256 sinceLast = timestamp - t; lastTokenTime = timestamp; uint256 thisWeek = (t / WEEK) * WEEK; uint256 nextWeek = 0; for (uint256 index = 0; index < 20; index++) { nextWeek = thisWeek + WEEK; if (timestamp < nextWeek) { if (sinceLast == 0 && timestamp == t) tokensPerWeek[thisWeek] += toDistribute; else tokensPerWeek[thisWeek] += (toDistribute * (timestamp - t)) / sinceLast; break; } else { if (sinceLast == 0 && nextWeek == t) tokensPerWeek[thisWeek] += toDistribute; else tokensPerWeek[thisWeek] += (toDistribute * (nextWeek - t)) / sinceLast; } t = nextWeek; thisWeek = nextWeek; } emit CheckpointToken(timestamp, toDistribute); } function checkpointToken() external override { require( ((block.timestamp > lastTokenTime + TOKEN_CHECKPOINT_DEADLINE)), "cant checkpoint now" ); _checkpointToken(block.timestamp); } function _findTimestampEpoch( uint256 _timestamp ) internal view returns (uint256) { uint256 min = 0; uint256 max = locker.epoch(); for (uint256 index = 0; index < 128; index++) { if (min >= max) { break; } uint256 mid = (min + max + 2) / 2; IZeroLocker.Point memory pt = locker.pointHistory(mid); if (pt.ts <= _timestamp) min = mid; else max = mid - 1; } return min; } function _findTimestampUserEpoch( uint256 nftId, uint256 _timestamp, uint256 maxUserEpoch ) internal view returns (uint256) { uint256 min = 0; uint256 max = maxUserEpoch; for (uint256 index = 0; index < 128; index++) { if (min >= max) { break; } uint256 mid = (min + max + 2) / 2; IZeroLocker.Point memory pt = locker.userPointHistory(nftId, mid); if (pt.ts <= _timestamp) min = mid; else max = mid - 1; } return min; } function _checkpointTotalSupply(uint256 timestamp) internal { uint256 t = timeCursor; uint256 roundedTimestamp = (timestamp / WEEK) * WEEK; locker.checkpoint(); for (uint256 index = 0; index < 20; index++) { if (t > roundedTimestamp) break; else { uint256 epoch = _findTimestampEpoch(t); IZeroLocker.Point memory pt = locker.pointHistory(epoch); int128 dt = 0; if (t > pt.ts) dt = int128(uint128(t - pt.ts)); veSupply[t] = Math.max(uint128(pt.bias - pt.slope * dt), 0); } t += WEEK; } timeCursor = t; } function checkpointTotalSupply() external override { _checkpointTotalSupply(block.timestamp); } function _claim( uint256 nftId, uint256 _lastTokenTime ) internal returns (uint256) { uint256 userEpoch = 0; uint256 toDistribute = 0; uint256 maxUserEpoch = locker.userPointEpoch(nftId); uint256 _startTime = startTime; if (maxUserEpoch == 0) return 0; uint256 weekCursor = timeCursorOf[nftId]; if (weekCursor == 0) userEpoch = _findTimestampUserEpoch( nftId, _startTime, maxUserEpoch ); else userEpoch = userEpochOf[nftId]; if (userEpoch == 0) userEpoch = 1; IZeroLocker.Point memory userPoint = locker.userPointHistory( nftId, userEpoch ); if (weekCursor == 0) weekCursor = ((userPoint.ts + WEEK - 1) / WEEK) * WEEK; if (weekCursor >= _lastTokenTime) return 0; if (weekCursor < _startTime) weekCursor = _startTime; IZeroLocker.Point memory oldUserPoint = IZeroLocker.Point(0, 0, 0, 0); for (uint256 index = 0; index < 50; index++) { if (weekCursor >= _lastTokenTime) break; if (weekCursor >= userPoint.ts && userEpoch <= maxUserEpoch) { userEpoch += 1; oldUserPoint = userPoint; if (userEpoch > maxUserEpoch) userPoint = IZeroLocker.Point(0, 0, 0, 0); else userPoint = locker.userPointHistory(nftId, userEpoch); } else { int128 dt = int128(uint128(weekCursor - oldUserPoint.ts)); uint256 balanceOf = Math.max( uint128(oldUserPoint.bias - dt * oldUserPoint.slope), 0 ); if (balanceOf == 0 && userEpoch > maxUserEpoch) break; if (balanceOf > 0) toDistribute += (balanceOf * tokensPerWeek[weekCursor]) / veSupply[weekCursor]; weekCursor += WEEK; } } userEpoch = Math.min(maxUserEpoch, userEpoch - 1); userEpochOf[nftId] = userEpoch; timeCursorOf[nftId] = weekCursor; emit Claimed(nftId, toDistribute, userEpoch, maxUserEpoch); return toDistribute; } function _claimWithChecks(uint256 nftId) internal returns (uint256) { if (block.timestamp >= timeCursor) _checkpointTotalSupply(block.timestamp); uint256 _lastTokenTime = lastTokenTime; if ((block.timestamp > lastTokenTime + TOKEN_CHECKPOINT_DEADLINE)) { _checkpointToken(block.timestamp); _lastTokenTime = block.timestamp; } _lastTokenTime = (_lastTokenTime / WEEK) * WEEK; uint256 amount = _claim(nftId, _lastTokenTime); address who = locker.ownerOf(nftId); if (amount != 0) { tokenLastBalance -= amount; token.transfer(who, amount); } return amount; } function claim( uint256 id ) external override nonReentrant returns (uint256) { return _claimWithChecks(id); } function claimMany( uint256[] memory nftIds ) external override nonReentrant returns (bool) { if (block.timestamp >= timeCursor) _checkpointTotalSupply(block.timestamp); uint256 _lastTokenTime = lastTokenTime; if ((block.timestamp > lastTokenTime + TOKEN_CHECKPOINT_DEADLINE)) { _checkpointToken(block.timestamp); _lastTokenTime = block.timestamp; } _lastTokenTime = (_lastTokenTime / WEEK) * WEEK; for (uint256 index = 0; index < nftIds.length; index++) { uint256 amount = _claim(nftIds[index], _lastTokenTime); address who = locker.ownerOf(nftIds[index]); if (amount != 0) { tokenLastBalance -= amount; token.transfer(who, amount); } } return true; } } give every vulnerable line with code that contain the issues and explaining with evidence the existing of the vulnerabilities
b1a5fd165046f7e5f7ea23c54350ca0f
{ "intermediate": 0.3330020010471344, "beginner": 0.34557464718818665, "expert": 0.32142341136932373 }
37,459
#ifndef HP_FILE_H #define HP_FILE_H #include <stddef.h> #include "record.h" #include "bf.h" typedef struct HP_info{ int lastBlockId; int totalRecords; int blockCapacity; } HP_info; extern struct HP_info openFiles[20]; /*The function HP_CreateFile is used to create and appropriately initialize an empty heap file with the given fileName. If the execution is successful, it returns 0; otherwise, it returns -1.*/ int HP_CreateFile(char *fileName); /* The function HP_OpenFile opens the file with the name filename. The variable *file_desc refers to the opening identifier of this file as derived from BF_OpenFile.*/ int HP_OpenFile(char *fileName, int *file_desc); /* The function HP_CloseFile closes the file identified by the descriptor file_desc. If the operation is successful, it returns 0; otherwise, it returns -1.*/ int HP_CloseFile(int file_desc); /* The function HP_InsertEntry is used to insert a record into the heap file. The identifier for the file is file_desc, and the record to be inserted is specified by the record structure. If the operation is successful, it returns 1; otherwise, it returns -1.*/ int HP_InsertEntry(int file_desc, Record record); /* The function HP_GetRecord is designed to retrieve a record from a heap file specified by the file descriptor file_desc. It takes three parameters: blockId, which indicates the block from which to retrieve the record, cursor, which specifies the position of the record within that block, and record, which is a pointer to a Record structure. The retrieved record will be stored in the memory location pointed to by the record parameter.*/ int HP_GetRecord( int file_desc, int blockId, int cursor, Record* record); /* The function HP_UpdateRecord updates or sets a record in a heap file specified by the file descriptor file_desc. It takes four parameters: blockId, which indicates the block where the record will be updated, cursor, which specifies the position of the record within that block, and record, which is the new data that will replace the existing record at the specified location. If the operation is successful, the function returns 1; otherwise, it returns -1.*/ int HP_UpdateRecord(int file_desc, int blockId, int cursor,Record record); /* The function HP_Unpin is designed to release the block identified by blockId in the heap file associated with the descriptor file_desc. If the unpin is successful, it returns 0; otherwise, it returns -1.*/ int HP_Unpin(int file_desc, int blockId); // Prints all entries(records) stored in the heap file. int HP_PrintAllEntries(int file_desc); // Retrieves the current record count in a specified block. int HP_GetRecordCounter(int file_desc, int blockId); // Returns the identifier of the last block in the heap file. int HP_GetIdOfLastBlock(int file_desc); // Retrieves the number of records that can fit in a block of the heap file. int HP_GetMaxRecordsInBlock(int file_desc); // Prints all entries(records) contained in the specified block of the heap file. int HP_PrintBlockEntries(int file_desc, int blockId); #endif // HP_FILE_H
9833484be3f14c9db249b0420858a4ea
{ "intermediate": 0.2404457926750183, "beginner": 0.5833695530891418, "expert": 0.17618460953235626 }
37,460
import os import subprocess import numpy as np import uuid # Import uuid to generate unique IDs from moviepy.editor import VideoFileClip from scipy.io import wavfile import random import tempfile import shutil temporary_audio_files = [] # Define video file extensions and the output folder video_extensions = ['.mp4', '.mkv', '.wmv', '.avi'] output_folder = 'Output' def get_video_durations(include_subfolders): video_durations = {} for root, dirs, files in os.walk('.', topdown=True): if not include_subfolders: dirs[:] = [] for file in files: if file.lower().endswith(tuple(video_extensions)): video_path = os.path.join(root, file) try: # Open the video file and extract metadata video_clip = VideoFileClip(video_path) if not video_clip.audio: # Vérifier si la vidéo a une piste audio print(f"La vidéo {video_path} n'a pas de piste audio.") continue # Passer à la vidéo suivante video_duration = video_clip.duration video_durations[video_path] = video_duration except Exception as e: print(f"Error processing video {video_path}: {e}") finally: video_clip.close() # Make sure to close the clip to release resources return video_durations def ask_min_or_max_duration_preference(): print("Souhaitez-vous vous baser sur la durée de la vidéo la plus courte ou la plus longue pour le calcul du nombre de segments ?") print("1- Sur la vidéo la plus courte") print("2- Sur la vidéo la plus longue") while True: choice = input("Veuillez entrer votre choix (1 ou 2) : ") if choice in ('1', '2'): return choice else: print("Entrée non valide, veuillez réessayer.") def ask_batch_or_individual_processing(): print("Comment souhaitez-vous traiter les fichiers vidéo ?") print("1- Par lot (traiter tous les fichiers avec les mêmes paramètres)") print("2- Individuellement (définir des paramètres pour chaque fichier)") while True: choice = input("Veuillez entrer le numéro de votre choix (1 ou 2) : ").strip() if choice in ('1', '2'): return choice else: print("Entrée non valide, veuillez réessayer.") def ask_for_number_of_moments(max_segments): while True: num_input = input(f"Veuillez entrer le nombre de moments forts à extraire (maximum {max_segments}): ") try: num = int(num_input) if num > 0 and num <= max_segments: return num else: print(f"Le nombre doit être supérieur à 0 et inférieur ou égal à {max_segments}. Veuillez réessayer.") except ValueError: print("Entrée non valide, veuillez réessayer avec un nombre entier.") def ask_yes_no_question(question): answer = None while answer not in ('1', '2'): print(question) print("1- Oui") print("2- Non") answer = input("Veuillez entrer le numéro de votre choix (1 ou 2) : ").strip() if answer not in ('1', '2'): print("Entrée non valide, veuillez réessayer.") return answer == '1' def ask_offset_type(): print("Souhaitez-vous un décalage temporel relatif ou absolu ?") print("1- Relatif (pourcentage)") print("2- Absolu (secondes)") while True: choice = input("Veuillez entrer le numéro de votre choix (1 ou 2) : ").strip() if choice in ('1', '2'): return choice else: print("Entrée non valide, veuillez réessayer.") def get_offset_value(video_duration, offset_type): if offset_type == '1': # Relative offset while True: percent = input("Entrez le pourcentage du temps vidéo à ignorer : ") try: percent_value = float(percent) return percent_value * video_duration / 100 except ValueError: print("Veuillez entrer un nombre valide.") else: # Absolute offset while True: seconds = input("Entrez le nombre de secondes à ignorer : ") try: return float(seconds) except ValueError: print("Veuillez entrer un nombre valide.") def ask_for_segment_duration(allowable_duration, video_duration, starting_offset_seconds, ending_offset_seconds): while True: duration = input("Quelle est la durée (en secondes) de chaque segment vidéo à extraire ? ") try: segment_duration = float(duration) if segment_duration > 0 and segment_duration <= allowable_duration: # Calculez le nombre maximal de segments pour une vidéo available_duration = video_duration - (starting_offset_seconds + ending_offset_seconds) max_segments = int(available_duration // segment_duration) return segment_duration, max_segments else: print(f"La durée doit être un nombre positif et inférieure ou égale à {allowable_duration} secondes.") except ValueError: print("Veuillez entrer un nombre valide.") def ask_directory_preference(): print("Souhaitez-vous inclure les sous-dossiers dans la recherche des vidéos ?") print("1- Oui") print("2- Non") choice = input("Veuillez entrer le numéro de votre choix (1 ou 2) : ") return choice.strip() == '1' # Retourne True si l'utilisateur choisit '1' (Oui), False sinon def calculate_loudness(audio_data): if audio_data.ndim == 1: volume = audio_data.astype('float32') ** 2 else: volume = np.mean(audio_data.astype('float32') ** 2, axis=1) volume_dB = 10 * np.log10(volume + 1e-9) # +1e-9 to avoid log(0) and convert to dB return volume_dB def find_loudest_moments(audio_filename, num_moments, segment_duration, video_duration, starting_offset, ending_offset): try: # Read the audio data from the file rate, audio_data = wavfile.read(audio_filename) if audio_data.ndim == 2: # if stereo, average the channels to mono audio_data = np.mean(audio_data, axis=1) volume_dB = calculate_loudness(audio_data) segment_half_duration = segment_duration / 2.0 start_index = int(starting_offset * rate) end_index = int((video_duration - ending_offset) * rate) moments = [] volumes = [] # While there are fewer moments found than requested and there is still data to analyze while len(moments) < num_moments and (end_index - start_index) > int(segment_duration * rate): index = np.argmax(volume_dB[start_index:end_index]) moment = (start_index + index) / rate moment_volume = volume_dB[start_index + index] # Check if the moment is within allowed offsets and add it to the list if so if moment - segment_half_duration >= starting_offset and moment + segment_half_duration <= video_duration - ending_offset: moments.append(moment) volumes.append(moment_volume) # Clear the volume around the found moment to prevent picking up nearby moments clear_range_start = max(start_index, start_index + index - int(segment_half_duration * rate)) clear_range_end = min(end_index, start_index + index + int(segment_half_duration * rate)) volume_dB[clear_range_start:clear_range_end] = -np.inf else: # If the moment is not within the offsets, just clear its volume and continue volume_dB[start_index + index] = -np.inf moments.append(moment) volumes.append(moment_volume) # Suppress loudness of the recently found moment suppression_start = max(index - int(segment_half_duration * rate), 0) suppression_end = min(index + int(segment_half_duration * rate), len(volume_dB)) volume_dB[suppression_start:suppression_end] = -np.inf # Move the start_index past the recently found moment by at least the duration start_index = max(start_index + int(segment_duration * rate), suppression_end) print(f"Found {len(moments)} moments in {audio_filename}") return moments, volumes except Exception as e: print(f"An error occurred while processing the audio file: {e}") return [], [] def extract_segments(video_path, moments, segment_duration, video_duration, peak_position): # Vérifiez si FFmpeg est installé if shutil.which("ffmpeg") is None: raise FileNotFoundError("FFmpeg n'est pas installé ou n'est pas dans le chemin du système.") if not os.path.exists(output_folder): os.makedirs(output_folder) base_name = os.path.splitext(os.path.basename(video_path))[0] half_segment_duration = segment_duration / 2 for i, moment in enumerate(moments): # If the volume peak is selected to be in the middle of the segment (-t 0.5), start time should be adjusted. if peak_position == '1': # 1/4 start_time = max(moment - segment_duration * 0.25, 0) elif peak_position == '2': # 1/2 start_time = max(moment - segment_duration * 0.5, 0) elif peak_position == '3': # 3/4 start_time = max(moment - segment_duration * 0.75, 0) end_time = min(start_time + segment_duration, video_duration) output_filename = f"{base_name}_moment{i + 1}.mp4" output_path = os.path.join(output_folder, output_filename) command = [ "ffmpeg", "-y", # Overwrite output files without asking "-ss", str(start_time), # Start time "-i", video_path, # Input file "-t", str(min(segment_duration, video_duration - start_time)), # Duration or remaining video "-c:v", "libx264", # Specify video codec for output "-preset", "medium", # Specify the encoding preset (trade-off between encoding speed and quality) "-crf", "23", # Specify the Constant Rate Factor for quality (lower means better quality) "-c:a", "aac", # Specify audio codec for output "-strict", "-2", # Necessary for some versions of ffmpeg to use experimental aac encoder "-b:a", "192k", # Specify the audio bitrate output_path # Output path ] print(f"Extracting {len(moments)} segments from {video_path}") try: result = subprocess.run(command, check=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) print(f"Extracted and re-encoded {output_filename}") except subprocess.CalledProcessError as e: err_msg = e.stderr.decode('utf-8') if e.stderr else 'Unknown error' out_msg = e.stdout.decode('utf-8') if e.stdout else 'No output' print(f"Failed to extract segment from {video_path}: {err_msg}") print(f"FFmpeg Output: {out_msg}") def store_segment_info(video_path, moment, volume, order): base_name = os.path.splitext(os.path.basename(video_path))[0] output_filename = f"{base_name}_moment{order}.mp4" output_path = os.path.join(output_folder, output_filename) extracted_segments.append({ 'path': output_path, 'timestamp': moment, 'volume': volume }) def ask_sorting_preference(): print("Comment souhaitez-vous trier les vidéos extraites ?") print("1- Par ordre de lecture de la vidéo") print("2- Par ordre inverse de lecture de la vidéo") print("3- Par volume croissant") print("4- Par volume décroissant") print("5- Aléatoire") choice = int(input("Veuillez entrer le numéro de votre choix : ")) return choice def sort_moments(moments, volumes, choice): if choice == 1: # Par ordre de lecture de la vidéo zipped = sorted(zip(moments, volumes), key=lambda x: x[0]) elif choice == 2: # Par ordre inverse de lecture de la vidéo zipped = sorted(zip(moments, volumes), key=lambda x: x[0], reverse=True) elif choice == 3: # Par volume croissant zipped = sorted(zip(moments, volumes), key=lambda x: x[1]) elif choice == 4: # Par volume décroissant zipped = sorted(zip(moments, volumes), key=lambda x: x[1], reverse=True) elif choice == 5: # Pas de tri, sélection aléatoire zipped = list(zip(moments, volumes)) random.shuffle(zipped) else: zipped = zip(moments, volumes) # Unzip the list of tuples to two lists sorted_moments, sorted_volumes = zip(*zipped) if zipped else ([], []) return list(sorted_moments), list(sorted_volumes) def confirm_segment_number_or_ask_again(video_duration, starting_offset_seconds, ending_offset_seconds): while True: segment_duration, max_segments = ask_for_segment_duration(video_duration - (starting_offset_seconds + ending_offset_seconds), video_duration, starting_offset_seconds, ending_offset_seconds) print(f"Avec cette durée, vous pouvez extraire jusqu'à {max_segments} segments.") confirmation = ask_yes_no_question("Voulez-vous continuer avec cette durée de segments ?") if confirmation: num_moments = ask_for_number_of_moments(max_segments) return segment_duration, num_moments # Retournons maintenant le nombre de moments choisis else: print("Veuillez entrer une nouvelle durée pour les segments.") def ask_peak_position(): print("Où doit être situé le pic sonore dans la vidéo extraite ?") print("1- A 1/4 du temps de lecture de la vidéo") print("2- A 1/2 du temps de lecture de la vidéo") print("3- A 3/4 du temps de lecture de la vidéo") while True: choice = input("Veuillez entrer le numéro de votre choix (1, 2, ou 3) : ").strip() if choice in ('1', '2', '3'): return choice else: print("Entrée non valide, veuillez réessayer.") def extract_audio(video_path): try: # Use tempfile to create a temporary audio file with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_audio: audio_file_path = temp_audio.name # Extract audio using moviepy with VideoFileClip(video_path) as video_clip: if video_clip.audio: video_clip.audio.write_audiofile(audio_file_path, codec='pcm_s16le', fps=44100, nbytes=2, buffersize=2000) return audio_file_path except Exception as e: print(f"An error occurred while extracting audio from video {video_path}: {e}") return None def main(): if not os.path.exists(output_folder): os.makedirs(output_folder) batch_or_individual = ask_batch_or_individual_processing() include_subfolders = ask_yes_no_question("Souhaitez-vous inclure les sous-dossiers dans la recherche des vidéos ?") video_durations = get_video_durations(include_subfolders) if not video_durations: print("Aucune vidéo trouvée pour l'analyse.") return processed_videos = 0 if batch_or_individual == '1': # Traitement par lot duration_choice = ask_min_or_max_duration_preference() reference_video_duration = min(video_durations.values()) if duration_choice == '1' else max(video_durations.values()) perform_temporal_offset = ask_yes_no_question("Souhaitez-vous effectuer un retrait temporel (début et fin) pour l'analyse des vidéos ?") if perform_temporal_offset: offset_type = ask_offset_type() print("Configuration du retrait temporel pour le début de la vidéo:") starting_offset_seconds = get_offset_value(reference_video_duration, offset_type) print("Configuration du retrait temporel pour la fin de la vidéo:") ending_offset_seconds = get_offset_value(reference_video_duration, offset_type) else: starting_offset_seconds = 0 ending_offset_seconds = 0 segment_duration, num_moments = confirm_segment_number_or_ask_again(reference_video_duration, starting_offset_seconds, ending_offset_seconds) sorting_preference = ask_sorting_preference() peak_position = ask_peak_position() for video_path, duration in video_durations.items(): print(f"Traitement de la vidéo : {video_path}") # Utilisez le module tempfile pour créer un fichier audio temporaire with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_audio: audio_path = temp_audio.name # Traitement individuel pour chaque vidéo if batch_or_individual == '2': perform_temporal_offset = ask_yes_no_question("Souhaitez-vous effectuer un retrait temporel (début et fin) pour l'analyse de cette vidéo ?") if perform_temporal_offset: offset_type = ask_offset_type() print("Configuration du retrait temporel pour le début de la vidéo:") starting_offset_seconds = get_offset_value(duration, offset_type) print("Configuration du retrait temporel pour la fin de la vidéo:") ending_offset_seconds = get_offset_value(duration, offset_type) else: starting_offset_seconds = 0 ending_offset_seconds = 0 segment_duration, num_moments = confirm_segment_number_or_ask_again(duration, starting_offset_seconds, ending_offset_seconds) sorting_preference = ask_sorting_preference() peak_position = ask_peak_position() audio_path = f'temp_audio_{uuid.uuid4().hex}.wav' temporary_audio_files.append(audio_path) try: with VideoFileClip(video_path) as video_clip: if video_clip.audio: video_clip.audio.write_audiofile(audio_path, codec='pcm_s16le', fps=44100, nbytes=2, buffersize=2000) moments, volumes = find_loudest_moments(audio_path, num_moments, segment_duration, duration, starting_offset_seconds, ending_offset_seconds) selected_moments, associated_volumes = sort_moments(moments, volumes, sorting_preference) extract_segments(video_path, selected_moments, segment_duration, duration, peak_position) processed_videos += 1 if len(moments) < num_moments: print(f"Insufficient moments found for {video_path}, found {len(moments)} of {num_moments}") print(f"Traitement terminé pour la vidéo '{video_path}'") else: print(f"La vidéo {video_path} n'a pas de piste audio. Aucun moment ne peut être extrait.") continue # Passer à la vidéo suivante except Exception as e: print(f"Error processing video {video_path}: {e}") finally: if os.path.exists(audio_path): os.remove(audio_path) # Pour les traitements par lot, pas de demande de satisfaction après chaque vidéo if batch_or_individual == '2': satisfied = ask_yes_no_question("Êtes-vous satisfait de la position du pic sonore dans les vidéos extraites ?") if not satisfied: print("Les paramètres peuvent être ajustés pour la vidéo suivante.") print(f"Le traitement de toutes les vidéos est terminé. Nombre total de vidéos traitées : {processed_videos}") if __name__ == "__main__": main() Le script extrait chaque segment deux fois. 1 et 2 sont identiques, 3 et 4 sont identiques, 5 et 6 sont identiques...
3a4ea636bef9b54f88e7ff1161852290
{ "intermediate": 0.4377445876598358, "beginner": 0.4119659662246704, "expert": 0.150289386510849 }
37,461
How do I automate zoom calls? I want to be able to log onto a meeting, and wait for half the participants to leave, then leave the call
966e4eebc5853779e8c513b1f3423c1f
{ "intermediate": 0.3696552515029907, "beginner": 0.1692119538784027, "expert": 0.46113285422325134 }
37,462
voglio creare un EA che sfrutti questo indicatore. bisogna impostare stop loss, take profit, trailing stop (con possibilità di annullarlo mettendo valore 0), e max ordini aperti #property strict #property indicator_chart_window #property indicator_buffers 2 #property indicator_color1 Lime #property indicator_color2 Red // Input parameters extern int EmaPeriod = 10; extern int BollingerPeriod = 17; extern double BollingerDeviations = 2.0; extern int RsiPeriod = 12; extern int MacdFastEmaPeriod = 10; extern int MacdSlowEmaPeriod = 19; extern int MacdSignalSmoothing = 13; extern double RsiUpperLevel = 80; extern double RsiLowerLevel = 20; // Buffer per i segnali di buy e sell double BuySignalBuffer[]; double SellSignalBuffer[]; // Flag per tenere traccia se il segnale precedente era di buy o sell bool prevBuySignal = false; bool prevSellSignal = false; // Identifica il codice simbolo di Wingdings per le frecce enum arrow_codes { UP_ARROW = 233, // Freccia verde verso l’alto DOWN_ARROW = 234 // Freccia rossa verso il basso }; // Inizializzazione dell’indicatore int OnInit() { // Mappare i buffer dei segnali a colori specifici IndicatorBuffers(2); SetIndexBuffer(0, BuySignalBuffer); SetIndexBuffer(1, SellSignalBuffer); SetIndexArrow(0, UP_ARROW); SetIndexArrow(1, DOWN_ARROW); SetIndexStyle(0, DRAW_ARROW, 0, 2, clrLime); // Freccia verde per buy SetIndexStyle(1, DRAW_ARROW, 0, 2, clrRed); // Freccia rossa per sell ArraySetAsSeries(BuySignalBuffer, true); ArraySetAsSeries(SellSignalBuffer, true); return(INIT_SUCCEEDED); } // Funzione chiamata ad ogni tick int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { // Begin calculation from enough bars for the bands and moving averages. int bars_required = MathMax(BollingerPeriod, EmaPeriod); int start = prev_calculated > bars_required ? prev_calculated - 1 : bars_required; for (int i = start; i < rates_total; i++) { double currentEma = iMA(NULL, 0, EmaPeriod, 0, MODE_EMA, PRICE_CLOSE, i); double previousEma = iMA(NULL, 0, EmaPeriod, 0, MODE_EMA, PRICE_CLOSE, i + 2); double middleBand = iBands(NULL, 0, BollingerPeriod, BollingerDeviations, 0, PRICE_CLOSE, MODE_MAIN, i); // Acquiring MACD current and signal values indirectly double MACD = iMACD(NULL, 0, MacdFastEmaPeriod, MacdSlowEmaPeriod, MacdSignalSmoothing, PRICE_CLOSE, MODE_MAIN, i); double MACDSignal = iMACD(NULL, 0, MacdFastEmaPeriod, MacdSlowEmaPeriod, MacdSignalSmoothing, PRICE_CLOSE, MODE_SIGNAL, i); double RsiValue = iRSI(NULL, 0, RsiPeriod, PRICE_CLOSE, i); // Buy condition if (currentEma > middleBand && previousEma < middleBand && MACD > MACDSignal && RsiValue > RsiLowerLevel && RsiValue < RsiUpperLevel) { if (!prevBuySignal) { // Solo se prima non c’era un segnale di buy prevBuySignal = true; BuySignalBuffer[i] = low[i] - 4 * _Point; } } else { prevBuySignal = false; BuySignalBuffer[i] = EMPTY_VALUE; } // Sell condition if (currentEma < middleBand && previousEma > middleBand && MACD < MACDSignal && RsiValue > RsiLowerLevel && RsiValue < RsiUpperLevel) { if (!prevSellSignal) { // Solo se prima non c’era un segnale di sell prevSellSignal = true; SellSignalBuffer[i] = high[i] + 4 * _Point; } } else { prevSellSignal = false; SellSignalBuffer[i] = EMPTY_VALUE; } } return(rates_total); }
e28d95270ee626eab185045b55ad825c
{ "intermediate": 0.35355985164642334, "beginner": 0.29367783665657043, "expert": 0.35276228189468384 }
37,463
voglio creare un EA che sfrutti questo indicatore. bisogna impostare stop loss, take profit, trailing stop (con possibilità di annullarlo mettendo valore 0), e max ordini aperti #property strict #property indicator_chart_window #property indicator_buffers 2 #property indicator_color1 Lime #property indicator_color2 Red // Input parameters extern int EmaPeriod = 10; extern int BollingerPeriod = 17; extern double BollingerDeviations = 2.0; extern int RsiPeriod = 12; extern int MacdFastEmaPeriod = 10; extern int MacdSlowEmaPeriod = 19; extern int MacdSignalSmoothing = 13; extern double RsiUpperLevel = 80; extern double RsiLowerLevel = 20; // Buffer per i segnali di buy e sell double BuySignalBuffer[]; double SellSignalBuffer[]; // Flag per tenere traccia se il segnale precedente era di buy o sell bool prevBuySignal = false; bool prevSellSignal = false; // Identifica il codice simbolo di Wingdings per le frecce enum arrow_codes { UP_ARROW = 233, // Freccia verde verso l’alto DOWN_ARROW = 234 // Freccia rossa verso il basso }; // Inizializzazione dell’indicatore int OnInit() { // Mappare i buffer dei segnali a colori specifici IndicatorBuffers(2); SetIndexBuffer(0, BuySignalBuffer); SetIndexBuffer(1, SellSignalBuffer); SetIndexArrow(0, UP_ARROW); SetIndexArrow(1, DOWN_ARROW); SetIndexStyle(0, DRAW_ARROW, 0, 2, clrLime); // Freccia verde per buy SetIndexStyle(1, DRAW_ARROW, 0, 2, clrRed); // Freccia rossa per sell ArraySetAsSeries(BuySignalBuffer, true); ArraySetAsSeries(SellSignalBuffer, true); return(INIT_SUCCEEDED); } // Funzione chiamata ad ogni tick int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { // Begin calculation from enough bars for the bands and moving averages. int bars_required = MathMax(BollingerPeriod, EmaPeriod); int start = prev_calculated > bars_required ? prev_calculated - 1 : bars_required; for (int i = start; i < rates_total; i++) { double currentEma = iMA(NULL, 0, EmaPeriod, 0, MODE_EMA, PRICE_CLOSE, i); double previousEma = iMA(NULL, 0, EmaPeriod, 0, MODE_EMA, PRICE_CLOSE, i + 2); double middleBand = iBands(NULL, 0, BollingerPeriod, BollingerDeviations, 0, PRICE_CLOSE, MODE_MAIN, i); // Acquiring MACD current and signal values indirectly double MACD = iMACD(NULL, 0, MacdFastEmaPeriod, MacdSlowEmaPeriod, MacdSignalSmoothing, PRICE_CLOSE, MODE_MAIN, i); double MACDSignal = iMACD(NULL, 0, MacdFastEmaPeriod, MacdSlowEmaPeriod, MacdSignalSmoothing, PRICE_CLOSE, MODE_SIGNAL, i); double RsiValue = iRSI(NULL, 0, RsiPeriod, PRICE_CLOSE, i); // Buy condition if (currentEma > middleBand && previousEma < middleBand && MACD > MACDSignal && RsiValue > RsiLowerLevel && RsiValue < RsiUpperLevel) { if (!prevBuySignal) { // Solo se prima non c’era un segnale di buy prevBuySignal = true; BuySignalBuffer[i] = low[i] - 4 * _Point; } } else { prevBuySignal = false; BuySignalBuffer[i] = EMPTY_VALUE; } // Sell condition if (currentEma < middleBand && previousEma > middleBand && MACD < MACDSignal && RsiValue > RsiLowerLevel && RsiValue < RsiUpperLevel) { if (!prevSellSignal) { // Solo se prima non c’era un segnale di sell prevSellSignal = true; SellSignalBuffer[i] = high[i] + 4 * _Point; } } else { prevSellSignal = false; SellSignalBuffer[i] = EMPTY_VALUE; } } return(rates_total); } puoi scrivere il codice completo di ogni sua parte?
7dd7ad7788b37ea702c6626f24f070f8
{ "intermediate": 0.353007048368454, "beginner": 0.3760039210319519, "expert": 0.2709890305995941 }
37,464
voglio creare un EA che sfrutti questo indicatore. bisogna impostare stop loss, take profit, trailing stop (con possibilità di annullarlo mettendo valore 0), e max ordini aperti #property strict #property indicator_chart_window #property indicator_buffers 2 #property indicator_color1 Lime #property indicator_color2 Red // Input parameters extern int EmaPeriod = 10; extern int BollingerPeriod = 17; extern double BollingerDeviations = 2.0; extern int RsiPeriod = 12; extern int MacdFastEmaPeriod = 10; extern int MacdSlowEmaPeriod = 19; extern int MacdSignalSmoothing = 13; extern double RsiUpperLevel = 80; extern double RsiLowerLevel = 20; // Buffer per i segnali di buy e sell double BuySignalBuffer[]; double SellSignalBuffer[]; // Flag per tenere traccia se il segnale precedente era di buy o sell bool prevBuySignal = false; bool prevSellSignal = false; // Identifica il codice simbolo di Wingdings per le frecce enum arrow_codes { UP_ARROW = 233, // Freccia verde verso l’alto DOWN_ARROW = 234 // Freccia rossa verso il basso }; // Inizializzazione dell’indicatore int OnInit() { // Mappare i buffer dei segnali a colori specifici IndicatorBuffers(2); SetIndexBuffer(0, BuySignalBuffer); SetIndexBuffer(1, SellSignalBuffer); SetIndexArrow(0, UP_ARROW); SetIndexArrow(1, DOWN_ARROW); SetIndexStyle(0, DRAW_ARROW, 0, 2, clrLime); // Freccia verde per buy SetIndexStyle(1, DRAW_ARROW, 0, 2, clrRed); // Freccia rossa per sell ArraySetAsSeries(BuySignalBuffer, true); ArraySetAsSeries(SellSignalBuffer, true); return(INIT_SUCCEEDED); } // Funzione chiamata ad ogni tick int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { // Begin calculation from enough bars for the bands and moving averages. int bars_required = MathMax(BollingerPeriod, EmaPeriod); int start = prev_calculated > bars_required ? prev_calculated - 1 : bars_required; for (int i = start; i < rates_total; i++) { double currentEma = iMA(NULL, 0, EmaPeriod, 0, MODE_EMA, PRICE_CLOSE, i); double previousEma = iMA(NULL, 0, EmaPeriod, 0, MODE_EMA, PRICE_CLOSE, i + 2); double middleBand = iBands(NULL, 0, BollingerPeriod, BollingerDeviations, 0, PRICE_CLOSE, MODE_MAIN, i); // Acquiring MACD current and signal values indirectly double MACD = iMACD(NULL, 0, MacdFastEmaPeriod, MacdSlowEmaPeriod, MacdSignalSmoothing, PRICE_CLOSE, MODE_MAIN, i); double MACDSignal = iMACD(NULL, 0, MacdFastEmaPeriod, MacdSlowEmaPeriod, MacdSignalSmoothing, PRICE_CLOSE, MODE_SIGNAL, i); double RsiValue = iRSI(NULL, 0, RsiPeriod, PRICE_CLOSE, i); // Buy condition if (currentEma > middleBand && previousEma < middleBand && MACD > MACDSignal && RsiValue > RsiLowerLevel && RsiValue < RsiUpperLevel) { if (!prevBuySignal) { // Solo se prima non c’era un segnale di buy prevBuySignal = true; BuySignalBuffer[i] = low[i] - 4 * _Point; } } else { prevBuySignal = false; BuySignalBuffer[i] = EMPTY_VALUE; } // Sell condition if (currentEma < middleBand && previousEma > middleBand && MACD < MACDSignal && RsiValue > RsiLowerLevel && RsiValue < RsiUpperLevel) { if (!prevSellSignal) { // Solo se prima non c’era un segnale di sell prevSellSignal = true; SellSignalBuffer[i] = high[i] + 4 * _Point; } } else { prevSellSignal = false; SellSignalBuffer[i] = EMPTY_VALUE; } } return(rates_total); } scrivi il codice completo dell'EA mt4
c433b432b1d90e147eea91c495bc686e
{ "intermediate": 0.353007048368454, "beginner": 0.3760039210319519, "expert": 0.2709890305995941 }
37,465
In this javascript why does the '// If not a new personal best, display the saved personal best station.innerHTML += `<br><br>Personal Best: ${savedPersonalBest.toFixed(2)} miles`;' not display the saved PersonalBest score - //display game score station.innerHTML = `Well done!<br><br> You've found all the paintings! <br><br> ${roundDistances .map((distance, index) => `Round ${index + 1}: ${distance.toFixed(2)} miles`) .join("<br>")}<br> <br>Total distance: ${totalDistance.toFixed(2)} miles.`; // Retrieve the previously saved personal best, or set it to 0 if not found const savedPersonalBest = localStorage.getItem("personalBest") || 0; // Check if the current totalDistance is a new personal best if (totalDistance < savedPersonalBest) { // Update the personal best in local storage localStorage.setItem("personalBest", totalDistance); // Add the personal best statement to the innerHTML station.innerHTML += `<br><br>Personal Best: ${totalDistance.toFixed(2)} miles`; } else { // If not a new personal best, display the saved personal best station.innerHTML += `<br><br>Personal Best: ${savedPersonalBest.toFixed(2)} miles`; }
a3bcd8b1a20f6118da63a374901e57cd
{ "intermediate": 0.3720099627971649, "beginner": 0.3662303686141968, "expert": 0.2617596685886383 }
37,466
How do I uninstall pip on mac
10eed92a3ed871995b5ece43c1f78520
{ "intermediate": 0.5546453595161438, "beginner": 0.22404418885707855, "expert": 0.22131049633026123 }
37,467
My pip is broken, calling it breaks it. How do I uninstall pip without using pip
4f001135e093dfa2afbdfeb81f7c3a30
{ "intermediate": 0.598021388053894, "beginner": 0.19159100949764252, "expert": 0.21038752794265747 }
37,468
Can you give some pros and cons of using a CSS in JS solution to manage styles in a front end application?
460084bfde1e8b47fb48c7577a7cd20e
{ "intermediate": 0.3814077377319336, "beginner": 0.31335508823394775, "expert": 0.30523720383644104 }
37,469
TUDOD AZONOSÍTANI A PROBLÉMÁT?? 01/12/24 23:34:19:586 | [ERROR] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | | 4072 | SendEvent failed. HTTPConnectorResponse is : 68 01/12/24 23:34:19:586 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | | 4072 | Event with guid 'f629919f-432e-43e6-9737-4a4c42400a04' is being sent 01/12/24 23:34:19:588 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | | 4072 | Sending event: <eventList><HostedServicesEvent><eventGuid>f629919f-432e-43e6-9737-4a4c42400a04</eventGuid><eventDts>2024-01-12T23:34:19.586+01:00</eventDts><eventCode>HDESD_INSTALL_ACC_INSTALL_END</eventCode><eventSubCode>NULL_SUB_CODE</eventSubCode><eventSource>HDESD.HDESD_client.5.3.1.470</eventSource><eventParamData><eventParam name="ProductID">PHSP</eventParam><eventParam name="ProductVersion">24.4.1</eventParam><eventParam name="ProductLanguage">en_GB</eventParam><eventParam name="Locale">en_US</eventParam><eventParam name="IsSuite">false</eventParam><eventParam name="IsLBS">false</eventParam><eventParam name="IsNonCC">false</eventParam><eventParam name="AdobeID"></eventParam><eventParam name="DeviceID"></eventParam><eventParam name="HDESD_HYPERDRIVE_VERSION">5.3.1.470</eventParam><eventParam name="OS">win</eventParam><eventParam name="OSBitness">64</eventParam><eventParam name="OSVersion">10.0.0</eventParam><eventParam name="SessionID">{55C88B5C-3029-4FFC-A456-7DB282B5A996}</eventParam><eventParam name="TimeStamp">2024-01-12T23:34:19.586+01:00</eventParam><eventParam name="lbsWorkflowID">{F8AB4900-3AD2-49AB-8F97-F39C88073C0D}</eventParam><eventParam name="event.guid">f629919f-432e-43e6-9737-4a4c42400a04</eventParam><eventParam name="event.dts_end">2024-01-12T23:34:19.586+01:00</eventParam></eventParamData></HostedServicesEvent> </eventList> 01/12/24 23:34:19:588 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | Sending HTTP request message: Method: POST || URL: 127.0.0.1 || Timeout: 30 || Compression: false || Request headers: Content-Type : text/xml 01/12/24 23:34:19:608 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | Proxy detected: WPAD 01/12/24 23:34:19:610 | [WARN] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | GetIEProxyInfo - Failed to get proxy for the url, error:12180 01/12/24 23:34:19:610 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | No default proxy present on the user machine 01/12/24 23:34:21:638 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | The http request returned HTTP_Status:0 HttpCommunicator error:68 01/12/24 23:34:21:638 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | Received HTTP response: URL = 127.0.0.1 Response code = -1 Response headers: 01/12/24 23:34:21:639 | [ERROR] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | | 4072 | SendEvent failed. HTTPConnectorResponse is : 68 01/12/24 23:34:21:639 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | | 4072 | Event with guid '1ca21734-fce6-47aa-9a61-e024414804e1' is being sent 01/12/24 23:34:21:642 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | | 4072 | Sending event: <eventList><HostedServicesEvent><eventGuid>1ca21734-fce6-47aa-9a61-e024414804e1</eventGuid><eventDts>2024-01-12T23:34:21.639+01:00</eventDts><eventCode>HDESD_INSTALL_PRODUCT_INSTALL_START</eventCode><eventSubCode>NULL_SUB_CODE</eventSubCode><eventSource>HDESD.HDESD_client.5.3.1.470</eventSource><eventParamData><eventParam name="ProductID">PHSP</eventParam><eventParam name="ProductVersion">24.4.1</eventParam><eventParam name="ProductLanguage">en_GB</eventParam><eventParam name="Locale">en_US</eventParam><eventParam name="IsSuite">false</eventParam><eventParam name="IsLBS">false</eventParam><eventParam name="IsNonCC">false</eventParam><eventParam name="AdobeID"></eventParam><eventParam name="DeviceID"></eventParam><eventParam name="HDESD_HYPERDRIVE_VERSION">5.3.1.470</eventParam><eventParam name="OS">win</eventParam><eventParam name="OSBitness">64</eventParam><eventParam name="OSVersion">10.0.0</eventParam><eventParam name="SessionID">{55C88B5C-3029-4FFC-A456-7DB282B5A996}</eventParam><eventParam name="TimeStamp">2024-01-12T23:34:21.639+01:00</eventParam><eventParam name="lbsWorkflowID">{F8AB4900-3AD2-49AB-8F97-F39C88073C0D}</eventParam><eventParam name="event.guid">1ca21734-fce6-47aa-9a61-e024414804e1</eventParam><eventParam name="event.dts_end">2024-01-12T23:34:21.639+01:00</eventParam></eventParamData></HostedServicesEvent> </eventList> 01/12/24 23:34:21:643 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | Sending HTTP request message: Method: POST || URL: 127.0.0.1 || Timeout: 30 || Compression: false || Request headers: Content-Type : text/xml 01/12/24 23:34:21:678 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | Proxy detected: WPAD 01/12/24 23:34:21:679 | [WARN] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | GetIEProxyInfo - Failed to get proxy for the url, error:12180 01/12/24 23:34:21:679 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | No default proxy present on the user machine 01/12/24 23:34:23:718 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | The http request returned HTTP_Status:0 HttpCommunicator error:68 01/12/24 23:34:23:718 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | Received HTTP response: URL = 127.0.0.1 Response code = -1 Response headers: 01/12/24 23:34:23:718 | [ERROR] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | | 4072 | SendEvent failed. HTTPConnectorResponse is : 68 01/12/24 23:34:39:704 | [WARN] | 9536 | Bootstrapper | | WorkFlowHelper | | | 16488 | WorkFlowHelper::updateProductProgressCallbackProc : Received ERROR : type : 4, error code : 127, suberror code : <ProgressData><MsgName>hdpimProgressCallback</MsgName><MsgData><sessionID>{BC6ACCFF-E6C3-45BE-8677-FAE39C4448CE}</sessionID><progressType>8</progressType><errorCode>127</errorCode><overallProgressPercentage>28.6112</overallProgressPercentage><downloadPercentage>100</downloadPercentage><installPercentage>0</installPercentage><downloadSpeed>28.1873</downloadSpeed><sizeDownloaded>1824052185</sizeDownloaded><timeElapsed>24</timeElapsed><genericProgressMessage><errorData><Error_Subcode_Details></Error_Subcode_Details><ErrorProductID>PHSP</ErrorProductID><ErrorProductVersion>24.4.1</ErrorProductVersion></errorData></genericProgressMessage></MsgData></ProgressData> , progress : 28.611244, errorParamXML : <errorData><Error_Subcode_Details></Error_Subcode_Details><ErrorProductID>PHSP</ErrorProductID><ErrorProductVersion>24.4.1</ErrorProductVersion></errorData>, isErrorResumable : false, moreInfoLink : C:\ProgramData\Adobe\Installer\Summary.htm 01/12/24 23:34:39:748 | [INFO] | 3908 | Bootstrapper | | ViewMediatorUI | | | 20972 | Event Guid generated is: '4e375ad6-382c-4ff0-9e47-d8caf77163cf' 01/12/24 23:34:39:749 | [INFO] | 3908 | Bootstrapper | | ViewMediatorUI | | | 4072 | Event with guid '4e375ad6-382c-4ff0-9e47-d8caf77163cf' is being sent 01/12/24 23:34:39:749 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | | 4072 | Sending event: <eventList><HostedServicesEvent><eventGuid>4e375ad6-382c-4ff0-9e47-d8caf77163cf</eventGuid><eventDts>2024-01-12T23:34:39.749+01:00</eventDts><eventCode>HDESD_INSTALL_ERROR</eventCode><eventSubCode>NULL_SUB_CODE</eventSubCode><eventSource>HDESD.HDESD_client.5.3.1.470</eventSource><eventParamData><eventParam name="ProductID">PHSP</eventParam><eventParam name="ProductVersion">24.4.1</eventParam><eventParam name="ProductLanguage">en_GB</eventParam><eventParam name="Locale">en_US</eventParam><eventParam name="IsSuite">false</eventParam><eventParam name="IsLBS">false</eventParam><eventParam name="IsNonCC">false</eventParam><eventParam name="AdobeID"></eventParam><eventParam name="DeviceID"></eventParam><eventParam name="HDESD_HYPERDRIVE_VERSION">5.3.1.470</eventParam><eventParam name="OS">win</eventParam><eventParam name="OSBitness">64</eventParam><eventParam name="OSVersion">10.0.0</eventParam><eventParam name="SessionID">{55C88B5C-3029-4FFC-A456-7DB282B5A996}</eventParam><eventParam name="ErrorType">ExtractionError</eventParam><eventParam name="ErrorCode">127</eventParam><eventParam name="ErrorSubcode"></eventParam><eventParam name="IsErrorRetryable">false</eventParam><eventParam name="CurrentProgress">29</eventParam><eventParam name="TimeStamp">2024-01-12T23:34:39.749+01:00</eventParam><eventParam name="lbsWorkflowID">{F8AB4900-3AD2-49AB-8F97-F39C88073C0D}</eventParam><eventParam name="event.guid">4e375ad6-382c-4ff0-9e47-d8caf77163cf</eventParam><eventParam name="event.dts_end">2024-01-12T23:34:39.749+01:00</eventParam></eventParamData></HostedServicesEvent> </eventList> 01/12/24 23:34:39:750 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | Sending HTTP request message: Method: POST || URL: 127.0.0.1 || Timeout: 30 || Compression: false || Request headers: Content-Type : text/xml 01/12/24 23:34:39:762 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | Proxy detected: WPAD 01/12/24 23:34:39:763 | [WARN] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | GetIEProxyInfo - Failed to get proxy for the url, error:12180 01/12/24 23:34:39:763 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | No default proxy present on the user machine 01/12/24 23:34:41:801 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | The http request returned HTTP_Status:0 HttpCommunicator error:68 01/12/24 23:34:41:801 | [INFO] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | HTTPConnector | 4072 | Received HTTP response: URL = 127.0.0.1 Response code = -1 Response headers: 01/12/24 23:34:41:802 | [ERROR] | 3908 | Bootstrapper | OOBEUtils | HTTPConnector | | | 4072 | SendEvent failed. HTTPConnectorResponse is : 68 01/12/24 23:34:46:715 | [INFO] | 3908 | Bootstrapper | | ViewMediatorUI | | | 2360 | Waiting for the async thread to get the task completed 01/12/24 23:34:46:715 | [INFO] | 3908 | Bootstrapper | | ViewMediatorUI | | | 4072 | Async thread is completed. Now exiting from function. 01/12/24 23:34:46:727 | [WARN] | 9536 | Bootstrapper | OOBEUtils | CommBridge | | OOBEUtils | 14724 | Aborting read on pipe 00000518 , errno: 109 01/12/24 23:34:46:727 | [WARN] | 9536 | Bootstrapper | OOBEUtils | CommBridge | | OOBEUtils | 14724 | Aborting read on pipe 00000518 , CBRawReadTry failed for packet info. 01/12/24 23:34:46:727 | [INFO] | 9536 | Bootstrapper | OOBEUtils | CommBridge | | | 8804 | *********************** Workflow end. Version: 5.3.1.470 ************************** 01/12/24 23:34:46:741 | [WARN] | 3908 | Bootstrapper | | MessageGateway | | OOBEUtils | 2360 | Pipe 00000000 not initialized, aborting write. 01/12/24 23:34:46:777 | [INFO] | 3908 | Bootstrapper | OOBEUtils | FileUtils | | OOBEUtils | 4452 | Successfully deleted directory from path: C:\Users\Dell\AppData\Local\Temp\{687DA4F6-A2FD-49CD-BD23-468AFF600901}. Recursive: 1 01/12/24 23:34:46:793 | [INFO] | 3908 | Bootstrapper | OOBEUtils | FileUtils | | | 4452 | *********************** Workflow end. Version: 5.3.1.470 **************************
84fa18c2bdc1730cd73e0a00ca742eaa
{ "intermediate": 0.3974020481109619, "beginner": 0.3691500723361969, "expert": 0.23344790935516357 }
37,470
make a custom roblox script that makes you run with an animation.
2f917a54e886a40e98225beb46f870bb
{ "intermediate": 0.43855395913124084, "beginner": 0.22075606882572174, "expert": 0.3406899869441986 }
37,471
Poursuis la réponse : Pour résoudre le problème de la condition qui ne fonctionne pas systématiquement parce qu’elle dépend de la longueur du panier, vous pouvez plutôt définir un flag pour détecter si l’article a été ajouté indépendamment de la longueur du panier. Voici comment vous pourriez faire cela dans votre addToCartHandler : const addToCartHandler = async ( event: React.MouseEvent<HTMLButtonElement> ) => { event.stopPropagation(); setIsLoading(true); // Pas besoin de la longueur du panier ici // const currentCartLength = (getCookie(“cart”) || []).length; const selectedDays = isForfait ? Object.entries(days) .filter(([_, isChosen]) => isChosen) .map(([day, _]) => day) : []; const itemForCart = { id, title, price: typeof price === “number” ? price : 0, quantity: tickets, selectedDays, }; // Nous allons utiliser un flag pour suivre si un nouvel article a été ajouté let itemWasAdded = false; let newCart = cart.slice(); const billetIndex = newCart.findIndex((billet) => billet.id === itemForCart.id); if (billetIndex > -1) { newCart[billetIndex].quantity += itemForCart.quantity; itemWasAdded CODE ORIGINAL : import { TargetAndTransition, motion } from "framer-motion"; import { useContext, useState } from "react"; import Button from "../components/form/Button"; import { getCookie, setCookie } from "../cookies/CookiesLib.tsx"; import { CartContext } from "../App"; const initialDays = { "20 Jui": false, "21 Jui": false, "22 Jui": false, }; type Props = { id: number; title: string; price: number | string; nbTicket: number; isForfait?: boolean; }; export default function TicketCard({ id, title, price, nbTicket, isForfait, }: Props) { const [isOpen, setIsOpen] = useState(false); const [tickets, setTickets] = useState(nbTicket); const [rotation, setRotation] = useState(0); const [days, setDays] = useState(initialDays); const { cart, setCart } = useContext(CartContext); const [isLoading, setIsLoading] = useState(false); const [isAdded, setIsAdded] = useState(false); const handleTicketChange = (newTickets: number, event: React.MouseEvent) => { event.stopPropagation(); setTickets(newTickets); }; const addToCartHandler = async ( event: React.MouseEvent<HTMLButtonElement> ) => { event.stopPropagation(); setIsLoading(true); // Longueur actuelle du panier dans les cookies const selectedDays = isForfait ? Object.entries(days) .filter(([_, isChosen]) => isChosen) .map(([day, _]) => day) : []; const itemForCart = { id, title, price: typeof price === "number" ? price : 0, quantity: tickets, selectedDays, }; setTimeout(() => { setIsLoading(false); // Termine le chargement const newCartLength = (getCookie("cart") || []).length; if (newCartLength > currentCartLength) { setIsAdded(true); setTimeout(() => setIsAdded(false), 1000); console.log("article ajouté") } }, 500); // const currentCartLength = (getCookie("cart") || []).length; // condition non valide car si on ajoute un typê billet déjà présent dans le panier, // l'ajout des nouveaux billets ne ferons que changer la valeur de quantité dans le tableau et // donc la longueur du tableau ne changera pas let itemWasAdded = false; let newCart = cart.slice(); const billetIndex = newCart.findIndex( (billet) => billet.id === itemForCart.id ); if (billetIndex > -1) { newCart[billetIndex].quantity += itemForCart.quantity; } else { newCart.push(itemForCart); } setCart(newCart); // Met à jour l'état global du panier setCookie("cart", newCart, { expires: 7, sameSite: "None", secure: true }); }; const displayDay = (day: string) => day.replace("Juillet", "Juillet"); const buttonVariants: { [key: string]: TargetAndTransition } = { tap: { scale: 0.95 }, selected: { scale: 1.1, backgroundColor: "#E45A3B" }, unselected: { scale: 1, backgroundColor: "#FFFFFF" }, }; const contentVariants = { closed: { opacity: 0, height: 0, overflow: "hidden", transition: { duration: 0.2, ease: "easeInOut", when: "afterChildren", }, }, open: { opacity: 1, height: title === "Forfait 2 jours" ? 150 : 130, transition: { duration: 0.2, ease: "easeInOut", when: "beforeChildren", }, }, }; const cardVariants = { hidden: { opacity: 0, y: 50 }, visible: { opacity: 1, y: 0, transition: { type: "spring", stiffness: 120, }, }, }; const maxSelectedDays = 2; const selectedDayCount = () => { return Object.values(days).filter(Boolean).length; }; const toggleDaySelection = (day: keyof typeof initialDays) => { setDays((prevDays) => { const isSelected = prevDays[day]; const count = selectedDayCount(); if (!isSelected && count >= maxSelectedDays) { return prevDays; } return { ...prevDays, [day]: !prevDays[day] }; }); }; return ( <motion.div className="ticket-card" layout initial="hidden" animate="visible" variants={cardVariants} onClick={() => { setIsOpen(!isOpen); setRotation(rotation === 0 ? 90 : 0); }} > <div className="content"> <div className="left-part"> <h4>{title}</h4> <p>Les tickets ne sont pas remboursables.</p> <p>Dernière entrée à 11H.</p> </div> <div className="right-part"> <p>{price}€</p> <motion.div className="svg-container" animate={{ rotate: rotation }}> <svg xmlns="http://www.w3.org/2000/svg" width="13" height="20" viewBox="0 0 13 20" fill="none" > <path d="M2 18L10 10L2 2" stroke="#4E4E4E" strokeWidth="4" /> </svg> </motion.div> </div> </div> <motion.div className={`sub-menu ${ title === "Forfait 2 jours" ? "forfait-2j" : "" }`} variants={contentVariants} initial="closed" animate={isOpen ? "open" : "closed"} exit="closed" > <div className="top-partsubmenu"> <div className="left-part-sub"> <div className="sub-menu-left-part"> <div className="rect"> <img className="" src="images/billet_pass1j.png" alt="Billet pass 1 jour" /> </div> <div className="article-select"> <svg xmlns="http://www.w3.org/2000/svg" width="22" height="21" viewBox="0 0 22 21" fill="none" > <path d="M22 9.03848H14.6966L19.8599 4.10947L17.6953 2.04109L12.532 6.97007V0H9.46799V6.97007L4.30475 2.04109L2.13807 4.10947L7.30131 9.03848H0V11.9615H7.30131L2.13807 16.8906L4.30475 18.9589L9.46799 14.0299V21H12.532V14.0299L17.6953 18.9589L19.8599 16.8906L14.6966 11.9615H22V9.03848Z" fill="#FFD600" /> </svg> <p>x{tickets} Article(s) sélectionné(s)</p> </div> <div className="day-checkbox-container"> {isForfait && (Object.keys(days) as Array<keyof typeof initialDays>).map( (day) => ( <motion.label key={day} className="day-checkbox" whileTap="tap" > <input type="checkbox" checked={days[day]} onChange={() => toggleDaySelection(day)} style={{ display: "none" }} /> <motion.div className="day-button" variants={buttonVariants} animate={days[day] ? "selected" : "unselected"} > {displayDay(day)} </motion.div> </motion.label> ) )} </div> </div> <div className="ticket-control"> <button className="minusButton" onClick={(event) => handleTicketChange(Math.max(tickets - 1, 0), event) } > - </button> <span>{tickets}</span> <button className="sommeButton" onClick={(event) => handleTicketChange(tickets + 1, event)} > + </button> </div> </div> </div> <div className="delimiter-submenu"></div> <div className="bottom-partsubmenu"> <div className="bottom-part-left"> <p>Sous-total</p> <p>{tickets * (typeof price === "number" ? price : 0)}€</p> </div> <Button text={ isLoading ? "Chargement…" : isAdded ? "ARTICLE AJOUTÉ" : "AJOUT PANIER" } isLoading={isLoading} onClick={(event: React.MouseEvent<HTMLElement>) => addToCartHandler(event as React.MouseEvent<HTMLButtonElement>) } /> </div> </motion.div> </motion.div> ); }
ca2f7b14be84cf4236487e59bea324e0
{ "intermediate": 0.4079420268535614, "beginner": 0.37664729356765747, "expert": 0.2154107540845871 }
37,472
ELI5 in-context learning of language models
2cde12b6388e3f52b1012e01df4fc3a1
{ "intermediate": 0.1313636600971222, "beginner": 0.30633941292762756, "expert": 0.5622969269752502 }
37,473
How can I get a list of subscriptions of office 365 in my domain?
638d5d92ca23be8c2bb0bbc3c01da4d4
{ "intermediate": 0.40159299969673157, "beginner": 0.32875120639801025, "expert": 0.2696557343006134 }
37,474
In unity, how would I use an existing reload animation with the animation rigging?
786edea4ca563ec811a70c913a054c05
{ "intermediate": 0.462773859500885, "beginner": 0.2241978645324707, "expert": 0.3130282759666443 }
37,475
Localization of q-form fields on a de Sitter brane in chameleon gravity
ea2eef18d4390ead480b1c12463876a1
{ "intermediate": 0.3298363983631134, "beginner": 0.26616257429122925, "expert": 0.4040010869503021 }
37,476
private IEnumerator Reload() { for (int i = 0; i < InvManager.MaxItems; i++) { if (InvManager.Slots[i].IsTaken == true) //Checking if there's an item in this slot. { Item ItemScript = InvManager.Slots[i].Item.GetComponent<Item>(); //Getting the item script from the items inside the bag. //ItemScript.Name = PlayerPrefs.GetString("Name" + i.ToString()); //Loading the item's name. if (ItemScript.Name == "Ammunition" && ItemScript.Amount >= 1) //Checking if the type of the new item matches with another item already in the bag. { isReloading = true; m_Animator.SetBool("isReloading", true); MotionControllerMotion reload = mMotionController.GetMotion(1, "Reload"); mMotionController.ActivateMotion(reload); reloadingRig.weight += Time.deltaTime / aimDuration; handIKRig.weight -= Time.deltaTime / aimDuration; weaponPoseRig.weight -= Time.deltaTime / aimDuration; bodyAimRig.weight = 0f; aimRig.weight = 0f; int ammoToRemove = (maxAmmo - currentAmmo); if (ammoToRemove > ItemScript.Amount) { ammoToRemove = ItemScript.Amount; } InvManager.RemoveItem(InvManager.Slots[i].Item, (maxAmmo - currentAmmo)); for (int b = 0; b < ammoToRemove; b++) { weaponAudioSource.PlayOneShot(BulletReloadSound); currentAmmo++; yield return new WaitForSeconds(reloadtime); if (currentAmmo == maxAmmo) { AudioClip clip = ReloadSound; weaponAudioSource.PlayOneShot(clip); m_Animator.SetBool("isReloading", false); isReloading = false; } } m_Animator.SetBool("isReloading", false); isReloading = false; reloadingRig.weight -= Time.deltaTime / aimDuration; handIKRig.weight += Time.deltaTime / aimDuration; weaponPoseRig.weight += Time.deltaTime / aimDuration; bodyAimRig.weight = 0f; aimRig.weight = 0f; } } } }
d2f6199319948176ae5118dec5ddcd6d
{ "intermediate": 0.33604103326797485, "beginner": 0.33774206042289734, "expert": 0.3262169361114502 }
37,477
// Start the reload animations by interpolating the rig weight changes. while (elapsedTime < animationDuration) { // Calculate the weight based on the elapsed time float weight = elapsedTime / animationDuration; // Set the weight of your rigs based on this factor reloadingRig.weight += weight; handIKRig.weight -= weight; weaponPoseRig.weight -= weight; // Increase the elapsed time by deltaTime since the last frame elapsedTime += Time.deltaTime; // Wait until the next frame before continuing the loop yield return null; } // Here, after the animation duration has passed, we ensure the weights are set to their final value. reloadingRig.weight = 1f; // Replace with the targeted final value or adjust as needed. handIKRig.weight = 0f; // Replace with the targeted final value or adjust as needed. weaponPoseRig.weight = 0f; // Replace with the targeted final value or adjust as needed.
17e6cf62cd2782e93696a024ae69f87a
{ "intermediate": 0.2503005266189575, "beginner": 0.4209156632423401, "expert": 0.32878378033638 }
37,478
// Initialize the elapsed time to zero. float elapsedTime = 0f; float animationDuration = 0.2f; // Initial weights before the animation starts. // Assuming the weights start from their current values. float initialReloadingRigWeight = reloadingRig.weight; float initialHandIKRigWeight = handIKRig.weight; float initialWeaponPoseRigWeight = weaponPoseRig.weight; // Start the reload animations by interpolating the rig weight changes. while (elapsedTime < animationDuration) { // Calculate the weight based on the elapsed time, using an interpolation method like Lerp (Linear Interpolation). float weight = elapsedTime / animationDuration; // Interpolate the weights of your rigs from their initial values to the final values. reloadingRig.weight = Mathf.Lerp(initialReloadingRigWeight, 1f, weight); handIKRig.weight = Mathf.Lerp(initialHandIKRigWeight, 0f, weight); weaponPoseRig.weight = Mathf.Lerp(initialWeaponPoseRigWeight, 0f, weight); // Increase the elapsed time by deltaTime since the last frame. elapsedTime += Time.deltaTime; // Wait until the next frame before continuing the loop. yield return null; } // Here, after the animation duration has passed, we ensure the weights are set to their final values. reloadingRig.weight = 1f; // Final weight for reloading rig. handIKRig.weight = 0f; // Final weight for hand IK rig. weaponPoseRig.weight = 0f; // Final weight for weapon pose rig.
14eaeb9abb8b975e27160e8bde4daf5f
{ "intermediate": 0.4194360673427582, "beginner": 0.32777610421180725, "expert": 0.25278785824775696 }
37,479
difference between break and continue in javascript
b6d0082aaba7b6558072833b39aa5dd1
{ "intermediate": 0.344327837228775, "beginner": 0.28451797366142273, "expert": 0.37115418910980225 }
37,480
Is there easyest way to print __int128 variable?
af85121323570c64084f3c0e6d3818b7
{ "intermediate": 0.2714065909385681, "beginner": 0.5921854376792908, "expert": 0.13640795648097992 }
37,481
TT
035ce0bb30f71b93708057a5f94d1e04
{ "intermediate": 0.3445412516593933, "beginner": 0.2674623429775238, "expert": 0.3879964351654053 }
37,482
Please assume the role of a unity developer specialising in unity 2020.2.6f1 and visual studio 2017. Can you write an editor script that scans your project for any assets that aren't being used and gives you a list with a checkbox with the option to delete selected assets? Include options to be able to filter by types of asset such as scripts, objects etc. in the view box can you present it like the hierarchy i.e folders as parents?
56e41c772d5fa0474a648e7cfa3bc403
{ "intermediate": 0.5590084195137024, "beginner": 0.26811668276786804, "expert": 0.17287491261959076 }
37,483
If a have a 64 bit system with 32gb ram memory in total but it is from 4 modules of 8gb each. Can I allocate continuous memory block of 25gb using nmap if I it is free there?
3e8022f2a086d631bdd73479ad7df4c0
{ "intermediate": 0.40921589732170105, "beginner": 0.23653967678546906, "expert": 0.3542444109916687 }
37,484
make a program in py to send up packets with random data of a set lenght at a server
fc5b1e164997c1a4587a35d4bc29efed
{ "intermediate": 0.4101649820804596, "beginner": 0.13444916903972626, "expert": 0.45538586378097534 }
37,485
I have two div elements, one called 'messages' and the other called 'mapcontainer'. I want to place 'messages' on top of the 'mapcontainer' div however 'mapcontainer has to have a 'position:absolute;' property. Give me the css needed to put the 'messages' div directly on top of the 'mapcontainer' div.
d2f563ae4429c6e92d930e5afd46d963
{ "intermediate": 0.4492465853691101, "beginner": 0.26496225595474243, "expert": 0.28579115867614746 }
37,486
make a really simple api in python for now that measures how many requests are being done in total to an enpoint, for example /hit, it will add t hese all to a total and provide it in a simple /api/dstat, it will return just the total request since the start of the program and nothing else.
0ae964b029c318c6fc5f5fbf1c63d0d4
{ "intermediate": 0.8089243173599243, "beginner": 0.06526821851730347, "expert": 0.12580744922161102 }
37,487
do you know what a ddos dstat is?
6638ddf29d71b1e9ba54da5c58f03598
{ "intermediate": 0.40023675560951233, "beginner": 0.18649274110794067, "expert": 0.41327041387557983 }
37,488
Instructions: The project focuses on the use of FMCW radar. It is used for data collection, point detection, tracking and other functions. The project is broken down into several modules. The aim of this division is to decouple as much as possible the functionalities present in each module, and make the development of new functionalities more flexible and rapid. Some information will be presented to you in json format: - module: the name of the module - module_structure: the structure of the module (the files making up the module and their hierarchy) - module_files_already_generated_doc: the documentation of the module's files if already generated - other_modules_doc: the documentation of the other modules on which the module depends (possibly none at all) - gen_doc_of_file: the file you will be given to generate the documentation of. If no file is given, the documentation of the entire module must be generated. Your goal is to create a markdown documentation of the file you will be given, or the entire module if no file is given. This documentation is intended to guide a developer who is new to the project, you can therefore add whatever you feel is relevant for this task. Informations: {"module": "radar_area_detection", "module_structure": "radar_area_detection/detection.py;radar_area_detection/display.py;radar_area_detection/live_area_detection.py;radar_area_detection\\comm/camera_alert.py;radar_area_detection\\comm/rabbitmq.py;radar_area_detection\\conf/6432_ti_config.cfg;radar_area_detection\\conf/6843_ti_config.cfg;radar_area_detection\\conf/detection_conf.json;radar_area_detection\\conf/live_area_detection.json;radar_area_detection\\conf/rabbitmq_conf.json;radar_area_detection\\conf/tracking_conf.json;", "module_files_already_generated_doc": [{"file": "docs\\radar_area_detection\\detection.md", "doc": "# radar_area_detection/detection.py Documentation\n\n## Overview\n\nThe detection.py script is part of the [radar_area_detection](radar_area_detection.md) module, which is responsible for the area detection functionality using FMCW radar technology. This module aids in the detection of points, tracking, and implementation of alert systems for certain areas within the radar\u00e2\u20ac\u2122s detection range.\n\n## File Structure\n\n`detection.py` includes the following classes:\n\n- `Area`: A simple data structure representing a rectangular detection area.\n- `Alert`: An abstract base class that defines the structure for raising and clearing alerts.\n- `AreaDetector`: The primary class that manages detection areas and processes radar data to trigger alerts.\n\n### Area Class\n\nThe Area class serves as a representation of a detection zone, defined by its boundaries in Cartesian coordinates.\n\n#### Attributes\n\n- `xl`: Float. Represents the x-coordinate of the left boundary of the area.\n- `xr`: Float. Represents the x-coordinate of the right boundary of the area.\n- `yb`: Float. Represents the y-coordinate of the bottom boundary of the area.\n- `yt`: Float. Represents the y-coordinate of the top boundary of the area.\n\n#### Methods\n\n- `serialize`: Serializes area\u00e2\u20ac\u2122s attributes into a dictionary format.\n\n### Alert Abstract Class\n\nThe `Alert` class provides a blueprint for implementing the alert system that will respond to detection events.\n\n#### Methods (Abstract)\n\n- `RaiseAlert`: Abstract method to be defined to specify the actions required when an alert is raised.\n- `ClearAlert`: Abstract method to be defined to specify the actions required when an alert is cleared.\n\n### AreaDetector Class\n\n`AreaDetector` is the central class that orchestrates the area detection and alerting process.\n\n#### Constructor\n\n- `__init__(areas, alerts=None)`: Initializes the detector with a list of areas and optional alert mechanisms.\n\n#### Attributes\n\n- `alerts`: List of Alert objects. Used to handle alerts when a tracked object enters a detection area.\n- `areas`: List of Area objects. These define the detection areas within the radar\u00e2\u20ac\u2122s field of view.\n- `ok_areas`: List of Area objects that are considered clear of tracked objects.\n- `alert_areas`: List of Area objects where alerts have been triggered due to the presence of tracked objects.\n- `alert_triggered`: Boolean indicating if an alert has been triggered.\n\n#### Methods\n\n- `update(clusters_up_to_date)`: Updates the state of each detection area based on the latest tracked clusters information.\n- `serialize`: Serializes the status of ok_areas and alert_areas into a dictionary format.\n\n## Integration with Other Modules\n\nThe `detection.py` script in the [radar_area_detection](radar_area_detection.md) module works in coordination with the [radar_tracking](../radar_tracking/radar_tracking.md) module (tracks objects detected by the radar) and may utilize the alerting infrastructure provided by the `radar_area_detection\\comm` submodule (for example, sending messages via [RabbitMQ](comm/rabbitmq.md)).\n\n## Usage\n\nDevelopers can use this script to define detection areas, integrate tracking data, and manage alert systems based on their specific needs in the context of FMCW radar applications.\n\n## Developer Notes\n\nThe AreaDetector class initializes with predefined detection areas and has the capability to receive real-time tracking data. Upon receipt of new cluster information, the update method reevaluates and categorizes each area as clear or under alert, triggering the appropriate alert mechanisms if any are in place. \n- When creating new Area instances, ensure that the coordinates correctly reflect the detection zone intended for monitoring.\n- When implementing concrete alert classes, define clear procedures for both RaiseAlert and ClearAlert methods.\n- During the update process, ensure that the centroid of clusters is being correctly obtained from the tracking data.\n- It is crucial to manage ok_areas and alert_areas accurately, reflecting the radar\u00e2\u20ac\u2122s real-time assessment of the monitored areas.\n\n[Radar Area Detection](radar_area_detection.md)"}, {"file": "docs\\radar_area_detection\\display.md", "doc": "# radar_area_detection/display.py Documentation\n\n## Overview\n\nThe `display.py` script is part of the [radar_area_detection](radar_area_detection.md) module, which integrates with the area detection and object tracking functionalities. This script specifically provides visualization capabilities, extending the `TrackingDisplay2D` class from the radar_tracking module to represent detection areas and the status of those areas (either as \"ok\" or under \"alert\").\n\n## File Structure\n\ndisplay.py includes the following class:\n\n- `AreasDisplay2D`: Extends the `TrackingDisplay2D` class to display detection areas and denote their status on a 2D plot.\n\n### AreasDisplay2D Class\n\nThe `AreasDisplay2D` class is responsible for visualizing areas on a 2D display, differentiating between areas that are clear (ok) and those that have an active alert. It allows real-time updates of the visualization as the status of the areas changes according to the radar data.\n\n#### Constructor\n\n- **\\_\\_init__(self, *args, \\*\\*kwargs)**: Initializes the `AreasDisplay2D` class with arguments passed to its superclass and initializes an empty list for patches.\n\n#### Attributes\n\n- **patches**: List. Stores the drawing patches corresponding to areas on the display.\n\n#### Methods\n\n- **_prepare_draw(self, clusters, ok_areas: List[Area], alert_areas: List[Area])**: Internally prepares the drawing of the clusters and areas. It removes any existing patches and re-adds them according to the updated area states.\n- **show(self, clusters, area_detector: AreaDetector)**: Public method to display the radar clusters and areas. This method calls _prepare_draw with the ok_areas and alert_areas from an AreaDetector instance and then proceeds to draw the updated visualization.\n\n### Integration with Other Modules\n\nThe detect.py script in the [radar_area_detection](radar_area_detection.md) module interacts with the AreasDisplay2D class to visualize active areas and alerts. Moreover, the AreasDisplay2D class uses functionality from the radar_tracking module\u00e2\u20ac\u2122s visualization utilities, signifying how various modules within the system come together to fulfill the project\u00e2\u20ac\u2122s overall objectives.\n\n## Usage\n\nDevelopers can instantiate the `AreasDisplay2D` class to visualise the area detection results in the context of FMCW radar applications. This enables a graphical representation of which areas are clear (ok) and which are under alert.\n\n## Data Flow\n\n1. An instance of `AreasDisplay2D` is created with appropriate arguments.\n2. Radar data (clusters) and area statuses are processed by an `AreaDetector`.\n3. Area statuses and clusters are passed to the `AreasDisplay2D` instance\u00e2\u20ac\u2122s show method.\n4. The show method updates the visual representation according to the current state of detection areas and tracked clusters.\n\n## Developer Notes\n\n- Use the `AreasDisplay2D` class to create a visual feedback loop for area detection and alert visualization in real-time radar applications.\n- Ensure active areas and their statuses are correctly updated and reflected in the visualization to provide continuous situational awareness.\n- The visual representation is crucial for debugging and monitoring the radar area detection functionality, hence strive for clear visual distinction between different states for better readability and interpretation.\n\n## Conclusion\n\n`display.py` within the [radar_area_detection](radar_area_detection.md) module serves a pivotal role in visually representing the status of detection areas in real-time. The AreasDisplay2D class demonstrates an effective integration of visualization techniques with radar detection and tracking capabilities. It contributes to the wider goal of creating a modular and adaptable system for FMCW radar applications.\n\n[Radar Area Detection](radar_area_detection.md)"}, {"file": "docs\\radar_area_detection\\live_area_detection.md", "doc": "# radar_area_detection/live_area_detection.py Documentation\n\n## Overview\n\nThe `live_area_detection.py` script is part of the [radar_area_detection](radar_area_detection.md) module. It orchestrates live area detection leveraging data from mmWave radar hardware. Using configuration files, this script setups the radar system, executes detection and tracking algorithms, and detects intrusions within predefined areas. If configured, it sends alert notifications and visualizes the detection areas.\n\n## Usage\n\nThis script should be run with a parameter to indicate the configuration file to use:\n\n
1212466b87eb5c5857bf2cf3e33e9469
{ "intermediate": 0.34244200587272644, "beginner": 0.43980252742767334, "expert": 0.217755526304245 }
37,489
Please write a class of camera follow player also add class of camera rotation
e5d61edac371589c1977da3b0cf7bb46
{ "intermediate": 0.21667274832725525, "beginner": 0.5773324370384216, "expert": 0.2059948742389679 }
37,490
with GTP4 API how to input image and a prompt and generate an image based on that
aeec3dfc53f8a8163474b84647b592aa
{ "intermediate": 0.7915892601013184, "beginner": 0.05426127463579178, "expert": 0.15414944291114807 }
37,491
class CustomTimeDialog(simpledialog.Dialog): def body(self, master): self.timebutton_style = {"font": ("consolas", 11), "fg": "white", "bg": "#3c3c3c", "relief": "flat"} self.title('Custom Time') self.time_background = "#3c3c3c" self.time_fg="white" master.configure(bg=self.time_background) self.configure(bg=self.time_background) self.listbox = tk.Listbox(master, height=7, width=15, font=("Arial", 12), bg=self.time_background, fg=self.time_fg) for time_string in ['0:15', '0:30', '0:45', '1:00', '2:00', '5:00', '10:00']: self.listbox.insert(tk.END, time_string) self.listbox.pack() self.listbox.bind('<<ListboxSelect>>', self.set_spinboxes_from_selection) # Main frame to contain the minutes and seconds frames time_frame = tk.Frame(master, bg=self.time_background) time_frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5) # Create a frame for the minutes spinbox and label minutes_frame = tk.Frame(time_frame, bg=self.time_background) minutes_frame.pack(side=tk.LEFT, fill=tk.X, padx=5) tk.Label(minutes_frame, text="Minutes:", bg=self.time_background, fg=self.time_fg).pack(side=tk.TOP) self.spin_minutes = tk.Spinbox(minutes_frame, from_=0, to=59, width=5, font=("Arial", 12)) self.spin_minutes.pack(side=tk.TOP) # Create a frame for the seconds spinbox and label seconds_frame = tk.Frame(time_frame, bg=self.time_background) seconds_frame.pack(side=tk.LEFT, fill=tk.X, padx=5) tk.Label(seconds_frame, text="Seconds:", bg=self.time_background, fg=self.time_fg).pack(side=tk.TOP) self.spin_seconds = tk.Spinbox(seconds_frame, from_=0, to=59, width=5, font=("Arial", 12), wrap=True) self.spin_seconds.pack(side=tk.TOP) return self.spin_seconds # initial focus def buttonbox(self): box = tk.Frame(self, bg=self.time_background) self.ok_button = tk.Button(box, text="Apply", width=10, command=self.ok, default=tk.ACTIVE) self.ok_button.config(**self.timebutton_style) self.ok_button.pack(side=tk.TOP, padx=5, pady=5) box.pack() def set_spinboxes_from_selection(self, event=None): index = self.listbox.curselection() if not index: return time_string = self.listbox.get(index) minutes, seconds = map(int, time_string.split(':')) self.spin_minutes.delete(0, tk.END) self.spin_minutes.insert(0, minutes) self.spin_seconds.delete(0, tk.END) self.spin_seconds.insert(0, seconds) def apply(self): minutes = int(self.spin_minutes.get()) seconds = int(self.spin_seconds.get()) self.result = minutes * 60 + seconds def validate(self): try: minutes = int(self.spin_minutes.get()) seconds = int(self.spin_seconds.get()) return True except ValueError: self.bell() return False how do i make it so that the list show 15s,30s,45s,1m,5m,10m but still set the same value on the spin when clicked
962629dd8047fae00311b9f2e474142b
{ "intermediate": 0.27713724970817566, "beginner": 0.5186335444450378, "expert": 0.2042291909456253 }
37,492
régle le problème de scope qui fait que je ne peuix pas utiliser calculPrixSelonJourSelec pour le sous total, montre la partie haute du code sans le return en entier et sans abréger avec les modifications nécessaires : Cannot find name 'calculPrixSelonJourSelec'.import { TargetAndTransition, motion } from "framer-motion"; import { useContext, useState } from "react"; import Button from "../components/form/Button"; import { getCookie, setCookie } from "../cookies/CookiesLib.tsx"; import { CartContext } from "../App"; const initialDays = { "20 Jui": false, "21 Jui": false, "22 Jui": false, }; type Props = { id: number; title: string; price: number | string; nbTicket: number; isForfait?: boolean; disabled?: boolean; }; export default function TicketCard({ id, title, price, nbTicket, isForfait, }: Props) { const [isOpen, setIsOpen] = useState(false); const [tickets, setTickets] = useState(nbTicket); const [rotation, setRotation] = useState(0); const [days, setDays] = useState(initialDays); const { cart, setCart } = useContext(CartContext); const [isLoading, setIsLoading] = useState(false); const [isAdded, setIsAdded] = useState(false); type DayKey = "20 Jui" |"21 Jui"|"22 Jui"; const pricesByDay:{[key in DayKey]: number} = { "20 Jui": 60, "21 Jui": 80, "22 Jui": 90, }; const selectedDayCount = () => { return Object.values(days).filter(Boolean).length; } const isDisabled = tickets === 0 || (isForfait && selectedDayCount() !== 2); const handleTicketChange = (newTickets: number, event: React.MouseEvent) => { event.stopPropagation(); setTickets(newTickets); } const addToCartHandler = async ( event: React.MouseEvent<HTMLButtonElement> ) => { event.stopPropagation(); setIsLoading(true); // Longueur actuelle du panier dans les cookies const selectedDays = isForfait ? Object.entries(days) .filter(([_, isChosen]) => isChosen) .map(([day, _]) => day) : []; const calculPrixSelonJourSelec = () => { if (isForfait && selectedDays.length >= 2) { return selectedDays.reduce((total, day) => { const dayKey = day as DayKey; return total + pricesByDay[dayKey]; }, 0); } return 0; }; const itemForCart = { id, title, price: isForfait ? calculPrixSelonJourSelec() : (typeof price === "number" ? price : 0), quantity: tickets, selectedDays, }; // const currentCartLength = (getCookie("cart") || []).length; // condition non valide car si on ajoute un typê billet déjà présent dans le panier, // l'ajout des nouveaux billets ne ferons que changer la valeur de quantité dans le tableau et // donc la longueur du tableau ne changera pas // Initialise la vérification de l'ajout let previousQuantity = 0; let expectedNewQuantity = itemForCart.quantity; let newCart = [...cart]; const billetIndex = newCart.findIndex( (billet) => billet.id === itemForCart.id ); // Si l'article existait déjà dans le panier, on garde la quantité précédente et on détermine la nouvelle quantité attendue if (billetIndex > -1) { previousQuantity = newCart[billetIndex].quantity; expectedNewQuantity += previousQuantity; newCart[billetIndex].quantity = expectedNewQuantity; } else { newCart.push(itemForCart); } // Met à jour le panier setCart(newCart); setCookie("cart", newCart, { expires: 7, sameSite: "None", secure: true }); // Vérification finale si l'ajout est correct en quantité const newBilletIndex = newCart.findIndex( (billet) => billet.id === itemForCart.id ); const hasCorrectQuantity = billetIndex > -1 ? newCart[newBilletIndex].quantity === expectedNewQuantity : newCart.some(billet => billet.id === itemForCart.id && billet.quantity === itemForCart.quantity); if (hasCorrectQuantity) { setTimeout(() => { setIsAdded(true); setIsLoading(false); //arrete l'animation de chargement une fois l'article ajouté + le timeout // fixe un autre délai pour afficher “ARTICLE AJOUTÉ” pendant un moment setTimeout(() => { setIsAdded(false); }, 2000); // Temps pendant lequel “ARTICLE AJOUTÉ” est visible }, 400); // Temps simulant le processus de chargement } else { // ssi l'article a pas été ajouté correctement, j'arrete l'animation de chargement. setTimeout(() => { setIsLoading(false); }, 500); } }; const displayDay = (day: string) => day.replace("Juillet", "Juillet"); const buttonVariants: { [key: string]: TargetAndTransition } = { tap: { scale: 0.95 }, selected: { scale: 1.1, backgroundColor: "#E45A3B" }, unselected: { scale: 1, backgroundColor: "#FFFFFF" }, }; const contentVariants = { closed: { opacity: 0, height: 0, overflow: "hidden", transition: { duration: 0.2, ease: "easeInOut", when: "afterChildren", }, }, open: { opacity: 1, height: title === "Forfait 2 jours" ? 160 : 150, transition: { duration: 0.2, ease: "easeInOut", when: "beforeChildren", }, }, }; const cardVariants = { hidden: { opacity: 0, y: 50 }, visible: { opacity: 1, y: 0, transition: { type: "spring", stiffness: 120, }, }, }; const maxSelectedDays = 2; const toggleDaySelection = (day: keyof typeof initialDays) => { setDays((prevDays) => { const isSelected = prevDays[day]; const count = selectedDayCount(); if (!isSelected && count >= maxSelectedDays) { return prevDays; } return { ...prevDays, [day]: !prevDays[day] }; }); }; return ( <motion.div className="ticket-card" layout initial="hidden" animate="visible" variants={cardVariants} onClick={() => { setIsOpen(!isOpen); setRotation(rotation === 0 ? 90 : 0); }} > <div className="content"> <div className="left-part"> <h4>{title}</h4> <p>Les tickets ne sont pas remboursables.</p> <p>Dernière entrée à 11H.</p> </div> <div className="right-part"> <p>{price}€</p> <motion.div className="svg-container" animate={{ rotate: rotation }}> <svg xmlns="http://www.w3.org/2000/svg" width="13" height="20" viewBox="0 0 13 20" fill="none" > <path d="M2 18L10 10L2 2" stroke="#4E4E4E" strokeWidth="4" /> </svg> </motion.div> </div> </div> <motion.div className={`sub-menu ${ title === "Forfait 2 jours" ? "forfait-2j" : "" }`} variants={contentVariants} initial="closed" animate={isOpen ? "open" : "closed"} exit="closed" > <div className="top-partsubmenu"> <div className="left-part-sub"> <div className="sub-menu-left-part"> <div className="rect"> <img className="" src="images/billet_pass1j.png" alt="Billet pass 1 jour" /> </div> <div className="container"></div> <div className="article-select"> <svg xmlns="http://www.w3.org/2000/svg" width="22" height="21" viewBox="0 0 22 21" fill="none" > <path d="M22 9.03848H14.6966L19.8599 4.10947L17.6953 2.04109L12.532 6.97007V0H9.46799V6.97007L4.30475 2.04109L2.13807 4.10947L7.30131 9.03848H0V11.9615H7.30131L2.13807 16.8906L4.30475 18.9589L9.46799 14.0299V21H12.532V14.0299L17.6953 18.9589L19.8599 16.8906L14.6966 11.9615H22V9.03848Z" fill="#FFD600" /> </svg> <p>x{tickets} Article(s) sélectionné(s)</p> </div> </div> <div className="ticket-control"> <button className="minusButton" onClick={(event) => handleTicketChange(Math.max(tickets - 1, 0), event) } > - </button> <span>{tickets}</span> <button className="sommeButton" onClick={(event) => handleTicketChange(tickets + 1, event)} > + </button> </div> </div> </div> <div className="delimiter-submenu"></div> <div className="bottom-partsubmenu"> <div className="bottom-part-left"> <div className="day-checkbox-container"> {isForfait && (Object.keys(days) as Array<keyof typeof initialDays>).map( (day) => ( <motion.label key={day} className="day-checkbox" whileTap="tap" > <input type="checkbox" checked={days[day]} onChange={() => toggleDaySelection(day)} style={{ display: "none" }} /> <motion.div className="day-button" variants={buttonVariants} animate={days[day] ? "selected" : "unselected"} > {displayDay(day)} </motion.div> </motion.label> ) )} </div> <p>Sous-total</p> <p>{tickets * (isForfait ? calculPrixSelonJourSelec() : (typeof price === "number" ? price : 0))}€</p> </div> <Button text={ isLoading ? "Chargement…" : isAdded ? "ARTICLE AJOUTÉ" : "AJOUT PANIER" } isLoading={isLoading} onClick={(event: React.MouseEvent<HTMLElement>) => addToCartHandler(event as React.MouseEvent<HTMLButtonElement>) } isDisabled={isDisabled} // Passer la prop disabled ici /> </div> </motion.div> </motion.div> ); }
e8c3175cb3068dec510689d5a34bf069
{ "intermediate": 0.39806094765663147, "beginner": 0.2673788368701935, "expert": 0.33456018567085266 }
37,493
je veux avoir pour les tickets de forfait 2 jours un affichage des checboxes qui définissent les jours choisit dans l'item du panier, il faudrait par exemple qu'un forfait 2 jours pour le 20 juillet et le 21 juillet et un autre forfait 2 jours pour le 21 juillet et 22 juillet soit séparées dans le panier, afin que ce soit plus logique d'ajouter des billets avec les memes jours selectionnées : import React, { useContext } from 'react'; import { CartContext } from '../../../../App.tsx'; import { setCookie } from '../../../../cookies/CookiesLib.tsx'; type Props = { id: number; typeBillet: number, title: string, price: number, quantite: number, }; export const ItemPanier: React.FC<Props> = ({ typeBillet, price, quantite, title}) => { const { cart, setCart } = useContext(CartContext); // Fonction pour enlever un billet du panier const removeFromCart = () => { const updatedCart = cart.filter((item: { id: number; }) => item.id !== typeBillet); setCart(updatedCart); setCookie('cart', updatedCart, { expires: 7, sameSite: 'None', secure: true }) }; // Fonction pour mettre à jour la quantité d'un billet dans le panier const updateQuantity = (newQuantity: number) => { const updatedCart = cart.map((item) => { if (item.id === typeBillet) { return { ...item, quantity: newQuantity }; } return item; }); setCart(updatedCart); setCookie('cart', updatedCart, { expires: 7, path: '/' }); // Ajoutez le chemin si nécessaire }; return ( <div className="item-panier"> <div className="container-item-panier"> <div className="container-image"> <img src="/images/billet.png" alt="billet" /> </div> <div className="informations"> <div className='partie-texte'> <div className="textes"> <h4>{title}</h4> <h5>{price}€</h5> </div> </div> <div className="compteur-quantitee"> <span className='ajout-retrait' onClick={() => updateQuantity(Math.max(0, quantite - 1))}>-</span> <input type="number" className='quantite' value={quantite} readOnly /> <span className='ajout-retrait' onClick={() => updateQuantity(quantite + 1)}>+</span> </div> </div> </div> <img className='cross' src="/icones/cross.svg" alt="croix" onClick={removeFromCart} /> </div> ); };import React, { useContext } from 'react'; import { CartContext } from '../../../../App.tsx'; // Assurez-vous que le chemin est correct import { ItemPanier } from './ItemPanier'; import { motion } from 'framer-motion'; import Button from '../../../../components/form/Button'; type Props = { isOpen: boolean; setIsOpen: (isOpen: boolean) => void; }; const MenuPanier: React.FC<Props> = ({ isOpen, setIsOpen }) => { const { cart } = useContext(CartContext); // Calculer le sous-total const subtotal = cart.reduce((acc: number, item: { price: number; quantity: number; }) => acc + item.price * item.quantity, 0); const menuVariants = { hidden: { x: '42rem', transition: { duration: 0.5, ease: [1, -0.02, 0, 1] } }, visible: { x: 0, transition: { duration: 0.5, ease: [1, -0.02, 0, 1] } }, }; return ( <motion.div className="side-menu cart" variants={menuVariants} initial="hidden" animate={isOpen ? "visible" : "hidden"} > <svg className="cross" onClick={() => setIsOpen(false)} width="36" height="28" viewBox="0 0 36 28" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect x="6.52539" y="0.321533" width="35.8974" height="3.58974" rx="1.79487" transform="rotate(45 6.52539 0.321533)" fill="#E45A3B"/> <rect x="3.87891" y="25.5957" width="35.8974" height="3.58974" rx="1.79487" transform="rotate(-45 3.87891 25.5957)" fill="#E45A3B"/> </svg> <div className="container"> <h2>Mon panier</h2> <section className='le-panier'> {cart.length > 0 ? ( cart.map((item) => ( <ItemPanier key={item.id} id={item.id} typeBillet={item.id} title={item.title} price={typeof item.price === 'number' ? item.price : parseInt(item.price, 10)} quantite={item.quantity} /> )) ) : ( <p>Panier Vide</p> )} </section> <div className="sous-total"> <h4>Sous total: </h4> <h4>{subtotal.toFixed(2)}€</h4> </div> <Button text="RESERVER"></Button> </div> </motion.div> ); }; export default MenuPanier;
a2815622ead7618d8e4d5f8262e26e58
{ "intermediate": 0.23990409076213837, "beginner": 0.5745935440063477, "expert": 0.185502290725708 }
37,494
Write a flask api to verify if the entered username exist in the sqldb table or not, and return a boolean true or false. Below is a snippet of code querying the same db for reference: getDbUserName = session.query(Model.models.Application.M_PatientsDtl.MPD_Name, Model.models.Application.M_PatientsDtl.MPDID, Model.models.Application.M_PatientsDtl.MPD_Mobile, Model.models.Application.M_PatientsDtl.MPD_hashedPassword).filter_by(MPD_hashedPassword=pswd, MPD_Username=username, MPD_User=1, MPD_IsActive=1, MPD_IsDeleted=0).all()
3aa194f4e3c3478a1d3d5a28eca1662a
{ "intermediate": 0.5538959503173828, "beginner": 0.2674516439437866, "expert": 0.17865239083766937 }
37,495
how specify Content-type: text/json; charset=utf-8; in requests.post
324ac43d44c19e7c05666d3e40b118f3
{ "intermediate": 0.36960989236831665, "beginner": 0.24452954530715942, "expert": 0.38586053252220154 }
37,496
User Below is my models/user: import mongoose, { Schema, models } from "mongoose" const userSchema = new Schema ( { name: { type: String, required: true, }, email: { type: String, required: true, }, password: { type: String, required: true, }, dob: { type: Date, required: true, }, constituency: { type: String, required: true, }, uvc: { type: String }, voted: { type: Boolean, required: true, }, admin: { type: Boolean, required: true, } }, { timestamps: true } ); const User = models.User || mongoose.model("User", userSchema); export default User; Below is my partyselection.jsx: "use client"; import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { useRouter } from 'next/navigation'; // Import useRouter export default function Dashboard() { const [showPopup, setShowPopup] = useState(false); const [selectedParty, setSelectedParty] = useState(''); const [parties, setParties] = useState({}); // Updated const router = useRouter(); // Create an instance of useRouter const handleLogout = async () => { try { await axios.post('/api/logout'); router.push('/'); // Redirect to home page } catch (error) { console.error('Error during logout:', error); } }; useEffect(() => { const fetchParties = async () => { try { const response = await axios.get('api/partymembers'); setParties(response.data); // Update parties with response data } catch (error) { console.error('Error fetching parties:', error); } }; fetchParties(); }, []); const partyColors = { Blue: 'bg-blue-500', Red: 'bg-red-500', Yellow: 'bg-yellow-500', Independent: 'bg-gray-500', }; const handlePartySelect = (party) => { setSelectedParty(party); setShowPopup(true); }; const handleClosePopup = () => { setShowPopup(false); setSelectedParty(''); }; // Modify handleSubmit in PartySelection.jsx const handleSubmit = async (event) => { event.preventDefault(); const candidateName = event.target.candidate.value; try { // First, check if the user has already voted const voteCheckResponse = await axios.get('/api/checkvoted'); // Check if the user has already voted if (voteCheckResponse.status === 403) { alert("You have already cast your vote."); return; // Exit the function to prevent further execution } // If the user hasn't voted, continue with the voting process const voteResponse = await axios.post('/api/incrementvote', { candidateName, party: selectedParty }); if (voteResponse.status === 200) { alert(`Vote for ${candidateName} from ${selectedParty} Party submitted successfully!`); handleClosePopup(); } else { throw new Error("Failed to submit the vote"); } } catch (error) { if (error.response && error.response.status === 403) { // Handle the specific case where the user has already voted alert("You have already cast your vote."); } else { // Handle other errors console.error('Error submitting vote:', error); alert('Error submitting vote. Please try again.'); } } }; return ( <div className="grid place-items-center min-h-screen"> {/* Logout Button */} <div className="absolute top-4 right-4"> <button onClick={handleLogout} className="bg-red-600 text-white font-bold cursor-pointer px-6 py-2 rounded" > Log Out </button> </div> {/* Rest of the Dashboard */} <div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-4 w-full max-w-4xl"> {/* ... */} </div> <div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-4 w-full max-w-4xl"> {/* Party buttons */} {Object.keys(parties).map((party, index) => ( <div key={index} className="shadow-lg p-8 bg-zinc-300/10 flex flex-col gap-4"> <div className="text-center"> <span className="font-bold text-lg md:text-xl">{`${party} Party`}</span> </div> <button className={`${partyColors[party]} text-white font-bold px-4 py-2 text-sm md:text-lg w-full`} onClick={() => handlePartySelect(party)} > View candidates </button> </div> ))} {/* Popup */} {showPopup && ( <div className="fixed top-0 left-0 w-full h-full bg-black bg-opacity-50 flex justify-center items-center"> <div className="bg-white p-5 rounded flex flex-col items-center justify-center"> <form onSubmit={handleSubmit} className="w-full"> <label className="block text-center mb-4">Select a candidate from {selectedParty} Party:</label> <select name="candidate" className="w-full p-2 border border-gray-300 rounded mb-4"> {parties[selectedParty].map((candidate, index) => ( <option key={index} value={candidate}>{candidate}</option> ))} </select> <div className="flex justify-between gap-3"> <button type="submit" className="bg-green-500 text-white px-4 py-2 rounded flex-1">Submit</button> <button type="button" onClick={handleClosePopup} className="bg-orange-500 text-white px-4 py-2 rounded flex-1">Cancel</button> </div> </form> </div> </div> )} </div> </div> ); } Below is an example api used for getting candidates: import { connectMongoDB } from "@/lib/mongodb"; import Candidate from "@/models/candidate"; export async function GET(req) { try { await connectMongoDB(); // Fetch all candidates from the database const candidates = await Candidate.find({}).select("name party votes constituency"); return new Response( JSON.stringify(candidates), { status: 200, headers: { 'Content-Type': 'application/json' } } ); } catch (error) { console.error("Error fetching candidates: ", error); return new Response( JSON.stringify({ message: "An error occurred while fetching candidates" }), { status: 500, headers: { 'Content-Type': 'application/json' } } ); } } Please provide code changes needed to update the users voted value to true upon voting. Use this as an example for the new api so layout stays consistent
3e56085f96ea6e4dc0e646a4f4dbd0ef
{ "intermediate": 0.3878208100795746, "beginner": 0.36675670742988586, "expert": 0.24542245268821716 }
37,497
Please update the below code so that if a users voted value is false, it is updated to true: import { connectMongoDB } from "@/lib/mongodb"; import User from "@/models/user"; import { NextResponse } from "next/server"; export async function GET(req) { try { await connectMongoDB(); // Retrieve the user's email from the cookie const email = req.cookies.get('email').value; // Assuming email is stored in a cookie console.log(email) if (!email) { return new Response( JSON.stringify({ message: "No user email found in cookies" }), { status: 401, headers: { 'Content-Type': 'application/json' } } ); } // Find the user by email const user = await User.findOne({ email }); if (!user) { return new Response( JSON.stringify({ message: "User not found" }), { status: 404, headers: { 'Content-Type': 'application/json' } } ); } // Check if the user has already voted if (user.voted) { return new Response( JSON.stringify({ message: "User has already voted" }), { status: 403, headers: { 'Content-Type': 'application/json' } } ); } // User has not voted return new Response( JSON.stringify({ message: "User has not voted" }), { status: 200, headers: { 'Content-Type': 'application/json' } } ); } catch (error) { console.error("Error checking voting status: ", error); return new Response( JSON.stringify({ message: "An error occurred while checking voting status", error: error.message }), { status: 500, headers: { 'Content-Type': 'application/json' } } ); } }
e44d41765a0cefe6755efb47bbdbe7d4
{ "intermediate": 0.36697980761528015, "beginner": 0.3667539656162262, "expert": 0.26626622676849365 }
37,498
If a have a 64 bit system with 32gb ram memory in total but it is from 4 modules of 8gb each. Can I allocate continuous memory block of 25gb using mmap if I it is free there but some memory fragmentations take a place there?
e11312bc0c87dc8feea4c0a78b1e0025
{ "intermediate": 0.3992578089237213, "beginner": 0.22768330574035645, "expert": 0.37305888533592224 }
37,499
how do I get rid of the white background behind the whole graph ? <!DOCTYPE html> <html> <head> <title>L7 DSTAT :3</title> <script src="https://code.highcharts.com/highcharts.js"></script> <link rel="stylesheet" href="css/index.css"> </head> <body> <div id="requestCountGraph" style="width: 100%; height: 400px;"></div> <script> var requestData = []; var lastRequestCount = null; var maxDataPoints = 40; // Modify as needed for max length of the graph // Create the Highcharts graph var chart = Highcharts.chart('requestCountGraph', { chart: { type: 'line', backbroundColor: null, events: { load: requestDataUpdate } }, title: { text: 'L7 DSTAT ~ http://127.0.0.1:5000/hit' }, xAxis: { type: 'datetime', tickPixelInterval: 150 }, yAxis: { title: { text: 'Request Count Difference' } }, plotOptions: { line: { lineWidth: 2, } }, series: [{ name: 'Requests', data: [] }] }); function requestDataUpdate() { setInterval(function() { fetch('http://127.0.0.1:5000/api/dstat') .then(response => response.json()) .then(data => { var currentRequestCount = data.total_requests; if (lastRequestCount !== null) { // Skip first request var diff = currentRequestCount - lastRequestCount; var x = (new Date()).getTime(); // current time // Add the point to the graph // and shift the series if necessary var shift = chart.series[0].data.length >= maxDataPoints; chart.series[0].addPoint([x, diff], true, shift); // No need to use requestData array as Highcharts manages the data } lastRequestCount = currentRequestCount; }); }, 1000); // Update every second } </script> </body> </html>
573267bc24c20b1a5ba49706720a8818
{ "intermediate": 0.345670223236084, "beginner": 0.42952582240104675, "expert": 0.22480392456054688 }
37,500
<!DOCTYPE html> <html> <head> <title>L7 DSTAT :3</title> <script src="https://code.highcharts.com/highcharts.js"></script> <link rel="stylesheet" href="css/index.css"> </head> <body> <div id="requestCountGraph" style="width: 100%; height: 400px;"></div> <script> var requestData = []; var lastRequestCount = null; var maxDataPoints = 40; // Modify as needed for max length of the graph // Create the Highcharts graph var chart = Highcharts.chart('requestCountGraph', { chart: { type: 'line', backgroundColor: null, events: { load: requestDataUpdate } }, title: { text: 'L7 DSTAT ~ http://127.0.0.1:5000/hit' }, xAxis: { type: 'datetime', tickPixelInterval: 150 }, yAxis: { title: { text: 'Requests/second' } }, plotOptions: { line: { lineWidth: 2, } }, series: [{ name: 'Requests', data: [] }] }); function requestDataUpdate() { setInterval(function() { fetch('http://127.0.0.1:5000/api/dstat') .then(response => response.json()) .then(data => { var currentRequestCount = data.total_requests; if (lastRequestCount !== null) { // Skip first request var diff = currentRequestCount - lastRequestCount; var x = (new Date()).getTime(); // current time // Add the point to the graph // and shift the series if necessary var shift = chart.series[0].data.length >= maxDataPoints; chart.series[0].addPoint([x, diff], true, shift); // No need to use requestData array as Highcharts manages the data } lastRequestCount = currentRequestCount; }); }, 1000); // Update every second } </script> </body> </html> I removed the background on the charts, now all the lines are still gray even though my background is aslo gray which looks shit and is bad to read. how can I make it all white
589bf0f7028231b39292811f4f3e553d
{ "intermediate": 0.3359330892562866, "beginner": 0.49791789054870605, "expert": 0.1661490499973297 }
37,501
Dans cet application Flask React, implémente la logique pour inserer les billets dans la base de données lorsqu'on clique sur le bouton "RESERVER" de menu panier, from datetime import datetime, date, time, timedelta class Faq: def __init__(self, idFaq: int, question: str, reponse: str): self._idFaq = idFaq self._question = question self._reponse = reponse def get_idFaq(self): return self._idFaq def get_question(self): return self._question def get_reponse(self): return self._reponse def to_dict(self): return { "idFaq": self._idFaq, "question": self._question, "reponse": self._reponse } class User: def __init__(self, idUser: int, pseudoUser: str, mdpUser: str, emailUser: str, statutUser: str): self.__idUser = idUser self.__pseudoUser = pseudoUser self.__mdpUser = mdpUser self.__emailUser = emailUser self.__statutUser = statutUser def get_idUser(self): return self.__idUser def get_pseudoUser(self): return self.__pseudoUser def get_mdpUser(self): return self.__mdpUser def get_emailUser(self): return self.__emailUser def get_statutUser(self): return self.__statutUser def set_pseudoUser(self, pseudoUser): self.__pseudoUser = pseudoUser def set_mdpUser(self, mdpUser): self.__mdpUser = mdpUser def set_emailUser(self, emailUser): self.__emailUser = emailUser def to_dict(self): return { "idUser": self.__idUser, "pseudoUser": self.__pseudoUser, "emailUser": self.__emailUser } class Festival: def __init__(self, idF: int, nomF: str, villeF: str, dateDebutF: str, dateFinF: str): self.__idF = idF self.__nomF = nomF self.__villeF = villeF self.__dateDebutF = dateDebutF if isinstance(dateDebutF, date) else datetime.strptime(dateDebutF, '%Y-%m-%d').date() self.__dateFinF = dateFinF if isinstance(dateFinF, date) else datetime.strptime(dateFinF, '%Y-%m-%d').date() def get_idF(self): return self.__idF def get_nomF(self): return self.__nomF def get_villeF(self): return self.__villeF def get_dateDebutF(self): return self.__dateDebutF def get_dateFinF(self): return self.__dateFinF def __repr__(self): return f"({self.__idF}, {self.__nomF}, {self.__villeF}, {self.__dateDebutF}, {self.__dateFinF})" def to_dict(self): return { "idF": self.__idF, "nomF": self.__nomF, "villeF": self.__villeF, "dateDebutF": self.__dateDebutF.isoformat(), "dateFinF": self.__dateFinF.isoformat() } class Type_Billet: def __init__(self, idType: int, duree: int): self.__idType = idType self.__duree = duree def get_idType(self): return self.__idType def get_duree(self): return self.__duree def to_dict(self): return { "idType": self.__idType, "duree": self.__duree } class Spectateur: def __init__(self, idS: int, nomS: str, prenomS: str, adresseS: str, emailS: str, mdpS: str): self.__idS = idS self.__nomS = nomS self.__prenomS = prenomS self.__adresseS = adresseS self.__emailS = emailS self.__mdpS = mdpS def get_idS(self): return self.__idS def get_nomS(self): return self.__nomS def get_prenomS(self): return self.__prenomS def get_adresseS(self): return self.__adresseS def get_emailS(self): return self.__emailS def get_mdpS(self): return self.__mdpS def to_dict(self): return { "idS": self.__idS, "nomS": self.__nomS, "prenomS": self.__prenomS, "adresseS": self.__adresseS, "emailS": self.__emailS, "mdpS": self.__mdpS } class Billet: def __init__(self, idB: int, idF: int, idType: int, idS: int, prix: int, dateAchat: str, dateDebutB: str, dateFinB: str): self.__idB = idB self.__idF = idF self.__idType = idType self.__idS = idS self.__prix = prix self.__dateAchat = dateAchat if isinstance(dateAchat, date) else datetime.strptime(dateAchat, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() if dateDebutB != None and dateFinB != None: self.__dateDebutB = dateDebutB if isinstance(dateDebutB, date) else datetime.strptime(dateDebutB, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() self.__dateFinB = dateFinB if isinstance(dateFinB, date) else datetime.strptime(dateFinB, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() else: self.__dateDebutB = None self.__dateFinB = None def get_idB(self): return self.__idB def get_idFestival(self): return self.__idF def get_idType(self): return self.__idType def get_idSpectateur(self): return self.__idS def get_prix(self): return self.__prix def get_dateAchat(self): return self.__dateAchat def get_dateDebutB(self): return self.__dateDebutB def get_dateFinB(self): return self.__dateFinB def to_dict(self): return { "idB": self.__idB, "idF": self.__idF, "idType": self.__idType, "idS": self.__idS, "prix": self.__prix, "dateAchat": self.__dateAchat.isoformat(), "dateDebutB": self.__dateDebutB.isoformat(), "dateFinB": self.__dateFinB.isoformat() } class Lieu: def __init__(self, idL: int, idF: int, nomL: str, adresseL: str, jaugeL: int): self.__idL = idL self.__idF = idF self.__nomL = nomL self.__adresseL = adresseL self.__jaugeL = jaugeL def get_idL(self): return self.__idL def get_idFestival(self): return self.__idF def get_nomL(self): return self.__nomL def get_adresseL(self): return self.__adresseL def get_jaugeL(self): return self.__jaugeL def to_dict(self): return { "idL": self.__idL, "idF": self.__idF, "nomL": self.__nomL, "adresseL": self.__adresseL, "jaugeL": self.__jaugeL } class Hebergement: def __init__(self, idH: int, nomH: str, limitePlacesH: int, adresseH: int): self.__idH = idH self.__nomH = nomH self.__limitePlacesH = limitePlacesH self.__adresseH = adresseH def get_idH(self): return self.__idH def get_nomH(self): return self.__nomH def get_limitePlacesH(self): return self.__limitePlacesH def get_adresseH(self): return self.__adresseH def set_nomH(self, nomH): self.__nomH = nomH def set_limitePlacesH(self, limitePlacesH): self.__limitePlacesH = limitePlacesH def set_adresseH(self, adresseH): self.__adresseH = adresseH def to_dict(self): return { "idH": self.__idH, "nomH": self.__nomH, "limitePlacesH": self.__limitePlacesH, "adresseH": self.__adresseH } class Programmer: def __init__(self, idF: int, idL: int, idH: int, dateArrivee: str, heureArrivee: str, dateDepart: str, heureDepart: str): self.__idF = idF self.__idL = idL self.__idH = idH self.__dateArrivee = dateArrivee if isinstance(dateArrivee, date) else datetime.strptime(dateArrivee, '%Y-%m-%d').date() self.__heureArrivee = self.timedelta_to_time(heureArrivee) if isinstance(heureArrivee, timedelta) else datetime.strptime(heureArrivee, '%H:%M').time() self.__dateDepart = dateDepart if isinstance(dateDepart, date) else datetime.strptime(dateDepart, '%Y-%m-%d').date() self.__heureDepart = self.timedelta_to_time(heureDepart) if isinstance(heureDepart, timedelta) else datetime.strptime(heureDepart, '%H:%M').time() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idFestival(self): return self.__idF def get_idLieu(self): return self.__idL def get_idHebergement(self): return self.__idH def get_dateArrivee(self): return self.__dateArrivee def get_heureArrivee(self): return self.__heureArrivee def get_dateDepart(self): return self.__dateDepart def get_heureDepart(self): return self.__heureDepart def to_dict(self): return { "idF": self.__idF, "idL": self.__idL, "idH": self.__idH, "dateArrivee": self.__dateArrivee.isoformat(), "heureArrivee": self.__heureArrivee.strftime("%H:%M:%S"), "dateDepart": self.__dateDepart.isoformat(), "heureDepart": self.__heureDepart.strftime("%H:%M:%S") } class Groupe: def __init__(self, idG: int, idH: int, nomG: str, descriptionG: str): self.__idG = idG self.__idH = idH self.__nomG = nomG self.__descriptionG = descriptionG def get_idG(self): return self.__idG def get_idHebergement(self): return self.__idH def get_nomG(self): return self.__nomG def get_descriptionG(self): return self.__descriptionG def set_idHebergement(self, idH): self.__idH = idH def to_dict(self): return { "idG": self.__idG, "idH": self.__idH, "nomG": self.__nomG, "descriptionG": self.__descriptionG } def set_nomG(self, nomG): self.__nomG = nomG def set_descriptionG(self, descriptionG): self.__descriptionG = descriptionG class Membre_Groupe: def __init__(self, idMG: int, idG, nomMG: str, prenomMG: str, nomDeSceneMG: str): self.__idMG = idMG self.__idG = idG self.__nomMG = nomMG self.__prenomMG = prenomMG self.__nomDeSceneMG = nomDeSceneMG def get_idMG(self): return self.__idMG def get_idGroupe(self): return self.__idG def get_nomMG(self): return self.__nomMG def get_prenomMG(self): return self.__prenomMG def get_nomDeSceneMG(self): return self.__nomDeSceneMG def __repr__(self): return f"({self.__idMG}, {self.__idG}, {self.__nomMG}, {self.__prenomMG}, {self.__nomDeSceneMG})" def to_dict(self): return { "idMG": self.__idMG, "idG": self.__idG, "nomMG": self.__nomMG, "prenomMG": self.__prenomMG, "nomDeSceneMG": self.__nomDeSceneMG } def set_nomMG(self, nomMG): self.__nomMG = nomMG def set_prenomMG(self, prenomMG): self.__prenomMG = prenomMG def set_nomDeSceneMG(self, nomDeSceneMG): self.__nomDeSceneMG = nomDeSceneMG class Instrument: def __init__(self, idI: int, nomI: str): self.__idI = idI self.__nomI = nomI def get_idI(self): return self.__idI def get_nomI(self): return self.__nomI def to_dict(self): return { "idI": self.__idI, "nomI": self.__nomI } class Style_Musical: def __init__(self, idSt: int, nomSt: str): self.__idSt = idSt self.__nomSt = nomSt def get_idSt(self): return self.__idSt def get_nomSt(self): return self.__nomSt def to_dict(self): return { "idSt": self.__idSt, "nomSt": self.__nomSt } class Lien_Video: def __init__(self, idLV: int, idG: int, video: str): self.__idLV = idLV self.__idG = idG self.__video = video def get_idLV(self): return self.__idLV def get_idGroupe(self): return self.__idG def get_video(self): return self.__video def to_dict(self): return { "idLV": self.__idLV, "idG": self.__idG, "video": self.__video } class Lien_Reseaux_Sociaux: def __init__(self, idLRS: int, idG: int, reseau: str): self.__idLRS = idLRS self.__idG = idG self.__reseau = reseau def get_idLRS(self): return self.__idLRS def get_idGroupe(self): return self.__idG def get_reseau(self): return self.__reseau def to_dict(self): return { "idLRS": self.__idLRS, "idG": self.__idG, "reseau": self.__reseau } class Evenement: def __init__(self, idE: int, idG: int, idL: int, nomE: str, heureDebutE: str, heureFinE: str, dateDebutE: str, dateFinE: str): self.__idE = idE self.__idG = idG self.__idL = idL self.__nomE = nomE self.__heureDebutE = self.timedelta_to_time(heureDebutE) if isinstance(heureDebutE, timedelta) else datetime.strptime(heureDebutE, '%H:%M').time() self.__heureFinE = self.timedelta_to_time(heureFinE) if isinstance(heureFinE, timedelta) else datetime.strptime(heureFinE, '%H:%M').time() self.__dateDebutE = dateDebutE if isinstance(dateDebutE, date) else datetime.strptime(dateDebutE, "%Y-%m-%d").date() self.__dateFinE = dateFinE if isinstance(dateFinE, date) else datetime.strptime(dateFinE, "%Y-%m-%d").date() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idE(self): return self.__idE def get_idG(self): return self.__idG def get_idL(self): return self.__idL def get_nomE(self): return self.__nomE def get_heureDebutE(self): return self.__heureDebutE def get_heureFinE(self): return self.__heureFinE def get_dateDebutE(self): return self.__dateDebutE def get_dateFinE(self): return self.__dateFinE def set_idG(self, idG): self.__idG = idG def set_idL(self, idL): self.__idL = idL def set_nomE(self, nomE): self.__nomE = nomE def set_heureDebutE(self, heureDebutE): self.__heureDebutE = heureDebutE def set_heureFinE(self, heureFinE): self.__heureFinE = heureFinE def set_dateDebutE(self, dateDebutE): self.__dateDebutE = dateDebutE def set_dateFinE(self, dateFinE): self.__dateFinE = dateFinE def to_dict(self): return { "idE": self.__idE, "idG": self.__idG, "idL": self.__idL, "nomE": self.__nomE, "heureDebutE": self.__heureDebutE.strftime("%H:%M:%S") if self.__heureDebutE else None, "heureFinE": self.__heureFinE.strftime("%H:%M:%S") if self.__heureFinE else None, "dateDebutE": self.__dateDebutE.isoformat() if self.__dateDebutE else None, "dateFinE": self.__dateFinE.isoformat() if self.__dateFinE else None } class Activite_Annexe: def __init__(self, idE: int, typeA: str, ouvertAuPublic: bool): self.__idE = idE self.__typeA = typeA self.__ouvertAuPublic = ouvertAuPublic def get_idEvenement(self): return self.__idE def get_typeA(self): return self.__typeA def get_ouvertAuPublic(self): return self.__ouvertAuPublic def to_dict(self): return { "idE": self.__idE, "typeA": self.__typeA, "ouvertAuPublic": self.__ouvertAuPublic } class Concert: def __init__(self, idE: int, tempsMontage: str, tempsDemontage: str): self.__idE = idE self.__tempsMontage = self.timedelta_to_time(tempsMontage) if isinstance(tempsMontage, timedelta) else datetime.strptime(tempsMontage, '%H:%M').time() self.__tempsDemontage = self.timedelta_to_time(tempsDemontage) if isinstance(tempsDemontage, timedelta) else datetime.strptime(tempsDemontage, '%H:%M').time() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idEvenement(self): return self.__idE def get_tempsMontage(self): return self.__tempsMontage def get_tempsDemontage(self): return self.__tempsDemontage def to_dict(self): return { "idE": self.__idE, "tempsMontage": self.__tempsMontage.strftime("%H:%M:%S"), "tempsDemontage": self.__tempsDemontage.strftime("%H:%M:%S") } class Groupe_Style: def __init__(self, idG: int, idSt: int): self.__idG = idG self.__idSt = idSt def get_idG(self): return self.__idG def get_idSt(self): return self.__idSt def to_dict(self): return { "idG": self.__idG, "idSt": self.__idSt }from flask import Flask, send_file from flask_cors import CORS from flask import Flask, request, jsonify, render_template, redirect, url_for from flask_sqlalchemy import SQLAlchemy import sys sys.path.append('../BD') sys.path.append('../mail') from GroupeBD import GroupeBD from LienRS_BD import LienRS_BD from HebergementBD import HebergementBD from Membre_GroupeBD import Membre_GroupeBD from ConnexionBD import ConnexionBD from UserBD import UserBD from emailSender import EmailSender from generateurCode import genererCode from FaqBD import FaqBD from EvenementBD import EvenementBD from Style_MusicalBD import Style_MusicalBD from Groupe_StyleBD import Groupe_StyleBD from ConcertBD import ConcertBD from Activite_AnnexeBD import Activite_AnnexeBD from LieuBD import LieuBD from BilletBD import BilletBD from Type_BilletBD import Type_BilletBD from SpectateurBD import SpectateurBD from InstrumentBD import InstrumentBD from BD import * MAIL_FESTIUTO = "festiuto@gmail.com" MDP_FESTIUTO = "xutxiocjikqolubq" app = Flask(__name__) # app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://coursimault:coursimault@servinfo-mariadb/DBcoursimault' app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/gestiuto' CORS(app, resources={r"/*": {"origins": "*"}}) db = SQLAlchemy(app) app.config['BOOTSTRAP_SERVE_LOCAL'] = True @app.route('/') def index(): return render_template('API.html') @app.route('/getNomsArtistes') def getNomsArtistes(): connexion_bd = ConnexionBD() membre_groupebd = Membre_GroupeBD(connexion_bd) res = membre_groupebd.getNomsArtistes_json() if res is None: return jsonify({"error": "Aucun artiste trouve"}) else: return res @app.route('/getArtistes') def getArtistes(): connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) res = groupebd.get_groupes_json() if res is None: return jsonify({"error": "Aucun artiste trouve"}) else: return res @app.route('/filtrerArtistes') def filtrerArtistes(): connexion_bd = ConnexionBD() evenementbd = EvenementBD(connexion_bd) liste_groupes_21 = evenementbd.groupes_21_juillet_to_json() liste_groupes_22 = evenementbd.groupes_22_juillet_to_json() liste_groupes_23 = evenementbd.groupes_23_juillet_to_json() return jsonify({"21 juillet": liste_groupes_21, "22 juillet": liste_groupes_22, "23 juillet": liste_groupes_23}) @app.route('/getInformationsSupplementairesArtiste/<int:id>') def getInformationsSupplementairesArtiste(id): connexion_bd = ConnexionBD() lienRS = LienRS_BD(connexion_bd) res = lienRS.get_lienRS_json(id) if res is None: return jsonify({"error": "Aucun artiste trouve"}) else: return res @app.route('/getArtiste/<int:id>') def getArtiste(id): connexion_bd = ConnexionBD() membre_groupebd = Membre_GroupeBD(connexion_bd) mb = membre_groupebd.get_artiste_by_id(id) res = mb.to_dict() return jsonify({"error": "Aucun artiste trouve"}) if res is None else res @app.route('/connecter', methods=['POST']) def connecter(): connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) data = request.get_json() print(data) email = data["email"] password = data["password"] if userbd.exist_user(email, password): return userbd.user_to_json(userbd.get_user_by_email(email)) else: return jsonify({"error": "Utilisateur non trouve"}) @app.route('/inscription', methods=['POST']) def inscription(): connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) data = request.get_json() print(data) pseudo = data["pseudo"] email = data["email"] password = data["password"] if userbd.exist_user(email, password): return jsonify({"error": "Utilisateur déjà existant"}) else: res = userbd.add_user(pseudo, email, password) if res: return userbd.user_to_json(userbd.get_user_by_email(email)) elif res == "emailErr": return jsonify({"error": "Email déjà existant"}) else: return jsonify({"error": "Erreur lors de l'ajout de l'utilisateur"}) @app.route('/modifierProfil', methods=['POST']) def modifierProfil(): connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) data = request.get_json() print(data) idUser =data['id'] pseudo = data["pseudo"] email = data["email"] password = data["password"] ancien_mdp = data['oldPassword'] if userbd.exist_user_with_id(idUser, ancien_mdp): res = userbd.update_user(idUser, email, pseudo, password) if res: return userbd.user_to_json(userbd.get_user_by_email(email)) elif res == "emailErr": return jsonify({"error": "Email déjà existant"}) else: return jsonify({"error": "Erreur lors de la modification de l'utilisateur"}) else: return jsonify({"error": "Utilisateur non trouve"}) @app.route('/envoyerCodeVerification', methods=['POST']) def envoyerCodeVerification(): data = request.get_json() emailUser = data["email"] connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) if not userbd.email_exists(emailUser): return jsonify({"error": "Email non existant"}) code = genererCode() email_sender = EmailSender(MAIL_FESTIUTO, MDP_FESTIUTO) res = email_sender.sendCodeVerification(emailUser, code) if res: resAjout = userbd.ajouterCodeVerification(emailUser, code) if resAjout: return jsonify({"success": "code envoyé"}) return jsonify({"error": "erreur lors de l'envoi du code"}) @app.route('/testerCodeVerification', methods=['POST']) def tester_code_verification(): data = request.get_json() emailUser = data["email"] code = data["code"] connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) if not userbd.email_exists(emailUser): return jsonify({"error": "Email non existant"}) if userbd.tester_code_verification(emailUser, code): return jsonify({"success": "code correct"}) else: return jsonify({"error": "code incorrect"}) @app.route("/modifierMdp", methods=['POST']) def modifierMdp(): data = request.get_json() emailUser = data["email"] nouveauMdp = data["password"] code = data["code"] connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) if not userbd.email_exists(emailUser): return jsonify({"error": "Email non existant"}) if userbd.tester_code_verification(emailUser, code): res = userbd.update_password(emailUser, nouveauMdp) if res: return jsonify({"success": "mot de passe modifié"}) else: return jsonify({"error": "erreur lors de la modification du mot de passe"}) @app.route('/ajouterImage', methods=['POST']) def ajouterImage(): # permet de stocker l'image dans la base de données sous forme de blob idG = request.form['idG'] image_file = request.files['img'] if image_file: image = image_file.read() connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) res = groupebd.add_image(idG, image) if res: return jsonify({"success": "image ajoutée"}) return jsonify({"error": "erreur lors de l'ajout de l'image"}) import io @app.route('/getImageArtiste/<int:id>') def getImageArtiste(id): #get l'image en blob de l'artiste et l'affiche try: connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) image_blob = groupebd.get_image(id) if image_blob is None: return jsonify({"error": "Aucune image trouve"}) else: image = io.BytesIO(image_blob) image.seek(0) return send_file(image, mimetype='image/jpeg') except Exception as e: print(e) return jsonify({"error": "erreur lors de la récupération de l'image"}) @app.route('/getFaq') def get_faq(): connexion_bd = ConnexionBD() faqbd = FaqBD(connexion_bd) res = faqbd.get_faqs_json() if res is None: return jsonify({"error": "Aucune faq trouve"}) else: return res @app.route("/recherche/", methods=["GET", "POST"]) def recherche(): if request.method == "POST": recherche = request.form.get("recherche", "") else: recherche = request.args.get("recherche", "") connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) membre_groupebd = Membre_GroupeBD(connexion_bd) groupes = groupebd.search_groupes(recherche) if recherche else [] artistes = membre_groupebd.search_membres_groupe(recherche) if recherche else [] return render_template("recherche.html", recherche=recherche, groupes=groupes, artistes=artistes) @app.route("/styles_musicaux", methods=["GET", "POST"]) def filtrer_styles(): connexion_bd = ConnexionBD() style_musicalbd = Style_MusicalBD(connexion_bd) styles_musicaux = style_musicalbd.get_all_styles() liste_groupes = [] if request.method == "POST": nomStyle = request.form.get("nomStyle", "") idStyle = style_musicalbd.get_id_style_by_name(nomStyle) if idStyle is not None: groupe_stylebd = Groupe_StyleBD(connexion_bd) liste_groupes = groupe_stylebd.get_groupes_selon_style(idStyle) return render_template("styles_musicaux.html", styles_musicaux=styles_musicaux, liste_groupes=liste_groupes) @app.route("/menu_admin/", methods=["GET", "POST"]) def menu_admin(): return render_template("menu_admin.html") @app.route("/login_admin") def login_admin(): return render_template("login.html") @app.route("/groupes_festival") def groupes_festival(): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) liste_groupes = groupebd.get_all_groupes() if liste_groupes is None: liste_groupes = [] return render_template("groupes_festival.html", liste_groupes=liste_groupes) @app.route("/hebergements_festival") def hebergements_festival(): connexionbd = ConnexionBD() hebergementbd = HebergementBD(connexionbd) liste_hebergements = hebergementbd.get_all_hebergements() if liste_hebergements is None: liste_hebergements = [] return render_template("hebergements_festival.html", liste_hebergements=liste_hebergements) @app.route("/modifier_groupe", methods=["POST"]) def modifier_groupe(): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) id_groupe = request.form["id_groupe"] nom_groupe = request.form["nom_groupe"] description_groupe = request.form["description_groupe"] groupe = groupebd.get_groupe_by_id(id_groupe) groupe.set_nomG(nom_groupe) groupe.set_descriptionG(description_groupe) groupebd.modifier_img(id_groupe, request.files['image_groupe'].read()) succes = groupebd.update_groupe(groupe) if succes: print(f"Le groupe {id_groupe} a été mis à jour.") else: print(f"La mise à jour du groupe {id_groupe} a échoué.") return redirect(url_for("groupes_festival")) @app.route("/modifier_hebergement", methods=["POST"]) def modifier_hebergement(): connexionbd = ConnexionBD() hebergementbd = HebergementBD(connexionbd) id_hebergement = request.form["id_hebergement"] nom_hebergement = request.form["nom_hebergement"] adresse_hebergement = request.form["adresse_hebergement"] limite_places_hebergement = request.form["limite_places"] hebergement = hebergementbd.get_hebergement_by_id(id_hebergement) hebergement.set_nomH(nom_hebergement) hebergement.set_adresseH(adresse_hebergement) hebergement.set_limitePlacesH(limite_places_hebergement) succes = hebergementbd.update_hebergement(hebergement) if succes: print(f"L'hebergement {id_hebergement} a été mis à jour.") else: print(f"La mise à jour de l'hebergement {id_hebergement} a échoué.") return redirect(url_for("hebergements_festival")) @app.route("/supprimer_groupe", methods=["POST"]) def supprimer_groupe(): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) id_groupe = request.form["id_groupe"] groupe = groupebd.get_groupe_by_id(id_groupe) nom_groupe = groupe.get_nomG() groupebd.delete_groupe_by_name(groupe, nom_groupe) return redirect(url_for("groupes_festival")) @app.route("/supprimer_hebergement", methods=["POST"]) def supprimer_hebergement(): connexionbd = ConnexionBD() hebergementbd = HebergementBD(connexionbd) id_hebergement = request.form["id_hebergement"] hebergementbd.delete_hebergement_by_id(id_hebergement) return redirect(url_for("hebergements_festival")) @app.route("/ajouter_groupe", methods=["POST"]) def ajouter_groupe(): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) nom_groupe = request.form["nom_nouveau_groupe"] if request.form["nom_nouveau_groupe"] else None description_groupe = request.form["description_nouveau_groupe"] if request.form["description_nouveau_groupe"] else None groupe = Groupe(None, None, nom_groupe, description_groupe) groupebd.insert_groupe(groupe) idG = groupebd.get_id_groupe_by_name(nom_groupe) image_file = request.files['image_nouveau_groupe'] if image_file: image = image_file.read() connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) res = groupebd.add_image(idG, image) if (res): print("image ajoutée") else: print("erreur lors de l'ajout de l'image") return redirect(url_for("groupes_festival")) @app.route("/ajouter_hebergement", methods=["POST"]) def ajouter_hebergement(): connexionbd = ConnexionBD() hebergementbd = HebergementBD(connexionbd) nom_hebergement = request.form["nom_nouveau_hebergement"] adresse_hebergement = request.form["adresse_hebergement"] limite_places_hebergement = request.form["limite_places"] hebergement = Hebergement(None, nom_hebergement, limite_places_hebergement, adresse_hebergement) hebergementbd.insert_hebergement(hebergement) return redirect(url_for("hebergements_festival")) @app.route("/consulter_groupe/<int:id_groupe>") def consulter_groupe(id_groupe): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) groupe = groupebd.get_groupe_by_id(id_groupe) membres_groupe = groupebd.get_membres_groupe(id_groupe) if not membres_groupe: return render_template("membres_groupe.html", groupe=groupe, membres_groupe=[]) return render_template("membres_groupe.html", groupe=groupe, membres_groupe=membres_groupe) @app.route("/consulter_hebergement/<int:id_hebergement>") def consulter_hebergement(id_hebergement): connexionbd = ConnexionBD() hebergementbd = HebergementBD(connexionbd) hebergement = hebergementbd.get_hebergement_by_id(id_hebergement) groupes_hebergement = hebergementbd.get_groupes_hebergement(id_hebergement) groupes_not_in_hebergement = hebergementbd.get_groupes_not_in_hebergement(id_hebergement) dict_groupes_not_in_hebergement = {} for groupe in groupes_not_in_hebergement: id_hebergement_groupe = groupe.get_idHebergement() nom_hebergement_groupe = hebergementbd.get_hebergement_by_id(id_hebergement_groupe).get_nomH() if id_hebergement_groupe is not None else None dict_groupes_not_in_hebergement[groupe] = nom_hebergement_groupe return render_template("groupes_hebergement.html", hebergement=hebergement, groupes_hebergement=groupes_hebergement, dict_groupes_not_in_hebergement=dict_groupes_not_in_hebergement) @app.route("/modifier_membre", methods=["POST"]) def modifier_membre_groupe(): connexionbd = ConnexionBD() membre_groupebd = Membre_GroupeBD(connexionbd) nom_membre_groupe = request.form["nom_membre"] prenom_membre_groupe = request.form["prenom_membre"] nom_scene_membre_groupe = request.form["nom_scene_membre"] id_membre_groupe = request.form["id_membre"] membre_groupe = membre_groupebd.get_artiste_by_id(id_membre_groupe) membre_groupe.set_nomMG(nom_membre_groupe) membre_groupe.set_prenomMG(prenom_membre_groupe) membre_groupe.set_nomDeSceneMG(nom_scene_membre_groupe) succes = membre_groupebd.update_membre_groupe(membre_groupe) if succes: print(f"Le membre {id_membre_groupe} a été mis à jour.") else: print(f"La mise à jour du membre {id_membre_groupe} a échoué.") return redirect(url_for("consulter_groupe", id_groupe=membre_groupe.get_idGroupe())) @app.route("/supprimer_membre", methods=["POST"]) def supprimer_membre_groupe(): connexionbd = ConnexionBD() membre_groupebd = Membre_GroupeBD(connexionbd) id_membre_groupe = request.form["id_membre"] membre_groupe = membre_groupebd.get_artiste_by_id(id_membre_groupe) nom_scene_membre_groupe = membre_groupe.get_nomDeSceneMG() membre_groupebd.delete_membre_groupe_by_name_scene(membre_groupe, nom_scene_membre_groupe) return redirect(url_for("consulter_groupe", id_groupe=membre_groupe.get_idGroupe())) @app.route("/supprimer_groupe_hebergement", methods=["POST"]) def supprimer_groupe_hebergement(): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) id_hebergement = request.form["id_hebergement"] id_groupe = request.form["id_groupe"] groupe = groupebd.get_groupe_by_id(id_groupe) groupe.set_idHebergement(None) print(groupe.get_idHebergement()) groupebd.update_groupe(groupe) return redirect(url_for("consulter_hebergement", id_hebergement=id_hebergement)) @app.route("/ajouter_membre", methods=["POST"]) def ajouter_membre_groupe(): connexionbd = ConnexionBD() membre_groupebd = Membre_GroupeBD(connexionbd) id_groupe = request.form["id_groupe"] nom_membre_groupe = request.form["nom_nouveau_membre"] if request.form["nom_nouveau_membre"] else None prenom_membre_groupe = request.form["prenom_nouveau_membre"] if request.form["prenom_nouveau_membre"] else None nom_scene_membre_groupe = request.form["nom_scene_nouveau_membre"] if request.form["nom_scene_nouveau_membre"] else None membre_groupe = Membre_Groupe(None, id_groupe, nom_membre_groupe, prenom_membre_groupe, nom_scene_membre_groupe) membre_groupebd.insert_membre_groupe(membre_groupe) return redirect(url_for("consulter_groupe", id_groupe=id_groupe)) @app.route("/ajouter_groupe_hebergement", methods=["POST"]) def ajouter_groupe_hebergement(): connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) id_groupe = request.form["nom_groupe"] id_hebergement = request.form["id_hebergement"] groupe = groupebd.get_groupe_by_id(id_groupe) groupe.set_idHebergement(id_hebergement) groupebd.update_groupe(groupe) return redirect(url_for("consulter_hebergement", id_hebergement=id_hebergement)) @app.route("/evenements_festival") def evenements_festival(): connexionbd = ConnexionBD() evenementbd = EvenementBD(connexionbd) groupebd = GroupeBD(connexionbd) liste_groupes = groupebd.get_all_groupes() liste_evenements = evenementbd.get_all_evenements() liste_evenements_concerts = [] liste_evenements_activites_annexes = [] if not liste_evenements: return render_template("evenements_festival.html", liste_evenements=[], liste_evenements_concerts=[], liste_evenements_activites_annexes=[], liste_lieux=[], liste_groupes=[]) lieubd = LieuBD(connexionbd) liste_lieux = lieubd.get_all_lieux() for evenement in liste_evenements: if evenementbd.verify_id_in_concert(evenement.get_idE()): liste_evenements_concerts.append(evenement) elif evenementbd.verify_id_in_activite_annexe(evenement.get_idE()): liste_evenements_activites_annexes.append(evenement) return render_template("evenements_festival.html", liste_evenements=liste_evenements, liste_evenements_concerts=liste_evenements_concerts, liste_evenements_activites_annexes=liste_evenements_activites_annexes, liste_lieux=liste_lieux, liste_groupes=liste_groupes) @app.route("/modifier_evenement", methods=["POST"]) def modifier_evenement(): connexionbd = ConnexionBD() evenementbd = EvenementBD(connexionbd) id_evenement = request.form["id_evenement"] id_lieu = request.form["lieu_evenement"] if request.form["lieu_evenement"] else None id_groupe = request.form["groupe_evenement"] if request.form["groupe_evenement"] else None nom_evenement = request.form["nom_evenement"] date_debut = request.form["date_debut"] date_fin = request.form["date_fin"] heure_debut = request.form["heure_debut"] heure_fin = request.form["heure_fin"] evenement = evenementbd.get_evenement_by_id(id_evenement) evenement.set_idG(id_groupe) evenement.set_idL(id_lieu) evenement.set_nomE(nom_evenement) evenement.set_dateDebutE(date_debut) evenement.set_dateFinE(date_fin) evenement.set_heureDebutE(heure_debut) evenement.set_heureFinE(heure_fin) succes = evenementbd.update_evenement(evenement) if succes: print(f"L'événement {id_evenement} a été mis à jour.") else: print(f"La mise à jour de l'événement {id_evenement} a échoué.") return redirect(url_for("evenements_festival")) @app.route("/supprimer_evenement", methods=["POST"]) def supprimer_evenement(): connexionbd = ConnexionBD() evenementbd = EvenementBD(connexionbd) concert_bd = ConcertBD(connexionbd) id_evenement = request.form["id_evenement"] evenement = evenementbd.get_evenement_by_id(id_evenement) nom_evenement = evenement.get_nomE() if evenementbd.verify_id_in_concert(id_evenement): concert_bd.delete_concert_by_id(id_evenement) elif evenementbd.verify_id_in_activite_annexe(id_evenement): activite_annexe_bd = Activite_AnnexeBD(connexionbd) activite_annexe_bd.delete_activite_annexe_by_id(id_evenement) evenementbd.delete_evenement_by_name(evenement, nom_evenement) return redirect(url_for("evenements_festival")) @app.route("/ajouter_evenement", methods=["POST"]) def ajouter_evenement(): connexionbd = ConnexionBD() evenementbd = EvenementBD(connexionbd) id_lieu = request.form["lieu_evenement"] if request.form["lieu_evenement"] else None id_groupe = request.form["groupe_evenement"] if request.form["groupe_evenement"] else None nom_evenement = request.form["nom_evenement"] if request.form["nom_evenement"] else None date_debut = request.form["date_debut"] if request.form["date_debut"] else None date_fin = request.form["date_fin"] if request.form["date_fin"] else None heure_debut = request.form["heure_debut"] if request.form["heure_debut"] else None heure_fin = request.form["heure_fin"] if request.form["heure_fin"] else None evenement = Evenement(None, id_groupe, id_lieu, nom_evenement, heure_debut, heure_fin, date_debut, date_fin) id_evenement = evenementbd.insert_evenement(evenement) type_evenement = request.form["type_evenement"] if type_evenement == "concert": temps_montage = request.form["temps_montage"] if request.form["temps_montage"] else None temps_demontage = request.form["temps_demontage"] if request.form["temps_demontage"] else None concert_bd = ConcertBD(connexionbd) concert = Concert(id_evenement, temps_montage, temps_demontage) concert_bd.insert_concert(concert) elif type_evenement == "activite": type_activite = request.form["type_activite"] if request.form["type_activite"] else None ouvert_public = True if "ouvert_public" in request.form else False print(ouvert_public) activite_annexebd = Activite_AnnexeBD(connexionbd) activite_annexe = Activite_Annexe(id_evenement, type_activite, ouvert_public) print(activite_annexe.get_ouvertAuPublic()) activite_annexebd.insert_activite_annexe(activite_annexe) return redirect(url_for("evenements_festival")) @app.route("/billets_festival") def billets_festival(): connexionbd = ConnexionBD() billetbd = BilletBD(connexionbd) liste_billets = billetbd.get_all_billets() if not liste_billets: return render_template("admin_billets.html", liste_billets=[]) return render_template("admin_billets.html", liste_billets=liste_billets) @app.route("/lieux_festival") def lieux_festival(): connexionbd = ConnexionBD() lieubd = LieuBD(connexionbd) liste_lieux = lieubd.get_all_lieux() if not liste_lieux: return render_template("admin_lieux.html", liste_lieux=[]) return render_template("admin_lieux.html", liste_lieux=liste_lieux) @app.route("/types_billet_festival") def types_billet_festival(): connexionbd = ConnexionBD() type_billetbd = Type_BilletBD(connexionbd) liste_types_billet = type_billetbd.get_all_types_billets() if not liste_types_billet: return render_template("admin_types_billet.html", liste_types_billet=[]) return render_template("admin_types_billet.html", liste_types_billet=liste_types_billet) @app.route("/spectateurs_festival") def spectateurs_festival(): connexionbd = ConnexionBD() spectateurbd = SpectateurBD(connexionbd) liste_spectateurs = spectateurbd.get_all_spectateurs() if not liste_spectateurs: return render_template("admin_spectateurs.html", liste_spectateurs=[]) return render_template("admin_spectateurs.html", liste_spectateurs=liste_spectateurs) @app.route("/styles_musicaux_festival") def styles_musicaux_festival(): connexionbd = ConnexionBD() style_musicalbd = Style_MusicalBD(connexionbd) liste_styles_musicaux = style_musicalbd.get_all_styles() if not liste_styles_musicaux: return render_template("admin_styles.html", liste_styles_musicaux=[]) return render_template("admin_styles.html", liste_styles_musicaux=liste_styles_musicaux) @app.route("/instruments_festival") def instruments_festival(): connexionbd = ConnexionBD() instrumentbd = InstrumentBD(connexionbd) liste_instruments = instrumentbd.get_all_instruments() if not liste_instruments: return render_template("admin_instruments.html", liste_instruments=[]) return render_template("admin_instruments.html", liste_instruments=liste_instruments) @app.route("/users_festival") def users_festival(): connexionbd = ConnexionBD() userbd = UserBD(connexionbd) liste_users = userbd.get_all_users() if not liste_users: return render_template("admin_users.html", liste_users=[]) return render_template("admin_users.html", liste_users=liste_users) @app.route("/ajouter_user", methods=["POST"]) def ajouter_user(): connexionbd = ConnexionBD() userbd = UserBD(connexionbd) pseudo_user = request.form["pseudo_user"] email_user = request.form["email_user"] mdp_user = request.form["mdp_user"] statut_user = request.form["statut_user"] user = User(None, pseudo_user, mdp_user, email_user, statut_user) userbd.insert_user_admin(user) return redirect(url_for("users_festival")) @app.route("/supprimer_user", methods=["POST"]) def supprimer_user(): connexionbd = ConnexionBD() userbd = UserBD(connexionbd) id_user = request.form["id_user"] userbd.delete_user_by_id(id_user) return redirect(url_for("users_festival")) @app.route("/modifier_user", methods=["POST"]) def modifier_user(): connexionbd = ConnexionBD() userbd = UserBD(connexionbd) id_user = request.form["id_user"] pseudo_user = request.form["pseudo_user"] email_user = request.form["email_user"] mdp_user = request.form["mdp_user"] user = userbd.get_user_by_id(id_user) user.set_pseudoUser(pseudo_user) user.set_emailUser(email_user) user.set_mdpUser(mdp_user) success = userbd.update_user_admin(user) if success: print(f"L'utilisateur {id_user} a été mis à jour.") else: print(f"La mise à jour de l'utilisateur {id_user} a échoué.") return redirect(url_for("users_festival")) if __name__ == '__main__': app.run(debug=True, port=8080)import { TargetAndTransition, motion } from "framer-motion"; import { useContext, useState } from "react"; import Button from "../components/form/Button"; import { getCookie, setCookie } from "../cookies/CookiesLib.tsx"; import { CartContext } from "../App"; const initialDays = { "20 Jui": false, "21 Jui": false, "22 Jui": false, }; type Props = { id: number; title: string; price: number | string; nbTicket: number; isForfait?: boolean; disabled?: boolean; }; export default function TicketCard({ id, title, price, nbTicket, isForfait, }: Props) { const [isOpen, setIsOpen] = useState(false); const [tickets, setTickets] = useState(nbTicket); const [rotation, setRotation] = useState(0); const [days, setDays] = useState(initialDays); const { cart, setCart } = useContext(CartContext); const [isLoading, setIsLoading] = useState(false); const [isAdded, setIsAdded] = useState(false); type DayKey = "20 Jui" |"21 Jui"|"22 Jui"; const pricesByDay:{[key in DayKey]: number} = { "20 Jui": 60, "21 Jui": 80, "22 Jui": 90, }; const selectedDayCount = () => { return Object.values(days).filter(Boolean).length; } const isDisabled = tickets === 0 || (isForfait && selectedDayCount() !== 2); const handleTicketChange = (newTickets: number, event: React.MouseEvent) => { event.stopPropagation(); setTickets(newTickets); } const addToCartHandler = async ( event: React.MouseEvent<HTMLButtonElement> ) => { event.stopPropagation(); setIsLoading(true); // Longueur actuelle du panier dans les cookies const selectedDaysSortedString = isForfait ? Object.entries(days) .filter(([_, isChosen]) => isChosen) .map(([day, _]) => day) .sort() .join('-') : null; const calculPrixSelonJourSelec = isForfait && selectedDaysSortedString ? selectedDaysSortedString.split('-').reduce((total, dayKey) => { return total + pricesByDay[dayKey as DayKey]; }, 0) : (typeof price === "number" ? price : 0); const uniqueId = isForfait && selectedDaysSortedString ? `${id}-${selectedDaysSortedString}` : `${id}`; const itemForCart = { id, uniqueId, title, price: isForfait ? calculPrixSelonJourSelec : (typeof price === "number" ? price : 0), quantity: tickets, selectedDaysSortedString: isForfait ? selectedDaysSortedString : null, }; // const currentCartLength = (getCookie("cart") || []).length; // condition non valide car si on ajoute un typê billet déjà présent dans le panier, // l'ajout des nouveaux billets ne ferons que changer la valeur de quantité dans le tableau et // donc la longueur du tableau ne changera pas // Initialise la vérification de l'ajout let expectedNewQuantity = itemForCart.quantity; let newCart = [...cart]; const forfaitIndex = newCart.findIndex((billet) => billet.uniqueId === uniqueId); // si l'article existait déjà dans le panie on garde la quantité précédente et on détermine la nouvelle quantité attendue if (forfaitIndex > -1) { // si ce type de billet existe déjà, ajoute à la quantité et calcule la nouvelle quantité attendue expectedNewQuantity += newCart[forfaitIndex].quantity; newCart[forfaitIndex].quantity = expectedNewQuantity; } else { // sinon on l'ajoute au panier newCart.push(itemForCart); } setCart(newCart); setCookie("cart", newCart, { expires: 7, sameSite: "None", secure: true }); setTimeout(() => { // trouver l'article après la mise à jour pour vérifier que la quantité est correcte const newForfaitIndex = newCart.findIndex((billet) => billet.uniqueId === uniqueId); const hasCorrectQuantity = newForfaitIndex > -1 ? newCart[newForfaitIndex].quantity === expectedNewQuantity : false; if (hasCorrectQuantity) { setIsAdded(true); } else { console.error('Erreur : la quantité dans le panier ne correspond pas à la quantité attendue.'); } setIsLoading(false); // Afficher le message 'ARTICLE AJOUTÉ' pendant un certain temps setTimeout(() => { setIsAdded(false); }, 2000); }, 400); }; const displayDay = (day: string) => day.replace("Juillet", "Juillet"); const buttonVariants: { [key: string]: TargetAndTransition } = { tap: { scale: 0.95 }, selected: { scale: 1.1, backgroundColor: "#E45A3B" }, unselected: { scale: 1, backgroundColor: "#FFFFFF" }, }; const contentVariants = { closed: { opacity: 0, height: 0, overflow: "hidden", transition: { duration: 0.2, ease: "easeInOut", when: "afterChildren", }, }, open: { opacity: 1, height: title === "Forfait 2 jours" ? 160 : 150, transition: { duration: 0.2, ease: "easeInOut", when: "beforeChildren", }, }, }; const cardVariants = { hidden: { opacity: 0, y: 50 }, visible: { opacity: 1, y: 0, transition: { type: "spring", stiffness: 120, }, }, }; const maxSelectedDays = 2; const toggleDaySelection = (day: keyof typeof initialDays) => { setDays((prevDays) => { const isSelected = prevDays[day]; const count = selectedDayCount(); if (!isSelected && count >= maxSelectedDays) { return prevDays; } return { ...prevDays, [day]: !prevDays[day] }; }); }; return ( <motion.div className="ticket-card" layout initial="hidden" animate="visible" variants={cardVariants} onClick={() => { setIsOpen(!isOpen); setRotation(rotation === 0 ? 90 : 0); }} > <div className="content"> <div className="left-part"> <h4>{title}</h4> <p>Les tickets ne sont pas remboursables.</p> <p>Dernière entrée à 11H.</p> </div> <div className="right-part"> <p>{price}€</p> <motion.div className="svg-container" animate={{ rotate: rotation }}> <svg xmlns="http://www.w3.org/2000/svg" width="13" height="20" viewBox="0 0 13 20" fill="none" > <path d="M2 18L10 10L2 2" stroke="#4E4E4E" strokeWidth="4" /> </svg> </motion.div> </div> </div> <motion.div className={`sub-menu ${ title === "Forfait 2 jours" ? "forfait-2j" : "" }`} variants={contentVariants} initial="closed" animate={isOpen ? "open" : "closed"} exit="closed" > <div className="top-partsubmenu"> <div className="left-part-sub"> <div className="sub-menu-left-part"> <div className="rect"> <img className="" src="images/billet_pass1j.png" alt="Billet pass 1 jour" /> </div> <div className="container"></div> <div className="article-select"> <svg xmlns="http://www.w3.org/2000/svg" width="22" height="21" viewBox="0 0 22 21" fill="none" > <path d="M22 9.03848H14.6966L19.8599 4.10947L17.6953 2.04109L12.532 6.97007V0H9.46799V6.97007L4.30475 2.04109L2.13807 4.10947L7.30131 9.03848H0V11.9615H7.30131L2.13807 16.8906L4.30475 18.9589L9.46799 14.0299V21H12.532V14.0299L17.6953 18.9589L19.8599 16.8906L14.6966 11.9615H22V9.03848Z" fill="#FFD600" /> </svg> <p>x{tickets} Article(s) sélectionné(s)</p> </div> </div> <div className="ticket-control"> <button className="minusButton" onClick={(event) => handleTicketChange(Math.max(tickets - 1, 0), event) } > - </button> <span>{tickets}</span> <button className="sommeButton" onClick={(event) => handleTicketChange(tickets + 1, event)} > + </button> </div> </div> </div> <div className="delimiter-submenu"></div> <div className="bottom-partsubmenu"> <div className="bottom-part-left"> <div className="day-checkbox-container"> {isForfait && (Object.keys(days) as Array<keyof typeof initialDays>).map( (day) => ( <motion.label key={day} className="day-checkbox" whileTap="tap" > <input type="checkbox" checked={days[day]} onChange={() => toggleDaySelection(day)} style={{ display: "none" }} /> <motion.div className="day-button" variants={buttonVariants} animate={days[day] ? "selected" : "unselected"} > {displayDay(day)} </motion.div> </motion.label> ) )} </div> <p>Sous-total</p> <p>{tickets * (typeof price === "number" ? price : 0)}€</p> </div> <Button text={ isLoading ? "Chargement…" : isAdded ? "ARTICLE AJOUTÉ" : "AJOUT PANIER" } isLoading={isLoading} onClick={(event: React.MouseEvent<HTMLElement>) => addToCartHandler(event as React.MouseEvent<HTMLButtonElement>) } isDisabled={isDisabled} // Passer la prop disabled ici /> </div> </motion.div> </motion.div> ); }import React, { useContext } from 'react'; import { CartContext } from '../../../../App.tsx'; import { setCookie } from '../../../../cookies/CookiesLib.tsx'; import { AnimatePresence, motion } from 'framer-motion'; type Props = { id: number; uniqueId: string; typeBillet: number, title: string, price: number, quantite: number, selectedDays?: Array<string>; }; export const ItemPanier: React.FC<Props> = ({ typeBillet, price, quantite, title, selectedDays, uniqueId}) => { const { cart, setCart } = useContext(CartContext); // Fonction pour enlever un billet du panier const removeFromCart = () => { const updatedCart = cart.filter((item) => item.uniqueId !== uniqueId); setCart(updatedCart); setCookie('cart', updatedCart, { expires: 7, sameSite: 'None', secure: true }); }; // Fonction pour mettre à jour la quantité d'un billet dans le panier const updateQuantity = (newQuantity: number) => { const updatedCart = cart.map((item) => { if (item.uniqueId === uniqueId) { return { ...item, quantity: newQuantity }; } return item; }); setCart(updatedCart); setCookie('cart', updatedCart, { expires: 7, path: '/' }); };// Ajoutez le chemin si nécessaire const itemVariant = { hidden: { opacity: 0, x: -20 }, visible: { opacity: 1, x: 0 }, exit: { opacity: 0, x: 20, transition: {duration: 0.1} } }; const daysList = selectedDays && ( <div className="selected-days-container"> {selectedDays.map(day => ( <span key={day} className="selected-day-badge">{day}</span> ))} </div> ); return ( <motion.div className="item-panier" layout initial="visible" animate="visible" exit="exit" variants={itemVariant} key={uniqueId} > <div className="container-item-panier"> <div className="container-image"> <img src="/images/billet.png" alt="billet" /> </div> <div className="informations"> <div className='partie-texte'> <div className="textes"> <h4>{title}</h4> <h5>{price}€</h5> <div className="jours"> {daysList} </div> </div> </div> <div className="compteur-quantitee"> <span className='ajout-retrait' onClick={() => updateQuantity(Math.max(0, quantite - 1))}>-</span> <input type="number" className='quantite' value={quantite} readOnly /> <span className='ajout-retrait' onClick={() => updateQuantity(quantite + 1)}>+</span> </div> </div> </div> <img className='cross' src="/icones/cross.svg" alt="croix" onClick={removeFromCart} /> </motion.div> ); };import React, { useContext } from 'react'; import { CartContext } from '../../../../App.tsx'; // Assurez-vous que le chemin est correct import { ItemPanier } from './ItemPanier'; import { motion, AnimatePresence } from 'framer-motion'; import Button from '../../../../components/form/Button'; type Props = { isOpen: boolean; setIsOpen: (isOpen: boolean) => void; }; const MenuPanier: React.FC<Props> = ({ isOpen, setIsOpen }) => { const { cart } = useContext(CartContext); // Calculer le sous-total const subtotal = cart.reduce((acc: number, item: { price: number; quantity: number; }) => acc + item.price * item.quantity, 0); const menuVariants = { hidden: { x: '42rem', transition: { duration: 0.5, ease: [1, -0.02, 0, 1] } }, visible: { x: 0, transition: { duration: 0.5, ease: [1, -0.02, 0, 1] } }, }; return ( <motion.div className="side-menu cart" variants={menuVariants} initial="hidden" animate={isOpen ? "visible" : "hidden"} > <svg className="cross" onClick={() => setIsOpen(false)} width="36" height="28" viewBox="0 0 36 28" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect x="6.52539" y="0.321533" width="35.8974" height="3.58974" rx="1.79487" transform="rotate(45 6.52539 0.321533)" fill="#E45A3B"/> <rect x="3.87891" y="25.5957" width="35.8974" height="3.58974" rx="1.79487" transform="rotate(-45 3.87891 25.5957)" fill="#E45A3B"/> </svg> <div className="container"> <h2>Mon panier</h2> <section className='le-panier'> <AnimatePresence> {cart.length > 0 ? ( cart.map((item) => ( <ItemPanier key={item.uniqueId} id={item.id} typeBillet={item.id} title={item.title} price={typeof item.price === 'number' ? item.price : parseInt(item.price, 10)} quantite={item.quantity} selectedDays={item.selectedDaysSortedString ? item.selectedDaysSortedString.split('-') : undefined} uniqueId={item.uniqueId} /> )) ) : ( <p>Panier Vide</p> )} </AnimatePresence> </section> <div className="sous-total"> <h4>Sous total: </h4> <h4>{subtotal.toFixed(2)}€</h4> </div> <Button text="RESERVER"></Button> </div> </motion.div> ); }; export default MenuPanier;
7821dd64c448bc590fc6666f58fc5157
{ "intermediate": 0.38944751024246216, "beginner": 0.4756394028663635, "expert": 0.1349131017923355 }
37,502
how can I make this fill the area below the line? <!DOCTYPE html> <html> <head> <title>L7 DSTAT :3</title> <script src="https://code.highcharts.com/highcharts.js"></script> <link rel="stylesheet" href="css/index.css"> </head> <body> <div id="requestCountGraph" style="width: 100%; height: 400px;"></div> <script> var requestData = []; var lastRequestCount = null; var maxDataPoints = 40; // Modify as needed for max length of the graph // Create the Highcharts graph var chart = Highcharts.chart('requestCountGraph', { chart: { type: 'line', backgroundColor: null, events: { load: requestDataUpdate } }, title: { text: 'L7 DSTAT ~ http://127.0.0.1:5000/hit', style: { color: '#FFFFFF' // Changes the color of chart title to white } }, xAxis: { type: 'datetime', tickPixelInterval: 150, labels: { style: { color: '#FFFFFF' // Changes the color of xAxis labels to white } }, }, yAxis: { title: { text: 'Requests/second', style: { color: '#FFFFFF' } } }, plotOptions: { line: { lineWidth: 2, } }, series: [{ name: 'Requests', data: [], color: '#F9A9FC' }] }); function requestDataUpdate() { setInterval(function() { fetch('http://127.0.0.1:5000/api/dstat') .then(response => response.json()) .then(data => { var currentRequestCount = data.total_requests; if (lastRequestCount !== null) { // Skip first request var diff = currentRequestCount - lastRequestCount; var x = (new Date()).getTime(); // current time // Add the point to the graph // and shift the series if necessary var shift = chart.series[0].data.length >= maxDataPoints; chart.series[0].addPoint([x, diff], true, shift); // No need to use requestData array as Highcharts manages the data } lastRequestCount = currentRequestCount; }); }, 1000); // Update every second } </script> </body> </html>
a52c99b6c105e3f44eda04371c59cdf5
{ "intermediate": 0.3096460700035095, "beginner": 0.4761786460876465, "expert": 0.2141752690076828 }
37,503
Error: /home/runner/work/ubiquitous-bassoon/ubiquitous-bassoon/src/main/java/net/minecraft/server/Village.java:[328,47] method getList in class net.minecraft.server.NBTTagCompound cannot be applied to given types; Error: required: java.lang.String Error: found: java.lang.String,int Error: reason: actual and formal argument lists differ in length Error: /home/runner/work/ubiquitous-bassoon/ubiquitous-bassoon/src/main/java/net/minecraft/server/Village.java:[331,56] cannot find symbol Error: symbol: method getCompound(int) Error: location: variable nbttaglist of type net.minecraft.server.NBTTagList Error: /home/runner/work/ubiquitous-bassoon/ubiquitous-bassoon/src/main/java/net/minecraft/server/Village.java:[337,48] method getList in class net.minecraft.server.NBTTagCompound cannot be applied to given types; Error: required: java.lang.String Error: found: java.lang.String,int Error: reason: actual and formal argument lists differ in length Error: /home/runner/work/ubiquitous-bassoon/ubiquitous-bassoon/src/main/java/net/minecraft/server/Village.java:[340,57] cannot find symbol Error: symbol: method getCompound(int) Error: location: variable nbttaglist1 of type net.minecraft.server.NBTTagList Error: -> [Help 1]
33296934496a01031ef54ff284582044
{ "intermediate": 0.3248935639858246, "beginner": 0.3802356421947479, "expert": 0.2948707938194275 }
37,504
How many 6-digit numbers contain exactly 3 different digits? Write the Python code
17e85ea1038b96d88ee3ddaca0dbe480
{ "intermediate": 0.3400432765483856, "beginner": 0.32099059224128723, "expert": 0.33896613121032715 }
37,505
in mt4 cosa significa questo errore? 2024.01.13 15:11:55.634 2023.12.01 00:00:01 VIBRIX GROUP EA[hgtrade-ea.com] EURUSD,M5: array out of range in 'XPERT.mq4' (171,37)
8cddec0548e51062aa598648deb36de7
{ "intermediate": 0.38350018858909607, "beginner": 0.33664026856422424, "expert": 0.2798595130443573 }
37,506
I stress tested a simple flask app which just increments a number every time you request an endpoint, then annother endpoint to get the total requests. I think I might have to rewrite in annother language which is faster, i had two processes running at 2000 threads each then it started getting huge lag spikes every once in wa while, when i add a third its basicalyl unusable, if you ran an actual app on this. the endpoint was capping out at 2k rps , wehn it should techincally do 3k on 2 instances. is pythons slowness to blame, flask, or something else? this is the server: from flask import Flask, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) # This will act as our “database” to store the hit count hit_count = 0 @app.route('/hit', methods=['GET']) def hit_endpoint(): global hit_count hit_count += 1 # Increment the request count return '200', 200 @app.route('/api/dstat', methods=['GET']) def api_stats(): return jsonify(total_requests=hit_count) if __name__ == '__main__': app.run(port=5000, debug=True)
ca0a15f57dc5727a3d5bb2cce29973c9
{ "intermediate": 0.8266966342926025, "beginner": 0.09438785165548325, "expert": 0.0789155513048172 }
37,507
[ { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S1104", "severity": 1, "message": "Make a a static final constant or non-public and provide accessors if needed.", "source": "sonarlint", "startLineNumber": 12, "startColumn": 16, "endLineNumber": 12, "endColumn": 17 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S1104", "severity": 1, "message": "Make b a static final constant or non-public and provide accessors if needed.", "source": "sonarlint", "startLineNumber": 13, "startColumn": 16, "endLineNumber": 13, "endColumn": 17 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S1104", "severity": 1, "message": "Make c a static final constant or non-public and provide accessors if needed.", "source": "sonarlint", "startLineNumber": 14, "startColumn": 16, "endLineNumber": 14, "endColumn": 17 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S1104", "severity": 1, "message": "Make d a static final constant or non-public and provide accessors if needed.", "source": "sonarlint", "startLineNumber": 15, "startColumn": 16, "endLineNumber": 15, "endColumn": 17 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S1104", "severity": 1, "message": "Make e a static final constant or non-public and provide accessors if needed.", "source": "sonarlint", "startLineNumber": 18, "startColumn": 20, "endLineNumber": 18, "endColumn": 21 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S1845", "severity": 1, "message": "Rename method \"a\" to prevent any misunderstanding/clash with field \"a\". [+1 location]", "source": "sonarlint", "startLineNumber": 48, "startColumn": 17, "endLineNumber": 48, "endColumn": 18 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S2696", "severity": 1, "message": "Make the enclosing method \"static\" or remove this set.", "source": "sonarlint", "startLineNumber": 56, "startColumn": 13, "endLineNumber": 56, "endColumn": 24 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S1845", "severity": 1, "message": "Rename method \"a\" to prevent any misunderstanding/clash with field \"a\". [+1 location]", "source": "sonarlint", "startLineNumber": 87, "startColumn": 17, "endLineNumber": 87, "endColumn": 18 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S1845", "severity": 1, "message": "Rename method \"a\" to prevent any misunderstanding/clash with field \"a\". [+1 location]", "source": "sonarlint", "startLineNumber": 101, "startColumn": 16, "endLineNumber": 101, "endColumn": 17 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S6541", "severity": 1, "message": "A \"Brain Method\" was detected. Refactor it to reduce at least one of the following metrics: LOC from 68 to 64, Complexity from 37 to 14, Nesting Level from 3 to 2, Number of Variables from 12 to 6.", "source": "sonarlint", "startLineNumber": 105, "startColumn": 28, "endLineNumber": 105, "endColumn": 29 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S3776", "severity": 1, "message": "Refactor this method to reduce its Cognitive Complexity from 47 to the 15 allowed. [+35 locations]", "source": "sonarlint", "startLineNumber": 105, "startColumn": 28, "endLineNumber": 105, "endColumn": 29 }, { "resource": "/d:/Загрузки/911/PROJECTS/Java/ubiquitous-bassoon/src/main/java/net/minecraft/server/Packet51MapChunk.java", "code": "java:S1845", "severity": 1, "message": "Rename method \"a\" to prevent any misunderstanding/clash with field \"a\". [+1 location]", "source": "sonarlint", "startLineNumber": 105, "startColumn": 28, "endLineNumber": 105, "endColumn": 29 } ]
28b7129f49e2aec2346708ddf9b372c4
{ "intermediate": 0.30670619010925293, "beginner": 0.39381399750709534, "expert": 0.29947981238365173 }
37,508
#ifndef HP_FILE_H #define HP_FILE_H #include <stddef.h> #include "record.h" #include "bf.h" typedef struct HP_info{ int lastBlockId; int totalRecords; int blockCapacity; } HP_info; extern struct HP_info openFiles[20]; /*The function HP_CreateFile is used to create and appropriately initialize an empty heap file with the given fileName. If the execution is successful, it returns 0; otherwise, it returns -1.*/ int HP_CreateFile(char *fileName); /* The function HP_OpenFile opens the file with the name filename. The variable *file_desc refers to the opening identifier of this file as derived from BF_OpenFile.*/ int HP_OpenFile(char *fileName, int *file_desc); /* The function HP_CloseFile closes the file identified by the descriptor file_desc. If the operation is successful, it returns 0; otherwise, it returns -1.*/ int HP_CloseFile(int file_desc); /* The function HP_InsertEntry is used to insert a record into the heap file. The identifier for the file is file_desc, and the record to be inserted is specified by the record structure. If the operation is successful, it returns 1; otherwise, it returns -1.*/ int HP_InsertEntry(int file_desc, Record record); /* The function HP_GetRecord is designed to retrieve a record from a heap file specified by the file descriptor file_desc. It takes three parameters: blockId, which indicates the block from which to retrieve the record, cursor, which specifies the position of the record within that block, and record, which is a pointer to a Record structure. The retrieved record will be stored in the memory location pointed to by the record parameter.*/ int HP_GetRecord( int file_desc, int blockId, int cursor, Record* record); /* The function HP_UpdateRecord updates or sets a record in a heap file specified by the file descriptor file_desc. It takes four parameters: blockId, which indicates the block where the record will be updated, cursor, which specifies the position of the record within that block, and record, which is the new data that will replace the existing record at the specified location. If the operation is successful, the function returns 1; otherwise, it returns -1.*/ int HP_UpdateRecord(int file_desc, int blockId, int cursor,Record record); /* The function HP_Unpin is designed to release the block identified by blockId in the heap file associated with the descriptor file_desc. If the unpin is successful, it returns 0; otherwise, it returns -1.*/ int HP_Unpin(int file_desc, int blockId); // Prints all entries(records) stored in the heap file. int HP_PrintAllEntries(int file_desc); // Retrieves the current record count in a specified block. int HP_GetRecordCounter(int file_desc, int blockId); // Returns the identifier of the last block in the heap file. int HP_GetIdOfLastBlock(int file_desc); // Retrieves the number of records that can fit in a block of the heap file. int HP_GetMaxRecordsInBlock(int file_desc); // Prints all entries(records) contained in the specified block of the heap file. int HP_PrintBlockEntries(int file_desc, int blockId);
287232597abd52c907e1f0e86ac6e5de
{ "intermediate": 0.3096630871295929, "beginner": 0.5057659149169922, "expert": 0.18457096815109253 }
37,509
#include <merge.h> #include <stdio.h> #include "chunk.h" CHUNK_Iterator CHUNK_CreateIterator(int fileDesc, int blocksInChunk) { CHUNK_Iterator iterator; iterator.file_desc = fileDesc; iterator.current = 1; // Initialize the iterator to point to the first block. iterator.lastBlocksID = HP_GetIdOfLastBlock(fileDesc); // Get the last block ID in the file. iterator.blocksInChunk = blocksInChunk; return iterator; } int CHUNK_GetNext(CHUNK_Iterator *iterator, CHUNK *chunk) { // Calculate the last block ID to consider in this iteration int lastBlockToConsider = iterator->current + iterator->blocksInChunk - 1; // Check if there are more blocks to iterate over if (iterator->current <= iterator->lastBlocksID) { chunk->file_desc = iterator->file_desc; chunk->from_BlockId = iterator->current; // Ensure that to_BlockId does not exceed the last block ID chunk->to_BlockId = (lastBlockToConsider <= iterator->lastBlocksID) ? lastBlockToConsider : iterator->lastBlocksID; // Calculate the number of records and blocks in the chunk chunk->recordsInChunk = 0; for (int blockId = chunk->from_BlockId; blockId <= chunk->to_BlockId; ++blockId) { chunk->recordsInChunk += HP_GetRecordCounter(iterator->file_desc, blockId); } // Calculate blocksInChunk based on from_BlockId and to_BlockId chunk->blocksInChunk = chunk->to_BlockId - chunk->from_BlockId + 1; // Update iterator state for the next iteration iterator->current = chunk->to_BlockId + 1; return 1; // Success } else { // No more blocks to iterate return 0; } } int CHUNK_GetIthRecordInChunk(CHUNK *chunk, int i, Record *record) { // Check if i is a valid index within the recordsInChunk range if (i >= 0 && i < chunk->recordsInChunk) { // Calculate the block and cursor position for the i-th record int blockId = chunk->from_BlockId + (i / HP_GetMaxRecordsInBlock(chunk->file_desc)); int cursor = i % HP_GetMaxRecordsInBlock(chunk->file_desc); // Retrieve the record from the heap file if (HP_GetRecord(chunk->file_desc, blockId, cursor, record) == -1) { // Record retrieval failed HP_Unpin(chunk->file_desc, blockId); return -1; } // Unpin the block after using the record HP_Unpin(chunk->file_desc, blockId); // Record retrieval successful return 0; } else { // Invalid index return -1; } } int CHUNK_UpdateIthRecord(CHUNK *chunk, int i, Record record) { // Check if i is a valid index within the recordsInChunk range if (i >= 0 && i < chunk->recordsInChunk) { // Calculate the block and cursor position for the i-th record int blockId = chunk->from_BlockId + (i / HP_GetMaxRecordsInBlock(chunk->file_desc)); int cursor = i % HP_GetMaxRecordsInBlock(chunk->file_desc); // Update the record in the heap file if (HP_UpdateRecord(chunk->file_desc, blockId, cursor, record) == -1) { // Record update failed HP_Unpin(chunk->file_desc, blockId); return -1; } // Unpin the block after updating the record HP_Unpin(chunk->file_desc, blockId); // Record update successful return 0; } else { // Invalid index return -1; } } void CHUNK_Print(CHUNK chunk) { printf("Printing records in CHUNK:\n"); // Iterate through records in the chunk for (int i = 0; i < chunk.recordsInChunk; ++i) { Record record; // Retrieve the i-th record in the chunk if (CHUNK_GetIthRecordInChunk(&chunk, i, &record) == 0) { // Print the record details using the printRecord function printf("Record %d: ", i + 1); printRecord(record); } else { // Handle record retrieval failure printf("Failed to retrieve record %d in the chunk.\n", i + 1); } } } CHUNK_RecordIterator CHUNK_CreateRecordIterator(CHUNK *chunk) { CHUNK_RecordIterator iterator; // Check if the chunk pointer is NULL if (chunk == NULL) { // Handle the case of a NULL pointer (e.g., log an error, return a default iterator, etc.) // For simplicity, let's set the iterator properties to default values iterator.chunk.file_desc = -1; iterator.chunk.from_BlockId = -1; iterator.chunk.to_BlockId = -1; iterator.chunk.recordsInChunk = 0; iterator.chunk.blocksInChunk = 0; iterator.currentBlockId = -1; iterator.cursor = -1; return iterator; } // Initialize iterator properties iterator.chunk = *chunk; // Copy the CHUNK structure iterator.currentBlockId = chunk->from_BlockId; iterator.cursor = 0; return iterator; } int CHUNK_GetNextRecord(CHUNK_RecordIterator *iterator,Record* record){ }
5307624e3281d272cde8a626054d93f5
{ "intermediate": 0.4696233570575714, "beginner": 0.3612292408943176, "expert": 0.1691473424434662 }
37,510
Rewrite the code by replacing zip with zstd in this code ZSTD Library is zstd-jni
805310bc96fa4cf01dd5f353659dac66
{ "intermediate": 0.593417227268219, "beginner": 0.16625961661338806, "expert": 0.24032314121723175 }
37,511
je n'arrive plus à me connecter car le handleCLick du boutton n'utilise plus props.fromRef, comment rectifiez cela en prenant en compte le hanle click déjà présent : import { motion } from 'framer-motion'; import React, { useState } from 'react' type Prop = { text:string; formRef?:React.RefObject<HTMLFormElement>; isLoading?:boolean; isSmallPading?:boolean; onClick?:(event: React.MouseEvent<HTMLDivElement>) => void; isDisabled?: boolean; className?: string; }; export default function Button(props:Prop) { const handleClick = (event: React.MouseEvent<HTMLDivElement>) => { if (props.onClick) { props.onClick(event); } }; const buttonClasses = `btn ${props.className || ''} ${props.isDisabled ? 'disabled' : ''}`; const[isHovered, setIsHovered] = useState(false); const animRectVariants = { hidden: { scale:0, rotate:45, transition:{ duration: 0.25, ease: [1, -0.02, 0,1] } }, visible:{ scale: 12, rotate:45, transition:{ duration:0.25, ease: [1, 0, 0,1] } } } const spinnerVariants = { hidden:{ opacity:0, y: "-50%", scale:1.3, }, loading:{ opacity:1, rotate: 360, y: "-50%", scale:1, transition:{ rotate:{ repeat: Infinity, repeatType: 'loop', duration: 2, ease: 'linear' }, scale:{ duration: 0.25, ease: [1, 0, 0,1] }, opacity:{ duration: 0.25, ease: [1, 0, 0,1] } } } } const arrowVariants = { hidden:{ opacity:0, x:"-0.75rem", y:"-50%", transition:{ duration: 0.25, ease: [1, 0, 0,1] } }, visible:{ opacity:1, x: "0.75rem", y:"-57%", transition:{ duration: 0.25, ease: [1, 0, 0,1] } }, hiddenFromLoading:{ x:"0.75rem", scale:0, y:"-57%", transition:{ duration: 0.25, ease: [1, 0, 0,1] } } } const bgVariants={ hidden:{ padding:"0.875rem 2.25rem 0.875rem 2.25rem", transition:{ duration: 0.25, ease: [1, 0, 0,1] } }, visible:{ padding:"0.875rem 5rem 0.875rem 2.25rem", transition:{ duration: 0.25, ease: [1, 0, 0,1] } }, } const inputVariants = { hidden:{ color:"#FFFFFF", transition:{ duration: 0.25, ease: [1, 0, 0,1] } }, visible:{ color:"#E45A3B", transition:{ duration: 0.25, ease: [1, 0, 0,1] } } } // const handleClick = () => { // if(props.formRef){ // props.formRef.current?.requestSubmit() // } // } return ( <motion.div className='btn' onClick={!props.isDisabled ? props.onClick : undefined} onMouseEnter={!props.isDisabled ? () => setIsHovered(true) : undefined} onMouseLeave={!props.isDisabled ? () => setIsHovered(false) : undefined} variants={bgVariants} initial="hidden" animate={props.isLoading || isHovered ? "visible" : "hidden"} > <motion.input type="submit" value={props.text} variants={inputVariants} initial="hidden" animate={props.isLoading || isHovered ? "visible":"hidden"} onClick={(e) => e.preventDefault()} /> <motion.img src="/icones/right-arrow.svg" alt="fleche vers la droite" variants={arrowVariants} initial="hidden" animate={props.isLoading ? "hiddenFromLoading" : isHovered ? "visible" : "hidden"} /> <motion.svg variants={spinnerVariants} initial="hidden" animate={props.isLoading ? "loading" : "hidden"} width="43" height="43" viewBox="0 0 43 43" fill="none" xmlns="http://www.w3.org/2000/svg"> <mask id="path-1-inside-1_1177_1978" fill="white"> <path d="M8.22035 16.4431C7.61939 16.2224 6.9487 16.5299 6.77511 17.1461C5.97128 19.9994 6.0288 23.0366 6.95464 25.8709C8.00083 29.0736 10.0948 31.8309 12.8992 33.6984C15.7036 35.5658 19.0551 36.4348 22.4136 36.1652C25.772 35.8955 28.942 34.503 31.4125 32.2121C33.8831 29.9211 35.5104 26.8651 36.0322 23.5365C36.554 20.2079 35.94 16.8005 34.2891 13.8634C32.6382 10.9263 30.0465 8.63052 26.9316 7.34605C24.1751 6.20934 21.1509 5.92321 18.2452 6.50981C17.6176 6.63649 17.2605 7.28212 17.4353 7.898C17.61 8.51387 18.2505 8.86588 18.8797 8.74808C21.2823 8.29828 23.7729 8.55116 26.0478 9.48928C28.6813 10.5752 30.8724 12.5162 32.2682 14.9993C33.6639 17.4825 34.1831 20.3632 33.7419 23.1774C33.3007 25.9916 31.9249 28.5753 29.8362 30.5122C27.7474 32.4491 25.0675 33.6263 22.228 33.8543C19.3886 34.0822 16.5551 33.3476 14.1842 31.7687C11.8132 30.1899 10.0429 27.8588 9.15836 25.151C8.39427 22.8119 8.32972 20.3094 8.95921 17.9475C9.12408 17.3289 8.82131 16.6637 8.22035 16.4431Z"/> </mask> <path d="M8.22035 16.4431C7.61939 16.2224 6.9487 16.5299 6.77511 17.1461C5.97128 19.9994 6.0288 23.0366 6.95464 25.8709C8.00083 29.0736 10.0948 31.8309 12.8992 33.6984C15.7036 35.5658 19.0551 36.4348 22.4136 36.1652C25.772 35.8955 28.942 34.503 31.4125 32.2121C33.8831 29.9211 35.5104 26.8651 36.0322 23.5365C36.554 20.2079 35.94 16.8005 34.2891 13.8634C32.6382 10.9263 30.0465 8.63052 26.9316 7.34605C24.1751 6.20934 21.1509 5.92321 18.2452 6.50981C17.6176 6.63649 17.2605 7.28212 17.4353 7.898C17.61 8.51387 18.2505 8.86588 18.8797 8.74808C21.2823 8.29828 23.7729 8.55116 26.0478 9.48928C28.6813 10.5752 30.8724 12.5162 32.2682 14.9993C33.6639 17.4825 34.1831 20.3632 33.7419 23.1774C33.3007 25.9916 31.9249 28.5753 29.8362 30.5122C27.7474 32.4491 25.0675 33.6263 22.228 33.8543C19.3886 34.0822 16.5551 33.3476 14.1842 31.7687C11.8132 30.1899 10.0429 27.8588 9.15836 25.151C8.39427 22.8119 8.32972 20.3094 8.95921 17.9475C9.12408 17.3289 8.82131 16.6637 8.22035 16.4431Z" fill="#D9D9D9" stroke="#D9D9D9" stroke-width="8" mask="url(#path-1-inside-1_1177_1978)"/> </motion.svg> <motion.div className='anim-rectangle' variants={animRectVariants} initial="hidden" animate={props.isLoading || isHovered ? "visible" : "hidden"} /> </motion.div> ) } ? import { AnimatePresence, motion } from 'framer-motion' import React from 'react' import { Link } from 'react-router-dom' import {useState, useEffect, useRef} from 'react'; import TextField from '../../form/TextField'; import Button from '../../form/Button'; import axios from 'axios'; import { setUserCookie, getUserCookie, isConnected, removeUserCookie } from '../../../cookies/CookiesLib'; import ChampCode from '../../form/ChampCode'; type Props = { isOpen: boolean; setIsOpen: (isOpen : boolean) => void; } type menuConnexionTabs = "connexion" | "inscription" | "connecte" | "aideConnexion" | "modifierInfos" | "mesBillets" | "codeVerification" | "changerMdp"; type typeErreur = "email" | "password" | "pseudo" | "oldPassword" | "verifPassword" | "codeVerification"; export default function MenuConnexion(props: Props) { const[currentMenu, setCurrentMenu] = useState<menuConnexionTabs>(isConnected() ? "connecte" : "connexion"); const formConnexionRef = useRef<HTMLFormElement>(null); const formInscriptionRef = useRef<HTMLFormElement>(null); const formResetMdpRef = useRef<HTMLFormElement>(null); const formModifierInfosRef = useRef<HTMLFormElement>(null); const formCodeVerificationRef = useRef<HTMLFormElement>(null); const formModifMdpRef = useRef<HTMLFormElement>(null); const[isLoading, setIsLoading] = useState(false); useEffect(() => { setCurrentMenu(isConnected() ? "connecte" : "connexion"); }, [props.isOpen === true]) const[email, setEmail] = useState(""); const[password, setPassword] = useState(""); const[verifierPassword, setVerifierPassword] = useState(""); const[pseudo, setPseudo] = useState(""); const[oldPassword, setOldPassword] = useState(""); const[codeVerification, setCodeVerification] = useState(""); const[errorEmail, setErrorEmail] = useState(""); const[errorPassword, setErrorPassword] = useState(""); const[errorPseudo, setErrorPseudo] = useState(""); const[errorOldPassword, setErrorOldPassword] = useState(""); const[errorVerifPassword, setErrorVerifPassword] = useState(""); const[errorCodeVerification, setErrorCodeVerification] = useState(""); const[isWrong, setIsWrong] = useState(false); useEffect(() => { if (codeVerification.length === 6){ formCodeVerificationRef.current?.requestSubmit(); } }, [codeVerification]) const goTo = (menu : menuConnexionTabs, e? : React.MouseEvent<HTMLAnchorElement>) => { if(e) {e.preventDefault();} //reset tous les champs setEmail(""); setPassword(""); setPseudo(""); setOldPassword(""); setVerifierPassword(""); clearErrors(); setIsLoading(false); if (menu === "modifierInfos"){ if (isConnected() === false){ goTo("connexion"); return; } const user = getUserCookie(); setEmail(user.emailUser); setPseudo(user.pseudoUser); } setCurrentMenu(menu); } const clearErrors = () => { setErrorEmail(""); setErrorPassword(""); setErrorPseudo(""); setErrorOldPassword(""); setErrorVerifPassword(""); } const setErreur = (type : typeErreur, message : string) => { setIsWrong(true); setIsLoading(false); switch (type){ case "email": setErrorEmail(message); break; case "password": setErrorPassword(message); break; case "pseudo": setErrorPseudo(message); break; case "oldPassword": setErrorOldPassword(message); break; case "verifPassword": setErrorVerifPassword(message); break; case "codeVerification": setErrorCodeVerification(message); break; } setTimeout(() => { setIsWrong(false); }, 500); } const checkEmail = (email : string) => { const regexEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const isEmail = regexEmail.test(email); if (!isEmail){ setErreur("email", "L'email n'est pas valide"); return false; } return true; } // regarde si le pseudo fait +4 caractères const checkPseudo = (pseudo : string) => { if (pseudo.length < 4){ setErreur("pseudo", "Le pseudo doit faire au moins 4 caractères"); return false; } return true; } // regarde si le mot de passe fait +4 caractères const checkPassword = (password : string) => { if (password.length < 4){ setErreur("password", "Le mot de passe doit faire au moins 4 caractères"); return false; } return true; } const CheckOldPassword = (oldPassword : string) => { if (oldPassword.length < 4){ setErreur("oldPassword", "Le mot de passe doit faire au moins 4 caractères"); return false; } return true; } const checkPasswordMatching = (password : string, verifierPassword : string) => { if (password !== verifierPassword){ setErreur("verifPassword", "Les mots de passe ne correspondent pas"); return false; } return true; } const handleConnexion = (e : React.FormEvent<HTMLFormElement>) => { clearErrors(); e.preventDefault(); setIsLoading(true); // verifie si les champs sont remplis // verifie si l'email est bien un email (regex) if (!checkEmail(email) || !checkPassword(password)){ return; } // fais une requete post avec axios à localhost:8080/connecter const data = { email, password } axios.post("http://localhost:8080/connecter", data).then((res) => { const data = res.data; if (data.error){ setErreur("email", data.error); setErreur("password", data.error); return; } const idUser = data.idUser; const pseudoUser = data.pseudoUser; const emailUser = data.emailUser; setUserCookie({idUser, pseudoUser, emailUser}); goTo("connecte"); setIsLoading(false); }) } const handleDeconnexion = (e : React.MouseEvent<HTMLAnchorElement>) => { e.preventDefault(); clearErrors(); removeUserCookie(); setCurrentMenu("connexion"); } const handleInscription = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); clearErrors(); setIsLoading(true); if (!checkEmail(email) || !checkPassword(password) || !checkPseudo(pseudo)){ return; } const data = { pseudo, email, password } axios.post("http://localhost:8080/inscription", data).then((res) => { const data = res.data; if (data.error){ setErreur("email", data.error); return; } const idUser = data.idUser; const pseudoUser = data.pseudoUser; const emailUser = data.emailUser; setUserCookie({idUser, pseudoUser, emailUser}); goTo("connecte"); setIsLoading(false); }) } const handleResetMdp = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); clearErrors(); setIsLoading(true); if (!checkEmail(email)){ return; } const data = { email } axios.post("http://localhost:8080/envoyerCodeVerification", data).then((res) => { const dataRes = res.data; if (res.data.error){ setErreur("email", dataRes.error); return; } if (res.data.success){ goTo("codeVerification") setCodeVerification(""); setEmail(data.email); } setIsLoading(false); }) } const handleEnvoyerCode = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); clearErrors(); setIsLoading(true); if (codeVerification.length !== 6){ setErreur("codeVerification", "Le code doit faire 6 caractères"); return; } const data = { email, code:codeVerification } axios.post("http://localhost:8080/testerCodeVerification", data).then((res) =>{ const dataRes = res.data; if(dataRes.error){ setErreur("codeVerification", dataRes.error); setCodeVerification(""); return; } if(res.data.success){ console.log("code correct"); goTo("changerMdp") setEmail(data.email); setCodeVerification(data.code); } setIsLoading(false); }) }; const handleModifierInfos = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); clearErrors(); setIsLoading(true); if (isConnected() === false){ goTo("connexion"); return; } const currentID = getUserCookie().idUser; if (!checkEmail(email) || !checkPassword(password) || !checkPseudo(pseudo) || !CheckOldPassword(oldPassword)){ return; } const data = { id:currentID, pseudo, email, password, oldPassword } axios.post("http://localhost:8080/modifierProfil", data).then((res) => { const data = res.data; if (data.error){ setErreur("oldPassword", data.error); return; } const idUser = data.idUser; const pseudoUser = data.pseudoUser; const emailUser = data.emailUser; setUserCookie({idUser, pseudoUser, emailUser}); goTo("connecte"); setIsLoading(false); }) } const handleModifierMdp = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); clearErrors(); setIsLoading(true); if (!checkPassword(password) || !checkPasswordMatching(password, verifierPassword)){ return; } const data = { email, password, code: codeVerification } axios.post("http://localhost:8080/modifierMdp", data).then((res) => { const dataRes = res.data; if (dataRes.error){ alert(dataRes.error); return; } if (dataRes.success){ removeUserCookie(); goTo("connexion"); } setIsLoading(false); }) } const menuVariants = { hidden:{ x: "42rem", transition:{ duration: 0.5, ease: [1, -0.02, 0,1] } }, visible:{ x: 0, transition:{ duration: 0.5, ease: [1, -0.02, 0,1] } } } const menuSwitchVariants = { exit:{ // part à gauche et disparait x: "-100vw", transition:{ duration: 0.5, ease: [1, -0.02, 0,1] } }, appearing:{ // vient de droite et apparait x: "100vw", transition:{ duration: 0.5, ease: [1, -0.02, 0,1] } }, default:{ // reste au centre x: 0, transition:{ duration: 0.5, ease: [1, -0.02, 0,1] } }, wrong:{ // fais remuer le menu de gauche à droite avant qu'il aille au centre x: [0, -20, 20, -20, 20, 0], transition:{ duration: 0.4, ease: "linear" } } } return ( <motion.div className='side-menu connexion' variants={menuVariants} initial="hidden" animate={props.isOpen ? "visible" : "hidden"}> <div className="cross" onClick={() => {props.setIsOpen(false); }}> <svg width="36" height="28" viewBox="0 0 36 28" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect x="6.52539" y="0.321533" width="35.8974" height="3.58974" rx="1.79487" transform="rotate(45 6.52539 0.321533)" fill="#E45A3B"/> <rect x="3.87891" y="25.5957" width="35.8974" height="3.58974" rx="1.79487" transform="rotate(-45 3.87891 25.5957)" fill="#E45A3B"/> </svg> </div> <AnimatePresence> {currentMenu === "connexion" ? ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Me connecter</h2> <form onSubmit={handleConnexion} ref={formConnexionRef}> <TextField errorText={errorEmail} text="e-mail" textVar={email} setTextVar={setEmail}/> <TextField errorText={errorPassword} text="mot de passe" textVar={password} setTextVar={setPassword} isPassword/> <Button isLoading={isLoading} text="CONNEXION" formRef={formConnexionRef}/> </form> <div className="other"> <a href="" onClick={(e) => goTo("aideConnexion",e)}>Je n'arrive pas à me connecter</a> <a href="" onClick={(e) => goTo("inscription",e)}>Créer un compte</a> </div> </motion.div> ): currentMenu === "connecte" ?( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate="default" exit="exit" key={currentMenu} > <h2>Bonjour {getUserCookie().pseudoUser}</h2> { // todo billets achetés } <div className="other"> <a href="" onClick={(e) => goTo("modifierInfos",e)}>Modifier mes informations</a> <a href="" onClick={handleDeconnexion} className='deconnexion'>Déconnexion</a> </div> </motion.div> ) : currentMenu === "inscription" ? ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Créer un compte</h2> <form onSubmit={handleInscription} ref={formInscriptionRef} > <TextField errorText={errorPseudo} text="pseudo" textVar={pseudo} setTextVar={setPseudo}/> <TextField errorText={errorEmail} text="e-mail" textVar={email} setTextVar={setEmail}/> <TextField errorText={errorPassword} text="mot de passe" textVar={password} setTextVar={setPassword} isPassword/> <Button isLoading={isLoading} text="M'INSCRIRE" formRef={formInscriptionRef}/> </form> <div className="other"> <a href="" onClick={(e) => goTo("aideConnexion",e)}>Je n'arrive pas à me connecter</a> <a href="" onClick={(e) => goTo("connexion",e)}>J'ai déjà un compte</a> </div> </motion.div> ) : currentMenu === "aideConnexion" ? ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Réinitialiser mon mot de passe</h2> <form onSubmit={handleResetMdp} ref={formResetMdpRef} > <TextField errorText={errorEmail} text="e-mail" textVar={email} setTextVar={setEmail}/> <Button isLoading={isLoading} text="REINITIALISER" formRef={formResetMdpRef}/> </form> <div className="other"> <a href="" onClick={(e) => goTo("inscription",e)}>Créer un compte</a> <a href="" onClick={(e) => goTo("connexion",e)}>J'ai déjà un compte</a> </div> </motion.div> ) : currentMenu === "modifierInfos" ? ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Modifier mes informations</h2> <form onSubmit={handleModifierInfos} ref={formModifierInfosRef} > <TextField errorText={errorPseudo} text="pseudo" textVar={pseudo} setTextVar={setPseudo}/> <TextField errorText={errorEmail} text="e-mail" textVar={email} setTextVar={setEmail}/> <TextField errorText={errorPassword} text="mot de passe" textVar={password} setTextVar={setPassword} isPassword/> <TextField errorText={errorOldPassword} text="ancien mot de passe" textVar={oldPassword} setTextVar={setOldPassword} isPassword/> <Button isLoading={isLoading} text="MODIFIER" formRef={formModifierInfosRef}/> </form> <div className="other"> <a href="" onClick={(e) => goTo("connecte",e)}>Retour</a> </div> </motion.div> ) : currentMenu === "mesBillets" ? ( <></> ) : currentMenu === "codeVerification" ? ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Entrez le code reçu par e-mail</h2> <form onSubmit={handleEnvoyerCode} ref={formCodeVerificationRef} > <ChampCode errorText={errorCodeVerification} codeVar={codeVerification} setCodeVar={setCodeVerification} nbChar={6}/> <Button isLoading={isLoading} text="VALIDER" formRef={formCodeVerificationRef}/> </form> <div className="other"> <a href="" onClick={(e) => goTo("connexion",e)}>Retour</a> </div> </motion.div> ) : currentMenu === "changerMdp" && ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Choisissez un nouveau mot de passe</h2> <form onSubmit={handleModifierMdp} ref={formModifMdpRef} > <TextField errorText={errorPassword} isPassword text="Mot de passe" textVar={password} setTextVar={setPassword}/> <TextField errorText={errorVerifPassword} isPassword text="Vérifiez votre mot de passe" textVar={verifierPassword} setTextVar={setVerifierPassword}/> <Button isLoading={isLoading} text="VALIDER" formRef={formModifMdpRef}/> </form> </motion.div> ) } </AnimatePresence> </motion.div> ) }
66607a56e3d92d03685c4b7bdb6567fc
{ "intermediate": 0.3691194951534271, "beginner": 0.4275217652320862, "expert": 0.20335868000984192 }
37,512
Change zip to zstd-jni
bbc14c99b435054a30e74127147f2468
{ "intermediate": 0.3202398419380188, "beginner": 0.2900800108909607, "expert": 0.3896802067756653 }
37,513
Assume given data is in Google sheets column c, write me single formula to show duplicate month name which appear more than once 4-Feb-1999 6-Mar-1999 5-Apr-1999 5-May-1999 4-Jul-1999 2-Sep-1999 2-Oct-1999 31-Dec-1999 20-Feb-1999 22-Mar-1999 21-Apr-1999 21-May-1999 20-Jul-1999 18-Sep-1999 18-Oct-1999 16-Jan-2000 In this example feb appeared more than once so write me formula that show duplicate month name along with date
94fc4c97557ba3fc1ffae33352bf3ae9
{ "intermediate": 0.41245853900909424, "beginner": 0.19659948348999023, "expert": 0.3909420073032379 }
37,514
I would like to use jackson-core in a a java project. How do I manually use this package without using any build tool like maven or gradle?
9381b3cc136e26fe9e26ccb2ec15071e
{ "intermediate": 0.6313570737838745, "beginner": 0.16106922924518585, "expert": 0.20757371187210083 }
37,515
La requête a échoué : (mysql.connector.errors.DatabaseError) 1205 (HY000): Lock wait timeout exceeded; try restarting transaction [SQL: INSERT INTO USER (pseudoUser, emailUser, mdpUser, statutUser) VALUES (%(pseudo)s, %(email)s, %(password)s, 'user')] [parameters: {'pseudo': 'tsug', 'email': 'alexandre.raviart1@gmail.com', 'password': '/Saturne72'}] (Background on this error at: https://sqlalche.me/e/20/4xp6) 127.0.0.1 - - [13/Jan/2024 16:55:26] "POST /inscription HTTP/1.1" 200 -@app.route('/inscription', methods=['POST']) def inscription(): connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) data = request.get_json() print(data) pseudo = data["pseudo"] email = data["email"] password = data["password"] if userbd.exist_user(email, password): return jsonify({"error": "Utilisateur déjà existant"}) else: res = userbd.add_user(pseudo, email, password) if res: user = userbd.get_user_by_email(email) if user is not None: return userbd.user_to_json(user) else: return jsonify({"error": "Utilisateur ajouté mais non retrouvé"}) # Nouvelle gestion d’erreur elif res == "emailErr": return jsonify({"error": "Email déjà existant"}) else: return jsonify({"error": "Erreur lors de l’ajout de l’utilisateur"}) import { AnimatePresence, motion } from 'framer-motion' import React from 'react' import { Link } from 'react-router-dom' import {useState, useEffect, useRef} from 'react'; import TextField from '../../form/TextField'; import Button from '../../form/Button'; import axios from 'axios'; import { setUserCookie, getUserCookie, isConnected, removeUserCookie } from '../../../cookies/CookiesLib'; import ChampCode from '../../form/ChampCode'; type Props = { isOpen: boolean; setIsOpen: (isOpen : boolean) => void; } type menuConnexionTabs = "connexion" | "inscription" | "connecte" | "aideConnexion" | "modifierInfos" | "mesBillets" | "codeVerification" | "changerMdp"; type typeErreur = "email" | "password" | "pseudo" | "oldPassword" | "verifPassword" | "codeVerification"; export default function MenuConnexion(props: Props) { const[currentMenu, setCurrentMenu] = useState<menuConnexionTabs>(isConnected() ? "connecte" : "connexion"); const formConnexionRef = useRef<HTMLFormElement>(null); const formInscriptionRef = useRef<HTMLFormElement>(null); const formResetMdpRef = useRef<HTMLFormElement>(null); const formModifierInfosRef = useRef<HTMLFormElement>(null); const formCodeVerificationRef = useRef<HTMLFormElement>(null); const formModifMdpRef = useRef<HTMLFormElement>(null); const[isLoading, setIsLoading] = useState(false); useEffect(() => { setCurrentMenu(isConnected() ? "connecte" : "connexion"); }, [props.isOpen === true]) const[email, setEmail] = useState(""); const[password, setPassword] = useState(""); const[verifierPassword, setVerifierPassword] = useState(""); const[pseudo, setPseudo] = useState(""); const[oldPassword, setOldPassword] = useState(""); const[codeVerification, setCodeVerification] = useState(""); const[errorEmail, setErrorEmail] = useState(""); const[errorPassword, setErrorPassword] = useState(""); const[errorPseudo, setErrorPseudo] = useState(""); const[errorOldPassword, setErrorOldPassword] = useState(""); const[errorVerifPassword, setErrorVerifPassword] = useState(""); const[errorCodeVerification, setErrorCodeVerification] = useState(""); const[isWrong, setIsWrong] = useState(false); useEffect(() => { if (codeVerification.length === 6){ formCodeVerificationRef.current?.requestSubmit(); } }, [codeVerification]) const goTo = (menu : menuConnexionTabs, e? : React.MouseEvent<HTMLAnchorElement>) => { if(e) {e.preventDefault();} //reset tous les champs setEmail(""); setPassword(""); setPseudo(""); setOldPassword(""); setVerifierPassword(""); clearErrors(); setIsLoading(false); if (menu === "modifierInfos"){ if (isConnected() === false){ goTo("connexion"); return; } const user = getUserCookie(); setEmail(user.emailUser); setPseudo(user.pseudoUser); } setCurrentMenu(menu); } const clearErrors = () => { setErrorEmail(""); setErrorPassword(""); setErrorPseudo(""); setErrorOldPassword(""); setErrorVerifPassword(""); } const setErreur = (type : typeErreur, message : string) => { setIsWrong(true); setIsLoading(false); switch (type){ case "email": setErrorEmail(message); break; case "password": setErrorPassword(message); break; case "pseudo": setErrorPseudo(message); break; case "oldPassword": setErrorOldPassword(message); break; case "verifPassword": setErrorVerifPassword(message); break; case "codeVerification": setErrorCodeVerification(message); break; } setTimeout(() => { setIsWrong(false); }, 500); } const checkEmail = (email : string) => { const regexEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const isEmail = regexEmail.test(email); if (!isEmail){ setErreur("email", "L'email n'est pas valide"); return false; } return true; } // regarde si le pseudo fait +4 caractères const checkPseudo = (pseudo : string) => { if (pseudo.length < 4){ setErreur("pseudo", "Le pseudo doit faire au moins 4 caractères"); return false; } return true; } // regarde si le mot de passe fait +4 caractères const checkPassword = (password : string) => { if (password.length < 4){ setErreur("password", "Le mot de passe doit faire au moins 4 caractères"); return false; } return true; } const CheckOldPassword = (oldPassword : string) => { if (oldPassword.length < 4){ setErreur("oldPassword", "Le mot de passe doit faire au moins 4 caractères"); return false; } return true; } const checkPasswordMatching = (password : string, verifierPassword : string) => { if (password !== verifierPassword){ setErreur("verifPassword", "Les mots de passe ne correspondent pas"); return false; } return true; } const handleConnexion = (e : React.FormEvent<HTMLFormElement>) => { clearErrors(); e.preventDefault(); setIsLoading(true); // verifie si les champs sont remplis // verifie si l'email est bien un email (regex) if (!checkEmail(email) || !checkPassword(password)){ return; } // fais une requete post avec axios à localhost:8080/connecter const data = { email, password, statUser: "user" } axios.post("http://localhost:8080/connecter", data).then((res) => { const data = res.data; if (data.error){ setErreur("email", data.error); setErreur("password", data.error); return; } const idUser = data.idUser; const pseudoUser = data.pseudoUser; const emailUser = data.emailUser; setUserCookie({idUser, pseudoUser, emailUser}); goTo("connecte"); setIsLoading(false); }) } const handleDeconnexion = (e : React.MouseEvent<HTMLAnchorElement>) => { e.preventDefault(); clearErrors(); removeUserCookie(); setCurrentMenu("connexion"); } const handleInscription = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); clearErrors(); setIsLoading(true); if (!checkEmail(email) || !checkPassword(password) || !checkPseudo(pseudo)){ return; } const data = { pseudo, email, password } axios.post("http://localhost:8080/inscription", data).then((res) => { const data = res.data; if (data.error){ setErreur("email", data.error); return; } const idUser = data.idUser; const pseudoUser = data.pseudoUser; const emailUser = data.emailUser; setUserCookie({idUser, pseudoUser, emailUser}); goTo("connecte"); setIsLoading(false); }) } const handleResetMdp = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); clearErrors(); setIsLoading(true); if (!checkEmail(email)){ return; } const data = { email } axios.post("http://localhost:8080/envoyerCodeVerification", data).then((res) => { const dataRes = res.data; if (res.data.error){ setErreur("email", dataRes.error); return; } if (res.data.success){ goTo("codeVerification") setCodeVerification(""); setEmail(data.email); } setIsLoading(false); }) } const handleEnvoyerCode = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); clearErrors(); setIsLoading(true); if (codeVerification.length !== 6){ setErreur("codeVerification", "Le code doit faire 6 caractères"); return; } const data = { email, code:codeVerification } axios.post("http://localhost:8080/testerCodeVerification", data).then((res) =>{ const dataRes = res.data; if(dataRes.error){ setErreur("codeVerification", dataRes.error); setCodeVerification(""); return; } if(res.data.success){ console.log("code correct"); goTo("changerMdp") setEmail(data.email); setCodeVerification(data.code); } setIsLoading(false); }) }; const handleModifierInfos = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); clearErrors(); setIsLoading(true); if (isConnected() === false){ goTo("connexion"); return; } const currentID = getUserCookie().idUser; if (!checkEmail(email) || !checkPassword(password) || !checkPseudo(pseudo) || !CheckOldPassword(oldPassword)){ return; } const data = { id:currentID, pseudo, email, password, oldPassword } axios.post("http://localhost:8080/modifierProfil", data).then((res) => { const data = res.data; if (data.error){ setErreur("oldPassword", data.error); return; } const idUser = data.idUser; const pseudoUser = data.pseudoUser; const emailUser = data.emailUser; setUserCookie({idUser, pseudoUser, emailUser}); goTo("connecte"); setIsLoading(false); }) } const handleModifierMdp = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); clearErrors(); setIsLoading(true); if (!checkPassword(password) || !checkPasswordMatching(password, verifierPassword)){ return; } const data = { email, password, code: codeVerification } axios.post("http://localhost:8080/modifierMdp", data).then((res) => { const dataRes = res.data; if (dataRes.error){ alert(dataRes.error); return; } if (dataRes.success){ removeUserCookie(); goTo("connexion"); } setIsLoading(false); }) } const menuVariants = { hidden:{ x: "42rem", transition:{ duration: 0.5, ease: [1, -0.02, 0,1] } }, visible:{ x: 0, transition:{ duration: 0.5, ease: [1, -0.02, 0,1] } } } const menuSwitchVariants = { exit:{ // part à gauche et disparait x: "-100vw", transition:{ duration: 0.5, ease: [1, -0.02, 0,1] } }, appearing:{ // vient de droite et apparait x: "100vw", transition:{ duration: 0.5, ease: [1, -0.02, 0,1] } }, default:{ // reste au centre x: 0, transition:{ duration: 0.5, ease: [1, -0.02, 0,1] } }, wrong:{ // fais remuer le menu de gauche à droite avant qu'il aille au centre x: [0, -20, 20, -20, 20, 0], transition:{ duration: 0.4, ease: "linear" } } } return ( <motion.div className='side-menu connexion' variants={menuVariants} initial="hidden" animate={props.isOpen ? "visible" : "hidden"}> <div className="cross" onClick={() => {props.setIsOpen(false); }}> <svg width="36" height="28" viewBox="0 0 36 28" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect x="6.52539" y="0.321533" width="35.8974" height="3.58974" rx="1.79487" transform="rotate(45 6.52539 0.321533)" fill="#E45A3B"/> <rect x="3.87891" y="25.5957" width="35.8974" height="3.58974" rx="1.79487" transform="rotate(-45 3.87891 25.5957)" fill="#E45A3B"/> </svg> </div> <AnimatePresence> {currentMenu === "connexion" ? ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Me connecter</h2> <form onSubmit={handleConnexion} ref={formConnexionRef}> <TextField errorText={errorEmail} text="e-mail" textVar={email} setTextVar={setEmail}/> <TextField errorText={errorPassword} text="mot de passe" textVar={password} setTextVar={setPassword} isPassword/> <Button isLoading={isLoading} text="CONNEXION" formRef={formConnexionRef}/> </form> <div className="other"> <a href="" onClick={(e) => goTo("aideConnexion",e)}>Je n'arrive pas à me connecter</a> <a href="" onClick={(e) => goTo("inscription",e)}>Créer un compte</a> </div> </motion.div> ): currentMenu === "connecte" ?( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate="default" exit="exit" key={currentMenu} > <h2>Bonjour {getUserCookie().pseudoUser}</h2> { // todo billets achetés } <div className="other"> <a href="" onClick={(e) => goTo("modifierInfos",e)}>Modifier mes informations</a> <a href="" onClick={handleDeconnexion} className='deconnexion'>Déconnexion</a> </div> </motion.div> ) : currentMenu === "inscription" ? ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Créer un compte</h2> <form onSubmit={handleInscription} ref={formInscriptionRef} > <TextField errorText={errorPseudo} text="pseudo" textVar={pseudo} setTextVar={setPseudo}/> <TextField errorText={errorEmail} text="e-mail" textVar={email} setTextVar={setEmail}/> <TextField errorText={errorPassword} text="mot de passe" textVar={password} setTextVar={setPassword} isPassword/> <Button isLoading={isLoading} text="M'INSCRIRE" formRef={formInscriptionRef}/> </form> <div className="other"> <a href="" onClick={(e) => goTo("aideConnexion",e)}>Je n'arrive pas à me connecter</a> <a href="" onClick={(e) => goTo("connexion",e)}>J'ai déjà un compte</a> </div> </motion.div> ) : currentMenu === "aideConnexion" ? ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Réinitialiser mon mot de passe</h2> <form onSubmit={handleResetMdp} ref={formResetMdpRef} > <TextField errorText={errorEmail} text="e-mail" textVar={email} setTextVar={setEmail}/> <Button isLoading={isLoading} text="REINITIALISER" formRef={formResetMdpRef}/> </form> <div className="other"> <a href="" onClick={(e) => goTo("inscription",e)}>Créer un compte</a> <a href="" onClick={(e) => goTo("connexion",e)}>J'ai déjà un compte</a> </div> </motion.div> ) : currentMenu === "modifierInfos" ? ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Modifier mes informations</h2> <form onSubmit={handleModifierInfos} ref={formModifierInfosRef} > <TextField errorText={errorPseudo} text="pseudo" textVar={pseudo} setTextVar={setPseudo}/> <TextField errorText={errorEmail} text="e-mail" textVar={email} setTextVar={setEmail}/> <TextField errorText={errorPassword} text="mot de passe" textVar={password} setTextVar={setPassword} isPassword/> <TextField errorText={errorOldPassword} text="ancien mot de passe" textVar={oldPassword} setTextVar={setOldPassword} isPassword/> <Button isLoading={isLoading} text="MODIFIER" formRef={formModifierInfosRef}/> </form> <div className="other"> <a href="" onClick={(e) => goTo("connecte",e)}>Retour</a> </div> </motion.div> ) : currentMenu === "mesBillets" ? ( <></> ) : currentMenu === "codeVerification" ? ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Entrez le code reçu par e-mail</h2> <form onSubmit={handleEnvoyerCode} ref={formCodeVerificationRef} > <ChampCode errorText={errorCodeVerification} codeVar={codeVerification} setCodeVar={setCodeVerification} nbChar={6}/> <Button isLoading={isLoading} text="VALIDER" formRef={formCodeVerificationRef}/> </form> <div className="other"> <a href="" onClick={(e) => goTo("connexion",e)}>Retour</a> </div> </motion.div> ) : currentMenu === "changerMdp" && ( <motion.div className="container" variants={menuSwitchVariants} initial="appearing" animate={isWrong ? "wrong" : "default"} exit={!props.isOpen ? "default" : "exit"} key={currentMenu} > <h2>Choisissez un nouveau mot de passe</h2> <form onSubmit={handleModifierMdp} ref={formModifMdpRef} > <TextField errorText={errorPassword} isPassword text="Mot de passe" textVar={password} setTextVar={setPassword}/> <TextField errorText={errorVerifPassword} isPassword text="Vérifiez votre mot de passe" textVar={verifierPassword} setTextVar={setVerifierPassword}/> <Button isLoading={isLoading} text="VALIDER" formRef={formModifMdpRef}/> </form> </motion.div> ) } </AnimatePresence> </motion.div> ) }
aa198ac6fd49700f17e162a20b8e1b07
{ "intermediate": 0.4132597744464874, "beginner": 0.4553796947002411, "expert": 0.13136054575443268 }
37,516
What is the difference between == and === control operators in JavaScript?
d1fcfcd1844ea819b9f986534e95b539
{ "intermediate": 0.31911909580230713, "beginner": 0.43923312425613403, "expert": 0.24164770543575287 }
37,517
Instructions: The project focuses on the use of FMCW radar. It is used for data collection, point detection, tracking and other functions. The project is broken down into several modules. The aim of this division is to decouple as much as possible the functionalities present in each module, and make the development of new functionalities more flexible and rapid. Some information will be presented to you in json format: - module: the name of the module - module_structure: the structure of the module (the files making up the module and their hierarchy) - module_files_already_generated_doc: the documentation of the module's files if already generated - other_modules_doc: the documentation of the other modules on which the module depends (possibly none at all) - gen_doc_of_file: the file you will be given to generate the documentation of. If no file is given, the documentation of the entire module must be generated. Your goal is to create a markdown documentation of the file you will be given, or the entire module if no file is given. This documentation is intended to guide a developer who is new to the project, you can therefore add whatever you feel is relevant for this task. Informations: {"module": "radar_area_detection", "module_structure": "radar_area_detection/detection.py;radar_area_detection/display.py;radar_area_detection/live_area_detection.py;radar_area_detection\\comm/camera_alert.py;radar_area_detection\\comm/rabbitmq.py;radar_area_detection\\conf/6432_ti_config.cfg;radar_area_detection\\conf/6843_ti_config.cfg;radar_area_detection\\conf/detection_conf.json;radar_area_detection\\conf/live_area_detection.json;radar_area_detection\\conf/rabbitmq_conf.json;radar_area_detection\\conf/tracking_conf.json;", "module_files_already_generated_doc": [{"file": "docs\\radar_area_detection\\detection.md", "doc": "# radar_area_detection/detection.py Documentation\n\n## Overview\n\nThe detection.py script is part of the [radar_area_detection](radar_area_detection.md) module, which is responsible for the area detection functionality using FMCW radar technology. This module aids in the detection of points, tracking, and implementation of alert systems for certain areas within the radar\u00e2\u20ac\u2122s detection range.\n\n## File Structure\n\n`detection.py` includes the following classes:\n\n- `Area`: A simple data structure representing a rectangular detection area.\n- `Alert`: An abstract base class that defines the structure for raising and clearing alerts.\n- `AreaDetector`: The primary class that manages detection areas and processes radar data to trigger alerts.\n\n### Area Class\n\nThe Area class serves as a representation of a detection zone, defined by its boundaries in Cartesian coordinates.\n\n#### Attributes\n\n- `xl`: Float. Represents the x-coordinate of the left boundary of the area.\n- `xr`: Float. Represents the x-coordinate of the right boundary of the area.\n- `yb`: Float. Represents the y-coordinate of the bottom boundary of the area.\n- `yt`: Float. Represents the y-coordinate of the top boundary of the area.\n\n#### Methods\n\n- `serialize`: Serializes area\u00e2\u20ac\u2122s attributes into a dictionary format.\n\n### Alert Abstract Class\n\nThe `Alert` class provides a blueprint for implementing the alert system that will respond to detection events.\n\n#### Methods (Abstract)\n\n- `RaiseAlert`: Abstract method to be defined to specify the actions required when an alert is raised.\n- `ClearAlert`: Abstract method to be defined to specify the actions required when an alert is cleared.\n\n### AreaDetector Class\n\n`AreaDetector` is the central class that orchestrates the area detection and alerting process.\n\n#### Constructor\n\n- `__init__(areas, alerts=None)`: Initializes the detector with a list of areas and optional alert mechanisms.\n\n#### Attributes\n\n- `alerts`: List of Alert objects. Used to handle alerts when a tracked object enters a detection area.\n- `areas`: List of Area objects. These define the detection areas within the radar\u00e2\u20ac\u2122s field of view.\n- `ok_areas`: List of Area objects that are considered clear of tracked objects.\n- `alert_areas`: List of Area objects where alerts have been triggered due to the presence of tracked objects.\n- `alert_triggered`: Boolean indicating if an alert has been triggered.\n\n#### Methods\n\n- `update(clusters_up_to_date)`: Updates the state of each detection area based on the latest tracked clusters information.\n- `serialize`: Serializes the status of ok_areas and alert_areas into a dictionary format.\n\n## Integration with Other Modules\n\nThe `detection.py` script in the [radar_area_detection](radar_area_detection.md) module works in coordination with the [radar_tracking](../radar_tracking/radar_tracking.md) module (tracks objects detected by the radar) and may utilize the alerting infrastructure provided by the `radar_area_detection\\comm` submodule (for example, sending messages via [RabbitMQ](comm/rabbitmq.md)).\n\n## Usage\n\nDevelopers can use this script to define detection areas, integrate tracking data, and manage alert systems based on their specific needs in the context of FMCW radar applications.\n\n## Developer Notes\n\nThe AreaDetector class initializes with predefined detection areas and has the capability to receive real-time tracking data. Upon receipt of new cluster information, the update method reevaluates and categorizes each area as clear or under alert, triggering the appropriate alert mechanisms if any are in place. \n- When creating new Area instances, ensure that the coordinates correctly reflect the detection zone intended for monitoring.\n- When implementing concrete alert classes, define clear procedures for both RaiseAlert and ClearAlert methods.\n- During the update process, ensure that the centroid of clusters is being correctly obtained from the tracking data.\n- It is crucial to manage ok_areas and alert_areas accurately, reflecting the radar\u00e2\u20ac\u2122s real-time assessment of the monitored areas.\n\n[Radar Area Detection](radar_area_detection.md)"}, {"file": "docs\\radar_area_detection\\display.md", "doc": "# radar_area_detection/display.py Documentation\n\n## Overview\n\nThe `display.py` script is part of the [radar_area_detection](radar_area_detection.md) module, which integrates with the area detection and object tracking functionalities. This script specifically provides visualization capabilities, extending the `TrackingDisplay2D` class from the radar_tracking module to represent detection areas and the status of those areas (either as \"ok\" or under \"alert\").\n\n## File Structure\n\ndisplay.py includes the following class:\n\n- `AreasDisplay2D`: Extends the `TrackingDisplay2D` class to display detection areas and denote their status on a 2D plot.\n\n### AreasDisplay2D Class\n\nThe `AreasDisplay2D` class is responsible for visualizing areas on a 2D display, differentiating between areas that are clear (ok) and those that have an active alert. It allows real-time updates of the visualization as the status of the areas changes according to the radar data.\n\n#### Constructor\n\n- **\\_\\_init__(self, *args, \\*\\*kwargs)**: Initializes the `AreasDisplay2D` class with arguments passed to its superclass and initializes an empty list for patches.\n\n#### Attributes\n\n- **patches**: List. Stores the drawing patches corresponding to areas on the display.\n\n#### Methods\n\n- **_prepare_draw(self, clusters, ok_areas: List[Area], alert_areas: List[Area])**: Internally prepares the drawing of the clusters and areas. It removes any existing patches and re-adds them according to the updated area states.\n- **show(self, clusters, area_detector: AreaDetector)**: Public method to display the radar clusters and areas. This method calls _prepare_draw with the ok_areas and alert_areas from an AreaDetector instance and then proceeds to draw the updated visualization.\n\n### Integration with Other Modules\n\nThe detect.py script in the [radar_area_detection](radar_area_detection.md) module interacts with the AreasDisplay2D class to visualize active areas and alerts. Moreover, the AreasDisplay2D class uses functionality from the radar_tracking module\u00e2\u20ac\u2122s visualization utilities, signifying how various modules within the system come together to fulfill the project\u00e2\u20ac\u2122s overall objectives.\n\n## Usage\n\nDevelopers can instantiate the `AreasDisplay2D` class to visualise the area detection results in the context of FMCW radar applications. This enables a graphical representation of which areas are clear (ok) and which are under alert.\n\n## Data Flow\n\n1. An instance of `AreasDisplay2D` is created with appropriate arguments.\n2. Radar data (clusters) and area statuses are processed by an `AreaDetector`.\n3. Area statuses and clusters are passed to the `AreasDisplay2D` instance\u00e2\u20ac\u2122s show method.\n4. The show method updates the visual representation according to the current state of detection areas and tracked clusters.\n\n## Developer Notes\n\n- Use the `AreasDisplay2D` class to create a visual feedback loop for area detection and alert visualization in real-time radar applications.\n- Ensure active areas and their statuses are correctly updated and reflected in the visualization to provide continuous situational awareness.\n- The visual representation is crucial for debugging and monitoring the radar area detection functionality, hence strive for clear visual distinction between different states for better readability and interpretation.\n\n## Conclusion\n\n`display.py` within the [radar_area_detection](radar_area_detection.md) module serves a pivotal role in visually representing the status of detection areas in real-time. The AreasDisplay2D class demonstrates an effective integration of visualization techniques with radar detection and tracking capabilities. It contributes to the wider goal of creating a modular and adaptable system for FMCW radar applications.\n\n[Radar Area Detection](radar_area_detection.md)"}, {"file": "docs\\radar_area_detection\\live_area_detection.md", "doc": "# radar_area_detection/live_area_detection.py Documentation\n\n## Overview\n\nThe `live_area_detection.py` script is part of the [radar_area_detection](radar_area_detection.md) module. It orchestrates live area detection leveraging data from mmWave radar hardware. Using configuration files, this script setups the radar system, executes detection and tracking algorithms, and detects intrusions within predefined areas. If configured, it sends alert notifications and visualizes the detection areas.\n\n## Usage\n\nThis script should be run with a parameter to indicate the configuration file to use:\n\n
e654b8a24df2abb5b0b708a7a3d2fafc
{ "intermediate": 0.34244200587272644, "beginner": 0.43980252742767334, "expert": 0.217755526304245 }
37,518
ile "C:\Users\alexa\AppData\Roaming\Python\Python310\site-packages\flask\app.py", line 852, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) File "C:\Users\alexa\Desktop\sae-fest-iuto-back\Code\appli\app.py", line 106, in connecter session['user_id'] = user.getIdUser() AttributeError: 'User' object has no attribute 'getIdUser'@app.route('/connecter', methods=['POST']) def connecter(): connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) data = request.get_json() print(data) email = data["email"] password = data["password"] if userbd.exist_user(email, password): user = userbd.get_user_by_email(email) session['user_id'] = user.getIdUser() return userbd.user_to_json(userbd.get_user_by_email(email)) else: return jsonify({"error": "Utilisateur non trouve"})from flask import session from BD import User from ConnexionBD import ConnexionBD from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.sql.expression import text import json class UserBD: def __init__(self, conx: ConnexionBD): self.connexion = conx def email_exists(self, email): try: query = text("SELECT count(*) FROM USER WHERE emailUser = :email") result = self.connexion.get_connexion().execute(query, {"email": email}) return result.fetchone()[0] == 1 except SQLAlchemyError as e: print(f"La requête a échoué : {e}") def exist_user(self, email, password): try: query = text("SELECT count(*) FROM USER WHERE emailUser = :email AND mdpUser = :password") result = self.connexion.get_connexion().execute(query, {"email": email, "password": password}) return result.fetchone()[0] == 1 except SQLAlchemyError as e: print(f"La requête a échoué : {e}") def exist_user_with_id(self, idUser, password): try: query = text("SELECT count(*) FROM USER WHERE idUser = :idUser AND mdpUser = :password") result = self.connexion.get_connexion().execute(query, {"idUser": idUser, "password": password}) return result.fetchone()[0] == 1 except SQLAlchemyError as e: print(f"La requête a échoué : {e}") def get_user_by_email(self, email): try: query = text("SELECT idUser, pseudoUser, mdpUser, emailUser, statutUser FROM USER WHERE emailUser = :email") result = self.connexion.get_connexion().execute(query, {"email": email}) idUser, pseudoUser, mdpUser, emailUser, statutUser = result.fetchone() return User(idUser, pseudoUser, mdpUser, emailUser, statutUser) except SQLAlchemyError as e: print(f"La requête a échoué : {e}") def add_user(self, pseudo, email, password): try: query = text("INSERT INTO USER (pseudoUser, emailUser, mdpUser, statutUser) VALUES (:pseudo, :email, :password, 'user')") print("INSERT INTO USER : " + "\n" + "pseudoUser = " + pseudo + "\n" + "emailUser = " + email + "\n" + "mdpUser = " + password + "\n") self.connexion.get_connexion().execute(query, {"pseudo": pseudo, "email": email, "password": password}) self.connexion.get_connexion().commit() return True except SQLAlchemyError as e: if ("emailUser" in str(e) and "Duplicate entry" in str(e)): return "emailErr" print(f"La requête a échoué : {e}") return False def update_user(self, idUser, email, pseudo, password): try: query = text("UPDATE USER SET pseudoUser = :pseudo, emailUser = :email, mdpUser = :password WHERE idUser = :idUser") print("UPDATE USER : " + "\n" + "idUser = " + str(idUser) + "\n" + "pseudoUser = " + pseudo + "\n" + "emailUser = " + email + "\n" + "mdpUser = " + password + "\n") self.connexion.get_connexion().execute(query, {"idUser": idUser, "pseudo": pseudo, "email": email, "password": password}) self.connexion.get_connexion().commit() return True except SQLAlchemyError as e: if ("emailUser" in str(e) and "Duplicate entry" in str(e)): return "emailErr" print(f"La requête a échoué : {e}") return False def ajouterCodeVerification(self, emailUser, code): try: query = text("UPDATE USER SET codeTempUser = :code WHERE emailUser = :email") self.connexion.get_connexion().execute(query, {"code": code, "email": emailUser}) self.connexion.get_connexion().commit() return True except SQLAlchemyError as e: print(f"La requête a échoué : {e}") return False def tester_code_verification(self, emailUser, code): try: query = text("SELECT count(*) FROM USER WHERE emailUser = :email AND codeTempUser = :code") # si la requete retourne 1 alors le code est bon result = self.connexion.get_connexion().execute(query, {"email": emailUser, "code": code}) return result.fetchone()[0] == 1 except SQLAlchemyError as e: print(f"La requête a échoué : {e}") return False def update_password(self,emailUser, newPassword): try: query = text("UPDATE USER SET mdpUser= :mdp, codeTempUser = null WHERE emailUser = :email") self.connexion.get_connexion().execute(query, {"mdp": newPassword, "email": emailUser}) self.connexion.get_connexion().commit() return True except SQLAlchemyError as e: print(f"La requête a échoué : {e}") return False def user_to_json(self, user): return json.dumps(user.to_dict(), ensure_ascii=False) def get_all_users(self): try: query = text("select idUser, pseudoUser, mdpUser, emailUser, statutUser from USER") result = self.connexion.get_connexion().execute(query) users = [] for idUser, pseudoUser, mdpUser, emailUser, statutUser in result: users.append(User(idUser, pseudoUser, mdpUser, emailUser, statutUser)) return users except SQLAlchemyError as e: print(f"La requête a échoué : {e}") return False def insert_user_admin(self, user): try: query = text("INSERT INTO USER (pseudoUser, mdpUser, emailUser, statutUser) VALUES (:pseudo, :password, :email, :statut)") result = self.connexion.get_connexion().execute(query, {"pseudo": user.get_pseudoUser(), "password": user.get_mdpUser(), "email": user.get_emailUser(), "statut": user.get_statutUser()}) id_user = result.lastrowid print(f"L'utilisateur {id_user} a été ajouté") self.connexion.get_connexion().commit() return True except SQLAlchemyError as e: if ("emailUser" in str(e) and "Duplicate entry" in str(e)): return "emailErr" print(f"La requête a échoué : {e}") return False def delete_user_by_id(self, idUser): try: query = text("DELETE FROM USER WHERE idUser = :idUser") self.connexion.get_connexion().execute(query, {"idUser": idUser}) self.connexion.get_connexion().commit() return True except SQLAlchemyError as e: print(f"La requête a échoué : {e}") return False def update_user_admin(self, user): try: query = text("UPDATE USER SET pseudoUser = :pseudo, mdpUser = :password, emailUser = :email WHERE idUser = :idUser") self.connexion.get_connexion().execute(query, {"pseudo": user.get_pseudoUser(), "password": user.get_mdpUser(), "email": user.get_emailUser(), "idUser": user.get_idUser()}) print(f"L'utilisateur {user.get_idUser()} a été modifié") self.connexion.get_connexion().commit() return True except SQLAlchemyError as e: if ("emailUser" in str(e) and "Duplicate entry" in str(e)): return "emailErr" print(f"La requête a échoué : {e}") return False def get_user_by_id(self, idUser): try: query = text("SELECT idUser, pseudoUser, mdpUser, emailUser, statutUser FROM USER WHERE idUser = :idUser") result = self.connexion.get_connexion().execute(query, {"idUser": idUser}) idUser, pseudoUser, mdpUser, emailUser, statutUser = result.fetchone() return User(idUser, pseudoUser, mdpUser, emailUser, statutUser) except SQLAlchemyError as e: print(f"La requête a échoué : {e}") return False def get_authenticated_user_id(): user_id = session.get('user_id') if user_id: return user_id from datetime import datetime, date, time, timedelta class Faq: def __init__(self, idFaq: int, question: str, reponse: str): self._idFaq = idFaq self._question = question self._reponse = reponse def get_idFaq(self): return self._idFaq def get_question(self): return self._question def get_reponse(self): return self._reponse def to_dict(self): return { "idFaq": self._idFaq, "question": self._question, "reponse": self._reponse } class User: def __init__(self, idUser: int, pseudoUser: str, mdpUser: str, emailUser: str, statutUser: str): self.__idUser = idUser self.__pseudoUser = pseudoUser self.__mdpUser = mdpUser self.__emailUser = emailUser self.__statutUser = statutUser def get_idUser(self): return self.__idUser def get_pseudoUser(self): return self.__pseudoUser def get_mdpUser(self): return self.__mdpUser def get_emailUser(self): return self.__emailUser def get_statutUser(self): return self.__statutUser def set_pseudoUser(self, pseudoUser): self.__pseudoUser = pseudoUser def set_mdpUser(self, mdpUser): self.__mdpUser = mdpUser def set_emailUser(self, emailUser): self.__emailUser = emailUser def to_dict(self): return { "idUser": self.__idUser, "pseudoUser": self.__pseudoUser, "emailUser": self.__emailUser } class Festival: def __init__(self, idF: int, nomF: str, villeF: str, dateDebutF: str, dateFinF: str): self.__idF = idF self.__nomF = nomF self.__villeF = villeF self.__dateDebutF = dateDebutF if isinstance(dateDebutF, date) else datetime.strptime(dateDebutF, '%Y-%m-%d').date() self.__dateFinF = dateFinF if isinstance(dateFinF, date) else datetime.strptime(dateFinF, '%Y-%m-%d').date() def get_idF(self): return self.__idF def get_nomF(self): return self.__nomF def get_villeF(self): return self.__villeF def get_dateDebutF(self): return self.__dateDebutF def get_dateFinF(self): return self.__dateFinF def __repr__(self): return f"({self.__idF}, {self.__nomF}, {self.__villeF}, {self.__dateDebutF}, {self.__dateFinF})" def to_dict(self): return { "idF": self.__idF, "nomF": self.__nomF, "villeF": self.__villeF, "dateDebutF": self.__dateDebutF.isoformat(), "dateFinF": self.__dateFinF.isoformat() } class Type_Billet: def __init__(self, idType: int, duree: int): self.__idType = idType self.__duree = duree def get_idType(self): return self.__idType def get_duree(self): return self.__duree def to_dict(self): return { "idType": self.__idType, "duree": self.__duree } class Spectateur: def __init__(self, idS: int, nomS: str, prenomS: str, adresseS: str, emailS: str, mdpS: str): self.__idS = idS self.__nomS = nomS self.__prenomS = prenomS self.__adresseS = adresseS self.__emailS = emailS self.__mdpS = mdpS def get_idS(self): return self.__idS def get_nomS(self): return self.__nomS def get_prenomS(self): return self.__prenomS def get_adresseS(self): return self.__adresseS def get_emailS(self): return self.__emailS def get_mdpS(self): return self.__mdpS def to_dict(self): return { "idS": self.__idS, "nomS": self.__nomS, "prenomS": self.__prenomS, "adresseS": self.__adresseS, "emailS": self.__emailS, "mdpS": self.__mdpS } class Billet: def __init__(self, idB: int, idF: int, idType: int, idS: int, prix: int, dateAchat: str, dateDebutB: str, dateFinB: str): self.__idB = idB self.__idF = idF self.__idType = idType self.__idS = idS self.__prix = prix self.__dateAchat = dateAchat if isinstance(dateAchat, date) else datetime.strptime(dateAchat, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() if dateDebutB != None and dateFinB != None: self.__dateDebutB = dateDebutB if isinstance(dateDebutB, date) else datetime.strptime(dateDebutB, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() self.__dateFinB = dateFinB if isinstance(dateFinB, date) else datetime.strptime(dateFinB, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() else: self.__dateDebutB = None self.__dateFinB = None def get_idB(self): return self.__idB def get_idFestival(self): return self.__idF def get_idType(self): return self.__idType def get_idSpectateur(self): return self.__idS def get_prix(self): return self.__prix def get_dateAchat(self): return self.__dateAchat def get_dateDebutB(self): return self.__dateDebutB def get_dateFinB(self): return self.__dateFinB def to_dict(self): return { "idB": self.__idB, "idF": self.__idF, "idType": self.__idType, "idS": self.__idS, "prix": self.__prix, "dateAchat": self.__dateAchat.isoformat(), "dateDebutB": self.__dateDebutB.isoformat(), "dateFinB": self.__dateFinB.isoformat() } class Lieu: def __init__(self, idL: int, idF: int, nomL: str, adresseL: str, jaugeL: int): self.__idL = idL self.__idF = idF self.__nomL = nomL self.__adresseL = adresseL self.__jaugeL = jaugeL def get_idL(self): return self.__idL def get_idFestival(self): return self.__idF def get_nomL(self): return self.__nomL def get_adresseL(self): return self.__adresseL def get_jaugeL(self): return self.__jaugeL def to_dict(self): return { "idL": self.__idL, "idF": self.__idF, "nomL": self.__nomL, "adresseL": self.__adresseL, "jaugeL": self.__jaugeL } class Hebergement: def __init__(self, idH: int, nomH: str, limitePlacesH: int, adresseH: int): self.__idH = idH self.__nomH = nomH self.__limitePlacesH = limitePlacesH self.__adresseH = adresseH def get_idH(self): return self.__idH def get_nomH(self): return self.__nomH def get_limitePlacesH(self): return self.__limitePlacesH def get_adresseH(self): return self.__adresseH def set_nomH(self, nomH): self.__nomH = nomH def set_limitePlacesH(self, limitePlacesH): self.__limitePlacesH = limitePlacesH def set_adresseH(self, adresseH): self.__adresseH = adresseH def to_dict(self): return { "idH": self.__idH, "nomH": self.__nomH, "limitePlacesH": self.__limitePlacesH, "adresseH": self.__adresseH } class Programmer: def __init__(self, idF: int, idL: int, idH: int, dateArrivee: str, heureArrivee: str, dateDepart: str, heureDepart: str): self.__idF = idF self.__idL = idL self.__idH = idH self.__dateArrivee = dateArrivee if isinstance(dateArrivee, date) else datetime.strptime(dateArrivee, '%Y-%m-%d').date() self.__heureArrivee = self.timedelta_to_time(heureArrivee) if isinstance(heureArrivee, timedelta) else datetime.strptime(heureArrivee, '%H:%M').time() self.__dateDepart = dateDepart if isinstance(dateDepart, date) else datetime.strptime(dateDepart, '%Y-%m-%d').date() self.__heureDepart = self.timedelta_to_time(heureDepart) if isinstance(heureDepart, timedelta) else datetime.strptime(heureDepart, '%H:%M').time() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idFestival(self): return self.__idF def get_idLieu(self): return self.__idL def get_idHebergement(self): return self.__idH def get_dateArrivee(self): return self.__dateArrivee def get_heureArrivee(self): return self.__heureArrivee def get_dateDepart(self): return self.__dateDepart def get_heureDepart(self): return self.__heureDepart def to_dict(self): return { "idF": self.__idF, "idL": self.__idL, "idH": self.__idH, "dateArrivee": self.__dateArrivee.isoformat(), "heureArrivee": self.__heureArrivee.strftime("%H:%M:%S"), "dateDepart": self.__dateDepart.isoformat(), "heureDepart": self.__heureDepart.strftime("%H:%M:%S") } class Groupe: def __init__(self, idG: int, idH: int, nomG: str, descriptionG: str): self.__idG = idG self.__idH = idH self.__nomG = nomG self.__descriptionG = descriptionG def get_idG(self): return self.__idG def get_idHebergement(self): return self.__idH def get_nomG(self): return self.__nomG def get_descriptionG(self): return self.__descriptionG def set_idHebergement(self, idH): self.__idH = idH def to_dict(self): return { "idG": self.__idG, "idH": self.__idH, "nomG": self.__nomG, "descriptionG": self.__descriptionG } def set_nomG(self, nomG): self.__nomG = nomG def set_descriptionG(self, descriptionG): self.__descriptionG = descriptionG class Membre_Groupe: def __init__(self, idMG: int, idG, nomMG: str, prenomMG: str, nomDeSceneMG: str): self.__idMG = idMG self.__idG = idG self.__nomMG = nomMG self.__prenomMG = prenomMG self.__nomDeSceneMG = nomDeSceneMG def get_idMG(self): return self.__idMG def get_idGroupe(self): return self.__idG def get_nomMG(self): return self.__nomMG def get_prenomMG(self): return self.__prenomMG def get_nomDeSceneMG(self): return self.__nomDeSceneMG def __repr__(self): return f"({self.__idMG}, {self.__idG}, {self.__nomMG}, {self.__prenomMG}, {self.__nomDeSceneMG})" def to_dict(self): return { "idMG": self.__idMG, "idG": self.__idG, "nomMG": self.__nomMG, "prenomMG": self.__prenomMG, "nomDeSceneMG": self.__nomDeSceneMG } def set_nomMG(self, nomMG): self.__nomMG = nomMG def set_prenomMG(self, prenomMG): self.__prenomMG = prenomMG def set_nomDeSceneMG(self, nomDeSceneMG): self.__nomDeSceneMG = nomDeSceneMG class Instrument: def __init__(self, idI: int, nomI: str): self.__idI = idI self.__nomI = nomI def get_idI(self): return self.__idI def get_nomI(self): return self.__nomI def to_dict(self): return { "idI": self.__idI, "nomI": self.__nomI } class Style_Musical: def __init__(self, idSt: int, nomSt: str): self.__idSt = idSt self.__nomSt = nomSt def get_idSt(self): return self.__idSt def get_nomSt(self): return self.__nomSt def to_dict(self): return { "idSt": self.__idSt, "nomSt": self.__nomSt } class Lien_Video: def __init__(self, idLV: int, idG: int, video: str): self.__idLV = idLV self.__idG = idG self.__video = video def get_idLV(self): return self.__idLV def get_idGroupe(self): return self.__idG def get_video(self): return self.__video def to_dict(self): return { "idLV": self.__idLV, "idG": self.__idG, "video": self.__video } class Lien_Reseaux_Sociaux: def __init__(self, idLRS: int, idG: int, reseau: str): self.__idLRS = idLRS self.__idG = idG self.__reseau = reseau def get_idLRS(self): return self.__idLRS def get_idGroupe(self): return self.__idG def get_reseau(self): return self.__reseau def to_dict(self): return { "idLRS": self.__idLRS, "idG": self.__idG, "reseau": self.__reseau } class Evenement: def __init__(self, idE: int, idG: int, idL: int, nomE: str, heureDebutE: str, heureFinE: str, dateDebutE: str, dateFinE: str): self.__idE = idE self.__idG = idG self.__idL = idL self.__nomE = nomE self.__heureDebutE = self.timedelta_to_time(heureDebutE) if isinstance(heureDebutE, timedelta) else datetime.strptime(heureDebutE, '%H:%M').time() self.__heureFinE = self.timedelta_to_time(heureFinE) if isinstance(heureFinE, timedelta) else datetime.strptime(heureFinE, '%H:%M').time() self.__dateDebutE = dateDebutE if isinstance(dateDebutE, date) else datetime.strptime(dateDebutE, "%Y-%m-%d").date() self.__dateFinE = dateFinE if isinstance(dateFinE, date) else datetime.strptime(dateFinE, "%Y-%m-%d").date() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idE(self): return self.__idE def get_idG(self): return self.__idG def get_idL(self): return self.__idL def get_nomE(self): return self.__nomE def get_heureDebutE(self): return self.__heureDebutE def get_heureFinE(self): return self.__heureFinE def get_dateDebutE(self): return self.__dateDebutE def get_dateFinE(self): return self.__dateFinE def set_idG(self, idG): self.__idG = idG def set_idL(self, idL): self.__idL = idL def set_nomE(self, nomE): self.__nomE = nomE def set_heureDebutE(self, heureDebutE): self.__heureDebutE = heureDebutE def set_heureFinE(self, heureFinE): self.__heureFinE = heureFinE def set_dateDebutE(self, dateDebutE): self.__dateDebutE = dateDebutE def set_dateFinE(self, dateFinE): self.__dateFinE = dateFinE def to_dict(self): return { "idE": self.__idE, "idG": self.__idG, "idL": self.__idL, "nomE": self.__nomE, "heureDebutE": self.__heureDebutE.strftime("%H:%M:%S") if self.__heureDebutE else None, "heureFinE": self.__heureFinE.strftime("%H:%M:%S") if self.__heureFinE else None, "dateDebutE": self.__dateDebutE.isoformat() if self.__dateDebutE else None, "dateFinE": self.__dateFinE.isoformat() if self.__dateFinE else None } class Activite_Annexe: def __init__(self, idE: int, typeA: str, ouvertAuPublic: bool): self.__idE = idE self.__typeA = typeA self.__ouvertAuPublic = ouvertAuPublic def get_idEvenement(self): return self.__idE def get_typeA(self): return self.__typeA def get_ouvertAuPublic(self): return self.__ouvertAuPublic def to_dict(self): return { "idE": self.__idE, "typeA": self.__typeA, "ouvertAuPublic": self.__ouvertAuPublic } class Concert: def __init__(self, idE: int, tempsMontage: str, tempsDemontage: str): self.__idE = idE self.__tempsMontage = self.timedelta_to_time(tempsMontage) if isinstance(tempsMontage, timedelta) else datetime.strptime(tempsMontage, '%H:%M').time() self.__tempsDemontage = self.timedelta_to_time(tempsDemontage) if isinstance(tempsDemontage, timedelta) else datetime.strptime(tempsDemontage, '%H:%M').time() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idEvenement(self): return self.__idE def get_tempsMontage(self): return self.__tempsMontage def get_tempsDemontage(self): return self.__tempsDemontage def to_dict(self): return { "idE": self.__idE, "tempsMontage": self.__tempsMontage.strftime("%H:%M:%S"), "tempsDemontage": self.__tempsDemontage.strftime("%H:%M:%S") } class Groupe_Style: def __init__(self, idG: int, idSt: int): self.__idG = idG self.__idSt = idSt def get_idG(self): return self.__idG def get_idSt(self): return self.__idSt def to_dict(self): return { "idG": self.__idG, "idSt": self.__idSt }
f774aa762100dd42be7a5db221907b08
{ "intermediate": 0.29899901151657104, "beginner": 0.5018613338470459, "expert": 0.19913968443870544 }
37,519
PS C:\Users\bsbul\Desktop\New folder> pip install sklearn Collecting sklearn Downloading sklearn-0.0.post12.tar.gz (2.6 kB) ERROR: Command errored out with exit status 1: command: 'c:\users\bsbul\appdata\local\programs\python\python39\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\bsbul\\AppData\\Local\\Temp\\pip-install-m_i_y_c8\\sklearn\\setup.py'"'"'; __file__='"'"'C:\\Users\\bsbul\\AppData\\Local\\Temp\\pip-install-m_i_y_c8\\sklearn\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\bsbul\AppData\Local\Temp\pip-pip-egg-info-5z6k2cfw' cwd: C:\Users\bsbul\AppData\Local\Temp\pip-install-m_i_y_c8\sklearn\ Complete output (15 lines): The 'sklearn' PyPI package is deprecated, use 'scikit-learn' rather than 'sklearn' for pip commands. Here is how to fix this error in the main use cases: - use 'pip install scikit-learn' rather than 'pip install sklearn' - replace 'sklearn' by 'scikit-learn' in your pip requirements files (requirements.txt, setup.py, setup.cfg, Pipfile, etc ...) - if the 'sklearn' package is used by one of your dependencies, it would be great if you take some time to track which package uses 'sklearn' instead of 'scikit-learn' and report it to their issue tracker - as a last resort, set the environment variable SKLEARN_ALLOW_DEPRECATED_SKLEARN_PACKAGE_INSTALL=True to avoid this error More information is available at https://github.com/scikit-learn/sklearn-pypi-package
b110a7b296297d13d63a851d542dbc0f
{ "intermediate": 0.3376811146736145, "beginner": 0.3794236183166504, "expert": 0.2828953266143799 }
37,520
How do I specify a source in eclipse jdtls using the command line?
1fd0e1cf96ae2ba41be2125a7ac2fb91
{ "intermediate": 0.6052135229110718, "beginner": 0.15136836469173431, "expert": 0.2434181272983551 }
37,521
How do I capitalize a string in a shell script, without using any bash specific features?
61f016a6fb797402d08abc091eaa8469
{ "intermediate": 0.33001992106437683, "beginner": 0.373974472284317, "expert": 0.29600557684898376 }
37,522
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.20; import {Kernel, Module, Keycode} from "@src/Kernel.sol"; import {Proxiable} from "@src/proxy/Proxiable.sol"; import {RentalUtils} from "@src/libraries/RentalUtils.sol"; import {RentalId, RentalAssetUpdate} from "@src/libraries/RentalStructs.sol"; import {Errors} from "@src/libraries/Errors.sol"; /** * @title StorageBase * @notice Storage exists in its own base contract to avoid storage slot mismatch during upgrades. */ contract StorageBase { ///////////////////////////////////////////////////////////////////////////////// // Rental Storage // ///////////////////////////////////////////////////////////////////////////////// // Points an order hash to whether it is active. mapping(bytes32 orderHash => bool isActive) public orders; // Points an item ID to its number of actively rented tokens. This is used to // determine if an item is actively rented within the protocol. For ERC721, this // value will always be 1 when actively rented. Any inactive rentals will have a // value of 0. mapping(RentalId itemId => uint256 amount) public rentedAssets; ///////////////////////////////////////////////////////////////////////////////// // Deployed Safe Storage // ///////////////////////////////////////////////////////////////////////////////// // Records all safes that have been deployed by the protocol. mapping(address safe => uint256 nonce) public deployedSafes; // Records the total amount of deployed safes. uint256 public totalSafes; ///////////////////////////////////////////////////////////////////////////////// // Hook Storage // ///////////////////////////////////////////////////////////////////////////////// // When interacting with the guard, any contracts that have hooks enabled // should have the guard logic routed through them. mapping(address to => address hook) internal _contractToHook; // Mapping of a bitmap which denotes the hook functions that are enabled. mapping(address hook => uint8 enabled) public hookStatus; ///////////////////////////////////////////////////////////////////////////////// // Whitelist Storage // ///////////////////////////////////////////////////////////////////////////////// // Allows the safe to delegate call to an approved address. For example, delegate // call to a contract that would swap out an old gnosis safe module for a new one. mapping(address delegate => bool isWhitelisted) public whitelistedDelegates; // Allows for the safe registration of extensions that can be enabled on a safe. mapping(address extension => bool isWhitelisted) public whitelistedExtensions; } /** * @title Storage * @notice Module dedicated to maintaining all the storage for the protocol. Includes * storage for active rentals, deployed rental safes, hooks, and whitelists. */ contract Storage is Proxiable, Module, StorageBase { using RentalUtils for address; ///////////////////////////////////////////////////////////////////////////////// // Kernel Module Configuration // ///////////////////////////////////////////////////////////////////////////////// /** * @dev Instantiate this contract as a module. When using a proxy, the kernel address * should be set to address(0). * * @param kernel_ Address of the kernel contract. */ constructor(Kernel kernel_) Module(kernel_) {} /** * @notice Instantiates this contract as a module via a proxy. * * @param kernel_ Address of the kernel contract. */ function MODULE_PROXY_INSTANTIATION( Kernel kernel_ ) external onlyByProxy onlyUninitialized { kernel = kernel_; initialized = true; } /** * @notice Specifies which version of a module is being implemented. */ function VERSION() external pure override returns (uint8 major, uint8 minor) { return (1, 0); } /** * @notice Defines the keycode for this module. */ function KEYCODE() public pure override returns (Keycode) { return Keycode.wrap("STORE"); } ///////////////////////////////////////////////////////////////////////////////// // View Functions // ///////////////////////////////////////////////////////////////////////////////// /** * @notice Determines if an asset is actively being rented by a wallet. * * @param recipient Address of the wallet which rents the asset. * @param token Address of the token. * @param identifier ID of the token. */ function isRentedOut( address recipient, address token, uint256 identifier ) external view returns (bool) { // calculate the rental ID RentalId rentalId = RentalUtils.getItemPointer(recipient, token, identifier); // Determine if there is a positive amount return rentedAssets[rentalId] != 0; } /** * @notice Fetches the hook address that is pointing at the the target. * * @param to Address which has a hook pointing to it. */ function contractToHook(address to) external view returns (address) { // Fetch the hook that the address currently points to. address hook = _contractToHook[to]; // This hook may have been disabled without setting a new hook to take its place. // So if the hook is disabled, then return the 0 address. return hookStatus[hook] != 0 ? hook : address(0); } /** * @notice Determines whether the `onTransaction()` function is enabled for the hook. * * @param hook Address of the hook contract. */ function hookOnTransaction(address hook) external view returns (bool) { // 1 is 0x00000001. Determines if the masked bit is enabled. return (uint8(1) & hookStatus[hook]) != 0; } /** * @notice Determines whether the `onStart()` function is enabled for the hook. * * @param hook Address of the hook contract. */ function hookOnStart(address hook) external view returns (bool) { // 2 is 0x00000010. Determines if the masked bit is enabled. return uint8(2) & hookStatus[hook] != 0; } /** * @notice Determines whether the `onStop()` function is enabled for the hook. * * @param hook Address of the hook contract. */ function hookOnStop(address hook) external view returns (bool) { // 4 is 0x00000100. Determines if the masked bit is enabled. return uint8(4) & hookStatus[hook] != 0; } ///////////////////////////////////////////////////////////////////////////////// // External Functions // ///////////////////////////////////////////////////////////////////////////////// /** * @notice Adds an order hash to storage. Once an order hash is added to storage, * the assets contained within are considered actively rented. Additionally, * rental asset IDs are added to storage which creates a blocklist on those * assets. When the blocklist is active, the protocol guard becomes active on * them and prevents transfer or approval of the assets by the owner of the * safe. * * @param orderHash Hash of the rental order which is added to storage. * @param rentalAssetUpdates Asset update structs which are added to storage. */ function addRentals( bytes32 orderHash, RentalAssetUpdate[] memory rentalAssetUpdates ) external onlyByProxy permissioned { // Add the order to storage. orders[orderHash] = true; // Add the rented items to storage. for (uint256 i = 0; i < rentalAssetUpdates.length; ++i) { RentalAssetUpdate memory asset = rentalAssetUpdates[i]; // Update the order hash for that item. rentedAssets[asset.rentalId] += asset.amount; } } /** * @notice Removes an order hash from storage. Once an order hash is removed from * storage, it can no longer be stopped since the protocol will have no * record of the order. Addtionally, rental asset IDs are removed from * storage. Once these hashes are removed, they are no longer blocklisted * from being transferred out of the rental wallet by the owner. * * @param orderHash Hash of the rental order which will be removed from * storage. * @param rentalAssetUpdates Asset update structs which will be removed from storage. */ function removeRentals( bytes32 orderHash, RentalAssetUpdate[] calldata rentalAssetUpdates ) external onlyByProxy permissioned { // The order must exist to be deleted. if (!orders[orderHash]) { revert Errors.StorageModule_OrderDoesNotExist(orderHash); } else { // Delete the order from storage. delete orders[orderHash]; } // Process each rental asset. for (uint256 i = 0; i < rentalAssetUpdates.length; ++i) { RentalAssetUpdate memory asset = rentalAssetUpdates[i]; // Reduce the amount of tokens for the particular rental ID. rentedAssets[asset.rentalId] -= asset.amount; } } /** * @notice Behaves the same as `removeRentals()`, except that orders are processed in * a loop. * * @param orderHashes All order hashes which will be removed from storage. * @param rentalAssetUpdates Asset update structs which will be removed from storage. */ function removeRentalsBatch( bytes32[] calldata orderHashes, RentalAssetUpdate[] calldata rentalAssetUpdates ) external onlyByProxy permissioned { // Delete the orders from storage. for (uint256 i = 0; i < orderHashes.length; ++i) { // The order must exist to be deleted. if (!orders[orderHashes[i]]) { revert Errors.StorageModule_OrderDoesNotExist(orderHashes[i]); } else { // Delete the order from storage. delete orders[orderHashes[i]]; } } // Process each rental asset. for (uint256 i = 0; i < rentalAssetUpdates.length; ++i) { RentalAssetUpdate memory asset = rentalAssetUpdates[i]; // Reduce the amount of tokens for the particular rental ID. rentedAssets[asset.rentalId] -= asset.amount; } } /** * @notice Adds the addresss of a rental safe to storage so that protocol-deployed * rental safes can be distinguished from those deployed elsewhere. * * @param safe Address of the rental safe to add to storage. */ function addRentalSafe(address safe) external onlyByProxy permissioned { // Get the new safe count. uint256 newSafeCount = totalSafes + 1; // Register the safe as deployed. deployedSafes[safe] = newSafeCount; // Increment nonce. totalSafes = newSafeCount; } /** * @notice Connects a hook to a destination address. Once an active path is made, * any transactions originating from a rental safe to the target address * will use a hook as middleware. The hook chosen is determined by the path * set. * * @param to Target address which will use a hook as middleware. * @param hook Address of the hook which will act as a middleware. */ function updateHookPath(address to, address hook) external onlyByProxy permissioned { // Require that the `to` address is a contract. if (to.code.length == 0) revert Errors.StorageModule_NotContract(to); // Require that the `hook` address is a contract. if (hook.code.length == 0) revert Errors.StorageModule_NotContract(hook); // Point the `to` address to the `hook` address. _contractToHook[to] = hook; } /** * @notice Updates a hook with a bitmap that indicates its active functionality. * A valid bitmap is any decimal value that is less than or equal * to 7 (0x111). * * @param hook Address of the hook contract. * @param bitmap Decimal value that defines the active functionality on the hook. */ function updateHookStatus( address hook, uint8 bitmap ) external onlyByProxy permissioned { // Require that the `hook` address is a contract. if (hook.code.length == 0) revert Errors.StorageModule_NotContract(hook); // 7 is 0x00000111. This ensures that only a valid bitmap can be set. if (bitmap > uint8(7)) revert Errors.StorageModule_InvalidHookStatusBitmap(bitmap); // Update the status of the hook. hookStatus[hook] = bitmap; } /** * @notice Toggles whether an address can be delegate called. * * @param delegate Address which can be delegate called. * @param isEnabled Boolean indicating whether the address is enabled. */ function toggleWhitelistDelegate( address delegate, bool isEnabled ) external onlyByProxy permissioned { whitelistedDelegates[delegate] = isEnabled; } /** * @notice Toggles whether an extension is whitelisted. * * @param extension Gnosis safe module which can be added to a rental safe. * @param isEnabled Boolean indicatingwhether the module is enabled. */ function toggleWhitelistExtension( address extension, bool isEnabled ) external onlyByProxy permissioned { whitelistedExtensions[extension] = isEnabled; } /** * @notice Upgrades the contract to a different implementation. This implementation * contract must be compatible with ERC-1822 or else the upgrade will fail. * * @param newImplementation Address of the implementation contract to upgrade to. */ function upgrade(address newImplementation) external onlyByProxy permissioned { // _upgrade is implemented in the Proxiable contract. _upgrade(newImplementation); } /** * @notice Freezes the contract which prevents upgrading the implementation contract. * There is no way to unfreeze once a contract has been frozen. */ function freeze() external onlyByProxy permissioned { // _freeze is implemented in the Proxiable contract. _freeze(); } } REVIEW FOR ISSUES is contract seems to handle storage for rental orders, rental safes, hooks, and whitelists. Could you tell me more about how these components interact with each other and with external systems? For instance, how does the rental process start, and what are the steps involved?
4d2f28d2ef1e0a549ceb5446ef4f011c
{ "intermediate": 0.41806721687316895, "beginner": 0.24128605425357819, "expert": 0.3406467139720917 }
37,523
import cv2 import torch import numpy as np # Check if CUDA is available and set the default to GPU if possible #device = 'cuda' if torch.cuda.is_available() else 'cpu' #print(f'Using device: {device}') # Load YOLOv5 model model = torch.hub.load('ultralytics/yolov5', 'yolov5s6') model.cuda() # Your supervision library would be used here import supervision as sv # Initialize the camera (0 for default camera, 1 for external cameras, and so on) camera = cv2.VideoCapture(0) # Define the BoxAnnotator from the supervision library box_annotator = sv.BoxAnnotator(thickness=4, text_thickness=4, text_scale=2) # Define the ROI polygon points (clockwise or counter-clockwise) roi_polygon = np.array([ [100, 300], # Point 1 (x1, y1) [300, 200], # Point 2 (x2, y2) [400, 400], # Point 3 (x3, y3) [200, 500] # Point 4 (x4, y4) ], dtype=np.int32) def create_mask(frame, roi_polygon): # Create a black mask with the same dimensions as the frame mask = np.zeros_like(frame, dtype=np.uint8) # Fill the ROI polygon with white color cv2.fillPoly(mask, [roi_polygon], (255, 255, 255)) # Mask the frame to only keep ROI and set everything else to black frame_roi = cv2.bitwise_and(frame, mask) return frame_roi def live_inference(camera): while True: # Capture frame-by-frame from camera ret, frame = camera.read() if not ret: print("Failed to grab frame") break # Convert the image from BGR to RGB frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Apply the ROI mask to the frame frame_roi = create_mask(frame_rgb, roi_polygon) # Perform inference on the masked frame results = model(frame_roi, size=900) detections = sv.Detections.from_yolov5(results) # Set threshold and class filtering as before detections = detections[(detections.class_id == 0) & (detections.confidence > 0.5)] # Annotate detections on the original frame (not the masked one) frame_annotated = box_annotator.annotate(scene=frame_rgb, detections=detections) # Draw the ROI polygon on the annotated frame cv2.polylines(frame_annotated, [roi_polygon], isClosed=True, color=(0, 255, 0), thickness=3) # Get the number of detections within the ROI num_detections = len(detections) # Display the number of detected objects on the frame text = f"Detections in ROI: {num_detections}" cv2.putText(frame_annotated, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA) # Convert the image from RGB to BGR for OpenCV display frame_annotated_bgr = cv2.cvtColor(frame_annotated, cv2.COLOR_RGB2BGR) # Display the resulting frame cv2.imshow('OLOv5 Live Detection', frame_annotated_bgr) # Break the loop if ‘q’ is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture camera.release() cv2.destroyAllWindows() # Run the live inference function live_inference(camera) please help me display the gridlines on the left hand side when running the inference for the video capture
ffe35f782791040cf3fe816f34a3685c
{ "intermediate": 0.34175410866737366, "beginner": 0.5143694877624512, "expert": 0.1438763588666916 }
37,524
déplace la partie logique du endpoint /reserver_billets dans BilletBD avec les modifications nécessaire puis utilise la route reserver_billets qui récupèrera les données data et appelera la fonction dans billetBD : import datetime from flask import Flask, send_file, session from flask_cors import CORS from flask import Flask, request, jsonify, render_template, redirect, url_for from flask_sqlalchemy import SQLAlchemy import sys sys.path.append('../BD') sys.path.append('../mail') from GroupeBD import GroupeBD from LienRS_BD import LienRS_BD from HebergementBD import HebergementBD from Membre_GroupeBD import Membre_GroupeBD from ConnexionBD import ConnexionBD from UserBD import UserBD from emailSender import EmailSender from generateurCode import genererCode from FaqBD import FaqBD from EvenementBD import EvenementBD from Style_MusicalBD import Style_MusicalBD from Groupe_StyleBD import Groupe_StyleBD from ConcertBD import ConcertBD from Activite_AnnexeBD import Activite_AnnexeBD from LieuBD import LieuBD from BilletBD import BilletBD from Type_BilletBD import Type_BilletBD from SpectateurBD import SpectateurBD from InstrumentBD import InstrumentBD from BD import * MAIL_FESTIUTO = "festiuto@gmail.com" MDP_FESTIUTO = "xutxiocjikqolubq" app = Flask(__name__) # app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://coursimault:coursimault@servinfo-mariadb/DBcoursimault' app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/gestiuto' CORS(app, resources={r"/*": {"origins": "*"}}) db = SQLAlchemy(app) app.config['BOOTSTRAP_SERVE_LOCAL'] = True @app.route('/') def index(): return render_template('API.html') @app.route('/getNomsArtistes') def getNomsArtistes(): connexion_bd = ConnexionBD() membre_groupebd = Membre_GroupeBD(connexion_bd) res = membre_groupebd.getNomsArtistes_json() if res is None: return jsonify({"error": "Aucun artiste trouve"}) else: return res @app.route('/getArtistes') def getArtistes(): connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) res = groupebd.get_groupes_json() if res is None: return jsonify({"error": "Aucun artiste trouve"}) else: return res @app.route('/filtrerArtistes') def filtrerArtistes(): connexion_bd = ConnexionBD() evenementbd = EvenementBD(connexion_bd) liste_groupes_21 = evenementbd.groupes_21_juillet_to_json() liste_groupes_22 = evenementbd.groupes_22_juillet_to_json() liste_groupes_23 = evenementbd.groupes_23_juillet_to_json() return jsonify({"21 juillet": liste_groupes_21, "22 juillet": liste_groupes_22, "23 juillet": liste_groupes_23}) @app.route('/getInformationsSupplementairesArtiste/<int:id>') def getInformationsSupplementairesArtiste(id): connexion_bd = ConnexionBD() lienRS = LienRS_BD(connexion_bd) res = lienRS.get_lienRS_json(id) if res is None: return jsonify({"error": "Aucun artiste trouve"}) else: return res @app.route('/getArtiste/<int:id>') def getArtiste(id): connexion_bd = ConnexionBD() membre_groupebd = Membre_GroupeBD(connexion_bd) mb = membre_groupebd.get_artiste_by_id(id) res = mb.to_dict() return jsonify({"error": "Aucun artiste trouve"}) if res is None else res @app.route('/connecter', methods=['POST']) def connecter(): connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) data = request.get_json() print(data) email = data["email"] password = data["password"] if userbd.exist_user(email, password): return userbd.user_to_json(userbd.get_user_by_email(email)) else: return jsonify({"error": "Utilisateur non trouve"}) @app.route('/inscription', methods=['POST']) def inscription(): connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) data = request.get_json() print(data) pseudo = data["pseudo"] email = data["email"] password = data["password"] if userbd.exist_user(email, password): return jsonify({"error": "Utilisateur déjà existant"}) else: res = userbd.add_user(pseudo, email, password) if res: user = userbd.get_user_by_email(email) if user is not None: return userbd.user_to_json(user) else: return jsonify({"error": "Utilisateur ajouté mais non retrouvé"}) # Nouvelle gestion d’erreur elif res == "emailErr": return jsonify({"error": "Email déjà existant"}) else: return jsonify({"error": "Erreur lors de l’ajout de l’utilisateur"}) @app.route('/modifierProfil', methods=['POST']) def modifierProfil(): connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) data = request.get_json() print(data) idUser =data['id'] pseudo = data["pseudo"] email = data["email"] password = data["password"] ancien_mdp = data['oldPassword'] if userbd.exist_user_with_id(idUser, ancien_mdp): res = userbd.update_user(idUser, email, pseudo, password) if res: return userbd.user_to_json(userbd.get_user_by_email(email)) elif res == "emailErr": return jsonify({"error": "Email déjà existant"}) else: return jsonify({"error": "Erreur lors de la modification de l'utilisateur"}) else: return jsonify({"error": "Utilisateur non trouve"}) @app.route('/envoyerCodeVerification', methods=['POST']) def envoyerCodeVerification(): data = request.get_json() emailUser = data["email"] connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) if not userbd.email_exists(emailUser): return jsonify({"error": "Email non existant"}) code = genererCode() email_sender = EmailSender(MAIL_FESTIUTO, MDP_FESTIUTO) res = email_sender.sendCodeVerification(emailUser, code) if res: resAjout = userbd.ajouterCodeVerification(emailUser, code) if resAjout: return jsonify({"success": "code envoyé"}) return jsonify({"error": "erreur lors de l'envoi du code"}) @app.route('/testerCodeVerification', methods=['POST']) def tester_code_verification(): data = request.get_json() emailUser = data["email"] code = data["code"] connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) if not userbd.email_exists(emailUser): return jsonify({"error": "Email non existant"}) if userbd.tester_code_verification(emailUser, code): return jsonify({"success": "code correct"}) else: return jsonify({"error": "code incorrect"}) @app.route("/modifierMdp", methods=['POST']) def modifierMdp(): data = request.get_json() emailUser = data["email"] nouveauMdp = data["password"] code = data["code"] connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) if not userbd.email_exists(emailUser): return jsonify({"error": "Email non existant"}) if userbd.tester_code_verification(emailUser, code): res = userbd.update_password(emailUser, nouveauMdp) if res: return jsonify({"success": "mot de passe modifié"}) else: return jsonify({"error": "erreur lors de la modification du mot de passe"}) @app.route('/ajouterImage', methods=['POST']) def ajouterImage(): # permet de stocker l'image dans la base de données sous forme de blob idG = request.form['idG'] image_file = request.files['img'] if image_file: image = image_file.read() connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) res = groupebd.add_image(idG, image) if res: return jsonify({"success": "image ajoutée"}) return jsonify({"error": "erreur lors de l'ajout de l'image"}) import io @app.route('/getImageArtiste/<int:id>') def getImageArtiste(id): #get l'image en blob de l'artiste et l'affiche try: connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) image_blob = groupebd.get_image(id) if image_blob is None: return jsonify({"error": "Aucune image trouve"}) else: image = io.BytesIO(image_blob) image.seek(0) return send_file(image, mimetype='image/jpeg') except Exception as e: print(e) return jsonify({"error": "erreur lors de la récupération de l'image"}) @app.route('/getFaq') def get_faq(): connexion_bd = ConnexionBD() faqbd = FaqBD(connexion_bd) res = faqbd.get_faqs_json() if res is None: return jsonify({"error": "Aucune faq trouve"}) else: return res @app.route("/recherche/", methods=["GET", "POST"]) def recherche(): if request.method == "POST": recherche = request.form.get("recherche", "") else: recherche = request.args.get("recherche", "") connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) membre_groupebd = Membre_GroupeBD(connexion_bd) groupes = groupebd.search_groupes(recherche) if recherche else [] artistes = membre_groupebd.search_membres_groupe(recherche) if recherche else [] return render_template("recherche.html", recherche=recherche, groupes=groupes, artistes=artistes) @app.route("/styles_musicaux", methods=["GET", "POST"]) def filtrer_styles(): connexion_bd = ConnexionBD() style_musicalbd = Style_MusicalBD(connexion_bd) styles_musicaux = style_musicalbd.get_all_styles() liste_groupes = [] if request.method == "POST": nomStyle = request.form.get("nomStyle", "") idStyle = style_musicalbd.get_id_style_by_name(nomStyle) if idStyle is not None: groupe_stylebd = Groupe_StyleBD(connexion_bd) liste_groupes = groupe_stylebd.get_groupes_selon_style(idStyle) return render_template("styles_musicaux.html", styles_musicaux=styles_musicaux, liste_groupes=liste_groupes) @app.route("/menu_admin/", methods=["GET", "POST"]) def menu_admin(): return render_template("menu_admin.html") @app.route("/login_admin") def login_admin(): return render_template("login.html") @app.route("/groupes_festival") def groupes_festival(): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) liste_groupes = groupebd.get_all_groupes() if liste_groupes is None: liste_groupes = [] return render_template("groupes_festival.html", liste_groupes=liste_groupes) @app.route("/hebergements_festival") def hebergements_festival(): connexionbd = ConnexionBD() hebergementbd = HebergementBD(connexionbd) liste_hebergements = hebergementbd.get_all_hebergements() if liste_hebergements is None: liste_hebergements = [] return render_template("hebergements_festival.html", liste_hebergements=liste_hebergements) @app.route("/modifier_groupe", methods=["POST"]) def modifier_groupe(): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) id_groupe = request.form["id_groupe"] nom_groupe = request.form["nom_groupe"] description_groupe = request.form["description_groupe"] groupe = groupebd.get_groupe_by_id(id_groupe) groupe.set_nomG(nom_groupe) groupe.set_descriptionG(description_groupe) groupebd.modifier_img(id_groupe, request.files['image_groupe'].read()) succes = groupebd.update_groupe(groupe) if succes: print(f"Le groupe {id_groupe} a été mis à jour.") else: print(f"La mise à jour du groupe {id_groupe} a échoué.") return redirect(url_for("groupes_festival")) @app.route("/modifier_hebergement", methods=["POST"]) def modifier_hebergement(): connexionbd = ConnexionBD() hebergementbd = HebergementBD(connexionbd) id_hebergement = request.form["id_hebergement"] nom_hebergement = request.form["nom_hebergement"] adresse_hebergement = request.form["adresse_hebergement"] limite_places_hebergement = request.form["limite_places"] hebergement = hebergementbd.get_hebergement_by_id(id_hebergement) hebergement.set_nomH(nom_hebergement) hebergement.set_adresseH(adresse_hebergement) hebergement.set_limitePlacesH(limite_places_hebergement) succes = hebergementbd.update_hebergement(hebergement) if succes: print(f"L'hebergement {id_hebergement} a été mis à jour.") else: print(f"La mise à jour de l'hebergement {id_hebergement} a échoué.") return redirect(url_for("hebergements_festival")) @app.route("/supprimer_groupe", methods=["POST"]) def supprimer_groupe(): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) id_groupe = request.form["id_groupe"] groupe = groupebd.get_groupe_by_id(id_groupe) nom_groupe = groupe.get_nomG() groupebd.delete_groupe_by_name(groupe, nom_groupe) return redirect(url_for("groupes_festival")) @app.route("/supprimer_hebergement", methods=["POST"]) def supprimer_hebergement(): connexionbd = ConnexionBD() hebergementbd = HebergementBD(connexionbd) id_hebergement = request.form["id_hebergement"] hebergementbd.delete_hebergement_by_id(id_hebergement) return redirect(url_for("hebergements_festival")) @app.route("/ajouter_groupe", methods=["POST"]) def ajouter_groupe(): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) nom_groupe = request.form["nom_nouveau_groupe"] if request.form["nom_nouveau_groupe"] else None description_groupe = request.form["description_nouveau_groupe"] if request.form["description_nouveau_groupe"] else None groupe = Groupe(None, None, nom_groupe, description_groupe) groupebd.insert_groupe(groupe) idG = groupebd.get_id_groupe_by_name(nom_groupe) image_file = request.files['image_nouveau_groupe'] if image_file: image = image_file.read() connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) res = groupebd.add_image(idG, image) if (res): print("image ajoutée") else: print("erreur lors de l'ajout de l'image") return redirect(url_for("groupes_festival")) @app.route("/ajouter_hebergement", methods=["POST"]) def ajouter_hebergement(): connexionbd = ConnexionBD() hebergementbd = HebergementBD(connexionbd) nom_hebergement = request.form["nom_nouveau_hebergement"] adresse_hebergement = request.form["adresse_hebergement"] limite_places_hebergement = request.form["limite_places"] hebergement = Hebergement(None, nom_hebergement, limite_places_hebergement, adresse_hebergement) hebergementbd.insert_hebergement(hebergement) return redirect(url_for("hebergements_festival")) @app.route("/consulter_groupe/<int:id_groupe>") def consulter_groupe(id_groupe): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) groupe = groupebd.get_groupe_by_id(id_groupe) membres_groupe = groupebd.get_membres_groupe(id_groupe) if not membres_groupe: return render_template("membres_groupe.html", groupe=groupe, membres_groupe=[]) return render_template("membres_groupe.html", groupe=groupe, membres_groupe=membres_groupe) @app.route("/consulter_hebergement/<int:id_hebergement>") def consulter_hebergement(id_hebergement): connexionbd = ConnexionBD() hebergementbd = HebergementBD(connexionbd) hebergement = hebergementbd.get_hebergement_by_id(id_hebergement) groupes_hebergement = hebergementbd.get_groupes_hebergement(id_hebergement) groupes_not_in_hebergement = hebergementbd.get_groupes_not_in_hebergement(id_hebergement) dict_groupes_not_in_hebergement = {} for groupe in groupes_not_in_hebergement: id_hebergement_groupe = groupe.get_idHebergement() nom_hebergement_groupe = hebergementbd.get_hebergement_by_id(id_hebergement_groupe).get_nomH() if id_hebergement_groupe is not None else None dict_groupes_not_in_hebergement[groupe] = nom_hebergement_groupe return render_template("groupes_hebergement.html", hebergement=hebergement, groupes_hebergement=groupes_hebergement, dict_groupes_not_in_hebergement=dict_groupes_not_in_hebergement) @app.route("/modifier_membre", methods=["POST"]) def modifier_membre_groupe(): connexionbd = ConnexionBD() membre_groupebd = Membre_GroupeBD(connexionbd) nom_membre_groupe = request.form["nom_membre"] prenom_membre_groupe = request.form["prenom_membre"] nom_scene_membre_groupe = request.form["nom_scene_membre"] id_membre_groupe = request.form["id_membre"] membre_groupe = membre_groupebd.get_artiste_by_id(id_membre_groupe) membre_groupe.set_nomMG(nom_membre_groupe) membre_groupe.set_prenomMG(prenom_membre_groupe) membre_groupe.set_nomDeSceneMG(nom_scene_membre_groupe) succes = membre_groupebd.update_membre_groupe(membre_groupe) if succes: print(f"Le membre {id_membre_groupe} a été mis à jour.") else: print(f"La mise à jour du membre {id_membre_groupe} a échoué.") return redirect(url_for("consulter_groupe", id_groupe=membre_groupe.get_idGroupe())) @app.route("/supprimer_membre", methods=["POST"]) def supprimer_membre_groupe(): connexionbd = ConnexionBD() membre_groupebd = Membre_GroupeBD(connexionbd) id_membre_groupe = request.form["id_membre"] membre_groupe = membre_groupebd.get_artiste_by_id(id_membre_groupe) nom_scene_membre_groupe = membre_groupe.get_nomDeSceneMG() membre_groupebd.delete_membre_groupe_by_name_scene(membre_groupe, nom_scene_membre_groupe) return redirect(url_for("consulter_groupe", id_groupe=membre_groupe.get_idGroupe())) @app.route("/supprimer_groupe_hebergement", methods=["POST"]) def supprimer_groupe_hebergement(): connexionbd = ConnexionBD() groupebd = GroupeBD(connexionbd) id_hebergement = request.form["id_hebergement"] id_groupe = request.form["id_groupe"] groupe = groupebd.get_groupe_by_id(id_groupe) groupe.set_idHebergement(None) print(groupe.get_idHebergement()) groupebd.update_groupe(groupe) return redirect(url_for("consulter_hebergement", id_hebergement=id_hebergement)) @app.route("/ajouter_membre", methods=["POST"]) def ajouter_membre_groupe(): connexionbd = ConnexionBD() membre_groupebd = Membre_GroupeBD(connexionbd) id_groupe = request.form["id_groupe"] nom_membre_groupe = request.form["nom_nouveau_membre"] if request.form["nom_nouveau_membre"] else None prenom_membre_groupe = request.form["prenom_nouveau_membre"] if request.form["prenom_nouveau_membre"] else None nom_scene_membre_groupe = request.form["nom_scene_nouveau_membre"] if request.form["nom_scene_nouveau_membre"] else None membre_groupe = Membre_Groupe(None, id_groupe, nom_membre_groupe, prenom_membre_groupe, nom_scene_membre_groupe) membre_groupebd.insert_membre_groupe(membre_groupe) return redirect(url_for("consulter_groupe", id_groupe=id_groupe)) @app.route("/ajouter_groupe_hebergement", methods=["POST"]) def ajouter_groupe_hebergement(): connexion_bd = ConnexionBD() groupebd = GroupeBD(connexion_bd) id_groupe = request.form["nom_groupe"] id_hebergement = request.form["id_hebergement"] groupe = groupebd.get_groupe_by_id(id_groupe) groupe.set_idHebergement(id_hebergement) groupebd.update_groupe(groupe) return redirect(url_for("consulter_hebergement", id_hebergement=id_hebergement)) @app.route("/evenements_festival") def evenements_festival(): connexionbd = ConnexionBD() evenementbd = EvenementBD(connexionbd) groupebd = GroupeBD(connexionbd) liste_groupes = groupebd.get_all_groupes() liste_evenements = evenementbd.get_all_evenements() liste_evenements_concerts = [] liste_evenements_activites_annexes = [] if not liste_evenements: return render_template("evenements_festival.html", liste_evenements=[], liste_evenements_concerts=[], liste_evenements_activites_annexes=[], liste_lieux=[], liste_groupes=[]) lieubd = LieuBD(connexionbd) liste_lieux = lieubd.get_all_lieux() for evenement in liste_evenements: if evenementbd.verify_id_in_concert(evenement.get_idE()): liste_evenements_concerts.append(evenement) elif evenementbd.verify_id_in_activite_annexe(evenement.get_idE()): liste_evenements_activites_annexes.append(evenement) return render_template("evenements_festival.html", liste_evenements=liste_evenements, liste_evenements_concerts=liste_evenements_concerts, liste_evenements_activites_annexes=liste_evenements_activites_annexes, liste_lieux=liste_lieux, liste_groupes=liste_groupes) @app.route("/modifier_evenement", methods=["POST"]) def modifier_evenement(): connexionbd = ConnexionBD() evenementbd = EvenementBD(connexionbd) id_evenement = request.form["id_evenement"] id_lieu = request.form["lieu_evenement"] if request.form["lieu_evenement"] else None id_groupe = request.form["groupe_evenement"] if request.form["groupe_evenement"] else None nom_evenement = request.form["nom_evenement"] date_debut = request.form["date_debut"] date_fin = request.form["date_fin"] heure_debut = request.form["heure_debut"] heure_fin = request.form["heure_fin"] evenement = evenementbd.get_evenement_by_id(id_evenement) evenement.set_idG(id_groupe) evenement.set_idL(id_lieu) evenement.set_nomE(nom_evenement) evenement.set_dateDebutE(date_debut) evenement.set_dateFinE(date_fin) evenement.set_heureDebutE(heure_debut) evenement.set_heureFinE(heure_fin) succes = evenementbd.update_evenement(evenement) if succes: print(f"L'événement {id_evenement} a été mis à jour.") else: print(f"La mise à jour de l'événement {id_evenement} a échoué.") return redirect(url_for("evenements_festival")) @app.route("/supprimer_evenement", methods=["POST"]) def supprimer_evenement(): connexionbd = ConnexionBD() evenementbd = EvenementBD(connexionbd) concert_bd = ConcertBD(connexionbd) id_evenement = request.form["id_evenement"] evenement = evenementbd.get_evenement_by_id(id_evenement) nom_evenement = evenement.get_nomE() if evenementbd.verify_id_in_concert(id_evenement): concert_bd.delete_concert_by_id(id_evenement) elif evenementbd.verify_id_in_activite_annexe(id_evenement): activite_annexe_bd = Activite_AnnexeBD(connexionbd) activite_annexe_bd.delete_activite_annexe_by_id(id_evenement) evenementbd.delete_evenement_by_name(evenement, nom_evenement) return redirect(url_for("evenements_festival")) @app.route("/ajouter_evenement", methods=["POST"]) def ajouter_evenement(): connexionbd = ConnexionBD() evenementbd = EvenementBD(connexionbd) id_lieu = request.form["lieu_evenement"] if request.form["lieu_evenement"] else None id_groupe = request.form["groupe_evenement"] if request.form["groupe_evenement"] else None nom_evenement = request.form["nom_evenement"] if request.form["nom_evenement"] else None date_debut = request.form["date_debut"] if request.form["date_debut"] else None date_fin = request.form["date_fin"] if request.form["date_fin"] else None heure_debut = request.form["heure_debut"] if request.form["heure_debut"] else None heure_fin = request.form["heure_fin"] if request.form["heure_fin"] else None evenement = Evenement(None, id_groupe, id_lieu, nom_evenement, heure_debut, heure_fin, date_debut, date_fin) id_evenement = evenementbd.insert_evenement(evenement) type_evenement = request.form["type_evenement"] if type_evenement == "concert": temps_montage = request.form["temps_montage"] if request.form["temps_montage"] else None temps_demontage = request.form["temps_demontage"] if request.form["temps_demontage"] else None concert_bd = ConcertBD(connexionbd) concert = Concert(id_evenement, temps_montage, temps_demontage) concert_bd.insert_concert(concert) elif type_evenement == "activite": type_activite = request.form["type_activite"] if request.form["type_activite"] else None ouvert_public = True if "ouvert_public" in request.form else False print(ouvert_public) activite_annexebd = Activite_AnnexeBD(connexionbd) activite_annexe = Activite_Annexe(id_evenement, type_activite, ouvert_public) print(activite_annexe.get_ouvertAuPublic()) activite_annexebd.insert_activite_annexe(activite_annexe) return redirect(url_for("evenements_festival")) @app.route("/billets_festival") def billets_festival(): connexionbd = ConnexionBD() billetbd = BilletBD(connexionbd) liste_billets = billetbd.get_all_billets() if not liste_billets: return render_template("admin_billets.html", liste_billets=[]) return render_template("admin_billets.html", liste_billets=liste_billets) @app.route("/lieux_festival") def lieux_festival(): connexionbd = ConnexionBD() lieubd = LieuBD(connexionbd) liste_lieux = lieubd.get_all_lieux() if not liste_lieux: return render_template("admin_lieux.html", liste_lieux=[]) return render_template("admin_lieux.html", liste_lieux=liste_lieux) @app.route("/types_billet_festival") def types_billet_festival(): connexionbd = ConnexionBD() type_billetbd = Type_BilletBD(connexionbd) liste_types_billet = type_billetbd.get_all_types_billets() if not liste_types_billet: return render_template("admin_types_billet.html", liste_types_billet=[]) return render_template("admin_types_billet.html", liste_types_billet=liste_types_billet) @app.route("/spectateurs_festival") def spectateurs_festival(): connexionbd = ConnexionBD() spectateurbd = SpectateurBD(connexionbd) liste_spectateurs = spectateurbd.get_all_spectateurs() if not liste_spectateurs: return render_template("admin_spectateurs.html", liste_spectateurs=[]) return render_template("admin_spectateurs.html", liste_spectateurs=liste_spectateurs) @app.route("/styles_musicaux_festival") def styles_musicaux_festival(): connexionbd = ConnexionBD() style_musicalbd = Style_MusicalBD(connexionbd) liste_styles_musicaux = style_musicalbd.get_all_styles() if not liste_styles_musicaux: return render_template("admin_styles.html", liste_styles_musicaux=[]) return render_template("admin_styles.html", liste_styles_musicaux=liste_styles_musicaux) @app.route("/instruments_festival") def instruments_festival(): connexionbd = ConnexionBD() instrumentbd = InstrumentBD(connexionbd) liste_instruments = instrumentbd.get_all_instruments() if not liste_instruments: return render_template("admin_instruments.html", liste_instruments=[]) return render_template("admin_instruments.html", liste_instruments=liste_instruments) @app.route("/users_festival") def users_festival(): connexionbd = ConnexionBD() userbd = UserBD(connexionbd) liste_users = userbd.get_all_users() if not liste_users: return render_template("admin_users.html", liste_users=[]) return render_template("admin_users.html", liste_users=liste_users) @app.route("/ajouter_user", methods=["POST"]) def ajouter_user(): connexionbd = ConnexionBD() userbd = UserBD(connexionbd) pseudo_user = request.form["pseudo_user"] email_user = request.form["email_user"] mdp_user = request.form["mdp_user"] statut_user = request.form["statut_user"] user = User(None, pseudo_user, mdp_user, email_user, statut_user) userbd.insert_user_admin(user) return redirect(url_for("users_festival")) @app.route("/supprimer_user", methods=["POST"]) def supprimer_user(): connexionbd = ConnexionBD() userbd = UserBD(connexionbd) id_user = request.form["id_user"] userbd.delete_user_by_id(id_user) return redirect(url_for("users_festival")) @app.route("/modifier_user", methods=["POST"]) def modifier_user(): connexionbd = ConnexionBD() userbd = UserBD(connexionbd) id_user = request.form["id_user"] pseudo_user = request.form["pseudo_user"] email_user = request.form["email_user"] mdp_user = request.form["mdp_user"] user = userbd.get_user_by_id(id_user) user.set_pseudoUser(pseudo_user) user.set_emailUser(email_user) user.set_mdpUser(mdp_user) success = userbd.update_user_admin(user) if success: print(f"L'utilisateur {id_user} a été mis à jour.") else: print(f"La mise à jour de l'utilisateur {id_user} a échoué.") return redirect(url_for("users_festival")) @app.route('/reserver_billets', methods=['POST']) def reserver_billets(): connexion_bd = ConnexionBD() userbd = UserBD(connexion_bd) billet_bd = BilletBD(connexion_bd) data = request.get_json() print(f"data: {data}") idUser= data[0]['id'] data = request.get_json() billets_a_ajouter = [] for billet_json in data: date_debut_b = datetime.strptime(billet_json['selectedDaysSortedString'].split('-')[0], '%d %b %Y').date() if billet_json['selectedDaysSortedString'] else None date_fin_b = datetime.strptime(billet_json['selectedDaysSortedString'].split('-')[1], '%d %b %Y').date() if billet_json['selectedDaysSortedString'] else None id_festival = 1 # Exemple d'ajout des billets à la base de données for i in range(billet_json['quantity']): idBilletDisponible = billet_bd.billet_id_dispo() billet = Billet( idB = idBilletDisponible, idF=id_festival, idType=billet_json['id'], idS=idUser, prix=billet_json['price'], dateAchat=datetime.utcnow(), dateDebutB=date_debut_b, dateFinB=date_fin_b) billets_a_ajouter.append(billet) print(f"billets_a_ajouter: {billets_a_ajouter}") # print billets_a_ajouter db.session.add_all(billets_a_ajouter) db.session.commit()from BD import Billet from ConnexionBD import ConnexionBD from sqlalchemy.sql.expression import text from sqlalchemy.exc import SQLAlchemyError class BilletBD: def __init__(self, conx: ConnexionBD): self.connexion = conx def get_all_billets(self): try: query = text("SELECT idB, idF, idType, idS, prix, dateAchat, dateDebutB, dateFinB FROM BILLET") result = self.connexion.get_connexion().execute(query) liste_billets = [] for idB, idF, idType, idS, prix, dateAchat, dateDebutB, dateFinB in result: liste_billets.append(Billet(idB, idF, idType, idS, prix, dateAchat, dateDebutB, dateFinB)) return liste_billets except SQLAlchemyError as e: print(f"La requête a échoué : {e}") def get_billets_spectateur(self, idFestival, idType, idSpectateur): try: query = text("SELECT idB, idF, idType, idS, prix, dateAchat, dateDebutB, dateFinB FROM BILLET WHERE idF = :idFestival AND idType = :idType AND idS = :idSpectateur") billets = [] result = self.connexion.get_connexion().execute(query, {"idFestival": idFestival, "idType": idType, "idSpectateur": idSpectateur}) for idB, idF, idType, idS, prix, dateAchat, dateDebutB, dateFinB in result: billets.append(Billet(idB, idF, idType, idS, prix, dateAchat, dateDebutB, dateFinB)) return billets except SQLAlchemyError as e: print(f"La requête a échoué : {e}") def insert_billet(self, billet): try: query = text("INSERT INTO billet (idF, idType, idS, prix, dateAchat, dateDebutB, dateFinB) VALUES (:idF, :idType, :idS, :prix, :dateAchat, :dateDebutB, :dateFinB)") result = self.connexion.get_connexion().execute(query, {"idF": billet.get_idFestival(), "idType": billet.get_idType(), "idS": billet.get_idSpectateur(), "prix": billet.get_prix(), "dateAchat": billet.get_dateAchat(), "dateDebutB": billet.get_dateDebutB(), "dateFinB": billet.get_dateFinB()}) billet_id = result.lastrowid print(f"Le billet {billet_id} a été ajouté") self.connexion.get_connexion().commit() except SQLAlchemyError as e: print(f"La requête a échoué : {e}") def delete_billet_by_id_spectateur(self, billet, id_spectateur): try: query = text("DELETE FROM billet WHERE idB = :idB AND idS = :idS") self.connexion.get_connexion().execute(query, {"idB": billet.get_idB(), "idS": id_spectateur}) print(f"Le billet {billet.get_idB()} a été supprimé") self.connexion.get_connexion().commit() except SQLAlchemyError as e: print(f"La requête a échoué : {e}") def billet_id_dispo(self): try: query = text("SELECT MAX(idB) FROM BILLET") result = self.connexion.get_connexion().execute(query) max_id = result.fetchone()[0] if max_id is None: return 1 return max_id + 1 except SQLAlchemyError as e: print(f"La requête a échoué : {e}") return None
c8a15903dd7e9fc4e15c74d28131fc78
{ "intermediate": 0.42586150765419006, "beginner": 0.40024489164352417, "expert": 0.17389358580112457 }
37,525
def calcUpdate(self, planets): for planet in planets: d = (planet.pos - self.pos).magnitude() if d != 0: # Planet calculating update for itself magnitude = G * planet.mass * self.mass / (d * d) angle = math.atan2(planet.pos.x - self.pos.x, planet.pos.y - self.pos.y) * 180 / math.pi self.vel.x = magnitude * math.cos(angle) self.vel.y = magnitude * math.sin(angle) Can you fix this gravity siulation code?
0ece3a469c1f34d7f46df1d1faf65e10
{ "intermediate": 0.45009645819664, "beginner": 0.2271518111228943, "expert": 0.3227517306804657 }
37,526
make a javascript script that runs from the browser console that fills in mat-input-4 with a randomly generated gmail address, and the mat-input-5 input with a preset password, for now, "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1"
d6a526dedc7476d60f1e38fde43b0582
{ "intermediate": 0.3742082715034485, "beginner": 0.24243760108947754, "expert": 0.38335418701171875 }
37,527
How do I programmically use the screen reader
20af1e4e6c0a04e126d30c98ffb8aa2c
{ "intermediate": 0.23287038505077362, "beginner": 0.465109258890152, "expert": 0.3020203411579132 }
37,528
make me a simple python program to index all of folder content
1f34bb11eed94fbc07481c2928fb3906
{ "intermediate": 0.5148090124130249, "beginner": 0.1830359846353531, "expert": 0.3021549582481384 }
37,529
Can you show me some advanced examples of "Cinema 4D Redshift OSL Shader" codes please?
c4bcbb0626e16bc63b8558ae8c0a96b8
{ "intermediate": 0.35667985677719116, "beginner": 0.0875345841050148, "expert": 0.555785596370697 }
37,530
import os import glob import random from tkinter import Tk, Button, filedialog, Label from PIL import Image # Supported image extensions IMAGE_EXTENSIONS = [‘.jpg’, ‘.jpeg’, ‘.png’, ‘.gif’, ‘.bmp’, ‘.webp’] class ImageIndexerApp: def init(self, root): self.root = root self.root.title(“Image Indexer”) self.open_button = Button(self.root, text=“Open Folder”, command=self.on_open_folder) self.open_button.pack() self.next_button = Button(self.root, text=“Next Image”, command=self.next_image, state=‘disabled’) self.next_button.pack() self.random_button = Button(self.root, text=“Random Image”, command=self.random_image, state=‘disabled’) self.random_button.pack() self.total_images_label = Label(self.root, text=“Total images: 0”) self.total_images_label.pack() # Initialize index and file list self.current_image_index = 0 self.image_files = [] def is_image(self, filename): try: Image.open(filename) # Attempt to open the image file using Pillow return True except (IOError, FileNotFoundError): return False def on_open_folder(self): directory = filedialog.askdirectory() if not directory: return self.image_files = self.list_images(directory) self.current_image_index = 0 # Reset index self.total_images_label.config(text=f"Total images: {len(self.image_files)}“) # Enable next and random buttons only if there are images if self.image_files: self.next_button.config(state=‘normal’) self.random_button.config(state=‘normal’) def next_image(self): if self.image_files: print(f”{self.current_image_index + 1}: {self.image_files[self.current_image_index]}“) self.current_image_index = (self.current_image_index + 1) % len(self.image_files) def random_image(self): if self.image_files: self.current_image_index = random.randint(0, len(self.image_files) - 1) print(f”{self.current_image_index + 1}: {self.image_files[self.current_image_index]}“) def list_images(self, directory): images = [] for extension in IMAGE_EXTENSIONS: images.extend(glob.glob(os.path.join(directory, f”*{extension}"))) images = [img for img in images if self.is_image(img)] return images if name == ‘main’: root = Tk() app = ImageIndexerApp(root) root.mainloop() add a previous button that print the image called previously, as opposed to the previous file in the index. change current_image_index to img_num. then make add a "random" checkbox that will make the next image button call random image in the index instead of going linearly. make it so that when i press previous while the "random" checkbox is on, it returns to the previously called image, and before that, and so on, instead of going to the previous file on the index, but only when the random checkbox is deactivated, it calls the previous image in the index list. make sure to add comments to explain each method and important parts
c02b681efbcb8646fa4caee549877ba4
{ "intermediate": 0.2969985604286194, "beginner": 0.5916916131973267, "expert": 0.11130982637405396 }
37,531
make a custom roblox code that when the map is picked and whoever is tagged has a ball and they have to click to throw the ball to someone, if they miss the ball goes back to them, if they hit someone, the ball goes to the other person and gets tagged
38afe2c8c9b3237a13e5d1b8a08db625
{ "intermediate": 0.2691912353038788, "beginner": 0.11657101660966873, "expert": 0.6142377853393555 }
37,532
import os import glob import random from tkinter import Tk, Button, filedialog, Label, Checkbutton, IntVar from PIL import Image # Supported image extensions IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'] class ImageIndexerApp: def __init__(self, root): self.root = root self.root.title("Image Indexer") self.open_button = Button(self.root, text="Open Folder", command=self.on_open_folder) self.open_button.pack() self.next_button = Button(self.root, text="Next Image", command=self.next_image, state='disabled') self.next_button.pack() self.prev_button = Button(self.root, text="Previous Image", command=self.prev_image, state='disabled') self.prev_button.pack() self.random_button = Button(self.root, text="Random Image", command=self.random_image, state='disabled') self.random_button.pack() self.total_images_label = Label(self.root, text="Total images: 0") self.total_images_label.pack() # Label to show the count of images displayed self.img_count_label = Label(self.root, text="Images shown: 0") self.img_count_label.pack() self.random_mode = IntVar() self.random_checkbox = Checkbutton(self.root, text="Random", variable=self.random_mode) self.random_checkbox.pack() self.limit_mode = IntVar() self.limit_checkbox = Checkbutton(self.root, text="Limit to 20", variable=self.limit_mode) self.limit_checkbox.pack() self.img_num = 0 self.image_files = [] self.image_history = [] self.random_pool = [] # Store images not yet shown in random mode self.img_count = 0 # Counter for images shown self.img_limit = 20 # Restrict to 20 images def is_image(self, filename): """Check if a file is an image that can be opened.""" try: Image.open(filename) return True except (IOError, FileNotFoundError): return False def on_open_folder(self): """Open a directory and list all valid image files.""" directory = filedialog.askdirectory() if not directory: return self.image_files = self.list_images(directory) self.img_num = 0 self.image_history = [] self.random_pool = self.image_files.copy() self.img_count = 0 self.total_images_label.config(text=f"Total images: {len(self.image_files)}") self.update_img_count_label() if self.image_files: # Enable buttons after directory is loaded self.next_button.config(state='normal') self.prev_button.config(state='normal') self.random_button.config(state='normal') def next_image(self): """Display the next image in a linear or random fashion without repetition.""" if not self.image_files or (self.limit_mode.get() and self.img_count >= self.img_limit): return if not self.random_mode.get(): # Linear mode self.img_num = (self.img_num + 1) % len(self.image_files) else: # Random mode without repetition if not self.random_pool: self.shuffle_images() self.img_num = self.random_pool.pop(0) # Get the next image index from the shuffled pool self.display_image(add_to_history=True) self.img_count += 1 self.update_img_count_label() def prev_image(self): """Display the previous image from the history, or in a linear/random fashion if empty.""" if self.image_history: # Use history to go back self.img_num = self.image_history.pop() else: if self.random_mode.get(): # Random mode without repetition if not self.random_pool: self.shuffle_images() self.img_num = self.random_pool.pop(0) else: # Linear mode self.img_num = (self.img_num - 1) % len(self.image_files) self.display_image(add_to_history=False) def shuffle_images(self): """Shuffle the image files for random mode.""" self.random_pool = list(range(len(self.image_files))) random.shuffle(self.random_pool) # Shuffle the indexes def random_image(self): """Selects a random image from the pool and displays it.""" if self.image_files: if not self.random_pool: self.random_pool = self.image_files.copy() self.img_num = random.choice(self.random_pool) self.random_pool.remove(self.img_num) self.display_image(add_to_history=True) def display_image(self, add_to_history): """Display the current image and update the history if required.""" # Fixed the TypeError: now using the index to access the image file current_file = self.image_files[self.img_num] print(f"{self.img_num + 1}: {current_file}") if add_to_history: # Add the current index to the history, not the file itself self.image_history.append(self.img_num) # Potential code to actually show the image if desired - Replace the print statement # image = Image.open(current_file) # image.show() self.prev_button.config(state='normal') # Always enable 'Previous' button def update_img_count_label(self): """Update the label that shows the count of images displayed.""" self.img_count_label.config(text=f"Images shown: {self.img_count}") def list_images(self, directory): """List all the image files in a given directory.""" images = [] for extension in IMAGE_EXTENSIONS: images.extend(glob.glob(os.path.join(directory, f"*{extension}"))) images = [img for img in images if self.is_image(img)] return images if __name__ == '__main__': root = Tk() app = ImageIndexerApp(root) root.mainloop() it returns the following error: line 128, in display_image current_file = self.image_files[self.img_num] ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^ TypeError: list indices must be integers or slices, not str
f3f9bc7a0ae54a891ff7a40454a5337e
{ "intermediate": 0.3022982180118561, "beginner": 0.5819537043571472, "expert": 0.11574811488389969 }
37,533
import os import glob import random from tkinter import Tk, Button, filedialog, Label, Checkbutton, IntVar from PIL import Image # Supported image extensions IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'] class ImageIndexerApp: def __init__(self, root): self.root = root self.root.title("Image Indexer") self.open_button = Button(self.root, text="Open Folder", command=self.on_open_folder) self.open_button.pack() self.next_button = Button(self.root, text="Next Image", command=self.next_image, state='disabled') self.next_button.pack() self.prev_button = Button(self.root, text="Previous Image", command=self.prev_image, state='disabled') self.prev_button.pack() self.total_images_label = Label(self.root, text="Total images: 0") self.total_images_label.pack() # Label to show the count of images displayed self.img_count_label = Label(self.root, text="Images shown: 0") self.img_count_label.pack() self.random_mode = IntVar() self.random_checkbox = Checkbutton(self.root, text="Random", variable=self.random_mode) self.random_checkbox.pack() self.limit_mode = IntVar() self.limit_checkbox = Checkbutton(self.root, text="Limit to 20", variable=self.limit_mode) self.limit_checkbox.pack() self.img_num = 0 self.image_files = [] self.image_history = [] self.random_pool = [] # Store images not yet shown in random mode self.img_count = 0 # Counter for images shown self.img_limit = 20 # Restrict to 20 images def is_image(self, filename): """Check if a file is an image that can be opened.""" try: Image.open(filename) return True except (IOError, FileNotFoundError): return False def on_open_folder(self): """Open a directory and list all valid image files.""" directory = filedialog.askdirectory() if not directory: return self.image_files = self.list_images(directory) # This is your existing code. # Right after loading image files and before setting the index to 0: # Initialize random_pool with a list of indices self.random_pool = list(range(len(self.image_files))) # Reset the current image index self.img_num = 0 self.image_history = [] # Initialize random_pool with indices self.random_pool = list(range(len(self.image_files))) if self.random_mode.get() else [] self.img_count = 0 self.total_images_label.config(text=f"Total images: {len(self.image_files)}") self.update_img_count_label() if self.image_files: # Enable buttons after directory is loaded self.next_button.config(state='normal') self.prev_button.config(state='normal') def next_image(self): """Display the next image in a linear or random fashion without repetition.""" if not self.image_files or (self.limit_mode.get() and self.img_count >= self.img_limit): return # Check if random_mode is enabled if self.random_mode.get(): # Random mode without repetition if not self.random_pool: self.shuffle_images() # Prepare pool if it's not already set self.img_num = self.random_pool.pop(0) # Get the next image index from the pool else: # Linear mode self.img_num = (self.img_num + 1) % len(self.image_files) self.display_image(add_to_history=True) self.img_count += 1 self.update_img_count_label() # Check if 'Previous' button should be enabled self.prev_button.config(state='normal' if self.image_history else 'disabled') def prev_image(self): """Display the previous image from the history, or in a linear/random fashion if empty.""" if self.image_history: # Use history to go back self.img_num = self.image_history.pop() else: if self.random_mode.get(): # Random mode without repetition if not self.random_pool: self.shuffle_images() self.img_num = self.random_pool.pop(0) else: # Linear mode self.img_num = (self.img_num - 1) % len(self.image_files) self.display_image(add_to_history=False) def shuffle_images(self): """Shuffle the image files for random mode.""" # Shuffle the indices, not the files self.random_pool = list(range(len(self.image_files))) random.shuffle(self.random_pool) def random_image(self): """Selects a random image from the pool and displays it.""" if not self.image_files or (self.limit_mode.get() and self.img_count >= self.img_limit): return if not self.random_pool: self.shuffle_images() # Make sure random_pool has indices # Pop a random index from the random pool self.img_num = self.random_pool.pop(random.randrange(len(self.random_pool))) self.display_image(add_to_history=True) self.img_count += 1 self.update_img_count_label() def display_image(self, add_to_history): """Display the current image and update the history if required.""" # Fixed the TypeError: now using the index to access the image file current_file = self.image_files[self.img_num] print(f"{self.img_num + 1}: {current_file}") if add_to_history: # Add the current index to the history, not the file itself self.image_history.append(self.img_num) # Potential code to actually show the image if desired - Replace the print statement # image = Image.open(current_file) # image.show() self.prev_button.config(state='normal') # Always enable 'Previous' button def update_img_count_label(self): """Update the label that shows the count of images displayed.""" self.img_count_label.config(text=f"Images shown: {self.img_count}") def list_images(self, directory): """List all the image files in a given directory.""" images = [] for extension in IMAGE_EXTENSIONS: images.extend(glob.glob(os.path.join(directory, f"*{extension}"))) images = [img for img in images if self.is_image(img)] return images if __name__ == '__main__': root = Tk() app = ImageIndexerApp(root) root.mainloop() make it so that when the limit is clicked, it sets the limits for the following images after it is set, after the current image, then prints "end of image yr done". instead of stopping the program when the total image that has been shown is 20 also when i press previous three times, when the history is like: 1. 2. 3. *previous press* it returns 1. 2. 3. *previous press* 2. 1. make sure it calls
af3bc44c6bcd3a8dfd9c06fdb56024c7
{ "intermediate": 0.3154275119304657, "beginner": 0.5632245540618896, "expert": 0.12134788185358047 }
37,534
<a class="btn btn-primary" type="button" href="/items/{restaurantDetails.RestUsername}"> weiter zur Speisekarte</a> why doesnt this code work? Im using svelte. Which is the right syntax for dynamic links?
9b53f6d84248a1e1851debd82a908b7b
{ "intermediate": 0.5116881728172302, "beginner": 0.35100266337394714, "expert": 0.13730914890766144 }
37,535
class ImageIndexerApp: def __init__(self, root): self.root = root self.root.title("Image Indexer") self.open_button = Button(self.root, text="Open Folder", command=self.on_open_folder) self.open_button.pack() self.next_button = Button(self.root, text="Next Image", command=self.next_image, state='disabled') self.next_button.pack() self.prev_button = Button(self.root, text="Previous Image", command=self.prev_image, state='disabled') self.prev_button.pack() self.total_images_label = Label(self.root, text="Total images: 0") self.total_images_label.pack() # Label to show the count of images displayed self.img_count_label = Label(self.root, text="Images shown: 0") self.img_count_label.pack() self.random_mode = IntVar() self.random_checkbox = Checkbutton(self.root, text="Random", variable=self.random_mode) self.random_checkbox.pack() self.limit_mode = IntVar() self.limit_checkbox = Checkbutton(self.root, text="Limit to 20", variable=self.limit_mode) self.limit_checkbox.pack() self.img_num = 0 self.image_files = [] self.image_history = [] self.random_pool = [] # Store images not yet shown in random mode self.img_count = 0 # Counter for images shown self.img_limit = 20 # Restrict to 20 images def is_image(self, filename): """Check if a file is an image that can be opened.""" try: Image.open(filename) return True except (IOError, FileNotFoundError): return False def on_open_folder(self): """Open a directory and list all valid image files.""" directory = filedialog.askdirectory() if not directory: return self.image_files = self.list_images(directory) # This is your existing code. # Right after loading image files and before setting the index to 0: # Initialize random_pool with a list of indices self.random_pool = list(range(len(self.image_files))) # Reset the current image index self.img_num = 0 self.image_history = [] # Initialize random_pool with indices self.random_pool = list(range(len(self.image_files))) if self.random_mode.get() else [] self.img_count = 0 self.total_images_label.config(text=f"Total images: {len(self.image_files)}") self.update_img_count_label() if self.image_files: # Enable buttons after directory is loaded self.next_button.config(state='normal') self.prev_button.config(state='normal') def next_image(self): """Display the next image in a linear or random fashion without repetition.""" if not self.image_files or (self.limit_mode.get() and self.img_count >= self.img_limit): return # Check if random_mode is enabled if self.random_mode.get(): # Random mode without repetition if not self.random_pool: self.shuffle_images() # Prepare pool if it's not already set self.img_num = self.random_pool.pop(0) # Get the next image index from the pool else: # Linear mode self.img_num = (self.img_num + 1) % len(self.image_files) self.display_image(add_to_history=True) self.img_count += 1 self.update_img_count_label() # Check if 'Previous' button should be enabled self.prev_button.config(state='normal' if self.image_history else 'disabled') def prev_image(self): """Display the previous image from the history, or in a linear/random fashion if empty.""" if self.image_history: # Use history to go back self.img_num = self.image_history.pop() else: if self.random_mode.get(): # Random mode without repetition if not self.random_pool: self.shuffle_images() self.img_num = self.random_pool.pop(0) else: # Linear mode self.img_num = (self.img_num - 1) % len(self.image_files) self.display_image(add_to_history=False) def shuffle_images(self): """Shuffle the image files for random mode.""" # Shuffle the indices, not the files self.random_pool = list(range(len(self.image_files))) random.shuffle(self.random_pool) def random_image(self): """Selects a random image from the pool and displays it.""" if not self.image_files or (self.limit_mode.get() and self.img_count >= self.img_limit): return if not self.random_pool: self.shuffle_images() # Make sure random_pool has indices # Pop a random index from the random pool self.img_num = self.random_pool.pop(random.randrange(len(self.random_pool))) self.display_image(add_to_history=True) self.img_count += 1 self.update_img_count_label() def display_image(self, add_to_history): """Display the current image and update the history if required.""" # Fixed the TypeError: now using the index to access the image file current_file = self.image_files[self.img_num] print(f"{self.img_num + 1}: {current_file}") if add_to_history: # Add the current index to the history, not the file itself self.image_history.append(self.img_num) # Potential code to actually show the image if desired - Replace the print statement # image = Image.open(current_file) # image.show() self.prev_button.config(state='normal') # Always enable 'Previous' button def update_img_count_label(self): """Update the label that shows the count of images displayed.""" self.img_count_label.config(text=f"Images shown: {self.img_count}") def list_images(self, directory): """List all the image files in a given directory.""" images = [] for extension in IMAGE_EXTENSIONS: images.extend(glob.glob(os.path.join(directory, f"*{extension}"))) images = [img for img in images if self.is_image(img)] return images make it so that when the limit is clicked, it sets the limits for the following images after it is set, after the current image, then prints “end of image it's 20”. instead of stopping the program when the total image that has been shown is 20. but if i press previous let it call the previous number going back 1 number for the limit. until i pres next again, after 20 again, then return "end of image yr done it's 20" message. and when the next button is clicked after, the limit is on and reached it just goes to another limit cycle. another 20
c1d6274545281ea98dbe858ecf01011e
{ "intermediate": 0.2820955812931061, "beginner": 0.5744332671165466, "expert": 0.14347116649150848 }
37,536
J'ai ce fichier html : {% block styles %} <link rel="stylesheet" href="{{ url_for('static', filename='admin_billets.css') }}"> {% endblock %} {% block content%} <a id="retour" href="{{ url_for('menu_admin') }}" class="btn-retour">Retour</a> <h1>Les billets du festival</h1> <table> <thead> <tr> <th>id Billet</th> <th>id Type</th> <th>id Spectateur</th> <th>prix</th> <th>date d'achat</th> <th>date de début</th> <th>date de fin</th> <th>Actions</th> </tr> </thead> <tbody> {% for billet in liste_billets %} <tr> <td> {{ billet.get_idB() }} </td> <td> {{ billet.get_idType() }} </td> <td> {{ billet.get_idSpectateur() }} </td> <td> {{ billet.get_prix() }} </td> <td> {{ billet.get_dateAchat() }} </td> <td> {{ billet.get_dateDebutB() }} </td> <td> {{ billet.get_dateFinB() }} </td> <td> <button class="btn-modifier" data-id="{{ billet.get_idB() }}" data-idType="{{ billet.get_idType() }}" data-idSpectateur="{{ billet.get_idSpectateur() }}" data-prix="{{ billet.get_prix() }}" data-dateAchat="{{ billet.get_dateAchat() }}" data-dateDebutB="{{ billet.get_dateDebutB() }}" data-dateFinB="{{ billet.get_dateFinB() }}">Modifier <button class="btn-supprimer" data-id="{{ billet.get_idB() }}">Supprimer</button> </td> </tr> {% endfor %} </tbody> </table> <button id="ajouter">Ajouter</button> <!-- Modale pour modifier un billet --> <div id="modal-modifier" class="modal"> <div class="modal-content"> <span class="close-button">x</span> <form action="modifier_billet" method="POST"> <input type="hidden" name="id_billet" id="id_billet_modifier"> <select name="type_billet" id="y=type_billet_modifier" required> <option value="" disabled selected>Choisir un type de billet</option> {% for type in liste_types %} <option value="{{ type.get_idType() }}">{{ type.get_duree() }}</option> {% endfor %} </select> <select name="spectateur_billet" id="spectateur_billet_modifier" required> <option value="" disabled selected>Choisir un spectateur</option> {% for spectateur in liste_spectateurs %} <option value="{{ spectateur.get_idS() }}">{{ spectateur.get_nomS() }}</option> {% endfor %} </select> <label for="prix">prix</label> <input type="text" name="prix" id="prix_modifier" required> <label for="dateAchat">date d'achat</label> <input type="text" name="date_achat" id="date_achat_modifier" required> <label for="dateDebutB">date de début</label> <input type="text" name="date_debutB" id="date_debutB_modifirer" required> <label for="dateFinB">date de fin</label> <input type="text" name="date_finB" id="date_finB_modifier" required> <button id="modifier" type="submit"> Modifier </button> </form> </div> </div> <!-- Modale pour supprimer un évènement --> <div id ="modal-supprimer" class="modal"> <div class="modal-content"> <span class="close-button">x</span> <form action="/supprimer_billet" method="POST"> <input type="hidden" name="id_billet" id="id_billet_supprimer"> <p>Êtes-vous sûr de vouloir supprimer ce billet ?</p> <button id="supprimer" type="submit"> Supprimer </button> </form> </div> </div> <!-- Modale pour ajouter un billet --> <div id="modal-ajouter" class="modal"> <div class="modal-content"> <span class="close-button">x</span> <form action="/ajouter_billet" method="POST"> <label for="type_billet">Type de billet</label> <select name="type_billet" id="type_billet_ajouter" required> <option value="" disabled selected>Choisir un type de billet</option> {% for type in liste_types %} <option value="{{ type.get_idType() }}">{{ type.get_duree() }}</option> {% endfor %} </select> <select name="spectateur_billet" id="spectateur_billet_ajouter" required> <option value="" disabled selected>Choisir un spectateur</option> {% for spectateur in liste_spectateurs %} <option value="{{ spectateur.get_idS() }}">{{ spectateur.get_nomS() }}</option> {% endfor %} </select> <label for="prix">prix</label> <input type="text" name="prix" id="prix_ajouter" required> <label for="dateAchat">date d'achat</label> <input type="date" name="date_achat" id="date_achat_ajouter" required> <label for="date_debutB">date de début</label> <input type="date" name="date_debut" id="date_debutB_ajouter" max="2024-07-23" min="2024-07-21" required> <label for="date_finB">date de fin</label> <input type="date" name="date_fin" id="date_finB_ajouter" max="2024-07-23" min="2024-07-21" required> <button class="btn-ajouter" type="submit"> Ajouter </button> </form> </div> </div> <script> document.addEventListener("DOMContentLoaded", function() { var modalModifier = document.getElementById("modal-modifier"); var modalSupprimer = document.getElementById("modal-supprimer"); var modalAjouter = document.getElementById("modal-ajouter"); var btnClose = document.querySelectorAll(".close-button"); btnClose.forEach(function(btn) { btn.onclick = function() { btn.closest(".modal").style.display = "none"; }; }); document.querySelectorAll(".btn-modifier").forEach(function(btn) { btn.onclick = function() { modalModifier.style.display = "block"; document.querySelector("id_billet_modifier").value = btn.getAttribute("data-id"); document.querySelector("type_billet_modifier").value = btn.getAttribute("data-idType"); document.querySelector("id_spectateur_modifier").value = btn.getAttribute("data-idSpectateur"); document.querySelector("prix_modifier").value = btn.getAttribute("data-prix"); document.querySelector("date_achat_modifier").value = btn.getAttribute("data-dateAchat"); document.querySelector("date_debutB_modifirer").value = btn.getAttribute("data-dateDebutB"); document.querySelector("date_finB_modifier").value = btn.getAttribute("data-dateFinB"); }; }); document.querySelectorAll(".btn-supprimer").forEach(function(btn) { btn.onclick = function() { modalSupprimer.style.display = "block"; document.querySelector("id_billet_supprimer").value = btn.getAttribute("data-id"); }; }); document.getElementById("ajouter").onclick = function() { modalAjouter.style.display = "block"; }; window.onclick = function(event) { if (event.target.classList.contains("modal")) { event.target.style.display = "none"; } } }); </script> {% endblock %} cette vue : @app.route("/supprimer_billet", methods=["POST"]) def supprimer_billet(): connexionbd = ConnexionBD() billetbd = BilletBD(connexionbd) id_billet = request.form["id_billet"] billetbd.delete_billet_by_id(id_billet) return redirect(url_for("billets_festival")) et cette fonction : def delete_billet_by_id(self, id_billet): try: query = text("DELETE FROM billet WHERE idB = :idB") self.connexion.get_connexion().execute(query, {"idB": id_billet}) self.connexion.get_connexion().commit() print(f"Le billet {id_billet} a été supprimé") return True except SQLAlchemyError as e: print(f"La requête a échoué : {e}") return False pourtant quand je clique sur le bouton supprimer ça ne fait rien, pourquoi ? j'ai aussi cette bd : CREATE DATABASE IF NOT EXISTS `FESTIUTO` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE FESTIUTO; CREATE TABLE FAQ ( idFaq INT NOT NULL AUTO_INCREMENT, question VARCHAR(9999) NOT NULL, reponse VARCHAR(9999) NOT NULL, PRIMARY KEY(idFaq) ); CREATE TABLE USER( idUser INT NOT NULL AUTO_INCREMENT, pseudoUser VARCHAR(99) NOT NULL UNIQUE, mdpUser VARCHAR(9999) NOT NULL, codeTempUser VARCHAR(6), emailUser VARCHAR(99) UNIQUE, PRIMARY KEY(idUser) ); CREATE TABLE FESTIVAL ( idF INT NOT NULL AUTO_INCREMENT, nomF VARCHAR(50) NOT NULL, villeF VARCHAR(50) NOT NULL, dateDebutF DATE NOT NULL, dateFinF DATE NOT NULL, PRIMARY KEY (idF) ); CREATE TABLE BILLET ( idB INT NOT NULL AUTO_INCREMENT, idF INT NOT NULL, idType INT NOT NULL, idS INT NOT NULL, prix INT, dateAchat DATE NOT NULL, dateDebutB DATE NOT NULL CHECK (dateDebutB <= dateFinB), dateFinB DATE NOT NULL CHECK (dateFinB >= dateDebutB), PRIMARY KEY (idB) ); CREATE TABLE TYPE_BILLET ( idType INT NOT NULL AUTO_INCREMENT, duree INT NOT NULL CHECK (duree > 0), PRIMARY KEY (idType) ); CREATE TABLE SPECTATEUR ( idS INT NOT NULL AUTO_INCREMENT, nomS VARCHAR(50) NOT NULL, prenomS VARCHAR(50) NOT NULL, adresseS VARCHAR(50) NOT NULL, emailS VARCHAR(50) NOT NULL, mdpS VARCHAR(50) NOT NULL, PRIMARY KEY (idS) ); CREATE TABLE LIEU ( idL INT NOT NULL AUTO_INCREMENT, idF INT NOT NULL, nomL VARCHAR(50) NOT NULL, adresseL VARCHAR(50) NOT NULL, jaugeL INT NOT NULL CHECK (jaugeL > 0), PRIMARY KEY (idL) ); CREATE TABLE PROGRAMMER ( idF INT NOT NULL, idG INT NOT NULL, idH INT NOT NULL, dateArrivee DATE NOT NULL, heureArrivee TIME NOT NULL, dateDepart DATE NOT NULL, heureDepart TIME NOT NULL, PRIMARY KEY (idF, idG, idH) ); CREATE TABLE HEBERGEMENT ( idH INT NOT NULL AUTO_INCREMENT, nomH VARCHAR(50) NOT NULL, limitePlacesH INT NOT NULL CHECK (limitePlacesH > 0), adresseH VARCHAR(50) NOT NULL, PRIMARY KEY (idH) ); CREATE TABLE GROUPE ( idG INT NOT NULL AUTO_INCREMENT, idH INT, nomG VARCHAR(50) NOT NULL, descriptionG VARCHAR(50) NOT NULL, imgG LONGBLOB, PRIMARY KEY (idG) ); CREATE TABLE MEMBRE_GROUPE ( idMG INT NOT NULL AUTO_INCREMENT, idG INT NOT NULL, nomMG VARCHAR(50) NOT NULL, prenomMG VARCHAR(50) NOT NULL, nomDeSceneMG VARCHAR(50) NOT NULL, PRIMARY KEY (idMG) ); CREATE TABLE INSTRUMENT ( idI INT NOT NULL AUTO_INCREMENT, idMG INT NOT NULL, nomI VARCHAR(50) NOT NULL, PRIMARY KEY (idI) ); CREATE TABLE STYLE_MUSICAL ( idSt INT NOT NULL AUTO_INCREMENT, nomSt VARCHAR(50) NOT NULL, PRIMARY KEY (idSt) ); CREATE TABLE LIEN_VIDEO ( idLV INT NOT NULL AUTO_INCREMENT, idG INT NOT NULL, video VARCHAR(50), PRIMARY KEY (idLV) ); CREATE TABLE LIEN_RESEAUX_SOCIAUX ( idLRS INT NOT NULL AUTO_INCREMENT, idG INT NOT NULL, reseau VARCHAR(50), PRIMARY KEY (idLRS) ); CREATE TABLE EVENEMENT ( idE INT NOT NULL AUTO_INCREMENT, idG INT, idL INT, nomE VARCHAR(50) NOT NULL, heureDebutE TIME NOT NULL CHECK (heureDebutE < heureFinE), heureFinE TIME NOT NULL CHECK (heureFinE > heureDebutE), dateDebutE DATE NOT NULL CHECK (dateDebutE <= dateFinE), dateFinE DATE NOT NULL CHECK (dateFinE >= dateDebutE), PRIMARY KEY (idE) ); CREATE TABLE ACTIVITE_ANNEXE ( idE INT NOT NULL, typeA VARCHAR(50) NOT NULL, ouvertAuPublic BOOLEAN NOT NULL, PRIMARY KEY (idE) ); CREATE TABLE CONCERT ( idE INT NOT NULL, tempsMontage TIME NOT NULL, tempsDemontage TIME NOT NULL, PRIMARY KEY (idE) ); CREATE TABLE GROUPE_STYLE ( idG INT NOT NULL, idSt INT NOT NULL, PRIMARY KEY (idG, idSt), FOREIGN KEY (idG) REFERENCES GROUPE (idG), FOREIGN KEY (idSt) REFERENCES STYLE_MUSICAL (idSt) ); ALTER TABLE BILLET ADD FOREIGN KEY (idF) REFERENCES FESTIVAL (idF); ALTER TABLE BILLET ADD FOREIGN KEY (idType) REFERENCES TYPE_BILLET (idType); ALTER TABLE BILLET ADD FOREIGN KEY (idS) REFERENCES SPECTATEUR (idS); ALTER TABLE LIEU ADD FOREIGN KEY (idF) REFERENCES FESTIVAL (idF); ALTER TABLE PROGRAMMER ADD FOREIGN KEY (idF) REFERENCES FESTIVAL (idF); ALTER TABLE PROGRAMMER ADD FOREIGN KEY (idG) REFERENCES GROUPE (idG); ALTER TABLE PROGRAMMER ADD FOREIGN KEY (idH) REFERENCES HEBERGEMENT (idH); ALTER TABLE HEBERGEMENT ADD FOREIGN KEY (idG) REFERENCES GROUPE (idG); ALTER TABLE MEMBRE_GROUPE ADD FOREIGN KEY (idG) REFERENCES GROUPE (idG); ALTER TABLE INSTRUMENT ADD FOREIGN KEY (idMG) REFERENCES MEMBRE_GROUPE (idMG); ALTER TABLE LIEN_VIDEO ADD FOREIGN KEY (idG) REFERENCES GROUPE (idG); ALTER TABLE LIEN_RESEAUX_SOCIAUX ADD FOREIGN KEY (idG) REFERENCES GROUPE (idG); ALTER TABLE ACTIVITES_ANNEXES ADD FOREIGN KEY (idE) REFERENCES EVENEMENT (idE); ALTER TABLE CONCERT ADD FOREIGN KEY (idE) REFERENCES EVENEMENT (idE); ALTER TABLE EVENEMENT ADD FOREIGN KEY (idG) REFERENCES GROUPE (idG); ALTER TABLE EVENEMENT ADD FOREIGN KEY (idL) REFERENCES LIEU (idL); -- Les Fonctions DELIMITER | CREATE OR REPLACE FUNCTION getNbBilletsVendus(idFestival INT) RETURNS INT BEGIN IF NOT EXISTS (SELECT * FROM FESTIVAL WHERE idF = idFestival) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "Le festival n'existe pas"; END IF; DECLARE nbBillets INT; SELECT COUNT(*) INTO nbBillets FROM BILLET WHERE idF = idFestival; RETURN nbBillets; END | DELIMITER ; DELIMITER | CREATE OR REPLACE FUNCTION getGroupesByStyle(nomStyle VARCHAR(50)) RETURNS INT BEGIN IF NOT EXISTS (SELECT * FROM STYLE_MUSICAL WHERE nomSt = nomStyle) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "Le style musical n'existe pas"; END IF; DECLARE idStyleMusical INT; SELECT idSt INTO idStyleMusical FROM STYLE_MUSICAL WHERE nomSt = nomStyle; RETURN (SELECT COUNT(*) FROM GROUPE WHERE idSt = idStyleMusical); END | DELIMITER ; DELIMITER | CREATE OR REPLACE FUNCTION getPrixTotalBilletSpec(idSpectateur INT) RETURNS INT BEGIN IF NOT EXISTS (SELECT * FROM SPECTATEUR WHERE idS = idSpectateur) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "Le spectateur n'existe pas"; END IF; DECLARE totalPrix INT; SELECT SUM(prix) INTO totalPrix FROM BILLET WHERE idS = idSpectateur; RETURN totalPrix; END | DELIMITER ; DELIMITER | CREATE OR REPLACE FUNCTION majPrixBillet(idBillet INT, nouveauPrix INT) BEGIN IF NOT EXISTS (SELECT * FROM BILLET WHERE idB = idBillet) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "Le billet n'existe pas"; END IF; UPDATE BILLET SET prix = nouveauPrix WHERE idB = idBillet; END | DELIMITER ; -- Les procédures DELIMITER | CREATE OR REPLACE PROCEDURE listeFestivals() BEGIN DECLARE resultat VARCHAR (500) DEFAULT 'Liste des festivals : \n'; DECLARE fini INT DEFAULT false ; DECLARE idFest INT ; DECLARE nomFest VARCHAR (50) ; DECLARE villeFest VARCHAR (50) ; DECLARE dateDebutFest DATE ; DECLARE dateFinFest DATE ; DECLARE nbFest INT DEFAULT 0; DECLARE lm CURSOR FOR select idF , nomF , villeF, dateDebutF, dateFinF from FESTIVAL; DECLARE continue handler for not found set fini = true ; open lm; while not fini do fetch lm into idFest , nomFest , villeFest, dateDebutFest, dateFinFest; if not fini then set nbFest = nbFest +1; set resultat = concat(resultat , 'festival id', idFest, ' : ', nomFest, ' à ', villeFest, ' du ', dateDebutFest, ' au ', dateFinFest, '\n'); end if; end while; close lm; set resultat = concat(resultat, 'Il y a ', nbFest , ' festival(s) en tout \n') ; select resultat ; END | DELIMITER ; CALL listeFestivals(); -- Les triggers -- BILLET : -- Trigger pour vérifier la date d'achat par rapport à la fin du festival delimiter | create or replace trigger billetAchetable before insert on BILLET for each row begin declare dateFinFestival DATE; select dateFinF into dateFinFestival from FESTIVAL where idF = new.idF; if (new.dateAchat > dateFinFestival) then SIGNAL SQLSTATE '45000' set MESSAGE_TEXT = "Impossible d'acheter un billet pour un événement qui a déjà eu lieu"; end if; end | delimiter ; -- Trigger pour vérifier la durée du billet par rapport à la durée du festival delimiter | create or replace trigger dureeTypeBillet before insert on BILLET for each row begin declare dureeType INT; declare dateDebutFestival DATE; declare dateFinFestival DATE; select duree into dureeType from TYPE_BILLET where idType = new.idType; select dateDebutF into dateDebutFestival from FESTIVAL where idF = new.idF; select dateFinF into dateFinFestival from FESTIVAL where idF = new.idF; if (dureeType > (DATEDIFF(dateFinFestival, dateDebutFestival))) then SIGNAL SQLSTATE '45000' set MESSAGE_TEXT = "La durée du billet est trop grande par rapport à celle du festival"; end if; end | delimiter ; -- Trigger pour vérifier la date d'arrivée du groupe par rapport à la date de début du festival delimiter | create or replace trigger dateArriveeHebergement before insert on PROGRAMMER for each row begin declare dateDebutFestival DATE; declare dateFinFestival DATE; select dateDebutF into dateDebutFestival from FESTIVAL where idF = new.idF; select dateFinF into dateFinFestival from FESTIVAL where idF = new.idF; if (new.dateArrivee < dateDebutFestival) then SIGNAL SQLSTATE '45000' set MESSAGE_TEXT = "Le groupe ne peut pas arriver avant le début du festival"; end if; end | delimiter ; -- Trigger pour vérifier la date d'arrivée du groupe par rapport à la date de fin du festival delimiter | create or replace trigger groupeArriveTropTardHebergement before insert on PROGRAMMER for each row begin declare dateArriveeGroupe DATE; declare dateFinFestival DATE; select dateArrivee into dateArriveeGroupe from PROGRAMMER where idF = new.idF and idL = new.idL and idH = new.idH; select dateFinF into dateFinFestival from FESTIVAL where idF = new.idF; if (dateArriveeGroupe > dateFinFestival) then SIGNAL SQLSTATE '45000' set MESSAGE_TEXT = "Le groupe ne peut pas arriver après la fin du festival"; end if; end | delimiter ; -- Trigger pour vérifier si le lieu existe déjà pour ce festival delimiter | create or replace trigger memeNomLieuFestival before insert on LIEU for each row begin if exists (select 1 from LIEU where idF = new.idF and nomL = new.nomL) then SIGNAL SQLSTATE '45000' set MESSAGE_TEXT = "Un lieu avec le même nom existe déjà pour ce festival"; end if; end | delimiter ; -- Trigger pour vérifier si un hébergement avec la même adresse existe déjà delimiter | create or replace trigger memeNomAdresseHebergement before insert on HEBERGEMENT for each row begin if exists (select 1 from HEBERGEMENT where nomH = new.nomH and adresseH = new.adresseH) then SIGNAL SQLSTATE '45000' set MESSAGE_TEXT = "Un hébergement avec le même nom et la même adresse existe déjà"; end if; end | delimiter ; -- Trigger pour vérifier si un membre avec le même nom et prénom existe déjà dans ce groupe delimiter | create or replace trigger memeNomPrenomMembreGroupe before insert on MEMBRE_GROUPE for each row begin if exists (select 1 from MEMBRE_GROUPE where idG = new.idG and nomMG = new.nomMG and prenomMG = new.prenomMG and nomDeSceneMG = new.nomDeSceneMG) then SIGNAL SQLSTATE '45000' set MESSAGE_TEXT = "Un membre avec le même nom et prénom existe déjà dans ce groupe"; end if; end | delimiter ; -- Trigger pour vérifier si un style musical avec le même nom existe déjà delimiter | create or replace trigger memeNomStyleMusical before insert on STYLE_MUSICAL for each row begin if exists (select 1 from STYLE_MUSICAL where nomSt = new.nomSt) then SIGNAL SQLSTATE '45000' set MESSAGE_TEXT = "Un style musical avec le même nom existe déjà"; end if; end | delimiter ; -- Trigger pour vérifier si un type de billet avec la même durée existe déjà delimiter | create or replace trigger memeDureeTypeBillet before insert on TYPE_BILLET for each row begin if exists (select 1 from TYPE_BILLET where duree = new.duree) then SIGNAL SQLSTATE '45000' set MESSAGE_TEXT = "Un type de billet avec la même durée existe déjà"; end if; end | delimiter ; delimiter | create or replace trigger emailDejaUtilise before insert on SPECTATEUR for each row begin if exists (select 1 from SPECTATEUR where emailS = new.emailS) then SIGNAL SQLSTATE '45000' set MESSAGE_TEXT = "Cet email est déjà associé à un compte"; end if; end | delimiter ; delimiter | CREATE TRIGGER lieuDejaUtiliseDurantHoraire BEFORE INSERT ON EVENEMENT FOR EACH ROW BEGIN DECLARE conflitTrouve INT DEFAULT 0; DECLARE tempsDemontageConcert TIME; DECLARE finEvenement TIME; SELECT IFNULL(MAX(c.tempsDemontage), '00:00:00') INTO tempsDemontageConcert FROM CONCERT c JOIN EVENEMENT e ON c.idE = e.idE WHERE e.idL = NEW.idL AND e.dateDebutE <= NEW.dateDebutE AND e.dateFinE >= NEW.dateDebutE AND ADDTIME(e.heureFinE, c.tempsDemontage) > NEW.heureDebutE; SELECT COUNT(*) INTO conflitTrouve FROM EVENEMENT e WHERE e.idL = NEW.idL AND e.dateDebutE = NEW.dateDebutE AND ( (e.heureDebutE < NEW.heureFinE AND e.heureFinE > NEW.heureDebutE) OR (ADDTIME(e.heureFinE, tempsDemontageConcert) > NEW.heureDebutE) ); IF conflitTrouve > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "Un événement ou concert est déjà prévu à ce lieu et cet horaire."; END IF; END | delimiter ; DELIMITER | CREATE TRIGGER verifDisponibiliteGroupe BEFORE INSERT ON EVENEMENT FOR EACH ROW BEGIN DECLARE conflitExistant INT DEFAULT 0; DECLARE tempsMontageConcert TIME; IF NEW.idE IN (SELECT idE FROM CONCERT) THEN SET tempsMontageConcert := (SELECT tempsMontage FROM CONCERT WHERE idE = NEW.idE); ELSE SET tempsMontageConcert := '00:00:00'; END IF; SELECT COUNT(*) INTO conflitExistant FROM EVENEMENT e LEFT JOIN CONCERT c ON e.idE = c.idE WHERE e.idG = NEW.idG AND e.dateDebutE = NEW.dateDebutE AND ( (NEW.heureDebutE < ADDTIME(e.heureFinE, IFNULL(c.tempsDemontage, '00:00:00'))) OR (ADDTIME(NEW.heureDebutE, tempsMontageConcert) > e.heureDebutE AND ADDTIME(NEW.heureDebutE, tempsMontageConcert) < e.heureFinE) ); IF conflitExistant > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "Le groupe a déjà un événement prévu qui entre en conflit avec le nouvel horaire."; END IF; END | DELIMITER ;
25933e9a64e86864ee3c277a807b6ddd
{ "intermediate": 0.4163295030593872, "beginner": 0.4574471116065979, "expert": 0.1262233555316925 }
37,537
controller.request(new GetVersionRequest()).onSuccess(System.out::println).queue(); How do I print text in a one liner like this, but instead of using ::, it's "Hi!"
77addbd5aa039aa8cb471fc5e93206d2
{ "intermediate": 0.23902450501918793, "beginner": 0.6292365193367004, "expert": 0.13173899054527283 }
37,538
How do I fire a completablefuture after a certain delay
b23f3d12d5009f6854708ec46b1b488e
{ "intermediate": 0.3403814733028412, "beginner": 0.1459861695766449, "expert": 0.5136323571205139 }
37,539
How do I fire a completablefuture after a delay
7e0186191e0f08fa6642bc890ff1ac84
{ "intermediate": 0.3841609060764313, "beginner": 0.149321049451828, "expert": 0.4665180742740631 }
37,540
Почему в коде ниже не вызывается move конструктор #include <vector>> struct Person { string name{}; int age = 0; int* massive = nullptr; int len_m=0; Person() : name{ "No_name" }, age{ -1 }, massive{ new int[10] {100} }, len_m(10) {}; ~Person() { delete[] massive; massive = nullptr; } Person(const Person& other) : name(other.name), age(other.age), len_m(other.len_m), massive(nullptr) //копирование () - память не инициализирована, оператора присваивания - уже есть во что копировать { cout << "copy" << endl; if (other.massive != nullptr) { massive = new int[len_m]; for (int i = 0; i < len_m; i++) { massive[i] = other.massive[i]; } } } Person& operator=(const Person& other) { cout << "copy op=" << endl; if (&other != this) { name = other.name; age = other.age; len_m = other.len_m; massive = new int[len_m]; for (int i = 0; i < len_m; i++) { massive[i] = other.massive[i]; } } return *this; } Person(Person&& moved) noexcept { cout << "move()" << endl; name = moved.name; age = moved.age; len_m = moved.len_m; massive = moved.massive; moved.massive = nullptr; } Person& operator=(Person&& moved)noexcept { cout << "move=" << endl; if (&moved != this) { delete[] this->massive; name = moved.name; age = moved.age; len_m = moved.len_m; massive = moved.massive; moved.massive = nullptr; } return *this; } }; int main() { /*Animal* dog = new Dog; delete dog;*/ vector<Person*> v; for (int i = 0; i < 5; i++) { Person* t = new Person; cout << t->massive[0] << endl; v.push_back(move(t)); cout<<t->massive[0]<<endl; //v.push_back(new Person); }
d228be3af01a9024348956fde8c02539
{ "intermediate": 0.32705923914909363, "beginner": 0.48716622591018677, "expert": 0.185774564743042 }
37,541
Give me py code to compute and find the reciprocal function for a given function f(x) and determine if it is bijective or not in the first place
fc7f10d2cc29472a0f379bf62d08a26e
{ "intermediate": 0.34705811738967896, "beginner": 0.08313334733247757, "expert": 0.5698085427284241 }
37,542
Please check this documentation for Cinema 4D Redshift OSL Shaders: OSL Introduction OSL stands for Open Shading Language and allows to write your own shader descriptions, that can be shared between other renderers that also offer OSL support. OSL scripts can be loaded as files or written directly inside the shader dialog. You can find out more about OSL on this website: https://github.com/AcademySoftwareFoundation/OpenShadingLanguage and some Redshift compatible OSL shaders here: https://github.com/redshift3d/RedshiftOSLShaders OSL Here you can load an OSL definition or write your own OSL script into the Code field. Source Choose the source of your OSL code: Text: Write your OSL code directly to the Code field of the node. File: Use the folder icon to load your OSL file Code Use this input to paste or write the OSL code. Path In File mode you can find the loaded file path here. Load In Text mode you can use this button to open an OSL file and copy its content to the Code field. Edit If you have loaded an OSL file in File mode, you can use this button to open a script editor or text editor to edit the content of the file. Messages This area gives feedback about the OSL code, such as compiler messages. Parameters You can define variables in your OSL code which are then displayed in this tab. You can for example add additional input variables for a float and a vector value at the preset code like this: shader OSLShader( color inColor=color(1, 1, 1), float myValue=0.0, point myVector=vector(0), output color outColor=0 ) { outColor = inColor; }
e0aa9a6f8cedefdaa4e88c98ab9ecaef
{ "intermediate": 0.3625325560569763, "beginner": 0.3987072706222534, "expert": 0.23876015841960907 }
37,543
i have this script "from selenium import webdriver from bs4 import BeautifulSoup import time from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.ui import WebDriverWait from webdriver_manager.chrome import ChromeDriverManager import datetime import os chromedriver_directory = r'C:\Program Files\Google\Chrome\Application\chrome-win64' # Add the path to chromedriver.exe to PATH os.environ['PATH'] = f"{os.environ['PATH']};{chromedriver_directory}" # Create a ChromeOptions object to set additional options (if needed) chrome_options = webdriver.ChromeOptions() # Specify the path to the Chrome browser executable (if needed) # chrome_options.binary_location = '/path/to/chrome' # Initialize the WebDriver with specified options driver = webdriver.Chrome(options=chrome_options) driver driver.get("https://www.avito.ma/fr/maroc/voitures-%C3%A0_vendre") start = time.time() # will be used in the while loop initialScroll = 0 finalScroll = 1000 while True: driver.execute_script(f"window.scrollTo({initialScroll},{finalScroll})") # this command scrolls the window starting from # the pixel value stored in the initialScroll # variable to the pixel value stored at the # finalScroll variable initialScroll = finalScroll finalScroll += 1000 # we will stop the script for 3 seconds so that # the data can load time.sleep(3) # You can change it as per your needs and internet speed end = time.time() # We will scroll for 20 seconds. # You can change it as per your needs and internet speed if round(end - start) > 20: break url1=[] for i in range(1,5): url = 'https://www.avito.ma/fr/maroc/voiture--%C3%A0_vendre?o={}'.format(i) results = driver.find_elements(By.XPATH,"//*[@id='__next']/div/main/div/div[5]//div[contains(@class, 'sc-1nre5ec-1')]/a") results1 = driver.find_elements(By.XPATH,'//*[@id="__next"]/div/main/div/div[6]/div[1]/div/div[2]/div/a') for link_element in results: link_href = link_element.get_attribute('href') url1.append(link_href) L = [] for i in range(0, 2): link = url1[i] driver.get(link) # Type type_elements = driver.find_elements(By.XPATH, '//*[@id="__next"]/div/main/div/div[3]/div[1]/div[2]/div[1]/div[1]/div[2]/div[3]/div[2]/ol') type_data = [element.text.split('\n') for element in type_elements] # Description description_elements = driver.find_elements(By.XPATH, '//*[@id="__next"]/div/main/div/div[3]/div[1]/div[2]/div[1]/div[1]/div[2]/div[4]/p') description_data = [element.text for element in description_elements] # Equipement equipement_elements = driver.find_elements(By.XPATH, '//*[@id="__next"]/div/main/div/div[3]/div[1]/div[2]/div[1]/div[1]/div[2]/div[5]/div/div[1]//div') equipement_data = {} if equipement_elements: for equipement in equipement_elements: try: span = equipement.find_element(By.XPATH, './/span') span_text = span.text equipement_data[span_text] = None # Use None as a placeholder value except NoSuchElementException as e: print(f"Error extracting equipement information: {e}") # Adding data to the dataset dataset_entry = { 'Type': type_data, 'Description': description_data, 'Equipement': equipement_data.keys() # Use keys() to get unique values } L.append(dataset_entry)" can you make it as an application
0e51207fcd17de037a2e46054be89f72
{ "intermediate": 0.29066890478134155, "beginner": 0.5376380085945129, "expert": 0.17169317603111267 }
37,544
adapte le code Programmation.tsx et CarteArtiste.tsx pour prendre en charge la nouvelle structure de données étant celle-ci : [ { "dateDebutE": "2023-07-21", "dateFinE": "2023-07-21", "descriptionG": "Desc", "heureDebutE": "09:00:00", "heureFinE": "10:00:00", "idE": 1, "idG": 1, "idH": 1, "idL": null, "nomE": "Concert Groupe 1", "nomG": "Vladimir Cauchemar" }, { "dateDebutE": "2023-07-21", "dateFinE": "2023-07-21", "descriptionG": "Desc", "heureDebutE": "13:00:00", "heureFinE": "14:00:00", "idE": 2, "idG": 2, "idH": 1, "idL": null, "nomE": "Concert Groupe 2", "nomG": "Booba" }, { "dateDebutE": "2023-07-21", "dateFinE": "2023-07-21", "descriptionG": "Desc", "heureDebutE": "17:00:00", "heureFinE": "18:00:00", "idE": 3, "idG": 3, "idH": 1, "idL": null, "nomE": "Concert Groupe 3", "nomG": "Freeze Corleone" }, { "dateDebutE": "2023-07-22", "dateFinE": "2023-07-22", "descriptionG": "Desc", "heureDebutE": "09:00:00", "heureFinE": "10:00:00", "idE": 4, "idG": 4, "idH": 2, "idL": null, "nomE": "Concert Groupe 4", "nomG": "Damso" }, { "dateDebutE": "2023-07-22", "dateFinE": "2023-07-22", "descriptionG": "Desc", "heureDebutE": "13:00:00", "heureFinE": "14:00:00", "idE": 5, "idG": 5, "idH": 2, "idL": null, "nomE": "Concert Groupe 5", "nomG": "Ashe 22" }, { "dateDebutE": "2023-07-22", "dateFinE": "2023-07-22", "descriptionG": "Desc", "heureDebutE": "17:00:00", "heureFinE": "18:00:00", "idE": 6, "idG": 6, "idH": 2, "idL": null, "nomE": "Concert Groupe 6", "nomG": "Heuss l'Enfoiré" }, { "dateDebutE": "2023-07-23", "dateFinE": "2023-07-23", "descriptionG": "Desc", "heureDebutE": "08:00:00", "heureFinE": "09:00:00", "idE": 7, "idG": 7, "idH": 3, "idL": null, "nomE": "Concert Groupe 7", "nomG": "Zola" }, { "dateDebutE": "2023-07-23", "dateFinE": "2023-07-23", "descriptionG": "Desc", "heureDebutE": "11:00:00", "heureFinE": "12:00:00", "idE": 8, "idG": 8, "idH": 3, "idL": null, "nomE": "Concert Groupe 8", "nomG": "Sch" }, { "dateDebutE": "2023-07-23", "dateFinE": "2023-07-23", "descriptionG": "Desc", "heureDebutE": "14:00:00", "heureFinE": "15:00:00", "idE": 9, "idG": 9, "idH": 3, "idL": null, "nomE": "Concert Groupe 9", "nomG": "H Jeunecrack" }, { "dateDebutE": "2023-07-23", "dateFinE": "2023-07-23", "descriptionG": "Desc", "heureDebutE": "17:00:00", "heureFinE": "18:00:00", "idE": 10, "idG": 10, "idH": 3, "idL": null, "nomE": "Concert Groupe 10", "nomG": "Luther" } ]import {useEffect, useState, useRef, useLayoutEffect} from 'react' import SearchBar from '../../components/form/SearchBar'; import Combo from '../../components/form/Combo'; import CarteArtiste from '../../components/Artiste/CarteArtiste'; import { motion } from 'framer-motion'; import { useLocation } from 'react-router-dom'; import axios from 'axios'; import Footer from '../../components/footer'; type Props = { isNavInFocus: boolean; setIsNavTransparent: (isNavTransparent : boolean) => void; } type Groupe = { idG: number; nomG: string; descriptionG: string; datePassage: string; heurePassage: string; } export default function Programmation(props : Props) { const location = useLocation(); const idArtistComingFrom = location.state?.comesFromPageArtist; const oldX = location.state?.oldX; const oldY = location.state?.oldY; const oldGroupes = location.state?.oldGroupes; window.history.replaceState({}, document.title) const[lesGroupes, setLesGroupes] = useState<Groupe[]>(location.state? oldGroupes : []); useEffect(() => { if (!location.state){ axios.get('http://localhost:8080/getGroupesWithEvenements').then((res) => { const data = res.data; console.log(data) const listeGroupes : Groupe[] = []; console.log(data) data.forEach((groupe: Groupe) => { if (groupe.datePassage && groupe.heurePassage) { const lesMois = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet","Août", "Septembre", "Octobre", "Novembre", "Décembre"]; const date = groupe.datePassage.split("-"); const datePassage = date[2] + " " + lesMois[parseInt(date[1])-1]; groupe.datePassage = datePassage; const heure = groupe.heurePassage.split(":"); const heurePassage = heure[0] + "H" + heure[1]; groupe.heurePassage = heurePassage; listeGroupes.push(groupe); } }); setLesGroupes(listeGroupes); }) } }, []) const[filtreDate, setFiltreDate] = useState("Tout"); const[filtreAffichage, setFiltreAffichage] = useState("Grille"); const[filtreGenre, setFiltreGenre] = useState("Tout"); const pageRef = useRef<HTMLDivElement>(null); const contentVariants = { visible:{ filter: "blur(0px)", scale:1, zIndex:1, transition:{ duration:0.5, ease: [1, 0, 0,1] } }, hidden:{ filter:"blur(10px)", scale:0.8, zIndex:-1, transition:{ duration:0.5, ease: [1, 0, 0,1] } } } useEffect(() => { window.scrollTo(0, 0) props.setIsNavTransparent(false) }, []) return ( <> <motion.div id="Programmation" className='page-defaut' variants={contentVariants} animate={props.isNavInFocus ? "hidden" : "visible"} ref={pageRef} > <header> <div className="title"> <h2>PROGRAMMATION</h2> <svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M62.9991 27.739L42.1815 27.7675L56.8787 13.0286L50.7001 6.86056L36.0029 21.5994L35.9744 0.785744L27.2406 0.797718L27.2692 21.6114L12.5316 6.91288L6.36413 13.0979L21.1017 27.7964L0.289932 27.825L0.301899 36.5537L21.1137 36.5251L6.41646 51.2641L12.6009 57.4321L27.2981 42.6932L27.3266 63.5069L36.0603 63.4949L36.0318 42.6812L50.7694 57.3798L56.931 51.1948L42.1934 36.4962L63.011 36.4677L62.9991 27.739Z" fill="#FFD600"/> </svg> </div> <div className="filters-container"> <div className="filters"> <Combo title="DATE" choices={["Tout", "21 Juillet", "22 Juillet", "23 Juillet"]} currentChoice={filtreDate} setCurrentChoice={setFiltreDate} /> <Combo title="AFFICHAGE" choices={["Grille", "Horaires"]} currentChoice={filtreAffichage} setCurrentChoice={setFiltreAffichage} /> <Combo title="GENRE" choices={["Tout", "Rap", "Rock", "Pop"]} currentChoice={filtreGenre} setCurrentChoice={setFiltreGenre} /> </div> <SearchBar text="Rechercher un artiste"/> </div> </header> <main className='liste-artistes'> { lesGroupes.map((groupe, index) => { return( <CarteArtiste oldGroupes={lesGroupes} key={groupe.idG} id={groupe.idG} oldX={idArtistComingFrom == groupe.idG ? oldX : null} oldY={idArtistComingFrom == groupe.idG ? oldY : null} comesFromPageArtist={idArtistComingFrom == groupe.idG} nomArtiste={groupe.nomG} date={groupe.datePassage} heure={groupe.heurePassage} setIsNavTransparent={props.setIsNavTransparent} /> ) }) } </main> </motion.div> <Footer/> </> ) } import { motion } from 'framer-motion' import {useState,useRef, useEffect} from 'react' import { Link } from 'react-router-dom' type Props = { id:number, date: string, heure: string, nomArtiste: string, setIsNavTransparent: (isNavTransparent : boolean) => void; comesFromPageArtist?: boolean; oldX?: number; oldY?: number; oldGroupes?: Groupe[]; } type Groupe = { idG: number; nomG: string; descriptionG: string; datePassage: string; heurePassage: string; } export default function CarteArtiste(props: Props) { // change le nomArtiste en majuscule et remplace les espaces par des retours à la ligne const nomArtiste = props.nomArtiste.toUpperCase().split(" ") const[isHovered, setIsHovered] = useState(false) const[isSwitching, setIsSwitching] = useState(false) const[delay, setDelay] = useState(props.comesFromPageArtist? 0.2 : 0) const refCarte = useRef<HTMLDivElement>(null); const[zIndexCard, setZIndexCard] = useState(props.comesFromPageArtist ? 99 : 1) useEffect(() => { setTimeout(() => { console.log(props.date) console.log(props.heure) setZIndexCard(1) setDelay(0) }, 600); }, []) const titleVariants = { hover:{ fontSize: "2.3rem", color:"#FFD600", transition:{ duration:0.4, ease: [1, 0, 0,1] } }, default:{ fontSize: "2.3rem", color:"#FFFBEE", transition:{ delay:delay, duration:0.4, ease: [1, 0, 0,1] } }, exit:{ fontSize: "7.625rem", color:"#FFD600", transition:{ duration:0.4, ease: [1, 0, 0,1] } } } // fais le variant pour l'image de l'artiste (scale 1.2 sur hover) const imageVariants = { hover:{ scale:1.3, transition:{ duration:0.4, ease: [1, 0, 0,1] } }, default:{ scale:1, transition:{ duration:0.4, ease: [1, 0, 0,1] } } } // fais le variant pour le texte de dateHeure (x 2rem sur hover) const dateHeureVariants = { hover:{ y:"0rem", fontSize: "1.875rem", transition:{ duration:0.4, ease: [1, 0, 0,1] } }, default:{ y:(window.innerWidth <= 576 ? 3.1 : 2.9).toString() + "rem", fontSize: "1.875rem", transition:{ delay:delay, duration:0.4, ease: [1, 0, 0,1] } }, exit:{ y:"0rem", fontSize: "4.6875rem", transition:{ duration:0.4, ease: [1, 0, 0,1] } } } // default font-size: 1.875rem; // exit font-size: 4.6875rem; const heureVariants = { hover:{ transition:{ duration:0.4, ease: [1, 0, 0,1] } }, default:{ transition:{ duration:0.4, ease: [1, 0, 0,1] } }, } const carteVariants = { default:{ zIndex:zIndexCard, width: "24rem", height: "15.5rem", y:0, x:0, transition:{ delay:0.2, duration:0.4, ease: [1, 0, 0,1] } }, exit:{ x: refCarte.current? -refCarte.current.offsetLeft : props.oldX? -props.oldX : 0, y: refCarte.current? -refCarte.current.offsetTop : props.oldY? -props.oldY : 0, height: "100vh", width: "100vw", zIndex:99, transition:{ duration:0.4, ease: [1, 0, 0,1] } } } const textVariants = { default:{ padding: "0.5rem 1rem", transition:{ delay:delay*2, duration:0.4, ease: [1, 0, 0,1] } }, exit:{ padding: "3rem", transition:{ duration:0.4, ease: [1, 0, 0,1] } } } return ( <motion.div className="outer-carte-artiste" ref={refCarte} variants={carteVariants} initial={props.comesFromPageArtist ? "exit" : "default"} animate="default" exit={isSwitching ? "exit" : "default"} onClick={() => window.scrollTo(0,0)} > <Link className="carte-artiste" onMouseEnter={() => setIsHovered(true)} onMouseLeave={() => setIsHovered(false)} to={{ pathname:"/artiste", search:`?id=${props.id}`, }} state={{ nomArtiste: props.nomArtiste, date: props.date, heure: props.heure, oldX: refCarte.current?.offsetLeft, oldY: refCarte.current?.offsetTop, oldGroupes: props.oldGroupes }} onClick={() => {props.setIsNavTransparent(true); setIsSwitching(true)}} > <motion.img src={"http://localhost:8080/getImageArtiste/" + props.id} alt="image de l'artiste" variants={imageVariants} initial="default" animate={isHovered ? "hover" : "default"} exit="default" /> <motion.div className="texts" variants={textVariants} initial={props.comesFromPageArtist ? "exit" : "default"} animate="default" exit={isSwitching ? "exit" : "default"} > <motion.h3 variants={titleVariants} initial={props.comesFromPageArtist ? "exit" : "default"} animate={isHovered ? "hover" : "default"} exit={isSwitching ? "exit" : "default"} >{ nomArtiste.map((mot, index) => { return( <span key={index}>{mot}<br/></span> ) }) }</motion.h3> <motion.div className="date-heure" variants={dateHeureVariants} initial={props.comesFromPageArtist ? "exit" : "default"} animate={isHovered ? "hover" : "default"} exit={isSwitching ? "exit" : "default"} > <h4 >{props.date}</h4> <motion.h4 variants={heureVariants} initial="default" animate={isHovered ? "hover" : "default"} exit={isSwitching ? "exit" : "default"} >{props.heure}</motion.h4> </motion.div> </motion.div> </Link> </motion.div> ) }
ad1b5da97c26a31a6a155dd85140e7c8
{ "intermediate": 0.29185304045677185, "beginner": 0.5066157579421997, "expert": 0.20153118669986725 }
37,545
can you code me an interactive rock paper scissor game
bd826dd04a125991bfbceef9db7a2f49
{ "intermediate": 0.35211777687072754, "beginner": 0.2274608314037323, "expert": 0.42042139172554016 }