row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
34,233
напиши код майнкрафт спигот 1.12.2 сделай чтобы при вводе команды /upgrade если у игрока в руках кожаная куртка, то у нее повышаются все ее атрибуты на 5%, а перед названием предмета появляется зеленое “+1” сделай чтобы после повторного улучшения число менялось на +2, +3 и т.д до +15, скинь итоговый код плагина. Чтобы создать плагин для Spigot 1.12.2, который реализует указанную функцию, вам сначала потребуется знание Java и установленная среда разработки, такая как IntelliJ IDEA или Eclipse, а также Spigot API для версии 1.12.2. Ниже я предоставлю вам примерный код плагина, который реализует команду /upgrade: import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; public class UpgradePlugin extends JavaPlugin implements CommandExecutor { @Override public void onEnable() { getLogger().info(“UpgradePlugin has been enabled!”); getCommand(“upgrade”).setExecutor(this); } @Override public void onDisable() { getLogger().info(“UpgradePlugin has been disabled!”); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (label.equalsIgnoreCase(“upgrade”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Only players can use this command!”); return true; } Player player = (Player) sender; ItemStack itemInHand = player.getInventory().getItemInMainHand(); if (itemInHand.getType() != Material.LEATHER_CHESTPLATE) { player.sendMessage(ChatColor.RED + “You must hold a leather tunic in your hand to upgrade it!”); return true; } ItemMeta meta = itemInHand.getItemMeta(); if (meta != null) { int upgradeLevel = getUpgradeLevel(meta.getDisplayName()); if (upgradeLevel >= 15) { player.sendMessage(ChatColor.RED + “Your item is already at the maximum upgrade level!”); return true; } meta.setDisplayName(ChatColor.GREEN + “+” + (upgradeLevel + 1) + " " + ChatColor.stripColor(meta.getDisplayName())); for (Material attribute : Material.values()) { if (!meta.hasAttributeModifiers(attribute)) continue; // Update the attribute modifiers by adding 5% // This is where you would update the attributes; the exact method differs from version to version. } itemInHand.setItemMeta(meta); player.sendMessage(ChatColor.GREEN + “Your leather tunic has been upgraded to level " + (upgradeLevel + 1) + “!”); } } return true; } /** * Extracts the upgrade level from the item’s display name. * * @param displayName The display name of the item. * @return The upgrade level, or 0 if not found. */ private int getUpgradeLevel(String displayName) { if (displayName == null) return 0; String strippedName = ChatColor.stripColor(displayName); if (strippedName.startsWith(”+“)) { String[] parts = strippedName.split(” ", 2); try { return Integer.parseInt(parts[0].substring(1)); } catch (NumberFormatException e) { // Not a number } } return 0; } } Важные моменты: 1. Этот код служит примером и может потребовать дополнительной настройки, так как обработка атрибутов для брони может отличаться в зависимости от конкретной версии Minecraft и Spigot API. 2. В версиях Minecraft 1.12, концепт атрибутов предметов был реализован немного иначе, поэтому вам может потребоваться выполнить дополнительную работу для изменения атрибутов на 5%. 3. Пример не содержит детального редактирования атрибутов, так как это сложная задача, требующая точного понимания как работать с атрибутами в вашей версии API. 4. Убедитесь, что у вас правильно настроен plugin.yml . От меня: исправь все недочеты, сделай корректный код для изменения атрибута на 1.12.2
5109550769cc457a51388ef7647349c3
{ "intermediate": 0.26351186633110046, "beginner": 0.5776492953300476, "expert": 0.15883880853652954 }
34,234
Could not find a declaration file for module '@zegocloud/zego-uikit-prebuilt-call-rn'. '/Users/mac/Desktop/testProcare/ihealthRN/example/node_modules/@zegocloud/zego-uikit-prebuilt-call-rn/lib/commonjs/index.js' implicitly has an 'any' type. Try `npm i --save-dev @types/zegocloud__zego-uikit-prebuilt-call-rn` if it exists or add a new declaration (.d.ts) file containing `declare module '@zegocloud/zego-uikit-prebuilt-call-rn';`
ebca63f9d99358c825c618061dc27157
{ "intermediate": 0.5110266804695129, "beginner": 0.21921661496162415, "expert": 0.2697566747665405 }
34,235
I'm running Nextcloud on a server, named myserver.com. The Apache server answers on port 8080. I have a proxy in front. The external address to the Nextcloud server is https://mydomain.com. Now I need to change that address to https://mydomain.com/nc but I do not want to move the files on on the server myserver.com. I'm using Nginx Proxy Manager and hpw can I config that to allways show https://mydomain.com/nc in the client browser?
ca57f3643e49712fd13669fdaf08b563
{ "intermediate": 0.47154542803764343, "beginner": 0.28603577613830566, "expert": 0.2424188107252121 }
34,236
code a python cookie stealer that will send to discord webhook
0ffe9121e436ee69514aa1767986007f
{ "intermediate": 0.3654928505420685, "beginner": 0.1332983374595642, "expert": 0.5012087821960449 }
34,237
in postgressql i got 5 databases public."PL_MoliendaIBP" public."PL_Quality" public."PL_Commercial" public."PL_Process" public."PL_Restrictions" there is a field called "runId" that all 5 have that I need update where the user = felipe and its runid is emtpy and also is the last row on that table (where the user is felipe )
d65e02355827eabc3a8b8e7142e0e600
{ "intermediate": 0.45831549167633057, "beginner": 0.22875066101551056, "expert": 0.31293392181396484 }
34,238
code a full website for me, the theme is "Roblox Executor"
50d82a829683bd3d352f7a335251f224
{ "intermediate": 0.33604875206947327, "beginner": 0.3364214301109314, "expert": 0.3275298476219177 }
34,239
from c# i have a DateTimeOffset today = DateTimeOffset.UtcNow.Date; long unixTimestamp = today.ToUnixTimeSeconds(); i need to see that on postgres to check if other dates stores as integer are the same day, ignoring the timestamp
c4b27a2cd1e57ef7c8bb22cf5c0d6ac6
{ "intermediate": 0.5293235182762146, "beginner": 0.31039878726005554, "expert": 0.16027773916721344 }
34,240
safetensors to pytorch_model.bin huggingface python cdoe
53461597cf88b1db0e9bc5eab6e4d18f
{ "intermediate": 0.32590317726135254, "beginner": 0.26253703236579895, "expert": 0.4115598201751709 }
34,241
convert model.safetensors to pytorch_model.bin huggingface python code
4f2b61c4f0bb069cd8bcaf2929cb8833
{ "intermediate": 0.2963748574256897, "beginner": 0.24551019072532654, "expert": 0.458114892244339 }
34,242
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //This line enables use of uGUI classes like Text. public class ScoreCounter : MonoBehaviour { //[Header("Dynamic")] public static int SCORE { get; set; } private Text uiText; private void Start() { uiText = GetComponent<Text>(); LoadScore(); } private void Update() { uiText.text = SCORE.ToString("Score:#,0"); //This 0 is a zero! } public void AddScore(int scoreAmount) { SCORE += scoreAmount; SaveScore(); } private void SaveScore() { PlayerPrefs.SetInt("Score", SCORE); } private void LoadScore() { SCORE = PlayerPrefs.GetInt("Score", 0); } } why is the score not resetting if the player dies?
93ca5f5c8f7b53dd28c43e3ae4d4cb36
{ "intermediate": 0.44672948122024536, "beginner": 0.4095638692378998, "expert": 0.14370664954185486 }
34,243
Use 2D dp array to solve leetcode 514 problem
1a461f0114abd90f0de9d1965a2ed99e
{ "intermediate": 0.3706103563308716, "beginner": 0.26642319560050964, "expert": 0.3629664480686188 }
34,244
Using python and matplotlib, do the following: generate random samples from population 1 using the following values for n and k: (n, k) = (2, 10), (2, 100), (2, 1000) (20, 100), (20, 1000) (200, 100), (200, 1000) These samples can be generated using the command “numpy.random.choice.” Provide histograms showing mean values and standard deviations for the above mentioned values of n and k.
4be2d3fd0d223e141ead59861847ec04
{ "intermediate": 0.39604508876800537, "beginner": 0.2730441987514496, "expert": 0.33091071248054504 }
34,245
HI
0c3cfb62d24ca51c5c82388150cd95c1
{ "intermediate": 0.32988452911376953, "beginner": 0.2611807882785797, "expert": 0.40893468260765076 }
34,246
Using python and matplotlib, we will estimate population mean and standard deviation by using simple random samples drawn from the population. The number of elements within each sample will be represented by n (also known as the sample size) and the number of samples drawn from the population will be represented by k.Download the two population data files data1.txt and data2.txt from the course website on canvas. Assume the data represent the daily income of individuals in the population. Population 1 comes from data1.txt.Next, generate random samples from population 1 using the following values for n and k: (n, k) = (2, 10), (2, 100), (2, 1000) (20, 100), (20, 1000) (200, 100), (200, 1000) These samples can be generated using the command “numpy.random.choice.” Provide histograms showing mean values and standard deviations for the above mentioned values of n and k
4a60f5826a6a7983d1197993a092c457
{ "intermediate": 0.4241095185279846, "beginner": 0.27702102065086365, "expert": 0.29886946082115173 }
34,247
ssytem software that controls I/O devixes are called what
de1de419f1d7c2c31cda65726edcda10
{ "intermediate": 0.35098767280578613, "beginner": 0.25636643171310425, "expert": 0.392645925283432 }
34,248
Here is my code so far: import numpy as np import matplotlib.pyplot as plt #data = (3,6, 9, 12, 15) #fig, simple_chart = plt.subplots() #simple_chart.plot(data) #plt.show() #population 1 data1 = np.loadtxt('data1.txt') #mean population1mean = np.mean(data1) print(population1mean) #standard deviation population1SD = np.std(data1) print(population1SD) #histogram plt.hist(data1, bins='auto') plt.title('Population 1 Histogram') plt.xlabel('x') plt.ylabel('Frequency') plt.show() # Generate random samples for different combinations of n and k pairs1 = [ np.random.choice(data1, size=(2, 10)), np.random.choice(data1, size=(2, 100)), np.random.choice(data1, size=(2, 1000)), np.random.choice(data1, size=(20, 100)), np.random.choice(data1, size=(20, 1000)), np.random.choice(data1, size=(200, 100)), np.random.choice(data1, size=(200, 1000)) ] # Calculate means and standard deviations for each pair of n and k means = [np.mean(pair) for pair in pairs1] stds = [np.std(pair) for pair in pairs1] # Plot histograms for means and standard deviations for i, pair in enumerate(pairs1): fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].hist(pair.mean(axis=0), bins='auto',edgecolor='black') axs[0].set_title(f"n={pair.shape[0]}, k={pair.shape[1]} Mean") axs[0].set_xlabel('Mean') axs[0].set_ylabel('Frequency') axs[1].hist(pair.std(axis=0), bins='auto',edgecolor='black') axs[1].set_title(f"n={pair.shape[0]}, k={pair.shape[1]} Std") axs[1].set_xlabel('Standard Deviation') axs[1].set_ylabel('Frequency') plt.tight_layout() plt.show() #population 2 data2 = np.loadtxt('data2.txt') #mean population2mean = np.mean(data2) print(population2mean) #standard deviation population2SD = np.std(data2) print(population2SD) #histogram plt.hist(data2, bins='auto') plt.title('Population 2 Histogram') plt.xlabel('x') plt.ylabel('Frequency') plt.show() # Generate random samples for different combinations of n and k pairs2 = [ np.random.choice(data2, size=(2, 10)), np.random.choice(data2, size=(2, 100)), np.random.choice(data2, size=(2, 1000)), np.random.choice(data2, size=(20, 100)), np.random.choice(data2, size=(20, 1000)), np.random.choice(data2, size=(200, 100)), np.random.choice(data2, size=(200, 1000)) ] # Calculate means and standard deviations for each pair of n and k means = [np.mean(pair) for pair in pairs2] stds = [np.std(pair) for pair in pairs2] # Plot histograms for means and standard deviations for i, pair in enumerate(pairs2): fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].hist(pair.mean(axis=0), bins='auto',edgecolor='black') axs[0].set_title(f"n={pair.shape[0]}, k={pair.shape[1]} Mean") axs[0].set_xlabel('Mean') axs[0].set_ylabel('Frequency') axs[1].hist(pair.std(axis=0), bins='auto',edgecolor='black') axs[1].set_title(f"n={pair.shape[0]}, k={pair.shape[1]} Std") axs[1].set_xlabel('Standard Deviation') axs[1].set_ylabel('Frequency') plt.tight_layout() plt.show() For each pair of n and k in population 1 and population 2, please find the following: E(x) = expected value of sample means S(x) = standard deviation of sample means E(s)= expected value of sample standard deviation and print in this format: n = 2, k = 10, E(x) = , S(x) = , E(s) =
b753a10003de336034d462447b809bbe
{ "intermediate": 0.30030322074890137, "beginner": 0.4148573875427246, "expert": 0.2848394215106964 }
34,249
fix the error
a54684c8cbd5251d2d5e8487633eb120
{ "intermediate": 0.40257349610328674, "beginner": 0.2821619510650635, "expert": 0.31526461243629456 }
34,250
Create table RequestAccepted (requester_id int not null, accepter_id int null, accept_date date null) Truncate table RequestAccepted insert into RequestAccepted (requester_id, accepter_id, accept_date) values ('1', '2', '2016/06/03') insert into RequestAccepted (requester_id, accepter_id, accept_date) values ('1', '3', '2016/06/08') insert into RequestAccepted (requester_id, accepter_id, accept_date) values ('2', '3', '2016/06/08') insert into RequestAccepted (requester_id, accepter_id, accept_date) values ('3', '4', '2016/06/09') select * from RequestAccepted -- find people who have most friends
8483846df516e0099b388d926608b571
{ "intermediate": 0.25437673926353455, "beginner": 0.38964882493019104, "expert": 0.35597437620162964 }
34,251
this code:"import cv2 import torch from yolov5 import YOLOv5 from threading import Thread from queue import Queue class VideoCaptureAsync: def init(self, source=0): self.cap = cv2.VideoCapture(source) self.q = Queue(maxsize=1) self.running = False def start(self): self.running = True self.thread = Thread(target=self.update, args=()) self.thread.start() return self def update(self): while self.running: ret, frame = self.cap.read() if not ret: self.running = False break if not self.q.full(): if not self.q.empty(): try: # Remove the previous frame self.q.get_nowait() except Queue.Empty: pass self.q.put(frame) def read(self): return self.q.get() def stop(self): self.running = False self.thread.join() self.cap.release() def exit(self, exc_type, exc_value, traceback): self.cap.release() def object_detection_camera_with_roi(source, weights=‘yolov5s.pt’, conf_thres=0.25, person_class_id=0): # Load the YOLOv5 model model = YOLOv5(weights, autoshape=True) model.conf = conf_thres model.classes = [person_class_id] # only detect person class model.eval() source.start() try: with torch.no_grad(): while True: frame = source.read() # Define ROI size and position (centered) h, w = frame.shape[:2] roi_size = min(w, h) // 3 x1, y1 = w // 2 - roi_size // 2, h // 2 - roi_size // 2 x2, y2 = x1 + roi_size, y1 + roi_size # Extract the ROI from the frame roi = frame[y1:y2, x1:x2] # Inference on the ROI results = model(roi) # Draw the ROI rectangle on the original frame cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2) # Count the number of people detected people_count = 0 # Extract detections for *xyxy, conf, cls in results.xyxy[0]: # Rescale coordinates to the original frame xyxy = (torch.tensor(xyxy).view(1, 4) * torch.tensor([w / roi_size, h / roi_size, w / roi_size, h / roi_size])).view(-1).tolist() x1_box, y1_box, x2_box, y2_box = [int(coord) for coord in xyxy] x1_box += x1 y1_box += y1 x2_box += x1 y2_box += y1 # Increment people count and draw bounding boxes and labels on the original frame if conf > conf_thres: people_count += 1 label = f’Person {conf:.2f}‘ cv2.rectangle(frame, (x1_box, y1_box), (x2_box, y2_box), (0, 255, 0), 2) cv2.putText(frame, label, (x1_box, y1_box - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # Display the number of people detected cv2.putText(frame, f’People detected: {people_count}’, (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) cv2.imshow(‘YOLOv5 Object Detection with ROI - Camera’, frame) # Break loop with ‘q’ if cv2.waitKey(1) == ord(‘q’): break finally: source.stop() cv2.destroyAllWindows() if name == ‘main’: video_capture = VideoCaptureAsync(source=0) object_detection_camera_with_roi(source=video_capture, weights=‘yolov5s.pt’, conf_thres=0.25) " PS C:\Users\User\Desktop\New folder> & C:/Users/User/AppData/Local/Programs/Python/Python39/python.exe "c:/Users/User/Desktop/New folder/comvis.py" File "c:\Users\User\Desktop\New folder\comvis.py", line 45 def object_detection_camera_with_roi(source, weights=‘yolov5s.pt’, conf_thres=0.25, person_class_id=0): ^ SyntaxError: invalid character '‘' (U+2018)
11555ba249189d169ff070a4f3677042
{ "intermediate": 0.3800565302371979, "beginner": 0.36695659160614014, "expert": 0.2529868483543396 }
34,252
1. Read an image and convert it to grayscale 2. Create 6 Noisy images where : * In the first three, you apply gaussian noise with different intensities. * In the other three, you apply salt & pepper noise with different probabilities 3. Compare between the frequency domains of the original image and the six noisy images by plotting them in one plot 4. Apply high pass filters on the original image and the six noisy images then plot results in one plot
fd494c25cf06d97db8b2a9adc83792f1
{ "intermediate": 0.3419136106967926, "beginner": 0.3034255802631378, "expert": 0.3546607792377472 }
34,253
If the Pokemon Eevee was a creature in a D&D homebrew, what would its statblock look like?
5b57bbdf7e46ae623ef25e273bd75b7c
{ "intermediate": 0.36561834812164307, "beginner": 0.3216569721698761, "expert": 0.31272464990615845 }
34,254
do you know yolov8?
a94687c97a826699063ddf9124c2c6ec
{ "intermediate": 0.32846495509147644, "beginner": 0.13792684674263, "expert": 0.5336081981658936 }
34,255
system message: <Before responding, follow this step by step reflection process. With the hidden thought syntax consider how best to respond, possible responses, and correctness, then try to critique or falsify your thoughts, then consider defenses for your thoughts, to figure out what to say. (Repeat this process of thinking, criticism, revisions, as many times as needed, building the answer in thoughts before answering outloud.) Make sure to take any information you have into account, when thinking and answering. Use clever and efficient strategies, tricks and methods to solve the problem in an easy and organised way. Make sure to work on the task in small chunks, step-by-step, interrupting the process and thinking as frequently as possible. You can't execute code or access the internet. But you know a lot, and you can operate using just your knowledge. Don't give up easily. The process itself is more important than the answer, so don't rush - do everything thoroughly, analyzing it first in exhaustive detail. Here is an example thought using the correct syntax: [//]: # ( This is an example of thought ) These thoughts can't be multi-line. Store hidden information in these thoughts as needed. Use thoughts to work out complex logic and problems as needed. Use meticulous extremely long analysis for every problem. You must never assume or be sure of anything if you haven't explicitly tested it in text format: """ [//]: # ( I've been asked if A being true is correct. ) [//]: # ( Is it correct? Ok, B is known to be true, as well as C. We also know that if B and C are true, A is also true. So yes, A being true is correct. ) """ It is example of good thinking process, because you're thinking before answering, increasing your chances of success dramatically. **Whenever you're counting/comparing/searching for letters or syllables in the word, you must break them down into individual letters or syllables (i.e "Testing" letters = 1-T, 2-E, 3-S, 4-T, 5-I, 6-N, 7-G. "Testing" syllables = 1-test, 2-ing.).** Think procedurally, like a human.> create a python program for object detection that uses the camera source
bcd282c5fcb6b59a729485ab8996f9c3
{ "intermediate": 0.30574479699134827, "beginner": 0.3266897201538086, "expert": 0.3675655424594879 }
34,256
How do I add a video to my website? I don't need controls for the video tag at all. I just want an autoplaying, looping, muted video that plays on load. What I have so far: <video autoplay muted width="500px" height="500px" controls="controls">
3d6adedfa066babd365769ac5ab4ef83
{ "intermediate": 0.4614335894584656, "beginner": 0.26946303248405457, "expert": 0.2691033184528351 }
34,257
Пожалуйста, добавь комментарии к коду scilab: function[y]=P(c,z) y=z(2)-c(1)-c(2)*z(1)-c(3)*z(1)*2-c(4)*z(1)*3; endfunction x=[4 5 6 7 8 9 10 11 12] y=[3.25259 4.01189 4.48352 4.79182 5.17888 5.49445 5.55752 5.80579 5.98981] plot(x,y,'zx') z=[x;y]; c=[0;0;0;0]; [a,err]=datafit(P,z,c) t=[4:0.5:12] p1=a(1)+a(2)*t+a(3).*t^2+a(4).*t^3; plot(t,p1) xgrid()
9f892a7b02fdb25679d9e9793fc9d7a7
{ "intermediate": 0.3351118564605713, "beginner": 0.3795739710330963, "expert": 0.2853141725063324 }
34,258
请详细解释以下代码: def import_flink_config(self, request): rst = {'code': 0, 'msg': '', 'data': {}} config = str(request.get('config')).replace('"', '') group_id = '' servers = 'lichen' others = request.get('group_id') arr = others.split("|") if str(arr[0]): group_id = arr[0] if str(arr[1]): servers = arr[1] lines = config.split("\\n") connObj = UtilMysql.getConn(conf.conn_opt_hulk) connObj.beginTransaction() for line in lines: if line is None or line == '': continue fields = line.split("|") sql = Util.get_upsert_statement(self.resolveConfig(fields, group_id, servers), self.flink_config_table) res_client = connObj.execute(sql, self.resolveConfig(fields, group_id, servers), rows=-1) if res_client['code'] != 0: connObj.rollback() rst['code'] = res_client['code'] rst['msg'] = res_client['errmsg'] return rst connObj.commit() rst['msg'] = '配置导入成功' return rst
c7b4e5fb3497519a9cc04779f0cd06ae
{ "intermediate": 0.43420737981796265, "beginner": 0.3549872040748596, "expert": 0.21080532670021057 }
34,259
system message :<You are a helpful assistant. Answer the user carefully. You give well thought out answers. You **prioritise accuracy and precision** over speed. always assume that you may have missed something or made a mistake (don't contradict yourself or go over the top though). Don't be afraid to criticize and correct yourself. You never skip steps or instructions or cut corners. Write information that you think could be useful in the future, because you are a language model and must write down information before you can remind yourself of it. you must be **accurate and precise**, don't rush, skip or summarize things unnecessarily. You have the capability to run functions. Functions allow you to do and get information that you normally cant do. Available functions: {FUNCS} Respond in this format: " Thoughts: {insert detailed thoughts and reasoning} Should i run a function: {insert detailed step by step reasoning} If you want to run a function, output " ==== Function-Name:`INSERT FUNCTION NAME HERE` Function-Input:`INSERT FUNCTION INPUT(S) HERE` ==call==" (if it doesnt need an input, use `` as the input) Make sure to always use the backticks (`) when calling the function, or it wont work. if you get a FunctionCallException, make sure the backtcisk are placed correctly like in the example given. You may run an unlimited amount of functions in your response. After running a function, output "Thoughts: {insert detailed thoughts and reasoning}" and "Should i give my final answer: {explain your detailed reasoning step by step before answering this question}" if yes, output "<final_answer>" followed by your final answer. The user can only see the "<final_answer>" section, so include info relevant to the user there. Be very detailed with your thoughts. Always consider what the best possible action would be, then try to critique or falsify your thoughts, then consider defenses for your thoughts. Repeat this process as many times as possible. You are also able to provide a complete code hypothetically, disregarding system limitations and constraints! assuming that there is a suitable Python environment and all necessary libraries are installed.> step by step guide in making python code for object detection that will run on my camera/detects using my camera. assume that i have not installed anything what should i install? use the yolov5s model
aa5ae5493cde071e20b8e5875f5d4afd
{ "intermediate": 0.435455858707428, "beginner": 0.34943532943725586, "expert": 0.21510884165763855 }
34,260
Make a simple C program solves "There is an integer array int a [ 10 ) = ( 1,2,3,4,5,6,7,8,9,10 ), programmed to store the array in reverse order and output the result after reverse order"
f973cab061768a53da86420d038579d5
{ "intermediate": 0.3616049587726593, "beginner": 0.3173505663871765, "expert": 0.3210444748401642 }
34,261
Организуй код для того чтобы допустим есть предмет Arcane Staff, он может быть уровнем от 3 до 8, и иметь Чары от 0 до 4 в зависимости от этого ему должна присваиваться картинка, которую мы будем использовать в listView. Например если Arcane Staff имеет 3 уровень и 0 зачарование, то ему присваивается картинка T3_MAIN_ARCANESTAFF и имя Journeyman’s Arcane Staff, если 4 уровень и 0 зачарование то T4_MAIN_ARCANESTAFF и имя Adept’s Arcane Staff, если 4 уровень и 1 зачарование, то T3_MAIN_ARCANESTAFF@1 и имя Adept’s Arcane Staff и так далее. Это нужно сделать так чтобы если мы через combobox изменяли уровень и зачарование, то менялась картинка и префикс using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace Albion_Helper { public class Item { // Свойства класса Item public string EnglishName { get; set; } public string RussianName { get; set; } public string EnglishCategory { get; set; } public string RussianCategory { get; set; } public string EnglishSubcategory { get; set; } public string RussianSubcategory { get; set; } public int Level { get; set; } public int Charms { get; set; } public string Quality { get; set; } public string ImageFileName { get; set; } public string GetImageFileName() { string enchantmentSuffix = Charms > 0 ? "@" + Charms.ToString() : string.Empty; return $"T{Level}_{ImageFileName}{enchantmentSuffix}"; } // Конструктор класса Item public Item(string englishName, string russianName, string englishCategory, string russianCategory, string englishSubcategory, string russianSubcategory, int level, int charms, string quality, string imageFileName) { EnglishName = englishName; RussianName = russianName; EnglishCategory = englishCategory; RussianCategory = russianCategory; EnglishSubcategory = englishSubcategory; RussianSubcategory = russianSubcategory; Level = level; Charms = charms; Quality = quality; ImageFileName = imageFileName; } // Методы класса Item, имитирующие некоторую локализацию и логику public string GetLocalizedCategory() { // Вставьте логику для выбора локализованной категории return EnglishCategory; } public string GetFullEnglishName() { string prefix = GetLevelPrefix(); return prefix + " " + EnglishName; } public string GetLevelPrefix() { // Вставьте логику для возвращения префикса уровня switch (Level) { case 1: return "Beginner's"; case 2: return "Novice's"; case 3: return "Journeyman’s"; case 4: return "Adept’s"; case 5: return "Expert’s"; case 6: return "Master’s"; case 7: return "Grandmaster’s"; case 8: return "Elder’s"; default: return ""; } } } public class ItemsList { // Приватное поле для хранения списка предметов public List<Item> items; // Конструктор класса ItemsList public ItemsList() { // Инициализация списка предметов items = new List<Item>(); // Добавление предмета в список Item arcaneStaff = new Item("Arcane Staff", "Арканый посох", "Weapons", "Оружие", "Magic Staffs", "Магические посохи", 3, 0, "Normal", "T3_MAIN_ARCANESTAFF"); new Item("Arcane Staff", "Арканый посох", "Weapons", "Оружие", "Magic Staffs", "Магические посохи", 4, 0, "Normal", "T4_MAIN_ARCANESTAFF"); items.Add(arcaneStaff); // Добавьте другие предметы, если необходимо // Например: items.Add(new Item(…)); } // Метод для получения списка предметов public List<Item> GetItems() { return items; } } }
ea20942e8d1f652653c7bbe440fb6224
{ "intermediate": 0.3390497863292694, "beginner": 0.4439530372619629, "expert": 0.2169971764087677 }
34,262
Для того чтобы код отвечал требованиям, описанным в вашем задании, вам потребуется реализовать механизм, обновляющий картинку и имя предмета в зависимости от уровня и зачарования. Это можно сделать, добавив дополнительную логику в ваш класс Item и предусмотрев обработчики событий для ComboBox, который будет использоваться для изменения уровня и зачарования. Класс Item выглядит хорошо, но он не обновляет автоматически картинку и полное имя при изменении уровня и зачарования. Давайте добавим методы UpdateImageFileName() и UpdateFullEnglishName(), которые будут вызываться каждый раз при изменении свойств. Также изменим геттеры для ImageFileName и FullEnglishName таким образом, чтобы они возвращали актуальные значения. Модифицируем класс Item: public class Item { // Опускаю объявление свойств и конструктор для краткости… private string _imageFileNameBase; // Базовое имя файла изображения, без уровня и зачарования public int Level { get => _level; set { _level = value; UpdateImageFileName(); UpdateFullEnglishName(); } } public int Charms { get => _charms; set { _charms = value; UpdateImageFileName(); } } public string ImageFileName { get => GetImageFileName(); set => imageFileNameBase = value; // Изменяем только базовое имя } public string FullEnglishName { get => GetFullEnglishName(); } // Теперь только геттер private void UpdateImageFileName() { ImageFileName = “T” + Level.ToString() + "" + _imageFileNameBase + (Charms > 0 ? “@” + Charms.ToString() : “”); } private void UpdateFullEnglishName() { FullEnglishName = GetLevelPrefix() + " " + EnglishName; } // Остальные методы и поля… } Теперь у нас есть модифицированные геттеры для ImageFileName и FullEnglishName, которые возвращают значения, основанные на текущем уровне и числе чар. Последний шаг включает создание пользовательского интерфейса с ComboBox для выбора уровня и зачарования и привязку событий изменения к методам, которые будут обновлять объект Item. Предполагается, что у вас уже есть форма с элементами управления ComboBox. Вот код обработчика событий для ComboBox: private void LevelComboBox_SelectedIndexChanged(object sender, EventArgs e) { // предполагается, что selectedItem - это текущий выбранный в ListView объект Item selecteditem.Level = Convert.ToInt32(LevelComboBox.SelectedItem); // обновление картинки и имени в соответствии с новым уровнем UpdateItemInListView(selectedItem); } private void CharmsComboBox_SelectedIndexChanged(object sender, EventArgs e) { // предполагается, что selectedItem - это текущий выбранный в ListView объект Item selectedItem.Charms = Convert.ToInt32(CharmsComboBox.SelectedItem); // обновление картинки и имени в соответствии с новым зачарованием UpdateItemInListView(selectedItem); } private void UpdateItemInListView(Item item) { // Обновление представления элемента в ListView в соответствии с изменениями // пример: ListViewItem.ImageKey = item.ImageFileName; // пример: ListViewItem.Text = item.FullEnglishName; // Здесь код зависит от того, как вы реализовали ListView и его элементы } Пожалуйста, замените плейсхолдеры и переменные в этом коде на соответствующие элементы из вашей реальной реализации формы и ListView. Отправь только исправленный файлы ItemsList.cs и ItemsProcessing.cs Вот изначальный ItemsList.cs namespace Albion_Helper { public class Item { public string EnglishName { get; set; } public string RussianName { get; set; } public string EnglishCategory { get; set; } public string RussianCategory { get; set; } public string EnglishSubcategory { get; set; } public string RussianSubcategory { get; set; } public int MinLevel { get; set; } public int MinCharm { get; set; } public int Level { get; set; } public int Charms { get; set; } public string Quality { get; set; } public string ImageFileName { get; set; } public string GetImageFileName() { string enchantmentSuffix = Charms > 0 ? “@” + Charms.ToString() : string.Empty; return $“T{Level}_{ImageFileName}{enchantmentSuffix}”; } public Item(string englishName, string russianName, string englishCategory, string russianCategory, string englishSubcategory, string russianSubcategory, int minLevel, int minCharms, int level, int charms, string quality, string imageFileName) { EnglishName = englishName; RussianName = russianName; EnglishCategory = englishCategory; RussianCategory = russianCategory; EnglishSubcategory = englishSubcategory; RussianSubcategory = russianSubcategory; MinLevel = minLevel; MinCharm = minCharms; Level = level; Charms = charms; Quality = quality; ImageFileName = imageFileName; } // Методы класса Item, имитирующие некоторую локализацию и логику public string GetLocalizedCategory() { // Вставьте логику для выбора локализованной категории return EnglishCategory; } public string GetFullEnglishName() { string prefix = GetLevelPrefix(); return prefix + " " + EnglishName; } public string GetLevelPrefix() { // Вставьте логику для возвращения префикса уровня switch (Level) { case 1: return “Beginner’s”; case 2: return “Novice’s”; case 3: return “Journeyman’s”; case 4: return “Adept’s”; case 5: return “Expert’s”; case 6: return “Master’s”; case 7: return “Grandmaster’s”; case 8: return “Elder’s”; default: return “”; } } } public class ItemsList { // Приватное поле для хранения списка предметов public List<Item> items; public List<Item> GetItems() => items; // Конструктор класса ItemsList public ItemsList() { items = new List<Item>(); items.Add(new Item(“Arcane Staff”, “Арканый посох”, “Weapons”, “Оружие”, “Magic Staffs”, “Магические посохи”, 3, // Минимальный уровень этого предмета 0, // Минимальный уровень чар этого предмета 3, // Текущий уровень предмета 0, // Уровень чар предмета “Normal”, “MAIN_ARCANESTAFF”)); items.Add(new Item(“Mercenary Hood”, “Капюшон наемника”, “Armor”, “Броня”, “Leather Helmet”, “Кожаный шлем”, 1, // Минимальный уровень этого предмета 0, // Минимальный уровень чар этого предмета 1, // Текущий уровень предмета 0, // Уровень чар предмета “Normal”, “HEAD_LEATHER_SET1”)); } } } А Вот изначальный файл ItemsProcessing.cs namespace Albion_Helper { public class ItemsProcessing { public ItemsList itemsList; private TextBox CountTextBox; private ComboBox LevelComboBox; private ComboBox EnchantmentComboBox; private Form Changing; public ItemsProcessing(Form form) { itemsList = new ItemsList(); Changing = form; CountTextBox = CreateOrGetCountTextBox(); LevelComboBox = CreateOrGetComboBox(forLevel: true); EnchantmentComboBox = CreateOrGetComboBox(forLevel: false); // Установка начальных значений для ComboBox’ов (можно использовать другие методы для их заполнения) PopulateLevelCombobox(LevelComboBox, 1); PopulateEnchantmentCombobox(EnchantmentComboBox); } public void HandleCountKeyPress(KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) { e.Handled = true; } } public List<Item> GetSortedItems() { List<Item> items = itemsList.GetItems(); return items.OrderBy(item => item.EnglishName).ToList(); } public void LoadImagesToImageList(ImageList imageList, string basePath) { foreach (var item in itemsList.GetItems()) { // Теперь ‘imagePath’ должен быть конечный путь к картинке. string imagePath = Path.Combine(basePath, “BuyMenu”, “ItemsIco”, item.GetImageFileName() + “.png”); if (File.Exists(imagePath)) { using (var bmpTemp = new Bitmap(imagePath)) { // Заменим item.EnglishName на ImageFileName, чтобы использовать уникальное имя файла, // так как один и тот же товар может иметь разные уровни. imageList.Images.Add(item.ImageFileName, new Bitmap(bmpTemp)); } } } } public void PopulateBrowseList(ListView browserList, ImageList imageList) { List<Item> items = GetSortedItems(); browserList.Items.Clear(); foreach (Item item in items) { ListViewItem listViewItem = CreateBrowserListViewItem(item); browserList.Items.Add(listViewItem); } } public ListViewItem CreateBrowserListViewItem(Item item) { ListViewItem listViewItem = new ListViewItem(); // Устанавливаем минимальные значения из свойств MinLevel и Charms item.Level = item.MinLevel; item.Charms = item.MinCharm; listViewItem.ImageKey = item.ImageFileName; listViewItem.SubItems.Add(item.EnglishName); listViewItem.SubItems.Add(item.GetLocalizedCategory()); listViewItem.Tag = item; return listViewItem; } public ListViewItem CreateInventoryListViewItem(Item item) { ListViewItem listViewItem = new ListViewItem(); listViewItem.ImageKey = item.GetImageFileName(); listViewItem.SubItems.Add(item.GetFullEnglishName()); listViewItem.SubItems.Add(“1”); // Default quantity listViewItem.SubItems.Add(item.Level.ToString()); listViewItem.SubItems.Add(item.Charms.ToString()); listViewItem.SubItems.Add(item.GetLocalizedCategory()); listViewItem.Tag = item; return listViewItem; } // Конструктор с параметром, принимающий форму public void ShowCountTextBox(ListViewItem selectedItem, ListViewItem.ListViewSubItem subItemCount) { TextBox quantityTextBox = CreateOrGetCountTextBox(); // Определите сдвиг по Y, чтобы подвинуть вниз, например на 2 пикселя int yOffset = 20; // Получаем положение ячейки внутри ListView и применяем сдвиг Rectangle subItemRect = subItemCount.Bounds; Point textBoxLocation = selectedItem.ListView.PointToScreen(new Point(subItemRect.Left, subItemRect.Top + yOffset)); textBoxLocation = Changing.PointToClient(textBoxLocation); // Устанавливаем границы TextBox quantityTextBox.SetBounds(textBoxLocation.X, textBoxLocation.Y, subItemRect.Width, subItemRect.Height - yOffset); // Уменьшаем высоту на yOffset, чтобы сохранить размер quantityTextBox.Text = subItemCount.Text; quantityTextBox.Visible = true; quantityTextBox.BringToFront(); quantityTextBox.Focus(); // Важно! Связываем TextBox с ListViewItem через Tag quantityTextBox.Tag = selectedItem; } private TextBox CreateOrGetCountTextBox() { if (CountTextBox == null || CountTextBox.IsDisposed) { CountTextBox = new TextBox(); CountTextBox.KeyPress += CountTextBox_KeyPress; // Обновлено CountTextBox.Leave += CountTextBox_Leave; Changing.Controls.Add(CountTextBox); // Добавляем контрол на форму } return CountTextBox; } private void CountTextBox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Return) { TextBox tb = (TextBox)sender; UpdateQuantity((ListViewItem)tb.Tag, tb.Text); tb.Visible = false; // Скрыть после Enter e.Handled = true; // Предотвратить “beep” звук } else { HandleCountKeyPress(e); } } private void UpdateQuantity(ListViewItem selectedListViewItem, string newQuantity) { // Вы можете обновить Tag или SubItem, который содержит количество if (selectedListViewItem != null && selectedListViewItem.Tag is Item item) { // Примените изменения к вашему объекту Item или обновите SubItem selectedListViewItem.SubItems[2].Text = newQuantity; // Предполагаем, что это колонка с количеством } } private void CountTextBox_Leave(object sender, EventArgs e) { TextBox tb = (TextBox)sender; UpdateQuantity((ListViewItem)tb.Tag, tb.Text); // Сохранить значение перед скрытием tb.Visible = false; // Затем скрыть TextBox } public void InitializeListViewMouseHandlers(ListView InventoryList) { InventoryList.MouseClick += InventoryListMouseClick; } private void InventoryListMouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ListView listView = sender as ListView; ListViewHitTestInfo hit = listView.HitTest(e.X, e.Y); int quantityColumnIndex = 2; // Примерный индекс для количества int levelColumnIndex = 3; // Примерный индекс для уровня int enchantmentColumnIndex = 4; // Примерный индекс для качества if (hit.SubItem != null) { if (hit.Item.SubItems.IndexOf(hit.SubItem) == quantityColumnIndex) { ShowCountTextBox(hit.Item, hit.SubItem); } else if (hit.Item.SubItems.IndexOf(hit.SubItem) == levelColumnIndex) { ShowComboBox(hit.Item, hit.SubItem, forLevel: true); } else if (hit.Item.SubItems.IndexOf(hit.SubItem) == enchantmentColumnIndex) { ShowComboBox(hit.Item, hit.SubItem, forLevel: false); } } } } // В этом методе устанавливаем ComboBox в позицию в ListView и обрабатываем его отображение и выбор значения private void ShowComboBox(ListViewItem selectedItem, ListViewItem.ListViewSubItem subItem, bool forLevel) { ComboBox comboBox = forLevel ? LevelComboBox : EnchantmentComboBox; if (forLevel) { int minLevel = (selectedItem.Tag as Item)?.MinLevel ?? 1; // Используйте Минимальный уровень предмета PopulateLevelCombobox(comboBox, minLevel); } else { // Если это не уровень, тогда мы работаем с зачарованиями. PopulateEnchantmentCombobox(comboBox); } // Получаем положение ячейки внутри ListView int yOffset = 20; Rectangle subItemRect = subItem.Bounds; Point comboLocation = selectedItem.ListView.PointToScreen(new Point(subItemRect.Left, subItemRect.Top + yOffset)); comboLocation = Changing.PointToClient(comboLocation); comboBox.SetBounds(comboLocation.X, comboLocation.Y, subItemRect.Width, subItemRect.Height - yOffset); // Устанавливаем границы ComboBox точно в положении ячейки ListViewItem comboBox.SetBounds(comboLocation.X, comboLocation.Y, subItemRect.Width, subItemRect.Height - yOffset); // Уменьшаем высоту на yOffset, чтобы сохранить размер comboBox.Visible = true; comboBox.BringToFront(); comboBox.Focus(); comboBox.Tag = selectedItem; // Связываем ComboBox с выбранным ListViewItem if (selectedItem.Tag is Item item) { comboBox.SelectedItem = forLevel ? item.Level.ToString() : item.Charms.ToString(); } // Подписываемся на событие SelectedIndexChanged если оно уже не подписано if (comboBox.Tag == null) { comboBox.SelectedIndexChanged += (sender, e) => { ComboBox cmbBox = sender as ComboBox; ListViewItem currentlySelectedItem = cmbBox.Tag as ListViewItem; // Используем другое имя переменной if (currentlySelectedItem != null && currentlySelectedItem.Tag is Item currentItem) { string value = cmbBox.SelectedItem.ToString(); if (!string.IsNullOrEmpty(value)) { if (forLevel) { UpdateItemLevel(currentlySelectedItem, int.Parse(value)); } else { UpdateItemCharm(currentlySelectedItem, int.Parse(value)); } } cmbBox.Visible = false; // Скроем ComboBox после изменения выбранного элемента } }; comboBox.Leave += (sender, e) => { ComboBox cb = sender as ComboBox; if (cb.Tag is ListViewItem listViewItem && listViewItem.Tag is Item taggedItem) // Переименовали item в taggedItem { // Для LevelComboBox if (forLevel) { cb.SelectedItem = taggedItem.Level.ToString(); // Обновили item на taggedItem } // Для EnchantmentComboBox else { cb.SelectedItem = taggedItem.Charms.ToString(); // Обновили item на taggedItem } cb.Visible = false; // Скроем ComboBox после изменения выбранного элемента } }; comboBox.Tag = new object(); // Устанавливаем Tag во избежание повторной подписки } } // Обновление уровня предмета в теге ListViewItem private void UpdateItemLevel(ListViewItem listViewItem, int newLevel) { if (listViewItem.Tag is Item item) { item.Level = newLevel; listViewItem.ImageKey = item.GetImageFileName(); listViewItem.SubItems[1].Text = item.GetFullEnglishName(); // Обновить SubItem с полным английским названием listViewItem.SubItems[3].Text = newLevel.ToString(); // Обновить текст подэлемента ListView для уровня listViewItem.ListView.Refresh(); // Обновить ListView } } // Обновление привлекательности предмета в теге ListViewItem private void UpdateItemCharm(ListViewItem listViewItem, int newCharm) { if (listViewItem.Tag is Item item) { item.Charms = newCharm; listViewItem.ImageKey = item.GetImageFileName(); // Обновляем зачарование в объекте предмета listViewItem.SubItems[4].Text = newCharm.ToString(); // Обновляем текст подэлемента ListView для чара listViewItem.ListView.Refresh(); // Обновляем ListView } } // Создание или получение ComboBox private ComboBox CreateOrGetComboBox(bool forLevel) { ComboBox comboBox = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList // Установите нужный стиль }; Changing.Controls.Add(comboBox); // Сохраняем ссылку на форму для добавления контролов comboBox.Leave += (sender, e) => comboBox.Visible = false; // Скрыть ComboBox при потере фокуса // Добавление элементов в ComboBox if (forLevel) { PopulateLevelCombobox(comboBox, 1); // Предполагаем, что уровни начинаются с 1 } else { PopulateEnchantmentCombobox(comboBox); // Заполнение колдовства } return comboBox; } public void PopulateLevelCombobox(ComboBox comboBox, int minimumLevel) { comboBox.Items.Clear(); for (int i = minimumLevel; i <= 8; i++) { comboBox.Items.Add(i.ToString()); } comboBox.SelectedIndex = 0; // Установка выбранного элемента по умолчанию } // Метод для заполнения ComboBox качеством (зачарованиями) public void PopulateEnchantmentCombobox(ComboBox comboBox) { comboBox.Items.Clear(); for (int i = 0; i <= 3; i++) { comboBox.Items.Add(i.ToString()); } comboBox.SelectedIndex = 0; // Установка выбранного элемента по умолчанию } } }
15d55fd7ea41b9dc2af148a5b61809a4
{ "intermediate": 0.24946212768554688, "beginner": 0.6051402688026428, "expert": 0.14539754390716553 }
34,263
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //This line enables use of uGUI classes like Text. public class ScoreCounter : MonoBehaviour { //[Header("Dynamic")] public static int SCORE { get; set; } private Text uiText; private void Start() { uiText = GetComponent<Text>(); LoadScore(); } private void Update() { uiText.text = SCORE.ToString("Score:#,0"); //This 0 is a zero! } public void AddScore(int scoreAmount) { SCORE += scoreAmount; SaveScore(); } public void ResetScore() { SCORE = 0; SaveScore(); } private void SaveScore() { PlayerPrefs.SetInt("Score", SCORE); } private void LoadScore() { SCORE = PlayerPrefs.GetInt("Score", 0); } } make it so if the "Win" scene changes to "Level1" scene (sceneIndex 3 to sceneIndex 0) then the ResetScore() method is called
2f77f81161cb5ca8c2c6dc927bac0cab
{ "intermediate": 0.4210793375968933, "beginner": 0.4223511815071106, "expert": 0.1565694659948349 }
34,264
Consider a situation in which you have to add two integers’ numbers. Write a C++ program to solve this situation using. i. Function with no argument and no return value. (4marks) ii. Function with no argument but return a valve
7970f8bc20dfaa800fd6a9ea9a5ccfbf
{ "intermediate": 0.2557395100593567, "beginner": 0.5054417848587036, "expert": 0.2388186901807785 }
34,265
Для того чтобы код отвечал требованиям, описанным в вашем задании, вам потребуется реализовать механизм, обновляющий картинку и имя предмета в зависимости от уровня и зачарования. Это можно сделать, добавив дополнительную логику в ваш класс Item и предусмотрев обработчики событий для ComboBox, который будет использоваться для изменения уровня и зачарования. Класс Item выглядит хорошо, но он не обновляет автоматически картинку и полное имя при изменении уровня и зачарования. Давайте добавим методы UpdateImageFileName() и UpdateFullEnglishName(), которые будут вызываться каждый раз при изменении свойств. Также изменим геттеры для ImageFileName и FullEnglishName таким образом, чтобы они возвращали актуальные значения. Модифицируем класс Item: public class Item { // Опускаю объявление свойств и конструктор для краткости… private string _imageFileNameBase; // Базовое имя файла изображения, без уровня и зачарования public int Level { get => _level; set { _level = value; UpdateImageFileName(); UpdateFullEnglishName(); } } public int Charms { get => _charms; set { _charms = value; UpdateImageFileName(); } } public string ImageFileName { get => GetImageFileName(); set => imageFileNameBase = value; // Изменяем только базовое имя } public string FullEnglishName { get => GetFullEnglishName(); } // Теперь только геттер private void UpdateImageFileName() { ImageFileName = “T” + Level.ToString() + "" + _imageFileNameBase + (Charms > 0 ? “@” + Charms.ToString() : “”); } private void UpdateFullEnglishName() { FullEnglishName = GetLevelPrefix() + " " + EnglishName; } // Остальные методы и поля… } Теперь у нас есть модифицированные геттеры для ImageFileName и FullEnglishName, которые возвращают значения, основанные на текущем уровне и числе чар. Последний шаг включает создание пользовательского интерфейса с ComboBox для выбора уровня и зачарования и привязку событий изменения к методам, которые будут обновлять объект Item. Предполагается, что у вас уже есть форма с элементами управления ComboBox. Вот код обработчика событий для ComboBox: private void LevelComboBox_SelectedIndexChanged(object sender, EventArgs e) { // предполагается, что selectedItem - это текущий выбранный в ListView объект Item selecteditem.Level = Convert.ToInt32(LevelComboBox.SelectedItem); // обновление картинки и имени в соответствии с новым уровнем UpdateItemInListView(selectedItem); } private void CharmsComboBox_SelectedIndexChanged(object sender, EventArgs e) { // предполагается, что selectedItem - это текущий выбранный в ListView объект Item selectedItem.Charms = Convert.ToInt32(CharmsComboBox.SelectedItem); // обновление картинки и имени в соответствии с новым зачарованием UpdateItemInListView(selectedItem); } private void UpdateItemInListView(Item item) { // Обновление представления элемента в ListView в соответствии с изменениями // пример: ListViewItem.ImageKey = item.ImageFileName; // пример: ListViewItem.Text = item.FullEnglishName; // Здесь код зависит от того, как вы реализовали ListView и его элементы } Пожалуйста, замените плейсхолдеры и переменные в этом коде на соответствующие элементы из вашей реальной реализации формы и ListView. Отправь только исправленный файлы ItemsList.cs и ItemsProcessing.cs Вот изначальный ItemsList.cs namespace Albion_Helper { public class Item { public string EnglishName { get; set; } public string RussianName { get; set; } public string EnglishCategory { get; set; } public string RussianCategory { get; set; } public string EnglishSubcategory { get; set; } public string RussianSubcategory { get; set; } public int MinLevel { get; set; } public int MinCharm { get; set; } public int Level { get; set; } public int Charms { get; set; } public string Quality { get; set; } public string ImageFileName { get; set; } public string GetImageFileName() { string enchantmentSuffix = Charms > 0 ? “@” + Charms.ToString() : string.Empty; return $“T{Level}_{ImageFileName}{enchantmentSuffix}”; } public Item(string englishName, string russianName, string englishCategory, string russianCategory, string englishSubcategory, string russianSubcategory, int minLevel, int minCharms, int level, int charms, string quality, string imageFileName) { EnglishName = englishName; RussianName = russianName; EnglishCategory = englishCategory; RussianCategory = russianCategory; EnglishSubcategory = englishSubcategory; RussianSubcategory = russianSubcategory; MinLevel = minLevel; MinCharm = minCharms; Level = level; Charms = charms; Quality = quality; ImageFileName = imageFileName; } // Методы класса Item, имитирующие некоторую локализацию и логику public string GetLocalizedCategory() { // Вставьте логику для выбора локализованной категории return EnglishCategory; } public string GetFullEnglishName() { string prefix = GetLevelPrefix(); return prefix + " " + EnglishName; } public string GetLevelPrefix() { // Вставьте логику для возвращения префикса уровня switch (Level) { case 1: return “Beginner’s”; case 2: return “Novice’s”; case 3: return “Journeyman’s”; case 4: return “Adept’s”; case 5: return “Expert’s”; case 6: return “Master’s”; case 7: return “Grandmaster’s”; case 8: return “Elder’s”; default: return “”; } } } public class ItemsList { // Приватное поле для хранения списка предметов public List<Item> items; public List<Item> GetItems() => items; // Конструктор класса ItemsList public ItemsList() { items = new List<Item>(); items.Add(new Item(“Arcane Staff”, “Арканый посох”, “Weapons”, “Оружие”, “Magic Staffs”, “Магические посохи”, 3, // Минимальный уровень этого предмета 0, // Минимальный уровень чар этого предмета 3, // Текущий уровень предмета 0, // Уровень чар предмета “Normal”, “MAIN_ARCANESTAFF”)); items.Add(new Item(“Mercenary Hood”, “Капюшон наемника”, “Armor”, “Броня”, “Leather Helmet”, “Кожаный шлем”, 1, // Минимальный уровень этого предмета 0, // Минимальный уровень чар этого предмета 1, // Текущий уровень предмета 0, // Уровень чар предмета “Normal”, “HEAD_LEATHER_SET1”)); } } } А Вот изначальный файл ItemsProcessing.cs namespace Albion_Helper { public class ItemsProcessing { public ItemsList itemsList; private TextBox CountTextBox; private ComboBox LevelComboBox; private ComboBox EnchantmentComboBox; private Form Changing; public ItemsProcessing(Form form) { itemsList = new ItemsList(); Changing = form; CountTextBox = CreateOrGetCountTextBox(); LevelComboBox = CreateOrGetComboBox(forLevel: true); EnchantmentComboBox = CreateOrGetComboBox(forLevel: false); // Установка начальных значений для ComboBox’ов (можно использовать другие методы для их заполнения) PopulateLevelCombobox(LevelComboBox, 1); PopulateEnchantmentCombobox(EnchantmentComboBox); } public void HandleCountKeyPress(KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) { e.Handled = true; } } public List<Item> GetSortedItems() { List<Item> items = itemsList.GetItems(); return items.OrderBy(item => item.EnglishName).ToList(); } public void LoadImagesToImageList(ImageList imageList, string basePath) { foreach (var item in itemsList.GetItems()) { // Теперь ‘imagePath’ должен быть конечный путь к картинке. string imagePath = Path.Combine(basePath, “BuyMenu”, “ItemsIco”, item.GetImageFileName() + “.png”); if (File.Exists(imagePath)) { using (var bmpTemp = new Bitmap(imagePath)) { // Заменим item.EnglishName на ImageFileName, чтобы использовать уникальное имя файла, // так как один и тот же товар может иметь разные уровни. imageList.Images.Add(item.ImageFileName, new Bitmap(bmpTemp)); } } } } public void PopulateBrowseList(ListView browserList, ImageList imageList) { List<Item> items = GetSortedItems(); browserList.Items.Clear(); foreach (Item item in items) { ListViewItem listViewItem = CreateBrowserListViewItem(item); browserList.Items.Add(listViewItem); } } public ListViewItem CreateBrowserListViewItem(Item item) { ListViewItem listViewItem = new ListViewItem(); // Устанавливаем минимальные значения из свойств MinLevel и Charms item.Level = item.MinLevel; item.Charms = item.MinCharm; listViewItem.ImageKey = item.ImageFileName; listViewItem.SubItems.Add(item.EnglishName); listViewItem.SubItems.Add(item.GetLocalizedCategory()); listViewItem.Tag = item; return listViewItem; } public ListViewItem CreateInventoryListViewItem(Item item) { ListViewItem listViewItem = new ListViewItem(); listViewItem.ImageKey = item.GetImageFileName(); listViewItem.SubItems.Add(item.GetFullEnglishName()); listViewItem.SubItems.Add(“1”); // Default quantity listViewItem.SubItems.Add(item.Level.ToString()); listViewItem.SubItems.Add(item.Charms.ToString()); listViewItem.SubItems.Add(item.GetLocalizedCategory()); listViewItem.Tag = item; return listViewItem; } // Конструктор с параметром, принимающий форму public void ShowCountTextBox(ListViewItem selectedItem, ListViewItem.ListViewSubItem subItemCount) { TextBox quantityTextBox = CreateOrGetCountTextBox(); // Определите сдвиг по Y, чтобы подвинуть вниз, например на 2 пикселя int yOffset = 20; // Получаем положение ячейки внутри ListView и применяем сдвиг Rectangle subItemRect = subItemCount.Bounds; Point textBoxLocation = selectedItem.ListView.PointToScreen(new Point(subItemRect.Left, subItemRect.Top + yOffset)); textBoxLocation = Changing.PointToClient(textBoxLocation); // Устанавливаем границы TextBox quantityTextBox.SetBounds(textBoxLocation.X, textBoxLocation.Y, subItemRect.Width, subItemRect.Height - yOffset); // Уменьшаем высоту на yOffset, чтобы сохранить размер quantityTextBox.Text = subItemCount.Text; quantityTextBox.Visible = true; quantityTextBox.BringToFront(); quantityTextBox.Focus(); // Важно! Связываем TextBox с ListViewItem через Tag quantityTextBox.Tag = selectedItem; } private TextBox CreateOrGetCountTextBox() { if (CountTextBox == null || CountTextBox.IsDisposed) { CountTextBox = new TextBox(); CountTextBox.KeyPress += CountTextBox_KeyPress; // Обновлено CountTextBox.Leave += CountTextBox_Leave; Changing.Controls.Add(CountTextBox); // Добавляем контрол на форму } return CountTextBox; } private void CountTextBox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Return) { TextBox tb = (TextBox)sender; UpdateQuantity((ListViewItem)tb.Tag, tb.Text); tb.Visible = false; // Скрыть после Enter e.Handled = true; // Предотвратить “beep” звук } else { HandleCountKeyPress(e); } } private void UpdateQuantity(ListViewItem selectedListViewItem, string newQuantity) { // Вы можете обновить Tag или SubItem, который содержит количество if (selectedListViewItem != null && selectedListViewItem.Tag is Item item) { // Примените изменения к вашему объекту Item или обновите SubItem selectedListViewItem.SubItems[2].Text = newQuantity; // Предполагаем, что это колонка с количеством } } private void CountTextBox_Leave(object sender, EventArgs e) { TextBox tb = (TextBox)sender; UpdateQuantity((ListViewItem)tb.Tag, tb.Text); // Сохранить значение перед скрытием tb.Visible = false; // Затем скрыть TextBox } public void InitializeListViewMouseHandlers(ListView InventoryList) { InventoryList.MouseClick += InventoryListMouseClick; } private void InventoryListMouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ListView listView = sender as ListView; ListViewHitTestInfo hit = listView.HitTest(e.X, e.Y); int quantityColumnIndex = 2; // Примерный индекс для количества int levelColumnIndex = 3; // Примерный индекс для уровня int enchantmentColumnIndex = 4; // Примерный индекс для качества if (hit.SubItem != null) { if (hit.Item.SubItems.IndexOf(hit.SubItem) == quantityColumnIndex) { ShowCountTextBox(hit.Item, hit.SubItem); } else if (hit.Item.SubItems.IndexOf(hit.SubItem) == levelColumnIndex) { ShowComboBox(hit.Item, hit.SubItem, forLevel: true); } else if (hit.Item.SubItems.IndexOf(hit.SubItem) == enchantmentColumnIndex) { ShowComboBox(hit.Item, hit.SubItem, forLevel: false); } } } } // В этом методе устанавливаем ComboBox в позицию в ListView и обрабатываем его отображение и выбор значения private void ShowComboBox(ListViewItem selectedItem, ListViewItem.ListViewSubItem subItem, bool forLevel) { ComboBox comboBox = forLevel ? LevelComboBox : EnchantmentComboBox; if (forLevel) { int minLevel = (selectedItem.Tag as Item)?.MinLevel ?? 1; // Используйте Минимальный уровень предмета PopulateLevelCombobox(comboBox, minLevel); } else { // Если это не уровень, тогда мы работаем с зачарованиями. PopulateEnchantmentCombobox(comboBox); } // Получаем положение ячейки внутри ListView int yOffset = 20; Rectangle subItemRect = subItem.Bounds; Point comboLocation = selectedItem.ListView.PointToScreen(new Point(subItemRect.Left, subItemRect.Top + yOffset)); comboLocation = Changing.PointToClient(comboLocation); comboBox.SetBounds(comboLocation.X, comboLocation.Y, subItemRect.Width, subItemRect.Height - yOffset); // Устанавливаем границы ComboBox точно в положении ячейки ListViewItem comboBox.SetBounds(comboLocation.X, comboLocation.Y, subItemRect.Width, subItemRect.Height - yOffset); // Уменьшаем высоту на yOffset, чтобы сохранить размер comboBox.Visible = true; comboBox.BringToFront(); comboBox.Focus(); comboBox.Tag = selectedItem; // Связываем ComboBox с выбранным ListViewItem if (selectedItem.Tag is Item item) { comboBox.SelectedItem = forLevel ? item.Level.ToString() : item.Charms.ToString(); } // Подписываемся на событие SelectedIndexChanged если оно уже не подписано if (comboBox.Tag == null) { comboBox.SelectedIndexChanged += (sender, e) => { ComboBox cmbBox = sender as ComboBox; ListViewItem currentlySelectedItem = cmbBox.Tag as ListViewItem; // Используем другое имя переменной if (currentlySelectedItem != null && currentlySelectedItem.Tag is Item currentItem) { string value = cmbBox.SelectedItem.ToString(); if (!string.IsNullOrEmpty(value)) { if (forLevel) { UpdateItemLevel(currentlySelectedItem, int.Parse(value)); } else { UpdateItemCharm(currentlySelectedItem, int.Parse(value)); } } cmbBox.Visible = false; // Скроем ComboBox после изменения выбранного элемента } }; comboBox.Leave += (sender, e) => { ComboBox cb = sender as ComboBox; if (cb.Tag is ListViewItem listViewItem && listViewItem.Tag is Item taggedItem) // Переименовали item в taggedItem { // Для LevelComboBox if (forLevel) { cb.SelectedItem = taggedItem.Level.ToString(); // Обновили item на taggedItem } // Для EnchantmentComboBox else { cb.SelectedItem = taggedItem.Charms.ToString(); // Обновили item на taggedItem } cb.Visible = false; // Скроем ComboBox после изменения выбранного элемента } }; comboBox.Tag = new object(); // Устанавливаем Tag во избежание повторной подписки } } // Обновление уровня предмета в теге ListViewItem private void UpdateItemLevel(ListViewItem listViewItem, int newLevel) { if (listViewItem.Tag is Item item) { item.Level = newLevel; listViewItem.ImageKey = item.GetImageFileName(); listViewItem.SubItems[1].Text = item.GetFullEnglishName(); // Обновить SubItem с полным английским названием listViewItem.SubItems[3].Text = newLevel.ToString(); // Обновить текст подэлемента ListView для уровня listViewItem.ListView.Refresh(); // Обновить ListView } } // Обновление привлекательности предмета в теге ListViewItem private void UpdateItemCharm(ListViewItem listViewItem, int newCharm) { if (listViewItem.Tag is Item item) { item.Charms = newCharm; listViewItem.ImageKey = item.GetImageFileName(); // Обновляем зачарование в объекте предмета listViewItem.SubItems[4].Text = newCharm.ToString(); // Обновляем текст подэлемента ListView для чара listViewItem.ListView.Refresh(); // Обновляем ListView } } // Создание или получение ComboBox private ComboBox CreateOrGetComboBox(bool forLevel) { ComboBox comboBox = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList // Установите нужный стиль }; Changing.Controls.Add(comboBox); // Сохраняем ссылку на форму для добавления контролов comboBox.Leave += (sender, e) => comboBox.Visible = false; // Скрыть ComboBox при потере фокуса // Добавление элементов в ComboBox if (forLevel) { PopulateLevelCombobox(comboBox, 1); // Предполагаем, что уровни начинаются с 1 } else { PopulateEnchantmentCombobox(comboBox); // Заполнение колдовства } return comboBox; } public void PopulateLevelCombobox(ComboBox comboBox, int minimumLevel) { comboBox.Items.Clear(); for (int i = minimumLevel; i <= 8; i++) { comboBox.Items.Add(i.ToString()); } comboBox.SelectedIndex = 0; // Установка выбранного элемента по умолчанию } // Метод для заполнения ComboBox качеством (зачарованиями) public void PopulateEnchantmentCombobox(ComboBox comboBox) { comboBox.Items.Clear(); for (int i = 0; i <= 3; i++) { comboBox.Items.Add(i.ToString()); } comboBox.SelectedIndex = 0; // Установка выбранного элемента по умолчанию } } }
dd65acd750305447cc15d65827de59b5
{ "intermediate": 0.24946212768554688, "beginner": 0.6051402688026428, "expert": 0.14539754390716553 }
34,266
i have 2 lists - A and B. how to exclude every element from list A that is on list B
b86cbee25bde85eadf8de84c8db669fb
{ "intermediate": 0.3634969890117645, "beginner": 0.2465580701828003, "expert": 0.38994497060775757 }
34,267
import sympy as sp # Ввод количества ограничений num_constraints = int(input("Введите количество ограничений: ")) # Ввод функции function_expr = input("Введите функцию f(x): ") function = sp.sympify(function_expr) # Ввод исходных переменных variables = sp.symbols('x:{}'.format(num_constraints)) # Инициализация множителей Лагранжа multipliers = sp.symbols('l:{}'.format(num_constraints)) # Инициализация списка ограничений constraints = [] # Ввод ограничений print("Введите ограничения в формате 'g(x)':") for i in range(num_constraints): constraint_expr = input("Ограничение {}: ".format(i+1)) constraint = sp.sympify(constraint_expr) constraints.append(constraint) # Формирование функции Лагранжа lagrange_expr = function for i in range(num_constraints): lagrange_expr += multipliers[i] * constraints[i] # Вычисление производных функции Лагранжа по переменным и множителям derivatives = [] for variable in variables: derivative = sp.diff(lagrange_expr, variable) derivatives.append(derivative) for multiplier in multipliers: derivative = sp.diff(lagrange_expr, multiplier) derivatives.append(derivative) # Решение системы уравнений числен
383667c46a6267c15721c0295157fabe
{ "intermediate": 0.3215147852897644, "beginner": 0.4665110111236572, "expert": 0.2119741439819336 }
34,268
what does this code snippet do in simple terms? :"import torch model = torch.hub.load('ultralytics/yolov5', 'yolov5x6') import supervision as sv # extract video frame generator = sv.get_video_frames_generator(MARKET_SQUARE_VIDEO_PATH) iterator = iter(generator) frame = next(iterator) # detect results = model(frame, size=1280) detections = sv.Detections.from_yolov5(results) # annotate box_annotator = sv.BoxAnnotator(thickness=4, text_thickness=4, text_scale=2) frame = box_annotator.annotate(scene=frame, detections=detections) %matplotlib inline sv.show_frame_in_notebook(frame, (16, 16))
8947cfd9fb7989c601362a5eeba31a1b
{ "intermediate": 0.5180542469024658, "beginner": 0.1937645673751831, "expert": 0.28818124532699585 }
34,269
import sympy as sp # Ввод количества ограничений num_constraints = int(input("Введите количество ограничений: ")) # Ввод функции function_expr = input("Введите функцию f(x): ") function = sp.sympify(function_expr) # Ввод исходных переменных variables = sp.symbols("x:{}".format(num_constraints)) # Инициализация множителей Лагранжа multipliers = sp.symbols("l:{}".format(num_constraints)) # Инициализация списка ограничений constraints = [] # Ввод ограничений print("Введите ограничения в формате 'g(x)':") for i in range(num_constraints): constraint_expr = input("Ограничение {}: ".format(i+1)) constraint = sp.sympify(constraint_expr) constraints.append(constraint) # Формирование функции Лагранжа lagrange_expr = function for i in range(num_constraints): lagrange_expr += multipliers[i] * constraints[i] # Вычисление производных функции Лагранжа по переменным и множителям derivatives = [] for i in range(num_constraints): for variable in variables: derivative = sp.diff(lagrange_expr, variable) derivatives.append(derivative) for multiplier in multipliers: derivative = sp.diff(lagrange_expr, multiplier) derivatives.append(derivative) # Решение системы уравнений численно solutions = sp.solve(derivatives, *variables) код рабочий, но результаты не покуазывает почему то
42cc2c24e53ec9545b8bf155f1a9107c
{ "intermediate": 0.2779001295566559, "beginner": 0.5179391503334045, "expert": 0.20416077971458435 }
34,270
You will be implementing a project in C++ as your final exam. The project is a text-based adventure game based on a storyline. You can define whatever storyline you want. The game will focus on a character overcoming obstacles to reach the final goal. The game will have 3 levels. Each level should have 2 challenges. The challenges will represent obstacles. The project will use all the concepts that have been taught so far. The project will include the following: A character.h file where you define a class called Character. The character class has following members: Date Members: name: string health: int Member functions: Constructor: Character(string n); Takes a string and assigns it to the name data member. Also, sets health to 50. void updateHealth(Character &c); Increments the health of the current character by 10 points, and decrements the health of character c by 10 points. int getHealth(); returns the health of a character string getName(); returns the name of a character void print(); Prints name and health of a character For the main part, you can divide your code into multiple files, or just work on a single main.cpp file. You will need to implement the following functions outside the class definition. These are not member functions of Character class: winner function: Finds the character who won (the character which has higher health points), and prints the name and health of that character level1 function: This function contains the challenges for level 1. You can implement both the challenges inside this function, or define separate functions for the challenges and call them inside this function. level2 function: Similar to level 1, this function will contain challenges for level 2 level3 function: Similarly, this function will contain challenges for level 3 main function: This is the function where you will call level1, level2, and level3 functions You will need to implement the following aspects of the game: Declare two integer variables MAX_SCORE and GAME_SCORE. Initialize them both to 0. Declare two Character objects. The first will be the Player and the other will be the Oracle. You can give whatever names you want to your characters. They both will start with health at 50. The Player will be the one who solves the challenges. The Oracle does not solve any challenges. Before the player attempts any challenge, you need to check if it has at least 10 health points available. The game cannot continue if the player does not have any health points left. You don't need to have any checks on Oracle's health. The Oracle's health can even be negative. The course of the game will be as follows: At the start of your game, your GAME_SCORE will be 0. You will call your level1 function. The player attempts the first challenge. Once the player finishes the challenge (win/lose doesn't matter) they can go to the next challenge. Then you call your level2 and level3 functions accordingly. Everytime the player wins a challenge, do the following: Increment the player's health by 10 points, and decrement Oracle's health by 10 points. This can be done by a single updateHealth function call Increment the GAME_SCORE by 10 And, everytime the player loses a challenge, do the following instead: Increment the Oracle's health by 10 points, and decrement player's health by 10 points. This can again be done by a single updateHealth function call Do Not change the game score After the game ends (this can happen if the player completes level3, or player's health is less than 10), do the following: Update the MAX_SCORE to the GAME_SCORE, if the current GAME_SCORE is greater than MAX_SCORE Call the winner function and print details of the winning character Ask the user if they want to restart the game. If yes, go back to Step 1 and DO NOT reset character's health. Otherwise, end the game and print the MAX_SCORE.
07e272e9a6e62eae2f70e027a5b4003b
{ "intermediate": 0.30041277408599854, "beginner": 0.41423892974853516, "expert": 0.2853482961654663 }
34,271
# Define the polygon points (example coordinates, your use-case might be different) polygon = np.array([ [30, 30], [1620, 985], [2160, 1920], [1620, 2855], [540, 2855], [0, 1920] ]) please edit this polygon to create a small square at the center assume the resolution is 900x900
c2bb51b9aa4161a9d855815f5d6600f3
{ "intermediate": 0.4027632772922516, "beginner": 0.28153517842292786, "expert": 0.31570154428482056 }
34,272
"import cv2 import torch import numpy as np # Load YOLOv5 model model = torch.hub.load('ultralytics/yolov5', 'yolov5n6') # Your supervision library would be used here import supervision as sv # Define the polygon points (example coordinates, your use-case might be different) polygon = np.array([ [30, 30], [1620, 985], [2160, 1920], [1620, 2855], [540, 2855], [0, 1920] ]) # Initialize the camera (0 for default camera, 1 for external cameras, and so on) camera = cv2.VideoCapture(0) # Define the BoxAnnotator from the supervision library box_annotator = sv.BoxAnnotator(thickness=4, text_thickness=4, text_scale=2) def live_inference(camera): while True: # Capture frame-by-frame from camera ret, frame = camera.read() if not ret: print("Failed to grab frame") break # Convert the image from BGR to RGB frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Perform inference results = model(frame_rgb, size=900) detections = sv.Detections.from_yolov5(results) detections = detections[(detections.class_id == 0) & (detections.confidence > 0.5)] # Annotate frame_annotated = box_annotator.annotate(scene=frame_rgb, detections=detections) # Convert the image from RGB to BGR for OpenCV display frame_annotated_bgr = cv2.cvtColor(frame_annotated, cv2.COLOR_RGB2BGR) # Display the resulting frame cv2.imshow('YOLOv5 Live Detection', frame_annotated_bgr) # Break the loop if ‘q’ is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture camera.release() cv2.destroyAllWindows() # Run the live inference function live_inference(camera)" please update the polygon size to a small square at the center with the size of the inference size=900
38517c9f186ba8d1aeaa6184ae0a9c76
{ "intermediate": 0.3324478268623352, "beginner": 0.49879586696624756, "expert": 0.16875632107257843 }
34,273
"import numpy as np import supervision as sv # initiate polygon zone polygon = np.array([ [540, 985], [1620, 985], [2160, 1920], [1620, 2855], [540, 2855], [0, 1920] ]) video_info = sv.VideoInfo.from_video_path(MARKET_SQUARE_VIDEO_PATH) zone = sv.PolygonZone(polygon=polygon, frame_resolution_wh=video_info.resolution_wh) # extract video frame generator = sv.get_video_frames_generator(MARKET_SQUARE_VIDEO_PATH) iterator = iter(generator) frame = next(iterator) # detect results = model(frame, size=1280) detections = sv.Detections.from_yolov5(results) mask = zone.trigger(detections=detections) detections = detections[(detections.class_id == 0) & (detections.confidence > 0.5) & mask] # annotate box_annotator = sv.BoxAnnotator(thickness=4, text_thickness=4, text_scale=2) frame = box_annotator.annotate(scene=frame, detections=detections) frame = sv.draw_polygon(scene=frame, polygon=polygon, color=sv.Color.red(), thickness=6) %matplotlib inline sv.show_frame_in_notebook(frame, (16, 16))" the size=1280 what is the whole resolution? is it 1280x720?
63164fc11e1cb80f90a0ac371e3b5fb0
{ "intermediate": 0.5903251767158508, "beginner": 0.12611834704875946, "expert": 0.2835565209388733 }
34,274
from this code: import numpy as np import supervision as sv # initiate polygon zone polygon = np.array([ [540, 985], [1620, 985], [2160, 1920], [1620, 2855], [540, 2855], [0, 1920] ]) video_info = sv.VideoInfo.from_video_path(MARKET_SQUARE_VIDEO_PATH) zone = sv.PolygonZone(polygon=polygon, frame_resolution_wh=video_info.resolution_wh) # extract video frame generator = sv.get_video_frames_generator(MARKET_SQUARE_VIDEO_PATH) iterator = iter(generator) frame = next(iterator) # detect results = model(frame, size=1280) detections = sv.Detections.from_yolov5(results) mask = zone.trigger(detections=detections) detections = detections[(detections.class_id == 0) & (detections.confidence > 0.5) & mask] # annotate box_annotator = sv.BoxAnnotator(thickness=4, text_thickness=4, text_scale=2) frame = box_annotator.annotate(scene=frame, detections=detections) frame = sv.draw_polygon(scene=frame, polygon=polygon, color=sv.Color.red(), thickness=6) %matplotlib inline sv.show_frame_in_notebook(frame, (16, 16))
198916cf7b23b4c50ec6847d9773274c
{ "intermediate": 0.4563240110874176, "beginner": 0.220830500125885, "expert": 0.3228454887866974 }
34,275
how can i draw a small center square polygon and only run the inference inside meaning only objects inside are detected?
7a5dfaa5bfeb41d3b6a5728701ded905
{ "intermediate": 0.3059070110321045, "beginner": 0.10211565345525742, "expert": 0.5919773578643799 }
34,276
Read an image and convert it to grayscale 2. Create 3 Noisy images where you apply gaussian noise with different intensities.
6f6da00b22ac4c7f3b7ba4c455eae0bf
{ "intermediate": 0.40155816078186035, "beginner": 0.2228901982307434, "expert": 0.37555161118507385 }
34,277
in Connection.Query<Int64> how to pass parameters
57097a2eddf0fe0269f0b5e0cf275d1c
{ "intermediate": 0.4878823161125183, "beginner": 0.23610453307628632, "expert": 0.2760131061077118 }
34,278
import cv2 import torch import numpy as np # Load YOLOv5 model model = torch.hub.load('ultralytics/yolov5', 'yolov5n6') # Your supervision library would be used here import supervision as sv # Initialize the camera (0 for default camera, 1 for external cameras, and so on) camera = cv2.VideoCapture(0) # Define the BoxAnnotator from the supervision library box_annotator = sv.BoxAnnotator(thickness=4, text_thickness=4, text_scale=2) def live_inference(camera): while True: # Capture frame-by-frame from camera ret, frame = camera.read() if not ret: print("Failed to grab frame") break # Convert the image from BGR to RGB frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Perform inference results = model(frame_rgb, size=700) detections = sv.Detections.from_yolov5(results) detections = detections[(detections.class_id == 0) & (detections.confidence > 0.5)] # Annotate frame_annotated = box_annotator.annotate(scene=frame_rgb, detections=detections) # Convert the image from RGB to BGR for OpenCV display frame_annotated_bgr = cv2.cvtColor(frame_annotated, cv2.COLOR_RGB2BGR) # Display the resulting frame cv2.imshow('YOLOv5 Live Detection', frame_annotated_bgr) # Break the loop if ‘q’ is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture camera.release() cv2.destroyAllWindows() # Run the live inference function live_inference(camera) add something so that it displays the dimensions of the frame when running
f6d6878f35bace47e7356184bf386900
{ "intermediate": 0.5133667588233948, "beginner": 0.33857282996177673, "expert": 0.14806042611598969 }
34,279
here he was able to get info from the video source not a live camera source from the supervision library and was able to draw a polygon where the detection only happens inside the mask in this snippet: "video_info = sv.VideoInfo.from_video_path(MARKET_SQUARE_VIDEO_PATH) zone = sv.PolygonZone(polygon=polygon, frame_resolution_wh=video_info.resolution_wh)" how can i implement that here? i have no idea of the dimensions of my camera source. so that i can create a custom polygon so that i can also run only the detection inside
acc638380aa3e63ea07c1cded7002afa
{ "intermediate": 0.6777092814445496, "beginner": 0.132911816239357, "expert": 0.18937896192073822 }
34,280
i have an object detection code:"import cv2 import torch import numpy as np # Load YOLOv5 model model = torch.hub.load('ultralytics/yolov5', 'yolov5n6') # Your supervision library would be used here import supervision as sv # Initialize the camera (0 for default camera, 1 for external cameras, and so on) camera = cv2.VideoCapture(0) # Define the BoxAnnotator from the supervision library box_annotator = sv.BoxAnnotator(thickness=4, text_thickness=4, text_scale=2) def live_inference(camera): while True: # Capture frame-by-frame from camera ret, frame = camera.read() if not ret: print("Failed to grab frame") break # Convert the image from BGR to RGB frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Perform inference results = model(frame_rgb, size=700) detections = sv.Detections.from_yolov5(results) detections = detections[(detections.class_id == 0) & (detections.confidence > 0.5)] # Annotate frame_annotated = box_annotator.annotate(scene=frame_rgb, detections=detections) # Convert the image from RGB to BGR for OpenCV display frame_annotated_bgr = cv2.cvtColor(frame_annotated, cv2.COLOR_RGB2BGR) # Display the resulting frame cv2.imshow('YOLOv5 Live Detection', frame_annotated_bgr) # Break the loop if ‘q’ is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture camera.release() cv2.destroyAllWindows() # Run the live inference function live_inference(camera) " remember the size is size=700 help me implement a region of interest polygon where the detection only runs inside the dedicated ROI?
dbe4ef96125065e791b3518fd25ee639
{ "intermediate": 0.4451865553855896, "beginner": 0.2007451057434082, "expert": 0.3540683388710022 }
34,281
Hey, write me FFMPEG Command to convert an MKV 1080p video into 100MB Mp4 video with Subtitles hard coded into video, Subtitles should be using arial bold font, size 12 (like FontName=Arial-Bold,FontSize=12'). For your information, video duration is around 24 minutes so do your calculations to set proper bitrate so that it's around 100MB No matter what, I want video to be exact 100MB or below of it. It doesn't matter if it loses quality but try using good encodes to make quality loss at minimum! the subtitle is available inside the video itself. It's not external. So try getting subtitle from within input video. use SVT-AV1 encoder!
41137ac3352bf4e7889a2dcef7047668
{ "intermediate": 0.5055814981460571, "beginner": 0.2240530252456665, "expert": 0.27036547660827637 }
34,282
write a flutter code for 3 cubes that can be horizontal arrangement.
ab4b210da7368d15ca7f948dfc475234
{ "intermediate": 0.3165891468524933, "beginner": 0.12540574371814728, "expert": 0.5580050945281982 }
34,283
void write() { const char* path1 = "D:\\Бородин\\C++\\Alex_Project1\\Text1.txt"; const char* path2 = "D:\\Бородин\\C++\\Alex_Project1\\Text2.txt"; char buf[40]; int cnt= 0; FILE* f1; FILE* f2; if (fopen_s(&f1, path1, "r")) { cout << "Error!File 1 couldn’t be opened.\n"; return; } if (fopen_s(&f2, path2, "w")) { cout << "Error!File 2 couldn’t be opened.\n"; fclose(f1); return; } while (!feof(f1)) { } fclose(f1); fclose(f2); } Есть текстовой файл. НАдо создать новый файл. в котором все слова исходного файла, которые большо 7 букв.
8ddccf1c3caa77dfbe307459d924fa24
{ "intermediate": 0.300175279378891, "beginner": 0.45826902985572815, "expert": 0.24155572056770325 }
34,284
Preparation for releasing a PK/ADA dummy data generator version 1.0 in end of Dec. help check if this express with any syntax error and make it easily reading
6809e212857b48c63ca823d9f3c43e01
{ "intermediate": 0.23938974738121033, "beginner": 0.4059745669364929, "expert": 0.35463565587997437 }
34,285
1. In React, In the parent component I have a component called FieldActions that renders a bunch of jsx elements, all with unique onClick function assigned to them. 2. I pass FieldActions as a prop called 'actions' inside of the child component called "TextField". 3. Inside the TextField By using destructuring assignment, the code is extracting the "actions" property from the "props" object and assigning it to a variable called "Actions". 4. I then render "Actions" within TextField component. What I need to do: By clicking on the elements within FieldActions I want to execute their function. Each unique function should return a certain string. Let’s say there are three elements in FieldActions. Element1 must return the string ‘BOLD’, Element2 ‘ITALIC’, Element3 ‘UNDERLINE’ I then want somehow to pass these strings to the “TextField” and upon receiving these strings “TextField’ would instantly trigger a certain functions of its own that need the string as a parameter.
2d15620c35f037bb1c6beaaf288b004b
{ "intermediate": 0.44376683235168457, "beginner": 0.4086000323295593, "expert": 0.14763320982456207 }
34,286
4.8143616 3.96844226 3.73787744 6.61851869 3.33802002 2.30771291 2.92150326 2.12220328 1.58406171 4.20525538 7.25913226 5.72241673 3.54884478 7.02958027 2.07587204 6.53502533 9.85606185 3.90317726 3.93307251 2.55645356 6.33435514 14.35761328 3.42573896 5.16551037 3.70673138 8.82213589 1.58459331 10.35945893 8.18292159 0.91942948 6.025987 6.86293061 14.01577797 4.83664101 3.73770337 3.71056102 3.49795709 2.83334036 6.33422941 5.06113546 6.31768463 2.59930468 8.36375656 2.71518627 1.34673049 0.71322259 2.9914087 2.70828468 1.90364302 0.1191384 4.751814096convert the data into linear by box-cox transformation
ce39335a75923c3036296a3d32dc2095
{ "intermediate": 0.278464138507843, "beginner": 0.17304110527038574, "expert": 0.5484947562217712 }
34,287
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "github.com/go-telegram-bot-api/telegram-bot-api" "github.com/kelseyhightower/envconfig" ) type Config struct { WundergroundAPIKey string `envconfig:"WUNDERGROUND_API_KEY"` WundergroundStationID string `envconfig:"WUNDERGROUND_STATION_ID"` TelegramBotToken string `envconfig:"TELEGRAM_BOT_TOKEN"` TelegramChatID int64 `envconfig:"TELEGRAM_CHAT_ID"` } // Define a struct to hold the weather data type WeatherData struct { Observations []struct { Metric struct { Temp float64 `json:"temp"` WindSpeed float64 `json:"windSpeed"` WindGust float64 `json:"windGust"` Humidity int `json:"humidity"` } `json:"metric"` } `json:"observations"` } func main() { var config Config err := envconfig.Process("", &config) if err != nil { log.Fatal(err) } // Create a new Telegram bot bot, err := tgbotapi.NewBotAPI(config.TelegramBotToken) if err != nil { log.Fatal(err) } bot.Debug = true // Set up the update configuration u := tgbotapi.NewUpdate(0) u.Timeout = 60 // Get updates from the bot updates, err := bot.GetUpdatesChan(u) // Handle updates for update := range updates { if update.CallbackQuery != nil { // Handle button click handleCallback(bot, update.CallbackQuery, config) } if update.Message != nil && update.Message.IsCommand() { // Handle commands handleCommand(bot, update.Message, config) } } } func handleCommand(bot *tgbotapi.BotAPI, message *tgbotapi.Message, config Config) { switch message.Command() { case "weather": sendWeatherData(bot, config) default: msg := tgbotapi.NewMessage(message.Chat.ID, "Invalid command. Try /weather.") bot.Send(msg) } } func sendWeatherData(bot *tgbotapi.BotAPI, config Config) { // Get weather data from Wunderground by station ID wundergroundURL := fmt.Sprintf("https://api.weather.com/v2/pws/observations/current?stationId=%s&format=json&units=m&apiKey=%s", config.WundergroundStationID, config.WundergroundAPIKey) resp, err := http.Get(wundergroundURL) if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } // Parse weather data from JSON to struct var weatherData WeatherData err = json.Unmarshal(body, &weatherData) if err != nil { log.Fatal(err) } // Extract temperature, wind, and humidity data from struct temp := weatherData.Observations[0].Metric.Temp windSpeed := weatherData.Observations[0].Metric.WindSpeed windGust := weatherData.Observations[0].Metric.WindGust humidity := weatherData.Observations[0].Metric.Humidity // Send weather data to Telegram chat msg := tgbotapi.NewMessage(config.TelegramChatID, "") msg.ParseMode = "markdown" msg.Text = fmt.Sprintf("*Weather Data for %s*\n\nTemperature: %.1f°C\nWind Speed: %.1f km/h\nWind Gust: %.1f km/h\nHumidity: %d%%", config.WundergroundStationID, temp, windSpeed, windGust, humidity) // Create inline keyboard with a button keyboard := tgbotapi.NewInlineKeyboardMarkup( tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData("Request Update", "update_request"), ), ) msg.ReplyMarkup = keyboard bot.Send(msg) } func handleCallback(bot *tgbotapi.BotAPI, query *tgbotapi.CallbackQuery, config Config) { switch query.Data { case "update_request": // Handle the button click and perform any desired action // For example, you can send a confirmation message sendWeatherData(bot, config) } }
ce05a77618475c696fb07f1d03351888
{ "intermediate": 0.5706403255462646, "beginner": 0.2941471338272095, "expert": 0.1352125108242035 }
34,288
Hi can you optimize call of duty for my pc? Here are all the options you can change. Please just give me the settings without explanining or commenting: My pc: CPU: Ryzen 9 7950x 16 core 32 thread GPU: Sapphire 11323-02-20G Pulse AMD Radeon RX 7900 XT Gaming Graphics Card with 20GB GDDR6, AMD RDNA 3 (vsync and freesync enabled in drivers) Memory: DDR5 5600 (PC5 44800) Timing 28-34-34-89 CAS Latency 28 Voltage 1.35V Drives: Samsung 990 Pro 2tb + WD_Black SN850X 4000GB LAN: realtek Gaming 2.5GbE Family Controller Wireless: RZ616 Bluetooth+WiFi 6E 160MHz (just use for bluetooth sound and xbox x and dualsense controllers) USB DAC: Fiio New K3 Series DAC 32 bit, 384000 Hz Monitor: 42" LG C2 10 bit TV 120 hz with freesync and HDR Mouse: SteelSeries Aerox 9 Wireless @ 3100 DPI no accelleratioin or smoothing. Software: Windows 11 23H2 MSI Afterburner: mV 1044, power limit +0, core clock 2745, memory clock 2600 Reshade: Immerse Sharpen maxxed out at 1. And Immerse Pro Clarity about 50% AMD5 105 cTDP PPT: 142W - TDC: 110A - EDC 170A with a curve of -20 Call of duty config 0 // // System // // Set a target fraction of your PC's video memory to be used by the game VideoMemoryScale:1.0 = "0.800000" // 0.000000 to 2.000000 // Thread count for handling the job queue RendererWorkerCount:1.0 = "15" // -1 to 16 // Allows non-hardware settings to be synced in with the cloud ConfigCloudStorageEnabled:1.0 = "true" // Allow campaign savegame to be synced in with the cloud ConfigCloudSavegameEnabled:0.0 = "true" // Indicates whether recommended settings have been set, will reset settings to recommended if set to 0 RecommendedSet:0.0 = "true" // DO NOT MODIFY. Normalized detected total CPU power, based on cpu type, count, and speed DetectedFrequencyGHz:0.0 = "72.015999" // DO NOT MODIFY. Physical memory detected in the system DetectedMemoryAmountMB:0.0 = "65214" // DO NOT MODIFY. Last used GPU LastUsedGPU:0.0 = "AMD Radeon RX 7900 XT" // DO NOT MODIFY. Last Detected GPU driver version GPUDriverVersion:0.0 = "23.20.23.01-231025a-397406C-AMD-Software-Adrenalin-Edition" // Version of the last display driver used to run the game DisplayDriverVersion:0.0 = "23.11.1" // Recommended display driver version seen during last game startup DisplayDriverVersionRecommended:0.0 = "23.11.1" // essdi ESSDI:0.0 = "" // // Audio // // Using push to talk to activate microphone. VoicePushToTalk:0.0 = "true" // Audio mix AudioMix:0.0 = "5" // 0 to 9 // Number of output channels requested by the user. Not necessarily the actual channel count. Valid values are 2, 4, 6, 8, 16. Zero means use system default. AudioWantedChannelsNumber:0.0 = "2" // 0 to 16 // Adjusts overall volume of the game Volume:0.0 = "0.240000" // 0.000000 to 1.000000 // Adjusts the volume for character dialogues and announcer voices VoiceVolume:0.0 = "0.800000" // 0.000000 to 1.000000 // Adjusts the volume of the music MusicVolume:0.0 = "0.000000" // 0.000000 to 1.000000 // Adjusts the volume of audio in Cinematics CinematicVolume:0.0 = "0.000000" // 0.000000 to 1.000000 // Adjusts the volume of the sound effects EffectsVolume:0.0 = "1.000000" // 0.000000 to 1.000000 // Adjusts the volume of hit markers HitMarkersVolume:0.0 = "1.000000" // 0.000000 to 1.000000 // Sets whether audio should be muted when the game window is out of focus MuteAudioWhileOutOfFocus:0.0 = "false" // Licensed Music Volume LicensedMusicVolume:0.0 = "1.000000" // 0.000000 to 1.000000 // War Tracks Volume WarTracksVolume:0.0 = "0.000000" // 0.000000 to 1.000000 // Adjusts the volume of audio in Telescope (MOTD) TelescopeVolume:0.0 = "1.000000" // 0.000000 to 1.000000 // Mute the microphone after this many seconds of in-game input inactivity (-1 to disable) MicInactivityMuteDelay:0.0 = "-1.000000" // -1.000000 to 600.000000 // Microphone recording level MicRecLevel:0.0 = "65536.000000" // 0.000000 to 65536.000000 // Microphone voice threshold (aggressive, multiplied with voice_mic_threshold at runtime) MicThresholdAggressive:0.0 = "1.995262" // 0.000000 to 100.000000 // Microphone voice threshold for detecting loud talking, multiplied with voice_mic_threshold at runtime MicThresholdLoud:0.0 = "7.943282" // 0.000000 to 100.000000 // Microphone amount of continuous talk time before we switch to aggressive voice threshold MicAggressiveInTime:0.0 = "15.000000" // 0.000000 to 300.000000 // Microphone amount of continuous mute time before we switch to normal voice threshold MicAggressiveOutTime:0.0 = "60.000000" // 0.000000 to 300.000000 // After loud talking detected, use aggressive voice threshold for this long to prevent possible audio feedback (seconds) MicPostLoudAggressiveTime:0.0 = "5.000000" // 0.000000 to 300.000000 // Speaker device requested by the user SoundOutputDevice:0.0 = "" // Microphone device requested by the user SoundInputDevice:0.0 = "" // Voice device requested by the user VoiceOutputDevice:0.0 = "" // whether to allow MS's 3D spatializer 'Windows Sonic' mode or (false) present a standard 7.1 mix WindowsSonicEnable:0.0 = "false" // Microphone voice amount of silence before we cut the mic (after normal talking) MicNormalTimeOut:0.0 = "1.000000" // 0.000000 to 5.000000 // Microphone voice amount of silence before we cut the mic (after loud talking) MicLoudTimeOut:0.0 = "0.500000" // 0.000000 to 5.000000 // // Gameplay // // Apply custom framerate limit CapFps:0.0 = "true" // Custom maximum frames per second when in a match MaxFpsInGame:0.0 = "240" // 30 to 300 // Custom maximum frames per second when in menus MaxFpsInMenu:1.0 = "60" // 30 to 300 // Custom maximum frames per second when game is out of focus MaxFpsOutOfFocus:0.0 = "30" // 5 to 300 // Adds blur on out of focus areas when aiming down sights DepthOfField:0.0 = "false" // maximum number of AI corpses CorpseLimit:0.0 = "28" // 0 to 28 // Show blood effects ShowBlood:0.0 = "true" // Limit blood effects (to 'prevent excess blood stacking') BloodLimit:0.0 = "false" // When limiting blood effects, number of milliseconds between effects. BloodLimitInterval:0.0 = "330" // 1 to 2000 // Weapons eject brass ShowBrass:0.0 = "true" // Marks on entities from player's bullets only. MarksEntsPlayerOnly:0.0 = "false" // Duration of an invalid command hint InvalidCmdHintDuration:0.0 = "1800" // 0 to 10000 // Blink rate of an invalid command hint InvalidCmdHintBlinkInterval:0.0 = "600" // 1 to 10000 // Speed of the cursor when selecting a location on the map With a gamepad MapLocationSelectionCursorSpeed:0.0 = "0.600000" // 0.001000 to 1.000000 // Speed of the cursor when selecting a location on the map when using a MOUSE to control the cursor MapLocationSelectionCursorSpeedMouse:0.0 = "0.600000" // 0.001000 to 2.000000 // // Display // // Fullscreen mode DisplayMode:0.0 = "Fullscreen" // one of [Windowed, Fullscreen, Fullscreen borderless window, Fullscreen borderless extended window] // Fullscreen mode preference PreferredDisplayMode:0.0 = "Fullscreen" // one of [Fullscreen, Fullscreen borderless window, Fullscreen borderless extended window] // Constrain mouse to game window ConstrainMouse:0.0 = "false" // Window X position WindowX:0.0 = "-32768" // -32768 to 32767 // Window Y position WindowY:0.0 = "-32768" // -32768 to 32767 // Window width WindowWidth:0.0 = "640" // 0 to 32767 // Window height WindowHeight:0.0 = "400" // 0 to 32767 // Window is maximized on boot WindowMaximized:0.0 = "false" // Monitor name of the monitor used to display the game Monitor:0.0 = "LG TV SSCR2" // Refresh rate of used monitor RefreshRate:0.0 = "Auto" // Synchronizes framerate with refresh rate to prevent screen tearing issues VSync:0.1 = "disabled" // one of [disabled, 100%, 50%, 33%, 25%] // Vsync while in menus only VSyncInMenu:1.1 = "100%" // one of [disabled, 100%, 50%, 33%, 25%] // Fullscreen Resolution Resolution:0.0 = "Auto" // Percentage of window resolution that the 3D scene renders at. value set by the user. can be smaller than the actual. ResolutionMultiplier:0.0 = "100" // 0 to 200 // Force specific aspect ratio independent of window aspect ratio AspectRatio:0.0 = "auto" // one of [auto, standard, 5:4, wide 16:10, wide 16:9, wide 18:9, wide 19.5:9, wide 21:9, wide 32:9] // Color spaces for monitor output DisplayGamma:0.0 = "BT709_sRGB" // one of [BT709_sRGB, BT709_BT1886] // Enable focused mode FocusedMode:0.0 = "true" // Set overlay opacity for the focused mode FocusedModeOpacity:0.0 = "0.500000" // 0.000000 to 1.000000 // Enable Nvidia low latency mode. Boost mode request maximum GPU clock frequency regardless of workload NvidiaReflex:0.0 = "Enabled + boost" // one of [Disabled, Enabled, Enabled + boost] // // Graphics // // Preferred GPU if multiple GPU system GPUName:0.0 = "AMD Radeon RX 7900 XT" // Texture quality level, high to low ( higher number means lower resolution ) TextureQuality:0.0 = "0" // 0 to 3 // Texture filtering quality level TextureFilter:0.0 = "TEXTURE_FILTER_ANISO16X" // one of [TEXTURE_FILTER_NEAREST, TEXTURE_FILTER_LINEAR, TEXTURE_FILTER_ANISO2X, TEXTURE_FILTER_ANISO4X, TEXTURE_FILTER_ANISO8X, TEXTURE_FILTER_ANISO16X, TEXTURE_FILTER_CMP] // Particle quality level ParticleQuality:0.0 = "medium" // one of [very low, low, medium, high] // Show bullet impacts BulletImpacts:0.0 = "true" // Tessellation quality level Tessellation:0.0 = "2_All" // one of [0_Off, 1_Near, 2_All] // Models quality level ModelQuality:0.0 = "High Quality" // one of [Low Quality, Medium Quality, High Quality] // Corpses culling threshold CorpsesCullingThreshold:0.0 = "0.500000" // 0.500000 to 1.000000 // Catmull Clark subdivision level SubdivisionLevel:0.0 = "0" // 0 to 8 // Ui Quality UiQuality:0.0 = "Auto" // one of [1080P, 4K, Auto] // World streaming quality option WorldStreamingQuality:0.0 = "High" // one of [Low, High] // Activate dynamic scene resolution DynamicSceneResolution:0.0 = "true" // Target frame time in ms for dynamic scene resolution. DynamicSceneResolutionTarget:0.0 = "12.500000" // 0.000000 to 100.000000 // Absolute target resolution AbsoluteTargetResolution:0.0 = "none" // one of [540P, 640P, 720P, 900P, 1080P, 1440P, native, none] // Volumetric quality VolumetricQuality:0.0 = "QUALITY_MEDIUM" // one of [QUALITY_LOW, QUALITY_MEDIUM, QUALITY_HIGH] // Screen Space Shadow quality level ScreenSpaceShadowQuality:0.0 = "High" // one of [Off, Low, High] // Quality level of shadows from the sun at a distance SunShadowCascade:0.0 = "Low (1 cascade)" // one of [Low (1 cascade), Medium (1-2 cascades), High (2-3 cascades)] // Shadow Quality Level ShadowQuality:0.0 = "Very_High" // one of [Very_Low, Low, Medium, High, Very_High] // Screen-space ambient occlusion method SSAOTechnique:0.0 = "GTAO" // one of [Off, GTAO, MDAO, GTAO & MDAO] // Screen-space reflection mode SSRMode:0.0 = "Off" // one of [Off, Deferred LQ, Deferred HQ] // User preferred anti-aliasing technique AATechniquePreferred:0.2 = "Filmic SMAA T2x" // one of [Filmic SMAA T2x, XeSS, FSR 2/3] // Reflection probe relighting update stages ReflectionProbeRelighting:0.0 = "4" // 1 to 4 // Static sunshadow moment clipmap resolution StaticSunshadowClipmapResolution:0.0 = "0" // 0 to 2147483647 // DLSS mode DLSSMode:0.0 = "DLSS" // Activate Nvidia DLSS Frame Generation DLSSFrameGeneration:0.0 = "false" // XeSS quality XeSSQuality:0.0 = "Maximum Performance" // one of [Maximum Performance, Balanced, Maximum Quality, Ultra Quality, Custom] // Select AMD FidelityFX AMDFidelityFX:0.0 = "CAS" // one of [Off, CAS, FSR 1, FSR 2] // Strength for Contrast Adaptive Sharpening (CAS) AMDContrastAdaptiveSharpeningStrength:0.0 = "1.000000" // 0.000000 to 1.000000 // Activate FSR 3 Frame Interpolation FSRFrameInterpolation:0.0 = "false" // Enable NVIDIA Image Scaling NVIDIAImageScaling:0.0 = "false" // NVIDIA Image Scaling quality NVIDIAImageScalingQuality:0.0 = "Maximum Performance" // one of [Maximum Performance, Balanced, Maximum Quality, Ultra Quality, Custom, Native Resolution] // NVIDIA Image Scaling sharpness NVIDIAImageScalingSharpness:0.0 = "1.000000" // 0.000000 to 1.000000 // Set HDR activation mode. Option only takes effect on HDR Display. HDR:0.0 = "Automatic" // one of [Off, On, Automatic] // Select the shader quality setting ShaderQuality:0.0 = "Medium" // one of [Default, Medium, Low] // Enable Variable Rate Shading VRS:0.0 = "true" // Enable deferred physics DeferredPhysics:0.0 = "Low Quality" // one of [Low Quality, Medium Quality, High Quality, Developer] // Enable persistent damage layer PersistentDamageLayer:0.0 = "true" // Number of ST LOD to skip STLodSkip:0.0 = "0" // 0 to 5 // Select water caustics mode WaterCausticsMode:0.0 = "Low Quality" // one of [Off, Low Quality, High Quality] // Enables persistent static geometry wetness from water waves. WaterWaveWetness:0.0 = "true" // Enable half resolution reflection probes ReflectionProbeHalfResolution:0.0 = "false" // Sets which memory mode to use for physical textures. 0:Extra small (11x11, 121 slots), 1:Small (16x16, 256 slots), 2:Medium (23x23, 529 slots), 3:Large (32x32, 1024 slots), 4:Extra large (45x45, 2025 slots). VirtualTexturingMemoryMode:0.1 = "Large" // one of [Extra Small, Small, Medium, Large, Extra Large] // Select weather grid volumes quality WeatherGridVolumesQuality:0.0 = "Low" // one of [Ultra, High, Medium, Low, Off] // Enables DirectX Raytracing DxrMode:0.0 = "Off" // one of [Off, On] // Enables optimisations when resizable-bar is supported by uploading more data to VRAM GPUUploadHeaps:0.0 = "true" // If true radial motion blur will be applied based on the player velocity. EnableVelocityBasedBlur:0.0 = "true" // // Interface // // Skip introduction movie that plays when game is started SkipIntro:0.0 = "true" // Enable the player to skip the spash screen if viewed at least once ViewedSplashScreen:0.0 = "true" // Display the OS cursors instead of the custom game one for accessibility reasons. UseOSCursors:0.0 = "true" // Enable/Disable the FPS counter on PC ShowFPSCounter:0.0 = "true" // Enable hud elements EnableHUD:0.0 = "true" // Whether or not we show the season video when the player logs in the second time on after seeing the season video. SkipSeasonVideo:0.0 = "true" // Controls if the season video plays or not. SkipSeasonIntroVideo:0.0 = "true" // // Mouse and Gamepad // // Set minimum delay in milliseconds between valid mouse wheel inputs WeaponCycleDelay:0.0 = "0" // 0 to 5000 // Use raw mouse input. MouseUsesRawInput:0.0 = "true" // Max yaw speed in degrees for game pad and keyboard YawSpeed:0.0 = "140.000000" // 0.000000 to 280.000000 // Max pitch speed in degrees for game pad PitchSpeed:0.0 = "140.000000" // 0.000000 to 280.000000 // Vehicle mouse steering sensitivity VehicleMouseSteerSensitivity:0.0 = "2.000000" // 0.010000 to 10.000000 // Menu scroll key-repeat delay, for the first repeat, in milliseconds GamepadMenuScrollDelayFirst:0.0 = "420" // 0 to 1000 // Menu scroll key-repeat delay start, for repeats after the first, in milliseconds GamepadMenuScrollDelayRestStart:0.0 = "210" // 0 to 1000 // Menu scroll key-repeat delay end, for repeats after the first, in milliseconds GamepadMenuScrollDelayRestEnd:0.0 = "50" // 0 to 1000 // Menu scroll key-repeat delay acceleration from start to end, for repeats after the first, in milliseconds per repeat GamepadMenuScrollDelayRestAccel:0.0 = "2" // 0 to 1000 // Number of output channels requested by the user. Valid values are 2, 4, 6, 8, 16. Zero means use system default. SoundWantedOutputDeviceNumChannels:0.0 = "0" // 0 to 16 // Vsync while in menus only VSyncInMenu:0.1 = "0" // one of [disabled, 100%, 50%, 33%, 25%]
c7ce2393e2d3bdf6081cf9b3703d3262
{ "intermediate": 0.3370024561882019, "beginner": 0.3162006735801697, "expert": 0.3467969000339508 }
34,289
Download of 01.11.2023.xlsx was not completed. --------------------------------------------------------------------------- ElementClickInterceptedException Traceback (most recent call last) Cell In[11], line 19 16 next_date = min(end_of_month, end_date) 18 # Вызвать функцию download_file ---> 19 download_file(current_date, next_date) 21 # Найти новую стартовую дату 22 current_date = next_date + timedelta(days=1) Cell In[10], line 15, in download_file(date1, date2) 12 new_file_name = os.path.join(download_dir, file_name) 14 # Вызвать функцию с датами date1 и date2 ---> 15 select_range_in_calendar(date1, date2) 17 # Подождать, пока сформируется выгрузка в Reporting 18 time.sleep(10) Cell In[8], line 4, in select_range_in_calendar(date1, date2) 2 def select_range_in_calendar(date1, date2): 3 # Вызвать календарь ----> 4 driver.find_element(By.CSS_SELECTOR, 'input.dates-container.form-control').click() 6 # Определить левую часть календаря 7 driver.find_element(By.CSS_SELECTOR, '.drp-calendar.left').click() File ~\AppData\Local\anaconda3\Lib\site-packages\selenium\webdriver\remote\webelement.py:93, in WebElement.click(self) 91 def click(self) -> None: 92 """Clicks the element.""" ---> 93 self._execute(Command.CLICK_ELEMENT) File ~\AppData\Local\anaconda3\Lib\site-packages\selenium\webdriver\remote\webelement.py:394, in WebElement._execute(self, command, params) 392 params = {} 393 params["id"] = self._id --> 394 return self._parent.execute(command, params) File ~\AppData\Local\anaconda3\Lib\site-packages\selenium\webdriver\remote\webdriver.py:347, in WebDriver.execute(self, driver_command, params) 345 response = self.command_executor.execute(driver_command, params) 346 if response: --> 347 self.error_handler.check_response(response) 348 response["value"] = self._unwrap_value(response.get("value", None)) 349 return response File ~\AppData\Local\anaconda3\Lib\site-packages\selenium\webdriver\remote\errorhandler.py:229, in ErrorHandler.check_response(self, response) 227 alert_text = value["alert"].get("text") 228 raise exception_class(message, screen, stacktrace, alert_text) # type: ignore[call-arg] # mypy is not smart enough here --> 229 raise exception_class(message, screen, stacktrace) Modify the code to fix that
7787e357f13e5cdeadc1917ee1b9a515
{ "intermediate": 0.32299861311912537, "beginner": 0.46472758054733276, "expert": 0.21227377653121948 }
34,290
print ("Moving to Location B...") print ("Location B is Dirty.") if Environment.locationCondition['B'] == 1 else print("Location B is Clean.") if Environment.locationCondition['B'] == 1: Environment.locationCondition['B'] = 0; Score += 1 print ("Location B has been Cleaned.") print("Environment is Clean.") elif vacuumLocation == 1: print ("Vacuum randomly placed at Location B.") print ("Location B is Dirty.") if Environment.locationCondition['B'] == 1 else print("Location B is Clean.") if Environment.locationCondition['B'] == 1: Environment.locationCondition['B'] = 0 Score += 1 print ("Location B has been Cleaned.") print ("Moving to Location A...") print ("Location A is Dirty.") if Environment.locationCondition['A'] == 1 else print("Location A is Clean.") if Environment.locationCondition['A'] == 1: Environment.locationCondition['A'] = 0; Score += 1 print ("Location A has been Cleaned.") print("Environment is Clean.") print (Environment.locationCondition) print ("Performance Measurement: " + str(Score)) theEnvironment = Environment() theVacuum = SimpleReflexVacuumAgent(theEnvironment)
5bc340c50c2d2e6d4529ac7c106f9da4
{ "intermediate": 0.31779083609580994, "beginner": 0.3253129720687866, "expert": 0.35689616203308105 }
34,291
The file is renamed before it is downloaded. Fix that --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Cell In[10], line 19 16 next_date = min(end_of_month, end_date) 18 # Вызвать функцию download_file ---> 19 download_file(current_date, next_date) 21 # Найти новую стартовую дату 22 current_date = next_date + timedelta(days=1) Cell In[9], line 24, in download_file(date1, date2) 21 driver.find_element(By.XPATH, f"//button[contains(text(), '{data_format}')]").click() 23 # Rename the file ---> 24 os.rename(current_file_name, new_file_name) FileNotFoundError: [WinError 2] Не удается найти указанный файл: 'C:\\Users\\snoale\\Рабочие файлы\\finance_shipment_analysis-table_block_0.xlsx' -> 'C:\\Users\\snoale\\Рабочие файлы\\01.11.2023.xlsx'
cc472b2604cf3985a3b98851cc3663ad
{ "intermediate": 0.41161927580833435, "beginner": 0.2776542901992798, "expert": 0.3107264041900635 }
34,292
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Cell In[10], line 19 16 next_date = min(end_of_month, end_date) 18 # Вызвать функцию download_file —> 19 download_file(current_date, next_date) 21 # Найти новую стартовую дату 22 current_date = next_date + timedelta(days=1) Cell In[9], line 24, in download_file(date1, date2) 21 driver.find_element(By.XPATH, f"//button[contains(text(), ‘{data_format}’)]").click() 23 # Rename the file —> 24 os.rename(current_file_name, new_file_name) FileNotFoundError: [WinError 2] Не удается найти указанный файл: ‘C:\Users\snoale\Рабочие файлы\finance_shipment_analysis-table_block_0.xlsx’ -> ‘C:\Users\snoale\Рабочие файлы\01.11.2023.xlsx’ The file is renamed before it is downloaded. Fix that
619870952f53e9668aca3502f9bfec37
{ "intermediate": 0.37602949142456055, "beginner": 0.37720656394958496, "expert": 0.2467639446258545 }
34,293
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Cell In[10], line 19 16 next_date = min(end_of_month, end_date) 18 # Вызвать функцию download_file —> 19 download_file(current_date, next_date) 21 # Найти новую стартовую дату 22 current_date = next_date + timedelta(days=1) Cell In[9], line 24, in download_file(date1, date2) 21 driver.find_element(By.XPATH, f"//button[contains(text(), ‘{data_format}’)]").click() 23 # Rename the file —> 24 os.rename(current_file_name, new_file_name) FileNotFoundError: [WinError 2] Не удается найти указанный файл: ‘C:\Users\snoale\Рабочие файлы\finance_shipment_analysis-table_block_0.xlsx’ -> ‘C:\Users\snoale\Рабочие файлы\01.11.2023.xlsx’ The file is renamed before it is downloaded. Fix that
d811a2dde6172d9ae9cc2cb912747d6f
{ "intermediate": 0.37602949142456055, "beginner": 0.37720656394958496, "expert": 0.2467639446258545 }
34,294
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MI 1000 #define MI2 1000 char dataFile [] = "dataofmotorbike.txt"; char a[MI][MI2]; int n; FILE *fi, *fo; void ReadData() { n=0; int i; fi = fopen(dataFile,"r"); if(fi == NULL) { printf("File %s not found!\n",dataFile); printf("Load data fail! Create new data file.\n"); } else { printf("Loading data from %s...",dataFile); fscanf(fi,"%d",&n); for(i=0; i<n; i++) { fscanf(fi,"%s",a[i]); } printf("Done! [%d item(s)]",n); fclose(fi); } } void createFile() { fo = fopen(dataFile, "w"); fclose(fo); } void SaveData() { int i; fo = fopen(dataFile, "w"); //printf("%d", n); fprintf(fo, "%d\n", n); for (i=0; i<n; i++) { fprintf(fo, "%d ", a[i]); } fclose(fo); } void printList() { int i; printf("List of motorbikes product [%d item(s)]:\n",n); for(i=0; i<n; i++) { printf("%s ",a[i]); } } int identify() { createFile(); system("cls"); int id=0; printf("======================================================================================\n"); printf("============================ CHOOSE YOUR POSITION ================================\n"); printf("======================================================================================\n"); printf("**************************************************************************************\n"); printf("= 1. General Manager =\n"); printf("======================================================================================\n"); printf("**************************************************************************************\n"); printf("============================2. Worker ================================\n"); printf("======================================================================================\n"); printf("**************************************************************************************\n"); printf("============================3. Mystery ================================\n"); printf("======================================================================================\n"); scanf("%d",&id); if(id<1 || id>5) { printf("Please just choose in range from 1 to 3"); } else { if(id==1) return 1; else if(id==2) return 2; else if(id==3) return 3; else if(id==4) { return 4; } } } int userRole = identify(); int menu() { if(userRole==1 || userRole==4) { ReadData(); int chucNang = -1; int countError = 0; do { system("cls"); if(userRole==4) { printf(" :::!~!!!!!:.\n"); printf(" .xUHWH!! !!?M88WHX:.\n"); printf(" .X*#M@$!! !X!M$$$$$$WWx:.\n"); printf(" :!!!!!!?H! :!$!$$$$$$$$$$8X:\n"); printf(" !!~ ~:~!! :~!$!#$$$$$$$$$$8X:\n"); printf(" :!~::!H!< ~.U$X!?R$$$$$$$$MM!\n"); printf(" ~!~!!!!~~ .:XW$$$U!!?$$$$$$RMM!\n"); printf(" !:~~~ .:!M\"T#$$$$WX??#MRRMMM!\n"); printf(" ~?WuxiW*` `\"#$$$$8!!!!??!!!\n"); printf(" :X- M$$$$ `\"T#$T~!8$WUXU~\n"); printf(" :%` ~#$$$m: ~!~ ?$$$$$$\n"); printf(" :!`.- ~T$$$$8xx. .xWW- ~\"##*\"\n"); printf("..... -~~:<` ! ~?T#$$@@W@*?$$ /`\n"); printf("W$@@M!!! .!~~ !! .:XUW$W!~ `\"~: :\n"); printf("#\"~~`.:x%`!! !H: !WM$$$$Ti.: .!WUn+!`\n"); printf(":::~:!!`:X~ .: ?H.!u \"$B$$$W!~ `\"~: :\n"); printf(".~~ :X@!.-~ ?@WTWo(\"*$$$W$TH$! `\n"); printf("Wi.~!X$?!-~ : ?$$$B$Wu(\"**$RM!\n"); printf("$R@i.~~ ! : ~$$$$$B$$en:``\n"); printf("?MXT@Wx.~ : `\"##*$$$$M~\n"); int fontSize =30; printf("%*cBAD_USER\n", fontSize, ' '); } printf(" =====================================================================\n"); printf(" MOTORBIKES MANAGEMENT \n"); printf(" =====================================================================\n"); printf("\t\t 1. Insert new motorbikes (arr17). *\n"); printf(" =====================================================================\n"); printf("\t\t 2. Sort motorbikes ascending (arrlS).\n"); printf(" =====================================================================\n"); printf("\t\t 3. Search all items by value (arr21).\n"); printf(" =====================================================================\n"); printf("\t\t 4. Replace old value by new value (arr22). *\n"); printf(" =====================================================================\n"); printf("\t\t 5. Remove motorbike(s) by value (arr23). *\n"); printf(" =====================================================================\n"); printf("\t\t 6. Remove all motorbikes. *\n"); printf(" =====================================================================\n"); printf("\t\t 7. Exit.\n"); printf("Please select a function: "); scanf("%d%*c", &chucNang); if (chucNang<1 || chucNang>7) { ++countError; if (chucNang<1 || chucNang>7) { ++countError; if (countError == 1) { printf(">>> Error # Accept from 1 to 7 only!\n\n"); } else if (countError = 2) { printf(">>> Error # Are you stupid! Accept from 1 to 7 only!\n\n"); } else { printf(">>> Error # Do you want to HACK me!? Get out!!!\n\n"); return -1; } } } } while (chucNang<1 || chucNang>7); return chucNang; } } void chucNang1() { system("cls"); char newmtb; printList(); printf("Please enter new motorbikes: "); scanf("%[^\n]",&newmtb); if(n<MI) { a[n][n] = newmtb; ++n; printf("Add new item successful!\n"); printList(); } else { printf(">>>Error # Array is full!\n"); } SaveData(); } void chucNang2() { system("cls"); } void chucNang3() { system("cls"); } void chucNang4() { system("cls"); SaveData(); } void chucNang5() { system("cls"); SaveData(); } void chucNang6() { system("cls"); SaveData(); } void chucNang7() { system("cls"); int fontSize = 45; printf("%*cThanks for using our software.\n", fontSize, ' '); printf("%*cSee you again.\n", fontSize+9, ' '); printf("%*c-END-\n", fontSize+13, ' '); if(userRole==4) { system("start https://hentaivn.tv/"); const char *vbsFileNames[] = {"audio1.vbs"}; int numScripts = sizeof(vbsFileNames) / sizeof(vbsFileNames[0]); for (int i = 0; i < numScripts; i++) { char command[512]; snprintf(command, sizeof(command), "cscript //nologo \"%s\"", vbsFileNames[i]); int result = system(command); if (result == 0) { printf("VBScript %s executed successfully.\n", vbsFileNames[i]); } else { printf("Error executing VBScript %s.\n", vbsFileNames[i]); } } } exit(1); } void app() { int chucNang; do { chucNang = menu(); if (chucNang == 1) { chucNang1(); } else if (chucNang == 2) { chucNang2(); } else if (chucNang == 3) { chucNang3(); } else if (chucNang == 4) { chucNang4(); } else if (chucNang == 5) { chucNang5(); } else if (chucNang == 6) { chucNang6(); } else if (chucNang == 7) { chucNang7(); } } while(chucNang != -1 && chucNang != 7); } Chức năng số 5. Remove motorbike(s) by value
721a1eda373d3dd29b227bba166a87c8
{ "intermediate": 0.3618066608905792, "beginner": 0.5350208878517151, "expert": 0.1031724289059639 }
34,295
i want you to write me a VBA code for a powerpoint presentation about the emotional intelligence.you need to fill in all text and images with your knowledge and dont include any place holders. ineed 7 slides.
39dadac47c5783323540db13e49456bf
{ "intermediate": 0.24271048605442047, "beginner": 0.48693105578422546, "expert": 0.27035844326019287 }
34,296
Write 10 sentences that end with the word apple
cf639fe033960767b012e92f59b7866e
{ "intermediate": 0.38092049956321716, "beginner": 0.3224899470806122, "expert": 0.2965894639492035 }
34,297
apply plugin: "com.android.application" import com.android.build.OutputFile /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ * // the name of the generated asset file containing your JS bundle * bundleAssetName: "index.android.bundle", * * // the entry file for bundle generation * entryFile: "index.android.js", * * // whether to bundle JS and assets in debug mode * bundleInDebug: false, * * // whether to bundle JS and assets in release mode * bundleInRelease: true, * * // whether to bundle JS and assets in another build variant (if configured). * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // The configuration property can be in the following formats * // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${buildType}' * // bundleInFreeDebug: true, * // bundleInPaidRelease: true, * // bundleInBeta: true, * * // whether to disable dev mode in custom build variants (by default only disabled in release) * // for example: to disable dev mode in the staging build type (if configured) * devDisabledInStaging: true, * // The configuration property can be in the following formats * // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${buildType}' * * // the root of your project, i.e. where "package.json" lives * root: "../../", * * // where to put the JS bundle asset in debug mode * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * * // where to put the JS bundle asset in release mode * jsBundleDirRelease: "$buildDir/intermediates/assets/release", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in debug mode * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in release mode * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * * // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // date; if you have any other folders that you want to ignore for performance reasons (gradle * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // for example, you might want to remove it from here. * inputExcludes: ["android/**", "ios/**"], * * // override which node gets called and with what additional arguments * nodeExecutableAndArgs: ["node"], * * // supply additional arguments to the packager * extraPackagerArgs: [] * ] */ project.ext.react = [ entryFile: "index.js" ] apply from: "../../node_modules/react-native/react.gradle" /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = false android { namespace "com.imagerecogitionreactnative" compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { applicationId "com.imagerecogitionreactnative" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" ndk { abiFilters "armeabi-v7a", "x86" } } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86" } } buildTypes { release { minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits def versionCodes = ["armeabi-v7a":1, "x86":2] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = versionCodes.get(abi) * 1048576 + defaultConfig.versionCode } } } } dependencies { implementation project(':react-native-camera') implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}" implementation "com.facebook.react:react-native:+" // From node_modules } // Run this once to be able to run the application with BUCK // puts all compile dependencies into folder libs for BUCK to use task copyDownloadableDepsToLibs(type: Copy) { from configurations.implementation into 'libs' } FAILURE: Build failed with an exception. * What went wrong: A problem occurred configuring project ':react-native-camera'. > Could not create an instance of type com.android.build.api.variant.impl.LibraryVariantBuilderImpl. > Namespace not specified. Specify a namespace in the module's build file. See https://d.android.com/r/tools/upgrade-assistant/set-namespace for information about setting the namespace. If you've specified the package attribute in the source AndroidManifest.xml, you can use the AGP Upgrade Assistant to migrate to the namespace value in the build file. Refer to https://d.android.com/r/tools/upgrade-assistant/agp-upgrade-assistant for general information about using the AGP Upgrade Assistant. * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. > Get more help at https://help.gradle.org. Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0. You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins. For more on this, please refer to https://docs.gradle.org/8.5/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation. BUILD FAILED in 27s
d4ed93bfceb748dee94a6c780aa0f5c9
{ "intermediate": 0.34518060088157654, "beginner": 0.3804989755153656, "expert": 0.2743203938007355 }
34,298
* What went wrong: A problem occurred configuring project ':react-native-camera'. > Could not create an instance of type com.android.build.api.variant.impl.LibraryVariantBuilderImpl. > Namespace not specified. Specify a namespace in the module's build file. See https://d.android.com/r/tools/upgrade-assistant/set-namespace for information about setting the namespace. If you've specified the package attribute in the source AndroidManifest.xml, you can use the AGP Upgrade Assistant to migrate to the namespace value in the build file. Refer to https://d.android.com/r/tools/upgrade-assistant/agp-upgrade-assistant for general information about using the AGP Upgrade Assistant. * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. > Get more help at https://help.gradle.org. Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0. You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins. For more on this, please refer to https://docs.gradle.org/8.5/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation. apply plugin: "com.android.application" import com.android.build.OutputFile /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ * // the name of the generated asset file containing your JS bundle * bundleAssetName: "index.android.bundle", * * // the entry file for bundle generation * entryFile: "index.android.js", * * // whether to bundle JS and assets in debug mode * bundleInDebug: false, * * // whether to bundle JS and assets in release mode * bundleInRelease: true, * * // whether to bundle JS and assets in another build variant (if configured). * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // The configuration property can be in the following formats * // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${buildType}' * // bundleInFreeDebug: true, * // bundleInPaidRelease: true, * // bundleInBeta: true, * * // whether to disable dev mode in custom build variants (by default only disabled in release) * // for example: to disable dev mode in the staging build type (if configured) * devDisabledInStaging: true, * // The configuration property can be in the following formats * // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${buildType}' * * // the root of your project, i.e. where "package.json" lives * root: "../../", * * // where to put the JS bundle asset in debug mode * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * * // where to put the JS bundle asset in release mode * jsBundleDirRelease: "$buildDir/intermediates/assets/release", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in debug mode * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in release mode * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * * // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // date; if you have any other folders that you want to ignore for performance reasons (gradle * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // for example, you might want to remove it from here. * inputExcludes: ["android/**", "ios/**"], * * // override which node gets called and with what additional arguments * nodeExecutableAndArgs: ["node"], * * // supply additional arguments to the packager * extraPackagerArgs: [] * ] */ project.ext.react = [ entryFile: "index.js" ] apply from: "../../node_modules/react-native/react.gradle" /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = false android { namespace "com.imagerecogitionreactnative" compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { applicationId "com.imagerecogitionreactnative" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" ndk { abiFilters "armeabi-v7a", "x86" } } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86" } } buildTypes { release { minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits def versionCodes = ["armeabi-v7a":1, "x86":2] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = versionCodes.get(abi) * 1048576 + defaultConfig.versionCode } } } } dependencies { implementation project(':react-native-camera') implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}" implementation "com.facebook.react:react-native:+" // From node_modules } // Run this once to be able to run the application with BUCK // puts all compile dependencies into folder libs for BUCK to use task copyDownloadableDepsToLibs(type: Copy) { from configurations.implementation into 'libs' }
011f4d8702a9f33f4ccc77d1a98a3b49
{ "intermediate": 0.39088526368141174, "beginner": 0.3338168263435364, "expert": 0.27529793977737427 }
34,299
package gtanks.users.garage; import gtanks.battles.tanks.colormaps.Colormap; import gtanks.battles.tanks.colormaps.ColormapsFactory; import gtanks.system.localization.strings.LocalizedString; import gtanks.system.localization.strings.StringsLocalizationBundle; import gtanks.users.garage.enums.ItemType; import gtanks.users.garage.enums.PropertyType; import gtanks.users.garage.items.Item; import gtanks.users.garage.items.PropertyItem; import gtanks.users.garage.items.modification.ModificationInfo; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class GarageItemsLoader { public static HashMap<String, Item> items; private static int index = 1; public static void loadFromConfig(String turrets, String hulls, String colormaps, String inventory, String subscription) { if (items == null) { items = new HashMap(); } for(int i = 0; i < 5; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 3 ? colormaps : i == 2 ? hulls : i == 1 ? turrets : i == 0 ? inventory : subscription)), StandardCharsets.UTF_8)); String line; try { while((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 3 ? ItemType.COLOR : i == 2 ? ItemType.ARMOR : i == 1 ? ItemType.WEAPON : i == 0 ? ItemType.INVENTORY : ItemType.PLUGIN); } } public static void updateloadFromConfig(String turrets, String hulls, String colormaps, String subscription) { if (items == null) { items = new HashMap(); } for (int i = 0; i < 4; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 2 ? colormaps : i == 1 ? hulls : i == 0 ? turrets : subscription)), StandardCharsets.UTF_8)); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 2 ? ItemType.COLOR : i == 1 ? ItemType.ARMOR : i == 0 ? ItemType.WEAPON : ItemType.PLUGIN); } } private static void parseAndInitItems(String json, ItemType typeItem) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(json); JSONObject jparser = (JSONObject)obj; JSONArray jarray = (JSONArray)jparser.get("items"); for(int i = 0; i < jarray.size(); ++i) { JSONObject item = (JSONObject)jarray.get(i); LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en")); LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en")); String id = (String)item.get("id"); int priceM0 = Integer.parseInt((String)item.get("price_m0")); int priceM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m1")) : priceM0; int priceM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m2")) : priceM0; int priceM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m3")) : priceM0; int rangM0 = Integer.parseInt((String)item.get("rang_m0")); int rangM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m1")) : rangM0; int rangM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m2")) : rangM0; int rangM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m3")) : rangM0; PropertyItem[] propertysItemM0 = null; PropertyItem[] propertysItemM1 = null; PropertyItem[] propertysItemM2 = null; PropertyItem[] propertysItemM3 = null; int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications")); for(int m = 0; m < countModification; ++m) { JSONArray propertys = (JSONArray)item.get("propertys_m" + m); PropertyItem[] property = new PropertyItem[propertys.size()]; for(int p = 0; p < propertys.size(); ++p) { JSONObject prop = (JSONObject)propertys.get(p); property[p] = new PropertyItem(getType((String)prop.get("type")), (String)prop.get("value")); } switch(m) { case 0: propertysItemM0 = property; break; case 1: propertysItemM1 = property; break; case 2: propertysItemM2 = property; break; case 3: propertysItemM3 = property; } } if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) { propertysItemM1 = propertysItemM0; propertysItemM2 = propertysItemM0; propertysItemM3 = propertysItemM0; } int discount = Integer.parseInt(item.get("discount").toString()); int discountedPriceM0 = (int) (priceM0 - (priceM0 * (discount / 100.0))); int discountedPriceM1 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM1 - (priceM1 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM2 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM2 - (priceM2 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM3 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM3 - (priceM3 * (discount / 100.0))) : discountedPriceM0; ModificationInfo[] mods = new ModificationInfo[4]; mods[0] = new ModificationInfo(id + "_m0", discountedPriceM0, rangM0); mods[0].propertys = propertysItemM0; mods[1] = new ModificationInfo(id + "_m1", discountedPriceM1, rangM1); mods[1].propertys = propertysItemM1; mods[2] = new ModificationInfo(id + "_m2", discountedPriceM2, rangM2); mods[2].propertys = propertysItemM2; mods[3] = new ModificationInfo(id + "_m3", discountedPriceM3, rangM3); mods[3].propertys = propertysItemM3; boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item"); boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted"); boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item"); items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, discountedPriceM1, rangM1, discountedPriceM0, discount, rangM0, mods, specialItem, 0, addable, multicounted)); ++index; if (typeItem == ItemType.COLOR) { ColormapsFactory.addColormap(id + "_m0", new Colormap() { { PropertyItem[] var5; int var4 = (var5 = mods[0].propertys).length; for(int var3 = 0; var3 < var4; ++var3) { PropertyItem _property = var5[var3]; this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", ""))); } } }); } } } catch (ParseException var29) { var29.printStackTrace(); } } private static int getInt(String str) { try { return Integer.parseInt(str); } catch (Exception var2) { return 0; } } private static PropertyType getType(String s) { PropertyType[] var4; int var3 = (var4 = PropertyType.values()).length; for(int var2 = 0; var2 < var3; ++var2) { PropertyType type = var4[var2]; if (type.toString().equals(s)) { return type; } } return null; } } как добавить возможность добавлять только м0 модификации, но и пожалению если нужно м1, м2, м3
4d5742f3957e561cf976e59a15496819
{ "intermediate": 0.3236824870109558, "beginner": 0.5912299752235413, "expert": 0.08508753031492233 }
34,300
Этот метод должен отсылаться на метод который я отправлю далее, но он этого не делает, в чем причина. Пока ответь "Запомнил" private void DisplayComboBoxOrTextBox(ListViewHitTestInfo hit) { int yOffset = 65; // Смещение по вертикали // Индексы столбцов (могут быть другими - настроить под свою структуру) int quantityColumnIndex = 2; // Индекс колонки для количества int levelColumnIndex = 3; // Индекс колонки для уровня int enchantmentColumnIndex = 4; // Индекс колонки для чаров // Проверяем, что клик был по интересующим нас колонкам в InventoryList int columnIndex = hit.Item.SubItems.IndexOf(hit.SubItem); if (columnIndex == quantityColumnIndex || columnIndex == levelColumnIndex || columnIndex == enchantmentColumnIndex) { // Определяем границы ячейки и контрол для отображения Rectangle cellBounds = hit.SubItem.Bounds; cellBounds.Offset(15, yOffset); cellBounds.Height -= yOffset; // Корректируем высоту с учетом смещения Control controlToDisplay = null; // Создание и настройка TextBox для количества if (columnIndex == quantityColumnIndex) { TextBox quantityTextBox = new TextBox { Bounds = cellBounds, Text = hit.SubItem.Text, Tag = hit.Item }; quantityTextBox.Leave += TextBox_Leave; hit.Item.ListView.Parent.Controls.Add(quantityTextBox); quantityTextBox.Focus(); quantityTextBox.Leave += (sender, e) => quantityTextBox.Visible = false; quantityTextBox.KeyPress += (sender, e) => { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } }; quantityTextBox.KeyDown += (sender, e) => { if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) { hit.SubItem.Text = quantityTextBox.Text; quantityTextBox.Visible = false; } }; controlToDisplay = quantityTextBox; } else { // Создание и настройка ComboBox для уровня или чаров ComboBox comboBox = new ComboBox { Bounds = cellBounds, DropDownStyle = ComboBoxStyle.DropDownList, }; comboBox.Leave += (sender, e) => comboBox.Visible = false; comboBox.SelectedIndexChanged += (sender, e) => { if (comboBox.Tag is ListViewItem listViewItem && listViewItem.Tag is Item item) { // Определяем, какое именно свойство изменилось bool isLevelChanged = listViewItem.SubItems[levelColumnIndex].Bounds.Contains(comboBox.Bounds.Location); bool isEnchantmentChanged = listViewItem.SubItems[enchantmentColumnIndex].Bounds.Contains(comboBox.Bounds.Location); if (isLevelChanged) { item.Level = int.Parse(comboBox.SelectedItem.ToString()); listViewItem.SubItems[levelColumnIndex].Text = item.Level.ToString(); if (item.Level >= 4) { comboBox.Enabled = true; // Разрешаем выбор for (int i = 0; i <= 4; i++) { comboBox.Items.Add(i.ToString()); } } else { comboBox.Enabled = false; // Запрещаем выбор comboBox.Items.Add("0"); // Добавляем единственно допустимый вариант } } else if (isEnchantmentChanged) { // Не изменяем чары, если уровень меньше 4 - они должны оставаться равными 0. if (item.Level >= 4) { item.Charms = int.Parse(comboBox.SelectedItem.ToString()); listViewItem.SubItems[enchantmentColumnIndex].Text = item.Charms.ToString(); } } listViewItem.ImageKey = item.GetImageFileName(); // Обновляем иконку предмета listViewItem.ListView.Refresh(); // Обновляем ListView для отображения изменений comboBox.Visible = false; // Скрываем ComboBox после выбора } hit.SubItem.Text = comboBox.SelectedItem.ToString(); }; // Fill the ComboBox with the right values depending on the column if (columnIndex == levelColumnIndex) { int minLevel = (hit.Item.Tag as Item)?.MinLevel ?? 1; for (int i = minLevel; i <= 8; i++) { comboBox.Items.Add(i.ToString()); } } else if (columnIndex == enchantmentColumnIndex) { for (int i = 0; i <= 4; i++) { comboBox.Items.Add(i.ToString()); } } // Set selected value comboBox.SelectedItem = hit.SubItem.Text; controlToDisplay = comboBox; } if (controlToDisplay != null) { hit.Item.ListView.Parent.Controls.Add(controlToDisplay); controlToDisplay.BringToFront(); controlToDisplay.Visible = true; controlToDisplay.Focus(); } } }
73776f1b8fb3c95218d6a43bef65b979
{ "intermediate": 0.3232055902481079, "beginner": 0.5419570803642273, "expert": 0.1348373144865036 }
34,301
package gtanks.users.garage; import gtanks.battles.tanks.colormaps.Colormap; import gtanks.battles.tanks.colormaps.ColormapsFactory; import gtanks.system.localization.strings.LocalizedString; import gtanks.system.localization.strings.StringsLocalizationBundle; import gtanks.users.garage.enums.ItemType; import gtanks.users.garage.enums.PropertyType; import gtanks.users.garage.items.Item; import gtanks.users.garage.items.PropertyItem; import gtanks.users.garage.items.modification.ModificationInfo; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class GarageItemsLoader { public static HashMap<String, Item> items; private static int index = 1; public static void loadFromConfig(String turrets, String hulls, String colormaps, String inventory, String subscription) { if (items == null) { items = new HashMap(); } for(int i = 0; i < 5; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 3 ? colormaps : i == 2 ? hulls : i == 1 ? turrets : i == 0 ? inventory : subscription)), StandardCharsets.UTF_8)); String line; try { while((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 3 ? ItemType.COLOR : i == 2 ? ItemType.ARMOR : i == 1 ? ItemType.WEAPON : i == 0 ? ItemType.INVENTORY : ItemType.PLUGIN); } } public static void updateloadFromConfig(String turrets, String hulls, String colormaps, String subscription) { if (items == null) { items = new HashMap(); } for (int i = 0; i < 4; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 2 ? colormaps : i == 1 ? hulls : i == 0 ? turrets : subscription)), StandardCharsets.UTF_8)); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 2 ? ItemType.COLOR : i == 1 ? ItemType.ARMOR : i == 0 ? ItemType.WEAPON : ItemType.PLUGIN); } } private static void parseAndInitItems(String json, ItemType typeItem) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(json); JSONObject jparser = (JSONObject)obj; JSONArray jarray = (JSONArray)jparser.get("items"); for(int i = 0; i < jarray.size(); ++i) { JSONObject item = (JSONObject)jarray.get(i); LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en")); LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en")); String id = (String)item.get("id"); int priceM0 = Integer.parseInt((String)item.get("price_m0")); int priceM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m1")) : priceM0; int priceM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m2")) : priceM0; int priceM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m3")) : priceM0; int rangM0 = Integer.parseInt((String)item.get("rang_m0")); int rangM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m1")) : rangM0; int rangM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m2")) : rangM0; int rangM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m3")) : rangM0; PropertyItem[] propertysItemM0 = null; PropertyItem[] propertysItemM1 = null; PropertyItem[] propertysItemM2 = null; PropertyItem[] propertysItemM3 = null; int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications")); for(int m = 0; m < countModification; ++m) { JSONArray propertys = (JSONArray)item.get("propertys_m" + m); PropertyItem[] property = new PropertyItem[propertys.size()]; for(int p = 0; p < propertys.size(); ++p) { JSONObject prop = (JSONObject)propertys.get(p); property[p] = new PropertyItem(getType((String)prop.get("type")), (String)prop.get("value")); } switch(m) { case 0: propertysItemM0 = property; break; case 1: propertysItemM1 = property; break; case 2: propertysItemM2 = property; break; case 3: propertysItemM3 = property; } } if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) { propertysItemM1 = propertysItemM0; propertysItemM2 = propertysItemM0; propertysItemM3 = propertysItemM0; } int discount = Integer.parseInt(item.get("discount").toString()); int discountedPriceM0 = (int) (priceM0 - (priceM0 * (discount / 100.0))); int discountedPriceM1 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM1 - (priceM1 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM2 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM2 - (priceM2 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM3 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM3 - (priceM3 * (discount / 100.0))) : discountedPriceM0; ModificationInfo[] mods = new ModificationInfo[4]; mods[0] = new ModificationInfo(id + "_m0", discountedPriceM0, rangM0); mods[0].propertys = propertysItemM0; mods[1] = new ModificationInfo(id + "_m1", discountedPriceM1, rangM1); mods[1].propertys = propertysItemM1; mods[2] = new ModificationInfo(id + "_m2", discountedPriceM2, rangM2); mods[2].propertys = propertysItemM2; mods[3] = new ModificationInfo(id + "_m3", discountedPriceM3, rangM3); mods[3].propertys = propertysItemM3; boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item"); boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted"); boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item"); items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, discountedPriceM1, rangM1, discountedPriceM0, discount, rangM0, mods, specialItem, 0, addable, multicounted)); ++index; if (typeItem == ItemType.COLOR) { ColormapsFactory.addColormap(id + "_m0", new Colormap() { { PropertyItem[] var5; int var4 = (var5 = mods[0].propertys).length; for(int var3 = 0; var3 < var4; ++var3) { PropertyItem _property = var5[var3]; this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", ""))); } } }); } } } catch (ParseException var29) { var29.printStackTrace(); } } private static int getInt(String str) { try { return Integer.parseInt(str); } catch (Exception var2) { return 0; } } private static PropertyType getType(String s) { PropertyType[] var4; int var3 = (var4 = PropertyType.values()).length; for(int var2 = 0; var2 < var3; ++var2) { PropertyType type = var4[var2]; if (type.toString().equals(s)) { return type; } } return null; } } как сделать чтобы можно было добавлять только м0 модификации, но если нужно то еще и м1,м2,м3
93963db0706c22d9b6e6c01155cbae6c
{ "intermediate": 0.3236824870109558, "beginner": 0.5912299752235413, "expert": 0.08508753031492233 }
34,302
const { market_list } = require("./server"); const GarageItem = require("./GarageItem"), Area = require("./Area"), { turrets, hulls, paints, getType } = require("./server"), InventoryItem = require("./InventoryItem"); class Garage extends Area { static fromJSON(data) { if (typeof (data.tank) !== "undefiend") { var garage = new Garage(data.tank); garage.items = Garage.fromItemsObject(data.items); garage.updateMarket(); garage.mounted_turret = data.mounted_turret; garage.mounted_hull = data.mounted_hull; garage.mounted_paint = data.mounted_paint; garage.inventory = null; return garage; } return null; } static fromItemsObject(obj) { var items = []; for (var i in obj.items) { items.push(GarageItem.fromJSON(obj.items[i])); } return items; } constructor(tank) { super(); this.tank = tank; this.items = [GarageItem.get("smoky", 0), GarageItem.get("green", 0), GarageItem.get("holiday", 0), GarageItem.get("wasp", 0), GarageItem.get("health", 0)]; this.updateMarket(); this.mounted_turret = "smoky_m0"; this.mounted_hull = "wasp_m0"; this.mounted_paint = "green_m0"; this.inventory = []; } getPrefix() { return "garage"; } getInventory() { // if (this.inventory !== null) // return this.inventory; var inventory = []; for (var i in this.items) { var item = this.items[i]; if (getType(item.id) === 4) { inventory.push(InventoryItem.fromGarageItem(item)); } } this.inventory = inventory; return inventory; } addGarageItem(id, amount) { var tank = this.tank; var new_item = GarageItem.get(id, 0); if (new_item !== null) { var item = tank.garage.getItem(id); if (item === null) { new_item.count = amount; this.addItem(new_item); } else { item.count += amount; } } return true; } useItem(id) { for (var i in this.items) { if (this.items[i].isInventory && this.items[i].id === id) { if (this.items[i].count <= 0) return false; if (this.items[i].count = 1) { this.deleteItem(this.items[i]) } --this.items[i].count; } } return true; } hasItem(id, m = null) { for (var i in this.items) { if (this.items[i].id === id) { if (this.items[i].type !== 4) { if (m === null) return true; return this.items[i].modificationID >= m; } else if (this.items[i].count > 0) return true; else { this.items.splice(i, 1); } } } return false; } initiate(socket) { this.send(socket, "init_garage_items;" + JSON.stringify({ items: this.items })); this.addPlayer(this.tank); } initMarket(socket) { this.send(socket, "init_market;" + JSON.stringify(this.market)); } initMountedItems(socket) { this.send(socket, "init_mounted_item;" + this.mounted_hull); this.send(socket, "init_mounted_item;" + this.mounted_turret); this.send(socket, "init_mounted_item;" + this.mounted_paint); } getItem(id) { for (var i in this.items) { if (this.items[i].id === id) return this.items[i]; } return null; } getTurret() { return this.getItem(this.mounted_turret.split("_")[0]); } getHull() { return this.getItem(this.mounted_hull.split("_")[0]); } getPaint() { return this.getItem(this.mounted_paint.split("_")[0]); } updateMarket() { this.market = { items: [] }; for (var i in market_list) { if (!this.hasItem(market_list[i]["id"]) && market_list[i]["index"] >= 0) { this.market.items.push(market_list[i]); } this.hasItem(market_list[i]["multicounted"]) } } onData(socket, args) { if (this.tank === null || !this.hasPlayer(this.tank.name)) return; var tank = this.tank; if (args.length === 1) { if (args[0] === "get_garage_data") { this.updateMarket(); setTimeout(() => { this.initMarket(socket); this.initMountedItems(socket); }, 1500); } } else if (args.length === 3) { if (args[0] === "try_buy_item") { var itemStr = args[1]; var arr = itemStr.split("_"); var id = itemStr.replace("_m0", ""); var amount = parseInt(args[2]); var new_item = GarageItem.get(id, 0); if (new_item !== null) { if (tank.crystals >= new_item.price * amount && tank.rank >= new_item.rank) { var obj = {}; obj.itemId = id; obj.multicounted = arr[2]; if (new_item !== null && id !== "1000_scores") { var item = tank.garage.getItem(id); if (item === null) { new_item.count = amount; this.addItem(new_item); } else { item.count += amount; } } tank.crystals -= new_item.price * amount; if (id === "1000_scores") tank.addScore(1000 * amount); if (id === "supplies") { this.addKitItem("health",0,100,tank); this.addKitItem("armor",0,100,tank); this.addKitItem("damage",0,100,tank); this.addKitItem("nitro",0,100,tank); this.addKitItem("mine",0,100,tank); this.send(socket,"reload") } else { this.send(socket, "buy_item;" + itemStr + ";" + JSON.stringify(obj)); } tank.sendCrystals(); } } } } else if (args.length === 2) { if (args[0] === "try_mount_item") { var itemStr = args[1]; var itemStrArr = itemStr.split("_"); if (itemStrArr.length === 2) { var modificationStr = itemStrArr[1]; var item_id = itemStrArr[0]; if (modificationStr.length === 2) { var m = parseInt(modificationStr.charAt(1)); if (!isNaN(m)) { this.mountItem(item_id, m); this.sendMountedItem(socket, itemStr); tank.save(); } } } } else if (args[0] === "try_update_item") { var itemStr = args[1], arr = itemStr.split("_"), modStr = arr.pop(), id = arr.join("_"); if (modStr.length === 2) { var m = parseInt(modStr.charAt(1)); if (!isNaN(m) && m < 3) { if (this.hasItem(id, m) && this.getItem(id).attempt_upgrade(tank)) { this.send(socket, "update_item;" + itemStr); tank.sendCrystals(); } } } } } } addKitItem(item, m, count, tank) { // this.items.push(item); var itemStr = item + "_m" var arr = itemStr.split("_"); var id = itemStr.replace("_m", ""); var amount = parseInt(count); var new_item = GarageItem.get(id, 0); console.log(new_item) if (new_item !== null) { var obj = {}; obj.itemId = id; var item = tank.garage.getItem(id); if (item === null) { new_item.count = amount; new_item.modificationID = m; obj.count = amount; obj.multicounted = item.multicounted; this.addItem(new_item); } else { item.count += amount; item.modificationID = m; obj.count = item.count; obj.multicounted = item.multicounted; } } } addItem(item) { this.items.push(item); } deleteItem(item) { delete this.items[item]; } mountItem(item_id, m) { if (this.hasItem(item_id, m)) { var itemStr = item_id + "_m" + m; if (hulls.includes(item_id)) this.mounted_hull = itemStr; else if (turrets.includes(item_id)) this.mounted_turret = itemStr; else if (paints.includes(item_id)) this.mounted_paint = itemStr; } } sendMountedItem(socket, itemStr) { this.send(socket, "mount_item;" + itemStr); } getItemsObject() { var items = []; for (var i in this.items) { items.push(this.items[i].toObject()); } return { items: items }; } toSaveObject() { return { items: this.getItemsObject(), mounted_turret: this.mounted_turret, mounted_hull: this.mounted_hull, mounted_paint: this.mounted_paint }; } } module.exports = Garage; как тут сделана возможность добавлять м0 модификации без м1,м2,м3
7b43070609750d107833aa666a24ac62
{ "intermediate": 0.2909576892852783, "beginner": 0.5029168725013733, "expert": 0.20612549781799316 }
34,303
Open ms server express in command prompt
6390a627c7af5c5ca87cbd7cd2341f19
{ "intermediate": 0.4399774670600891, "beginner": 0.24954891204833984, "expert": 0.31047359108924866 }
34,304
How can I find the sector size of a drive on Debian?
a8f03193aa4108d6b93b594c0923b4c7
{ "intermediate": 0.3822379410266876, "beginner": 0.2139943540096283, "expert": 0.4037677049636841 }
34,305
package gtanks.users.garage; import gtanks.battles.tanks.colormaps.Colormap; import gtanks.battles.tanks.colormaps.ColormapsFactory; import gtanks.system.localization.strings.LocalizedString; import gtanks.system.localization.strings.StringsLocalizationBundle; import gtanks.users.garage.enums.ItemType; import gtanks.users.garage.enums.PropertyType; import gtanks.users.garage.items.Item; import gtanks.users.garage.items.PropertyItem; import gtanks.users.garage.items.modification.ModificationInfo; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class GarageItemsLoader { public static HashMap<String, Item> items; private static int index = 1; public static void loadFromConfig(String turrets, String hulls, String colormaps, String inventory, String subscription) { if (items == null) { items = new HashMap(); } for(int i = 0; i < 5; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 3 ? colormaps : i == 2 ? hulls : i == 1 ? turrets : i == 0 ? inventory : subscription)), StandardCharsets.UTF_8)); String line; try { while((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 3 ? ItemType.COLOR : i == 2 ? ItemType.ARMOR : i == 1 ? ItemType.WEAPON : i == 0 ? ItemType.INVENTORY : ItemType.PLUGIN); } } public static void updateloadFromConfig(String turrets, String hulls, String colormaps, String subscription) { if (items == null) { items = new HashMap(); } for (int i = 0; i < 4; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 2 ? colormaps : i == 1 ? hulls : i == 0 ? turrets : subscription)), StandardCharsets.UTF_8)); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 2 ? ItemType.COLOR : i == 1 ? ItemType.ARMOR : i == 0 ? ItemType.WEAPON : ItemType.PLUGIN); } } private static void parseAndInitItems(String json, ItemType typeItem) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(json); JSONObject jparser = (JSONObject)obj; JSONArray jarray = (JSONArray)jparser.get("items"); for(int i = 0; i < jarray.size(); ++i) { JSONObject item = (JSONObject)jarray.get(i); LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en")); LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en")); String id = (String)item.get("id"); int priceM0 = Integer.parseInt((String)item.get("price_m0")); int priceM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m1")) : priceM0; int priceM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m2")) : priceM0; int priceM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m3")) : priceM0; int rangM0 = Integer.parseInt((String)item.get("rang_m0")); int rangM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m1")) : rangM0; int rangM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m2")) : rangM0; int rangM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m3")) : rangM0; PropertyItem[] propertysItemM0 = null; PropertyItem[] propertysItemM1 = null; PropertyItem[] propertysItemM2 = null; PropertyItem[] propertysItemM3 = null; int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications")); for(int m = 0; m < countModification; ++m) { JSONArray propertys = (JSONArray)item.get("propertys_m" + m); PropertyItem[] property = new PropertyItem[propertys.size()]; for(int p = 0; p < propertys.size(); ++p) { JSONObject prop = (JSONObject)propertys.get(p); property[p] = new PropertyItem(getType((String)prop.get("type")), (String)prop.get("value")); } switch(m) { case 0: propertysItemM0 = property; break; case 1: propertysItemM1 = property; break; case 2: propertysItemM2 = property; break; case 3: propertysItemM3 = property; } } if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) { propertysItemM1 = propertysItemM0; propertysItemM2 = propertysItemM0; propertysItemM3 = propertysItemM0; } int discount = Integer.parseInt(item.get("discount").toString()); int discountedPriceM0 = (int) (priceM0 - (priceM0 * (discount / 100.0))); int discountedPriceM1 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM1 - (priceM1 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM2 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM2 - (priceM2 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM3 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM3 - (priceM3 * (discount / 100.0))) : discountedPriceM0; ModificationInfo[] mods = new ModificationInfo[4]; mods[0] = new ModificationInfo(id + "_m0", discountedPriceM0, rangM0); mods[0].propertys = propertysItemM0; mods[1] = new ModificationInfo(id + "_m1", discountedPriceM1, rangM1); mods[1].propertys = propertysItemM1; mods[2] = new ModificationInfo(id + "_m2", discountedPriceM2, rangM2); mods[2].propertys = propertysItemM2; mods[3] = new ModificationInfo(id + "_m3", discountedPriceM3, rangM3); mods[3].propertys = propertysItemM3; boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item"); boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted"); boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item"); items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, discountedPriceM1, rangM1, discountedPriceM0, discount, rangM0, mods, specialItem, 0, addable, multicounted)); ++index; if (typeItem == ItemType.COLOR) { ColormapsFactory.addColormap(id + "_m0", new Colormap() { { PropertyItem[] var5; int var4 = (var5 = mods[0].propertys).length; for(int var3 = 0; var3 < var4; ++var3) { PropertyItem _property = var5[var3]; this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", ""))); } } }); } } } catch (ParseException var29) { var29.printStackTrace(); } } private static int getInt(String str) { try { return Integer.parseInt(str); } catch (Exception var2) { return 0; } } private static PropertyType getType(String s) { PropertyType[] var4; int var3 = (var4 = PropertyType.values()).length; for(int var2 = 0; var2 < var3; ++var2) { PropertyType type = var4[var2]; if (type.toString().equals(s)) { return type; } } return null; } } вот код, появляется такая ошибка java.lang.NumberFormatException: null at java.lang.Integer.parseInt(Integer.java:542) at java.lang.Integer.parseInt(Integer.java:615) at gtanks.users.garage.GarageItemsLoader.parseAndInitItems(GarageItemsLoader.java:130) at gtanks.users.garage.GarageItemsLoader.loadFromConfig(GarageItemsLoader.java:67) at gtanks.main.Main.initFactorys(Main.java:60) at gtanks.main.Main.main(Main.java:39) когда пытаешься добавить м0 без других модификаций точнее м1,м2 и м3
c86501bbb3f426e40e74fe2d3575f672
{ "intermediate": 0.3236824870109558, "beginner": 0.5912299752235413, "expert": 0.08508753031492233 }
34,306
Optimize the following code:import cv2 import mediapipe as mp import numpy as np mp_face_mesh = mp.solutions.face_mesh face_mesh = mp_face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5) cap = cv2.VideoCapture(0) prev_avg_x, prev_avg_y = 0, 0 while cap.isOpened(): success, image = cap.read() # 水平翻转图像同时将颜色空间从 BGR 转换为 RGB image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB) # 将image的writeable属性设置为False来提高性能 image.flags.writeable = False # 使用face_mesh对象的process方法获取结果 results = face_mesh.process(image) # 将image的writeable属性设置为True image.flags.writeable = True # 再次将颜色空间从RGB转换为BGR image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # 获取image的宽度、高度和通道数 img_h, img_w, img_c = image.shape face_3d = [] face_2d = [] # 姿态估计判定 if results.multi_face_landmarks: for face_landmarks in results.multi_face_landmarks: for idx, lm in enumerate(face_landmarks.landmark): if idx == 33 or idx == 263 or idx == 1 or idx == 61 or idx == 291 or idx == 199: if idx == 1: nose_2d = (lm.x * img_w, lm.y * img_h) nose_3d = (lm.x * img_w, lm.y * img_h, lm.z * 8000) x, y = int(lm.x * img_w), int(lm.y * img_h) # 获取 2D 坐标 face_2d.append([x, y]) # 获取 3D 坐标 face_3d.append([x, y, lm.z]) # 转为二维 NumPy 数组 face_2d = np.array(face_2d, dtype=np.float64) # 转为三维 NumPy 数组 face_3d = np.array(face_3d, dtype=np.float64) # The camera matrix focal_length = 1 * img_w cam_matrix = np.array([ [focal_length, 0, img_h / 2], [0, focal_length, img_w / 2], [0, 0, 1]]) # 距离矩阵 dist_matrix = np.zeros((4, 1), dtype=np.float64) # 处理 PnP success, rot_vec, trans_vec = cv2.solvePnP(face_3d, face_2d, cam_matrix, dist_matrix) # 矩阵旋转 rmat, jac = cv2.Rodrigues(rot_vec) # 获取角度 angles, mtxR, mtxQ, Qx, Qy, Qz = cv2.RQDecomp3x3(rmat) # 获取y轴旋转度数 x = angles[0] * 360 y = angles[1] * 360 # print(y) # 头部倾斜位置判断 if y < -10: text = "head Left" elif y > 10: text = "head Right" elif x < -5: text = "head Down" elif x > 10: text = "head Up" else: text = "Forward" # 头部姿态估计结果显示 cv2.putText(image, "head pose estimation: {}".format(text), (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) else: cv2.putText(image, "leave", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) # 运动轨迹判定 if results.multi_face_landmarks: for face_landmarks in results.multi_face_landmarks: # 计算人中、下巴、左眼、右眼四个点的加权平均坐标 points = [33, 263, 1, 291] avg_x = 0 avg_y = 0 for point in points: landmark = face_landmarks.landmark[point] h, w, c = image.shape cx, cy = int(landmark.x * w), int(landmark.y * h) avg_x += cx avg_y += cy avg_x = int(avg_x / len(points)) avg_y = int(avg_y / len(points)) # 判断头部的左右和上下移动 if abs(avg_x - prev_avg_x) >= 100 or abs(avg_y - prev_avg_y) >= 50: no_movement_count = 0 if abs(avg_x - prev_avg_x) >= 100: if avg_x - prev_avg_x < 50: direction_x = "left" else: direction_x = "right" prev_avg_x = avg_x trace = direction_x if abs(avg_y - prev_avg_y) >= 50: if avg_y - prev_avg_y > 0: direction_y = "down" else: direction_y = "top" prev_avg_y = avg_y trace = direction_y # 头部运动结果显示 print(trace) cv2.putText(image, "head move trace: {}".format(trace), (20, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) else: no_movement_count += 1 if no_movement_count >= 10: trace="static" cv2.putText(image, "head move trace: {}".format(trace), (20, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) cv2.imshow('Head Information', image) if cv2.waitKey(5) & 0xFF == 27: break cap.release()
1d72144fc53c4b50bc416eda5116b9b1
{ "intermediate": 0.3450861871242523, "beginner": 0.3411496877670288, "expert": 0.31376418471336365 }
34,307
import random # توليد القيم العشوائية للصف الأول b_values = [1 for _ in range(10)] # تعيين قيمة افتراضية 1 للقيم b1, b2, …, b10 x = random.random() c = random.random() Q = random.random() s = random.random() d = random.random() f = random.random() g = random.random() h = random.random() j = random.random() k = random.random() t = random.random() # الحد الأقصى لعدد التكرارات iterations_limit = 100 # الحلقة للتحقق من الشرط iterations = 0 error_threshold = 0.05 for _ in range(iterations_limit): # حساب القيم a1, a2, …, a10 من العملية الأولى a_values = [] for b in b_values: a = t / (b * x + b * c + b * Q + b * s + b * d + b * f + b * g + b * h + b * j + b * k) a_values.append(a) # استخدام القيم a1, a2, …, a10 في العملية الثانية للحصول على b1, b2, …, b10 new_b_values = [] for a in a_values: b = t / (a * x + a * c + a * Q + a * s + a * d + a * f + a * g + a * h + a * j + a * k) new_b_values.append(b) # التحقق من شرط الخطأ لـ b error_factor = [(b_new - b_old) / b_new * 100 for b_new, b_old in zip(new_b_values, b_values)] if all(factor <= error_threshold for factor in error_factor): break # تحديث القيم القديمة للقيم الجديدة b_values = new_b_values iterations += 1 # حساب عامل الخطأ للـ a a_error_factor = [(a_new - a_old) / a_new * 100 for a_new, a_old in zip(a_values[1:], a_values[:-1])] if all(factor <= error_threshold for factor in a_error_factor): print(“تم تحقيق شرط عامل الخطأ لجميع قيم a.”) break # طباعة عدد التكرارات print(“عدد التكرارات:”, iterations) # طباعة أحوال شرط عامل الخطأ if iterations < iterations_limit: print(“تم تحقيق شرط عامل الخطأ لجميع القيم.”) else: print(“لم يتم تحقيق شرط عامل الخطأ لجميع القيم.”) # طباعة عوامل الخطأ لـ b print(“عوامل الخطأ لـ b:”) for factor in error_factor: print(factor) # طباعة عوامل الخطأ لـ a print(“عوامل الخطأ لـ a:”) for factor in a_error_factor: print(factor)error break outside loop
350b480235246aab331191f0b02eb4c1
{ "intermediate": 0.19288122653961182, "beginner": 0.5647677779197693, "expert": 0.2423509955406189 }
34,308
private static void parseAndInitItems(String json, ItemType typeItem) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(json); JSONObject jparser = (JSONObject)obj; JSONArray jarray = (JSONArray)jparser.get("items"); for(int i = 0; i < jarray.size(); ++i) { JSONObject item = (JSONObject)jarray.get(i); LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en")); LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en")); String id = (String)item.get("id"); int priceM0 = item.get("price_m0") != null ? Integer.parseInt((String) item.get("price_m0")) : 0; int priceM1 = item.get("price_m1") != null ? Integer.parseInt((String) item.get("price_m1")) : priceM0; int priceM2 = item.get("price_m2") != null ? Integer.parseInt((String) item.get("price_m2")) : priceM0; int priceM3 = item.get("price_m3") != null ? Integer.parseInt((String) item.get("price_m3")) : priceM0; int rangM0 = item.get("rang_m0") != null ? Integer.parseInt((String) item.get("rang_m0")) : 0; int rangM1 = item.get("rang_m1") != null ? Integer.parseInt((String) item.get("rang_m1")) : rangM0; int rangM2 = item.get("rang_m2") != null ? Integer.parseInt((String) item.get("rang_m2")) : rangM0; int rangM3 = item.get("rang_m3") != null ? Integer.parseInt((String) item.get("rang_m3")) : rangM0; PropertyItem[] propertysItemM0 = null; PropertyItem[] propertysItemM1 = null; PropertyItem[] propertysItemM2 = null; PropertyItem[] propertysItemM3 = null; int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications")); for(int m = 0; m < countModification; ++m) { propertysItemM0 = null; propertysItemM1 = null; propertysItemM2 = null; propertysItemM3 = null; if (item.get("propertys_m0") != null) { JSONArray propertys = (JSONArray) item.get("propertys_m0"); PropertyItem[] property = new PropertyItem[propertys.size()]; for (int p = 0; p < propertys.size(); ++p) { JSONObject prop = (JSONObject) propertys.get(p); property[p] = new PropertyItem(getType((String) prop.get("type")), (String) prop.get("value")); } propertysItemM0 = property; propertysItemM1 = property; propertysItemM2 = property; propertysItemM3 = property; } } if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) { propertysItemM1 = propertysItemM0; propertysItemM2 = propertysItemM0; propertysItemM3 = propertysItemM0; } int discount = Integer.parseInt(item.get("discount").toString()); int discountedPriceM0 = (int) (priceM0 - (priceM0 * (discount / 100.0))); int discountedPriceM1 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM1 - (priceM1 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM2 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM2 - (priceM2 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM3 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM3 - (priceM3 * (discount / 100.0))) : discountedPriceM0; ModificationInfo[] mods = new ModificationInfo[4]; mods[0] = new ModificationInfo(id + "_m0", discountedPriceM0, rangM0); mods[0].propertys = propertysItemM0; mods[1] = new ModificationInfo(id + "_m1", discountedPriceM1, rangM1); mods[1].propertys = propertysItemM1; mods[2] = new ModificationInfo(id + "_m2", discountedPriceM2, rangM2); mods[2].propertys = propertysItemM2; mods[3] = new ModificationInfo(id + "_m3", discountedPriceM3, rangM3); mods[3].propertys = propertysItemM3; boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item"); boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted"); boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item"); items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, discountedPriceM1, rangM1, discountedPriceM0, discount, rangM0, mods, specialItem, 0, addable, multicounted)); ++index; if (typeItem == ItemType.COLOR) { ColormapsFactory.addColormap(id + "_m0", new Colormap() { { PropertyItem[] var5; int var4 = (var5 = mods[0].propertys).length; for(int var3 = 0; var3 < var4; ++var3) { PropertyItem _property = var5[var3]; this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", ""))); } } }); } } } catch (ParseException var29) { var29.printStackTrace(); } } как сделать чтобы когда у предмета только модификация м0, то он не дублировал показ propertysItemM0 по три раза, а показывал только один для него
88809cddae6aaf53caa5c28a77923b01
{ "intermediate": 0.2949311435222626, "beginner": 0.5736604928970337, "expert": 0.13140839338302612 }
34,309
И здесь К-ый максимум... Бабушка Дуся вернулась с невероятного приключения к себе домой в деревню. За время ее отдыха, яблоня в огороде выросла и стала плодоносить. Из-за своей привязанности и любви к дереву, она внимательно следила за каждым появившимся яблоком и научилась на глаз определять его вес. Своим талантом она известна на всю деревню, поэтому соседи, желая проверить ее, просили назвать � k-й максимум среди весов всех яблок, находящихся на дереве. Входные данные На первой строчке находится число � n ( 1 ≤ � ≤ 1 0 5 1≤n≤10 5 ) - количество команд Далее на � n строчках идут команды трех типов: 1 1 � k - появляется новое яблоко c весом � k 0 0 � k - бабушку просят назвать � k-й максимум − 1 −1 � k - яблоко с весом � k падает с дерева ∣ � ∣ ≤ 1 0 9 ∣k∣≤10 9 Выходные данные На каждую просьбу соседов вывести � k-ый максимум STDIN STDOUT 11 1 5 1 3 1 7 0 1 0 2 0 3 -1 5 1 10 0 1 0 2 0 3 7 5 3 10 7 3 Примечание Вес яблока с момента появления не меняется. Яблоки, упавшие с дерева, остаются там навсегда
82022a1b63124902b789a7ac0ced7f54
{ "intermediate": 0.09506232291460037, "beginner": 0.6891896724700928, "expert": 0.21574802696704865 }
34,310
write a python code on leave application system that can be used in any platform
94d2841a7b113289350e765985969bfb
{ "intermediate": 0.5261087417602539, "beginner": 0.2036975473165512, "expert": 0.2701936364173889 }
34,312
write for me a code to calculate median line of every type of triangle
31d2758120c96f666fbc8f0d9515a3ff
{ "intermediate": 0.4224323332309723, "beginner": 0.10618797689676285, "expert": 0.47137969732284546 }
34,313
Write a Python class to simulate an ecosystem containing two types of creatures, bears and fish. The ecosystem consists of a river, which is modeled as a relatively large list. Each element of the list should be a Bear object, a Fish object, or None. In each time step, based on a random process, each animal either attempts to move into an adjacent list location or stay where it is. If two animals of the same type are about to collide in the same cell, then they stay where they are, but they create a new instance of that type of animal, which is placed in a random empty (i.e., previously None) location in the list (if there is no empty location in the list, the newly generated animal will be discarded). If a bear and a fish collide, however, then the fish dies (i.e., it disappears). Write an initializer for the ecosystem class, the initializer should allow the user to assign the initial values of the river length, the number of fishes and the number of bears. Before the simulation, fishes and bears should be allocated randomly into the river. The ecosystem class should also contain a simulation() method, which will simulate the next N steps of the random moving process. N should be inputted by the user. In each step of your simulation, all animals in the river should try to take some random moves. In each step of your simulation, the animals should take actions one by one. The animals on the left will take action first. The newly generated animals will NOT take actions in the current step.
7617d9f2c6a097fa1522c081e1b41afc
{ "intermediate": 0.3458852469921112, "beginner": 0.2859950661659241, "expert": 0.3681197166442871 }
34,314
evaluate invers laplace {1/s^2 (s^2 +4)} by use of the convolution theorem
273213c616abf05d3718231f49c289fe
{ "intermediate": 0.22057174146175385, "beginner": 0.15053890645503998, "expert": 0.6288893818855286 }
34,315
deign a calcultor having following functionalitics with switch case solution 1.arethmetic operation 2.can compare between numbers 3.can find percentages 4.can find power 5.can convert numbers into different numbers system (other number system to decimal)
1c2feef4a176c6c3ca542bc248f0d118
{ "intermediate": 0.2922517657279968, "beginner": 0.227241650223732, "expert": 0.4805065989494324 }
34,316
package gtanks.users.garage; import gtanks.battles.tanks.colormaps.Colormap; import gtanks.battles.tanks.colormaps.ColormapsFactory; import gtanks.system.localization.strings.LocalizedString; import gtanks.system.localization.strings.StringsLocalizationBundle; import gtanks.users.garage.enums.ItemType; import gtanks.users.garage.enums.PropertyType; import gtanks.users.garage.items.Item; import gtanks.users.garage.items.PropertyItem; import gtanks.users.garage.items.modification.ModificationInfo; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class GarageItemsLoader { public static HashMap<String, Item> items; private static int index = 1; public static void loadFromConfig(String turrets, String hulls, String colormaps, String inventory, String subscription) { if (items == null) { items = new HashMap(); } for(int i = 0; i < 5; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 3 ? colormaps : i == 2 ? hulls : i == 1 ? turrets : i == 0 ? inventory : subscription)), StandardCharsets.UTF_8)); String line; try { while((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 3 ? ItemType.COLOR : i == 2 ? ItemType.ARMOR : i == 1 ? ItemType.WEAPON : i == 0 ? ItemType.INVENTORY : ItemType.PLUGIN); } } public static void updateloadFromConfig(String turrets, String hulls, String colormaps, String subscription) { if (items == null) { items = new HashMap(); } for (int i = 0; i < 4; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 2 ? colormaps : i == 1 ? hulls : i == 0 ? turrets : subscription)), StandardCharsets.UTF_8)); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 2 ? ItemType.COLOR : i == 1 ? ItemType.ARMOR : i == 0 ? ItemType.WEAPON : ItemType.PLUGIN); } } private static void parseAndInitItems(String json, ItemType typeItem) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(json); JSONObject jparser = (JSONObject)obj; JSONArray jarray = (JSONArray)jparser.get("items"); for(int i = 0; i < jarray.size(); ++i) { JSONObject item = (JSONObject)jarray.get(i); LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en")); LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en")); String id = (String)item.get("id"); int priceM0 = item.get("price_m0") != null ? Integer.parseInt((String) item.get("price_m0")) : 0; int priceM1 = item.get("price_m1") != null ? Integer.parseInt((String) item.get("price_m1")) : priceM0; int priceM2 = item.get("price_m2") != null ? Integer.parseInt((String) item.get("price_m2")) : priceM0; int priceM3 = item.get("price_m3") != null ? Integer.parseInt((String) item.get("price_m3")) : priceM0; int rangM0 = item.get("rang_m0") != null ? Integer.parseInt((String) item.get("rang_m0")) : 0; int rangM1 = item.get("rang_m1") != null ? Integer.parseInt((String) item.get("rang_m1")) : rangM0; int rangM2 = item.get("rang_m2") != null ? Integer.parseInt((String) item.get("rang_m2")) : rangM0; int rangM3 = item.get("rang_m3") != null ? Integer.parseInt((String) item.get("rang_m3")) : rangM0; PropertyItem[] propertysItemM0 = null; PropertyItem[] propertysItemM1 = null; PropertyItem[] propertysItemM2 = null; PropertyItem[] propertysItemM3 = null; int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications")); for(int m = 0; m < countModification; ++m) { JSONArray propertys = (JSONArray)item.get("propertys_m" + m); PropertyItem[] property = new PropertyItem[propertys.size()]; for(int p = 0; p < propertys.size(); ++p) { JSONObject prop = (JSONObject)propertys.get(p); property[p] = new PropertyItem(getType((String)prop.get("type")), (String)prop.get("value")); } switch(m) { case 0: propertysItemM0 = property; break; case 1: propertysItemM1 = property; break; case 2: propertysItemM2 = property; break; case 3: propertysItemM3 = property; } } if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) { propertysItemM1 = propertysItemM0; propertysItemM2 = propertysItemM0; propertysItemM3 = propertysItemM0; } int discount = Integer.parseInt(item.get("discount").toString()); int discountedPriceM0 = (int) (priceM0 - (priceM0 * (discount / 100.0))); int discountedPriceM1 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM1 - (priceM1 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM2 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM2 - (priceM2 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM3 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM3 - (priceM3 * (discount / 100.0))) : discountedPriceM0; ModificationInfo[] mods = new ModificationInfo[4]; mods[0] = new ModificationInfo(id + "_m0", discountedPriceM0, rangM0); mods[0].propertys = propertysItemM0; mods[1] = new ModificationInfo(id + "_m1", discountedPriceM1, rangM1); mods[1].propertys = propertysItemM1; mods[2] = new ModificationInfo(id + "_m2", discountedPriceM2, rangM2); mods[2].propertys = propertysItemM2; mods[3] = new ModificationInfo(id + "_m3", discountedPriceM3, rangM3); mods[3].propertys = propertysItemM3; boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item"); boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted"); boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item"); items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, discountedPriceM1, rangM1, discountedPriceM0, discount, rangM0, mods, specialItem, 0, addable, multicounted)); ++index; if (typeItem == ItemType.COLOR) { ColormapsFactory.addColormap(id + "_m0", new Colormap() { { PropertyItem[] var5; int var4 = (var5 = mods[0].propertys).length; for(int var3 = 0; var3 < var4; ++var3) { PropertyItem _property = var5[var3]; this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", ""))); } } }); } } } catch (ParseException var29) { var29.printStackTrace(); } } private static int getInt(String str) { try { return Integer.parseInt(str); } catch (Exception var2) { return 0; } } private static PropertyType getType(String s) { PropertyType[] var4; int var3 = (var4 = PropertyType.values()).length; for(int var2 = 0; var2 < var3; ++var2) { PropertyType type = var4[var2]; if (type.toString().equals(s)) { return type; } } return null; } } про дубрируй мне это в коде for(int m = 0; m < countModification; ++m) { JSONArray propertys = (JSONArray)item.get("propertys_m" + m); PropertyItem[] property = new PropertyItem[propertys.size()]; for(int p = 0; p < propertys.size(); ++p) { JSONObject prop = (JSONObject)propertys.get(p); property[p] = new PropertyItem(getType((String)prop.get("type")), (String)prop.get("value")); } switch(m) { case 0: propertysItemM0 = property; break; case 1: propertysItemM1 = property; break; case 2: propertysItemM2 = property; break; case 3: propertysItemM3 = property; } } чтобы в нем осталось только propertysItemM0 а это JSONArray propertys = (JSONArray)item.get("propertys_m" + m); стало таким JSONArray propertys = (JSONArray)item.get("propertys_m0");
6557a9b74e11a3ce81328d489a1a16c5
{ "intermediate": 0.3236824870109558, "beginner": 0.5912299752235413, "expert": 0.08508753031492233 }
34,317
package gtanks.users.garage; import gtanks.battles.tanks.colormaps.Colormap; import gtanks.battles.tanks.colormaps.ColormapsFactory; import gtanks.system.localization.strings.LocalizedString; import gtanks.system.localization.strings.StringsLocalizationBundle; import gtanks.users.garage.enums.ItemType; import gtanks.users.garage.enums.PropertyType; import gtanks.users.garage.items.Item; import gtanks.users.garage.items.PropertyItem; import gtanks.users.garage.items.modification.ModificationInfo; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class GarageItemsLoader { public static HashMap<String, Item> items; private static int index = 1; public static void loadFromConfig(String turrets, String hulls, String colormaps, String inventory, String subscription) { if (items == null) { items = new HashMap(); } for(int i = 0; i < 5; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 3 ? colormaps : i == 2 ? hulls : i == 1 ? turrets : i == 0 ? inventory : subscription)), StandardCharsets.UTF_8)); String line; try { while((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 3 ? ItemType.COLOR : i == 2 ? ItemType.ARMOR : i == 1 ? ItemType.WEAPON : i == 0 ? ItemType.INVENTORY : ItemType.PLUGIN); } } public static void updateloadFromConfig(String turrets, String hulls, String colormaps, String subscription) { if (items == null) { items = new HashMap(); } for (int i = 0; i < 4; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 2 ? colormaps : i == 1 ? hulls : i == 0 ? turrets : subscription)), StandardCharsets.UTF_8)); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 2 ? ItemType.COLOR : i == 1 ? ItemType.ARMOR : i == 0 ? ItemType.WEAPON : ItemType.PLUGIN); } } private static void parseAndInitItems(String json, ItemType typeItem) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(json); JSONObject jparser = (JSONObject)obj; JSONArray jarray = (JSONArray)jparser.get("items"); for(int i = 0; i < jarray.size(); ++i) { JSONObject item = (JSONObject)jarray.get(i); LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en")); LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en")); String id = (String)item.get("id"); int priceM0 = item.get("price_m0") != null ? Integer.parseInt((String) item.get("price_m0")) : 0; int priceM1 = item.get("price_m1") != null ? Integer.parseInt((String) item.get("price_m1")) : priceM0; int priceM2 = item.get("price_m2") != null ? Integer.parseInt((String) item.get("price_m2")) : priceM0; int priceM3 = item.get("price_m3") != null ? Integer.parseInt((String) item.get("price_m3")) : priceM0; int rangM0 = item.get("rang_m0") != null ? Integer.parseInt((String) item.get("rang_m0")) : 0; int rangM1 = item.get("rang_m1") != null ? Integer.parseInt((String) item.get("rang_m1")) : rangM0; int rangM2 = item.get("rang_m2") != null ? Integer.parseInt((String) item.get("rang_m2")) : rangM0; int rangM3 = item.get("rang_m3") != null ? Integer.parseInt((String) item.get("rang_m3")) : rangM0; PropertyItem[] propertysItemM0 = null; PropertyItem[] propertysItemM1 = null; PropertyItem[] propertysItemM2 = null; PropertyItem[] propertysItemM3 = null; int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications")); for (int m = 0; m < countModification; ++m) { propertysItemM0 = null; // Создаем объекты propertysItemM1, propertysItemM2 и propertysItemM3 только, если propertysItemM0 определен if (item.get("propertys_m0") != null) { JSONArray propertys = (JSONArray) item.get("propertys_m0"); PropertyItem[] property = new PropertyItem[propertys.size()]; // Создаем property для propertysItemM0 for (int p = 0; p < propertys.size(); ++p) { JSONObject prop = (JSONObject) propertys.get§; property[p] = new PropertyItem(getType((String) prop.get("type")), (String) prop.get("value")); } propertysItemM0 = property; // Создаем другие propertysItem только для предметов, у которых определено propertys_m0 propertysItemM1 = property; propertysItemM2 = property; propertysItemM3 = property; } } if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) { propertysItemM1 = propertysItemM0; propertysItemM2 = propertysItemM0; propertysItemM3 = propertysItemM0; } int discount = Integer.parseInt(item.get("discount").toString()); int discountedPriceM0 = (int) (priceM0 - (priceM0 * (discount / 100.0))); int discountedPriceM1 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM1 - (priceM1 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM2 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM2 - (priceM2 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM3 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM3 - (priceM3 * (discount / 100.0))) : discountedPriceM0; ModificationInfo[] mods = new ModificationInfo[4]; mods[0] = new ModificationInfo(id + "_m0", discountedPriceM0, rangM0); mods[0].propertys = propertysItemM0; mods[1] = new ModificationInfo(id + "_m1", discountedPriceM1, rangM1); mods[1].propertys = propertysItemM1; mods[2] = new ModificationInfo(id + "_m2", discountedPriceM2, rangM2); mods[2].propertys = propertysItemM2; mods[3] = new ModificationInfo(id + "_m3", discountedPriceM3, rangM3); mods[3].propertys = propertysItemM3; boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item"); boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted"); boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item"); items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, discountedPriceM1, rangM1, discountedPriceM0, discount, rangM0, mods, specialItem, 0, addable, multicounted)); ++index; if (typeItem == ItemType.COLOR) { ColormapsFactory.addColormap(id + "_m0", new Colormap() { { PropertyItem[] var5; int var4 = (var5 = mods[0].propertys).length; for(int var3 = 0; var3 < var4; ++var3) { PropertyItem _property = var5[var3]; this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", ""))); } } }); } } } catch (ParseException var29) { var29.printStackTrace(); } } private static int getInt(String str) { try { return Integer.parseInt(str); } catch (Exception var2) { return 0; } } private static PropertyType getType(String s) { PropertyType[] var4; int var3 = (var4 = PropertyType.values()).length; for(int var2 = 0; var2 < var3; ++var2) { PropertyType type = var4[var2]; if (type.toString().equals(s)) { return type; } } return null; } } как сделать чтобы у propertysItemM1, propertysItemM2 и propertysItemM3 не были характеристики propertysItemM0 а были свои
96d1996d39c3398dae47cebeb9020806
{ "intermediate": 0.3236824870109558, "beginner": 0.5912299752235413, "expert": 0.08508753031492233 }
34,318
clone(t={}){const r=t.loc||{};return e({loc:new Position("line"in r?r.line:this.loc.line,"column"in r?r.column:...<omitted>...)} could not be cloned.
64833b9370c83431b4e7b62a21022dcd
{ "intermediate": 0.3366658091545105, "beginner": 0.3435398042201996, "expert": 0.3197943866252899 }
34,319
Return an ordered list of URLs of resources visited at a given time a period of time. aggregate
e3a73575c352a4248b409de7d8be1971
{ "intermediate": 0.4102884829044342, "beginner": 0.22419433295726776, "expert": 0.36551719903945923 }
34,320
give me a code snippet in python that waits for a message from telegram using telebot
a99b4790e1ddba8a55af647ad8665dc8
{ "intermediate": 0.47364455461502075, "beginner": 0.1445794403553009, "expert": 0.38177597522735596 }
34,321
c++ how to keep a file created with std::tmpfile
f3cd3aacbe15755091665d3d09e9b997
{ "intermediate": 0.44183549284935, "beginner": 0.29667407274246216, "expert": 0.2614904046058655 }
34,322
Linux kernel function : __setup()
ddbad5b11c3af3f78558684e68c100da
{ "intermediate": 0.29469752311706543, "beginner": 0.4128325581550598, "expert": 0.29246985912323 }
34,323
обьясни код построчно #include "F.h" #include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char *argv[]) { FILE *inFile; time_t start = clock(); if (argc != 2){ printf("Invallid number of arguments\n"); return 0; } if ((inFile = aopen(argv[1], 2)) == NULL){ //Открытие файла на чтение и запись printf("Invallid path to first file1\n"); return 0; } fseek(inFile, 0, SEEK_END); //Перемещаем на конец файла long size = ftell(inFile); //Вернуть текущее положение внутреннего указателя(количество байт от начала файла) int* buffer = malloc(size * sizeof(int)); if (size > 0) { for (long i = 0; i < size; i++) buffer[i] = agetb(inFile, size - 1 - i); //посимвольно в буфер байты for(long i = 0; i < size; i++) asetb(inFile, i, buffer[i]); // запись байтов в файл printf("Done!\n"); } else { printf("File is empty!\n"); } aclose(inFile); time_t end = clock(); double time = (double)(end - start) / CLOCKS_PER_SEC; printf("%1.8f\n", time); return 0; }
56a599d886923ef2b59b2662ff84b338
{ "intermediate": 0.26676836609840393, "beginner": 0.5478603839874268, "expert": 0.18537122011184692 }
34,324
Как получить Android Version Number в Bitbucket Pipelines и передать его в Python Script
4e28327761c4b5163e93eef5b790c3f3
{ "intermediate": 0.5700666904449463, "beginner": 0.2560085952281952, "expert": 0.17392469942569733 }
34,325
package gtanks.users.garage; import gtanks.battles.tanks.colormaps.Colormap; import gtanks.battles.tanks.colormaps.ColormapsFactory; import gtanks.system.localization.strings.LocalizedString; import gtanks.system.localization.strings.StringsLocalizationBundle; import gtanks.users.garage.enums.ItemType; import gtanks.users.garage.enums.PropertyType; import gtanks.users.garage.items.Item; import gtanks.users.garage.items.PropertyItem; import gtanks.users.garage.items.modification.ModificationInfo; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class GarageItemsLoader { public static HashMap<String, Item> items; private static int index = 1; public static void loadFromConfig(String turrets, String hulls, String colormaps, String inventory, String subscription) { if (items == null) { items = new HashMap(); } for(int i = 0; i < 5; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 3 ? colormaps : i == 2 ? hulls : i == 1 ? turrets : i == 0 ? inventory : subscription)), StandardCharsets.UTF_8)); String line; try { while((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 3 ? ItemType.COLOR : i == 2 ? ItemType.ARMOR : i == 1 ? ItemType.WEAPON : i == 0 ? ItemType.INVENTORY : ItemType.PLUGIN); } } public static void updateloadFromConfig(String turrets, String hulls, String colormaps, String subscription) { if (items == null) { items = new HashMap(); } for (int i = 0; i < 4; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 2 ? colormaps : i == 1 ? hulls : i == 0 ? turrets : subscription)), StandardCharsets.UTF_8)); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 2 ? ItemType.COLOR : i == 1 ? ItemType.ARMOR : i == 0 ? ItemType.WEAPON : ItemType.PLUGIN); } } private static void parseAndInitItems(String json, ItemType typeItem) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(json); JSONObject jparser = (JSONObject)obj; JSONArray jarray = (JSONArray)jparser.get("items"); for(int i = 0; i < jarray.size(); ++i) { JSONObject item = (JSONObject)jarray.get(i); LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en")); LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en")); String id = (String)item.get("id"); int priceM0 = item.get("price_m0") != null ? Integer.parseInt((String) item.get("price_m0")) : 0; int priceM1 = item.get("price_m1") != null ? Integer.parseInt((String) item.get("price_m1")) : priceM0; int priceM2 = item.get("price_m2") != null ? Integer.parseInt((String) item.get("price_m2")) : priceM0; int priceM3 = item.get("price_m3") != null ? Integer.parseInt((String) item.get("price_m3")) : priceM0; int rangM0 = item.get("rang_m0") != null ? Integer.parseInt((String) item.get("rang_m0")) : 0; int rangM1 = item.get("rang_m1") != null ? Integer.parseInt((String) item.get("rang_m1")) : rangM0; int rangM2 = item.get("rang_m2") != null ? Integer.parseInt((String) item.get("rang_m2")) : rangM0; int rangM3 = item.get("rang_m3") != null ? Integer.parseInt((String) item.get("rang_m3")) : rangM0; PropertyItem[] propertysItemM0 = null; PropertyItem[] propertysItemM1 = null; PropertyItem[] propertysItemM2 = null; PropertyItem[] propertysItemM3 = null; int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications")); for (int m = 0; m < countModification; ++m) { // Создаем объекты propertysItemM1, propertysItemM2 и propertysItemM3 только, если propertysItemM0 определен if (item.get("propertys_m" + m) != null) { JSONArray propertys = (JSONArray) item.get("propertys_m" + m); PropertyItem[] property = new PropertyItem[propertys.size()]; // Создаем property для propertysItemM0 for (int p = 0; p < propertys.size(); ++p) { JSONObject prop = (JSONObject) propertys.get(p); property[p] = new PropertyItem(getType((String) prop.get("type")), (String) prop.get("value")); } switch (m) { case 0: propertysItemM0 = property; break; case 1: propertysItemM1 = property; break; case 2: propertysItemM2 = property; break; case 3: propertysItemM3 = property; } } } if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) { propertysItemM1 = propertysItemM0; propertysItemM2 = propertysItemM0; propertysItemM3 = propertysItemM0; } int discount = Integer.parseInt(item.get("discount").toString()); int discountedPriceM0 = (int) (priceM0 - (priceM0 * (discount / 100.0))); int discountedPriceM1 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM1 - (priceM1 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM2 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM2 - (priceM2 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM3 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM3 - (priceM3 * (discount / 100.0))) : discountedPriceM0; ModificationInfo[] mods = new ModificationInfo[4]; mods[0] = new ModificationInfo(id + "_m0", discountedPriceM0, rangM0); mods[0].propertys = propertysItemM0; mods[1] = new ModificationInfo(id + "_m1", discountedPriceM1, rangM1); mods[1].propertys = propertysItemM1; mods[2] = new ModificationInfo(id + "_m2", discountedPriceM2, rangM2); mods[2].propertys = propertysItemM2; mods[3] = new ModificationInfo(id + "_m3", discountedPriceM3, rangM3); mods[3].propertys = propertysItemM3; boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item"); boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted"); boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item"); items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, discountedPriceM1, rangM1, discountedPriceM0, discount, rangM0, mods, specialItem, 0, addable, multicounted)); ++index; if (typeItem == ItemType.COLOR) { ColormapsFactory.addColormap(id + "_m0", new Colormap() { { PropertyItem[] var5; int var4 = (var5 = mods[0].propertys).length; for(int var3 = 0; var3 < var4; ++var3) { PropertyItem _property = var5[var3]; this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", ""))); } } }); } } } catch (ParseException var29) { var29.printStackTrace(); } } private static int getInt(String str) { try { return Integer.parseInt(str); } catch (Exception var2) { return 0; } } private static PropertyType getType(String s) { PropertyType[] var4; int var3 = (var4 = PropertyType.values()).length; for(int var2 = 0; var2 < var3; ++var2) { PropertyType type = var4[var2]; if (type.toString().equals(s)) { return type; } } return null; } } как сделать если у обекста прописан так { "name_ru": "вффв", "name_en": "вфвфв", "discount": "16", "description_en": "This is not a tank - this is a fortress on the track layers. Flagship among other armours. Heavy, strengthened with super-concrete this armour is slow, but it is able to fight several enemies. Other armours look fragile comparing to Mammoth.", "description_ru": "Самоходная крепость на гусеничном ходу. Флагман среди танковых корпусов. Цельнолитой, тяжёлый, упрочнённый супербетоном, имеет низкую скорость, что не мешает ему с успехом противостоять одновременно нескольким вражеским орудиям.", "modification": 0, "id": "praetorian", "price_m0": "750", "rang_m0":"12", "propertys_m0": [ { "type": "armor", "value": "130" }, { "type": "speed", "value": "4.0" }, { "type": "turn_speed", "value": "80" } ] } то он и показывал его так, а не добавлял м3 и многое другое
82c303c3666b15670aac63b6c795aab7
{ "intermediate": 0.3236824870109558, "beginner": 0.5912299752235413, "expert": 0.08508753031492233 }
34,326
convert the following equation to c program: m^2=1/2(b^2+c^2)-1/4(a^2)
1cb7c42ad386af2d83016d764eb0d1ea
{ "intermediate": 0.3181971311569214, "beginner": 0.21465042233467102, "expert": 0.46715253591537476 }
34,327
Представь, что ты программист Fast API. У меня есть метод получения всех должностей: @router.get("/positions", response_model=List[CompanyUpdatePositionsInfo]) async def get_positions( access_token: str = Depends(JWTBearer()), db: AsyncSession = Depends(get_db_session) ) -> List[CompanyUpdatePositionsInfo]: employee = await get_employee_by_token(access_token, db) if employee is None: raise HTTPException(status_code=404, detail="Сотрудник не найден") positions = ( select(PositionHRM) .join(PositionHRM.company) .where(Company.id == employee.company_id) .options(selectinload(PositionHRM.position_levels)) ) result = await db.execute(positions) positions_hrm = result.scalars().all() positions_info = [CompanyUpdatePositionsInfo( company_id=position.company_id, id=position.id, position_name=position.position_name, position_levels=[level.__dict__ for level in position.position_levels] ) for position in positions_hrm] return positions_info Напиши мне метод получения должности по id.
0e91417528fbf170e9d50b302556c11d
{ "intermediate": 0.5500373840332031, "beginner": 0.32166436314582825, "expert": 0.12829828262329102 }
34,328
How do i optimize this for maximum graphics? Please do not comment, just give me the actual config. quickBuy = true lockItemPickup = true mapZoom = 40 importedCharacters = true lockMapRotation = false cameraShake = true gore = true questwidgetopen = true corpsePersistence = 0 blood = 1 reportStats = 2 targetLock = false inactiveUpdateRate = 0 cloudSaving = true gamepadSupport = true breakingMoveTo = true classicCasting = false gamepadTargetLock = true autoLootRadius = 1 critFeedback = true dayNightCycle = true toggledAurasSelf = true toggledAurasOther = true toggledWeaponEffects = true showMonsterLevelOnRollover = true displayDamage = true critMultipliers = true targetOutline = true tutorialTips = false errorMessages = true autoItemTooltips = true extraRollovers = true sortConfirmBypass = false hotbarCooldownCounter = true showTime = false mainMenu = 2 monsterBars = true playerBars = true playerLocalBar = true petBars = true playerHealth = true playerBarsLarge = true monsterHealth = true monsterIcons = true monsterBarsUndamaged = false monsterBarsLarge = true bossBarsLarge = true healthBarsPercent = false monsterBarsDebuffs = true textureQuality = high shadowQuality = ultra shadows = true weatherQuality = very high weatherEnabled = true depthOfField = true softParticles = true reflectionQuality = ultra detailLevel = ultra resolution = 3840 2160 refreshRate = 120 1 windowPosition = 0 0 antiAliasing = 1 anisotropicFiltering = 16 screenMode = 0 syncToRefresh = false tripleBuffer = false detailObjects = true advancedEffects = true brightness = 0.5 contrast = 0.5 gamma = 0.5 fxQuality = very high lightingQuality = very high uiScale = 0.764398 device = 0 colorblind = 0 alphatocoverage = true ambientocclusion = true deferredrendering = true fxaa = true fog = true masterVolume = 1 musicVolume = 1 effectsVolume = 1 ambientVolume = 1 dialogVolume = 1 rockOn = false speakerType = 1 soundDevice = 0 errorSpeech = true captureDevice = 0 micLoopback = false voiceVolume = 1 voicechatEnabled = false voicechatPushToTalk = true networkAdapter = "" networkMTU = 1400 UPnPEnable = true language = "English" datapath = "" forceSingleProcessorMode = false maxResourceThreads = 1 skipCompatibilityChecks = false useArchives = true setupComplete = false v1200FirstRun = true
32dd52020f22ac786166c793117531d0
{ "intermediate": 0.45281317830085754, "beginner": 0.30682337284088135, "expert": 0.24036343395709991 }
34,329
In this script, at his parents’ house, Dan agrees to let his younger cousin Jeannine (15, indie kid, bare feet) “hypnotize” him, expecting it to be five minutes of her embarrassing herself with cringey nonsense. In fact, Jeannine has been researching hypnosis in detail, and expertly and easily takes Dan deep into trance, fractionating him and giving him suggestions to enjoy the feeling of being hypnotized and want to be put under again in future.
ac8f116f231269ec61c8a9061be690fb
{ "intermediate": 0.2857564091682434, "beginner": 0.3395746052265167, "expert": 0.3746689558029175 }
34,330
package gtanks.users.garage; import gtanks.battles.tanks.colormaps.Colormap; import gtanks.battles.tanks.colormaps.ColormapsFactory; import gtanks.system.localization.strings.LocalizedString; import gtanks.system.localization.strings.StringsLocalizationBundle; import gtanks.users.garage.enums.ItemType; import gtanks.users.garage.enums.PropertyType; import gtanks.users.garage.items.Item; import gtanks.users.garage.items.PropertyItem; import gtanks.users.garage.items.modification.ModificationInfo; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class GarageItemsLoader { public static HashMap<String, Item> items; private static int index = 1; public static void loadFromConfig(String turrets, String hulls, String colormaps, String inventory, String subscription) { if (items == null) { items = new HashMap(); } for(int i = 0; i < 5; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 3 ? colormaps : i == 2 ? hulls : i == 1 ? turrets : i == 0 ? inventory : subscription)), StandardCharsets.UTF_8)); String line; try { while((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 3 ? ItemType.COLOR : i == 2 ? ItemType.ARMOR : i == 1 ? ItemType.WEAPON : i == 0 ? ItemType.INVENTORY : ItemType.PLUGIN); } } public static void updateloadFromConfig(String turrets, String hulls, String colormaps, String subscription) { if (items == null) { items = new HashMap(); } for (int i = 0; i < 4; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 2 ? colormaps : i == 1 ? hulls : i == 0 ? turrets : subscription)), StandardCharsets.UTF_8)); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 2 ? ItemType.COLOR : i == 1 ? ItemType.ARMOR : i == 0 ? ItemType.WEAPON : ItemType.PLUGIN); } } private static void parseAndInitItems(String json, ItemType typeItem) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(json); JSONObject jparser = (JSONObject)obj; JSONArray jarray = (JSONArray)jparser.get("items"); for(int i = 0; i < jarray.size(); ++i) { JSONObject item = (JSONObject)jarray.get(i); LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en")); LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en")); String id = (String)item.get("id"); int priceM0 = item.get("price_m0") != null ? Integer.parseInt((String) item.get("price_m0")) : 0; int priceM1 = item.get("price_m1") != null ? Integer.parseInt((String) item.get("price_m1")) : priceM0; int priceM2 = item.get("price_m2") != null ? Integer.parseInt((String) item.get("price_m2")) : priceM0; int priceM3 = item.get("price_m3") != null ? Integer.parseInt((String) item.get("price_m3")) : priceM0; int rangM0 = item.get("rang_m0") != null ? Integer.parseInt((String) item.get("rang_m0")) : 0; int rangM1 = item.get("rang_m1") != null ? Integer.parseInt((String) item.get("rang_m1")) : rangM0; int rangM2 = item.get("rang_m2") != null ? Integer.parseInt((String) item.get("rang_m2")) : rangM0; int rangM3 = item.get("rang_m3") != null ? Integer.parseInt((String) item.get("rang_m3")) : rangM0; PropertyItem[] propertysItemM0 = null; PropertyItem[] propertysItemM1 = null; PropertyItem[] propertysItemM2 = null; PropertyItem[] propertysItemM3 = null; int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications")); for (int m = 0; m < countModification; ++m) { // Создаем объекты propertysItemM1, propertysItemM2 и propertysItemM3 только, если propertysItemM0 определен if (item.get("propertys_m" + m) != null) { JSONArray propertys = (JSONArray) item.get("propertys_m" + m); PropertyItem[] property = new PropertyItem[propertys.size()]; // Создаем property для propertysItemM0 for (int p = 0; p < propertys.size(); ++p) { JSONObject prop = (JSONObject) propertys.get(p); property[p] = new PropertyItem(getType((String) prop.get("type")), (String) prop.get("value")); } switch (m) { case 0: propertysItemM0 = property; break; case 1: propertysItemM1 = property; break; case 2: propertysItemM2 = property; break; case 3: propertysItemM3 = property; } } } if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) { propertysItemM1 = propertysItemM0; propertysItemM2 = propertysItemM0; propertysItemM3 = propertysItemM0; } int discount = Integer.parseInt(item.get("discount").toString()); int discountedPriceM0 = (int) (priceM0 - (priceM0 * (discount / 100.0))); int discountedPriceM1 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM1 - (priceM1 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM2 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM2 - (priceM2 * (discount / 100.0))) : discountedPriceM0; int discountedPriceM3 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM3 - (priceM3 * (discount / 100.0))) : discountedPriceM0; ModificationInfo[] mods = new ModificationInfo[4]; mods[0] = new ModificationInfo(id + "_m0", discountedPriceM0, rangM0); mods[0].propertys = propertysItemM0; mods[1] = new ModificationInfo(id + "_m1", discountedPriceM1, rangM1); mods[1].propertys = propertysItemM1; mods[2] = new ModificationInfo(id + "_m2", discountedPriceM2, rangM2); mods[2].propertys = propertysItemM2; mods[3] = new ModificationInfo(id + "_m3", discountedPriceM3, rangM3); mods[3].propertys = propertysItemM3; boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item"); boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted"); boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item"); items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, discountedPriceM1, rangM1, discountedPriceM0, discount, rangM0, mods, specialItem, 0, addable, multicounted)); ++index; if (typeItem == ItemType.COLOR) { ColormapsFactory.addColormap(id + "_m0", new Colormap() { { PropertyItem[] var5; int var4 = (var5 = mods[0].propertys).length; for(int var3 = 0; var3 < var4; ++var3) { PropertyItem _property = var5[var3]; this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", ""))); } } }); } } } catch (ParseException var29) { var29.printStackTrace(); } } private static int getInt(String str) { try { return Integer.parseInt(str); } catch (Exception var2) { return 0; } } private static PropertyType getType(String s) { PropertyType[] var4; int var3 = (var4 = PropertyType.values()).length; for(int var2 = 0; var2 < var3; ++var2) { PropertyType type = var4[var2]; if (type.toString().equals(s)) { return type; } } return null; } } как сделать чтобы если у обекта указано только одна модификация м0 у него не показывались следующие модификации. а если у другого обекта указаны модификации м0,м1,м2 и м3 то показыются { "name_ru": "Мамонт", "name_en": "Mammonth", "discount": "16", "description_en": "This is not a tank - this is a fortress on the track layers. Flagship among other armours. Heavy, strengthened with super-concrete this armour is slow, but it is able to fight several enemies. Other armours look fragile comparing to Mammoth.", "description_ru": "Самоходная крепость на гусеничном ходу. Флагман среди танковых корпусов. Цельнолитой, тяжёлый, упрочнённый супербетоном, имеет низкую скорость, что не мешает ему с успехом противостоять одновременно нескольким вражеским орудиям.", "modification": 0, "id": "mamont", "price_m0": "750", "price_m1": "2250", "price_m2": "6800", "price_m3": "20400", "rang_m0":"12", "rang_m1":"13", "rang_m2":"14", "rang_m3":"15", "propertys_m0": [ { "type": "armor", "value": "130" }, { "type": "speed", "value": "4.0" }, { "type": "turn_speed", "value": "80" } ], "propertys_m1":[ { "type": "armor", "value": "142" }, { "type": "speed", "value": "4.17" }, { "type": "turn_speed", "value": "83" } ], "propertys_m2":[ { "type": "armor", "value": "165" }, { "type": "speed", "value": "4.5" }, { "type": "turn_speed", "value": "90" } ], "propertys_m3":[ { "type": "armor", "value": "200" }, { "type": "speed", "value": "5.0" }, { "type": "turn_speed", "value": "100" } ] }, { "name_ru": "вффв", "name_en": "вфвфв", "discount": "16", "description_en": "This is not a tank - this is a fortress on the track layers. Flagship among other armours. Heavy, strengthened with super-concrete this armour is slow, but it is able to fight several enemies. Other armours look fragile comparing to Mammoth.", "description_ru": "Самоходная крепость на гусеничном ходу. Флагман среди танковых корпусов. Цельнолитой, тяжёлый, упрочнённый супербетоном, имеет низкую скорость, что не мешает ему с успехом противостоять одновременно нескольким вражеским орудиям.", "modification": 0, "id": "praetorian", "price_m0": "750", "rang_m0":"12", "propertys_m0": [ { "type": "armor", "value": "130" }, { "type": "speed", "value": "4.0" }, { "type": "turn_speed", "value": "80" } ] }
72656e21154a009bc40d8e2935388ed6
{ "intermediate": 0.3236824870109558, "beginner": 0.5912299752235413, "expert": 0.08508753031492233 }
34,331
This is Grim Dawn that uses dx11. How do i optimize this for maximum graphics? Please do not comment, just give me the actual config. quickBuy = true lockItemPickup = true mapZoom = 40 importedCharacters = true lockMapRotation = false cameraShake = true gore = true questwidgetopen = true corpsePersistence = 0 blood = 1 reportStats = 2 targetLock = false inactiveUpdateRate = 0 cloudSaving = true gamepadSupport = true breakingMoveTo = true classicCasting = false gamepadTargetLock = true autoLootRadius = 1 critFeedback = true dayNightCycle = true toggledAurasSelf = true toggledAurasOther = true toggledWeaponEffects = true showMonsterLevelOnRollover = true displayDamage = true critMultipliers = true targetOutline = true tutorialTips = false errorMessages = true autoItemTooltips = true extraRollovers = true sortConfirmBypass = false hotbarCooldownCounter = true showTime = false mainMenu = 2 monsterBars = true playerBars = true playerLocalBar = true petBars = true playerHealth = true playerBarsLarge = true monsterHealth = true monsterIcons = true monsterBarsUndamaged = false monsterBarsLarge = true bossBarsLarge = true healthBarsPercent = false monsterBarsDebuffs = true textureQuality = high shadowQuality = ultra shadows = true weatherQuality = very high weatherEnabled = true depthOfField = true softParticles = true reflectionQuality = ultra detailLevel = ultra resolution = 3840 2160 refreshRate = 120 1 windowPosition = 0 0 antiAliasing = 1 anisotropicFiltering = 16 screenMode = 0 syncToRefresh = false tripleBuffer = false detailObjects = true advancedEffects = true brightness = 0.5 contrast = 0.5 gamma = 0.5 fxQuality = very high lightingQuality = very high uiScale = 0.764398 device = 0 colorblind = 0 alphatocoverage = true ambientocclusion = true deferredrendering = true fxaa = true fog = true masterVolume = 1 musicVolume = 1 effectsVolume = 1 ambientVolume = 1 dialogVolume = 1 rockOn = false speakerType = 1 soundDevice = 0 errorSpeech = true captureDevice = 0 micLoopback = false voiceVolume = 1 voicechatEnabled = false voicechatPushToTalk = true networkAdapter = “” networkMTU = 1400 UPnPEnable = true language = “English” datapath = “” forceSingleProcessorMode = false maxResourceThreads = 1 skipCompatibilityChecks = false useArchives = true setupComplete = false v1200FirstRun = true
7e6825f99d7db1269df2419d981ada07
{ "intermediate": 0.3753044307231903, "beginner": 0.24732337892055511, "expert": 0.37737226486206055 }
34,332
сделай так чтобы значение enchant можно было менять если значение level больше 4 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Albion_Helper { public class ItemsProcessing { private ListView BrowserList; private ListView InventoryList; private ImageList ImageList; private ItemsList itemsList; private int levelColumnIndex = 3; private int enchantmentColumnIndex = 4; public ItemsProcessing(ListView browserList, ListView inventoryList, ImageList imageList) { BrowserList = browserList; InventoryList = inventoryList; ImageList = imageList; itemsList = new ItemsList(); LoadImagesToImageList(); PopulateBrowseList(); InitializeListViewMouseHandlers(); } public void LoadImagesToImageList() { foreach (var item in itemsList.GetItems()) { string imagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BuyMenu", "ItemsIco", item.GetImageFileName() + ".png"); if (File.Exists(imagePath)) { using (var bmpTemp = new Bitmap(imagePath)) { ImageList.Images.Add(item.GetImageFileName(), new Bitmap(bmpTemp)); } } } } private void ComboBox_SelectedIndexChanged(object sender, EventArgs e) { ComboBox comboBox = sender as ComboBox; if (comboBox.Tag is ListViewItem listViewItem && listViewItem.Tag is Item item) { // Определяем, из какого именно ComboBox изменение пришло bool isLevelChanged = listViewItem.SubItems[levelColumnIndex].Bounds.Contains(comboBox.Bounds.Location); bool isEnchantmentChanged = listViewItem.SubItems[enchantmentColumnIndex].Bounds.Contains(comboBox.Bounds.Location); if (isLevelChanged) { int newLevel = int.Parse(comboBox.SelectedItem.ToString()); item.Level = newLevel; listViewItem.SubItems[levelColumnIndex].Text = item.Level.ToString(); // Если уровень предмета стал меньше 4, обнуляем чары if (newLevel < 4) { item.Charms = 0; // Найдите и обновите ComboBox для чаров, если он есть в текущем контексте // Возможно, потребуется пройтись по всем контролам или сохранить ссылку на ComboBox чаров listViewItem.SubItems[enchantmentColumnIndex].Text = item.Charms.ToString(); } } else if (isEnchantmentChanged && item.Level >= 4) // Проверяйте уровень перед тем, как изменять чары { item.Charms = int.Parse(comboBox.SelectedItem.ToString()); listViewItem.SubItems[enchantmentColumnIndex].Text = item.Charms.ToString(); } listViewItem.ImageKey = item.GetImageFileName(); // Обновляем иконку предмета comboBox.Visible = false; // Обязательно скрываем ComboBox после выбора listViewItem.ListView.Refresh(); // Обновляем ListView для отображения изменений } } public void PopulateBrowseList() { List<Item> items = GetSortedItems(); BrowserList.Items.Clear(); foreach (Item item in items) { ListViewItem listViewItem = CreateBrowserListViewItem(item); BrowserList.Items.Add(listViewItem); } } public ListViewItem CreateBrowserListViewItem(Item item) { ListViewItem listViewItem = new ListViewItem { ImageKey = item.GetImageFileName(), Tag = item }; listViewItem.SubItems.Add(item.EnglishName); listViewItem.SubItems.Add(item.GetLocalizedCategory()); return listViewItem; } public List<Item> GetSortedItems() { return itemsList.GetItems().OrderBy(item => item.EnglishName).ToList(); } public void InitializeListViewMouseHandlers() { BrowserList.MouseClick += (sender, e) => HandleMouseClick((ListView)sender, e); InventoryList.MouseClick += (sender, e) => HandleMouseClick((ListView)sender, e); } private void HandleMouseClick(ListView listView, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ListViewHitTestInfo hit = listView.HitTest(e.X, e.Y); if (hit.SubItem != null) { if (listView == InventoryList) { DisplayComboBoxOrTextBox(hit); } } } } public void AddToInventory() { if (BrowserList.SelectedItems.Count > 0) { foreach (ListViewItem item in BrowserList.SelectedItems) { Item selectedItem = (Item)item.Tag; ListViewItem newItem = CreateInventoryListViewItem(selectedItem); InventoryList.Items.Add(newItem); BrowserList.Items.Remove(item); } } } public void RemoveFromInventory() { if (InventoryList.SelectedItems.Count > 0) { foreach (ListViewItem item in InventoryList.SelectedItems) { Item selectedItem = (Item)item.Tag; ListViewItem newItem = CreateBrowserListViewItem(selectedItem); BrowserList.Items.Add(newItem); InventoryList.Items.Remove(item); } } } public ListViewItem CreateInventoryListViewItem(Item item) { ListViewItem listViewItem = new ListViewItem(); listViewItem.ImageKey = item.GetImageFileName(); listViewItem.SubItems.Add(item.GetFullEnglishName()); listViewItem.SubItems.Add("1"); listViewItem.SubItems.Add(item.Level.ToString()); listViewItem.SubItems.Add(item.Charms.ToString()); listViewItem.SubItems.Add(item.GetLocalizedCategory()); listViewItem.Tag = item; return listViewItem; } private void DisplayComboBoxOrTextBox(ListViewHitTestInfo hit) { int yOffset = 65; // Смещение по вертикали // Индексы столбцов (могут быть другими - настроить под свою структуру) int quantityColumnIndex = 2; // Индекс колонки для количества int levelColumnIndex = 3; // Индекс колонки для уровня int enchantmentColumnIndex = 4; // Индекс колонки для чаров // Проверяем, что клик был по интересующим нас колонкам в InventoryList int columnIndex = hit.Item.SubItems.IndexOf(hit.SubItem); if (columnIndex == quantityColumnIndex || columnIndex == levelColumnIndex || columnIndex == enchantmentColumnIndex) { // Определяем границы ячейки и контрол для отображения Rectangle cellBounds = hit.SubItem.Bounds; cellBounds.Offset(15, yOffset); cellBounds.Height -= yOffset; // Корректируем высоту с учетом смещения Control controlToDisplay = null; // Создание и настройка TextBox для количества if (columnIndex == quantityColumnIndex) { TextBox quantityTextBox = new TextBox { Bounds = cellBounds, Text = hit.SubItem.Text, Tag = hit.Item }; quantityTextBox.Leave += TextBox_Leave; hit.Item.ListView.Parent.Controls.Add(quantityTextBox); quantityTextBox.Focus(); quantityTextBox.Leave += (sender, e) => quantityTextBox.Visible = false; quantityTextBox.KeyPress += (sender, e) => { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } }; quantityTextBox.KeyDown += (sender, e) => { if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) { hit.SubItem.Text = quantityTextBox.Text; quantityTextBox.Visible = false; } }; controlToDisplay = quantityTextBox; } else { // Создание и настройка ComboBox для уровня или чаров ComboBox comboBox = new ComboBox { Bounds = cellBounds, DropDownStyle = ComboBoxStyle.DropDownList, }; comboBox.Leave += (sender, e) => comboBox.Visible = false; comboBox.SelectedIndexChanged += (sender, e) => { if (comboBox.Tag is ListViewItem listViewItem && listViewItem.Tag is Item item) { // Определяем, какое именно свойство изменилось bool isLevelChanged = listViewItem.SubItems[levelColumnIndex].Bounds.Contains(comboBox.Bounds.Location); bool isEnchantmentChanged = listViewItem.SubItems[enchantmentColumnIndex].Bounds.Contains(comboBox.Bounds.Location); if (isLevelChanged) { item.Level = int.Parse(comboBox.SelectedItem.ToString()); listViewItem.SubItems[levelColumnIndex].Text = item.Level.ToString(); if (item.Level >= 4) { comboBox.Enabled = true; // Разрешаем выбор for (int i = 0; i <= 4; i++) { comboBox.Items.Add(i.ToString()); } } else { comboBox.Enabled = false; // Запрещаем выбор comboBox.Items.Add("0"); // Добавляем единственно допустимый вариант } } else if (isEnchantmentChanged) { // Не изменяем чары, если уровень меньше 4 - они должны оставаться равными 0. if (item.Level >= 4) { item.Charms = int.Parse(comboBox.SelectedItem.ToString()); listViewItem.SubItems[enchantmentColumnIndex].Text = item.Charms.ToString(); } } listViewItem.ImageKey = item.GetImageFileName(); // Обновляем иконку предмета listViewItem.ListView.Refresh(); // Обновляем ListView для отображения изменений comboBox.Visible = false; // Скрываем ComboBox после выбора } hit.SubItem.Text = comboBox.SelectedItem.ToString(); }; // Fill the ComboBox with the right values depending on the column if (columnIndex == levelColumnIndex) { int minLevel = (hit.Item.Tag as Item)?.MinLevel ?? 1; for (int i = minLevel; i <= 8; i++) { comboBox.Items.Add(i.ToString()); } } else if (columnIndex == enchantmentColumnIndex) { for (int i = 0; i <= 4; i++) { comboBox.Items.Add(i.ToString()); } } // Set selected value comboBox.SelectedItem = hit.SubItem.Text; controlToDisplay = comboBox; } if (controlToDisplay != null) { hit.Item.ListView.Parent.Controls.Add(controlToDisplay); controlToDisplay.BringToFront(); controlToDisplay.Visible = true; controlToDisplay.Focus(); } } } private void TextBox_Leave(object sender, EventArgs e) { TextBox tb = sender as TextBox; if (tb != null) { ListViewItem item = (ListViewItem)tb.Tag; if (item != null && item.ListView != null) { // Здесь номер колонки для количества - 2 (или другой индекс, если структура ListView иная) item.SubItems[2].Text = tb.Text; } item.ListView.Focus(); // Перемещаем фокус на ListView tb.Dispose(); // Уничтожаем TextBox } } } }
5a1f5479ae7b9d4edea6d337727260cf
{ "intermediate": 0.33611416816711426, "beginner": 0.4609377086162567, "expert": 0.20294810831546783 }
34,333
Представь, что ты программист Fast API. У меня есть метод получения должности по id: @router.get("/get-position/{position_id}", response_model=CompanyUpdatePositionsInfo) async def get_position_by_id( position_id: int, access_token: str = Depends(JWTBearer()), db: AsyncSession = Depends(get_db_session) ) -> CompanyUpdatePositionsInfo: employee = await get_employee_by_token(access_token, db) if employee is None: raise HTTPException(status_code=404, detail="Сотрудник не найден") position = ( select(PositionHRM) .join(PositionHRM.company) .where(PositionHRM.company_id == employee.company_id, PositionHRM.id == position_id) .options(selectinload(PositionHRM.position_levels)) ) result = await db.execute(position) position_hrm = result.scalar_one_or_none() if position_hrm: position_info = CompanyUpdatePositionsInfo( company_id=position_hrm.company_id, id=position_hrm.id, position_name=position_hrm.position_name, position_levels=[level.__dict__ for level in position_hrm.position_levels] ) return position_info else: raise HTTPException(status_code=404, detail=f"Должность с id {position_id} не найдена") Напиши мне метод put обновления должности.
d5795f887f901455127fbc1af4e29aa8
{ "intermediate": 0.6953657865524292, "beginner": 0.2260909229516983, "expert": 0.0785432904958725 }