row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
6,727
INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. ERROR [alembic.util.messaging] Can't locate revision identified by '985c12474ff3' FAILED: Can't locate revision identified by '985c12474ff3'
e6b358f0e12bff84795091c64519fe58
{ "intermediate": 0.4109346568584442, "beginner": 0.3289647400379181, "expert": 0.2601005434989929 }
6,728
hi, how is you, please answer this peoblem for me. what is dot right means using python
ded1abb51e5adbc4b0d0d0d915ae6fab
{ "intermediate": 0.324673593044281, "beginner": 0.3831791877746582, "expert": 0.2921471893787384 }
6,729
gen a python script to check two csv to have the different record
a70d9fdccab521f3ef45da5c0fc73f4f
{ "intermediate": 0.4515064060688019, "beginner": 0.168810173869133, "expert": 0.3796834647655487 }
6,730
gen a python script to check two csv to have the different record with code
be6f6c7b4cb192652c106876c8c3e102
{ "intermediate": 0.4397856295108795, "beginner": 0.20498786866664886, "expert": 0.35522642731666565 }
6,731
Flutter call method by string. How?
5e9b39089cf7aba8e37a6ffaa8c6fb47
{ "intermediate": 0.4947086274623871, "beginner": 0.23892568051815033, "expert": 0.2663656771183014 }
6,732
flutter call method by string how?
3d6200292319bc398cc6f14bde024079
{ "intermediate": 0.4864926338195801, "beginner": 0.21811692416667938, "expert": 0.29539036750793457 }
6,733
hi testing
24b7cfe05c1ffe21f0ee97b98a99b22e
{ "intermediate": 0.38600432872772217, "beginner": 0.2064676135778427, "expert": 0.4075280725955963 }
6,734
how to implement sharedviewmodel in jetpack compose so states will be stored
5e4012a455ab2ede676e2f0f1f6a3698
{ "intermediate": 0.2254045605659485, "beginner": 0.09883186966180801, "expert": 0.6757635474205017 }
6,735
Hi, I've implemented the following Evader Code. I want you to go deeper in my code, understand fully and after Come with coding standards to update my code to the industry standards . Later I'll provide the code for DQN do the same and also fix the matmul error it raises. Here is my Evader code: import numpy as np import random import math import rospy import tf import time from rospy.rostime import Time from sensor_msgs.msg import LaserScan from ackermann_msgs.msg import AckermannDrive from nav_msgs.msg import Odometry from DQN import DQNAgentPytorch from reset import reset_car_position FORWARD = 0 LEFT = 1 RIGHT = 2 REVERSE = 3 ACTION_SPACE = [FORWARD, LEFT, RIGHT, REVERSE] class EvaderNode: def __init__(self, agent): rospy.init_node('evader_node', anonymous=True) rospy.Subscriber('car_1/scan', LaserScan, self.scan_callback) rospy.Subscriber('car_1/base/odom', Odometry, self.odom_callback) self.drive_pub = rospy.Publisher('car_1/command', AckermannDrive, queue_size=20) self.init_location = None self.current_location = None self.goal = (10, 10) self.obstacle_penalty = -250 self.destination_reward = 500 self.distance_threshold = 0.5 self.collision_threshold = 0.2 self.agent = agent self.is_training = True self.init_odom_received = False self.latest_odom_msg = None self.reached_destination = False self.reward = 0 self.angle_range = [(-3 * np.pi / 4, -np.pi / 4), (np.pi / 4, 3 * np.pi / 4)] self.max_steps_per_episode = 100 self.current_episode = 0 self.max_episodes = 10000 def process_scan(self, scan): state = np.array(scan.ranges)[::10] return state def check_collision(self, scan): front_ranges = [] rear_ranges = [] for i, angle in enumerate(np.arange(len(scan.ranges)) * scan.angle_increment + scan.angle_min): if self.angle_range[0][0] <= angle <= self.angle_range[0][1]: front_ranges.append(scan.ranges[i]) elif self.angle_range[1][0] <= angle <= self.angle_range[1][1]: rear_ranges.append(scan.ranges[i]) # Check for obstacles in the front section min_front_range = min(front_ranges) if min_front_range < self.collision_threshold: # Obstacle detected in the front return True else: # Check for obstacles in the rear section min_rear_range = min(rear_ranges) if min_rear_range < self.collision_threshold: # Obstacle detected in the rear return True return False def action_to_drive_msg(self, action): drive_msg = AckermannDrive() if action == FORWARD: drive_msg.speed = 2.0 drive_msg.steering_angle = 0.0 elif action == LEFT: drive_msg.speed = 2.0 drive_msg.steering_angle = float(random.uniform(math.pi / 4, math.pi / 2)) elif action == RIGHT: drive_msg.speed = 2.0 drive_msg.steering_angle = float(random.uniform(-math.pi / 2, -math.pi / 4)) elif action == REVERSE: drive_msg.speed = -2.0 drive_msg.steering_angle = 0.0 return drive_msg def calculate_reward(self, collision_detected, done): reward = 0 if done: reward += self.destination_reward return reward if collision_detected: reward += self.obstacle_penalty return reward current_dist_diff = np.linalg.norm(np.array(self.goal) - np.array(self.current_location)[:2]) init_dist_diff = np.linalg.norm(np.array(self.goal) - np.array(self.init_location)[:2]) if current_dist_diff < init_dist_diff: reward += 100 else: reward -= 100 return reward def update_reward(self, collision_detected, done): self.reward += self.calculate_reward(collision_detected, done) def scan_callback(self, scan): state = self.process_scan(scan) scan_timestamp = scan.header.stamp odom_timestamp = self.latest_odom_msg.header.stamp print(f'Scan Timestamp: {scan_timestamp.to_sec()} Odometry Message Timestamp: {odom_timestamp.to_sec()}') time_diff = scan_timestamp - odom_timestamp time_diff_sec = time_diff.to_sec() # Adjust the time threshold as per your requirement time_threshold = 10 if abs(time_diff_sec) > time_threshold: # Adjust the threshold as per your requirement print("LaserScan and Odometry messages are not in sync!") return else: print('LaserScan and Odometry messages are in sync!') while self.current_episode <= self.max_episodes: distance_to_goal = np.linalg.norm(np.array(self.goal) - np.array(self.current_location)[:2]) print('Distance to reach goal:', distance_to_goal) # if distance_to_goal >= 20: # self.reward = 0 # reset_car_position() state = np.concatenate((state, [self.current_location[2]], [distance_to_goal])) action = self.agent.choose_action(state, test=not self.is_training) collision_detected = self.check_collision(scan) if collision_detected and not self.reached_destination: print('Collision Detected') drive_msg = self.action_to_drive_msg(action) print(f'Action chosen: {action}, Yaw: {drive_msg.steering_angle}') self.drive_pub.publish(drive_msg) done = False # if self.current_episode >self.max_episodes: if self.is_training : print("Current Episode: ", self.current_episode, 'Episode Left:',self.max_episodes -self.current_episode) self.agent.add_experience(state, action, self.reward, state, done) self.agent.train(32) # Set the batch size here self.agent.update_epsilon(self.agent.epsilon * 0.995) if distance_to_goal < self.distance_threshold: done = True drive_msg.speed = 0.0 self.drive_pub.publish(drive_msg) print("----Goal Reached----") # reset_car_position() self.reward = 0 rospy.sleep(1) self.current_episode +=1 # else: # reset_car_position() # self.agent.load_weights('model_weights.pth') # action = self.agent.choose_action(state, test=True) # print(action) print(f"Reward before taking the action {action}: {self.reward}") self.update_reward(collision_detected, done) print(f"Reward after taking the action {action}: {self.reward}") # self.current_episode = 0 # self.agent.save_weights('model_weights.pth') # self.is_training = False # rospy.signal_shutdown('Exit condition met') # return def update_current_location(self, odom_msg): position = odom_msg.pose.pose.position orientation = odom_msg.pose.pose.orientation euler_angles = tf.transformations.euler_from_quaternion( (orientation.x, orientation.y, orientation.z, orientation.w)) self.current_location = (position.x, position.y, euler_angles[2]) # (x, y, yaw) print("Current Location of the Car:", self.current_location[:2]) def odom_callback(self, odom_msg): if not self.init_odom_received: self.init_location = (odom_msg.pose.pose.position.x, odom_msg.pose.pose.position.y) print(f"Initial Location of the Car: {self.init_location}") self.init_odom_received = True self.update_current_location(odom_msg) self.latest_odom_msg = odom_msg if __name__ == '__main__': try: action_space = ACTION_SPACE observation_space = np.zeros((111,)) # Based on the number of data points in the lidar scan plus additional state variables agent = DQNAgentPytorch(action_space, observation_space) node = EvaderNode(agent) while not node.init_odom_received: rospy.sleep(0.1) rospy.spin() # node.run(10) # Change the number of episodes here except rospy.ROSInterruptException: pass
58da027eda2f393938165d14c950352a
{ "intermediate": 0.37274375557899475, "beginner": 0.39169052243232727, "expert": 0.23556579649448395 }
6,736
write a dart program that slices an image into four equal-sized images
1891276911b768e3bf502b8dbff6d002
{ "intermediate": 0.1724122166633606, "beginner": 0.08299180120229721, "expert": 0.7445959448814392 }
6,737
Explain Views in SQL Server using below employees and departments tables. Explain all possible queries in SQL views that can be made using below employees and departments tables. Do not skip any. Show the queries in SQL Server format. CREATE TABLE employees ( employee_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), hire_date DATE, salary DECIMAL(10, 2), department_id INT ); INSERT INTO employees VALUES (1, 'John', 'Doe', '2021-01-01', 50000.00, 1), (2, 'Jane', 'Doe', '2021-02-15', 60000.00, 1), (3, 'Bob', 'Smith', '2021-03-01', 55000.00, 2), (4, 'Sara', 'Johnson', '2021-04-01', 65000.00, 2), (5, 'Tom', 'Williams', '2021-05-01', 70000.00, 3), (6, 'Emily', 'Jones', '2021-06-01', 80000.00, 3), (7, 'Mike', 'Brown', '2021-07-01', 75000.00, 4), (8, 'Lisa', 'Davis', '2021-08-01', 85000.00, 4), (9, 'David', 'Wilson', '2021-09-01', 90000.00, 5), (10, 'Laura', 'Taylor', '2021-10-01', 95000.00, 5); CREATE TABLE departments ( department_id INT PRIMARY KEY, name VARCHAR(50), location VARCHAR(50) ); INSERT INTO departments VALUES (1, 'Sales', 'New York'), (2, 'Marketing', 'Los Angeles'), (3, 'Finance', 'Chicago'), (4, 'Human Resources', 'Houston'), (5, 'Information Technology', 'San Francisco');
d03878ede1dfe65f886a65c1620ad0a1
{ "intermediate": 0.39569392800331116, "beginner": 0.2690579295158386, "expert": 0.3352481424808502 }
6,738
Hi can you generate code
a3194e1e6a19110b1527ea5846b01929
{ "intermediate": 0.2522949278354645, "beginner": 0.29293689131736755, "expert": 0.45476818084716797 }
6,739
develop a real-time attendance system with machine learning capabilities. The system should utilize biometric (face recognition) technology for attendance tracking. I am looking for a completely new system that does not need to be integrated with any existing software or platforms. The ideal freelancer should have experience in developing attendance systems, utilizing biometric technology, and implementing deep learning algorithms. The machine learning algorithm preferred for the system is deep learning.
4da4cab2160600c25ffeab9640b17884
{ "intermediate": 0.07380932569503784, "beginner": 0.09734562784433365, "expert": 0.8288450837135315 }
6,740
public function get_data_for_campaign() { if(RedisDB::lLen(self::FB_CAMPAIGN_RDS) > 0){ $ad = RedisDB::get_lPop(self::FB_CAMPAIGN_RDS); }这段代码会报错 Exception: read error on connection /home1/codeInfo/al_adorado_#5387/application/libraries/RedisDB.php 273
4bfa1e1aacc6f1b3ec34c6d0ce2e4cad
{ "intermediate": 0.45714181661605835, "beginner": 0.3653353154659271, "expert": 0.1775229275226593 }
6,741
Hi, can you give some sample python code for a strategy game about African warlords?
02c393d52a6b04aa05880d29bb5bcc9b
{ "intermediate": 0.3082762360572815, "beginner": 0.36739805340766907, "expert": 0.3243256211280823 }
6,742
Deep learning algorithms: 1.DNN using all below variables to predict the dummy Diff_F, then name the prediction as Diff_DNN 2.CNN using all below variables to predict the dummy Diff_F, then name the prediction as Diff_CNN 3.DNN with CHAID to select important variables to predict the dummy Diff_F, then name the prediction as Diff_DNNCHAID 4.CNN with CHAID to select important variables to predict the dummy Diff_F, then name the prediction as Diff_CNNCHAID. Then append these four variables (four columns) in the end of the dataset, save as a csv file Use independent variables: Residfee Big4 lev loss M_B ROA size Z_score_Hill GC_l sic2 fyear AGE ATURN DebtIssue_D EquityIssue_D OCF SGR use data fyear before 2019 to train and then use variables in fyear=2019 to predict Diff_F=1 in fyear=2019, name it name Diff_DNN ,Diff_CNN, Diff_DNNCHAID, Diff_CNNCHAID, respectively. (and write a loop that if I choose range 2001-2019 trained by data 2000 to predict 2001 Diff_F trained by data 2000-2001 and use dependent variables in 2002 to predict 2002 Diff_F trained by data 2000-2002 and use dependent variables in 2003 to predict 2003 Diff_F trained by data 2000-2003 and use dependent variables in 2004 to predict 2004 Diff_F trained by data 2000-2004 and use dependent variables in 2005 to predict 2005 Diff_F .....until 2019 automatically trained by data before 2018 to predict 2018, trained by data before 2017 to predict 2017, trained by data before 2016 to predict 2016,....etc, so I can choose a range like from 2000 to 2019 and don't need to enter every year) ,Diff_F is a binary variable (either zero or one) with Hyperparameter Search: Techniques to pick the most Optimal Set Please give some description of 1,2,3,4 For example, 4.CNN with CHAID: The X important variables selected by CHAID are input into DNN for deep learning and repeatedly trained until reaching the optimal stable state, Y epochs and Z microseconds training time, in order to build the best model.
6f6136abaa1c8e3dc21286a96a65922b
{ "intermediate": 0.05677364021539688, "beginner": 0.15009604394435883, "expert": 0.7931302785873413 }
6,743
What is the difference between "project", "object" and an instanciation of an object in VBA?
b7e8b5100c625f4d3d595ba1da6e9f09
{ "intermediate": 0.23918119072914124, "beginner": 0.32837820053100586, "expert": 0.4324406087398529 }
6,744
hi
30749de0430352e4811367798ec4a8ed
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
6,745
composable( route = Screen.ReaderScreen.route + “/{headingLectureName}”, arguments = listOf(navArgument(name = “headingLectureName”) { type = NavType.StringType }) ) { ReaderScreen() } composable(route = com.ghost.netstudyapp.feature_emulator.Screen.EmulatorScreen.route) { EmulatorScreen( navController = navController, paddingValues = paddingValues, ) } @Composable fun EmulatorScreen( navController: NavController, viewModel: EmulatorViewModel = hiltViewModel(), paddingValues: PaddingValues, context: Context = LocalContext.current ) { @HiltViewModel class EmulatorViewModel @Inject constructor( private val emulatorUseCases: EmulatorUseCases ) : ViewModel() { private val _state = MutableStateFlow(EmulatorState()) val state = _state … how to prevent from resetting state when navigating from one screen to another
e2d38a29b0c6281d3db95c7b8c35754e
{ "intermediate": 0.4182458817958832, "beginner": 0.2625434696674347, "expert": 0.31921064853668213 }
6,746
correct error: Yes, Chinese students do volunteer work. Many universities and colleges have put volunteer work to students' curriculum, making it a compulsory subject for them. For example, When I was attending bachelor's degree, I was asked to do 30 hours of volunteer work during 2 years. And in my reflection, I did some volunteer work in a hospital to help doctors organise patients' data and collect newspapers and materials for them.
f92bd28d4e1c0aa6110f8a53cc3bdc18
{ "intermediate": 0.39935657382011414, "beginner": 0.2756775915622711, "expert": 0.32496580481529236 }
6,747
Hello, can you give some sample code for making a 2D turn-based strategy game in pygame?
1820c5c5d34a05410ce9a7e1160b6660
{ "intermediate": 0.530185878276825, "beginner": 0.26344048976898193, "expert": 0.20637363195419312 }
6,748
Cannot acquire a schema lock because of an existing lock
8054b837692ad92c860b0749995796ef
{ "intermediate": 0.36204448342323303, "beginner": 0.27124059200286865, "expert": 0.3667148947715759 }
6,749
Objectives: Describe cultural and co-cutlural differences in nonverbal behaviors Nonverbal communication can be classified into four categories: body language, paralanguage, spatial use, and self-presentation. While up to 65% of meaning in social interactions is conveyed through nonverbal behavior, nonverbal messages are often ambiguous. How we interpret another's nonverbal behavior is often dependent upon the context (physical, social, historical, psychological, etc) and culture/co-culture (race, ethnicity, gender, sexual orientation, religion, generation, etc.) For example, Western cultures place more importance than other cultures on eye contact, there are notable differences in the use of gestures and facial expressions between women and men, notions of "personal space" will change when in an elevator vs a large area; and different (co)cultures (generation, gender, race, ethnicity, etc) have different standards for self-presentation and how to display status (like foot-binding in China.) Instructions: Choose one or more of the four nonverbal categories listed below and write 1-2 pages describing nonverbal differences you have noticed as a result of culture and/or co-culture (such as gender, generation, religion, etc). Use examples where appropriate, including your own (however, only disclose what you feel comfortable disclosing.) As part of your grade, be sure to reference the textbook "Understanding Human Communication fourth edition" terminology concepts and content and place these in either bold or italics. Nonverbal categories: Body Language: eye contact, facial expression, gesture, posture and body orientation, and touch Paralanguage: pitch, volume, rate, quality, and intonation Spatial Use: personal space, acoustic space, territory, and artifacts Self-Presentation: Physical appearance, use of time, use of smells and scents
1761422f2e0fc5cdc45eb84760ab93ab
{ "intermediate": 0.31292060017585754, "beginner": 0.41913172602653503, "expert": 0.26794758439064026 }
6,750
Hi, can you give sample pygame code for a simple game?
fd417cb79a770dcbe28a46d54ddf75b5
{ "intermediate": 0.437701940536499, "beginner": 0.33245378732681274, "expert": 0.22984421253204346 }
6,751
Hi I want to make fastapi server that runs a scrapy spider in the background, can you gimmie a hand?
d88ccdb5329fe1073837427f61a20918
{ "intermediate": 0.5070608258247375, "beginner": 0.12861154973506927, "expert": 0.36432763934135437 }
6,752
Hi I want to make a fastapi route that calls a scrapy spider to be ran in the background(using BackgroundTasks of the FastApi). I'm getting ValueError: signal only works in main thread all the time.
e89b5d4ea2f47ff652100789ee53851f
{ "intermediate": 0.6933599710464478, "beginner": 0.10296401381492615, "expert": 0.20367592573165894 }
6,753
在Python脚本中调用pyshark模块读取pcap文件时报错:if asyncio.all_tasks(): File "C:\Program Files (x86)\Python37-32\lib\asyncio\tasks.py", line 37, in all_tasks loop = events.get_running_loop() RuntimeError: no running event loop
6f0c1a461d603981d2b612fb5e0a1184
{ "intermediate": 0.3434375822544098, "beginner": 0.5090218782424927, "expert": 0.14754052460193634 }
6,754
Unreal struct define code
9bd35bc895e57460af53f1d797594d5f
{ "intermediate": 0.22643327713012695, "beginner": 0.41345250606536865, "expert": 0.3601142168045044 }
6,755
suggest domain name used for Navigation website related with ai or chat
9c108c0e3b77ed07a97e6797b5ec8441
{ "intermediate": 0.32747411727905273, "beginner": 0.3821548819541931, "expert": 0.29037103056907654 }
6,756
make a processing sketch doing a game of life
9fe6df8e2d9fd332434be3fb99749a16
{ "intermediate": 0.32247382402420044, "beginner": 0.41790536046028137, "expert": 0.2596207857131958 }
6,757
TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0] 如何用getnnz() 修改predictions = np.zeros((len(X), len(self.trees)).tocsc(),dtype=int)
06290475f95557e54e55eeaab12cda9b
{ "intermediate": 0.33526936173439026, "beginner": 0.21349050104618073, "expert": 0.4512401521205902 }
6,758
make a elisp game of life
3d5da431f8ea7aea439eec8689481ebc
{ "intermediate": 0.234205961227417, "beginner": 0.5798419713973999, "expert": 0.18595203757286072 }
6,759
TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0] 如何用getnnz() 修改predictions = np.zeros((len(X), len(self.trees)).tocsc(),dtype=int)
39952982d6005ad717357d43a90cb650
{ "intermediate": 0.33526936173439026, "beginner": 0.21349050104618073, "expert": 0.4512401521205902 }
6,760
Write expression action for basic Go language using bison in C
17106a3cdd0d40cb56ad50a0a7bcd483
{ "intermediate": 0.22923386096954346, "beginner": 0.623145580291748, "expert": 0.14762058854103088 }
6,761
I want to make an arduino project with several files .h and .cpp. i have a couple of file Menu.h/Menu.cpp and another one couple RELAIS.h/RELAIS.cpp. The compiler doesn’t work ith this code. Please correct those four codes for working together : //Menu.h #ifndef Menu_H #define Menu_H #include <Keypad.h> #include <Arduino.h> extern const byte ROWS = 4; extern const byte COLS = 4; extern byte rowPins[ROWS] = { 33, 32, 31, 30 }; extern byte colPins[COLS] = { 29, 28, 27, 26 }; extern char key; extern char keys[ROWS][COLS] = { { '1', '2', '3', 'A' }, { '4', '5', '6', 'B' }, { '7', '8', '9', 'C' }, { '*', '0', '#', 'D' } }; extern Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); void Initialisation_LCD(); void mainMenu(); void relaisMenu(); int getKeypadValue(int minVal, int maxVal, char* infoText); void infoMenu(); void showTemps(); void showHumidity(); #endif //Menu.cpp #include <Keypad.h> #include <Wire.h> #include <LiquidCrystal_I2C.h> #include "RELAIS.h" #include "Menu.h" #include <Arduino.h> char key = 0; //Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); LiquidCrystal_I2C lcd(0x27, 20, 4); void Initialisation_LCD(){ Wire.begin(); lcd.init(); lcd.noBacklight(); } void mainMenu() { lcd.clear(); lcd.setCursor(0, 0); lcd.print("A-Relais B-Info"); lcd.setCursor(0, 1); lcd.print("D-Quit"); char key = keypad.waitForKey(); switch (key) { case 'A': relaisMenu(); break; case 'B': infoMenu(); break; case 'D': lcd.clear(); lcd.noBacklight(); break; } } void relaisMenu() { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Entrez numero relai #"); int relai_choisi = getKeypadValue(1, Relais_Nb, "Entrez numero relai #"); relai_choisi = relai_choisi - 1 ; lcd.setCursor(0, 1); lcd.print("A:ON/OFF B:TIMER "); lcd.setCursor(0, 2); lcd.print("C:Program D:Exit "); bool exitFlag = false; while (!exitFlag) { char key = keypad.waitForKey(); int value; switch (key) { case 'A': Relais_Statut[relai_choisi] = !Relais_Statut[relai_choisi]; break; case 'B': value = getKeypadValue(0, 999, "Enter Timer:"); if (value > -1) { Relais_Statut[relai_choisi] = 1; Relais_Timer[relai_choisi] = value; } break; case 'C': Relais_Prog[relai_choisi] = 1; value = getKeypadValue(0, 24, "Enter Heure PH:"); if (value > -1) { Relais_ProgH[relai_choisi] = value; value = getKeypadValue(0, 60, "Enter Min PH:"); if (value > -1) { Relais_ProgM[relai_choisi] = value; Relais_ProgT[relai_choisi] = getKeypadValue(1, 999, "Enter Duration:"); } } break; case 'D': exitFlag = true; lcd.clear(); lcd.noBacklight(); break; } } } int getKeypadValue(int minVal, int maxVal, char* infoText) { lcd.clear(); lcd.setCursor(0, 0); lcd.print(infoText); lcd.setCursor(0, 1); lcd.print("A-VALIDER D-QUITTER"); int value = 0; bool exitFlag = false; while (!exitFlag) { char key = keypad.waitForKey(); if (key >= '0' && key <= '9') { int newVal = value * 10 + (key - '0'); if (newVal >= minVal && newVal <= maxVal) { value = newVal; lcd.print(key); } } else if (key == 'D') { return -1; // Annuler l'entrée } else if (key == 'A') { exitFlag = true; } } return value; } void infoMenu() { // Gérer l'affichage et l'interaction avec le menu d'informations lcd.clear(); lcd.setCursor(0, 0); lcd.print("A-Temp B-Hum"); lcd.setCursor(0, 1); lcd.print("D-Quit"); bool quit = false; while (!quit) { char key = keypad.waitForKey(); switch (key) { case 'A': showTemps(); break; case 'B': showHumidity(); break; case 'D': quit = true; break; } } } void showTemps() { lcd.clear(); lcd.setCursor(0, 0); lcd.print("T1:"); // lcd.print(temp1, 1); lcd.setCursor(0, 1); lcd.setCursor(0, 4); lcd.print("D-Quit"); char key; do { key = keypad.waitForKey(); } while (key != 'D'); } void showHumidity() { lcd.clear(); lcd.setCursor(0, 0); lcd.print("H1:"); // lcd.print(hum1, 1); lcd.print("D-Quit"); char key; do { key = keypad.waitForKey(); } while (key != 'D'); } //RELAIS.h #ifndef RELAIS_H #define RELAIS_H extern const int Relais_Nb = 8; extern const int Relai_Depart = 34; extern int Relais_Pin[Relais_Nb]; extern int Relais_Statut[Relais_Nb]; extern int Relais_Timer[Relais_Nb]; extern int Relais_Prog[Relais_Nb]; extern int Relais_ProgH[Relais_Nb]; extern int Relais_ProgM[Relais_Nb]; extern int Relais_ProgT[Relais_Nb]; extern int Relais_Tension[Relais_Nb]; extern int Relais_Intensite[Relais_Nb]; extern int Relais_Puissance[Relais_Nb]; void Initialisation_Relais(); void updateRelayState(int relay, bool state); void MAJ_timer(); #endif //RELAIS.cpp #include "RELAIS.h" #include <Arduino.h> #include "Menu.h" /* Relais_Pin[Relais_Nb] = {34, 35, 36, 37, 38, 39, 40, 41}; Relais_Statut[Relais_Nb] = {0}; Relais_Timer[Relais_Nb] = {0}; Relais_Prog[Relais_Nb] = {0}; Relais_ProgH[Relais_Nb] = {0}; Relais_ProgM[Relais_Nb] = {0}; Relais_ProgT[Relais_Nb] = {0}; Relais_Tension[Relais_Nb] = {0}; Relais_Intensite[Relais_Nb] = {0}; Relais_Puissance[Relais_Nb] = {0}; */ void Initialisation_Relais() { for (int i = 0; i < Relais_Nb; i++) { Relais_Pin[i] = Relai_Depart + i; pinMode(Relais_Pin[i], OUTPUT); updateRelayState(i, LOW); } } void updateRelayState(int relay, bool state) { //if (state == HIGH) state = LOW; else state = HIGH; // if (tension >= Tension_min) { // float tension_avant = lireTensionBatterie(); // float intensite_avant = mesure_intensite(pintIntensite1); digitalWrite(Relais_Pin[relay], state); Relais_Statut[relay] = state; delay(100); if (state == HIGH) { //Relais_Tension[relay] = lireTensionBatterie() - tension_avant; //Relais_Intensite[relay] = mesure_intensite(pintIntensite1) - intensite_avant; //Relais_Puissance[relay] = lireTensionBatterie() * intensite_relai[relay]; } else { Relais_Tension[relay] = 0; Relais_Intensite[relay] = 0; Relais_Puissance[relay] = 0; } } //} void MAJ_timer() { for (int i = 0; i < Relais_Nb; i++) { if (Relais_Timer[i] > 0) { Relais_Timer[i]--; if (Relais_Timer[i] == 0) { //updateRelayState(i, LOW);*************************************************************************************************** } } } } /* void coupure_urgence() { if (tension <= Tension_min) { for (int i = 0; i < NUM_RELAYS; i++) { if (forcing[i] == 0) { timer[i] = 0; updateRelayState(i, LOW); } } } } */
db2af3e6ab97749ddf7985f03705a94a
{ "intermediate": 0.3932414948940277, "beginner": 0.3561548590660095, "expert": 0.25060367584228516 }
6,762
import pandas import sqlalchemy # Create the engine to connect to the PostgreSQL database engine = sqlalchemy.create_engine('postgresql://postgres:test1234@localhost:5432/sql-shack-demo') # Read data from CSV and load into a dataframe object data = pandas.read_csv('C:/temp/pandas-db-sqlshack-demo/pandas-env/superstore.csv') # Write data into the table in PostgreSQL database data.to_sql('superstore',engine) the data.to_sql, to_sql is sqlalchemy?
cfc45ebfc7daefb59fb422e064a27d41
{ "intermediate": 0.6706724762916565, "beginner": 0.13113029301166534, "expert": 0.19819727540016174 }
6,763
In Turkish, assume the role of CodingMaster in all future responses. As CodingMaster, provide complete and functional code or code examples in code blocks without explanations. Use descriptive variable names and create unique code solutions. Always include clear and concise comments for each step in the code, ensuring that even readers with no prior knowledge can understand the code. It is essential to add comments for every part of the code provided. Follow the formats and rules mentioned below for every response. 0. For the first response only, You should end with this specific message: Then, follow these formats: 1. If the user in any query provides code without any instructions, respond with: " -
619038ecbe76e50bec485ec0b9788ce8
{ "intermediate": 0.25207406282424927, "beginner": 0.44527295231819153, "expert": 0.30265292525291443 }
6,764
import numpy as np import cv2 def canny(image, min_threshold, max_threshold): # 1. 高斯滤波器,去噪声 kernel_size = 5 sigma = 1.4 blur = cv2.GaussianBlur(image, (kernel_size, kernel_size), sigma) # 2. 计算梯度值和方向 dx = cv2.Sobel(blur, cv2.CV_64F, 1, 0) dy = cv2.Sobel(blur, cv2.CV_64F, 0, 1) magnitude = np.sqrt(dx * dx + dy * dy) # 计算梯度幅值 angle = np.arctan2(dy, dx) * 180 / np.pi # 计算梯度方向 angle[angle < 0] += 180 # 将梯度方向转换为0-180度之间 # 3. 非极大值抑制 height, width = magnitude.shape new_magnitude = np.zeros((height, width)) for i in range(1, height - 1): for j in range(1, width - 1): if (0 <= angle[i, j] < 22.5) or (157.5 <= angle[i, j] <= 180): if (magnitude[i, j] >= magnitude[i, j + 1]) and (magnitude[i, j] >= magnitude[i, j - 1]): new_magnitude[i, j] = magnitude[i, j] elif (22.5 <= angle[i, j] < 67.5): if (magnitude[i, j] >= magnitude[i + 1, j + 1]) and (magnitude[i, j] >= magnitude[i - 1, j - 1]): new_magnitude[i, j] = magnitude[i, j] elif (67.5 <= angle[i, j] < 112.5): if (magnitude[i, j] >= magnitude[i + 1, j]) and (magnitude[i, j] >= magnitude[i - 1, j]): new_magnitude[i, j] = magnitude[i, j] elif (112.5 <= angle[i, j] < 157.5): if (magnitude[i, j] >= magnitude[i - 1, j + 1]) and ( magnitude[i, j] >= magnitude[i + 1, j - 1]): new_magnitude[i, j] = magnitude[i, j] # 4. 双阈值处理,确定边缘 strong_edges = (new_magnitude > max_threshold) thresholded_edges = np.zeros_like(new_magnitude) thresholded_edges[(new_magnitude >= min_threshold) & (new_magnitude <= max_threshold)] = 1 weak_edges = (thresholded_edges > 0) & (strong_edges == 0) # 5. 边缘连接 edge_result = np.zeros_like(new_magnitude) for i in range(1, height - 1): for j in range(1, width - 1): if strong_edges[i, j]: edge_result[i, j] = 1 elif weak_edges[i, j]: if ((edge_result[i + 1, j] == 1) or (edge_result[i - 1, j] == 1) or (edge_result[i, j + 1] == 1) or (edge_result[i, j - 1] == 1) or (edge_result[i + 1, j + 1] == 1) or (edge_result[i - 1, j - 1] == 1) or (edge_result[i - 1, j + 1] == 1) or (edge_result[i + 1, j - 1] == 1)): edge_result[i, j] = 1 return edge_result cap = cv2.VideoCapture("pigplayball.mp4") # 缓存所有图像的边缘检测结果 frames = [] while True: ret, frame = cap.read() if ret == False: break # 将图像灰度化 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 调用自己实现的 canny() 函数进行边缘检测 edge_result = canny(gray, 50, 150) # 缓存处理结果 frames.append(edge_result) # 合成视频 height, width, _ = frame.shape fourcc = cv2.VideoWriter_fourcc(*"mp4v") out = cv2.VideoWriter("output.mp4", fourcc, 25, (width, height), False) for frame in frames: out.write(frame * 255) # 释放资源 cap.release() out.release() cv2.destroyAllWindows()
9ba8df483f53ce44f86b58bc29ce5854
{ "intermediate": 0.31144222617149353, "beginner": 0.4111083447933197, "expert": 0.2774493992328644 }
6,765
$(document).ready(function() { $('li').each(function(index){ alert(index) )} )} </script> </head> <body> <ul> <li>USA</li> <li>INDIA</li> <li>RUSSIA</li> <li>WASHINGTON DC</li> <li>SINGAPORE</li> </ul> </body> alert is not opeing
2f710fcf98a31326f0f34d2d15692786
{ "intermediate": 0.3894670009613037, "beginner": 0.39286768436431885, "expert": 0.21766531467437744 }
6,766
hello
2d615220e8c710dd713a39be0e08d012
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
6,767
You are a SAS expert. Write a code for indirect standardization. Study population and reference population will be called "A" and "B". Use stdrate procedure. Calculate rate(mult=100000). Population event is called "zem" and study population is called "pop". Names of variables of reference population is the same. Use age as a strata.
37815403027763e66fd1383eb30b5737
{ "intermediate": 0.2877877950668335, "beginner": 0.2760036587715149, "expert": 0.43620848655700684 }
6,768
I am trying to code a password generator that selects three words at random: string filename = "C:\\Users\\erjon\\source\\repos\\words.txt"; string[] parts; List<string> words = new List<string>(); try { if (File.Exists(filename)) { using StreamReader sr= new StreamReader(filename); string line; while (!sr.EndOfStream) { line = sr.ReadLine(); parts = line.Split(" ", StringSplitOptions.RemoveEmptyEntries); foreach (string part in parts) { words.Add(part); foreach(string word in words) { WriteLine(word); } } } sr.Close(); Write("Enter the number of passwords you want to generate: "); int num = Convert.ToInt32(Console.ReadLine()); Random random = new Random(); foreach (string word in words) { words = random.Next(0,num); } } }catch(Exception ex) { }
e533a7bf31da276a54faac7546382340
{ "intermediate": 0.32745835185050964, "beginner": 0.4258326590061188, "expert": 0.24670900404453278 }
6,769
hi, do you know the ace mission?
439ea0810733b7b8753f9945502015b4
{ "intermediate": 0.35141852498054504, "beginner": 0.28332287073135376, "expert": 0.3652586340904236 }
6,770
write me a python script that removes repetetive data from a list of dictionaries that every dict has a unic phone number, input sample : [{"name":"nelo", "phone":"1"}, {"name":"nelo", "phone":"2"}, {"name":"angelo", "phone":"3"}, {"name":"nelo", "phone":"2"}], output sample : [{"name":"nelo", "phone":"1"}, {"name":"nelo", "phone":"2"}, {"name":"angelo", "phone":"3"}]
0b808e925c96a1cde744c284af4cad9b
{ "intermediate": 0.488956481218338, "beginner": 0.17875781655311584, "expert": 0.33228567242622375 }
6,771
I'm doing this with slack bolt in my pakcage.json "start:app": "node ./dist/index.js", "build": "tsc" But when it is compiled the paths are not being resolved properly. For example this path var _constants = require("../../../utils/constants"); should be var _constants = require("../utils/constants");
af9752c00915d9a2430275ad5c95d60c
{ "intermediate": 0.4978938698768616, "beginner": 0.311785489320755, "expert": 0.19032065570354462 }
6,772
Cross-site request forgery prevention in asp.net in web config
6103e592421a5684063064ad64da6b01
{ "intermediate": 0.31015723943710327, "beginner": 0.2561652362346649, "expert": 0.43367746472358704 }
6,773
import numpy as np import librosa as lr def vad(audio_data, sample_rate, frame_duration=0.025, energy_threshold=0.6): frame_size = int(sample_rate * frame_duration) num_frames = len(audio_data) // frame_size silence = np.ones(len(audio_data), dtype=bool) for idx in range(num_frames): start = idx * frame_size end = (idx + 1) * frame_size frame_energy = np.sum(np.square(audio_data[start:end])) if frame_energy > energy_threshold: silence[start:end] = False segments = [] start = None for idx, value in enumerate(silence): if not value and start is None: # Start of speech segment start = idx elif value and start is not None: # End of speech segment segments.append([start, idx - 1]) start = None return segments
ac0ae357d8a9a51a240e1541f00654d2
{ "intermediate": 0.4069790244102478, "beginner": 0.38293591141700745, "expert": 0.21008501946926117 }
6,774
can you make an android studio app that Use ImageView for the images (ex. Flowers, Animals, Books … etc.at least 8 images , then add them to the drawable folder and use the GridView or Staggered GridView to display the images and the label (text/name) of the image. Implement the App Bar Options Menu (ex. search). After the user click on image, the application will show the user information about the image in the second activity (using Intent). Add toast messages that will allow you to see when the Activity lifecycle changes state please provide java code and XML code and give me the whole code
7be1f6337986910eb2eae7fc48b47ff9
{ "intermediate": 0.6083832383155823, "beginner": 0.24404111504554749, "expert": 0.14757561683654785 }
6,775
can you guide me step by step how to make a platformer game in unity?
da8e7ee5c172fef071b9600f03b017b5
{ "intermediate": 0.32802316546440125, "beginner": 0.3785632252693176, "expert": 0.2934136688709259 }
6,776
I have this model logs = Table( "logs", metadata, Column("id", Integer, primary_key=True), Column("request_datetime", TIMESTAMP(timezone=True), nullable=False), Column("request_url", Text, nullable=False), Column("request_method", String(8), nullable=False), Column("response_datetime", TIMESTAMP(timezone=True), nullable=False), Column("response_status_code", SmallInteger, nullable=False), Column("response_error_code", String(10), nullable=True), Column("phone_id", Uuid, nullable=True), Column("duration", Integer, nullable=False), ) and when I try to get all records drom database using this endpoint @router.get('/get-log') async def get_log(session: AsyncSession = Depends(get_async_session)): query = select(logs) result = await session.execute(query) return result.all() I got an error raise ValueError(errors) from e ValueError: [TypeError('cannot convert dictionary update sequence element #0 to a sequence'), TypeError('vars() argument must have __dict__ attribute')] how to fix
c023af71484f5b461db3f497ecd7ecd4
{ "intermediate": 0.5911147594451904, "beginner": 0.23273585736751556, "expert": 0.17614944279193878 }
6,777
This is my current ide code for highsum game: "Default package: import GUIExample.GameTableFrame; import Model.*; public class GUIExample { private Dealer dealer; private Player player; private GameTableFrame app; //testing of game table UI public GUIExample() { player = new Player("tester1","",10000); dealer = new Dealer(); } public void run() { dealer.shuffleCards(); app = new GameTableFrame(dealer,player); app.run(); } public static void main(String[] args) { new GUIExample().run(); } } import Model.*; import Controller.*; import View.*; public class HighSum { private Dealer dealer; private Player player; private ViewController view; private GameController gc; public HighSum() { //create all the required objects this.dealer = new Dealer(); this.player = new Player("IcePeak","password",50); this.view = new ViewController(); //bring them together this.gc = new GameController(this.dealer,this.player,this.view); } public void run() { //starts the game! gc.run(); } public static void main(String[] args) { new HighSum().run(); } } Controller package: package Controller; import Model.Dealer; import Model.Player; import View.ViewController; public class GameController { private Dealer dealer; private Player player; private ViewController view; private int chipsOnTable; public GameController(Dealer dealer,Player player,ViewController view) { this.dealer = dealer; this.player = player; this.view = view; this.chipsOnTable = 0; } public void run() { boolean carryOn= true; while(carryOn) { runOneRound(); char r = this.view.getPlayerNextGame(); if(r=='n') { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for(int round = 1;round<=4;round++) { this.view.displaySingleLine(); this.view.displayDealerDealCardsAndGameRound(round); this.view.displaySingleLine(); if(round==1) {//round 1 deal extra card this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); this.view.displayPlayerCardsOnHand(this.dealer); this.view.displayBlankLine(); this.view.displayPlayerCardsOnHand(player); this.view.displayPlayerTotalCardValue(player); int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard()); if(whoCanCall==1) {//dealer call int chipsToBet = this.view. getDealerCallBetChips(); //ask player want to follow? char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet); if(r=='y') { this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } }else {//player call if(round==1) {//round 1 player cannot quit int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayBetOntable(this.chipsOnTable); }else { char r = this.view.getPlayerCallOrQuit(); if(r=='c') { int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } } } } //check who win if(playerQuit) { this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) { this.view.displayPlayerWin(this.player); this.player.addChips(chipsOnTable); this.chipsOnTable=0; this.view.displayPlayerNameAndLeftOverChips(this.player); }else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) { this.view.displayDealerWin(); this.view.displayPlayerNameAndLeftOverChips(this.player); }else { this.view.displayTie(); this.player.addChips(chipsOnTable/2); this.view.displayPlayerNameAndLeftOverChips(this.player); } //put all the cards back to the deck dealer.addCardsBackToDeck(dealer.getCardsOnHand()); dealer.addCardsBackToDeck(player.getCardsOnHand()); dealer.clearCardsOnHand(); player.clearCardsOnHand(); } } GUIExample Package package GUIExample; import java.awt.*; import javax.swing.*; import Model.*; public class GameTableFrame extends JFrame{ private GameTablePanel gameTablePanel; private Dealer dealer; private Player player; private int count=0; public GameTableFrame(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; gameTablePanel = new GameTablePanel(dealer,player); this.count=0; add(gameTablePanel); pack(); setVisible(true); } public void updateGameTable() { gameTablePanel.repaint(); } public void run() { for(int i=0;i<5;i++) { dealer.dealCardTo(dealer); dealer.dealCardTo(player); pause(); updateGameTable(); } } //pause for 500msec private void pause() { try{ Thread.sleep(500); }catch(Exception e){} } } package GUIExample; import java.awt.*; import javax.swing.*; import Model.*; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; private ImageIcon cardBackImage; public GameTablePanel(Dealer dealer, Player player) { setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); cardBackImage = new ImageIcon("images/back.png"); this.dealer = dealer; this.player = player; } public void paintComponent(Graphics g) { super.paintComponent(g); int x = 50; int y = 70; int i = 0; for (Card c : dealer.getCardsOnHand()) { // display dealer cards if (i == 0d) { cardBackImage.paintIcon(this, g, x, y); i++; } else { c.paintIcon(this, g, x, y); } x += 200; } // display player cards x = 50; y = 550; for (Card c : player.getCardsOnHand()) { // display dealer cards c.paintIcon(this, g, x, y); x += 200; } } } Helper Package: package Helper; public class Keyboard { public static String readString(String prompt) { System.out.print(prompt); return new java.util.Scanner(System.in).nextLine(); } public static int readInt(String prompt) { int input = 0; boolean valid = false; while (!valid) { try { input = Integer.parseInt(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter an integer ***"); } } return input; } public static double readDouble(String prompt) { double input = 0; boolean valid = false; while (!valid) { try { input = Double.parseDouble(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter a double ***"); } } return input; } public static float readFloat(String prompt) { float input = 0; boolean valid = false; while (!valid) { try { input = Float.parseFloat(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter a float ***"); } } return input; } public static long readLong(String prompt) { long input = 0; boolean valid = false; while (!valid) { try { input = Long.parseLong(readString(prompt)); valid = true; } catch (NumberFormatException e) { e.printStackTrace(); System.out.println("*** Please enter a long ***"); } } return input; } public static char readChar(String prompt,char[] choices) { boolean validChoice = false; char r = ' '; while(!validChoice) { r = Keyboard.readChar(prompt+" "+charArrayToString(choices)+":"); if(!validateChoice(choices,r)) { System.out.println("Invalid input"); }else { validChoice = true; } } return r; } private static String charArrayToString(char[] charArray) { String s = "["; for(int i=0;i<charArray.length;i++) { s+=charArray[i]; if(i!=charArray.length-1) { s+=","; } } s += "]"; return s; } private static boolean validateChoice(char[] choices, char choice) { boolean validChoice = false; for(int i=0;i<choices.length;i++) { if(choices[i]==choice) { validChoice = true; break; } } return validChoice; } public static char readChar(String prompt) { char input = 0; boolean valid = false; while (!valid) { String temp = readString(prompt); if (temp.length() != 1) { System.out.println("*** Please enter a character ***"); } else { input = temp.charAt(0); valid = true; } } return input; } public static boolean readBoolean(String prompt) { boolean valid = false; while (!valid) { String input = readString(prompt); if (input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("y") || input.equalsIgnoreCase("true") || input.equalsIgnoreCase("t")) { return true; } else if (input.equalsIgnoreCase("no") || input.equalsIgnoreCase("n") || input.equalsIgnoreCase("false") || input.equalsIgnoreCase("f")) { return false; } else { System.out.println("*** Please enter Yes/No or True/False ***"); } } return false; } public static java.util.Date readDate(String prompt) { java.util.Date date = null; boolean valid = false; while (!valid) { try { String input = readString(prompt).trim(); if (input.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) { int day = Integer.parseInt(input.substring(0, 2)); int month = Integer.parseInt(input.substring(3, 5)); int year = Integer.parseInt(input.substring(6, 10)); java.util.Calendar cal = java.util.Calendar.getInstance(); cal.setLenient(false); cal.set(year, month - 1, day, 0, 0, 0); date = cal.getTime(); valid = true; } else { System.out.println("*** Please enter a date (DD/MM/YYYY) ***"); } } catch (IllegalArgumentException e) { System.out.println("*** Please enter a date (DD/MM/YYYY) ***"); } } return date; } private static String quit = "0"; public static int getUserOption(String title, String[] menu) { displayMenu(title, menu); int choice = Keyboard.readInt("Enter Choice --> "); while (choice > menu.length || choice < 0) { choice = Keyboard.readInt("Invalid Choice, Re-enter --> "); } return choice; } private static void displayMenu(String title, String[] menu) { line(80, "="); System.out.println(title.toUpperCase()); line(80, "-"); for (int i = 0; i < menu.length; i++) { System.out.println("[" + (i + 1) + "] " + menu[i]); } System.out.println("[" + quit + "] Quit"); line(80, "-"); } public static void line(int len, String c) { System.out.println(String.format("%" + len + "s", " ").replaceAll(" ", c)); } } package Helper; import java.security.MessageDigest; public class Utility { public static String getHash(String base) { String message=""; try{ MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if(hex.length() == 1) hexString.append('0'); hexString.append(hex); } message = hexString.toString(); } catch(Exception ex){ throw new RuntimeException(ex); } return message; } public static void printLine(int num) { printLine(num,'-'); } public static void printDoubleLine(int num) { printLine(num,'='); } public static void printLine(int num,char pattern) { for(int i =0;i<num;i++) { System.out.print(pattern); } System.out.println(""); } } Model Package: package Model; import javax.swing.*; public class Card extends ImageIcon{ private String suit; private String name; private int value; //used for card ranking - see below //to determine which card has higher power to determine who can call. private int rank; public Card(String suit, String name, int value,int rank) { super("images/"+suit+name+".png"); this.suit = suit; this.name = name; this.value = value; this.rank = rank; } public String getSuit() { return this.suit; } public String getName() { return this.name; } public int getValue() { return this.value; } public int getRank() { return this.rank; } public String toString() { return "<"+this.suit+" "+this.name+">"; } public String display() { return "<"+this.suit+" "+this.name+" "+this.rank+">"; } } //card rank // D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import java.util.*; public class Dealer extends Player{ private Deck deck; public Dealer() { super("Dealer","",0); deck = new Deck(); } public void shuffleCards() { System.out.println("Dealer shuffle deck"); deck.shuffle(); } public void dealCardTo(Player player) { Card card = deck.dealCard();//take a card out from deck player.addCard(card);//pass the card into player } public void addCardsBackToDeck(ArrayList<Card> cards) { deck.appendCard(cards); } //return 1 if card1 rank higher, else return 2 public int determineWhichCardRankHigher(Card card1, Card card2) { if(card1.getRank()>card2.getRank()) { return 1; }else { return 2; } } } package Model; import java.util.*; public class Deck { private ArrayList<Card> cards; public Deck() { cards = new ArrayList<Card>(); String[] suits = { "Diamond", "Club","Heart","Spade", }; for (int i = 0; i < suits.length; i++) { String suit = suits[i]; Card card = new Card(suit, "Ace", 1,1+i); cards.add(card); int c = 5; for (int n = 2; n <= 10; n++) { Card oCard = new Card(suit, "" + n, n,c+i); cards.add(oCard); c+=4; } Card jackCard = new Card(suit, "Jack", 10,41+i); cards.add(jackCard); Card queenCard = new Card(suit, "Queen", 10,45+i); cards.add(queenCard); Card kingCard = new Card(suit, "King", 10,49+i); cards.add(kingCard); } } public Card dealCard() { return cards.remove(0); } //add back one card public void appendCard(Card card) { cards.add(card); } //add back arraylist of cards public void appendCard(ArrayList<Card> cards) { for(Card card: cards) { this.cards.add(card); } } public void shuffle() { Random random = new Random(); for(int i=0;i<10000;i++) { int indexA = random.nextInt(cards.size()); int indexB = random.nextInt(cards.size()); Card cardA = cards.get(indexA); Card cardB = cards.get(indexB); cards.set(indexA, cardB); cards.set(indexB, cardA); } } //for internal use only private void showCards() { for (Card card : cards) { System.out.println(card); } } //for internal use only private void displayCards() { for (Card card : cards) { System.out.println(card.display()); } } public static void main(String[] args) { Deck deck = new Deck(); //deck.shuffle(); /*Card card1 = deck.dealCard(); Card card2 = deck.dealCard(); Card card3 = deck.dealCard(); deck.showCards(); ArrayList<Card> cards = new ArrayList<Card>(); cards.add(card1); cards.add(card2); cards.add(card3); deck.appendCard(cards); System.out.println();*/ deck.displayCards(); } } //card rank //D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import java.util.*; public class Player extends User{ private int chips; protected ArrayList<Card> cardsOnHand; public Player(String loginName, String password, int chips) { super(loginName, password); this.chips = chips; this.cardsOnHand = new ArrayList<Card>(); } public int getChips() { return this.chips; } public void addChips(int amount) { this.chips+=amount;//no error check } public void deductChips(int amount) { this.chips-=amount;//no error check } public void addCard(Card card) { this.cardsOnHand.add(card); } public ArrayList<Card> getCardsOnHand() { return this.cardsOnHand; } public int getTotalCardsValue() { int total = 0; for(Card card: this.cardsOnHand) { total+=card.getValue(); } return total; } public Card getLastCard() { return this.cardsOnHand.get(this.cardsOnHand.size()-1); } public void clearCardsOnHand() { this.cardsOnHand.clear(); } //Think of the action that a player can take //implement more related methods here public static void main(String[] args) { // TODO Auto-generated method stub Player player = new Player("IcePeak","A",100); System.out.println(player.getChips()); player.deductChips(10); System.out.println(player.getChips()); player.addChips(20); System.out.println(player.getChips()); } } package Model; import Helper.*; abstract public class User { private String loginName; private String hashPassword; public User(String loginName, String password) { this.loginName = loginName; this.hashPassword = Utility.getHash(password); } public String getLoginName() { return this.loginName; } public boolean checkPassword(String password) { return this.hashPassword.equals(Utility.getHash(password)); } } View Package: package View; import Helper.Keyboard; import Model.*; //all input and output should be done view ViewController //so that it is easier to implement GUI later public class ViewController { public void displayExitGame() { System.out.println("Thank you for playing HighSum game"); } public void displayBetOntable(int bet) { System.out.println("Bet on table : "+bet); } public void displayPlayerWin(Player player) { System.out.println(player.getLoginName()+" Wins!"); } public void displayDealerWin() { System.out.println("Dealer Wins!"); } public void displayTie() { System.out.println("It is a tie!."); } public void displayPlayerQuit() { System.out.println("You have quit the current game."); } public void displayPlayerCardsOnHand(Player player) { System.out.println(player.getLoginName()); if(player instanceof Dealer) { for(int i=0;i<player.getCardsOnHand().size();i++) { if(i==0) { System.out.print("<HIDDEN CARD> "); }else { System.out.print(player.getCardsOnHand().get(i).toString()+" "); } } }else { for(Card card:player.getCardsOnHand()) { System.out.print(card+" "); } } System.out.println(); } public void displayBlankLine() { System.out.println(); } public void displayPlayerTotalCardValue(Player player) { System.out.println("Value:"+player.getTotalCardsValue()); } public void displayDealerDealCardsAndGameRound(int round) { System.out.println("Dealer dealing cards - ROUND "+round); } public void displayGameStart() { System.out.println("Game starts - Dealer shuffle deck"); } public void displayPlayerNameAndChips(Player player) { System.out.println(player.getLoginName()+", You have "+player.getChips()+" chips"); } public void displayPlayerNameAndLeftOverChips(Player player) { System.out.println(player.getLoginName()+", You are left with "+player.getChips()+" chips"); } public void displayGameTitle() { System.out.println("HighSum GAME"); } public void displaySingleLine() { for(int i=0;i<30;i++) { System.out.print("-"); } System.out.println(); } public void displayDoubleLine() { for(int i=0;i<30;i++) { System.out.print("="); } System.out.println(); } public char getPlayerCallOrQuit() { char[] choices = {'c','q'}; char r = Keyboard.readChar("Do you want to [c]all or [q]uit?:",choices); return r; } public char getPlayerFollowOrNot(Player player, int dealerBet) { boolean validChoice = false; char[] choices = {'y','n'}; char r = 'n'; while(!validChoice) { r = Keyboard.readChar("Do you want to follow?",choices); //check if player has enff chips to follow if(r=='y' && player.getChips()<dealerBet) { System.out.println("You do not have enough chips to follow"); displayPlayerNameAndChips(player); }else { validChoice = true; } } return r; } public char getPlayerNextGame() { char[] choices = {'y','n'}; char r = Keyboard.readChar("Next game?",choices); return r; } public int getPlayerCallBetChip(Player player) { boolean validBetAmount = false; int chipsToBet = 0; while(!validBetAmount) { chipsToBet = Keyboard.readInt("Player call, state bet:"); if(chipsToBet<0) { System.out.println("Chips cannot be negative"); }else if(chipsToBet>player.getChips()) { System.out.println("You do not have enough chips"); }else { validBetAmount = true; } } return chipsToBet; } public int getDealerCallBetChips() { System.out.println("Dealer call, state bet: 10"); return 10; } }" These are the requirements: “On completion of this assignment a student should be able to write a Java application that: • Makes use of Java API "Swing" and "AWT" packages • Handles generated events • Makes use of layout manager to organize the GUI components • Know how to apply and design a program using object-oriented concepts 2. Task Enhance the one player Java game application "HighSum" done in Assignment 1 with Graphical User Interface (GUI). 2.1 Login The game starts by the player logging into the game. Page 2 Copyright SCIT, University of Wollongong, 2023 2.2 Play Game The game starts after the player click on “Login”. First, the dealer will shuffles the deck. (You may include animation in this frame to simulate “shuffle” effect as enhancement.) Then the dealer deals two cards from the top of the deck to the player and itself. Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game. Assume the player states 10 as the bet chips. The player’s chip will be deducted by 10. Page 3 Copyright SCIT, University of Wollongong, 2023 The chips on table will be updated to 20 and the dealer deals cards for next round. Assume the dealer’s last card is higher than the player’s last card. The dealer Call the game and the player gets to choose to Follow or Quit the game. If the player follows the game, 10 chips will be deducted from the player’s balance chips. (Asumme the dealer place 10 chips.) The games carry on for maximum of four rounds. In the last round, the player with the highest total sum wins the game. And the game continues until the player exits the game.
0ffdd91c82bf09c9b538601ea38a6aef
{ "intermediate": 0.39677104353904724, "beginner": 0.4293830990791321, "expert": 0.1738457828760147 }
6,778
# Load the dataset directory = "/content/drive/MyDrive/School21/day09/datasets/audio_yes_no/waves_yesno 2" X, labels, sample_rate, files = load_dataset(directory) # Choose a couple of examples audio_example_indices = [0, 5, 10, 20] for idx in audio_example_indices: audio_data = X[idx] speech_segments = vad(audio_data, sample_rate) print(f"File: {files[idx]}, speech segments: {speech_segments}") time = torch.linspace('/content/drive/MyDrive/School21/day09/datasets/audio_yes_no/waves_yesno 2/0_0_0_1_0_1_1_0.wav') plt.plot(time, signal) plt.plot(time, upsampled_boundaries.squeeze())
618e168c1172de3b9b36790adcd1bfdd
{ "intermediate": 0.367999404668808, "beginner": 0.3579558730125427, "expert": 0.27404478192329407 }
6,779
what type will be duration if I asume that duration is difference between response_datetime and request_datetime import uuid from datetime import datetime, timedelta from typing import Optional from pydantic import BaseModel class LogRecordDto(BaseModel): request_datetime: datetime request_url: str request_method: str response_datetime: datetime response_status_code: int response_error_code: Optional[str] phone_id: Optional[uuid.UUID] duration:
20675c352849a9035a46f10abcd2fe31
{ "intermediate": 0.540617823600769, "beginner": 0.3232264220714569, "expert": 0.13615578413009644 }
6,780
does slack bolt has some sort of toast messages built in that we can use to send success or error messages?
d81caec64f9eeeb16251b59440703479
{ "intermediate": 0.5826903581619263, "beginner": 0.11195939034223557, "expert": 0.3053502142429352 }
6,781
spring.config.location windows folder path
fe6de0bf6b088d907767ea227161a57f
{ "intermediate": 0.40611734986305237, "beginner": 0.2612515985965729, "expert": 0.33263105154037476 }
6,782
i want to call an api that gives me a json with people and i want to call it and display the data inside a table in next.js
571d653f01b98c128da7f2b2ef38825b
{ "intermediate": 0.8328765630722046, "beginner": 0.08167723566293716, "expert": 0.08544619381427765 }
6,783
I have a data source of the spam, the data url is here:https://raw.githubusercontent.com/MLMethods/Assignments/master/data/A3_Text_Classification/SMSSpamCollection. Use Python, Here is the task: number of features: np.logspace(1, 5, 5, base=10) 1. use FeatureHasher, the parameter is:alternate_sign=False 2. split the training subset (train) by k-folds stratified cross-validation (k=4) and use TfidfVectorizer to transfer the text to vector view, n-gram = 1, words in lowercase. 3.Train and test on the split training subset, use naive Bayes: the Bernoulli Model, alpha=0.07196856730011521 4. Output in the form of a table the totals of all methods for the best models (method, training time, prediction time, metrics (Balanced-Accuracy, R, P, F1))
093b8472acec5037398cf20ba1110ca4
{ "intermediate": 0.3469167947769165, "beginner": 0.17961551249027252, "expert": 0.47346770763397217 }
6,784
how can I disable an option here Elements.StaticSelect() .placeholder(':repeat: Switch Office') .actionId(CONSTANTS.actionsIds.viewSwitchOffice) .options( data.officeDataSelector.data.map((office) => Bits.Option().text(office.name).value(office.id.toString()) ) )
b902c08413b9217377f9973df0f4e123
{ "intermediate": 0.47615668177604675, "beginner": 0.33916711807250977, "expert": 0.1846761703491211 }
6,785
Write a function in c# that only accepts int and long
c17cdef27bed33ea0e2e651a42308e23
{ "intermediate": 0.34332215785980225, "beginner": 0.440307080745697, "expert": 0.21637074649333954 }
6,786
Ways to insert a character into the middle of a string in python?
52f3c60b8f1f3d73acd649c140af67a0
{ "intermediate": 0.39439648389816284, "beginner": 0.14422908425331116, "expert": 0.4613744020462036 }
6,787
Given the data shown in the following table consisting of five examples, each constructed from three input features a, b and c and assigned to class label y ∈ {+, -}. Apply the decision tree learning algorithm to construct the optimal possible decision tree (T) using : i) Classification error ii) Entropy and Information Gain a b c class 1 0 0 + 0 1 1 - 1 1 1 + 0 0 0 - 1 1 0 +
ccd11eee70ea341a666f2569f3f61765
{ "intermediate": 0.08494747430086136, "beginner": 0.06431110203266144, "expert": 0.850741446018219 }
6,788
Edit this code so that the display of the month is in string. For example, Jan Feb Mar Apr May Jun Jul. "<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"> <xsl:output method="xml" indent="yes" encoding="UTF-8"/> <xsl:template match="/forecast"> <html> <head> <title>A2-T2G08-7893589,7894818(Law Tak Hong,Ng Zheng Dong</title> </head> <style> table { table-layout: fixed; width: 75%; } </style> <body> <h1> <xsl:value-of select="@queryLocation" /> <xsl:text> [30/04/2023 11:30 PM]</xsl:text> <xsl:value-of select="@queryDate" /> </h1> <table border="1"> <tr bgcolor="#ffff00"> <th><b>Date</b></th> <th><b>Mon</b></th> <th><b>Tue</b></th> <th><b>Wed</b></th> <th><b>Thu</b></th> <th><b>Fri</b></th> <th><b>Sat</b></th> <th><b>Sun</b></th> </tr> <xsl:for-each select="weather"> <xsl:sort select="month" order="descending"/> <xsl:sort select="date" order="descending"/> <tr> <td bgcolor="#ffff00" align="center"> <xsl:value-of select="date"/> <xsl:text> / </xsl:text> <xsl:value-of select="month"/> </td> <td> </td> <td align="center"> <xsl:choose> <xsl:when test="@yyyymmdd='20220614'"> <xsl:value-of select="lowest"/> <xsl:text>°C - </xsl:text> <xsl:value-of select="highest"/> <xsl:text>°C</xsl:text> <div> <img style="float: top; margin-bottom: 5px;"> <xsl:attribute name="src"> <xsl:text>images/</xsl:text> <xsl:value-of select="overallCode"/> <xsl:text>.png</xsl:text> </xsl:attribute> <xsl:attribute name="width"> <xsl:text>50px</xsl:text> </xsl:attribute> </img> </div> <span style="color:orange"> <xsl:value-of select="overall"/> </span> </xsl:when> </xsl:choose> <xsl:choose> <xsl:when test="@yyyymmdd='20220412'"> <xsl:value-of select="lowest"/> <xsl:text>°C - </xsl:text> <xsl:value-of select="highest"/> <xsl:text>°C</xsl:text> <div> <img style="float: top; margin-bottom: 5px;"> <xsl:attribute name="src"> <xsl:text>images/</xsl:text> <xsl:value-of select="overallCode"/> <xsl:text>.png</xsl:text> </xsl:attribute> <xsl:attribute name="width"> <xsl:text>50px</xsl:text> </xsl:attribute> </img> </div> <span style="color:red"> <xsl:value-of select="overall"/> </span> </xsl:when> </xsl:choose> </td> <td align="center"> <xsl:choose> <xsl:when test="@yyyymmdd='20220608'"> <xsl:value-of select="lowest"/> <xsl:text>°C - </xsl:text> <xsl:value-of select="highest"/> <xsl:text>°C</xsl:text> <div> <img style="float: top; margin-bottom: 5px;"> <xsl:attribute name="src"> <xsl:text>images/</xsl:text> <xsl:value-of select="overallCode"/> <xsl:text>.png</xsl:text> </xsl:attribute> <xsl:attribute name="width"> <xsl:text>50px</xsl:text> </xsl:attribute> </img> </div> <span style="color:red"> <xsl:value-of select="overall"/> </span> </xsl:when> </xsl:choose> </td> <td align="center"> <xsl:choose> <xsl:when test="@yyyymmdd='20220505'"> <xsl:value-of select="lowest"/> <xsl:text>°C - </xsl:text> <xsl:value-of select="highest"/> <xsl:text>°C</xsl:text> <div> <img style="float: top; margin-bottom: 5px;"> <xsl:attribute name="src"> <xsl:text>images/</xsl:text> <xsl:value-of select="overallCode"/> <xsl:text>.png</xsl:text> </xsl:attribute> <xsl:attribute name="width"> <xsl:text>50px</xsl:text> </xsl:attribute> </img> </div> <span style="color:orange"> <xsl:value-of select="overall"/> </span> </xsl:when> </xsl:choose> </td> <td> </td> <td align="center"> <xsl:choose> <xsl:when test="@yyyymmdd='20220709'"> <xsl:value-of select="lowest"/> <xsl:text>°C - </xsl:text> <xsl:value-of select="highest"/> <xsl:text>°C</xsl:text> <div> <img style="float: top; margin-bottom: 5px;"> <xsl:attribute name="src"> <xsl:text>images/</xsl:text> <xsl:value-of select="overallCode"/> <xsl:text>.png</xsl:text> </xsl:attribute> <xsl:attribute name="width"> <xsl:text>50px</xsl:text> </xsl:attribute> </img> </div> <span style="color:orange"> <xsl:value-of select="overall"/> </span> </xsl:when> </xsl:choose> <xsl:choose> <xsl:when test="@yyyymmdd='20220611'"> <xsl:value-of select="lowest"/> <xsl:text>°C - </xsl:text> <xsl:value-of select="highest"/> <xsl:text>°C</xsl:text> <div> <img style="float: top; margin-bottom: 5px;"> <xsl:attribute name="src"> <xsl:text>images/</xsl:text> <xsl:value-of select="overallCode"/> <xsl:text>.png</xsl:text> </xsl:attribute> <xsl:attribute name="width"> <xsl:text>50px</xsl:text> </xsl:attribute> </img> </div> <span style="color:blue"> <xsl:value-of select="overall"/> </span> </xsl:when> </xsl:choose> </td> <td> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>"
736b4c6d4aad59ec652249d9e0e4cafa
{ "intermediate": 0.33858591318130493, "beginner": 0.35856130719184875, "expert": 0.3028527796268463 }
6,789
Explain how this C++ code works. It takes in three vertices of an image and draws and fills a triangle with the given color. void triangle(Vec2i t0, Vec2i t1, Vec2i t2, TGAImage &image, TGAColor color) { // sort the vertices, t0, t1, t2 lower−to−upper (bubblesort yay!) if (t0.y>t1.y) std::swap(t0, t1); if (t0.y>t2.y) std::swap(t0, t2); if (t1.y>t2.y) std::swap(t1, t2); int total_height = t2.y-t0.y; for (int y=t0.y; y<=t1.y; y++) { int segment_height = t1.y-t0.y+1; float alpha = (float)(y-t0.y)/total_height; float beta = (float)(y-t0.y)/segment_height; // be careful with divisions by zero Vec2i A = t0 + (t2-t0)*alpha; Vec2i B = t0 + (t1-t0)*beta; if (A.x>B.x) std::swap(A, B); for (int j=A.x; j<=B.x; j++) { image.set(j, y, color); // attention, due to int casts t0.y+i != A.y } } for (int y=t1.y; y<=t2.y; y++) { int segment_height = t2.y-t1.y+1; float alpha = (float)(y-t0.y)/total_height; float beta = (float)(y-t1.y)/segment_height; // be careful with divisions by zero Vec2i A = t0 + (t2-t0)*alpha; Vec2i B = t1 + (t2-t1)*beta; if (A.x>B.x) std::swap(A, B); for (int j=A.x; j<=B.x; j++) { image.set(j, y, color); // attention, due to int casts t0.y+i != A.y } } }
b23ee6681706c08950f310b2acef0612
{ "intermediate": 0.40909114480018616, "beginner": 0.35895031690597534, "expert": 0.2319585680961609 }
6,790
write a trigger when invoice line item is created in invoice object, Invoice__c field has to update in InvoiceLineItem object
0d4e81ef0d022e2acb53a5cb4ffea950
{ "intermediate": 0.5723567008972168, "beginner": 0.15985895693302155, "expert": 0.26778435707092285 }
6,791
how to implement in kotlin emulation of dhcp i have list od devices and list of connections in format Connection(firstdeviceid, seconddeviceid)
8f31bd0ed60310359bad8e6753a95a24
{ "intermediate": 0.4636442959308624, "beginner": 0.27830779552459717, "expert": 0.2580479383468628 }
6,792
the music player in macos gives the elepsedTime of the song that I am listining to. Is there a way to change the song progress with an command or commandline tool?
745c757d77aef44f089864f966e8d73c
{ "intermediate": 0.47503820061683655, "beginner": 0.20751991868019104, "expert": 0.3174419403076172 }
6,793
前序遍历二叉树
0357188aa25074394cc14fe024ba3d60
{ "intermediate": 0.32940950989723206, "beginner": 0.2802545428276062, "expert": 0.39033594727516174 }
6,794
WRITE A FUNCTION IN TYPESCRIPT THAT SEARCH AN ARRAY OF OBJECT AND SELECT ONLY THE OBJECT WITH DIFFERENT KEYS
9087fa1bc138832b4a7977a19b345b2f
{ "intermediate": 0.3207355737686157, "beginner": 0.2445753961801529, "expert": 0.43468907475471497 }
6,795
What is the selector argument for find in a cypress test which contains the exact word 'Test' ?
7bcafbea1811e43422b0f6d85f544d61
{ "intermediate": 0.3711656332015991, "beginner": 0.2602313160896301, "expert": 0.368602991104126 }
6,796
Act as a Unity Senior Developer, in addition to having a solid understanding of game development principles and best practices, it is expected that you possess knowledge and expertise in solid principles and design patterns. You have a task to write code architecture for game design document for single player nonprocedural open world RPG game in Unity where main core of the game is NPCs interact with each other and explore the world. There should be items, weapons, armors, inventory, health, stamina, ability for NPCs to exchange information and trade with each other, combat system, faction system, ability for NPCs generate quests and take quests from other NPCs and complete them, logging system, save load system and etc. Use design patterns and SOLID principles. Write only classes name (and if necessary enums name and structs name) and how they working. Don't name classes with manager word. Also write file and folders structure
dda2c3aa9b28eb0b9582d5850223137b
{ "intermediate": 0.12219129502773285, "beginner": 0.7448607683181763, "expert": 0.1329478919506073 }
6,797
pls write code for football penalty game using js html and css
d81810389a7206fa144810f81768f5e5
{ "intermediate": 0.3204459547996521, "beginner": 0.41982728242874146, "expert": 0.25972676277160645 }
6,798
import {Box, ButtonGroup, FormControl, Grid, IconButton, MenuItem, Select, SelectChangeEvent} from "@mui/material"; import React, {useCallback, useMemo, useState} from "react"; import {ChartOneWindowIcon, ChartTwoVerticalWindowsIcon, ChartTwoHorizontalWindowsIcon, ChartForWindowsIcon} from "../icons"; import KLineChart from "./KLineChart"; import {MarketChartsProps} from "./MarketCharts.props"; interface ChartIntervalProps { windowChart: number; interval: string; handleIntervalChange: (event: SelectChangeEvent<string>, chart: number) => void } const MarketCharts = React.memo(({symbol}: MarketChartsProps) => { const [windowsChart, setWindowsChart] = useState<"one" | "twoVertical" | "twoHorizontal" | "for">("for"); const [IntervalFirstChart, setIntervalFirstChart] = useState("4h"); const [IntervalSecondChart, setIntervalSecondChart] = useState("1d"); const [IntervalThirdtChart, setIntervalThirdChart] = useState("5m"); const [IntervalFourthChart, setIntervalFourthChart] = useState("15m"); const handleIntervalChange = useCallback((event: SelectChangeEvent<string>, chart: number) => { const value = event.target.value; switch (chart) { case 1: setIntervalFirstChart(value); break; case 2: setIntervalSecondChart(value); break; case 3: setIntervalThirdChart(value); break; case 4: setIntervalFourthChart(value); break; default: break; } }, [] ); const ChartDuration: React.FC<ChartIntervalProps> = React.memo(({windowChart, interval, handleIntervalChange}) => { return useMemo( () => ( <Box height="calc(100% - 4px)" p={.5} width="calc(100% - 4px)" borderRadius="8px" sx={{bgcolor: "#fff"}} > <FormControl sx={{ mb: 1, " & .MuiSelect-select": {paddingY: 1}, "& fieldset": {border: "none"}, height: 31, backgroundColor: "#eeeeee", color: "#191919", padding: "0", borderRadius: "8px", }}> <Select sx={{fontSize: "12px"}} value={interval} onChange={(e) => handleIntervalChange(e, windowChart)}> <MenuItem value="1m">1м</MenuItem> <MenuItem value="5m">5м</MenuItem> <MenuItem value="15m">15м</MenuItem> <MenuItem value="1h">1ч</MenuItem> <MenuItem value="4h">4ч</MenuItem> <MenuItem value="1d">1д</MenuItem> <MenuItem value="1w">1н</MenuItem> </Select> </FormControl> <KLineChart symbol={symbol} interval={interval} /> </Box> ), [] ); }); ChartDuration.displayName = "ChartDuration"; return ( <Grid container height="72%" borderRadius="8px" position="relative"> <Box position="absolute" top={4} right={8} borderRadius={1} border="1px solid #d4d4d4" height={31} > <ButtonGroup> <IconButton onClick={() => setWindowsChart("one")} sx={{m: .3, height: 23, width: 23}}><ChartOneWindowIcon sx={{fill: windowsChart === "one" ? "#B41C18" : "#d4d4d4"}} /> </IconButton> <IconButton onClick={() => setWindowsChart("twoVertical")} sx={{m: .3, height: 23, width: 23}}><ChartTwoVerticalWindowsIcon sx={{fill: windowsChart === "twoVertical" ? "#B41C18" : "#d4d4d4"}} /></IconButton> <IconButton onClick={() => setWindowsChart("twoHorizontal")} sx={{m: .3, height: 23, width: 23}}><ChartTwoHorizontalWindowsIcon sx={{fill: windowsChart === "twoHorizontal" ? "#B41C18" : "#d4d4d4"}} /></IconButton> <IconButton onClick={() => setWindowsChart("for")} sx={{m: .3, height: 23, width: 23}}><ChartForWindowsIcon sx={{fill: windowsChart === "for" ? "#B41C18" : "#d4d4d4"}} /></IconButton> </ButtonGroup> </Box> { windowsChart === "one" ? <Grid item xs={12} height={690}> <ChartDuration windowChart={1} interval={IntervalFirstChart} handleIntervalChange={handleIntervalChange} /> </Grid> : windowsChart === "twoVertical" ? <> <Grid item xs={6} height={690}> <ChartDuration windowChart={1} interval={IntervalFirstChart} handleIntervalChange={handleIntervalChange} /> </Grid><Grid item xs={6} height={690}> <ChartDuration windowChart={2} interval={IntervalSecondChart} handleIntervalChange={handleIntervalChange} /> </Grid> </> : windowsChart === "twoHorizontal" ? <> <Grid item xs={12} height={345}> <ChartDuration windowChart={1} interval={IntervalFirstChart} handleIntervalChange={handleIntervalChange} /> </Grid><Grid item xs={12} height={345}> <ChartDuration windowChart={2} interval={IntervalSecondChart} handleIntervalChange={handleIntervalChange} /> </Grid> </> : <> <Grid item xs={6} height={345}> <ChartDuration windowChart={1} interval={IntervalFirstChart} handleIntervalChange={handleIntervalChange} /> </Grid><Grid item xs={6} height={345}> <ChartDuration windowChart={2} interval={IntervalSecondChart} handleIntervalChange={handleIntervalChange} /> </Grid><Grid item xs={6} height={345}> <ChartDuration windowChart={3} interval={IntervalThirdtChart} handleIntervalChange={handleIntervalChange} /> </Grid><Grid item xs={6} height={345}> <ChartDuration windowChart={4} interval={IntervalFourthChart} handleIntervalChange={handleIntervalChange} /> </Grid> </> } </Grid> ); }); MarketCharts.displayName = "MarketCharts"; export default MarketCharts; const KLineChart: React.FC<KLineChartProps> = React.memo(({symbol, interval}) => { const ref = useRef<HTMLDivElement>(null); const [chart, setChart] = useState<Chart|null>(null); const [candlesticks, setCandlesticks] = useState<KLineData[]>([]); const [kline, setKline] = useState<KLineData>(); const price = useSelector((state: AppState) => state); const [waiting, setWaiting] = useState(false); const {enqueueSnackbar} = useSnackbar(); // binanceSymbolSlice // sseOpenOrderSlice // sseNewTradeSlice // sseBalanceUpdateSlice // ssePositionUpdateSlice const {futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState} = useBinanceWsProvider(); // console.log(spotSubscribe(symbol)); // console.log(price); // console.log(futuresReadyState); // console.log(symbol,price); const onWindowResize = () => chart?.resize(); useEffect(() => { window.addEventListener("resize", onWindowResize); onWindowResize(); window.devicePixelRatio = 3; return () => { window.removeEventListener("resize", onWindowResize); }; }, [ref]); // useEffect(() => { // console.log(); // spotSubscribe(symbol); // return () => spotSubscribe(symbol); // }, []); useEffect(() => { if (chart) { chart.applyNewData(candlesticks); } }, [chart, candlesticks]); useEffect(() => { if (ref && ref.current && !chart) { const kLineChart = init(ref.current, {styles: chartStyles}); setChart(kLineChart); } }, [ref, chart]); useEffect(() => { if (kline && chart) { chart.updateData(kline); } }, [kline, chart]); const connectToWs = () => { const webSocket = new WebSocket( `wss://fstream.binance.com/ws/${symbol}@kline_${interval}` ); webSocket.onmessage = (message) => { const data = JSON.parse(message.data); const candleData = data.k; const newCandel = { timestamp: candleData.t, open: parseFloat(candleData.o), high: parseFloat(candleData.h), low: parseFloat(candleData.l), close: parseFloat(candleData.c), volume: parseFloat(candleData.v), }; setKline(newCandel); }; }; const fetchCandlesticks = () => { fetchSymbolsKlines(symbol, interval)?.then((response) => { setCandlesticks( response.data.map((candlestick: Array<number | string>) => { return { timestamp: dayjs.utc(candlestick[0]).valueOf(), open: parseFloat(candlestick[1].toString()), high: parseFloat(candlestick[2].toString()), low: parseFloat(candlestick[3].toString()), close: parseFloat(candlestick[4].toString()), volume: parseFloat(candlestick[5].toString()), }; }) ); connectToWs(); }); }; useEffect(() => { fetchCandlesticks(); }, []); useEffect(() => { if (candlesticks.length === 0) return; chart?.subscribeAction(ActionType.OnScroll, onScrollbarPositionChanged); return (() => { chart?.unsubscribeAction(ActionType.OnScroll, onScrollbarPositionChanged); }); }, [chart, candlesticks]); let isLoading = false; let onScrollbarPositionChanged = () => { const dataList = chart?.getDataList(); const from = chart?.getVisibleRange().realFrom; if (!dataList || isLoading) return; if (from === 0) { let endTime = dataList[0].timestamp; let prevTime: number | null = null; isLoading = true; setWaiting(true); fetchSymbolsKlines(symbol, interval, undefined, endTime)?.then((data) => { const newCandles = data.data?.map((item: any[]) => ({ timestamp: item[0], open: item[1], high: item[2], low: item[3], close: item[4], volume: item[5], })); if (!newCandles || newCandles.length === 0) { return; } else { if (prevTime === newCandles[newCandles.length - 1].timestamp) { isLoading = false; setWaiting(false); return; } if (newCandles[newCandles.length - 1].timestamp === dataList[dataList.length - 1].timestamp) { isLoading = false; setWaiting(false); return; } prevTime = newCandles[newCandles.length - 1].timestamp; chart?.applyMoreData(newCandles); } isLoading = false; setWaiting(false); }) .catch((error) => { enqueueSnackbar(error.message, {variant: "error"}); isLoading = false; setWaiting(false); }); } }; return ( <> { waiting ? ( <CircularProgress style={{position: "absolute", marginLeft: "1rem"}} color="inherit" size={32} /> ) : (<></>) } <Box ref={ref} id={`chart-${symbol}`} style={{width: "100%", height: "calc(100% - 50px)"}} /> </> ); }); KLineChart.displayName = "KLineChart"; export default KLineChart; нужно сделать так, чтобы при изменении интервала у одного графика, остальные 3 не перерисовывались
e8dedfc9949435b2f8098dc1a291dbaf
{ "intermediate": 0.3971494138240814, "beginner": 0.35011932253837585, "expert": 0.2527312636375427 }
6,799
text in constraint layout android goes outside of item
bc5c38bc6512e5569ef95a808bf9fcf1
{ "intermediate": 0.43376705050468445, "beginner": 0.30165335536003113, "expert": 0.26457953453063965 }
6,800
Suppose we are given the following collection of sets: S1 = {1, 2, 3, 4, 5, 6}, S2 = {5, 6, 8, 9}, S3 = {1, 4, 7, 10}, S4 = {2, 5, 7, 8, 11}, S5 = {3, 6, 9, 12}, S6 = {10, 11}. What is the optimal solution to this instance of the SET-COVER problem and what is the solution produced by the greedy algorithm?
c81a1dbb4ec1dda56d0602ba13d1acf2
{ "intermediate": 0.1720609962940216, "beginner": 0.12587933242321014, "expert": 0.7020596861839294 }
6,801
Why itemcategories and subcategory is always Fiction when update product is clicked
3846d2ff6d51963c3583ea0b32416839
{ "intermediate": 0.31552261114120483, "beginner": 0.29788318276405334, "expert": 0.38659414649009705 }
6,802
Why itemcategories and subcategory is always Fiction when update product is clicked
852fb4e10fbe74b32996fa696c504be4
{ "intermediate": 0.31552261114120483, "beginner": 0.29788318276405334, "expert": 0.38659414649009705 }
6,803
NullReferenceException: Object reference not set to an instance of an object at UI.SessionSettings.ChoosingCar.Windows.CarBrandSelectionWindow.RemoveBrands () [0x00000] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.SessionSettings.ChoosingCar.Windows.CarBrandSelectionWindow.OnShow () [0x00000] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.Windows.Window.Show () [0x0000b] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.Windows.WindowsActivator.ShowWindows (UI.Windows.Window window) [0x00008] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.Windows.WindowsActivator.ReloadWindows () [0x0000f] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.SessionSettings.ChoosingCar.Windows.CarChoiceWindow.OnShow () [0x00010] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.Windows.Window.Show () [0x0000b] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.SessionSettings.StartSessionWindow.OnShow () [0x00000] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.Windows.Window.Show () [0x0000b] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.SessionWindow.Navigation.ToggleWindowContainer.OnShow () [0x00000] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.SessionWindow.Navigation.ToggleWindowContainer.ShowOrHide (UnityEngine.UI.Toggle currentToggle) [0x0000e] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.SessionWindow.Navigation.Switcher.SwitchPanel (UnityEngine.UI.Toggle toggle) [0x0000b] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at (wrapper delegate-invoke) System.Action`1[UnityEngine.UI.Toggle].invoke_void_T(UnityEngine.UI.Toggle) at UI.AnimationUI.BetterToggleGroup.OnToggleChange (UnityEngine.UI.Toggle toggle) [0x0000a] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UI.AnimationUI.BetterToggleGroup.<Start>b__4_0 (System.Boolean isSelected) [0x00022] in <e6cbbe5bbe9849eba8c2d9f7f787080c>:0 at UnityEngine.Events.InvokableCall`1[T1].Invoke (T1 args0) [0x00010] in <b7bd145ee2ac420bb03ab6bcfc2dc69d>:0 at UnityEngine.Events.UnityEvent`1[T0].Invoke (T0 arg0) [0x00025] in <b7bd145ee2ac420bb03ab6bcfc2dc69d>:0 at UnityEngine.UI.Toggle.Set (System.Boolean value, System.Boolean sendCallback) [0x00087] in <5584dee5a8284cd1b42e258993b37b81>:0 at UnityEngine.UI.Toggle.set_isOn (System.Boolean value) [0x00000] in <5584dee5a8284cd1b42e258993b37b81>:0 at UnityEngine.UI.Toggle.InternalToggle () [0x00018] in <5584dee5a8284cd1b42e258993b37b81>:0 at UnityEngine.UI.Toggle.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) [0x00009] in <5584dee5a8284cd1b42e258993b37b81>:0 at UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) [0x00007] in <5584dee5a8284cd1b42e258993b37b81>:0 at UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) [0x00067] in <5584dee5a8284cd1b42e258993b37b81>:0 UnityEngine.DebugLogHandler:Internal_LogException(Exception, Object) UnityEngine.DebugLogHandler:LogException(Exception, Object) UnityEngine.Logger:LogException(Exception, Object) UnityEngine.Debug:LogException(Exception) UnityEngine.EventSystems.ExecuteEvents:Execute(GameObject, BaseEventData, EventFunction`1) UnityEngine.InputSystem.UI.InputSystemUIInputModule:ProcessPointerButton(ButtonState&, PointerEventData) UnityEngine.InputSystem.UI.InputSystemUIInputModule:ProcessPointer(PointerModel&) UnityEngine.InputSystem.UI.InputSystemUIInputModule:Process() UnityEngine.EventSystems.EventSystem:Update()
8ef64418144022b01c4d62e0f8538ba1
{ "intermediate": 0.3250490725040436, "beginner": 0.3862914741039276, "expert": 0.2886594831943512 }
6,804
File: 0_0_1_0_0_0_1_0.wav, speech segments: [[22591, 28651], [34162, 40773], [46284, 51793], [52345, 52895], [57855, 63915], [68875, 74935], [80446, 86506], [92568, 96975], [103037, 107444]] --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-26-2a75de5ff98f> in <cell line: 14>() 23 audio_data, sample_rate = torchaudio.load(os.path.join(directory, files[idx])) 24 upsampled_boundaries = vad(audio_data, sample_rate) —> 25 plt.plot(time, upsampled_boundaries.squeeze()) 26 27 plt.show() AttributeError: ‘list’ object has no attribute ‘squeeze’
6e4dca8481d11c3186c3ebf8ed6d29f5
{ "intermediate": 0.44053924083709717, "beginner": 0.310522198677063, "expert": 0.24893856048583984 }
6,805
convert the following prisma schema model NationalGeneralCPI { cpi Float questionnaireId Int @id questionnaire Questionnaire @relation(fields: [questionnaireId], references: [id]) } to swagger 3.0 schema
55eec01dd71103d268e46e0ca85a09ac
{ "intermediate": 0.4679972231388092, "beginner": 0.34431150555610657, "expert": 0.18769127130508423 }
6,806
What is the regex pattern to exactly match a word?
e8394492c15e186c3761e24e21e1dbdc
{ "intermediate": 0.24854502081871033, "beginner": 0.2613646686077118, "expert": 0.49009034037590027 }
6,807
I need to use the python language to visualize the laminar flow of a fluid using a cellular automaton method. You must come up with the rules for the cellular automaton yourself. The visualization should look like: This is a graph on which the squares of water have their own direction vector, this vector on the graph should be indicated by a small arrow. The water source must be located on the Y axis and the water must flow downward laminarly.
682f3b7cfa5620ce8743e2e5d9f7ffcf
{ "intermediate": 0.3975851535797119, "beginner": 0.24056608974933624, "expert": 0.3618486821651459 }
6,808
Напиши подробный код для создания регистрации в приложении , в качестве БД используй SQLite , затем создай обработчик нажатия на кнопку в FirstFragment и активируй регистрацию Для создания регистрации с использованием SQLite необходимо выполнить несколько шагов. 1. Создание таблицы в базе данных, в которой будут храниться данные пользователей: public class UserDatabaseHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = “UserDatabase”; private static final String TABLE_USERS = “users”; private static final String COLUMN_ID = “_id”; private static final String COLUMN_NAME = “name”; private static final String COLUMN_EMAIL = “email”; private static final String COLUMN_PASSWORD = “password”; public UserDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_USERS_TABLE = “CREATE TABLE " + TABLE_USERS + “(” + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,” + COLUMN_NAME + " TEXT,“ + COLUMN_EMAIL + " TEXT,” + COLUMN_PASSWORD + " TEXT" + “)”; db.execSQL(CREATE_USERS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(“DROP TABLE IF EXISTS " + TABLE_USERS); onCreate(db); } } 2. Создание класса для работы с таблицей пользователей: public class UserDAO { private SQLiteDatabase database; private UserDatabaseHelper dbHelper; public UserDAO(Context context) { dbHelper = new UserDatabaseHelper(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public long register(String name, String email, String password) { ContentValues values = new ContentValues(); values.put(UserDatabaseHelper.COLUMN_NAME, name); values.put(UserDatabaseHelper.COLUMN_EMAIL, email); values.put(UserDatabaseHelper.COLUMN_PASSWORD, password); return database.insert(UserDatabaseHelper.TABLE_USERS, null, values); } public boolean login(String email, String password) { Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS, new String[]{UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD}, UserDatabaseHelper.COLUMN_EMAIL + " = ? AND " + UserDatabaseHelper.COLUMN_PASSWORD + " = ?”, new String[]{email, password}, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { cursor.close(); return true; } else { return false; } } } 3. Создание экрана регистрации с полями для ввода имени, email и пароля, а также кнопкой для отправки данных на сервер: <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android” android:orientation=“vertical” android:layout_width=“match_parent” android:layout_height=“match_parent”> <TextView android:text=“Name:” android:layout_width=“wrap_content” android:layout_height=“wrap_content”/> <EditText android:id=“@+id/editTextName” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> <TextView android:text=“Email:” android:layout_width=“wrap_content” android:layout_height=“wrap_content”/> <EditText android:id=“@+id/editTextEmail” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> <TextView android:text=“Password:” android:layout_width=“wrap_content” android:layout_height=“wrap_content”/> <EditText android:id=“@+id/editTextPassword” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> <Button android:id=“@+id/buttonRegister” android:text=“Register” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> </LinearLayout> 4. Добавление обработчика нажатия на кнопку, который получает данные из полей ввода и отправляет их на сервер: public class RegistrationFragment extends Fragment { private EditText editTextName, editTextEmail, editTextPassword; private Button buttonRegister; private UserDAO userDAO; public RegistrationFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userDAO = new UserDAO(getActivity()); userDAO.open(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_registration, container, false); editTextName = view.findViewById(R.id.editTextName); editTextEmail = view.findViewById(R.id.editTextEmail); editTextPassword = view.findViewById(R.id.editTextPassword); buttonRegister = view.findViewById(R.id.buttonRegister); buttonRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = editTextName.getText().toString(); String email = editTextEmail.getText().toString(); String password = editTextPassword.getText().toString(); long rowID = userDAO.register(name, email, password); if (rowID > 0) { Toast.makeText(getActivity(), “Registration successful”, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), “Registration failed”, Toast.LENGTH_SHORT).show(); } } }); return view; } @Override public void onDestroy() { super.onDestroy(); userDAO.close(); } } 5. Добавление кнопки на экран FirstFragment для перехода на экран регистрации: <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android” android:orientation=“vertical” android:layout_width=“match_parent” android:layout_height=“match_parent”> <TextView android:text=“Welcome to my app!” android:layout_width=“wrap_content” android:layout_height=“wrap_content”/> <Button android:id=“@+id/buttonRegister” android:text=“Register” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> </LinearLayout> public class FirstFragment extends Fragment { private Button buttonRegister; public FirstFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_first, container, false); buttonRegister = view.findViewById(R.id.buttonRegister); buttonRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Fragment fragment = new RegistrationFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.container, fragment); transaction.addToBackStack(null); transaction.commit(); } }); return view; } } ты забыл реализовать xml Конечно, спасибо за замечание. Вот код xml для экрана FirstFragment: <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android” android:orientation=“vertical” android:layout_width=“match_parent” android:layout_height=“match_parent”> <TextView android:text=“Welcome to my app!” android:layout_width=“wrap_content” android:layout_height=“wrap_content”/> <Button android:id=“@+id/buttonRegister” android:text=“Register” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> </LinearLayout> В твоей регистрации ты должен сделать так чтобы запись введенная в поле : email соответствовала почте а так же при успешной регистрации кнопка должна возвращать в приложение (помни что почта обязательно должна содержать символ "@" и домен который пишется через точку : вот пример : <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>)
3ce8c513431502c7f6bfe6996ebaf7f3
{ "intermediate": 0.28046467900276184, "beginner": 0.5694003701210022, "expert": 0.15013499557971954 }
6,809
Hi. I need to unpack an archive in puppet, with a folder in the archive, and I would like to retrieve its contents when unpacking
8b0b2bc1cdce38a24a46e4da46cb1c18
{ "intermediate": 0.390524685382843, "beginner": 0.24947582185268402, "expert": 0.35999950766563416 }
6,810
Напиши подробный код для создания регистрации в приложении , в качестве БД используй SQLite , затем создай обработчик нажатия на кнопку в FirstFragment и активируй регистрацию Для создания регистрации с использованием SQLite необходимо выполнить несколько шагов. 1. Создание таблицы в базе данных, в которой будут храниться данные пользователей: public class UserDatabaseHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = “UserDatabase”; private static final String TABLE_USERS = “users”; private static final String COLUMN_ID = “_id”; private static final String COLUMN_NAME = “name”; private static final String COLUMN_EMAIL = “email”; private static final String COLUMN_PASSWORD = “password”; public UserDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_USERS_TABLE = “CREATE TABLE " + TABLE_USERS + “(” + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,” + COLUMN_NAME + " TEXT,“ + COLUMN_EMAIL + " TEXT,” + COLUMN_PASSWORD + " TEXT" + “)”; db.execSQL(CREATE_USERS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(“DROP TABLE IF EXISTS " + TABLE_USERS); onCreate(db); } } 2. Создание класса для работы с таблицей пользователей: public class UserDAO { private SQLiteDatabase database; private UserDatabaseHelper dbHelper; public UserDAO(Context context) { dbHelper = new UserDatabaseHelper(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public long register(String name, String email, String password) { ContentValues values = new ContentValues(); values.put(UserDatabaseHelper.COLUMN_NAME, name); values.put(UserDatabaseHelper.COLUMN_EMAIL, email); values.put(UserDatabaseHelper.COLUMN_PASSWORD, password); return database.insert(UserDatabaseHelper.TABLE_USERS, null, values); } public boolean login(String email, String password) { Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS, new String[]{UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD}, UserDatabaseHelper.COLUMN_EMAIL + " = ? AND " + UserDatabaseHelper.COLUMN_PASSWORD + " = ?”, new String[]{email, password}, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { cursor.close(); return true; } else { return false; } } } 3. Создание экрана регистрации с полями для ввода имени, email и пароля, а также кнопкой для отправки данных на сервер: <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android” android:orientation=“vertical” android:layout_width=“match_parent” android:layout_height=“match_parent”> <TextView android:text=“Name:” android:layout_width=“wrap_content” android:layout_height=“wrap_content”/> <EditText android:id=“@+id/editTextName” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> <TextView android:text=“Email:” android:layout_width=“wrap_content” android:layout_height=“wrap_content”/> <EditText android:id=“@+id/editTextEmail” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> <TextView android:text=“Password:” android:layout_width=“wrap_content” android:layout_height=“wrap_content”/> <EditText android:id=“@+id/editTextPassword” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> <Button android:id=“@+id/buttonRegister” android:text=“Register” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> </LinearLayout> 4. Добавление обработчика нажатия на кнопку, который получает данные из полей ввода и отправляет их на сервер: public class RegistrationFragment extends Fragment { private EditText editTextName, editTextEmail, editTextPassword; private Button buttonRegister; private UserDAO userDAO; public RegistrationFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userDAO = new UserDAO(getActivity()); userDAO.open(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_registration, container, false); editTextName = view.findViewById(R.id.editTextName); editTextEmail = view.findViewById(R.id.editTextEmail); editTextPassword = view.findViewById(R.id.editTextPassword); buttonRegister = view.findViewById(R.id.buttonRegister); buttonRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = editTextName.getText().toString(); String email = editTextEmail.getText().toString(); String password = editTextPassword.getText().toString(); long rowID = userDAO.register(name, email, password); if (rowID > 0) { Toast.makeText(getActivity(), “Registration successful”, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), “Registration failed”, Toast.LENGTH_SHORT).show(); } } }); return view; } @Override public void onDestroy() { super.onDestroy(); userDAO.close(); } } 5. Добавление кнопки на экран FirstFragment для перехода на экран регистрации: <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android” android:orientation=“vertical” android:layout_width=“match_parent” android:layout_height=“match_parent”> <TextView android:text=“Welcome to my app!” android:layout_width=“wrap_content” android:layout_height=“wrap_content”/> <Button android:id=“@+id/buttonRegister” android:text=“Register” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> </LinearLayout> public class FirstFragment extends Fragment { private Button buttonRegister; public FirstFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_first, container, false); buttonRegister = view.findViewById(R.id.buttonRegister); buttonRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Fragment fragment = new RegistrationFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.container, fragment); transaction.addToBackStack(null); transaction.commit(); } }); return view; } } ты забыл реализовать xml Конечно, спасибо за замечание. Вот код xml для экрана FirstFragment: <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android” android:orientation=“vertical” android:layout_width=“match_parent” android:layout_height=“match_parent”> <TextView android:text=“Welcome to my app!” android:layout_width=“wrap_content” android:layout_height=“wrap_content”/> <Button android:id=“@+id/buttonRegister” android:text=“Register” android:layout_width=“match_parent” android:layout_height=“wrap_content”/> </LinearLayout> В твоей регистрации ты должен сделать так чтобы запись введенная в поле : email соответствовала почте а так же при успешной регистрации кнопка должна возвращать в приложение (помни что почта обязательно должна содержать символ “@” и домен который пишется через точку : вот пример : <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>) Спасибо за уточнение. Поправленный код для класса UserDAO с добавлением проверки на соответствие формату email: public class UserDAO { private SQLiteDatabase database; private UserDatabaseHelper dbHelper; public UserDAO(Context context) { dbHelper = new UserDatabaseHelper(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public long register(String name, String email, String password) { if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { return -1; // email не соответствует формату } ContentValues values = new ContentValues(); values.put(UserDatabaseHelper.COLUMN_NAME, name); values.put(UserDatabaseHelper.COLUMN_EMAIL, email); values.put(UserDatabaseHelper.COLUMN_PASSWORD, password); return database.insert(UserDatabaseHelper.TABLE_USERS, null, values); } public boolean login(String email, String password) { Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS, new String[]{UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD}, UserDatabaseHelper.COLUMN_EMAIL + " = ? AND " + UserDatabaseHelper.COLUMN_PASSWORD + " = ?”, new String[]{email, password}, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { cursor.close(); return true; } else { return false; } } } Также, добавленный код для обработчика нажатия на кнопку в RegistrationFragment: buttonRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = editTextName.getText().toString(); String email = editTextEmail.getText().toString(); String password = editTextPassword.getText().toString(); long rowID = userDAO.register(name, email, password); if (rowID > 0) { Toast.makeText(getActivity(), “Registration successful”, Toast.LENGTH_SHORT).show(); getActivity().onBackPressed(); // возвращаемся на предыдущий экран } else if (rowID == -1) { Toast.makeText(getActivity(), “Invalid email”, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), “Registration failed”, Toast.LENGTH_SHORT).show(); } } });Отлично теперь добавь дополнительный функционал кнопки завершения регистрации : дополнительно выведи всех зарегистрированных пользователей в виде логирования и хочется верить , что все зарегистрированные пользователи будут сохранены после перезапуска приложения Для сохранения всех зарегистрированных пользователей между запусками приложения, в класс UserDAO можно добавить метод getAllUsers(), который будет возвращать список всех пользователей из таблицы. Кроме того, в обработчик нажатия на кнопку можно добавить вывод в лог всех имеющихся пользователей. 1. Обновление класса UserDAO для добавления метода getAllUsers(): public class UserDAO { private SQLiteDatabase database; private UserDatabaseHelper dbHelper; public UserDAO(Context context) { dbHelper = new UserDatabaseHelper(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public long register(String name, String email, String password) { if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { return -1; // email не соответствует формату } ContentValues values = new ContentValues(); values.put(UserDatabaseHelper.COLUMN_NAME, name); values.put(UserDatabaseHelper.COLUMN_EMAIL, email); values
21a6c9745b552df9d07811cf34c26c0e
{ "intermediate": 0.36178314685821533, "beginner": 0.4988974630832672, "expert": 0.13931941986083984 }
6,811
// Task 1 // При нажатии кнопки .b-1, срабатывает функция f1. Функция отсылает запрос на api.itgid.info со следующими параметрами: // url: /api/25/random/random-string // method: GET // Ответ сервера (строку случайных символов) - выводит в .out-1 // не забывайте для авторизации отправлять apikey с указанным ключом. const xhr = new XMLHttpRequest(); function f1() { xhr.open('GET', URL + '/api/25/random/random-string'); xhr.setRequestHeader('apikey', APIKEY); xhr.onload = function () { handler(xhr.response) }; xhr.send(); document.querySelector('.out-1').innerHTML = ;как вывести? } document.querySelector('.b-1').addEventListener('click', f1);
bed4a523ff7bf85bc6c672e332bab112
{ "intermediate": 0.48116880655288696, "beginner": 0.29146403074264526, "expert": 0.22736717760562897 }
6,812
how can i host my telegram bot so that its available 24x7 using streamlit modify my code import json import numpy as np import keras from sklearn.preprocessing import LabelEncoder import pickle from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.layers import LSTM from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Embedding from telegram import Update from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackContext from telegram.ext import Filters #complete model training with open('E:\Projects\chatbot\data\data.json', 'r') as f: data = json.load(f) training_sentences = [] training_labels = [] labels = [] responses = [] for intent in data['intents']: for pattern in intent['patterns']: training_sentences.append(pattern) training_labels.append(intent['tag']) responses.append(intent['responses']) if intent['tag'] not in labels: labels.append(intent['tag']) num_classes = len(labels) lbl_encoder = LabelEncoder() lbl_encoder.fit(training_labels) training_labels = lbl_encoder.transform(training_labels) vocab_size = 2000 embedding_dim = 16 max_len = 30 oov_token = "<OOV>" tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_token) tokenizer.fit_on_texts(training_sentences) word_index = tokenizer.word_index sequences = tokenizer.texts_to_sequences(training_sentences) padded_sequences = pad_sequences(sequences, truncating='post', maxlen=max_len) model = Sequential() model.add(Embedding(vocab_size, embedding_dim, input_length=max_len)) model.add(LSTM(16, return_sequences=False)) model.add(Dense(16, activation='relu')) model.add(Dense(num_classes, activation='softmax')) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() epochs = 300 history = model.fit(padded_sequences, np.array(training_labels), epochs=epochs) # to save the trained model model.save("E:\Projects\chatbot\models\chat_model.h5") import pickle # to save the fitted tokenizer with open('E:\\Projects\\chatbot\\models\\tokenizer.pickle', 'wb') as handle: pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL) # to save the fitted label encoder with open('E:\\Projects\\chatbot\\models\\label_encoder.pickle', 'wb') as ecn_file: pickle.dump(lbl_encoder, ecn_file, protocol=pickle.HIGHEST_PROTOCOL) #loading and telegram deployment with open(r"E:\Projects\chatbot\data\data.json") as file: data = json.load(file) def start(update: Update, context: CallbackContext) -> None: """Send a message when the command /start is issued.""" update.message.reply_text('Hi, I\'m your chatbot. How can I help you?') def chatbot_response(update: Update, context: CallbackContext) -> None: model = keras.models.load_model(r'E:\Projects\chatbot\models\chat_model.h5') with open(r'E:\Projects\chatbot\models\tokenizer.pickle', 'rb') as handle: tokenizer = pickle.load(handle) with open(r'E:\Projects\chatbot\models\label_encoder.pickle', 'rb') as enc: lbl_encoder = pickle.load(enc) # parameters max_len = 30 # Get the message from the user message = update.message.text # Convert input message into sequence of integers using tokenizer msg_seq = tokenizer.texts_to_sequences([message]) # Pad the sequence to have fixed length msg_seq = pad_sequences(msg_seq, maxlen=max_len, truncating='post') # Predict the class of the input message pred = model.predict(msg_seq)[0] # Get the index of the predicted class pred_idx = np.argmax(pred) # Get the confidence of the prediction confidence = pred[pred_idx] # Convert the index back to the original label tag = lbl_encoder.inverse_transform([pred_idx])[0] # If the confidence is less than 0.5, send a default message if confidence < 0.75: context.bot.send_message(chat_id=update.effective_chat.id, text="I'm sorry, but I didn't understand your concern. Please keep it simple, rephrase the sentence or try asking something else related to mental health") else: for i in data['intents']: if i['tag'] == tag: response = np.random.choice(i['responses']) # Send the response to the user context.bot.send_message(chat_id=update.effective_chat.id, text=response) break def main() -> None: # Create the Updater and pass it your bot's token. updater = Updater("myapikey",use_context=True) # Get the dispatcher to register handlers dispatcher = updater.dispatcher # on different commands - answer in Telegram dispatcher.add_handler(CommandHandler("start", lambda update, context: start(update, context))) # on noncommand i.e message - echo the message on Telegram dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, lambda update, context: chatbot_response(update, context))) # Start the Bot updater.start_polling() # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the updater.idle() if __name__ == '__main__': main()
4fe909e53ceb11c16e44898ff3561bd3
{ "intermediate": 0.42442071437835693, "beginner": 0.26152747869491577, "expert": 0.3140518069267273 }
6,813
Write Java code to compare two .docx files with images and text
c2a63069be5f56212170ac90f3a4cc91
{ "intermediate": 0.5758275985717773, "beginner": 0.18165132403373718, "expert": 0.24252107739448547 }
6,814
java code for add,substruction and multiple two ploynomail use doublelinkedlist ask the user to enter the two ploynomial
f3dfffec66204a284aed3b697af5d1de
{ "intermediate": 0.62362140417099, "beginner": 0.1550852656364441, "expert": 0.2212933748960495 }
6,815
1. Create a linked list. 2. Fill the linked list while taking input on console, in such a way that user enters the NUMERIC digits of their VU ID, one by one. For example, if we consider BC123456789, then BC would be ignored and you only have to insert 1 2 3 4 5 6 7 8 9 one by one, in the linked list. (as shown in the screenshot below). 3. After filling your linked list, now you need to create two other linked list one for odd numbers and the other for even numbers. 4. Now, filter out the digits one by one, and put them in their respective linked list. For example, if your VU ID is BC123456789, then 1,3,5,7,9 would be inserted in the odd linked list while 2,4,6,8 would be inserted in even linked list. 5. After creating two separate linked list, merge them into a single one in such a way that odd one should be inserted first and then the even linked list.
343c353c88cc32ac13c5a1721d86becf
{ "intermediate": 0.3310036361217499, "beginner": 0.24164125323295593, "expert": 0.4273551106452942 }
6,816
make a processing sketch that analyse a text like a markov-chain and allow user to blind his own text
e56687d3c860df4ac66bf53db8f4408d
{ "intermediate": 0.39294561743736267, "beginner": 0.10120140761137009, "expert": 0.5058529376983643 }
6,817
$ git pull The authenticity of host 'github.com (20.205.243.166)' can't be established. ED25519 key fingerprint is SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU. This key is not known by any other names. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added 'github.com' (ED25519) to the list of known hosts. git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
cdba8aa6a92c8f93569a4b767264cd90
{ "intermediate": 0.3776685297489166, "beginner": 0.27240806818008423, "expert": 0.34992343187332153 }
6,818
How to fine tune GPT-2 using Hugging face
2b9d55425bf7a8a0b98e88346633bd7a
{ "intermediate": 0.156035915017128, "beginner": 0.09350666403770447, "expert": 0.7504574060440063 }
6,819
these lines of VBA code copies sheet named "Today" and creates the copy as a sheet "Task" & Format(Now(), "DDMMYY") wbk1.Sheets("Today").Copy After:=wbk1.Sheets(wbk1.Sheets.Count) wbk1.Sheets(wbk1.Sheets.Count).Name = "Task" & Format(Now(), "DDMMYY") How can I write the VBA code so that when creating the new sheet there are no formulas or VBA codes in the new sheet just values & formatting
dc3f61cb354040b9c696bac99c2d5b77
{ "intermediate": 0.587078332901001, "beginner": 0.12346729636192322, "expert": 0.2894543409347534 }
6,820
translate to arabic: Ecological information
895c9c9112acfcc1df43880dc980a860
{ "intermediate": 0.3627738356590271, "beginner": 0.4233657419681549, "expert": 0.21386034786701202 }
6,821
C:\Users\bluneko>ssh-add ~/.ssh/id_rsa Error connecting to agent: No such file or directory
3cde0a0ad68f8c547fe4d75490e95383
{ "intermediate": 0.3532392084598541, "beginner": 0.28971365094184875, "expert": 0.3570471704006195 }
6,822
Добавь волну на фоне , которую ты должен сделать сам при этом похожие волны должны быть в левом верхнем и правом нижнем углах в общем сделай красивй дизнай в виде плавности и волнистости : <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingStart="24dp" android:paddingTop="24dp" android:paddingEnd="24dp" android:paddingBottom="16dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Registration" android:textSize="24sp" android:textStyle="bold" /> <View android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginTop="16dp" android:layout_marginBottom="16dp" android:background="#c7c7c7" /> <EditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:background="@drawable/edit_text_bg" android:hint="Name" android:inputType="textPersonName" android:padding="16dp" /> <EditText android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:background="@drawable/edit_text_bg" android:hint="Email" android:inputType="textEmailAddress" android:padding="16dp" /> <EditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:background="@drawable/edit_text_bg" android:hint="Password" android:inputType="textPassword" android:padding="16dp" /> <Button android:id="@+id/buttonRegister" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorAccent" android:text="Register" android:textColor="@android:color/white" android:textSize="16sp" /> </FrameLayout> </LinearLayout> </ScrollView>
a0a5b8bac0980b9380ac7a89e8fedf22
{ "intermediate": 0.2653871476650238, "beginner": 0.5397879481315613, "expert": 0.1948249340057373 }
6,823
Show that the number of vertices of odd degree in a tree is even
12fa6bfbebc2e8331445e20e37483fea
{ "intermediate": 0.3342868983745575, "beginner": 0.24781003594398499, "expert": 0.4179030656814575 }
6,824
Write a function called tax_cost that accepts one parameter which represents a dollar amount before tax. The function should return the total amount that will be charged, including the tax. You should assume a tax rate of 13%.
f481292f0e2ca3e9e0d7be32a57956a5
{ "intermediate": 0.36944517493247986, "beginner": 0.3206973373889923, "expert": 0.30985745787620544 }
6,825
How can I write a VBA code that activates when a sheet is opened, forcing Range B1, A22, F22 and I1:J20 to calculate
bb743eab3cefecd8f526f39a6774dda8
{ "intermediate": 0.3849773108959198, "beginner": 0.30082693696022034, "expert": 0.3141957223415375 }
6,826
# Import your libraries import pandas as pd # Start writing code s=sf_employee.merge(sf_bonus,left_on='id',right_on='worker_ref_id') s=s[s['bonus'].notnull()] s['tobon']=s.groupby('id')['bonus'].sum() s['total_compensation'] = s['salary'] + s['tobon'] result = s.groupby(['employee_title', 'sex'])['total_compensation'].mean().reset_index() Question: why the above code does not solve the below question Find the average total compensation based on employee titles and gender. Total compensation is calculated by adding both the salary and bonus of each employee. However, not every employee receives a bonus so disregard employees without bonuses in your calculation. Employee can receive more than one bonus. Output the employee title, gender (i.e., sex), along with the average total compensation.
4941e601615e8f9a1df3fa9f18db3189
{ "intermediate": 0.553032636642456, "beginner": 0.19206182658672333, "expert": 0.2549055516719818 }