row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
46,385
hi
74e6a063e4728d36b087341b9b274277
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
46,386
Recently you had a quarrel with your math teacher. Not only that nerd demands knowledge of all the theorems, but he turned to be an constructivist devotee! After you recited by heart Lagranges theorem of sum of four squares, he now demands a computer program to obtain such a decomposition, so that to see that you really understand a topic. What a downer! You remember well the theorem. Any positive integer can be decomposed into a sum of four squares of integers. Seems not too hard... But after a quarrel, your teacher wants blood. Apparently he will test your program on extremely huge numbers... And your program better finished working before the break - you don't want to get F, do you? Tip: random tests feature 20 numbers as high as 2^128 and 20 number as high as 2^1024. here is code
368b4d23efd7ceeb3a1b7afc0ca4a3a9
{ "intermediate": 0.37146103382110596, "beginner": 0.3671010732650757, "expert": 0.26143789291381836 }
46,387
if we have a function a.c which contain a static function static sum(int a, int b) { } shall I use a guard to disable the static value when doing unit test? Is it a good practice?
702ec6bc6d50c896bf1f49af41f914e6
{ "intermediate": 0.43782496452331543, "beginner": 0.3724276125431061, "expert": 0.18974748253822327 }
46,388
Привет! import requests class YandexGPT: def generate(self, prompt, apikey, sa_id): url = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion' headers = { 'Content-Type': 'application/json', 'Authorization': f'Api-Key {apikey}' } data = { "modelUri": f"gpt://{sa_id}/yandexgpt-lite/latest", "completionOptions": { "stream": False, "temperature": 0.6, "maxTokens": "1000" }, "messages": [ { "role": "system", "text": "Отвечай как можно более кратко" }, { "role": "user", "text": prompt } ] } response = requests.post(url, json=data, headers=headers) return response.text self = YandexGPT() string = YandexGPT.generate(self,"Привет! Как тебя зовут?", "AQVN1J4sCxYR98rj-tVppyp6gXQthbdmYvmgtO7a", "ajekjom0m5ghuv5e7uml") print(string) - при запуске дает ответ {"error":{"grpcCode":3,"httpCode":400,"message":"Specified folder ID 'ajekjom0m5ghuv5e7uml' does not match with service account folder ID 'b1g5og37bgh1ghh2s2qc'","httpStatus":"Bad Request","details":[]}}. Что это значит?
6d3e6d1f4a658648f7379bbd2cabf753
{ "intermediate": 0.21042484045028687, "beginner": 0.6652219295501709, "expert": 0.12435323745012283 }
46,389
Write a function named is_valid that gets two strings arguments, username and password. The function will return True if the username and password are valid in the system, otherwise False. Our system contains only two valid usernames - "admin" and "user". The valid password for username "user" is "qweasd". For username "admin" any password is valid!
fdb93444585ea863fa41170085209a94
{ "intermediate": 0.32544443011283875, "beginner": 0.3281097114086151, "expert": 0.34644585847854614 }
46,390
Write a python script that asks for what day of the week yesterday was and what day of the week tomorrow will be, the answer can be given either as a day or negatively as not day. Example "monday" or "not monday". Then it must show all the possible days of the week for today given that.
cde91769a3c58dfcf1766011ef672c16
{ "intermediate": 0.3782999515533447, "beginner": 0.22585509717464447, "expert": 0.395844966173172 }
46,391
What is ai
cbf9ba336699d9a3e7bf9bde4cb1db1f
{ "intermediate": 0.3500627875328064, "beginner": 0.21956095099449158, "expert": 0.4303763508796692 }
46,392
i need to know in GNN with the GAT, if i have node features for 20 nodes and its associated edge index and edge features are forward to the GNN model input layer as tensor structure, can we able to get specific number of nodes(sample 11 node features) as output layer
3d75ee471817914ee4932e8987c2512b
{ "intermediate": 0.06465546041727066, "beginner": 0.019946102052927017, "expert": 0.9153984785079956 }
46,393
this javascript animates a marker between two points. Can you change the marker to a square polygon. '// starttrain const firstPoint = L.latLng( firstCityCoords[1], firstCityCoords[0] ); const secondPoint = L.latLng( secondCityCoords[1], secondCityCoords[0] ); const intervalDuration = 10; // milliseconds per frame const distance = firstPoint.distanceTo(secondPoint); const steps = ((distance / speed) * 1000) / intervalDuration; // Assuming speed of 35 miles per hour const latStep = (secondPoint.lat - firstPoint.lat) / steps; const lngStep = (secondPoint.lng - firstPoint.lng) / steps; // Create the marker and set its initial position marker = L.marker(firstPoint).addTo(map); const moveMarker = (speed) => { if (progress < steps) { const newLat = firstPoint.lat + latStep * progress; const newLng = firstPoint.lng + lngStep * progress; const newLatLng = L.latLng(newLat, newLng); marker.setLatLng(newLatLng); // Update the marker's position progress++; setTimeout(function () { moveMarker(speed); }, intervalDuration); } else { // Marker reaches the second point, update money money += Math.floor(Math.random() * (2000 - 1000 + 1)) + 1000 * numberOfCarriages; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Wait two seconds before animating back and call moveBackMarker recursively setTimeout(() => { moveBackMarker(speed); }, 2000); // Wait for 2 seconds (2000 milliseconds) } }; const moveBackMarker = (speed) => { // Corrected calculation for animating back from second point to first if (progress > 0) { const newLat = secondPoint.lat - latStep * (steps - progress); const newLng = secondPoint.lng - lngStep * (steps - progress); const newLatLng = L.latLng(newLat, newLng); marker.setLatLng(newLatLng); // Update the marker's position progress--; setTimeout(function () { moveBackMarker(speed); }, intervalDuration); } else { console.log("Reached starting point again."); // Add random number to money and update display money += Math.floor(Math.random() * (2000 - 1000 + 1)) + 1000 * numberOfCarriages; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Reset progress for next round trip progress = 0; // Recursively call moveMarker to start next animation cycle moveMarker(speed); } }; moveMarker(speed); // Start the animation'
695418893251d7fb79bdfc8d62bb269f
{ "intermediate": 0.32541847229003906, "beginner": 0.3483444154262543, "expert": 0.32623717188835144 }
46,394
Привет! помоги мне интегрировать функцию в бота. Функция: import requests import json class YandexGPT: def generate(self, prompt, apikey, sa_id): url = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion' headers = { 'Content-Type': 'application/json', 'Authorization': f'Api-Key {apikey}' } data = { "modelUri": f"gpt://{sa_id}/yandexgpt/latest", "completionOptions": { "stream": False, "temperature": 0.6, "maxTokens": "1000" }, "messages": [ { "role": "system", "text": "Твоя задача - создать небольшой текст о биографии человека в соответствии с следующими ответами на вопросы (пишется вопрос? ответ). Также напиши короткую эпитафию в соответствии с биографией. Свой ответ пиши только по шаблону:\nБиография:\n\nЭпитафий:\n\nБиография должна быть не сильно длинной, но интересной. Если биография очевидно неправильная (ответы на вопросы невозможно распознать), то пиши: Извините, я не понял ваш запрос. Попробуйте ответить на вопросы еще раз. " }, { "role": "user", "text": prompt } ] } response = requests.post(url, json=data, headers=headers) return response.text self = YandexGPT() string = YandexGPT.generate(self, "Имя? - Артем\nДата рождения? - 12.03.2005\n Дата смерти? - 12.03.2024\nБыл женат? - Да.\n Кем работал? строителем ", "AQVN1J4sCxYR98rj-tVppyp6gXQthbdmYvmgtO7a", "b1g5og37bgh1ghh2s2qc") jsons = json.loads(string) print(jsons['result']['alternatives'][0]['message']['text']) Существующий код в боте: async def generate(prompt: str, apikey: str, sa_id: str, user_id : str): url = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion' headers = { 'Content-Type': 'application/json', 'Authorization': f'Api-Key {apikey}' } data = { "modelUri": f"gpt://{sa_id}/yandexgpt-lite/latest", "completionOptions": { "stream": False, "temperature": 0.6, "maxTokens": "1000" }, "messages": [ { "role": "system", "text": "Твоя задача - создать небольшой текст о биографии человека в соответствии с следующими ответами на вопросы (пишется вопрос? ответ). Также напиши короткую эпитафию в соответствии с биографией. Свой ответ пиши только по шаблону:\nБиография:\n\nЭпитафий:\n\nБиография должна быть не сильно длинной, но интересной. Если биография очевидно неправильная (ответы на вопросы невозможно распознать), то пиши: Извините, я не понял ваш запрос. Попробуйте ответить на вопросы еще раз. " }, { "role": "user", "text": prompt } ] } try: response = requests.post(url, json=data, headers=headers) response_data = response.json() jsons = response_data.loads(string) answer = jsons['result']['alternatives'][0]['message']['text'] await bot.send_message(user_id, answer) except Exception as e: return await bot.send_message(user_id, f"Произошла ошибка: {e}. Пожалуйста, попробуйте еще раз.")
6f8690adcc855b9c6bbdae9098788a0d
{ "intermediate": 0.25995007157325745, "beginner": 0.5612820982933044, "expert": 0.1787678450345993 }
46,395
Данный код читает шейп-файл с точками и таблицу со списком ребер из этих точек, связывает таблицу с шейп-файлом по номеру (идентификатору точки), чтобы извлечь ее геометрию, построить ребро и добавить его в новый шейп-файл. Однако возникает ошибка, как ее решить? path = r"C:\BAZA\COURSEWORK\GRID_1\with_dem\points_dem.shp" points = gpd.read_file(path) FID_land_p Landtype Road_type MEAN_speed MEDIAN_spe ELEV_DEM MERGE_SRC geometry TARGET_FID 0 113 Залежь None 3.312347 3.471036 162.055 land POINT Z (329981.690 6119284.376 0.000) 1 1 113 Залежь None 3.312347 3.471036 161.896 land POINT Z (329986.690 6119284.376 0.000) 2 2 113 Залежь None 3.312347 3.471036 161.719 land POINT Z (329991.690 6119284.376 0.000) 3 3 113 Залежь None 3.312347 3.471036 161.526 land POINT Z (329996.690 6119284.376 0.000) 4 4 113 Залежь None 3.312347 3.471036 161.318 land POINT Z (330001.690 6119284.376 0.000) 5 5 113 Залежь None 3.312347 3.471036 161.096 land POINT Z (330006.690 6119284.376 0.000) 6 6 113 Залежь None 3.312347 3.471036 160.853 land POINT Z (330011.690 6119284.376 0.000) 7 7 113 Залежь None 3.312347 3.471036 160.586 land POINT Z (330016.690 6119284.376 0.000) 8 8 113 Залежь None 3.312347 3.471036 160.294 land POINT Z (330021.690 6119284.376 0.000) 9 9 113 Залежь None 3.312347 3.471036 159.980 land POINT Z (330026.690 6119284.376 0.000) 10 len(points) 814404 all_table_points = pd.read_pickle(r"C:\BAZA\COURSEWORK\GRID_1\with_dem\all_table_points.pkl") OBJECTID IN_FID NEAR_FID NEAR_DIST NEAR_RANK 0 2 797613 797614 4.999981 1 1 3 797613 797612 5.000031 2 2 4 797614 797613 4.999981 1 3 5 797614 797615 5.000031 2 4 6 797615 797616 4.999981 1 5 7 797615 797614 5.000031 2 6 8 797616 797615 4.999981 1 7 9 797616 797617 5.000031 2 8 10 797617 797618 4.999940 1 9 11 797617 797616 5.000031 2 len(all_table_points) 6429638 table['FID_PAIR'] = table.apply(lambda row: tuple(sorted([row['IN_FID'], row['NEAR_FID']])), axis=1) table_unique = table.drop_duplicates(subset=['FID_PAIR']) table_unique.head(10) OBJECTID IN_FID NEAR_FID NEAR_DIST NEAR_RANK FID_PAIR 0 1 0 1 10.000000 1 (0.0, 1.0) 1 2 0 84 10.000000 1 (0.0, 84.0) 2 3 0 85 14.142136 2 (0.0, 85.0) 3 4 0 2 20.000000 3 (0.0, 2.0) 4 5 0 168 20.000000 3 (0.0, 168.0) 5 6 0 86 22.360680 4 (0.0, 86.0) 6 7 0 169 22.360680 4 (0.0, 169.0) 8 9 1 2 10.000000 1 (1.0, 2.0) 9 10 1 85 10.000000 1 (1.0, 85.0) 10 11 1 84 14.142136 2 (1.0, 84.0) %%time edges = [] for index, row in table_unique.iterrows(): start_id, end_id, dist = row['IN_FID'], row['NEAR_FID'], row['NEAR_DIST'] start_point = points[points['TARGET_FID'] == start_id].geometry.values[0] end_point = points[points['TARGET_FID'] == end_id].geometry.values[0] start = points[points['TARGET_FID'] == start_id]['land_avg_s'].values[0] end = points[points['TARGET_FID'] == end_id]['land_avg_s'].values[0] start_source = points[points['TARGET_FID'] == start_id]['Source'].values[0] end_source = points[points['TARGET_FID'] == end_id]['Source'].values[0] start_lt = points[points['TARGET_FID'] == start_id]['Landtype'].values[0] end_lt = points[points['TARGET_FID'] == end_id]['Landtype'].values[0] start_elev = points[points['TARGET_FID'] == start_id]['ELEV'].values[0] end_elev = points[points['TARGET_FID'] == end_id]['ELEV'].values[0] if start_lt == 'land' and end_lt == 'land': if dist == 22.36068: edge = LineString([start_point, end_point]) elif dist <= 14.142136: edge = LineString([start_point, end_point]) else: pass else: edge = LineString([start_point, end_point]) edges.append({'geometry': edge, 'START_ID': start_id, 'END_ID': end_id, 'START_SPEED': start, 'END_SPEED': end, 'START_SOURCE': start_source, 'END_SOURCE': end_source, 'LT1': start_lt, 'LT2': end_lt, 'ELEV1': start_elev, 'ELEV2': end_elev}) print(len(edges)) edges_gdf = gpd.GeoDataFrame(edges, crs=points.crs) output_shapefile = r"C:\BAZA\COURSEWORK\GRID_1\with_dem\knight_links_10m_dem_set.shp" edges_gdf.to_file(output_shapefile, driver='ESRI Shapefile', encoding='UTF-8') --------------------------------------------------------------------------- IndexError Traceback (most recent call last) File <timed exec>:7 File ~\.conda\envs\ELZAS_LORAN\lib\site-packages\geopandas\array.py:384, in GeometryArray.__getitem__(self, idx) 382 def __getitem__(self, idx): 383 if isinstance(idx, numbers.Integral): --> 384 return _geom_to_shapely(self._data[idx]) 385 # array-like, slice 386 # validate and convert IntegerArray/BooleanArray 387 # to numpy array, pass-through non-array-like indexers 388 idx = pd.api.indexers.check_array_indexer(self, idx) IndexError: index 0 is out of bounds for axis 0 with size 0
248cb5809e7a6d963baad1f5ae4657ed
{ "intermediate": 0.3613375425338745, "beginner": 0.4257080852985382, "expert": 0.21295438706874847 }
46,396
in this javascript for leaflet.js I want to add a number inside the black train number. This number should show the value of 'numberOfCarriages' - var money = 100000; var numberOfCarriages = 1; var speed = 60; var dailybonus = 0; const map = L.map("map").setView([54.2231637, -1.9381623], 6); // Add custom zoom control to the map with position set to ‘topright’ const customZoomControl = L.control.zoom({ position: "topright" }).addTo(map); // Remove the default zoom control from the map map.removeControl(map.zoomControl); let clickedPoints = []; let isLineDrawn = false; let marker; // Declare the marker variable let progress = 0; let cafeOneBonus = 0; let cafeTwoBonus = 0; let hotelOneBonus = 0; let hotelTwoBonus = 0; const increaseSpeed = () => { const speedIncrease = 20; speed += speedIncrease; }; // Function to create circle markers with click functionality function createCircleMarkers(geojson) { return L.geoJSON(geojson, { pointToLayer: function (feature, latlng) { const circleMarker = L.circleMarker(latlng, { radius: 4, fillColor: "#ff7800", color: "#000", weight: 0.2, opacity: 1, fillOpacity: 0.8, }); // Attach the feature to the circle marker circleMarker.feature = feature; circleMarker.on("mouseover", function () { this.bindPopup(feature.properties.city).openPopup(); }); circleMarker.on("click", function (e) { if (!isLineDrawn) { clickedPoints.push(e.target); // Push the circle marker with attached feature if (clickedPoints.length === 2) { const firstCityCoords = clickedPoints[0].feature.geometry.coordinates; const secondCityCoords = clickedPoints[1].feature.geometry.coordinates; const polyline = L.polyline( clickedPoints.map((p) => p.getLatLng()) ).addTo(map); const firstCity = clickedPoints[0].feature.properties.city; const secondCity = clickedPoints[1].feature.properties.city; clickedPoints = []; isLineDrawn = true; // Remove click event listener after a line has been drawn map.off("click"); // Set the map bounds to show the area with the polyline map.fitBounds(polyline.getBounds()); money = money - 50000; // Subtract 50000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; // Assuming money is a number moneyDisplay.textContent = moneyString; const instructionsElement = document.getElementById("instructions"); // Clear any existing content in the instructions element: instructionsElement.innerHTML = ""; // Create separate paragraph elements: const congratulationsParagraph = document.createElement("p"); congratulationsParagraph.textContent = `Congratulations you have built your first train line from ${firstCity} to ${secondCity}!`; const costsParagraph = document.createElement("p"); costsParagraph.textContent = `Your construction costs were £50,000. You have £50,000 remaining.`; const buyTrainParagraph = document.createElement("p"); buyTrainParagraph.textContent = "You now need to buy a train."; const newTrainParagraph = document.createElement("p"); newTrainParagraph.textContent = "At this time you can only afford to buy the train engine the Sleeping Lion. The Sleeping Lion has a traveling speed of 60 miles per hour. It can pull four carriages. Which means your train will have a capacity of around 120 seated passengers"; const traincost = document.createElement("p"); traincost.textContent = `The Sleeping Lion will cost you £30,000 to purchase. Do you wish to buy the Sleeping Lion?`; // Append paragraphs to the instructions element: instructionsElement.appendChild(congratulationsParagraph); instructionsElement.appendChild(costsParagraph); instructionsElement.appendChild(buyTrainParagraph); instructionsElement.appendChild(newTrainParagraph); instructionsElement.appendChild(traincost); // Add button element: const buyButton = document.createElement("button"); buyButton.id = "buybutton"; buyButton.textContent = "Buy Train"; // Append the button element to the instructions element: instructionsElement.appendChild(buyButton); //buybutton event listener document .getElementById("buybutton") .addEventListener("click", function () { // Check if you have enough money before purchase money = money - 30000; // Subtract 30000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Update instructions content after successful purchase instructionsElement.innerHTML = ""; // Clear previous content const successMessage = document.createElement("p"); successMessage.textContent = `You now have a train line from ${firstCity} to ${secondCity} and a train! Press the button below to begin operations.`; instructionsElement.appendChild(successMessage); // Add button element: const trainButton = document.createElement("button"); trainButton.id = "trainbutton"; trainButton.textContent = "Start Train"; // Append the button element to the instructions element: instructionsElement.appendChild(trainButton); trainButton.addEventListener("click", function () { console.log("Train Started"); //emptyinstructions add improvement buttons instructionsElement.innerHTML = ""; // Clear previous content //randomgeneration of dailybonus function generateDailyBonus(minBonus, maxBonus) { const randomNumber = Math.floor(Math.random() * (maxBonus - minBonus + 1)) + minBonus; dailybonus += randomNumber; console.log(`Daily bonus of ${randomNumber} added!`); } //buy carriages //add carriages button const carriageButton = document.createElement("button"); carriageButton.id = "trainbutton"; carriageButton.textContent = "Buy Train Carriage"; const carriageMessage = document.createElement("p"); carriageMessage.textContent = `Buy another passenger carriage for your train for £20,000`; instructionsElement.appendChild(carriageMessage); // Append the button element to the instructions element: instructionsElement.appendChild(carriageButton); //cariagebutton logic carriageButton.addEventListener("click", () => { console.log("Carriage Bought"); // Check if enough money is available if (money >= 20000) { // Check if maximum number of carriages reached if (numberOfCarriages < 4) { numberOfCarriages++; money -= 20000; // Subtract 20000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; } else { console.log( "Maximum number of carriages reached! You can't buy more." ); instructionsElement.removeChild(carriageButton); instructionsElement.removeChild(carriageMessage); } } }); //buy station cafes //add station one cafe button const stationOneMessage = document.createElement("p"); stationOneMessage.textContent = `Open a cafe in ${firstCity} Station for £2,500.`; instructionsElement.appendChild(stationOneMessage); // Add button element: const cafeOneButton = document.createElement("button"); cafeOneButton.id = "trainbutton"; cafeOneButton.textContent = "Buy Cafe"; // Append the button element to the instructions element: instructionsElement.appendChild(cafeOneButton); //cafeonelogic cafeOneButton.addEventListener("click", () => { if (money >= 2500) { // add a random number between 2000 and 7000 to dailbonus generateDailyBonus(2000, 7000); // Call with cafe bonus range cafeOneBonus = dailybonus; console.log("Cafe one bought"); money -= 2500; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(cafeOneButton); instructionsElement.removeChild(stationOneMessage); } else { } }); //add station two cafe buttons const stationTwoMessage = document.createElement("p"); stationTwoMessage.textContent = `Open a cafe in ${secondCity} Station for £2,500.`; instructionsElement.appendChild(stationTwoMessage); // Add button element: const cafeTwoButton = document.createElement("button"); cafeTwoButton.id = "trainbutton"; cafeTwoButton.textContent = "Buy Cafe"; // Append the button element to the instructions element: instructionsElement.appendChild(cafeTwoButton); //cafetwologic cafeTwoButton.addEventListener("click", () => { if (money >= 2500) { // Generate a random number between 2000 (inclusive) and 7000 (exclusive) generateDailyBonus(2000, 7000); // Call with cafe bonus range cafeTwoBonus = dailybonus; console.log("Cafe two bought"); money -= 2500; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(cafeTwoButton); instructionsElement.removeChild(stationTwoMessage); } else { } }); //buyhotel const hoteloneMessage = document.createElement("p"); hoteloneMessage.textContent = `Open a hotel in ${firstCity} Station for £10,000.`; instructionsElement.appendChild(hoteloneMessage); // Add button element: const hoteloneButton = document.createElement("button"); hoteloneButton.id = "trainbutton"; hoteloneButton.textContent = "Buy Hotel"; // Append the button element to the instructions element: instructionsElement.appendChild(hoteloneButton); //hotelonelogic hoteloneButton.addEventListener("click", () => { if (money >= 10000) { generateDailyBonus(8000, 24000); // Call with cafe bonus range hotelOneBonus = dailybonus; money -= 10000; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(hoteloneButton); instructionsElement.removeChild(hoteloneMessage); } else { } }); const hoteltwoMessage = document.createElement("p"); hoteltwoMessage.textContent = `Open a hotel in ${secondCity} Station for £10,000.`; instructionsElement.appendChild(hoteltwoMessage); // Add button element: const hoteltwoButton = document.createElement("button"); hoteltwoButton.id = "trainbutton"; hoteltwoButton.textContent = "Buy Hotel"; // Append the button element to the instructions element: instructionsElement.appendChild(hoteltwoButton); //hotelonelogic hoteltwoButton.addEventListener("click", () => { if (money >= 10000) { generateDailyBonus(8000, 24000); // Call with cafe bonus range hotelTwoBonus = dailybonus; money -= 10000; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(hoteltwoButton); instructionsElement.removeChild(hoteltwoMessage); } else { } }); // starttrain const firstPoint = L.latLng( firstCityCoords[1], firstCityCoords[0] ); const secondPoint = L.latLng( secondCityCoords[1], secondCityCoords[0] ); const intervalDuration = 10; // milliseconds per frame const distance = firstPoint.distanceTo(secondPoint); const steps = ((distance / speed) * 1000) / intervalDuration; // Assuming speed of 35 miles per hour const latStep = (secondPoint.lat - firstPoint.lat) / steps; const lngStep = (secondPoint.lng - firstPoint.lng) / steps; // Create a black circle marker and set its initial position const marker = L.circleMarker(firstPoint, { color: "black", fillColor: "black", fillOpacity: 1, radius: 5, // Adjust radius as desired }).addTo(map); const moveMarker = (speed) => { if (progress < steps) { const newLat = firstPoint.lat + latStep * progress; const newLng = firstPoint.lng + lngStep * progress; const newLatLng = L.latLng(newLat, newLng); marker.setLatLng(newLatLng); // Update the marker's position progress++; setTimeout(function () { moveMarker(speed); }, intervalDuration); } else { // Marker reaches the second point, update money money += Math.floor(Math.random() * (2000 - 1000 + 1)) + 1000 * numberOfCarriages; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Wait two seconds before animating back and call moveBackMarker recursively setTimeout(() => { moveBackMarker(speed); }, 2000); // Wait for 2 seconds (2000 milliseconds) } }; const moveBackMarker = (speed) => { // Corrected calculation for animating back from second point to first if (progress > 0) { const newLat = secondPoint.lat - latStep * (steps - progress); const newLng = secondPoint.lng - lngStep * (steps - progress); const newLatLng = L.latLng(newLat, newLng); marker.setLatLng(newLatLng); // Update the marker's position progress--; setTimeout(function () { moveBackMarker(speed); }, intervalDuration); } else { console.log("Reached starting point again."); // Add random number to money and update display money += Math.floor(Math.random() * (2000 - 1000 + 1)) + 1000 * numberOfCarriages; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Reset progress for next round trip progress = 0; // Recursively call moveMarker to start next animation cycle moveMarker(speed); } }; moveMarker(speed); // Start the animation }); }); } } }); return circleMarker; }, }); } fetch("gb.geojson") .then((response) => response.json()) .then((geojson) => { L.geoJSON(geojson, { fillColor: "none", // Style for polygon (empty fill) weight: 1, color: "#000", opacity: 1, fillOpacity: 0, }).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); }); fetch("cities.geojson") .then((response) => response.json()) .then((geojson) => { createCircleMarkers(geojson).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); }); //24 hour clock display const TIME_MULTIPLIER = 60 * 10; // 10 minutes = 600 seconds // Function to format time in 24-hour format with leading zeros function formatTime(hours, minutes) { // Handle the case where minutes reach 60 (should display the next hour) if (minutes === 60) { hours++; minutes = 0; } return `${hours.toString().padStart(2, "0")}:${minutes .toString() .padStart(2, "0")}`; } // Function to update the clock display and handle daily bonus function updateClock() { const currentTime = new Date(); // Simulate game time by multiplying actual time with multiplier const gameTime = new Date(currentTime.getTime() * TIME_MULTIPLIER); // Get hours and minutes in 24-hour format let hours = gameTime.getHours(); // Get minutes and force them to the nearest multiple of 10 (ending in 0) let minutes = Math.floor(gameTime.getMinutes() / 10) * 10; // Format the time string with fixed minute handling const formattedTime = formatTime(hours, minutes); // Update the content of the div with the formatted time document.getElementById("timedisplay").textContent = formattedTime; // Check if it's midnight (00:00) if (hours === 0 && minutes === 0) { // Generate random daily bonus (modify as needed) money += cafeOneBonus + cafeTwoBonus + hotelOneBonus; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; console.log( `Daily bonus of ${ cafeOneBonus + cafeTwoBonus + hotelOneBonus + hotelTwoBonus } added! Total money: ${money}` ); // You can replace console.log with your desired action } } // Call the updateClock function initially updateClock(); // Update the clock every second to simulate smooth time progression setInterval(updateClock, 1000);
ec759058ac22cea92e348b08882560ff
{ "intermediate": 0.3357192575931549, "beginner": 0.4156889319419861, "expert": 0.248591810464859 }
46,397
if sys.stdin.isatactive() and sys.stdin.read(1) == 'q': print("Quitting...") break is throwing error File "C:\Users\Andy\My Drive\python\codserial.py", line 22, in monitor_com_port if sys.stdin.isatactive() and sys.stdin.read(1) == 'q': AttributeError: '_io.TextIOWrapper' object has no attribute 'isatactive' why_
2e8a78af33f7cefd2355d7d8cbd50689
{ "intermediate": 0.40747350454330444, "beginner": 0.36130502820014954, "expert": 0.23122146725654602 }
46,398
I'm developing a GUI scrolling panel from scratch in java. float scroll = InputHandler.getScroll(); displayY += scroll; // displayY = MathUtils.clampf(displayY, 0, contentHeight - height); final float sus = 0.8f; if(displayY < 0) { displayY = MathUtils.lerp(displayY, 0, sus); } else if(displayY > contentHeight - height) { displayY = MathUtils.lerp(displayY, contentHeight - height, sus); } System.out.println(displayY); deltaDisplayY -= displayY; This is my current code. The problem I'm facing is I want the user to be able to scroll past the bounds of displayY a bit, but the further they scroll out of bounds, the stronger the pull will be to force the scroll panel to get back in frame. I thought I could achieve this with lerp, but I'm getting a strange jittery effect when I start to scroll repeatedly. Do you know of a smoother way I can handle this force
226529dc0783245d2c2c7a7cc625ff8c
{ "intermediate": 0.5302274823188782, "beginner": 0.23878605663776398, "expert": 0.23098643124103546 }
46,399
hi
2bcfed03f2de70af287c7a9d12b24475
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
46,400
Create a function named values that receives a list as an argument and prints all of the items in the list one after the other. To iterate over a list use the len() function inside the range() function: my_list = [10, 20, 30, 40, 50] for i in range(len(my_list)): my_list[i] This way i will iterate from 0 to len(my_list) (not including) which is exactly all of the list indices.
1fc085166b551bd3d455a88212baea4e
{ "intermediate": 0.2387385070323944, "beginner": 0.5779184699058533, "expert": 0.1833430826663971 }
46,401
I'm developing a GUI scrolling panel from scratch in java. The problem I'm facing is I want the user to be able to scroll past the bounds of displayY a bit, but the further they scroll out of bounds, the stronger the pull will be to force the scroll panel to get back in frame. I thought I could achieve this with lerp, but I'm getting a strange jittery effect when I start to scroll repeatedly. Do you know of a smoother way I can handle this force? How cna I google this online for solutions
860affe4c19b4f8929c7ce75ad3ea067
{ "intermediate": 0.4764571785926819, "beginner": 0.17552687227725983, "expert": 0.3480159044265747 }
46,402
I'm developing a GUI scrolling panel from scratch in java. The problem I'm facing is I want the user to be able to scroll past the bounds of displayY a bit, but the further they scroll out of bounds, the stronger the pull will be to force the scroll panel to get back in frame. I thought I could achieve this with lerp, but I'm getting a strange jittery effect when I start to scroll repeatedly. Do you know of a smoother way I can handle this force
ca78dcad57c03d63318f4e9009e1e7bd
{ "intermediate": 0.5145432949066162, "beginner": 0.21899007260799408, "expert": 0.26646655797958374 }
46,403
i want to translate english to hindi sentences using chat gpt give me code
497921d876dbd238e34ca7c2b2197b51
{ "intermediate": 0.31463268399238586, "beginner": 0.3285578489303589, "expert": 0.35680946707725525 }
46,404
Привет! ППривет! Помоги мне добавить несколько нововведений в бота. После того, как бот получил ответ от YandexGPT, нужно добавить следующие инлайн-кнопки к отправляющемуся сообщению: 1) Перегенерировать. Отправляет тот же запрос, удаляет текущее сообщение 2) Дополнить запрос. Должен отправлять запрос к YandexGPT с текущим ответом и дополнением пользователя 3) Сохранить ответ - пока просто напиши заглушку. from aiogram import Bot, Dispatcher, executor, types from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup from aiogram.utils.callback_data import CallbackData import aiosqlite import asyncio import aiohttp import json API_TOKEN = '7089345612:AAGMKDRabqD-8IBhkCLpShXpEwYoeGvFwIU' ADMINS = [989037374, 1515567046] bot = Bot(token=API_TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) class Form(StatesGroup): choosing_action = State() answer_question = State() class lk(StatesGroup): personal_account = State() edit_answer = State() new_answer = State() edit_answer_select = State() edit_answer_cb = State() new_answer_cb = State() class admin(StatesGroup): admin_panel = State() select_question_to_delete = State() select_question_to_edit = State() edit_question_text = State() new_question = State() async def create_db(): async with aiosqlite.connect('base.db') as db: await db.execute('''CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, username TEXT NOT NULL, last_question_idx INTEGER DEFAULT 0)''') await db.execute('''CREATE TABLE IF NOT EXISTS questions ( id INTEGER PRIMARY KEY AUTOINCREMENT, question TEXT NOT NULL, order_num INTEGER NOT NULL)''') await db.execute('''CREATE TABLE IF NOT EXISTS answers ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, question TEXT, answer TEXT, FOREIGN KEY (user_id) REFERENCES users (id))''') await db.commit() # Обработка под MarkdownV2 def mdv2(text: str) -> str: escape_chars = [ "_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!" ] for char in escape_chars: text = text.replace(char, f"\{char}") text = text.replace("**", "*").replace('"', '“') return text # калбэки change_action_cb = CallbackData('change', 'action') # КНОПКА МЕНЮ menu = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) menu.add(KeyboardButton("В меню")) async def add_user(user_id: int, username: str): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT id FROM users WHERE id = ?', (user_id,)) user_exists = await cursor.fetchone() if user_exists: await db.execute('UPDATE users SET username = ? WHERE id = ?', (username, user_id)) else: await db.execute('INSERT INTO users (id, username) VALUES (?, ?)', (user_id, username)) await db.commit() @dp.message_handler(commands="start", state="*") async def cmd_start(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) user_id = message.from_user.id username = message.from_user.username or "unknown" await add_user(user_id, username) if user_id not in ADMINS: await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() @dp.message_handler(lambda message: message.text == "В меню", state="*") async def back_to_menu(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) if message.from_user.id not in ADMINS: await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() async def save_answer(user_id: int, question: str, answer: str, question_idx: int): async with aiosqlite.connect('base.db') as db: await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question, answer)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (question_idx, user_id)) await db.commit() async def set_next_question(user_id: int): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() last_question_idx = result[0] if result else 0 next_question_idx = last_question_idx + 1 question_cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (next_question_idx,)) question_text = await question_cursor.fetchone() if question_text: await bot.send_message(user_id, question_text[0], reply_markup=menu) await Form.answer_question.set() await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (next_question_idx, user_id)) await db.commit() else: answers_text = "" cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question} - {answer}\n" markup = InlineKeyboardMarkup( inline_keyboard=[ [InlineKeyboardButton(text="Сгенерировать", callback_data=change_action_cb.new(action="generate"))], [InlineKeyboardButton(text="Изменить ответ", callback_data=change_action_cb.new(action="change"))], [InlineKeyboardButton(text="Заполнить заново", callback_data=change_action_cb.new(action="refill"))], ] ) await bot.send_message(user_id, f"Вот ваши ответы:\n\n{answers_text}", reply_markup=markup) await dp.current_state(user=user_id).reset_state(with_data=False) @dp.callback_query_handler(change_action_cb.filter(action="change"), state="*") async def change_answer(callback_query: types.CallbackQuery, state: FSMContext): await bot.answer_callback_query(callback_query.id) await lk.edit_answer.set() await bot.send_message(callback_query.from_user.id, "Введите номер вопроса, который хотите изменить:") @dp.message_handler(state=lk.edit_answer_cb) async def enter_question_number(message: types.Message, state: FSMContext): question_number = message.text if not question_number.isdigit(): await message.reply("Пожалуйста, введите номер вопроса цифрами. Попробуйте снова:") return await state.update_data(question_number=int(question_number)) await lk.new_answer.set() await message.answer("Введите новый ответ:") @dp.callback_query_handler(change_action_cb.filter(action="refill"), state="*") async def process_refill(callback_query: types.CallbackQuery, callback_data: dict): user_id = callback_query.from_user.id await bot.answer_callback_query(callback_query.id) markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да, начать заново", callback_data="confirm_refill")) await bot.send_message(user_id, "Вы уверены, что хотите начать заново? Ваши текущие ответы будут удалены.", reply_markup=markup) @dp.message_handler(state=lk.new_answer_cb) async def update_answer(message: types.Message, state: FSMContext): new_answer_text = message.text user_data = await state.get_data() question_number = user_data['question_number'] user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer_text, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer_text}", reply_markup=menu) else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Сгенерировать био", state=Form.choosing_action) async def generate_bio(message: types.Message): user_id = message.from_user.id await set_next_question(user_id) @dp.message_handler(state=Form.answer_question) async def process_question_answer(message: types.Message, state: FSMContext): user_id = message.from_user.id answer_text = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() current_question_idx = result[0] if result else 0 cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (current_question_idx,)) question = await cursor.fetchone() if question: question_text = question[0] await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question_text, answer_text)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (current_question_idx, user_id)) await db.commit() else: await message.answer("Произошла ошибка при сохранении вашего ответа.") await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Личный кабинет", state=Form.choosing_action) async def personal_account(message: types.Message): user_id = message.from_user.id answers_text = "Личный кабинет\n\nВаши ответы:\n" async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question, answer FROM answers WHERE user_id=? ORDER BY id', (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question}: {answer}\n" if answers_text == "Личный кабинет\n\nВаши ответы:\n": answers_text = "Личный кабинет\n\nВы еще не отвечали на вопросы. Пожалуйста, нажмите «В меню» и выберите «Сгенерировать био», чтобы ответить на вопросы" await message.answer(answers_text, reply_markup=menu) else: markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) await message.answer(answers_text, reply_markup=markup) await lk.personal_account.set() @dp.message_handler(lambda message: message.text == "Изменить ответ", state=lk.personal_account) async def change_answer(message: types.Message): await message.answer("Введите номер вопроса, на который хотите изменить ответ:",reply_markup=menu) await lk.edit_answer.set() @dp.message_handler(state=lk.edit_answer) async def process_question_number(message: types.Message, state: FSMContext): text = message.text question_number = int(text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await state.update_data(question=question_text[0], question_number=question_number) await message.answer("Введите новый ответ:") await lk.new_answer.set() else: await message.answer(f"Вопроса под номером {question_number} не существует.") @dp.message_handler(state=lk.new_answer) async def process_new_answer(message: types.Message, state: FSMContext): user_data = await state.get_data() question_number = user_data['question_number'] new_answer = message.text markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer}", reply_markup=markup) else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() await personal_account(message) @dp.message_handler(lambda message: message.text == "Заполнить заново", state=lk.personal_account) async def refill_form(message: types.Message): markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да", callback_data="confirm_refill")) await message.answer("Вы уверены, что хотите начать заново? Все текущие ответы будут удалены.", reply_markup=markup) @dp.callback_query_handler(lambda c: c.data == 'confirm_refill', state="*") async def process_refill(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with aiosqlite.connect('base.db') as db: await db.execute('DELETE FROM answers WHERE user_id=?', (user_id,)) await db.commit() await db.execute('UPDATE users SET last_question_idx = 0 WHERE id = ?', (user_id,)) await db.commit() state = dp.current_state(user=user_id) await state.reset_state(with_data=False) await bot.answer_callback_query(callback_query.id) await bot.send_message(user_id, "Ваши ответы удалены.") await cmd_start(callback_query.message) # ГЕНЕРАЦИЯ class YandexGPT: @staticmethod async def generate(prompt: str, apikey: str, sa_id: str, user_id : str): url = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion' headers = { 'Content-Type': 'application/json', 'Authorization': f'Api-Key {apikey}' } data = { "modelUri": f"gpt://{sa_id}/yandexgpt-lite/latest", "completionOptions": { "stream": False, "temperature": 0.6, "maxTokens": "1000" }, "messages": [ { "role": "system", "text": "Твоя задача - создать небольшой текст о биографии человека в соответствии с следующими ответами на вопросы (пишется вопрос? ответ). Также напиши короткую эпитафию в соответствии с биографией. Свой ответ пиши только по шаблону:\nБиография:\n\nЭпитафий:\n\nБиография должна быть не сильно длинной, но интересной. Если биография очевидно неправильная (ответы на вопросы невозможно распознать), то пиши: Извините, я не понял ваш запрос. Попробуйте ответить на вопросы еще раз. " }, { "role": "user", "text": prompt } ] } async with aiohttp.ClientSession() as session: async with session.post(url, json=data, headers=headers) as response: response_data = await response.json() try: answer = response_data['result']['alternatives'][0]['message']['text'] await bot.send_message(user_id, mdv2(answer), parse_mode="MarkdownV2") except KeyError as e: await bot.send_message(user_id, "Не удалось получить ответ от сервера. Проверьте переданные данные и попробуйте еще раз.") @dp.callback_query_handler(change_action_cb.filter(action="generate"), state="*") async def process_generate(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id prompt = "" async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,)) answers = await cursor.fetchall() for question, answer in answers: prompt += f"\n{question} - {answer}" api_key = "AQVN1J4sCxYR98rj-tVppyp6gXQthbdmYvmgtO7a" sa_id = "b1g5og37bgh1ghh2s2qc" await YandexGPT.generate(prompt, api_key, sa_id, user_id) # АДМИН-ПАНЕЛЬ # КНОПКА НАЗАД back = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False) back.add(KeyboardButton("Назад")) # КЛАВА admin_kb = ReplyKeyboardMarkup(resize_keyboard=True) admin_kb.add("Вопросы", "Добавить", "Удалить", "Редактировать","В меню") @dp.message_handler(lambda message: message.text == "Назад", state=[admin.new_question, admin.edit_question_text, admin.select_question_to_edit, admin.select_question_to_delete]) async def back_to_admin_panel(message: types.Message, state: FSMContext): await state.finish() await admin_panel(message) @dp.message_handler(lambda message: message.text == "Админ-панель", state=Form.choosing_action) async def admin_panel(message: types.Message): if message.from_user.id not in ADMINS: await message.answer("Доступ запрещен.") return await message.answer("Админ-панель:", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Вопросы", state=admin.admin_panel) async def show_questions(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if questions: text = "\n".join([f"{idx + 1}. {question[0]}" for idx, question in enumerate(questions)]) else: text = "Вопросы отсутствуют." await message.answer(text) @dp.message_handler(lambda message: message.text == "Добавить", state=admin.admin_panel) async def add_question_start(message: types.Message): await message.answer("Введите текст нового вопроса:", reply_markup=back) await admin.new_question.set() @dp.message_handler(state=admin.new_question) async def add_question_process(message: types.Message, state: FSMContext): new_question = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT MAX(order_num) FROM questions") max_order_num = await cursor.fetchone() next_order_num = (max_order_num[0] or 0) + 1 await db.execute("INSERT INTO questions (question, order_num) VALUES (?, ?)", (new_question, next_order_num)) await db.commit() await message.answer("Вопрос успешно добавлен.", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Редактировать", state=admin.admin_panel) async def select_question_to_edit_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для редактирования:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_edit.set() @dp.message_handler(state=admin.select_question_to_edit) async def edit_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with state.proxy() as data: data['question_id'] = qid await admin.edit_question_text.set() await message.answer("Введите новый текст вопроса:", reply_markup=back) @dp.message_handler(state=admin.edit_question_text) async def update_question(message: types.Message, state: FSMContext): new_text = message.text async with state.proxy() as data: qid = data['question_id'] async with aiosqlite.connect('base.db') as db: await db.execute("UPDATE questions SET question = ? WHERE id = ?", (new_text, qid)) await db.commit() await message.answer("Вопрос успешно отредактирован.", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Удалить", state=admin.admin_panel) async def select_question_to_delete_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для удаления:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_delete.set() @dp.message_handler(state=admin.select_question_to_delete) async def delete_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT order_num FROM questions WHERE id = ?", (qid,)) question = await cursor.fetchone() if not question: await message.answer(f"Вопрос под номером {qid} не найден. Пожалуйста, попробуйте другой номер.") return order_num_to_delete = question[0] await db.execute("DELETE FROM questions WHERE id = ?", (qid,)) await db.execute("UPDATE questions SET order_num = order_num - 1 WHERE order_num > ?", (order_num_to_delete,)) await db.commit() await message.answer("Вопрос успешно удален.", reply_markup=admin_kb) await admin.admin_panel.set() async def main(): await create_db() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) executor.start_polling(dp, skip_updates=True)
3fe633eb579262433652fc7656af6dc8
{ "intermediate": 0.2672380208969116, "beginner": 0.5421361923217773, "expert": 0.19062583148479462 }
46,405
Привет! Нужно дополнить код бота. После того, как бот обратился к YandexGPT и текст отправлен человеку, его автоматически надо сохранить в БД Привет! Помоги мне добавить несколько нововведений в бота. После того, как бот получил ответ от YandexGPT, нужно добавить следующие инлайн-кнопки к отправляющемуся сообщению: 1) Перегенерировать. Отправляет тот же запрос, удаляет текущее сообщение 2) Дополнить запрос. Должен отправлять запрос к YandexGPT с текущим ответом и дополнением пользователя 3) Сохранить ответ - пока просто напиши заглушку. from aiogram import Bot, Dispatcher, executor, types from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup from aiogram.utils.callback_data import CallbackData import aiosqlite import asyncio import aiohttp import json API_TOKEN = '7089345612:AAGMKDRabqD-8IBhkCLpShXpEwYoeGvFwIU' ADMINS = [989037374, 1515567046] bot = Bot(token=API_TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) class Form(StatesGroup): choosing_action = State() answer_question = State() class lk(StatesGroup): personal_account = State() edit_answer = State() new_answer = State() edit_answer_select = State() edit_answer_cb = State() new_answer_cb = State() class admin(StatesGroup): admin_panel = State() select_question_to_delete = State() select_question_to_edit = State() edit_question_text = State() new_question = State() async def create_db(): async with aiosqlite.connect('base.db') as db: await db.execute('''CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, username TEXT NOT NULL, last_question_idx INTEGER DEFAULT 0)''') await db.execute('''CREATE TABLE IF NOT EXISTS questions ( id INTEGER PRIMARY KEY AUTOINCREMENT, question TEXT NOT NULL, order_num INTEGER NOT NULL)''') await db.execute('''CREATE TABLE IF NOT EXISTS answers ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, question TEXT, answer TEXT, FOREIGN KEY (user_id) REFERENCES users (id))''') await db.commit() # Обработка под MarkdownV2 def mdv2(text: str) -> str: escape_chars = [ "_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!" ] for char in escape_chars: text = text.replace(char, f"\{char}") text = text.replace("**", "*").replace('"', '“') return text # калбэки change_action_cb = CallbackData('change', 'action') # КНОПКА МЕНЮ menu = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) menu.add(KeyboardButton("В меню")) async def add_user(user_id: int, username: str): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT id FROM users WHERE id = ?', (user_id,)) user_exists = await cursor.fetchone() if user_exists: await db.execute('UPDATE users SET username = ? WHERE id = ?', (username, user_id)) else: await db.execute('INSERT INTO users (id, username) VALUES (?, ?)', (user_id, username)) await db.commit() @dp.message_handler(commands="start", state="*") async def cmd_start(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) user_id = message.from_user.id username = message.from_user.username or "unknown" await add_user(user_id, username) if user_id not in ADMINS: await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() @dp.message_handler(lambda message: message.text == "В меню", state="*") async def back_to_menu(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) if message.from_user.id not in ADMINS: await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() async def save_answer(user_id: int, question: str, answer: str, question_idx: int): async with aiosqlite.connect('base.db') as db: await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question, answer)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (question_idx, user_id)) await db.commit() async def set_next_question(user_id: int): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() last_question_idx = result[0] if result else 0 next_question_idx = last_question_idx + 1 question_cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (next_question_idx,)) question_text = await question_cursor.fetchone() if question_text: await bot.send_message(user_id, question_text[0], reply_markup=menu) await Form.answer_question.set() await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (next_question_idx, user_id)) await db.commit() else: answers_text = "" cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question} - {answer}\n" markup = InlineKeyboardMarkup( inline_keyboard=[ [InlineKeyboardButton(text="Сгенерировать", callback_data=change_action_cb.new(action="generate"))], [InlineKeyboardButton(text="Изменить ответ", callback_data=change_action_cb.new(action="change"))], [InlineKeyboardButton(text="Заполнить заново", callback_data=change_action_cb.new(action="refill"))], ] ) await bot.send_message(user_id, f"Вот ваши ответы:\n\n{answers_text}", reply_markup=markup) await dp.current_state(user=user_id).reset_state(with_data=False) @dp.callback_query_handler(change_action_cb.filter(action="change"), state="*") async def change_answer(callback_query: types.CallbackQuery, state: FSMContext): await bot.answer_callback_query(callback_query.id) await lk.edit_answer.set() await bot.send_message(callback_query.from_user.id, "Введите номер вопроса, который хотите изменить:") @dp.message_handler(state=lk.edit_answer_cb) async def enter_question_number(message: types.Message, state: FSMContext): question_number = message.text if not question_number.isdigit(): await message.reply("Пожалуйста, введите номер вопроса цифрами. Попробуйте снова:") return await state.update_data(question_number=int(question_number)) await lk.new_answer.set() await message.answer("Введите новый ответ:") @dp.callback_query_handler(change_action_cb.filter(action="refill"), state="*") async def process_refill(callback_query: types.CallbackQuery, callback_data: dict): user_id = callback_query.from_user.id await bot.answer_callback_query(callback_query.id) markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да, начать заново", callback_data="confirm_refill")) await bot.send_message(user_id, "Вы уверены, что хотите начать заново? Ваши текущие ответы будут удалены.", reply_markup=markup) @dp.message_handler(state=lk.new_answer_cb) async def update_answer(message: types.Message, state: FSMContext): new_answer_text = message.text user_data = await state.get_data() question_number = user_data['question_number'] user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer_text, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer_text}", reply_markup=menu) else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Сгенерировать био", state=Form.choosing_action) async def generate_bio(message: types.Message): user_id = message.from_user.id await set_next_question(user_id) @dp.message_handler(state=Form.answer_question) async def process_question_answer(message: types.Message, state: FSMContext): user_id = message.from_user.id answer_text = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() current_question_idx = result[0] if result else 0 cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (current_question_idx,)) question = await cursor.fetchone() if question: question_text = question[0] await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question_text, answer_text)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (current_question_idx, user_id)) await db.commit() else: await message.answer("Произошла ошибка при сохранении вашего ответа.") await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Личный кабинет", state=Form.choosing_action) async def personal_account(message: types.Message): user_id = message.from_user.id answers_text = "Личный кабинет\n\nВаши ответы:\n" async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question, answer FROM answers WHERE user_id=? ORDER BY id', (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question}: {answer}\n" if answers_text == "Личный кабинет\n\nВаши ответы:\n": answers_text = "Личный кабинет\n\nВы еще не отвечали на вопросы. Пожалуйста, нажмите «В меню» и выберите «Сгенерировать био», чтобы ответить на вопросы" await message.answer(answers_text, reply_markup=menu) else: markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) await message.answer(answers_text, reply_markup=markup) await lk.personal_account.set() @dp.message_handler(lambda message: message.text == "Изменить ответ", state=lk.personal_account) async def change_answer(message: types.Message): await message.answer("Введите номер вопроса, на который хотите изменить ответ:",reply_markup=menu) await lk.edit_answer.set() @dp.message_handler(state=lk.edit_answer) async def process_question_number(message: types.Message, state: FSMContext): text = message.text question_number = int(text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await state.update_data(question=question_text[0], question_number=question_number) await message.answer("Введите новый ответ:") await lk.new_answer.set() else: await message.answer(f"Вопроса под номером {question_number} не существует.") @dp.message_handler(state=lk.new_answer) async def process_new_answer(message: types.Message, state: FSMContext): user_data = await state.get_data() question_number = user_data['question_number'] new_answer = message.text markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer}", reply_markup=markup) else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() await personal_account(message) @dp.message_handler(lambda message: message.text == "Заполнить заново", state=lk.personal_account) async def refill_form(message: types.Message): markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да", callback_data="confirm_refill")) await message.answer("Вы уверены, что хотите начать заново? Все текущие ответы будут удалены.", reply_markup=markup) @dp.callback_query_handler(lambda c: c.data == 'confirm_refill', state="*") async def process_refill(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with aiosqlite.connect('base.db') as db: await db.execute('DELETE FROM answers WHERE user_id=?', (user_id,)) await db.commit() await db.execute('UPDATE users SET last_question_idx = 0 WHERE id = ?', (user_id,)) await db.commit() state = dp.current_state(user=user_id) await state.reset_state(with_data=False) await bot.answer_callback_query(callback_query.id) await bot.send_message(user_id, "Ваши ответы удалены.") await cmd_start(callback_query.message) # ГЕНЕРАЦИЯ class YandexGPT: @staticmethod async def generate(prompt: str, apikey: str, sa_id: str, user_id : str): url = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion' headers = { 'Content-Type': 'application/json', 'Authorization': f'Api-Key {apikey}' } data = { "modelUri": f"gpt://{sa_id}/yandexgpt-lite/latest", "completionOptions": { "stream": False, "temperature": 0.6, "maxTokens": "1000" }, "messages": [ { "role": "system", "text": "Твоя задача - создать небольшой текст о биографии человека в соответствии с следующими ответами на вопросы (пишется вопрос? ответ). Также напиши короткую эпитафию в соответствии с биографией. Свой ответ пиши только по шаблону:\nБиография:\n\nЭпитафий:\n\nБиография должна быть не сильно длинной, но интересной. Если биография очевидно неправильная (ответы на вопросы невозможно распознать), то пиши: Извините, я не понял ваш запрос. Попробуйте ответить на вопросы еще раз. " }, { "role": "user", "text": prompt } ] } async with aiohttp.ClientSession() as session: async with session.post(url, json=data, headers=headers) as response: response_data = await response.json() try: answer = response_data['result']['alternatives'][0]['message']['text'] await bot.send_message(user_id, mdv2(answer), parse_mode="MarkdownV2") except KeyError as e: await bot.send_message(user_id, "Не удалось получить ответ от сервера. Проверьте переданные данные и попробуйте еще раз.") @dp.callback_query_handler(change_action_cb.filter(action="generate"), state="*") async def process_generate(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id prompt = "" async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,)) answers = await cursor.fetchall() for question, answer in answers: prompt += f"\n{question} - {answer}" api_key = "AQVN1J4sCxYR98rj-tVppyp6gXQthbdmYvmgtO7a" sa_id = "b1g5og37bgh1ghh2s2qc" await YandexGPT.generate(prompt, api_key, sa_id, user_id) # АДМИН-ПАНЕЛЬ # КНОПКА НАЗАД back = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False) back.add(KeyboardButton("Назад")) # КЛАВА admin_kb = ReplyKeyboardMarkup(resize_keyboard=True) admin_kb.add("Вопросы", "Добавить", "Удалить", "Редактировать","В меню") @dp.message_handler(lambda message: message.text == "Назад", state=[admin.new_question, admin.edit_question_text, admin.select_question_to_edit, admin.select_question_to_delete]) async def back_to_admin_panel(message: types.Message, state: FSMContext): await state.finish() await admin_panel(message) @dp.message_handler(lambda message: message.text == "Админ-панель", state=Form.choosing_action) async def admin_panel(message: types.Message): if message.from_user.id not in ADMINS: await message.answer("Доступ запрещен.") return await message.answer("Админ-панель:", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Вопросы", state=admin.admin_panel) async def show_questions(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if questions: text = "\n".join([f"{idx + 1}. {question[0]}" for idx, question in enumerate(questions)]) else: text = "Вопросы отсутствуют." await message.answer(text) @dp.message_handler(lambda message: message.text == "Добавить", state=admin.admin_panel) async def add_question_start(message: types.Message): await message.answer("Введите текст нового вопроса:", reply_markup=back) await admin.new_question.set() @dp.message_handler(state=admin.new_question) async def add_question_process(message: types.Message, state: FSMContext): new_question = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT MAX(order_num) FROM questions") max_order_num = await cursor.fetchone() next_order_num = (max_order_num[0] or 0) + 1 await db.execute("INSERT INTO questions (question, order_num) VALUES (?, ?)", (new_question, next_order_num)) await db.commit() await message.answer("Вопрос успешно добавлен.", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Редактировать", state=admin.admin_panel) async def select_question_to_edit_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для редактирования:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_edit.set() @dp.message_handler(state=admin.select_question_to_edit) async def edit_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with state.proxy() as data: data['question_id'] = qid await admin.edit_question_text.set() await message.answer("Введите новый текст вопроса:", reply_markup=back) @dp.message_handler(state=admin.edit_question_text) async def update_question(message: types.Message, state: FSMContext): new_text = message.text async with state.proxy() as data: qid = data['question_id'] async with aiosqlite.connect('base.db') as db: await db.execute("UPDATE questions SET question = ? WHERE id = ?", (new_text, qid)) await db.commit() await message.answer("Вопрос успешно отредактирован.", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Удалить", state=admin.admin_panel) async def select_question_to_delete_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для удаления:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_delete.set() @dp.message_handler(state=admin.select_question_to_delete) async def delete_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT order_num FROM questions WHERE id = ?", (qid,)) question = await cursor.fetchone() if not question: await message.answer(f"Вопрос под номером {qid} не найден. Пожалуйста, попробуйте другой номер.") return order_num_to_delete = question[0] await db.execute("DELETE FROM questions WHERE id = ?", (qid,)) await db.execute("UPDATE questions SET order_num = order_num - 1 WHERE order_num > ?", (order_num_to_delete,)) await db.commit() await message.answer("Вопрос успешно удален.", reply_markup=admin_kb) await admin.admin_panel.set() async def main(): await create_db() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) executor.start_polling(dp, skip_updates=True)
a8d65560b4b7032ef5b9f286382ac03b
{ "intermediate": 0.3222064971923828, "beginner": 0.5616750121116638, "expert": 0.11611843854188919 }
46,406
Привет! Нужно дополнить код бота. После того, как бот обратился к YandexGPT и текст отправлен человеку, его автоматически надо сохранить в БД from aiogram import Bot, Dispatcher, executor, types from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup from aiogram.utils.callback_data import CallbackData import aiosqlite import asyncio import aiohttp import json API_TOKEN = '7089345612:AAGMKDRabqD-8IBhkCLpShXpEwYoeGvFwIU' ADMINS = [989037374, 1515567046] bot = Bot(token=API_TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) class Form(StatesGroup): choosing_action = State() answer_question = State() class lk(StatesGroup): personal_account = State() edit_answer = State() new_answer = State() edit_answer_select = State() edit_answer_cb = State() new_answer_cb = State() class admin(StatesGroup): admin_panel = State() select_question_to_delete = State() select_question_to_edit = State() edit_question_text = State() new_question = State() async def create_db(): async with aiosqlite.connect('base.db') as db: await db.execute('''CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, username TEXT NOT NULL, last_question_idx INTEGER DEFAULT 0)''') await db.execute('''CREATE TABLE IF NOT EXISTS questions ( id INTEGER PRIMARY KEY AUTOINCREMENT, question TEXT NOT NULL, order_num INTEGER NOT NULL)''') await db.execute('''CREATE TABLE IF NOT EXISTS answers ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, question TEXT, answer TEXT, FOREIGN KEY (user_id) REFERENCES users (id))''') await db.commit() # Обработка под MarkdownV2 def mdv2(text: str) -> str: escape_chars = [ "_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!" ] for char in escape_chars: text = text.replace(char, f"\{char}") text = text.replace("**", "*").replace('"', '“') return text # калбэки change_action_cb = CallbackData('change', 'action') # КНОПКА МЕНЮ menu = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) menu.add(KeyboardButton("В меню")) async def add_user(user_id: int, username: str): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT id FROM users WHERE id = ?', (user_id,)) user_exists = await cursor.fetchone() if user_exists: await db.execute('UPDATE users SET username = ? WHERE id = ?', (username, user_id)) else: await db.execute('INSERT INTO users (id, username) VALUES (?, ?)', (user_id, username)) await db.commit() @dp.message_handler(commands="start", state="*") async def cmd_start(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) user_id = message.from_user.id username = message.from_user.username or "unknown" await add_user(user_id, username) if user_id not in ADMINS: await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() @dp.message_handler(lambda message: message.text == "В меню", state="*") async def back_to_menu(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) if message.from_user.id not in ADMINS: await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() async def save_answer(user_id: int, question: str, answer: str, question_idx: int): async with aiosqlite.connect('base.db') as db: await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question, answer)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (question_idx, user_id)) await db.commit() async def set_next_question(user_id: int): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() last_question_idx = result[0] if result else 0 next_question_idx = last_question_idx + 1 question_cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (next_question_idx,)) question_text = await question_cursor.fetchone() if question_text: await bot.send_message(user_id, question_text[0], reply_markup=menu) await Form.answer_question.set() await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (next_question_idx, user_id)) await db.commit() else: answers_text = "" cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question} - {answer}\n" markup = InlineKeyboardMarkup( inline_keyboard=[ [InlineKeyboardButton(text="Сгенерировать", callback_data=change_action_cb.new(action="generate"))], [InlineKeyboardButton(text="Изменить ответ", callback_data=change_action_cb.new(action="change"))], [InlineKeyboardButton(text="Заполнить заново", callback_data=change_action_cb.new(action="refill"))], ] ) await bot.send_message(user_id, f"Вот ваши ответы:\n\n{answers_text}", reply_markup=markup) await dp.current_state(user=user_id).reset_state(with_data=False) @dp.callback_query_handler(change_action_cb.filter(action="change"), state="*") async def change_answer(callback_query: types.CallbackQuery, state: FSMContext): await bot.answer_callback_query(callback_query.id) await lk.edit_answer.set() await bot.send_message(callback_query.from_user.id, "Введите номер вопроса, который хотите изменить:") @dp.message_handler(state=lk.edit_answer_cb) async def enter_question_number(message: types.Message, state: FSMContext): question_number = message.text if not question_number.isdigit(): await message.reply("Пожалуйста, введите номер вопроса цифрами. Попробуйте снова:") return await state.update_data(question_number=int(question_number)) await lk.new_answer.set() await message.answer("Введите новый ответ:") @dp.callback_query_handler(change_action_cb.filter(action="refill"), state="*") async def process_refill(callback_query: types.CallbackQuery, callback_data: dict): user_id = callback_query.from_user.id await bot.answer_callback_query(callback_query.id) markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да, начать заново", callback_data="confirm_refill")) await bot.send_message(user_id, "Вы уверены, что хотите начать заново? Ваши текущие ответы будут удалены.", reply_markup=markup) @dp.message_handler(state=lk.new_answer_cb) async def update_answer(message: types.Message, state: FSMContext): new_answer_text = message.text user_data = await state.get_data() question_number = user_data['question_number'] user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer_text, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer_text}", reply_markup=menu) else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Сгенерировать био", state=Form.choosing_action) async def generate_bio(message: types.Message): user_id = message.from_user.id await set_next_question(user_id) @dp.message_handler(state=Form.answer_question) async def process_question_answer(message: types.Message, state: FSMContext): user_id = message.from_user.id answer_text = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() current_question_idx = result[0] if result else 0 cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (current_question_idx,)) question = await cursor.fetchone() if question: question_text = question[0] await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question_text, answer_text)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (current_question_idx, user_id)) await db.commit() else: await message.answer("Произошла ошибка при сохранении вашего ответа.") await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Личный кабинет", state=Form.choosing_action) async def personal_account(message: types.Message): user_id = message.from_user.id answers_text = "Личный кабинет\n\nВаши ответы:\n" async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question, answer FROM answers WHERE user_id=? ORDER BY id', (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question}: {answer}\n" if answers_text == "Личный кабинет\n\nВаши ответы:\n": answers_text = "Личный кабинет\n\nВы еще не отвечали на вопросы. Пожалуйста, нажмите «В меню» и выберите «Сгенерировать био», чтобы ответить на вопросы" await message.answer(answers_text, reply_markup=menu) else: markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) await message.answer(answers_text, reply_markup=markup) await lk.personal_account.set() @dp.message_handler(lambda message: message.text == "Изменить ответ", state=lk.personal_account) async def change_answer(message: types.Message): await message.answer("Введите номер вопроса, на который хотите изменить ответ:",reply_markup=menu) await lk.edit_answer.set() @dp.message_handler(state=lk.edit_answer) async def process_question_number(message: types.Message, state: FSMContext): text = message.text question_number = int(text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await state.update_data(question=question_text[0], question_number=question_number) await message.answer("Введите новый ответ:") await lk.new_answer.set() else: await message.answer(f"Вопроса под номером {question_number} не существует.") @dp.message_handler(state=lk.new_answer) async def process_new_answer(message: types.Message, state: FSMContext): user_data = await state.get_data() question_number = user_data['question_number'] new_answer = message.text markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer}", reply_markup=markup) else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() await personal_account(message) @dp.message_handler(lambda message: message.text == "Заполнить заново", state=lk.personal_account) async def refill_form(message: types.Message): markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да", callback_data="confirm_refill")) await message.answer("Вы уверены, что хотите начать заново? Все текущие ответы будут удалены.", reply_markup=markup) @dp.callback_query_handler(lambda c: c.data == 'confirm_refill', state="*") async def process_refill(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with aiosqlite.connect('base.db') as db: await db.execute('DELETE FROM answers WHERE user_id=?', (user_id,)) await db.commit() await db.execute('UPDATE users SET last_question_idx = 0 WHERE id = ?', (user_id,)) await db.commit() state = dp.current_state(user=user_id) await state.reset_state(with_data=False) await bot.answer_callback_query(callback_query.id) await bot.send_message(user_id, "Ваши ответы удалены.") await cmd_start(callback_query.message) # ГЕНЕРАЦИЯ class YandexGPT: @staticmethod async def generate(prompt: str, apikey: str, sa_id: str, user_id : str): url = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion' headers = { 'Content-Type': 'application/json', 'Authorization': f'Api-Key {apikey}' } data = { "modelUri": f"gpt://{sa_id}/yandexgpt-lite/latest", "completionOptions": { "stream": False, "temperature": 0.6, "maxTokens": "1000" }, "messages": [ { "role": "system", "text": "Твоя задача - создать небольшой текст о биографии человека в соответствии с следующими ответами на вопросы (пишется вопрос? ответ). Также напиши короткую эпитафию в соответствии с биографией. Свой ответ пиши только по шаблону:\nБиография:\n\nЭпитафий:\n\nБиография должна быть не сильно длинной, но интересной. Если биография очевидно неправильная (ответы на вопросы невозможно распознать), то пиши: Извините, я не понял ваш запрос. Попробуйте ответить на вопросы еще раз. " }, { "role": "user", "text": prompt } ] } async with aiohttp.ClientSession() as session: async with session.post(url, json=data, headers=headers) as response: response_data = await response.json() try: answer = response_data['result']['alternatives'][0]['message']['text'] await bot.send_message(user_id, mdv2(answer), parse_mode="MarkdownV2") except KeyError as e: await bot.send_message(user_id, "Не удалось получить ответ от сервера. Проверьте переданные данные и попробуйте еще раз.") @dp.callback_query_handler(change_action_cb.filter(action="generate"), state="*") async def process_generate(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id prompt = "" async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,)) answers = await cursor.fetchall() for question, answer in answers: prompt += f"\n{question} - {answer}" api_key = "AQVN1J4sCxYR98rj-tVppyp6gXQthbdmYvmgtO7a" sa_id = "b1g5og37bgh1ghh2s2qc" await YandexGPT.generate(prompt, api_key, sa_id, user_id) # АДМИН-ПАНЕЛЬ # КНОПКА НАЗАД back = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False) back.add(KeyboardButton("Назад")) # КЛАВА admin_kb = ReplyKeyboardMarkup(resize_keyboard=True) admin_kb.add("Вопросы", "Добавить", "Удалить", "Редактировать","В меню") @dp.message_handler(lambda message: message.text == "Назад", state=[admin.new_question, admin.edit_question_text, admin.select_question_to_edit, admin.select_question_to_delete]) async def back_to_admin_panel(message: types.Message, state: FSMContext): await state.finish() await admin_panel(message) @dp.message_handler(lambda message: message.text == "Админ-панель", state=Form.choosing_action) async def admin_panel(message: types.Message): if message.from_user.id not in ADMINS: await message.answer("Доступ запрещен.") return await message.answer("Админ-панель:", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Вопросы", state=admin.admin_panel) async def show_questions(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if questions: text = "\n".join([f"{idx + 1}. {question[0]}" for idx, question in enumerate(questions)]) else: text = "Вопросы отсутствуют." await message.answer(text) @dp.message_handler(lambda message: message.text == "Добавить", state=admin.admin_panel) async def add_question_start(message: types.Message): await message.answer("Введите текст нового вопроса:", reply_markup=back) await admin.new_question.set() @dp.message_handler(state=admin.new_question) async def add_question_process(message: types.Message, state: FSMContext): new_question = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT MAX(order_num) FROM questions") max_order_num = await cursor.fetchone() next_order_num = (max_order_num[0] or 0) + 1 await db.execute("INSERT INTO questions (question, order_num) VALUES (?, ?)", (new_question, next_order_num)) await db.commit() await message.answer("Вопрос успешно добавлен.", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Редактировать", state=admin.admin_panel) async def select_question_to_edit_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для редактирования:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_edit.set() @dp.message_handler(state=admin.select_question_to_edit) async def edit_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with state.proxy() as data: data['question_id'] = qid await admin.edit_question_text.set() await message.answer("Введите новый текст вопроса:", reply_markup=back) @dp.message_handler(state=admin.edit_question_text) async def update_question(message: types.Message, state: FSMContext): new_text = message.text async with state.proxy() as data: qid = data['question_id'] async with aiosqlite.connect('base.db') as db: await db.execute("UPDATE questions SET question = ? WHERE id = ?", (new_text, qid)) await db.commit() await message.answer("Вопрос успешно отредактирован.", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Удалить", state=admin.admin_panel) async def select_question_to_delete_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для удаления:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_delete.set() @dp.message_handler(state=admin.select_question_to_delete) async def delete_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT order_num FROM questions WHERE id = ?", (qid,)) question = await cursor.fetchone() if not question: await message.answer(f"Вопрос под номером {qid} не найден. Пожалуйста, попробуйте другой номер.") return order_num_to_delete = question[0] await db.execute("DELETE FROM questions WHERE id = ?", (qid,)) await db.execute("UPDATE questions SET order_num = order_num - 1 WHERE order_num > ?", (order_num_to_delete,)) await db.commit() await message.answer("Вопрос успешно удален.", reply_markup=admin_kb) await admin.admin_panel.set() async def main(): await create_db() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) executor.start_polling(dp, skip_updates=True)
914b3ea6682497965c205b723924a303
{ "intermediate": 0.21273189783096313, "beginner": 0.7239773869514465, "expert": 0.06329073756933212 }
46,407
Привет! Нужно дополнить код бота. После того, как бот обратился к YandexGPT и текст отправлен человеку, его автоматически надо сохранить в БД в столбец "biography" в таблице users. Это тоже надо создать. from aiogram import Bot, Dispatcher, executor, types from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup from aiogram.utils.callback_data import CallbackData import aiosqlite import asyncio import aiohttp import json API_TOKEN = '7089345612:AAGMKDRabqD-8IBhkCLpShXpEwYoeGvFwIU' ADMINS = [989037374, 1515567046] bot = Bot(token=API_TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) class Form(StatesGroup): choosing_action = State() answer_question = State() class lk(StatesGroup): personal_account = State() edit_answer = State() new_answer = State() edit_answer_select = State() edit_answer_cb = State() new_answer_cb = State() class admin(StatesGroup): admin_panel = State() select_question_to_delete = State() select_question_to_edit = State() edit_question_text = State() new_question = State() async def create_db(): async with aiosqlite.connect('base.db') as db: await db.execute('''CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, username TEXT NOT NULL, last_question_idx INTEGER DEFAULT 0)''') await db.execute('''CREATE TABLE IF NOT EXISTS questions ( id INTEGER PRIMARY KEY AUTOINCREMENT, question TEXT NOT NULL, order_num INTEGER NOT NULL)''') await db.execute('''CREATE TABLE IF NOT EXISTS answers ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, question TEXT, answer TEXT, FOREIGN KEY (user_id) REFERENCES users (id))''') await db.commit() # Обработка под MarkdownV2 def mdv2(text: str) -> str: escape_chars = [ "_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!" ] for char in escape_chars: text = text.replace(char, f"\{char}") text = text.replace("**", "*").replace('"', '“') return text # калбэки change_action_cb = CallbackData('change', 'action') # КНОПКА МЕНЮ menu = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) menu.add(KeyboardButton("В меню")) async def add_user(user_id: int, username: str): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT id FROM users WHERE id = ?', (user_id,)) user_exists = await cursor.fetchone() if user_exists: await db.execute('UPDATE users SET username = ? WHERE id = ?', (username, user_id)) else: await db.execute('INSERT INTO users (id, username) VALUES (?, ?)', (user_id, username)) await db.commit() @dp.message_handler(commands="start", state="*") async def cmd_start(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) user_id = message.from_user.id username = message.from_user.username or "unknown" await add_user(user_id, username) if user_id not in ADMINS: await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() @dp.message_handler(lambda message: message.text == "В меню", state="*") async def back_to_menu(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) if message.from_user.id not in ADMINS: await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() async def save_answer(user_id: int, question: str, answer: str, question_idx: int): async with aiosqlite.connect('base.db') as db: await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question, answer)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (question_idx, user_id)) await db.commit() async def set_next_question(user_id: int): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() last_question_idx = result[0] if result else 0 next_question_idx = last_question_idx + 1 question_cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (next_question_idx,)) question_text = await question_cursor.fetchone() if question_text: await bot.send_message(user_id, question_text[0], reply_markup=menu) await Form.answer_question.set() await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (next_question_idx, user_id)) await db.commit() else: answers_text = "" cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question} - {answer}\n" markup = InlineKeyboardMarkup( inline_keyboard=[ [InlineKeyboardButton(text="Сгенерировать", callback_data=change_action_cb.new(action="generate"))], [InlineKeyboardButton(text="Изменить ответ", callback_data=change_action_cb.new(action="change"))], [InlineKeyboardButton(text="Заполнить заново", callback_data=change_action_cb.new(action="refill"))], ] ) await bot.send_message(user_id, f"Вот ваши ответы:\n\n{answers_text}", reply_markup=markup) await dp.current_state(user=user_id).reset_state(with_data=False) @dp.callback_query_handler(change_action_cb.filter(action="change"), state="*") async def change_answer(callback_query: types.CallbackQuery, state: FSMContext): await bot.answer_callback_query(callback_query.id) await lk.edit_answer.set() await bot.send_message(callback_query.from_user.id, "Введите номер вопроса, который хотите изменить:") @dp.message_handler(state=lk.edit_answer_cb) async def enter_question_number(message: types.Message, state: FSMContext): question_number = message.text if not question_number.isdigit(): await message.reply("Пожалуйста, введите номер вопроса цифрами. Попробуйте снова:") return await state.update_data(question_number=int(question_number)) await lk.new_answer.set() await message.answer("Введите новый ответ:") @dp.callback_query_handler(change_action_cb.filter(action="refill"), state="*") async def process_refill(callback_query: types.CallbackQuery, callback_data: dict): user_id = callback_query.from_user.id await bot.answer_callback_query(callback_query.id) markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да, начать заново", callback_data="confirm_refill")) await bot.send_message(user_id, "Вы уверены, что хотите начать заново? Ваши текущие ответы будут удалены.", reply_markup=markup) @dp.message_handler(state=lk.new_answer_cb) async def update_answer(message: types.Message, state: FSMContext): new_answer_text = message.text user_data = await state.get_data() question_number = user_data['question_number'] user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer_text, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer_text}", reply_markup=menu) else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Сгенерировать био", state=Form.choosing_action) async def generate_bio(message: types.Message): user_id = message.from_user.id await set_next_question(user_id) @dp.message_handler(state=Form.answer_question) async def process_question_answer(message: types.Message, state: FSMContext): user_id = message.from_user.id answer_text = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() current_question_idx = result[0] if result else 0 cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (current_question_idx,)) question = await cursor.fetchone() if question: question_text = question[0] await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question_text, answer_text)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (current_question_idx, user_id)) await db.commit() else: await message.answer("Произошла ошибка при сохранении вашего ответа.") await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Личный кабинет", state=Form.choosing_action) async def personal_account(message: types.Message): user_id = message.from_user.id answers_text = "Личный кабинет\n\nВаши ответы:\n" async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question, answer FROM answers WHERE user_id=? ORDER BY id', (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question}: {answer}\n" if answers_text == "Личный кабинет\n\nВаши ответы:\n": answers_text = "Личный кабинет\n\nВы еще не отвечали на вопросы. Пожалуйста, нажмите «В меню» и выберите «Сгенерировать био», чтобы ответить на вопросы" await message.answer(answers_text, reply_markup=menu) else: markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) await message.answer(answers_text, reply_markup=markup) await lk.personal_account.set() @dp.message_handler(lambda message: message.text == "Изменить ответ", state=lk.personal_account) async def change_answer(message: types.Message): await message.answer("Введите номер вопроса, на который хотите изменить ответ:",reply_markup=menu) await lk.edit_answer.set() @dp.message_handler(state=lk.edit_answer) async def process_question_number(message: types.Message, state: FSMContext): text = message.text question_number = int(text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await state.update_data(question=question_text[0], question_number=question_number) await message.answer("Введите новый ответ:") await lk.new_answer.set() else: await message.answer(f"Вопроса под номером {question_number} не существует.") @dp.message_handler(state=lk.new_answer) async def process_new_answer(message: types.Message, state: FSMContext): user_data = await state.get_data() question_number = user_data['question_number'] new_answer = message.text markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer}", reply_markup=markup) else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() await personal_account(message) @dp.message_handler(lambda message: message.text == "Заполнить заново", state=lk.personal_account) async def refill_form(message: types.Message): markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да", callback_data="confirm_refill")) await message.answer("Вы уверены, что хотите начать заново? Все текущие ответы будут удалены.", reply_markup=markup) @dp.callback_query_handler(lambda c: c.data == 'confirm_refill', state="*") async def process_refill(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with aiosqlite.connect('base.db') as db: await db.execute('DELETE FROM answers WHERE user_id=?', (user_id,)) await db.commit() await db.execute('UPDATE users SET last_question_idx = 0 WHERE id = ?', (user_id,)) await db.commit() state = dp.current_state(user=user_id) await state.reset_state(with_data=False) await bot.answer_callback_query(callback_query.id) await bot.send_message(user_id, "Ваши ответы удалены.") await cmd_start(callback_query.message) # ГЕНЕРАЦИЯ class YandexGPT: @staticmethod async def generate(prompt: str, apikey: str, sa_id: str, user_id : str): url = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion' headers = { 'Content-Type': 'application/json', 'Authorization': f'Api-Key {apikey}' } data = { "modelUri": f"gpt://{sa_id}/yandexgpt-lite/latest", "completionOptions": { "stream": False, "temperature": 0.6, "maxTokens": "1000" }, "messages": [ { "role": "system", "text": "Твоя задача - создать небольшой текст о биографии человека в соответствии с следующими ответами на вопросы (пишется вопрос? ответ). Также напиши короткую эпитафию в соответствии с биографией. Свой ответ пиши только по шаблону:\nБиография:\n\nЭпитафий:\n\nБиография должна быть не сильно длинной, но интересной. Если биография очевидно неправильная (ответы на вопросы невозможно распознать), то пиши: Извините, я не понял ваш запрос. Попробуйте ответить на вопросы еще раз. " }, { "role": "user", "text": prompt } ] } async with aiohttp.ClientSession() as session: async with session.post(url, json=data, headers=headers) as response: response_data = await response.json() try: answer = response_data['result']['alternatives'][0]['message']['text'] await bot.send_message(user_id, mdv2(answer), parse_mode="MarkdownV2") except KeyError as e: await bot.send_message(user_id, "Не удалось получить ответ от сервера. Проверьте переданные данные и попробуйте еще раз.") @dp.callback_query_handler(change_action_cb.filter(action="generate"), state="*") async def process_generate(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id prompt = "" async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,)) answers = await cursor.fetchall() for question, answer in answers: prompt += f"\n{question} - {answer}" api_key = "AQVN1J4sCxYR98rj-tVppyp6gXQthbdmYvmgtO7a" sa_id = "b1g5og37bgh1ghh2s2qc" await YandexGPT.generate(prompt, api_key, sa_id, user_id) # АДМИН-ПАНЕЛЬ # КНОПКА НАЗАД back = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False) back.add(KeyboardButton("Назад")) # КЛАВА admin_kb = ReplyKeyboardMarkup(resize_keyboard=True) admin_kb.add("Вопросы", "Добавить", "Удалить", "Редактировать","В меню") @dp.message_handler(lambda message: message.text == "Назад", state=[admin.new_question, admin.edit_question_text, admin.select_question_to_edit, admin.select_question_to_delete]) async def back_to_admin_panel(message: types.Message, state: FSMContext): await state.finish() await admin_panel(message) @dp.message_handler(lambda message: message.text == "Админ-панель", state=Form.choosing_action) async def admin_panel(message: types.Message): if message.from_user.id not in ADMINS: await message.answer("Доступ запрещен.") return await message.answer("Админ-панель:", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Вопросы", state=admin.admin_panel) async def show_questions(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if questions: text = "\n".join([f"{idx + 1}. {question[0]}" for idx, question in enumerate(questions)]) else: text = "Вопросы отсутствуют." await message.answer(text) @dp.message_handler(lambda message: message.text == "Добавить", state=admin.admin_panel) async def add_question_start(message: types.Message): await message.answer("Введите текст нового вопроса:", reply_markup=back) await admin.new_question.set() @dp.message_handler(state=admin.new_question) async def add_question_process(message: types.Message, state: FSMContext): new_question = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT MAX(order_num) FROM questions") max_order_num = await cursor.fetchone() next_order_num = (max_order_num[0] or 0) + 1 await db.execute("INSERT INTO questions (question, order_num) VALUES (?, ?)", (new_question, next_order_num)) await db.commit() await message.answer("Вопрос успешно добавлен.", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Редактировать", state=admin.admin_panel) async def select_question_to_edit_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для редактирования:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_edit.set() @dp.message_handler(state=admin.select_question_to_edit) async def edit_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with state.proxy() as data: data['question_id'] = qid await admin.edit_question_text.set() await message.answer("Введите новый текст вопроса:", reply_markup=back) @dp.message_handler(state=admin.edit_question_text) async def update_question(message: types.Message, state: FSMContext): new_text = message.text async with state.proxy() as data: qid = data['question_id'] async with aiosqlite.connect('base.db') as db: await db.execute("UPDATE questions SET question = ? WHERE id = ?", (new_text, qid)) await db.commit() await message.answer("Вопрос успешно отредактирован.", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Удалить", state=admin.admin_panel) async def select_question_to_delete_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для удаления:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_delete.set() @dp.message_handler(state=admin.select_question_to_delete) async def delete_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT order_num FROM questions WHERE id = ?", (qid,)) question = await cursor.fetchone() if not question: await message.answer(f"Вопрос под номером {qid} не найден. Пожалуйста, попробуйте другой номер.") return order_num_to_delete = question[0] await db.execute("DELETE FROM questions WHERE id = ?", (qid,)) await db.execute("UPDATE questions SET order_num = order_num - 1 WHERE order_num > ?", (order_num_to_delete,)) await db.commit() await message.answer("Вопрос успешно удален.", reply_markup=admin_kb) await admin.admin_panel.set() async def main(): await create_db() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) executor.start_polling(dp, skip_updates=True)
f4e1692316d9143ae74bba5de5cd78d4
{ "intermediate": 0.279865026473999, "beginner": 0.6012320518493652, "expert": 0.11890295147895813 }
46,408
can you create me a plantuml script that represents the hp non stop server, pathmon, pathway and server classes
1cbe98feae809996420725d785d69e4b
{ "intermediate": 0.3825242817401886, "beginner": 0.3796904683113098, "expert": 0.23778527975082397 }
46,409
Hello
12d6566db1759068099fd9a7950ab768
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
46,410
Исправь ошибку в коде: for movement_type in df_stab_agg_by_movement_type['movement_type'].unique(): fig = go.Figure() fig.add_trace(go.Scatter(x=df_stab_7_days_agg_by_movement_type.loc[(df_stab_7_days_agg_by_movement_type['cum_sh'] < 500) & (df_stab_7_days_agg_by_movement_type['movement_type'] == movement_type), ['cum_sh']], y=df_stab_7_days_agg_by_movement_type['mean_speed_km_h'], mode='lines', name='Более 7 дней на сервисе', color='movement_type')) fig.add_trace(go.Scatter(x=df_stab_14_days_agg_by_movement_type.loc[(df_stab_14_days_agg_by_movement_type['cum_sh'] < 500) & (df_stab_14_days_agg_by_movement_type['movement_type'] == movement_type), ['cum_sh']], y=df_stab_14_days_agg_by_movement_type['mean_speed_km_h'], mode='lines', name='Более 14 дней на сервисе', color='movement_type')) fig.add_trace(go.Scatter(x=df_stab_30_days_agg_by_movement_type.loc[(df_stab_30_days_agg_by_movement_type['cum_sh'] < 500) & (df_stab_30_days_agg_by_movement_type['movement_type'] == movement_type), ['cum_sh']], y=df_stab_30_days_agg_by_movement_type['mean_speed_km_h'], mode='lines', name='Более 30 дней на сервисе', color='movement_type')) fig.update_layout(title='Распределение средней скорости в зависимости от sh', xaxis_title='Опыт в SH', yaxis_title='Средняя скорость') fig.show()
665f361ca781f98d14853802c97c6f83
{ "intermediate": 0.3007630705833435, "beginner": 0.4690706133842468, "expert": 0.23016630113124847 }
46,411
Исправь ошибку в коде: for movement_type in df_stab_agg_by_movement_type['movement_type'].unique(): fig = go.Figure() fig.add_trace(go.Scatter(x=df_stab_7_days_agg_by_movement_type.loc[(df_stab_7_days_agg_by_movement_type['cum_sh'] < 500) & (df_stab_7_days_agg_by_movement_type['movement_type'] == movement_type), ['cum_sh']], y=df_stab_7_days_agg_by_movement_type['mean_speed_km_h'], mode='lines', name='Более 7 дней на сервисе', color='movement_type')) fig.add_trace(go.Scatter(x=df_stab_14_days_agg_by_movement_type.loc[(df_stab_14_days_agg_by_movement_type['cum_sh'] < 500) & (df_stab_14_days_agg_by_movement_type['movement_type'] == movement_type), ['cum_sh']], y=df_stab_14_days_agg_by_movement_type['mean_speed_km_h'], mode='lines', name='Более 14 дней на сервисе', color='movement_type')) fig.add_trace(go.Scatter(x=df_stab_7_days_agg_by_movement_type.loc[(df_stab_30_days_agg_by_movement_type['cum_sh'] < 500) & (df_stab_30_days_agg_by_movement_type['movement_type'] == movement_type), ['cum_sh']], y=df_stab_30_days_agg_by_movement_type['mean_speed_km_h'], mode='lines', name='Более 30 дней на сервисе', color='movement_type')) fig.update_layout(title='Распределение средней скорости в зависимости от sh', xaxis_title='Опыт в SH', yaxis_title='Средняя скорость') fig.show()
724670f48f062b890fcbcf911dca801f
{ "intermediate": 0.3046252727508545, "beginner": 0.4701884090900421, "expert": 0.22518634796142578 }
46,412
i have dict "sizes" where key is str - name of dataset (i have 19 of those), value - dict where key is str - name of compression algorithm used to compress rows in that dataset (12 of those), value is float - average size of those compressed rows. i need ideas what plots or diagrams to make with that info. note: those 12 algorithms actually are: one is just info serialized with json (json string), another is info serialized with protobuf, and rest 10 are those two but each were compressed with same 5 compression algorithms
ab0838afd617a46b15362becbe82ddcf
{ "intermediate": 0.3866211771965027, "beginner": 0.24463172256946564, "expert": 0.3687470555305481 }
46,413
root.render(list.innerHTML, <div className="note"><h3>{name}</h3></div>) but not works
81237c51eb6b49a728fea3dd018e2fdb
{ "intermediate": 0.3869117498397827, "beginner": 0.40989670157432556, "expert": 0.20319156348705292 }
46,414
corrija o erro : FeatureCollection (Error) List.map: Parameter 'list' is required. Aqui está o script de referencia : var aceh = ee.Image("projects/ee-cbcgeeanalises/assets/Classes_Prodes30m_2023_Raster"); var Tipos = ee.Dictionary({ 'APA': 'AREA_DE_PROTECAO_AMBIENTAL', 'ARIE': 'AREA_DE_RELEVANTE_INTERESSE_ECOLOGICO', 'ESEC': 'ESTACAO_ECOLOGICA', 'FLONA': 'FLORESTA_NACIONAL', 'MONA': 'MONUMENTO_NATURAL', 'PARNA': 'PARQUE_NACIONAL', 'RDS': 'RESERVA_DE_DESENVOLVIMENTO_SUSTENTAVEL', 'REBIO': 'RESERVA_BIOLOGICA', 'RESEX': 'RESERVA_EXTRATIVISTA', 'REVIS': 'REFUGIO_DE_VIDA_SILVESTRE' }); // Renomear UCs var substituirString = function(feature) { var nomeUCOriginal = ee.String(feature.get('NomeUC')); var siglaCateg = ee.String(feature.get('SiglaCateg')); var tipo1 = Tipos.get(siglaCateg); var novoNomeUC = nomeUCOriginal.replace(tipo1, siglaCateg); return feature.set('NewName', novoNomeUC); }; var districts = ee.FeatureCollection("projects/ee-cbcgeeanalises/assets/LimiteUCsFederais_28092023_Corrigido") //print(districts, 'districts') var nomesUCs1 = districts.aggregate_array('NomeUC').sort().slice(1,11) var UCs_filtradas = districts.filter(ee.Filter.inList('NomeUC', nomesUCs1)) .map(substituirString) var lista3 = ee.List([ 'NewName', 'Cnuc', ]); var areas = ee.Image.pixelArea().divide(10000).addBands(aceh) var acehstats = areas.reduceRegions({ collection: UCs_filtradas, reducer: ee.Reducer.sum().group({ groupField: 1, groupName: 'class', }), scale: 30, crs: 'EPSG:4326', tileScale: 16, }); print(acehstats, 'acehstats') var calculateClassArea = function(feature) { var classAreaLists = ee.List(feature.get('groups')).map(function(item) { var areaDict = ee.Dictionary(item); var classNumber = ee.Number(areaDict.get('class')); var formattedClassNumber = classNumber.format('%02d'); var area = ee.Number(areaDict.get('sum')) return ee.List([formattedClassNumber, area]); }); var result = ee.Dictionary(classAreaLists.flatten()); var output = ee.Feature(feature.geometry(), result); return output.copyProperties(feature, lista3); }; var fcWithAreas = ee.FeatureCollection(calculateClassArea(acehstats)) print(fcWithAreas, 'fcWithAreas') // Exportar CSV Export.table.toDrive({ collection: fcWithAreas, description: 'Tabela_Classes_Restauracao_2023', folder: 'Tabela_Classes_Restauracao1', fileFormat: 'CSV' });
908732a3f647865f1cae2ba04d25cb45
{ "intermediate": 0.3128393888473511, "beginner": 0.5026816129684448, "expert": 0.1844789981842041 }
46,415
Private Sub CommandButton2_Click() Dim fs As Object, folder As Object, file As Object Dim wbPath As String, ws As Worksheet Dim i As Integer ' Set the worksheet object to the active sheet Set ws = ThisWorkbook.Sheets("Sheet1") ' Initialize the FileSystemObject Set fs = CreateObject("Scripting.FileSystemObject") ' Get the folder where this workbook is saved Set folder = fs.GetFolder(ThisWorkbook.Path) ' Initialize row index for Sheet1 column G i = 4 ' Loop through each file in the directory For Each file In folder.Files If LCase(fs.GetExtensionName(file.Name)) = "txt" Then ' Open the text file textFile = FreeFile Open file.Path For Input As textFile fileContent = Input(LOF(textFile), textFile) Close textFile ' Use Regular Expression to find the numeric value after "Placed" Set RegEx = CreateObject("VBScript.RegExp") With RegEx .Global = False .IgnoreCase = True .Pattern = "Placed\D*(\d+)" End With ' If a matching pattern is found, extract the numeric value If RegEx.Test(fileContent) Then numericValue = RegEx.Execute(fileContent)(0).SubMatches(0) ' Write the numeric value into column G starting from row 4 ws.Cells(i, 7).Value = numericValue i = i + 1 End If ' Clean up RegExp object Set RegEx = Nothing End If Next file ' Clean up FileSystemObject Set fs = Nothing End Sub FOR THIS CODE I WANT FIRST TO SEARCH IN FILE FOR SAME NAME AS .TXT FILE FROM WHERE WE COPY NUMBER AFTER Placed: and on exact same row Write the numeric value into column G starting from row 4
0055e52bdf03f3aa4e9af0f34ad111b0
{ "intermediate": 0.43752244114875793, "beginner": 0.37822988629341125, "expert": 0.18424765765666962 }
46,416
Corrija o erro :" FeatureCollection (Error) List.map: Parameter 'list' is required. fcWithAreas". Aqui está o script de referência: var aceh = ee.Image("projects/ee-cbcgeeanalises/assets/Classes_Prodes30m_2023_Raster"); var Tipos = ee.Dictionary({ 'APA': 'AREA_DE_PROTECAO_AMBIENTAL', 'ARIE': 'AREA_DE_RELEVANTE_INTERESSE_ECOLOGICO', 'ESEC': 'ESTACAO_ECOLOGICA', 'FLONA': 'FLORESTA_NACIONAL', 'MONA': 'MONUMENTO_NATURAL', 'PARNA': 'PARQUE_NACIONAL', 'RDS': 'RESERVA_DE_DESENVOLVIMENTO_SUSTENTAVEL', 'REBIO': 'RESERVA_BIOLOGICA', 'RESEX': 'RESERVA_EXTRATIVISTA', 'REVIS': 'REFUGIO_DE_VIDA_SILVESTRE' }); // Renomear UCs var substituirString = function(feature) { var nomeUCOriginal = ee.String(feature.get('NomeUC')); var siglaCateg = ee.String(feature.get('SiglaCateg')); var tipo1 = Tipos.get(siglaCateg); var novoNomeUC = nomeUCOriginal.replace(tipo1, siglaCateg); return feature.set('NewName', novoNomeUC); }; var districts = ee.FeatureCollection("projects/ee-cbcgeeanalises/assets/LimiteUCsFederais_28092023_Corrigido") //print(districts, 'districts') var nomesUCs1 = districts.aggregate_array('NomeUC').sort().slice(1,11) var UCs_filtradas = districts.filter(ee.Filter.inList('NomeUC', nomesUCs1)) .map(substituirString) var lista3 = ee.List([ 'NewName', 'Cnuc', ]); var areas = ee.Image.pixelArea().divide(10000).addBands(aceh) var acehstats = areas.reduceRegions({ collection: UCs_filtradas, reducer: ee.Reducer.sum().group({ groupField: 1, groupName: 'class', }), scale: 30, crs: 'EPSG:4326', tileScale: 16, }); print(acehstats, 'acehstats') var calculateClassArea = function(feature) { var classAreaLists = ee.List(feature.get('groups')).map(function(item) { var areaDict = ee.Dictionary(item); var classNumber = ee.Number(areaDict.get('class')); var formattedClassNumber = classNumber.format('%02d'); var area = ee.Number(areaDict.get('sum')) return ee.List([formattedClassNumber, area]); }); var result = ee.Dictionary(classAreaLists.flatten()); var output = ee.Feature(feature.geometry(), result); return output.copyProperties(feature, lista3); }; var fcWithAreas = ee.FeatureCollection(calculateClassArea(acehstats)) print(fcWithAreas, 'fcWithAreas') // Exportar CSV Export.table.toDrive({ collection: fcWithAreas, description: 'Tabela_Classes_Restauracao_2023', folder: 'Tabela_Classes_Restauracao1', fileFormat: 'CSV' });
1e70399538526355f06a20940495db92
{ "intermediate": 0.3245965838432312, "beginner": 0.46614760160446167, "expert": 0.20925581455230713 }
46,417
Private Sub CommandButton4_Click() Dim sourceWorkbook As Workbook Dim destWorkbook As Workbook Dim sourceSheet As Worksheet Dim destSheet As Worksheet Dim folderPath As String Dim sourceFileName As String Dim sourceFilePath As String ' Dynamically get the folder path of the workbook containing this script (.xlsm) ' and ensure it ends with a backslash folderPath = ThisWorkbook.Path If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\" End If ' Get the name of the first .xlsx file in the folder sourceFileName = Dir(folderPath & "*.xlsx") ' Check if an .xlsx file was found If sourceFileName = "" Then MsgBox "No .xlsx file found in the same folder." Exit Sub End If ' Construct the full file path for the .xlsx file sourceFilePath = folderPath & sourceFileName ' Set the destination workbook and sheet ' ThisWorkbook refers to the workbook containing this script (.xlsm) Set destWorkbook = ThisWorkbook Set destSheet = destWorkbook.Sheets(1) ' Adjust as needed if copying to a different sheet ' Attempt to open the source .xlsx file On Error Resume Next ' In case the file doesn't open Set sourceWorkbook = Workbooks.Open(sourceFilePath) On Error GoTo 0 ' Turn back on regular error handling after attempt to open ' Check if the workbook was successfully opened If sourceWorkbook Is Nothing Then MsgBox "Failed to open the .xlsx file." Exit Sub End If ' Set the source sheet (assuming data is on the first sheet) Set sourceSheet = sourceWorkbook.Sheets(1) ' Copy the used range from the source sheet to the destination sheet sourceSheet.UsedRange.Copy Destination:=destSheet.Cells(2, 2) ' Starts pasting from B4 ' Close the source workbook without saving changes sourceWorkbook.Close SaveChanges:=False MsgBox "Data copied successfully from " & sourceFileName End Sub it start pasting from column c , i want column b
276c1ecf5dae32d8d3c61719e489e112
{ "intermediate": 0.5673888921737671, "beginner": 0.22907547652721405, "expert": 0.20353561639785767 }
46,418
https://github.com/oogunjob/Melody-Migrate he has done to migrate user library to transfer from one account to another in apple music (signing in one session and another session signin in with another account) can you give me in python code to do saame work
49d7525b67d1127d2bd7503716639c62
{ "intermediate": 0.6440439820289612, "beginner": 0.18719257414340973, "expert": 0.1687634289264679 }
46,419
path(index q, r) if (P[ q, r ]!=0) path(q, P[q, r]) println( “v”+ P[q, r]) path(P[q, r], r) return; //no intermediate nodes else return If D[q, r] < infinity, print node q and call path(...), after returning from path(...), print node r. Apply this logic to the Pmatrix in the program import java.io.*; import java.util.*; import java.util.Scanner; public class floyd { private static int[][] adjMatrix; private static int[][] pMatrix; private static final String OUTPUT_FILE = "output.txt"; public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: java Floyd <graph-file>"); return; } try (Scanner scanner = new Scanner(new BufferedReader(new FileReader(args[0])))) { createFile(); int problemCount = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("Problem")) { problemCount++; int n = extractNumberOfVertices(line); if (n < 5 || n > 10) { throw new IllegalArgumentException("Invalid number of vertices."); } // Read adjacency matrix for the current problem initializeMatrices(n, scanner); // Compute shortest paths and print results calculateShortestPaths(); printResult(problemCount, n); } } } } private static void createFile() throws FileNotFoundException { PrintWriter writer = new PrintWriter(OUTPUT_FILE); writer.close(); } private static int extractNumberOfVertices(String line) { // Extracts the number of vertices from the line String[] parts = line.split("n = "); return Integer.parseInt(parts[1].trim()); } private static void initializeMatrices(int n, Scanner scanner) { adjMatrix = new int[n][n]; pMatrix = new int[n][n]; for (int i = 0; i < n; i++) { String[] values = scanner.nextLine().trim().split("\s+"); for (int j = 0; j < n; j++) { if (values[j].equals("INF")) { adjMatrix[i][j] = Integer.MAX_VALUE; pMatrix[i][j] = j; // Initialize as destination node itself } else { int weight = Integer.parseInt(values[j]); adjMatrix[i][j] = weight; pMatrix[i][j] = i == j ? -1 : 0; // Direct path logic adjusted } } } } private static void calculateShortestPaths() { int n = adjMatrix.length; // Initialize pMatrix for direct paths and self-loops for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j || adjMatrix[i][j] == Integer.MAX_VALUE) { pMatrix[i][j] = -1; // No path initially } else { pMatrix[i][j] = i; // Direct path exists, storing predecessor } } } // Apply Floyd-Warshall algorithm for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (adjMatrix[i][k] != Integer.MAX_VALUE && adjMatrix[k][j] != Integer.MAX_VALUE) { long newPathDist = (long)adjMatrix[i][k] + adjMatrix[k][j]; if (newPathDist < adjMatrix[i][j]) { adjMatrix[i][j] = (int)newPathDist; pMatrix[i][j] = pMatrix[k][j]; } } } } } } private static void printResult(int problemCount, int n) throws FileNotFoundException, IOException { try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(OUTPUT_FILE, true)))) { out.println("Problem" + problemCount + ": n = " + n); out.println("Pmatrix:"); // Output the pMatrix for the problem for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { out.print("0 "); } else { // Print the number of the node just before destination on the shortest path out.print((pMatrix[i][j] != -1 ? (pMatrix[i][j] + 1) : "-") + " "); } } out.println(); } out.println(); // Output shortest paths for each city to all other cities for (int source = 0; source < n; source++) { out.println("V" + (source + 1) + "-Vj: shortest path and length"); for (int dest = 0; dest < n; dest++) { // Get the shortest path and distance between the source and destination String path = getShortestPath(source, dest); int distance = adjMatrix[source][dest]; out.println(path + ": " + distance); } out.println(); } out.println(); // Separate problems visually } } private static String getShortestPath(int source, int dest) { if (adjMatrix[source][dest] == Integer.MAX_VALUE) { return "No path"; } List<Integer> path = new ArrayList<>(); for (int at = dest; at != -1; at = pMatrix[source][at]) { path.add(at); // Collect in reverse order } Collections.reverse(path); // Reverse to get the correct order starting from source // Build the output StringBuilder pathStr = new StringBuilder(); for (int i = 0; i < path.size(); i++) { if (i > 0) pathStr.append(" "); pathStr.append("V").append(path.get(i) + 1); // Add 1 for 1-indexed vertex numbering } return pathStr.toString(); } }
5c2acd4479a0265c6297c6f823743a04
{ "intermediate": 0.35571524500846863, "beginner": 0.3884621262550354, "expert": 0.25582265853881836 }
46,420
Coding 2D orbital element simulation: Time: 1 hour Mass: 1 Solar mass Semi-major axis: 1 AU Orbital direction: 360 degree (repeating) True anomaly: 90 degree Argument of periapsis: 100 degree Eccentricity: 0.3 (0 to 1)
54f5e77ff465af919424595a8e5b85c3
{ "intermediate": 0.3173288106918335, "beginner": 0.2305600792169571, "expert": 0.45211103558540344 }
46,421
Привет у меня есть скрипт турели измени скрипт сделав чтобы она стреляла при попадание игрока а рейкаст каждую 1 секунду public Transform target; // Цель, за которой слежка (обычно игрок) public float trackingSpeed = 5f; // Скорость, с которой турель будет следовать за игроком // Raycast settings public float maxDistance = 100f; // Максимальное расстояние, на котором турель может “видеть” игрока public LayerMask whatToHit; // Слой, по которому можно стрелять (назначается для игрока) public GameObject objbul, objwhere; public GameObject objclone; public int power; private void Update() { TrackTarget(); CheckForShooting(); } void TrackTarget() { if (target) { Vector3 directionToTarget = target.position - transform.position; Quaternion lookRotation = Quaternion.LookRotation(directionToTarget); // Плавный поворот transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, trackingSpeed * Time.deltaTime); } } void CheckForShooting() { if (target) { Ray rayForward = new Ray(transform.position, transform.forward); RaycastHit hit; if (Physics.Raycast(rayForward, out hit, maxDistance, whatToHit)) { // Если Raycast попал в игрока, вызываем функцию для стрельбы (добавьте свою логику тут) if (hit.transform == target) { objclone = Instantiate(objbul, objwhere.transform.position, Quaternion.identity); objclone.GetComponent<Rigidbody>().AddForce(objwhere.transform.forward * power); Destroy(objclone, 1); } } } }
9aae57910b7abcfbf4f5d762d6762190
{ "intermediate": 0.28939342498779297, "beginner": 0.5143367052078247, "expert": 0.19626986980438232 }
46,422
Write a python script that asks for a list of numbers seperated by spaces each value representing the value at a position on a grid of 5 by 5 starting from top left and going right until end and then going to the next row below. The values are all numbers and if there is no value at a place it is given as "X". You are permitted to swap any two locations on the grid only once such that after swapping there should be atleast a single row or a column all the values of which are the same number whatever it may be. Show the positions swapped.
38f8b9df76675c4f00602447f48501a9
{ "intermediate": 0.48299548029899597, "beginner": 0.16021890938282013, "expert": 0.3567856252193451 }
46,423
Do I need to reinstall windows 10 to change for example ahci to something
ab635d28b7807822f51dddab256092b0
{ "intermediate": 0.3635313808917999, "beginner": 0.2605961859226227, "expert": 0.37587249279022217 }
46,424
How to know the programs that I have installed through Scoop?
933250286452934f49b8f7450fdcc0e6
{ "intermediate": 0.4661855697631836, "beginner": 0.2236768901348114, "expert": 0.3101375102996826 }
46,425
Suppose I want to make a header for a website. On the left side will be the logo of the website, and then there will be some empty space near the middle. Then of the left side there will be a navbar with clickable links to "dashboard", "products", "sales", and "customers". What would be the cleanest way to implement this in html and css?
b90b08ed25b164f2f78c2c4568fa698b
{ "intermediate": 0.40175724029541016, "beginner": 0.3224714994430542, "expert": 0.27577129006385803 }
46,426
110000 11**000**0 111110 + **111**000 + 111000 = 110000 11**111**0 111110, **000**000, 111000
addb527dd97edb90a5f50397cd40bb92
{ "intermediate": 0.36651328206062317, "beginner": 0.26232171058654785, "expert": 0.3711649775505066 }
46,427
I have this problem: chr1 stdin transcript 11869 14409 . + . gene_id "ENST00000456328.2"; transcript_id "ENST00000456328.2"; chr1 xxxx transcript 11869 14409 . + . gene_id "ENST00000456328.2"; transcript_id "ENST00000456328.2"; given two different gtf files, I want to compare them and output the unique lines from the first one. the second column is not a source of variation, meaning that the most important things to compare are: chr1 transcript 11869 14409 if you can do this from the command line would be amazing!
bb369f8cdbcbffb7c827cce8f8b987e7
{ "intermediate": 0.3530786633491516, "beginner": 0.30222755670547485, "expert": 0.3446938395500183 }
46,428
In pascal Create labyrinth. I can offer a general roadmap to help you get started on this task: Learn the basics of working with two-dimensional arrays in PascalABC.NET. You will need to create a matrix that will represent the maze. Develop an algorithm for generating the maze. You can use different methods, such as recursive division method or random walk method. Implement a maze generation algorithm in PascalABC.NET. You will need to create functions to create the initial configuration of the maze, add walls, remove walls, etc. Add the ability to visualize the maze. You can use standard text renderers or create your own graphics. Test your maze generator by creating a few example mazes and making sure they meet your expectations. Enhance your maze generator by adding additional features and functionality as you see fit. This is just a general outline. and you will need more detailed research and development to create a full-fledged maze generator.
c736717554f8b9776f2079e98a01a80d
{ "intermediate": 0.19819863140583038, "beginner": 0.29717472195625305, "expert": 0.5046266317367554 }
46,429
Hi. Can you write me a HTML code tshow an analog clock?
ae5b2d9bed753db8ab5098e514c9ffad
{ "intermediate": 0.4595504701137543, "beginner": 0.339770644903183, "expert": 0.20067892968654633 }
46,430
I am writing a lab report on how viscocsity changes with temperature. write an abstract on why understanding the relationship between the two is important. make it no longer than 100 words
69f8223411120c97e23f844c8a3ca1f4
{ "intermediate": 0.3363553285598755, "beginner": 0.35086676478385925, "expert": 0.31277790665626526 }
46,431
Suppose I have a html page that consists of body, with two children: a header element and a main element. The header element further contains a div and a navbar. The main element contains three section elements that have content inside them. The header element does not have a height specified. I want to be able to write css so that the main element takes up the rest of the body element. What is the cleanest way to achieve this?
5e39bdbf1b28b4c0cb4a3549bb0ac855
{ "intermediate": 0.4232504367828369, "beginner": 0.31279686093330383, "expert": 0.26395267248153687 }
46,432
what is lua code?
2d6387fc7f112b714bd92436f2fedfa6
{ "intermediate": 0.2216678261756897, "beginner": 0.41079527139663696, "expert": 0.36753684282302856 }
46,433
I want to stream youtube videos on MPV but the videos are on VP9. I don't want that codec and would rather like to have h264. I have tried to stream a video with this "ytdl-format=bestvideo[height<=1080][fps<=30][vcodec!=h264]+bestaudio/best" in my MPV config file but it didn't work.
1432e75b1c014dc94b96daabbcaccd0f
{ "intermediate": 0.4951949715614319, "beginner": 0.22427025437355042, "expert": 0.2805348038673401 }
46,434
Make this go script use opencl for computation and processing instead of the CPU package main import ( "encoding/binary" "errors" "flag" "fmt" "os" "path" "runtime" "sync" "time" "github.com/ethereum/go-ethereum/crypto/secp256k1" "github.com/farces/mt19937_64" ) var storeDir = flag.String("dir", "seeds", "seed store directory") var Curve = secp256k1.S256() func main() { flag.Parse() fmt.Println(os.Getwd()) err := os.MkdirAll(*storeDir, 0755) if err != nil { panic(err) } cpuCount := runtime.NumCPU() start := time.Now() perCPUCount := (1 << 32) / cpuCount var wg sync.WaitGroup for i := 0; i < cpuCount; i++ { go genSeedPublicKeysPerCpu(i, i*perCPUCount, (i+1)*perCPUCount-1, &wg) } time.Sleep(time.Second) wg.Wait() fmt.Println("done", time.Since(start)) } func PublicKeyFromSeed(seed uint32) uint64 { eng := mt19937_64.New() eng.Seed(int64(seed)) var r [32]byte binary.BigEndian.PutUint64(r[24:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[16:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[8:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[0:], uint64(eng.Int63())) X, _ := Curve.ScalarBaseMult(r[:]) return X.Uint64() } func genSeedPublicKeysPerCpu(cpuIndex, start, end int, wg *sync.WaitGroup) { wg.Add(1) seed := start filename := path.Join(*storeDir, fmt.Sprintf("seed-%08x-%08x.bin", start, end)) stat, err := os.Stat(filename) if err != nil { if !errors.Is(err, os.ErrNotExist) { panic(err) } } else { size := stat.Size() if size%8 != 0 { panic(fmt.Sprint(filename, "file size is", size)) } seed += int(size / 8) } f, err := os.OpenFile(filename, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { panic(err) } defer f.Close() count := uint64(end - start) buf := make([]byte, 0, 0x100000*8) for ; seed <= end; seed++ { key := PublicKeyFromSeed(uint32(seed)) buf = binary.LittleEndian.AppendUint32(buf, uint32(seed)) buf = binary.LittleEndian.AppendUint64(buf, key) if seed%0x1000 == 0 { index := seed - start fmt.Printf("CPU%d %d/%d %d%%%%\n", cpuIndex, index, count, uint64(index)*100/count) } if seed%0x100000 == 0 { _, err = f.Write(buf[:]) if err != nil { panic(err) } buf = buf[:0] } } _, err = f.Write(buf[:]) if err != nil { panic(err) } wg.Done() }
01c1e36c87886e79823e8916b66c3dad
{ "intermediate": 0.34188735485076904, "beginner": 0.3717924654483795, "expert": 0.28632014989852905 }
46,435
Make this go script use opencl for computation and processing instead of the CPU package main import ( “encoding/binary” “errors” “flag” “fmt” “os” “path” “runtime” “sync” “time” “github.com/ethereum/go-ethereum/crypto/secp256k1” “github.com/farces/mt19937_64” ) var storeDir = flag.String(“dir”, “seeds”, “seed store directory”) var Curve = secp256k1.S256() func main() { flag.Parse() fmt.Println(os.Getwd()) err := os.MkdirAll(storeDir, 0755) if err != nil { panic(err) } cpuCount := runtime.NumCPU() start := time.Now() perCPUCount := (1 << 32) / cpuCount var wg sync.WaitGroup for i := 0; i < cpuCount; i++ { go genSeedPublicKeysPerCpu(i, iperCPUCount, (i+1)*perCPUCount-1, &wg) } time.Sleep(time.Second) wg.Wait() fmt.Println(“done”, time.Since(start)) } func PublicKeyFromSeed(seed uint32) uint64 { eng := mt19937_64.New() eng.Seed(int64(seed)) var r [32]byte binary.BigEndian.PutUint64(r[24:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[16:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[8:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[0:], uint64(eng.Int63())) X, _ := Curve.ScalarBaseMult(r[:]) return X.Uint64() } func genSeedPublicKeysPerCpu(cpuIndex, start, end int, wg *sync.WaitGroup) { wg.Add(1) seed := start filename := path.Join(storeDir, fmt.Sprintf(“seed-%08x-%08x.bin”, start, end)) stat, err := os.Stat(filename) if err != nil { if !errors.Is(err, os.ErrNotExist) { panic(err) } } else { size := stat.Size() if size%8 != 0 { panic(fmt.Sprint(filename, “file size is”, size)) } seed += int(size / 8) } f, err := os.OpenFile(filename, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { panic(err) } defer f.Close() count := uint64(end - start) buf := make([]byte, 0, 0x1000008) for ; seed <= end; seed++ { key := PublicKeyFromSeed(uint32(seed)) buf = binary.LittleEndian.AppendUint32(buf, uint32(seed)) buf = binary.LittleEndian.AppendUint64(buf, key) if seed%0x1000 == 0 { index := seed - start fmt.Printf(“CPU%d %d/%d %d%%%%\n”, cpuIndex, index, count, uint64(index)*100/count) } if seed%0x100000 == 0 { , err = f.Write(buf[:]) if err != nil { panic(err) } buf = buf[:0] } } , err = f.Write(buf[:]) if err != nil { panic(err) } wg.Done() }
d448d870b697585ef54890ccbb32dca6
{ "intermediate": 0.31109145283699036, "beginner": 0.4050914943218231, "expert": 0.2838171124458313 }
46,436
What dose this go script do?: package main import ( "encoding/binary" "errors" "flag" "fmt" "os" "path" "runtime" "sync" "time" "github.com/ethereum/go-ethereum/crypto/secp256k1" "github.com/farces/mt19937_64" ) var storeDir = flag.String("dir", "seeds", "seed store directory") var Curve = secp256k1.S256() func main() { flag.Parse() fmt.Println(os.Getwd()) err := os.MkdirAll(*storeDir, 0755) if err != nil { panic(err) } cpuCount := runtime.NumCPU() start := time.Now() perCPUCount := (1 << 32) / cpuCount var wg sync.WaitGroup for i := 0; i < cpuCount; i++ { go genSeedPublicKeysPerCpu(i, i*perCPUCount, (i+1)*perCPUCount-1, &wg) } time.Sleep(time.Second) wg.Wait() fmt.Println("done", time.Since(start)) } func PublicKeyFromSeed(seed uint32) uint64 { eng := mt19937_64.New() eng.Seed(int64(seed)) var r [32]byte binary.BigEndian.PutUint64(r[24:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[16:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[8:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[0:], uint64(eng.Int63())) X, _ := Curve.ScalarBaseMult(r[:]) return X.Uint64() } func genSeedPublicKeysPerCpu(cpuIndex, start, end int, wg *sync.WaitGroup) { wg.Add(1) seed := start filename := path.Join(*storeDir, fmt.Sprintf("seed-%08x-%08x.bin", start, end)) stat, err := os.Stat(filename) if err != nil { if !errors.Is(err, os.ErrNotExist) { panic(err) } } else { size := stat.Size() if size%8 != 0 { panic(fmt.Sprint(filename, "file size is", size)) } seed += int(size / 8) } f, err := os.OpenFile(filename, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { panic(err) } defer f.Close() count := uint64(end - start) buf := make([]byte, 0, 0x100000*8) for ; seed <= end; seed++ { key := PublicKeyFromSeed(uint32(seed)) buf = binary.LittleEndian.AppendUint32(buf, uint32(seed)) buf = binary.LittleEndian.AppendUint64(buf, key) if seed%0x1000 == 0 { index := seed - start fmt.Printf("CPU%d %d/%d %d%%%%\n", cpuIndex, index, count, uint64(index)*100/count) } if seed%0x100000 == 0 { _, err = f.Write(buf[:]) if err != nil { panic(err) } buf = buf[:0] } } _, err = f.Write(buf[:]) if err != nil { panic(err) } wg.Done() }
e1adec23faf273b4a18072f37e33ec37
{ "intermediate": 0.2900010645389557, "beginner": 0.406698077917099, "expert": 0.3033008277416229 }
46,437
What dose this go script do?: package main import ( “encoding/binary” “errors” “flag” “fmt” “os” “path” “runtime” “sync” “time” “github.com/ethereum/go-ethereum/crypto/secp256k1” “github.com/farces/mt19937_64” ) var storeDir = flag.String(“dir”, “seeds”, “seed store directory”) var Curve = secp256k1.S256() func main() { flag.Parse() fmt.Println(os.Getwd()) err := os.MkdirAll(storeDir, 0755) if err != nil { panic(err) } cpuCount := runtime.NumCPU() start := time.Now() perCPUCount := (1 << 32) / cpuCount var wg sync.WaitGroup for i := 0; i < cpuCount; i++ { go genSeedPublicKeysPerCpu(i, iperCPUCount, (i+1)*perCPUCount-1, &wg) } time.Sleep(time.Second) wg.Wait() fmt.Println(“done”, time.Since(start)) } func PublicKeyFromSeed(seed uint32) uint64 { eng := mt19937_64.New() eng.Seed(int64(seed)) var r [32]byte binary.BigEndian.PutUint64(r[24:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[16:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[8:], uint64(eng.Int63())) binary.BigEndian.PutUint64(r[0:], uint64(eng.Int63())) X, _ := Curve.ScalarBaseMult(r[:]) return X.Uint64() } func genSeedPublicKeysPerCpu(cpuIndex, start, end int, wg *sync.WaitGroup) { wg.Add(1) seed := start filename := path.Join(storeDir, fmt.Sprintf(“seed-%08x-%08x.bin”, start, end)) stat, err := os.Stat(filename) if err != nil { if !errors.Is(err, os.ErrNotExist) { panic(err) } } else { size := stat.Size() if size%8 != 0 { panic(fmt.Sprint(filename, “file size is”, size)) } seed += int(size / 8) } f, err := os.OpenFile(filename, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { panic(err) } defer f.Close() count := uint64(end - start) buf := make([]byte, 0, 0x1000008) for ; seed <= end; seed++ { key := PublicKeyFromSeed(uint32(seed)) buf = binary.LittleEndian.AppendUint32(buf, uint32(seed)) buf = binary.LittleEndian.AppendUint64(buf, key) if seed%0x1000 == 0 { index := seed - start fmt.Printf(“CPU%d %d/%d %d%%%%\n”, cpuIndex, index, count, uint64(index)*100/count) } if seed%0x100000 == 0 { _, err = f.Write(buf[:]) if err != nil { panic(err) } buf = buf[:0] } } _, err = f.Write(buf[:]) if err != nil { panic(err) } wg.Done() }
aee6d520b7c9f6dfacb6463ee9402fc4
{ "intermediate": 0.24273622035980225, "beginner": 0.46625468134880066, "expert": 0.29100915789604187 }
46,438
Videos play with no sound on mpv with this config: ytdl-format=bestvideo[height<=1080][fps<=30][vcodec^=avc1]
996caacf3f0d2302bcac94c70ba5d320
{ "intermediate": 0.35190626978874207, "beginner": 0.2599548399448395, "expert": 0.38813892006874084 }
46,439
hi
aa703f149bf25a12207f09da3b8d5559
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
46,440
in this javascript for leaflet.js I want to increase the radius of the circle marker for firstcity when the cafeOneButton condition is met 'var money = 100000; var numberOfCarriages = 1; var speed = 60; var dailybonus = 0; const map = L.map("map").setView([54.2231637, -1.9381623], 6); // Add custom zoom control to the map with position set to ‘topright’ const customZoomControl = L.control.zoom({ position: "topright" }).addTo(map); // Remove the default zoom control from the map map.removeControl(map.zoomControl); let clickedPoints = []; let isLineDrawn = false; let marker; // Declare the marker variable let progress = 0; let cafeOneBonus = 0; let cafeTwoBonus = 0; let hotelOneBonus = 0; let hotelTwoBonus = 0; const increaseSpeed = () => { const speedIncrease = 20; speed += speedIncrease; }; // Function to create circle markers with click functionality function createCircleMarkers(geojson) { return L.geoJSON(geojson, { pointToLayer: function (feature, latlng) { const circleMarker = L.circleMarker(latlng, { radius: 4, fillColor: "#ff7800", color: "#000", weight: 0.2, opacity: 1, fillOpacity: 0.8, }); // Attach the feature to the circle marker circleMarker.feature = feature; circleMarker.on("mouseover", function () { this.bindPopup(feature.properties.city).openPopup(); }); circleMarker.on("click", function (e) { if (!isLineDrawn) { clickedPoints.push(e.target); // Push the circle marker with attached feature if (clickedPoints.length === 2) { const firstCityCoords = clickedPoints[0].feature.geometry.coordinates; const secondCityCoords = clickedPoints[1].feature.geometry.coordinates; const polyline = L.polyline( clickedPoints.map((p) => p.getLatLng()) ).addTo(map); const firstCity = clickedPoints[0].feature.properties.city; const secondCity = clickedPoints[1].feature.properties.city; clickedPoints = []; isLineDrawn = true; // Remove click event listener after a line has been drawn map.off("click"); // Set the map bounds to show the area with the polyline map.fitBounds(polyline.getBounds()); money = money - 50000; // Subtract 50000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; // Assuming money is a number moneyDisplay.textContent = moneyString; const instructionsElement = document.getElementById("instructions"); // Clear any existing content in the instructions element: instructionsElement.innerHTML = ""; // Create separate paragraph elements: const congratulationsParagraph = document.createElement("p"); congratulationsParagraph.textContent = `Congratulations you have built your first train line from ${firstCity} to ${secondCity}!`; const costsParagraph = document.createElement("p"); costsParagraph.textContent = `Your construction costs were £50,000. You have £50,000 remaining.`; const buyTrainParagraph = document.createElement("p"); buyTrainParagraph.textContent = "You now need to buy a train."; const newTrainParagraph = document.createElement("p"); newTrainParagraph.textContent = "At this time you can only afford to buy the train engine the Sleeping Lion. The Sleeping Lion has a traveling speed of 60 miles per hour. It can pull four carriages. Which means your train will have a capacity of around 120 seated passengers"; const traincost = document.createElement("p"); traincost.textContent = `The Sleeping Lion will cost you £30,000 to purchase. Do you wish to buy the Sleeping Lion?`; // Append paragraphs to the instructions element: instructionsElement.appendChild(congratulationsParagraph); instructionsElement.appendChild(costsParagraph); instructionsElement.appendChild(buyTrainParagraph); instructionsElement.appendChild(newTrainParagraph); instructionsElement.appendChild(traincost); // Add button element: const buyButton = document.createElement("button"); buyButton.id = "buybutton"; buyButton.textContent = "Buy Train"; // Append the button element to the instructions element: instructionsElement.appendChild(buyButton); //buybutton event listener document .getElementById("buybutton") .addEventListener("click", function () { // Check if you have enough money before purchase money = money - 30000; // Subtract 30000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Update instructions content after successful purchase instructionsElement.innerHTML = ""; // Clear previous content const successMessage = document.createElement("p"); successMessage.textContent = `You now have a train line from ${firstCity} to ${secondCity} and a train! Press the button below to begin operations.`; instructionsElement.appendChild(successMessage); // Add button element: const trainButton = document.createElement("button"); trainButton.id = "trainbutton"; trainButton.textContent = "Start Train"; // Append the button element to the instructions element: instructionsElement.appendChild(trainButton); trainButton.addEventListener("click", function () { console.log("Train Started"); //emptyinstructions add improvement buttons instructionsElement.innerHTML = ""; // Clear previous content //randomgeneration of dailybonus function generateDailyBonus(minBonus, maxBonus) { const randomNumber = Math.floor(Math.random() * (maxBonus - minBonus + 1)) + minBonus; dailybonus += randomNumber; console.log(`Daily bonus of ${randomNumber} added!`); } //buy carriages //add carriages button const carriageButton = document.createElement("button"); carriageButton.id = "trainbutton"; carriageButton.textContent = "Buy Train Carriage"; const carriageMessage = document.createElement("p"); carriageMessage.textContent = `Buy another passenger carriage for your train for £20,000`; instructionsElement.appendChild(carriageMessage); // Append the button element to the instructions element: instructionsElement.appendChild(carriageButton); //cariagebutton logic carriageButton.addEventListener("click", () => { console.log("Carriage Bought"); // Check if enough money is available if (money >= 20000) { // Check if maximum number of carriages reached if (numberOfCarriages < 4) { numberOfCarriages++; money -= 20000; // Subtract 20000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Update marker content using the previously retrieved reference markerContent.textContent = numberOfCarriages; } else { console.log( "Maximum number of carriages reached! You can't buy more." ); instructionsElement.removeChild(carriageButton); instructionsElement.removeChild(carriageMessage); } } }); //buy station cafes //add station one cafe button const stationOneMessage = document.createElement("p"); stationOneMessage.textContent = `Open a cafe in ${firstCity} Station for £2,500.`; instructionsElement.appendChild(stationOneMessage); // Add button element: const cafeOneButton = document.createElement("button"); cafeOneButton.id = "trainbutton"; cafeOneButton.textContent = "Buy Cafe"; // Append the button element to the instructions element: instructionsElement.appendChild(cafeOneButton); //cafeonelogic cafeOneButton.addEventListener("click", () => { if (money >= 2500) { // add a random number between 2000 and 7000 to dailbonus generateDailyBonus(2000, 7000); // Call with cafe bonus range cafeOneBonus = dailybonus; console.log("Cafe one bought"); money -= 2500; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(cafeOneButton); instructionsElement.removeChild(stationOneMessage); } else { } }); //add station two cafe buttons const stationTwoMessage = document.createElement("p"); stationTwoMessage.textContent = `Open a cafe in ${secondCity} Station for £2,500.`; instructionsElement.appendChild(stationTwoMessage); // Add button element: const cafeTwoButton = document.createElement("button"); cafeTwoButton.id = "trainbutton"; cafeTwoButton.textContent = "Buy Cafe"; // Append the button element to the instructions element: instructionsElement.appendChild(cafeTwoButton); //cafetwologic cafeTwoButton.addEventListener("click", () => { if (money >= 2500) { // Generate a random number between 2000 (inclusive) and 7000 (exclusive) generateDailyBonus(2000, 7000); // Call with cafe bonus range cafeTwoBonus = dailybonus; console.log("Cafe two bought"); money -= 2500; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(cafeTwoButton); instructionsElement.removeChild(stationTwoMessage); } else { } }); //buyhotel const hoteloneMessage = document.createElement("p"); hoteloneMessage.textContent = `Open a hotel in ${firstCity} Station for £10,000.`; instructionsElement.appendChild(hoteloneMessage); // Add button element: const hoteloneButton = document.createElement("button"); hoteloneButton.id = "trainbutton"; hoteloneButton.textContent = "Buy Hotel"; // Append the button element to the instructions element: instructionsElement.appendChild(hoteloneButton); //hotelonelogic hoteloneButton.addEventListener("click", () => { if (money >= 10000) { generateDailyBonus(8000, 24000); // Call with cafe bonus range hotelOneBonus = dailybonus; money -= 10000; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(hoteloneButton); instructionsElement.removeChild(hoteloneMessage); } else { } }); const hoteltwoMessage = document.createElement("p"); hoteltwoMessage.textContent = `Open a hotel in ${secondCity} Station for £10,000.`; instructionsElement.appendChild(hoteltwoMessage); // Add button element: const hoteltwoButton = document.createElement("button"); hoteltwoButton.id = "trainbutton"; hoteltwoButton.textContent = "Buy Hotel"; // Append the button element to the instructions element: instructionsElement.appendChild(hoteltwoButton); //hotelonelogic hoteltwoButton.addEventListener("click", () => { if (money >= 10000) { generateDailyBonus(8000, 24000); // Call with cafe bonus range hotelTwoBonus = dailybonus; money -= 10000; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(hoteltwoButton); instructionsElement.removeChild(hoteltwoMessage); } else { } }); // starttrain const firstPoint = L.latLng( firstCityCoords[1], firstCityCoords[0] ); const secondPoint = L.latLng( secondCityCoords[1], secondCityCoords[0] ); const intervalDuration = 10; // milliseconds per frame const distance = firstPoint.distanceTo(secondPoint); const steps = ((distance / speed) * 1000) / intervalDuration; // Assuming speed of 35 miles per hour const latStep = (secondPoint.lat - firstPoint.lat) / steps; const lngStep = (secondPoint.lng - firstPoint.lng) / steps; const marker = L.marker(firstPoint, { icon: L.divIcon({ className: "circle-marker", // Add a CSS class for styling (optional) html: `<b>${numberOfCarriages}</b>`, // Include the number inside a bold tag iconSize: [20, 20], // Adjust iconSize as needed (optional) }), }).addTo(map); // Assuming the marker variable is defined in this scope const markerContent = marker.getElement().querySelector("b"); // Assuming bold tag for number const moveMarker = (speed) => { if (progress < steps) { const newLat = firstPoint.lat + latStep * progress; const newLng = firstPoint.lng + lngStep * progress; const newLatLng = L.latLng(newLat, newLng); marker.setLatLng(newLatLng); // Update the marker's position progress++; setTimeout(function () { moveMarker(speed); }, intervalDuration); } else { // Marker reaches the second point, update money money += Math.floor(Math.random() * (2000 - 1000 + 1)) + 1000 * numberOfCarriages; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Wait two seconds before animating back and call moveBackMarker recursively setTimeout(() => { moveBackMarker(speed); }, 2000); // Wait for 2 seconds (2000 milliseconds) } }; const moveBackMarker = (speed) => { // Corrected calculation for animating back from second point to first if (progress > 0) { const newLat = secondPoint.lat - latStep * (steps - progress); const newLng = secondPoint.lng - lngStep * (steps - progress); const newLatLng = L.latLng(newLat, newLng); marker.setLatLng(newLatLng); // Update the marker's position progress--; setTimeout(function () { moveBackMarker(speed); }, intervalDuration); } else { console.log("Reached starting point again."); // Add random number to money and update display money += Math.floor(Math.random() * (2000 - 1000 + 1)) + 1000 * numberOfCarriages; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Reset progress for next round trip progress = 0; // Recursively call moveMarker to start next animation cycle moveMarker(speed); } }; moveMarker(speed); // Start the animation }); }); } } }); return circleMarker; }, }); } fetch("gb.geojson") .then((response) => response.json()) .then((geojson) => { L.geoJSON(geojson, { fillColor: "none", // Style for polygon (empty fill) weight: 1, color: "#000", opacity: 1, fillOpacity: 0, }).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); }); fetch("cities.geojson") .then((response) => response.json()) .then((geojson) => { createCircleMarkers(geojson).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); }); //24 hour clock display const TIME_MULTIPLIER = 60 * 10; // 10 minutes = 600 seconds // Function to format time in 24-hour format with leading zeros function formatTime(hours, minutes) { // Handle the case where minutes reach 60 (should display the next hour) if (minutes === 60) { hours++; minutes = 0; } return `${hours.toString().padStart(2, "0")}:${minutes .toString() .padStart(2, "0")}`; } // Function to update the clock display and handle daily bonus function updateClock() { const currentTime = new Date(); // Simulate game time by multiplying actual time with multiplier const gameTime = new Date(currentTime.getTime() * TIME_MULTIPLIER); // Get hours and minutes in 24-hour format let hours = gameTime.getHours(); // Get minutes and force them to the nearest multiple of 10 (ending in 0) let minutes = Math.floor(gameTime.getMinutes() / 10) * 10; // Format the time string with fixed minute handling const formattedTime = formatTime(hours, minutes); // Update the content of the div with the formatted time document.getElementById("timedisplay").textContent = formattedTime; // Check if it's midnight (00:00) if (hours === 0 && minutes === 0) { // Generate random daily bonus (modify as needed) money += cafeOneBonus + cafeTwoBonus + hotelOneBonus; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; console.log( `Daily bonus of ${ cafeOneBonus + cafeTwoBonus + hotelOneBonus + hotelTwoBonus } added! Total money: ${money}` ); // You can replace console.log with your desired action } } // Call the updateClock function initially updateClock(); // Update the clock every second to simulate smooth time progression setInterval(updateClock, 1000); '
9be8cb639daa6fd422ebd3e0b74e5e29
{ "intermediate": 0.3464096784591675, "beginner": 0.424446702003479, "expert": 0.22914355993270874 }
46,441
You are a world class software engineer. I need you to draft a technical software spec for building the following: {{write a complete python gui program that can be translate the documents using free google translate without API including the advanced mode that should have: A User options for specific list of language = (En, Am, Or and Tigrinya) A User option that explores and select specific document file from local computer automatically when start custom dictionary definition options for each lists of language as option if need!}} Think through how you would build it step by step. Then, respond with the complete spec as a well-organized markdown file. I will then reply with "build," and you will proceed to implement the exact spec, writing all of the code needed. I will periodically interject with "continue" to prompt you to keep going. Continue until complete.
cef1da88b44e82ba869ab3d37d6dbe9d
{ "intermediate": 0.41258323192596436, "beginner": 0.2333202064037323, "expert": 0.35409656167030334 }
46,442
I am working in power apps I have a canvas app. I have 3 buttons on the side and a gallery setup with an edit form connected to my data. When I press one button I want it to go to another edit from connected to another list how would I do that
d57d97a123ac1383848723825154b1f1
{ "intermediate": 0.5545562505722046, "beginner": 0.16666747629642487, "expert": 0.27877625823020935 }
46,443
#include <iostream> #include <fstream> #include <vector> #include <sstream> using namespace std; const int INF = 1e9; // Assuming INF represents infinity class floydGraphProcessor { public: void processInput(const string &line, ifstream &infile, ofstream &outfile) { // Extract problem number and matrix size size_t problem_position = line.find("Problem"); if (problem_position == string::npos) { cerr << "Error extracting parameters. \n"; return; } int problemNumber, n; sscanf(line.c_str() + problem_position, "Problem%d", &problemNumber); // Extracting n from the line size_t n_position = line.find("n = "); if (n_position == string::npos) { cerr << "Error: 'n =' not found.\n"; return; } sscanf(line.c_str() + n_position, "n = %d", &n); // Resize output matrix to n x n vector<vector<int>> matrix(n, vector<int>(n)); // Read n x n matrix values for (int i = 0; i < n; i++) { string r; getline(infile, r); istringstream iss(r); for (int j = 0; j < n; j++) { iss >> matrix[i][j]; } } // Output to file outfile << "Problem " << problemNumber << ": n = " << n << endl; vector<vector<int>> dist = matrix; vector<vector<int>> P(n, vector<int>(n, 0)); // Floyd-Warshall algorithm for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (k != i && k != j && (dist[i][j] >= dist[i][k] + dist[k][j])) { dist[i][j] = dist[i][k] + dist[k][j]; P[i][j] = k + 1; } } } } // Output final Pmatrix to file outfile << "Pmatrix:" << endl; printPath(P, n, outfile); outfile << endl; // shortest paths and length to file for (int i = 0; i < n; i++) { outfile << "V" << i + 1 << "-Vj: shortest path and length" << endl; for (int j = 0; j < n; j++) { outfile << "V" << i + 1 << " "; if (i != j) { outfile << "V" << j + 1 << " "; int v = j; while (P[i][v] != 0) { outfile << "V" << P[i][v] << " "; v = P[i][v] - 1; } } outfile << ": " << dist[i][j] << endl; } } } private: void printPath(const vector<vector<int>> &P, int n, ofstream &outfile) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { outfile << P[i][j] << " "; } outfile << endl; } } }; int main(int argc, char *argv[]) { if (argc != 2) { cerr << "Usage: " << argv[0] << " <input_file_path>" << endl; return 1; } ifstream infile(argv[1]); if (!infile.is_open()) { cerr << "Error!. Wrong usage of the file, error opening the file. " << endl; cout << "Correct usage : " << argv[0] << " <input_file_path>" << endl; return 1; } ofstream outfile("output.txt"); if (!outfile.is_open()) { cerr << "Error opening output file." << endl; return 1; } string line; floydGraphProcessor processor; while (getline(infile, line)) { size_t found = line.find("Problem"); if (found != string::npos) { processor.processInput(line, infile, outfile); } } infile.close(); outfile.close(); return 0; } Write the same program in Java with the same logic as applied in this program.
66615473931c19d4120782d134d433ca
{ "intermediate": 0.35287392139434814, "beginner": 0.2890014946460724, "expert": 0.35812461376190186 }
46,444
in this javascript for leaflet.js how can i create an array for the two circle markers added to the map for firstpoint and secondpoint - '// Function to create circle markers with click functionality function createCircleMarkers(geojson) { return L.geoJSON(geojson, { pointToLayer: function (feature, latlng) { const circleMarker = L.circleMarker(latlng, { radius: 4, fillColor: "#ff7800", color: "#000", weight: 0.2, opacity: 1, fillOpacity: 0.8, }); // Attach the feature to the circle marker circleMarker.feature = feature; circleMarker.on("mouseover", function () { this.bindPopup(feature.properties.city).openPopup(); }); circleMarker.on("click", function (e) { if (!isLineDrawn) { clickedPoints.push(e.target); // Push the circle marker with attached feature if (clickedPoints.length === 2) { const firstCityCoords = clickedPoints[0].feature.geometry.coordinates; const secondCityCoords = clickedPoints[1].feature.geometry.coordinates; const polyline = L.polyline( clickedPoints.map((p) => p.getLatLng()) ).addTo(map); const firstCity = clickedPoints[0].feature.properties.city; const secondCity = clickedPoints[1].feature.properties.city; clickedPoints = []; isLineDrawn = true; // Remove click event listener after a line has been drawn map.off("click"); // Set the map bounds to show the area with the polyline map.fitBounds(polyline.getBounds()); money = money - 50000; // Subtract 50000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; // Assuming money is a number moneyDisplay.textContent = moneyString; const instructionsElement = document.getElementById("instructions"); // Clear any existing content in the instructions element: instructionsElement.innerHTML = ""; // Create separate paragraph elements: const congratulationsParagraph = document.createElement("p"); congratulationsParagraph.textContent = `Congratulations you have built your first train line from ${firstCity} to ${secondCity}!`; const costsParagraph = document.createElement("p"); costsParagraph.textContent = `Your construction costs were £50,000. You have £50,000 remaining.`; const buyTrainParagraph = document.createElement("p"); buyTrainParagraph.textContent = "You now need to buy a train."; const newTrainParagraph = document.createElement("p"); newTrainParagraph.textContent = "At this time you can only afford to buy the train engine the Sleeping Lion. The Sleeping Lion has a traveling speed of 60 miles per hour. It can pull four carriages. Which means your train will have a capacity of around 120 seated passengers"; const traincost = document.createElement("p"); traincost.textContent = `The Sleeping Lion will cost you £30,000 to purchase. Do you wish to buy the Sleeping Lion?`; // Append paragraphs to the instructions element: instructionsElement.appendChild(congratulationsParagraph); instructionsElement.appendChild(costsParagraph); instructionsElement.appendChild(buyTrainParagraph); instructionsElement.appendChild(newTrainParagraph); instructionsElement.appendChild(traincost); // Add button element: const buyButton = document.createElement("button"); buyButton.id = "buybutton"; buyButton.textContent = "Buy Train"; // Append the button element to the instructions element: instructionsElement.appendChild(buyButton); //buybutton event listener document .getElementById("buybutton") .addEventListener("click", function () { // Check if you have enough money before purchase money = money - 30000; // Subtract 30000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Update instructions content after successful purchase instructionsElement.innerHTML = ""; // Clear previous content const successMessage = document.createElement("p"); successMessage.textContent = `You now have a train line from ${firstCity} to ${secondCity} and a train! Press the button below to begin operations.`; instructionsElement.appendChild(successMessage); // Add button element: const trainButton = document.createElement("button"); trainButton.id = "trainbutton"; trainButton.textContent = "Start Train"; // Append the button element to the instructions element: instructionsElement.appendChild(trainButton); trainButton.addEventListener("click", function () { console.log("Train Started"); //emptyinstructions add improvement buttons instructionsElement.innerHTML = ""; // Clear previous content //randomgeneration of dailybonus function generateDailyBonus(minBonus, maxBonus) { const randomNumber = Math.floor(Math.random() * (maxBonus - minBonus + 1)) + minBonus; dailybonus += randomNumber; console.log(`Daily bonus of ${randomNumber} added!`); } //buy carriages //add carriages button const carriageButton = document.createElement("button"); carriageButton.id = "trainbutton"; carriageButton.textContent = "Buy Train Carriage"; const carriageMessage = document.createElement("p"); carriageMessage.textContent = `Buy another passenger carriage for your train for £20,000`; instructionsElement.appendChild(carriageMessage); // Append the button element to the instructions element: instructionsElement.appendChild(carriageButton); //cariagebutton logic carriageButton.addEventListener("click", () => { console.log("Carriage Bought"); // Check if enough money is available if (money >= 20000) { // Check if maximum number of carriages reached if (numberOfCarriages < 4) { numberOfCarriages++; money -= 20000; // Subtract 20000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Update marker content using the previously retrieved reference markerContent.textContent = numberOfCarriages; } else { console.log( "Maximum number of carriages reached! You can't buy more." ); instructionsElement.removeChild(carriageButton); instructionsElement.removeChild(carriageMessage); } } }); //buy station cafes //add station one cafe button const stationOneMessage = document.createElement("p"); stationOneMessage.textContent = `Open a cafe in ${firstCity} Station for £2,500.`; instructionsElement.appendChild(stationOneMessage); // Add button element: const cafeOneButton = document.createElement("button"); cafeOneButton.id = "trainbutton"; cafeOneButton.textContent = "Buy Cafe"; // Append the button element to the instructions element: instructionsElement.appendChild(cafeOneButton); //cafeonelogic cafeOneButton.addEventListener("click", () => { if (money >= 2500) { // add a random number between 2000 and 7000 to dailbonus generateDailyBonus(2000, 7000); // Call with cafe bonus range cafeOneBonus = dailybonus; console.log("Cafe one bought"); money -= 2500; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(cafeOneButton); instructionsElement.removeChild(stationOneMessage); } else { } }); //add station two cafe buttons const stationTwoMessage = document.createElement("p"); stationTwoMessage.textContent = `Open a cafe in ${secondCity} Station for £2,500.`; instructionsElement.appendChild(stationTwoMessage); // Add button element: const cafeTwoButton = document.createElement("button"); cafeTwoButton.id = "trainbutton"; cafeTwoButton.textContent = "Buy Cafe"; // Append the button element to the instructions element: instructionsElement.appendChild(cafeTwoButton); //cafetwologic cafeTwoButton.addEventListener("click", () => { if (money >= 2500) { // Generate a random number between 2000 (inclusive) and 7000 (exclusive) generateDailyBonus(2000, 7000); // Call with cafe bonus range cafeTwoBonus = dailybonus; console.log("Cafe two bought"); money -= 2500; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(cafeTwoButton); instructionsElement.removeChild(stationTwoMessage); } else { } }); //buyhotel const hoteloneMessage = document.createElement("p"); hoteloneMessage.textContent = `Open a hotel in ${firstCity} Station for £10,000.`; instructionsElement.appendChild(hoteloneMessage); // Add button element: const hoteloneButton = document.createElement("button"); hoteloneButton.id = "trainbutton"; hoteloneButton.textContent = "Buy Hotel"; // Append the button element to the instructions element: instructionsElement.appendChild(hoteloneButton); //hotelonelogic hoteloneButton.addEventListener("click", () => { if (money >= 10000) { generateDailyBonus(8000, 24000); // Call with cafe bonus range hotelOneBonus = dailybonus; money -= 10000; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(hoteloneButton); instructionsElement.removeChild(hoteloneMessage); } else { } }); const hoteltwoMessage = document.createElement("p"); hoteltwoMessage.textContent = `Open a hotel in ${secondCity} Station for £10,000.`; instructionsElement.appendChild(hoteltwoMessage); // Add button element: const hoteltwoButton = document.createElement("button"); hoteltwoButton.id = "trainbutton"; hoteltwoButton.textContent = "Buy Hotel"; // Append the button element to the instructions element: instructionsElement.appendChild(hoteltwoButton); //hotelonelogic hoteltwoButton.addEventListener("click", () => { if (money >= 10000) { generateDailyBonus(8000, 24000); // Call with cafe bonus range hotelTwoBonus = dailybonus; money -= 10000; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; instructionsElement.removeChild(hoteltwoButton); instructionsElement.removeChild(hoteltwoMessage); } else { } }); // starttrain const firstPoint = L.latLng( firstCityCoords[1], firstCityCoords[0] ); const secondPoint = L.latLng( secondCityCoords[1], secondCityCoords[0] ); const intervalDuration = 10; // milliseconds per frame const distance = firstPoint.distanceTo(secondPoint); const steps = ((distance / speed) * 1000) / intervalDuration; // Assuming speed of 35 miles per hour const latStep = (secondPoint.lat - firstPoint.lat) / steps; const lngStep = (secondPoint.lng - firstPoint.lng) / steps; const marker = L.marker(firstPoint, { icon: L.divIcon({ className: 'circle-marker', // Add a CSS class for styling (optional) html: `<b>${numberOfCarriages}</b>`, // Include the number inside a bold tag iconSize: [20, 20] // Adjust iconSize as needed (optional) }) }).addTo(map); '
b2fab73516cc6c825f4f5f906a172bdd
{ "intermediate": 0.320561021566391, "beginner": 0.4089466631412506, "expert": 0.2704923152923584 }
46,445
in this javascript for leaflet.js why are the firstCircleMarker and secondCircleMarker not having their radius changed to 8 when the cafeOneButton and cafeTwoButton is pressed - 'var money = 100000; var numberOfCarriages = 1; var speed = 60; var dailybonus = 0; const map = L.map("map").setView([54.2231637, -1.9381623], 6); // Add custom zoom control to the map with position set to ‘topright’ const customZoomControl = L.control.zoom({ position: "topright" }).addTo(map); // Remove the default zoom control from the map map.removeControl(map.zoomControl); let clickedPoints = []; let isLineDrawn = false; let marker; // Declare the marker variable let progress = 0; let cafeOneBonus = 0; let cafeTwoBonus = 0; let hotelOneBonus = 0; let hotelTwoBonus = 0; let circleMarkers = []; let firstCircleMarker; let secondCircleMarker; const increaseSpeed = () => {  const speedIncrease = 20;  speed += speedIncrease; }; // Function to create circle markers with click functionality function createCircleMarkers(geojson) {  return L.geoJSON(geojson, {   pointToLayer: function (feature, latlng) {    const circleMarker = L.circleMarker(latlng, {     radius: 4,     fillColor: "#ff7800",     color: "#000",     weight: 0.2,     opacity: 1,     fillOpacity: 0.8,    });    // Push the circle marker to the array    circleMarkers.push(circleMarker);    // Attach the feature to the circle marker    circleMarker.feature = feature;    circleMarker.on("mouseover", function () {     this.bindPopup(feature.properties.city).openPopup();    });    circleMarker.on("click", function (e) {     if (!isLineDrawn) {      clickedPoints.push(e.target); // Push the circle marker with attached feature      if (clickedPoints.length === 2) {       const firstCityCoords =        clickedPoints[0].feature.geometry.coordinates;       const secondCityCoords =        clickedPoints[1].feature.geometry.coordinates;       // Update the global markers       firstCircleMarker = circleMarkers[0];       secondCircleMarker = circleMarkers[1];       const polyline = L.polyline(        clickedPoints.map((p) => p.getLatLng())       ).addTo(map);       const firstCity = clickedPoints[0].feature.properties.city;       const secondCity = clickedPoints[1].feature.properties.city;       clickedPoints = [];       isLineDrawn = true;       // Remove click event listener after a line has been drawn       map.off("click");       // Set the map bounds to show the area with the polyline       map.fitBounds(polyline.getBounds());       money = money - 50000; // Subtract 50000 from money       const moneyDisplay = document.getElementById("moneydisplay");       const moneyString = `£${money}`; // Assuming money is a number       moneyDisplay.textContent = moneyString;       const instructionsElement = document.getElementById("instructions");       // Clear any existing content in the instructions element:       instructionsElement.innerHTML = "";       // Create separate paragraph elements:       const congratulationsParagraph = document.createElement("p");       congratulationsParagraph.textContent = `Congratulations you have built your first train line from ${firstCity} to ${secondCity}!`;       const costsParagraph = document.createElement("p");       costsParagraph.textContent = `Your construction costs were £50,000. You have £50,000 remaining.`;       const buyTrainParagraph = document.createElement("p");       buyTrainParagraph.textContent = "You now need to buy a train.";       const newTrainParagraph = document.createElement("p");       newTrainParagraph.textContent =        "At this time you can only afford to buy the train engine the Sleeping Lion. The Sleeping Lion has a traveling speed of 60 miles per hour. It can pull four carriages. Which means your train will have a capacity of around 120 seated passengers";       const traincost = document.createElement("p");       traincost.textContent = `The Sleeping Lion will cost you £30,000 to purchase. Do you wish to buy the Sleeping Lion?`;       // Append paragraphs to the instructions element:       instructionsElement.appendChild(congratulationsParagraph);       instructionsElement.appendChild(costsParagraph);       instructionsElement.appendChild(buyTrainParagraph);       instructionsElement.appendChild(newTrainParagraph);       instructionsElement.appendChild(traincost);       // Add button element:       const buyButton = document.createElement("button");       buyButton.id = "buybutton";       buyButton.textContent = "Buy Train";       // Append the button element to the instructions element:       instructionsElement.appendChild(buyButton);       //buybutton event listener       document        .getElementById("buybutton")        .addEventListener("click", function () {         // Check if you have enough money before purchase         money = money - 30000; // Subtract 30000 from money         const moneyDisplay = document.getElementById("moneydisplay");         const moneyString = `£${money}`;         moneyDisplay.textContent = moneyString;         // Update instructions content after successful purchase         instructionsElement.innerHTML = ""; // Clear previous content         const successMessage = document.createElement("p");         successMessage.textContent = `You now have a train line from ${firstCity} to ${secondCity} and a train! Press the button below to begin operations.`;         instructionsElement.appendChild(successMessage);         // Add button element:         const trainButton = document.createElement("button");         trainButton.id = "trainbutton";         trainButton.textContent = "Start Train";         // Append the button element to the instructions element:         instructionsElement.appendChild(trainButton);         trainButton.addEventListener("click", function () {          console.log("Train Started");          //emptyinstructions add improvement buttons          instructionsElement.innerHTML = ""; // Clear previous content          //randomgeneration of dailybonus          function generateDailyBonus(minBonus, maxBonus) {           const randomNumber =            Math.floor(Math.random() * (maxBonus - minBonus + 1)) +            minBonus;           dailybonus += randomNumber;           console.log(`Daily bonus of ${randomNumber} added!`);          }          //buy carriages          //add carriages button          const carriageButton = document.createElement("button");          carriageButton.id = "trainbutton";          carriageButton.textContent = "Buy Train Carriage";          const carriageMessage = document.createElement("p");          carriageMessage.textContent = `Buy another passenger carriage for your train for £20,000`;          instructionsElement.appendChild(carriageMessage);          // Append the button element to the instructions element:          instructionsElement.appendChild(carriageButton);          //cariagebutton logic          carriageButton.addEventListener("click", () => {           console.log("Carriage Bought");           // Check if enough money is available           if (money >= 20000) {            // Check if maximum number of carriages reached            if (numberOfCarriages < 4) {             numberOfCarriages++;             money -= 20000; // Subtract 20000 from money             const moneyDisplay =              document.getElementById("moneydisplay");             const moneyString = `£${money}`;             moneyDisplay.textContent = moneyString;             // Update marker content using the previously retrieved reference             markerContent.textContent = numberOfCarriages;            } else {             console.log(              "Maximum number of carriages reached! You can't buy more."             );             instructionsElement.removeChild(carriageButton);             instructionsElement.removeChild(carriageMessage);            }           }          });          //buy station cafes          //add station one cafe button          const stationOneMessage = document.createElement("p");          stationOneMessage.textContent = `Open a cafe in ${firstCity} Station for £2,500.`;          instructionsElement.appendChild(stationOneMessage);          // Add button element:          const cafeOneButton = document.createElement("button");          cafeOneButton.id = "trainbutton";          cafeOneButton.textContent = "Buy Cafe";          // Append the button element to the instructions element:          instructionsElement.appendChild(cafeOneButton);          //cafeonelogic          cafeOneButton.addEventListener("click", () => {           if (money >= 2500) {            // add a random number between 2000 and 7000 to dailbonus            generateDailyBonus(2000, 7000); // Call with cafe bonus range            cafeOneBonus = dailybonus;            console.log("Cafe one bought");            money -= 2500;            if (firstCircleMarker) {             firstCircleMarker.setRadius(40);            }            const moneyDisplay =             document.getElementById("moneydisplay");            const moneyString = `£${money}`;            moneyDisplay.textContent = moneyString;            instructionsElement.removeChild(cafeOneButton);            instructionsElement.removeChild(stationOneMessage);           } else {           }          });          //add station two cafe buttons          const stationTwoMessage = document.createElement("p");          stationTwoMessage.textContent = `Open a cafe in ${secondCity} Station for £2,500.`;          instructionsElement.appendChild(stationTwoMessage);          // Add button element:          const cafeTwoButton = document.createElement("button");          cafeTwoButton.id = "trainbutton";          cafeTwoButton.textContent = "Buy Cafe";          // Append the button element to the instructions element:          instructionsElement.appendChild(cafeTwoButton);          //cafetwologic          cafeTwoButton.addEventListener("click", () => {           if (money >= 2500) {            // Generate a random number between 2000 (inclusive) and 7000 (exclusive)            generateDailyBonus(2000, 7000); // Call with cafe bonus range            cafeTwoBonus = dailybonus;            console.log("Cafe two bought");            money -= 2500;            if (secondCircleMarker) {             secondCircleMarker.setRadius(40);            }            const moneyDisplay =             document.getElementById("moneydisplay");            const moneyString = `£${money}`;            moneyDisplay.textContent = moneyString;            instructionsElement.removeChild(cafeTwoButton);            instructionsElement.removeChild(stationTwoMessage);           } else {           }          });          //buyhotel          const hoteloneMessage = document.createElement("p");          hoteloneMessage.textContent = `Open a hotel in ${firstCity} Station for £10,000.`;          instructionsElement.appendChild(hoteloneMessage);          // Add button element:          const hoteloneButton = document.createElement("button");          hoteloneButton.id = "trainbutton";          hoteloneButton.textContent = "Buy Hotel";          // Append the button element to the instructions element:          instructionsElement.appendChild(hoteloneButton);          //hotelonelogic          hoteloneButton.addEventListener("click", () => {           if (money >= 10000) {            generateDailyBonus(8000, 24000); // Call with cafe bonus range            hotelOneBonus = dailybonus;            money -= 10000;            const moneyDisplay =             document.getElementById("moneydisplay");            const moneyString = `£${money}`;            moneyDisplay.textContent = moneyString;            instructionsElement.removeChild(hoteloneButton);            instructionsElement.removeChild(hoteloneMessage);           } else {           }          });          const hoteltwoMessage = document.createElement("p");          hoteltwoMessage.textContent = `Open a hotel in ${secondCity} Station for £10,000.`;          instructionsElement.appendChild(hoteltwoMessage);          // Add button element:          const hoteltwoButton = document.createElement("button");          hoteltwoButton.id = "trainbutton";          hoteltwoButton.textContent = "Buy Hotel";          // Append the button element to the instructions element:          instructionsElement.appendChild(hoteltwoButton);          //hotelonelogic          hoteltwoButton.addEventListener("click", () => {           if (money >= 10000) {            generateDailyBonus(8000, 24000); // Call with cafe bonus range            hotelTwoBonus = dailybonus;            money -= 10000;            const moneyDisplay =             document.getElementById("moneydisplay");            const moneyString = `£${money}`;            moneyDisplay.textContent = moneyString;            instructionsElement.removeChild(hoteltwoButton);            instructionsElement.removeChild(hoteltwoMessage);           } else {           }          });          // starttrain          const firstPoint = L.latLng(           firstCityCoords[1],           firstCityCoords[0]          );          const secondPoint = L.latLng(           secondCityCoords[1],           secondCityCoords[0]          );          const intervalDuration = 10; // milliseconds per frame          const distance = firstPoint.distanceTo(secondPoint);          const steps = ((distance / speed) * 1000) / intervalDuration; // Assuming speed of 35 miles per hour          const latStep = (secondPoint.lat - firstPoint.lat) / steps;          const lngStep = (secondPoint.lng - firstPoint.lng) / steps;          const marker = L.marker(firstPoint, {           icon: L.divIcon({            className: "circle-marker", // Add a CSS class for styling (optional)            html: `<b>${numberOfCarriages}</b>`, // Include the number inside a bold tag            iconSize: [20, 20], // Adjust iconSize as needed (optional)           }),          }).addTo(map);          // Assuming the marker variable is defined in this scope          const markerContent = marker.getElement().querySelector("b"); // Assuming bold tag for number          const moveMarker = (speed) => {           if (progress < steps) {            const newLat = firstPoint.lat + latStep * progress;            const newLng = firstPoint.lng + lngStep * progress;            const newLatLng = L.latLng(newLat, newLng);            marker.setLatLng(newLatLng); // Update the marker's position            progress++;            setTimeout(function () {             moveMarker(speed);            }, intervalDuration);           } else {            // Marker reaches the second point, update money            money +=             Math.floor(Math.random() * (2000 - 1000 + 1)) +             1000 * numberOfCarriages;            const moneyDisplay =             document.getElementById("moneydisplay");            const moneyString = `£${money}`;            moneyDisplay.textContent = moneyString;            // Wait two seconds before animating back and call moveBackMarker recursively            setTimeout(() => {             moveBackMarker(speed);            }, 2000); // Wait for 2 seconds (2000 milliseconds)           }          };          const moveBackMarker = (speed) => {           // Corrected calculation for animating back from second point to first           if (progress > 0) {            const newLat =             secondPoint.lat - latStep * (steps - progress);            const newLng =             secondPoint.lng - lngStep * (steps - progress);            const newLatLng = L.latLng(newLat, newLng);            marker.setLatLng(newLatLng); // Update the marker's position            progress--;            setTimeout(function () {             moveBackMarker(speed);            }, intervalDuration);           } else {            console.log("Reached starting point again.");            // Add random number to money and update display            money +=             Math.floor(Math.random() * (2000 - 1000 + 1)) +             1000 * numberOfCarriages;            const moneyDisplay =             document.getElementById("moneydisplay");            const moneyString = `£${money}`;            moneyDisplay.textContent = moneyString;            // Reset progress for next round trip            progress = 0;            // Recursively call moveMarker to start next animation cycle            moveMarker(speed);           }          };          moveMarker(speed); // Start the animation         });        });      }     }    });    return circleMarker;   },  }); } fetch("gb.geojson")  .then((response) => response.json())  .then((geojson) => {   L.geoJSON(geojson, {    fillColor: "none", // Style for polygon (empty fill)    weight: 1,    color: "#000",    opacity: 1,    fillOpacity: 0,   }).addTo(map);  })  .catch((error) => {   console.error("Error loading GeoJSON:", error);  }); fetch("cities.geojson")  .then((response) => response.json())  .then((geojson) => {   createCircleMarkers(geojson).addTo(map);  })  .catch((error) => {   console.error("Error loading GeoJSON:", error);  }); //24 hour clock display const TIME_MULTIPLIER = 60 * 10; // 10 minutes = 600 seconds // Function to format time in 24-hour format with leading zeros function formatTime(hours, minutes) {  // Handle the case where minutes reach 60 (should display the next hour)  if (minutes === 60) {   hours++;   minutes = 0;  }  return `${hours.toString().padStart(2, "0")}:${minutes   .toString()   .padStart(2, "0")}`; } // Function to update the clock display and handle daily bonus function updateClock() {  const currentTime = new Date();  // Simulate game time by multiplying actual time with multiplier  const gameTime = new Date(currentTime.getTime() * TIME_MULTIPLIER);  // Get hours and minutes in 24-hour format  let hours = gameTime.getHours();  // Get minutes and force them to the nearest multiple of 10 (ending in 0)  let minutes = Math.floor(gameTime.getMinutes() / 10) * 10;  // Format the time string with fixed minute handling  const formattedTime = formatTime(hours, minutes);  // Update the content of the div with the formatted time  document.getElementById("timedisplay").textContent = formattedTime;  // Check if it's midnight (00:00)  if (hours === 0 && minutes === 0) {   // Generate random daily bonus (modify as needed)   money += cafeOneBonus + cafeTwoBonus + hotelOneBonus;   const moneyDisplay = document.getElementById("moneydisplay");   const moneyString = `£${money}`;   moneyDisplay.textContent = moneyString;   console.log(    `Daily bonus of ${     cafeOneBonus + cafeTwoBonus + hotelOneBonus + hotelTwoBonus    } added! Total money: ${money}`   ); // You can replace console.log with your desired action  } } // Call the updateClock function initially updateClock(); // Update the clock every second to simulate smooth time progression setInterval(updateClock, 1000); '
badd164ca1ba7712af127bf7f1690b18
{ "intermediate": 0.3350129723548889, "beginner": 0.39272087812423706, "expert": 0.272266149520874 }
46,446
import java.io.*; import java.util.Scanner; public class floyd { private static final int INF = (int) 1e9; // Assuming this might be used for initialization public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: java floyd <input_file_path>"); return; } String filePath = args[0]; try { Scanner scanner = new Scanner(new File(filePath)); PrintWriter writer = new PrintWriter("output.txt"); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("Problem")) { processInput(line, scanner, writer); } } scanner.close(); writer.close(); } catch (FileNotFoundException e) { System.err.println("File not found: " + e.getMessage()); } } private static void processInput(String line, Scanner scanner, PrintWriter writer) { // Initial splitting to identify the problem number String[] initialParts = line.split(" "); int problemNumber; try { // Assuming the line starts with "ProblemX" where X is the problem number problemNumber = Integer.parseInt(initialParts[0].replaceAll("[^0-9]", "")); } catch (NumberFormatException e) { System.err.println("Error parsing problem number from line: " + line); return; // Skip this problem due to parsing error } // Already read the line containing "Amatrix:", no need to skip // Directly extract "n" String nText = initialParts[2]; // Based on the assumption it’s at the third position int n = Integer.parseInt(nText); // Initialize distance and path matrices with appropriate values int[][] dist = new int[n][n]; int[][] P = new int[n][n]; // Read n x n matrix values for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (scanner.hasNextInt()) { // Added check to ensure there’s an integer to read dist[i][j] = scanner.nextInt(); // Fill the distance matrix P[i][j] = 0; // Initialization implying no intermediate vertex yet } } } for(int k = 0; k < n; k++) { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; P[i][j] = k+1; // Store intermediate vertex } } } } writer.printf("Problem %d: n = %d\n", problemNumber, n); writer.println("Pmatrix:"); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { writer.print(P[i][j] + " "); } writer.println(); } for(int i = 0; i < n; i++) { writer.printf("V%d-Vj: shortest path and length\n", i+1); for(int j = 0; j < n; j++) { displayPath(i, j, P, writer, ""); writer.printf(": %d\n", dist[i][j]); } } writer.println(); } private static void displayPath(int i, int j, int[][] P, PrintWriter writer, String path) { if(P[i][j] == 0) { if(!path.contains("V" + (j+1))) { writer.print(path + "V" + (j+1) + " "); } return; } displayPath(i, P[i][j]-1, P, writer, path); displayPath(P[i][j]-1, j, P, writer, path); } } java floyd graphfile.txt Exception in thread "main" java.lang.NumberFormatException: For input string: "n" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:662) at java.base/java.lang.Integer.parseInt(Integer.java:778) at floyd.processInput(floyd.java:49) at floyd.main(floyd.java:22)
a5b1868621801d0263d6fc3242fef224
{ "intermediate": 0.3359508514404297, "beginner": 0.469439297914505, "expert": 0.19460979104042053 }
46,447
in javascript how do I use the overpass api to retrieve road data 500 meters around this point ' const firstPoint = L.latLng( firstCityCoords[1], firstCityCoords[0] );'
220a73776e7d3ec082c63074795b73c8
{ "intermediate": 0.8533748388290405, "beginner": 0.10154742747545242, "expert": 0.04507772997021675 }
46,448
can you write app in rust lang that prints current timestamp every second with tray menu
4343593bca968a73150742774a8d11c2
{ "intermediate": 0.6315677762031555, "beginner": 0.16659529507160187, "expert": 0.2018369734287262 }
46,449
import java.io.*; import java.util.Scanner; public class floyd { private static final int INF = (int) 1e9; public static void main(String[] args) { if (args.length != 1) { System.err.println(“Usage: java floyd <input_file_path>”); return; } String filePath = args[0]; try (Scanner scanner = new Scanner(new File(filePath)); PrintWriter writer = new PrintWriter(“output.txt”)) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains(“Problem”)) { processInput(line, scanner, writer); } } } catch (FileNotFoundException e) { System.err.println(“File not found: " + e.getMessage()); } } private static void processInput(String line, Scanner scanner, PrintWriter writer) { String[] lineParts = line.split(”\s+“); int problemNumber = Integer.parseInt(lineParts[0].replaceAll(”[^0-9]“, “”)); int n = -1; for (String part : lineParts) { if (part.matches(”\d+")) { n = Integer.parseInt(part); break; } } if (n == -1) { System.err.println(“Failed to find matrix size ‘n’ in line: " + line); return; } int[][] dist = new int[n][n]; int[][] P = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (scanner.hasNextInt()) { int distance = scanner.nextInt(); dist[i][j] = distance == 0 && i != j ? INF : distance; P[i][j] = j + 1; } } } // Floyd-Warshall for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; P[i][j] = P[i][k]; } } } } // Output results writer.printf(“Problem %d: n = %d\n”, problemNumber, n); writer.println(“Pmatrix:”); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { writer.printf(”%d ", P[i][j]); } writer.println(); } writer.println(); for (int i = 0; i < n; i++) { writer.printf(“V%d-Vj: shortest path and length\n”, i+1); for (int j = 0; j < n; j++) { if (dist[i][j] >= INF) { writer.printf(“V%d to V%d: NO PATH\n”, i+1, j+1); } else { writer.printf("V%d ", i+1); // Start of path printPath(i, j, P, writer); writer.printf(“V%d “, j+1); // End of path writer.printf(”: %d\n”, dist[i][j]); } } } writer.println(); } // Updated to properly reconstruct and print the path private static void printPath(int i, int j, int[][] P, PrintWriter writer) { // If there’s a direct path or no path, do not print intermediates if (P[i][j] == j+1 || P[i][j] == 0) return; int intermediate = P[i][j] - 1; printPath(i, intermediate, P, writer); writer.printf("V%d ", P[i][j]); printPath(intermediate, j, P, writer); } } The program logic should be modified according to the logic of #include <iostream> #include <fstream> #include <vector> #include <sstream> using namespace std; const int INF = 1e9; // Assuming INF represents infinity class floydGraphProcessor { public: void processInput(const string &line, ifstream &infile, ofstream &outfile) { // Extract problem number and matrix size size_t problem_position = line.find("Problem"); if (problem_position == string::npos) { cerr << "Error extracting parameters. \n"; return; } int problemNumber, n; sscanf(line.c_str() + problem_position, "Problem%d", &problemNumber); // Extracting n from the line size_t n_position = line.find("n = "); if (n_position == string::npos) { cerr << "Error: 'n =' not found.\n"; return; } sscanf(line.c_str() + n_position, "n = %d", &n); // Resize output matrix to n x n vector<vector<int>> matrix(n, vector<int>(n)); // Read n x n matrix values for (int i = 0; i < n; i++) { string r; getline(infile, r); istringstream iss(r); for (int j = 0; j < n; j++) { iss >> matrix[i][j]; } } // Output to file outfile << "Problem " << problemNumber << ": n = " << n << endl; vector<vector<int>> dist = matrix; vector<vector<int>> P(n, vector<int>(n, 0)); // Floyd-Warshall algorithm for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (k != i && k != j && (dist[i][j] >= dist[i][k] + dist[k][j])) { dist[i][j] = dist[i][k] + dist[k][j]; P[i][j] = k + 1; } } } } // Output final Pmatrix to file outfile << "Pmatrix:" << endl; printPath(P, n, outfile); outfile << endl; // shortest paths and length to file for (int i = 0; i < n; i++) { outfile << "V" << i + 1 << "-Vj: shortest path and length" << endl; for (int j = 0; j < n; j++) { outfile << "V" << i + 1 << " "; if (i != j) { outfile << "V" << j + 1 << " "; int v = j; while (P[i][v] != 0) { outfile << "V" << P[i][v] << " "; v = P[i][v] - 1; } } outfile << ": " << dist[i][j] << endl; } } } private: void printPath(const vector<vector<int>> &P, int n, ofstream &outfile) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { outfile << P[i][j] << " "; } outfile << endl; } } }; int main(int argc, char *argv[]) { if (argc != 2) { cerr << "Usage: " << argv[0] << " <input_file_path>" << endl; return 1; } ifstream infile(argv[1]); if (!infile.is_open()) { cerr << "Error!. Wrong usage of the file, error opening the file. " << endl; cout << "Correct usage : " << argv[0] << " <input_file_path>" << endl; return 1; } ofstream outfile("output.txt"); if (!outfile.is_open()) { cerr << "Error opening output file." << endl; return 1; } string line; floydGraphProcessor processor; while (getline(infile, line)) { size_t found = line.find("Problem"); if (found != string::npos) { processor.processInput(line, infile, outfile); } } infile.close(); outfile.close(); return 0; } this program
3ce430464e423e7a799b490ed02d1eb7
{ "intermediate": 0.3289848268032074, "beginner": 0.5570781230926514, "expert": 0.11393702030181885 }
46,450
I am retrieving data from the overpass api with this javascript ' const overpassQuery = ` [out:json]; node["cuisine"="coffee_shop"](around:1500,${firstCityCoords[1]},${firstCityCoords[0]}); out; `; fetch('https://overpass-api.de/api/interpreter', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'data=' + encodeURIComponent(overpassQuery) }) .then(response => response.json()) .then(data => { // Process the data returned by the Overpass API console.log(data); }) .catch(error => { console.error('Error fetching data:', error); }); ' how can I add markers to a leaflet.js map using the fetched data
f77c64f8ddf9b4ab8fd37ee4cf3b155a
{ "intermediate": 0.6922705769538879, "beginner": 0.18340887129306793, "expert": 0.12432059645652771 }
46,451
#include <iostream> #include <fstream> #include <vector> #include <sstream> using namespace std; const int INF = 1e9; // Assuming INF represents infinity class floydGraphProcessor { public: void processInput(const string &line, ifstream &infile, ofstream &outfile) { // Extract problem number and matrix size size_t problem_position = line.find("Problem"); if (problem_position == string::npos) { cerr << "Error extracting parameters. \n"; return; } int problemNumber, n; sscanf(line.c_str() + problem_position, "Problem%d", &problemNumber); // Extracting n from the line size_t n_position = line.find("n = "); if (n_position == string::npos) { cerr << "Error: 'n =' not found.\n"; return; } sscanf(line.c_str() + n_position, "n = %d", &n); // Resize output matrix to n x n vector<vector<int>> matrix(n, vector<int>(n)); // Read n x n matrix values for (int i = 0; i < n; i++) { string r; getline(infile, r); istringstream iss(r); for (int j = 0; j < n; j++) { iss >> matrix[i][j]; } } // Output to file outfile << "Problem " << problemNumber << ": n = " << n << endl; vector<vector<int>> dist = matrix; vector<vector<int>> P(n, vector<int>(n, 0)); // Floyd-Warshall algorithm for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (k != i && k != j && (dist[i][j] >= dist[i][k] + dist[k][j])) { dist[i][j] = dist[i][k] + dist[k][j]; P[i][j] = k + 1; } } } } // Output final Pmatrix to file outfile << "Pmatrix:" << endl; printPath(P, n, outfile); outfile << endl; // shortest paths and length to file for (int i = 0; i < n; i++) { outfile << "V" << i + 1 << "-Vj: shortest path and length" << endl; for (int j = 0; j < n; j++) { outfile << "V" << i + 1 << " "; if (i != j) { outfile << "V" << j + 1 << " "; int v = j; while (P[i][v] != 0) { outfile << "V" << P[i][v] << " "; v = P[i][v] - 1; } } outfile << ": " << dist[i][j] << endl; } } } private: void printPath(const vector<vector<int>> &P, int n, ofstream &outfile) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { outfile << P[i][j] << " "; } outfile << endl; } } }; int main(int argc, char *argv[]) { if (argc != 2) { cerr << "Usage: " << argv[0] << " <input_file_path>" << endl; return 1; } ifstream infile(argv[1]); if (!infile.is_open()) { cerr << "Error!. Wrong usage of the file, error opening the file. " << endl; cout << "Correct usage : " << argv[0] << " <input_file_path>" << endl; return 1; } ofstream outfile("output.txt"); if (!outfile.is_open()) { cerr << "Error opening output file." << endl; return 1; } string line; floydGraphProcessor processor; while (getline(infile, line)) { size_t found = line.find("Problem"); if (found != string::npos) { processor.processInput(line, infile, outfile); } } infile.close(); outfile.close(); return 0; } Modify the program to get the output as Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 0 5 6 0 0 0 3 0 6 3 0 0 3 0 3 0 0 4 0 0 3 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 6 V1 V3: 5 V1 V6 V4: 4 V1 V3 V5: 6 V1 V6: 3 V1 V6 V7: 6 V2-Vj: shortest path and length V2 V1: 6 V2 V2: 0 V2 V5 V3: 6 V2 V4: 4 V2 V5: 5 V2 V4 V6: 5 V2 V7: 3 V3-Vj: shortest path and length V3 V1: 5 V3 V5 V2: 6 V3 V3: 0 V3 V4: 3 V3 V5: 1 V3 V6: 4 V3 V5 V7: 6 V4-Vj: shortest path and length V4 V6 V1: 4 V4 V2: 4 V4 V3: 3 V4 V4: 0 V4 V3 V5: 4 V4 V6: 1 V4 V6 V7: 4 V5-Vj: shortest path and length V5 V3 V1: 6 V5 V2: 5 V5 V3: 1 V5 V3 V4: 4 V5 V5: 0 V5 V3 V6: 5 V5 V7: 5 V6-Vj: shortest path and length V6 V1: 3 V6 V4 V2: 5 V6 V3: 4 V6 V4: 1 V6 V3 V5: 5 V6 V6: 0 V6 V7: 3 V7-Vj: shortest path and length V7 V6 V1: 6 V7 V2: 3 V7 V5 V3: 6 V7 V6 V4: 4 V7 V5: 5 V7 V6: 3 V7 V7: 0 Problem2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 1 V1 V3: 2 V1 V4: 1 V1 V2 V5: 3 V1 V2 V6: 4 V2-Vj: shortest path and length V2 V1: 1 V2 V2: 0 V2 V1 V3: 3 V2 V1 V4: 2 V2 V5: 2 V2 V6: 3 V3-Vj: shortest path and length V3 V1: 2 V3 V1 V2: 3 V3 V3: 0 V3 V1 V4: 3 V3 V5: 3 V3 V1 V2 V6: 6 V4-Vj: shortest path and length V4 V1: 1 V4 V1 V2: 2 V4 V1 V3: 3 V4 V4: 0 V4 V5: 3 V4 V1 V2 V6: 5 V5-Vj: shortest path and length V5 V2 V1: 3 V5 V2: 2 V5 V3: 3 V5 V4: 3 V5 V5: 0 V5 V2 V6: 5 V6-Vj: shortest path and length V6 V2 V1: 4 V6 V2: 3 V6 V2 V1 V3: 6 V6 V2 V1 V4: 5 V6 V2 V5: 5 V6 V6: 0
9bbe8b924ef6777707afd72490ad8fe6
{ "intermediate": 0.35287392139434814, "beginner": 0.2890014946460724, "expert": 0.35812461376190186 }
46,452
#include <iostream> #include <fstream> #include <vector> #include <sstream> using namespace std; const int INF = 1e9; // Assuming INF represents infinity class floydGraphProcessor { public: void processInput(const string &line, ifstream &infile, ofstream &outfile) { // Extract problem number and matrix size size_t problem_position = line.find("Problem"); if (problem_position == string::npos) { cerr << "Error extracting parameters. \n"; return; } int problemNumber, n; sscanf(line.c_str() + problem_position, "Problem%d", &problemNumber); // Extracting n from the line size_t n_position = line.find("n = "); if (n_position == string::npos) { cerr << "Error: 'n =' not found.\n"; return; } sscanf(line.c_str() + n_position, "n = %d", &n); // Resize output matrix to n x n vector<vector<int>> matrix(n, vector<int>(n)); // Read n x n matrix values for (int i = 0; i < n; i++) { string r; getline(infile, r); istringstream iss(r); for (int j = 0; j < n; j++) { iss >> matrix[i][j]; } } // Output to file outfile << "Problem " << problemNumber << ": n = " << n << endl; vector<vector<int>> dist = matrix; vector<vector<int>> P(n, vector<int>(n, 0)); // Floyd-Warshall algorithm for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (k != i && k != j && (dist[i][j] >= dist[i][k] + dist[k][j])) { dist[i][j] = dist[i][k] + dist[k][j]; P[i][j] = k + 1; } } } } // Output final Pmatrix to file outfile << "Pmatrix:" << endl; printPath(P, n, outfile); outfile << endl; // shortest paths and length to file for (int i = 0; i < n; i++) { outfile << "V" << i + 1 << "-Vj: shortest path and length" << endl; for (int j = 0; j < n; j++) { outfile << "V" << i + 1 << " "; if (i != j) { outfile << "V" << j + 1 << " "; int v = j; while (P[i][v] != 0) { outfile << "V" << P[i][v] << " "; v = P[i][v] - 1; } } outfile << ": " << dist[i][j] << endl; } } } private: void printPath(const vector<vector<int>> &P, int n, ofstream &outfile) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { outfile << P[i][j] << " "; } outfile << endl; } } }; int main(int argc, char *argv[]) { if (argc != 2) { cerr << "Usage: " << argv[0] << " <input_file_path>" << endl; return 1; } ifstream infile(argv[1]); if (!infile.is_open()) { cerr << "Error!. Wrong usage of the file, error opening the file. " << endl; cout << "Correct usage : " << argv[0] << " <input_file_path>" << endl; return 1; } ofstream outfile("output.txt"); if (!outfile.is_open()) { cerr << "Error opening output file." << endl; return 1; } string line; floydGraphProcessor processor; while (getline(infile, line)) { size_t found = line.find("Problem"); if (found != string::npos) { processor.processInput(line, infile, outfile); } } infile.close(); outfile.close(); return 0; } The program is giving output as Problem 1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 4 5 6 0 0 0 3 0 6 3 0 0 3 0 4 0 0 4 4 0 4 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 : 0 V1 V2 : 6 V1 V3 : 5 V1 V4 V6 : 4 V1 V5 V3 : 6 V1 V6 : 3 V1 V7 V6 : 6 V2-Vj: shortest path and length V2 V1 : 6 V2 : 0 V2 V3 V5 : 6 V2 V4 : 4 V2 V5 : 5 V2 V6 V4 : 5 V2 V7 : 3 V3-Vj: shortest path and length V3 V1 : 5 V3 V2 V5 : 6 V3 : 0 V3 V4 : 3 V3 V5 : 1 V3 V6 V4 : 4 V3 V7 V5 : 6 V4-Vj: shortest path and length V4 V1 V6 : 4 V4 V2 : 4 V4 V3 : 3 V4 : 0 V4 V5 V3 : 4 V4 V6 : 1 V4 V7 V6 : 4 V5-Vj: shortest path and length V5 V1 V3 : 6 V5 V2 : 5 V5 V3 : 1 V5 V4 V3 : 4 V5 : 0 V5 V6 V4 V3 : 5 V5 V7 : 5 V6-Vj: shortest path and length V6 V1 : 3 V6 V2 V4 : 5 V6 V3 V4 : 4 V6 V4 : 1 V6 V5 V4 : 5 V6 : 0 V6 V7 : 3 V7-Vj: shortest path and length V7 V1 V6 : 6 V7 V2 : 3 V7 V3 V5 : 6 V7 V4 V6 : 4 V7 V5 : 5 V7 V6 : 3 V7 : 0 Problem 2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 : 0 V1 V2 : 1 V1 V3 : 2 V1 V4 : 1 V1 V5 V2 : 3 V1 V6 V2 : 4 V2-Vj: shortest path and length V2 V1 : 1 V2 : 0 V2 V3 V1 : 3 V2 V4 V1 : 2 V2 V5 : 2 V2 V6 : 3 V3-Vj: shortest path and length V3 V1 : 2 V3 V2 V1 : 3 V3 : 0 V3 V4 V1 : 3 V3 V5 : 3 V3 V6 V2 V1 : 6 V4-Vj: shortest path and length V4 V1 : 1 V4 V2 V1 : 2 V4 V3 V1 : 3 V4 : 0 V4 V5 : 3 V4 V6 V2 V1 : 5 V5-Vj: shortest path and length V5 V1 V2 : 3 V5 V2 : 2 V5 V3 : 3 V5 V4 : 3 V5 : 0 V5 V6 V2 : 5 V6-Vj: shortest path and length V6 V1 V2 : 4 V6 V2 : 3 V6 V3 V2 : 6 V6 V4 V2 : 5 V6 V5 V2 : 5 V6 : 0 The output should be like Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 0 5 6 0 0 0 3 0 6 3 0 0 3 0 3 0 0 4 0 0 3 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 6 V1 V3: 5 V1 V6 V4: 4 V1 V3 V5: 6 V1 V6: 3 V1 V6 V7: 6 V2-Vj: shortest path and length V2 V1: 6 V2 V2: 0 V2 V5 V3: 6 V2 V4: 4 V2 V5: 5 V2 V4 V6: 5 V2 V7: 3 V3-Vj: shortest path and length V3 V1: 5 V3 V5 V2: 6 V3 V3: 0 V3 V4: 3 V3 V5: 1 V3 V6: 4 V3 V5 V7: 6 V4-Vj: shortest path and length V4 V6 V1: 4 V4 V2: 4 V4 V3: 3 V4 V4: 0 V4 V3 V5: 4 V4 V6: 1 V4 V6 V7: 4 V5-Vj: shortest path and length V5 V3 V1: 6 V5 V2: 5 V5 V3: 1 V5 V3 V4: 4 V5 V5: 0 V5 V3 V6: 5 V5 V7: 5 V6-Vj: shortest path and length V6 V1: 3 V6 V4 V2: 5 V6 V3: 4 V6 V4: 1 V6 V3 V5: 5 V6 V6: 0 V6 V7: 3 V7-Vj: shortest path and length V7 V6 V1: 6 V7 V2: 3 V7 V5 V3: 6 V7 V6 V4: 4 V7 V5: 5 V7 V6: 3 V7 V7: 0 Problem2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 1 V1 V3: 2 V1 V4: 1 V1 V2 V5: 3 V1 V2 V6: 4 V2-Vj: shortest path and length V2 V1: 1 V2 V2: 0 V2 V1 V3: 3 V2 V1 V4: 2 V2 V5: 2 V2 V6: 3 V3-Vj: shortest path and length V3 V1: 2 V3 V1 V2: 3 V3 V3: 0 V3 V1 V4: 3 V3 V5: 3 V3 V1 V2 V6: 6 V4-Vj: shortest path and length V4 V1: 1 V4 V1 V2: 2 V4 V1 V3: 3 V4 V4: 0 V4 V5: 3 V4 V1 V2 V6: 5 V5-Vj: shortest path and length V5 V2 V1: 3 V5 V2: 2 V5 V3: 3 V5 V4: 3 V5 V5: 0 V5 V2 V6: 5 V6-Vj: shortest path and length V6 V2 V1: 4 V6 V2: 3 V6 V2 V1 V3: 6 V6 V2 V1 V4: 5 V6 V2 V5: 5 V6 V6: 0
8568d721de47ba1e01213af1156b0538
{ "intermediate": 0.35287392139434814, "beginner": 0.2890014946460724, "expert": 0.35812461376190186 }
46,453
Finish the Savings class that inherits the class Account and supports display(), deposit(), and withdraw() functions. The Savings class should have an extra data member interestRate to track how much interest is generated (which we will calculate each time we make a deposit). Add an interestRate data member that can store a decimal value (e.g. 0.05 means 5% interest) Complete the constructor to take in an additional argument which is the interest rate and then calls the base class constructor and initializes the interest rate member. Write display() to provide the same display results of the base Account class, BUT also show the interest rate as the last entry. We provide a cout statement in the comments that you can use to meet our format. deposit() should first add interest and then add the value entered by the user to the balance. Each time we deposit, compute interest based on the current balance (BEFORE making the deposit) and using the interest rate data member. Add that value to the balance in addition to the deposit amount. For example, if the current balance is 1000, an interest rate of 5% is used, and a deposit of 200 is made, then the updated balance is the old balance, 1000, plus the interest (1000*0.05), 50, and the deposit amount, 200 for a total of 1250. withdraw() should behave the same as the Account implementation of withdraw(). class Account { private: string customer_name; int accountNumber; string accountType; protected: double balance; void displayAccountDetails() { cout<<"AccountType : "<< accountType << endl; cout<<"Customer Name : "<< customer_name << endl; cout<<"Account Num : "<< accountNumber << endl; cout<<"Balance : "<< setprecision(2) << fixed << balance << endl; } public: Account(string name, int accnum, string acctype){ customer_name = name; accountNumber = accnum; balance = 0; accountType = acctype; } string getName(){ return customer_name; } int getAccountNum(){ return accountNumber; } double getBalance(){ return balance; } void setName(string name){ customer_name = name; } void setAccountNum(int num){ accountNumber = num; } /* DO NOT ALTER */ virtual void deposit() { double deposit_amount; cout<<" Enter amount to Deposit : "; cin>> deposit_amount; cout << endl; balance = balance + deposit_amount; } /* DO NOT ALTER */ virtual void withdraw() { float withdraw_amount; cout << "Enter amount to be withdraw :"; cin >> withdraw_amount; if(balance >= withdraw_amount) { balance=balance-withdraw_amount; } else { cout<< endl << " Insufficient Balance" << endl; } } // Display specific account info virtual void display() = 0; }; // Complete - Understand this implementation of a derived class class Checking : public Account { private: string linkedDebitCardNum; public: Checking(string name, int accnum, string linkedCardnum) : Account(name, accnum, "Checking") { linkedDebitCardNum = linkedCardnum; } /* DO NOT ALTER */ void display() { displayAccountDetails(); cout<<"Linked Card Num : "<< linkedDebitCardNum <<endl; } }; class Savings : public Account{ private: public: // Complete the constructor and link it with the constructor of Base class Savings(string name, int accnum, double intRate) { } // Your code for Option 1 : Deposit // Everytime you make a deposit you also earn additional // interestRate * initialBalance (i.e. initialBalance is balance // before the deposit) void deposit() { //write code below this line - think about how to use // the deposit() function defined in Account to do the majority of // the deposit work and, here, just handle the interest } // Option 2: Do you need to provide new/updated code for Withdrawal? // Your code for Option 3 : Display which should include the normal // account info but also the interest rate after that info. // Use the following line in an appropriate place. // cout<<"Interest Rate : "<< setprecision(2) << fixed << interestRate << endl; void display() { // write code below this line } };
33117ae33df4d72151972d2490484268
{ "intermediate": 0.36394789814949036, "beginner": 0.470226526260376, "expert": 0.16582559049129486 }
46,454
I am retrieving data from the overpass api with this javascript ’ const overpassQuery = <br/> [out:json];<br/> node["cuisine"="coffee_shop"](around:1500,${firstCityCoords[1]},${firstCityCoords[0]});<br/> out;<br/>; fetch(‘https://overpass-api.de/api/interpreter’, { method: ‘POST’, headers: { ‘Content-Type’: ‘application/x-www-form-urlencoded’ }, body: ‘data=’ + encodeURIComponent(overpassQuery) }) .then(response => response.json()) .then(data => { // Process the data returned by the Overpass API console.log(data); }) .catch(error => { console.error(‘Error fetching data:’, error); });' can you change this to fetch road data instead of coffee shops
556c0712e0eb298d65bc176e5811f8e4
{ "intermediate": 0.771324634552002, "beginner": 0.13235315680503845, "expert": 0.09632217139005661 }
46,455
<html> <head> <title>Clickable Link Text Field</title> </head> <body> <label for="notes">Enter your notes:</label><br> <textarea id="notes" name="notes" rows="4" cols="50" placeholder="Type your notes here..."></textarea><br><br> <button id="btn" onclick="makeLink()">Make Link</button><br><br> <div id="display"></div> <script> function makeLink() { var note = document.getElementById('notes').value; var display = document.getElementById('display'); if (note.includes('http')) { display.innerHTML = '<a href="' + note + '" target="_blank">' + note + '</a>'; } else { display.innerHTML = note; } } </script> </body> </html> i want to make it so that if i put a text in there that contains link, it's clickable and bocme a hyperlink after i press the button
1342e5d6a7d8a0286df26b750fdfcf6f
{ "intermediate": 0.4263666868209839, "beginner": 0.2904961407184601, "expert": 0.28313717246055603 }
46,456
<html> <head> <title>Clickable Link Text Field</title> </head> <body> <label for="notes">Enter your notes:</label><br> <textarea id="notes" name="notes" rows="4" cols="50" placeholder="Type your notes here..."></textarea><br><br> <button id="btn" onclick="makeLink()">Make Link</button><br><br> <div id="display"></div> <script> function makeLink() { var note = document.getElementById('notes').value; var display = document.getElementById('display'); var urlRegex = /(https?://[^\s]+)/g; if (urlRegex.test(note)) { // Test if note is a valid URL // Wrap detected URL(s) with <a> tag var linkedText = note.replace(urlRegex, function(url) { return '<a href="' + url + '" target="_blank">' + url + '</a>'; }); display.innerHTML = linkedText; } else { display.innerText = note; } } </script> </body> </html> when i click the button with link text, nothing happens
5b1d2ba52cb846544be74ed17573be52
{ "intermediate": 0.37714484333992004, "beginner": 0.38726574182510376, "expert": 0.23558945953845978 }
46,457
make a html with text area that when i put text in there containing links, it'll parse each line into links in a field below it
70e11374d39d87db14806ba098131407
{ "intermediate": 0.5298832654953003, "beginner": 0.12999595701694489, "expert": 0.340120792388916 }
46,458
Help me make a minecraft plugin for 1.8.8
538ac40fad05a7b2ac97ea24dea15f5a
{ "intermediate": 0.3685685098171234, "beginner": 0.28096604347229004, "expert": 0.35046547651290894 }
46,459
make a html with a field that when i enter text that has links to it it parses each line and make it href to the html so it's clickable
c4e9ab02c0babee4e3b08b144899a856
{ "intermediate": 0.445202112197876, "beginner": 0.12079858779907227, "expert": 0.43399932980537415 }
46,460
put text and a href in htm be on each line
808d55a7a8517c546b75e842fd267a1d
{ "intermediate": 0.3794429898262024, "beginner": 0.2573878765106201, "expert": 0.3631691634654999 }
46,461
Event::Keyboard(KeyboardEvent::Key(key)) => { if key.key() == Key::Fn as u32 { let new_layer = match key.key_state() { KeyState::Pressed => 1, KeyState::Released => 0 }; if active_layer != new_layer { active_layer = new_layer; needs_complete_redraw = true; } } } how do i make the fn key toggle instead on having to hold it?
890de058c65fcd5d036e728e38dddb84
{ "intermediate": 0.4371558725833893, "beginner": 0.3982928991317749, "expert": 0.16455118358135223 }
46,462
use std::{ fs::{File, OpenOptions}, os::{ fd::{AsRawFd, AsFd}, unix::{io::OwnedFd, fs::OpenOptionsExt} }, path::Path, collections::HashMap, cmp::min, panic::{self, AssertUnwindSafe} }; use cairo::{ImageSurface, Format, Context, Surface, Rectangle, Antialias}; use rsvg::{Loader, CairoRenderer, SvgHandle}; use drm::control::ClipRect; use anyhow::Result; use input::{ Libinput, LibinputInterface, Device as InputDevice, event::{ Event, device::DeviceEvent, EventTrait, touch::{TouchEvent, TouchEventPosition, TouchEventSlot}, keyboard::{KeyboardEvent, KeyboardEventTrait, KeyState} } }; use libc::{O_ACCMODE, O_RDONLY, O_RDWR, O_WRONLY, c_char}; use input_linux::{uinput::UInputHandle, EventKind, Key, SynchronizeKind}; use input_linux_sys::{uinput_setup, input_id, timeval, input_event}; use nix::{ sys::{ signal::{Signal, SigSet}, epoll::{Epoll, EpollCreateFlags, EpollEvent, EpollFlags} }, errno::Errno }; use privdrop::PrivDrop; mod backlight; mod display; mod pixel_shift; mod fonts; mod config; use backlight::BacklightManager; use display::DrmBackend; use pixel_shift::{PixelShiftManager, PIXEL_SHIFT_WIDTH_PX}; use config::{ButtonConfig, Config}; use crate::config::ConfigManager; const DFR_WIDTH: i32 = 2008; const DFR_HEIGHT: i32 = 60; const DFR_STRIDE: i32 = 64; const BUTTON_SPACING_PX: i32 = 16; const BUTTON_COLOR_INACTIVE: f64 = 0.200; const BUTTON_COLOR_ACTIVE: f64 = 0.400; const ICON_SIZE: i32 = 48; const TIMEOUT_MS: i32 = 10 * 1000; enum ButtonImage { Text(String), Svg(SvgHandle), Bitmap(ImageSurface) } struct Button { image: ButtonImage, changed: bool, active: bool, action: Key } fn try_load_svg(path: &str) -> Result<ButtonImage> { let handle = Loader::new().read_path(format!("/etc/tiny-dfr/{}.svg", path)).or_else(|_| { Loader::new().read_path(format!("/usr/share/tiny-dfr/{}.svg", path)) })?; Ok(ButtonImage::Svg(handle)) } fn try_load_png(path: &str) -> Result<ButtonImage> { let mut file = File::open(format!("/etc/tiny-dfr/{}.png", path)).or_else(|_| { File::open(format!("/usr/share/tiny-dfr/{}.png", path)) })?; let surf = ImageSurface::create_from_png(&mut file)?; if surf.height() == ICON_SIZE && surf.width() == ICON_SIZE { return Ok(ButtonImage::Bitmap(surf)); } let resized = ImageSurface::create(Format::ARgb32, ICON_SIZE, ICON_SIZE).unwrap(); let c = Context::new(&resized).unwrap(); c.scale(ICON_SIZE as f64 / surf.width() as f64, ICON_SIZE as f64 / surf.height() as f64); c.set_source_surface(surf, 0.0, 0.0).unwrap(); c.set_antialias(Antialias::Best); c.paint().unwrap(); return Ok(ButtonImage::Bitmap(resized)); } impl Button { fn with_config(cfg: ButtonConfig) -> Button { if let Some(text) = cfg.text { Button::new_text(text, cfg.action) } else if let Some(icon) = cfg.icon { Button::new_icon(&icon, cfg.action) } else { panic!("Invalid config, a button must have either Text or Icon") } } fn new_text(text: String, action: Key) -> Button { Button { action, active: false, changed: false, image: ButtonImage::Text(text) } } fn new_icon(path: &str, action: Key) -> Button { let image = try_load_svg(path).or_else(|_| try_load_png(path)).unwrap(); Button { action, image, active: false, changed: false, } } fn render(&self, c: &Context, button_left_edge: f64, button_width: u64, y_shift: f64) { match &self.image { ButtonImage::Text(text) => { let extents = c.text_extents(text).unwrap(); c.move_to( button_left_edge + (button_width as f64 / 2.0 - extents.width() / 2.0).round(), y_shift + (DFR_HEIGHT as f64 / 2.0 + extents.height() / 2.0).round() ); c.show_text(text).unwrap(); }, ButtonImage::Svg(svg) => { let renderer = CairoRenderer::new(&svg); let x = button_left_edge + (button_width as f64 / 2.0 - (ICON_SIZE / 2) as f64).round(); let y = y_shift + ((DFR_HEIGHT as f64 - ICON_SIZE as f64) / 2.0).round(); renderer.render_document(c, &Rectangle::new(x, y, ICON_SIZE as f64, ICON_SIZE as f64) ).unwrap(); } ButtonImage::Bitmap(surf) => { let x = button_left_edge + (button_width as f64 / 2.0 - (ICON_SIZE / 2) as f64).round(); let y = y_shift + ((DFR_HEIGHT as f64 - ICON_SIZE as f64) / 2.0).round(); c.set_source_surface(surf, x, y).unwrap(); c.rectangle(x, y, ICON_SIZE as f64, ICON_SIZE as f64); c.fill().unwrap(); } } } fn set_active<F>(&mut self, uinput: &mut UInputHandle<F>, active: bool) where F: AsRawFd { if self.active != active { self.active = active; self.changed = true; toggle_key(uinput, self.action, active as i32); } } } #[derive(Default)] pub struct FunctionLayer { buttons: Vec<Button> } impl FunctionLayer { fn with_config(cfg: Vec<ButtonConfig>) -> FunctionLayer { if cfg.is_empty() { panic!("Invalid configuration, layer has 0 buttons"); } FunctionLayer { buttons: cfg.into_iter().map(Button::with_config).collect() } } fn draw(&mut self, config: &Config, surface: &Surface, pixel_shift: (f64, f64), complete_redraw: bool) -> Vec<ClipRect> { let c = Context::new(&surface).unwrap(); let mut modified_regions = if complete_redraw { vec![ClipRect::new(0, 0, DFR_HEIGHT as u16, DFR_WIDTH as u16)] } else { Vec::new() }; c.translate(DFR_HEIGHT as f64, 0.0); c.rotate((90.0f64).to_radians()); let pixel_shift_width = if config.enable_pixel_shift { PIXEL_SHIFT_WIDTH_PX } else { 0 }; let button_width = ((DFR_WIDTH - pixel_shift_width as i32) - (BUTTON_SPACING_PX * (self.buttons.len() - 1) as i32)) as f64 / self.buttons.len() as f64; let radius = 8.0f64; let bot = (DFR_HEIGHT as f64) * 0.15; let top = (DFR_HEIGHT as f64) * 0.85; let (pixel_shift_x, pixel_shift_y) = pixel_shift; if complete_redraw { c.set_source_rgb(0.0, 0.0, 0.0); c.paint().unwrap(); } c.set_font_face(&config.font_face); c.set_font_size(32.0); for (i, button) in self.buttons.iter_mut().enumerate() { if !button.changed && !complete_redraw { continue; }; let left_edge = (i as f64 * (button_width + BUTTON_SPACING_PX as f64)).floor() + pixel_shift_x + (pixel_shift_width / 2) as f64; let color = if button.active { BUTTON_COLOR_ACTIVE } else if config.show_button_outlines { BUTTON_COLOR_INACTIVE } else { 0.0 }; if !complete_redraw { c.set_source_rgb(0.0, 0.0, 0.0); c.rectangle(left_edge, bot - radius, button_width, top - bot + radius * 2.0); c.fill().unwrap(); } c.set_source_rgb(color, color, color); // draw box with rounded corners c.new_sub_path(); let left = left_edge + radius; let right = (left_edge + button_width.ceil()) - radius; c.arc( right, bot, radius, (-90.0f64).to_radians(), (0.0f64).to_radians(), ); c.arc( right, top, radius, (0.0f64).to_radians(), (90.0f64).to_radians(), ); c.arc( left, top, radius, (90.0f64).to_radians(), (180.0f64).to_radians(), ); c.arc( left, bot, radius, (180.0f64).to_radians(), (270.0f64).to_radians(), ); c.close_path(); c.fill().unwrap(); c.set_source_rgb(1.0, 1.0, 1.0); button.render(&c, left_edge, button_width.ceil() as u64, pixel_shift_y); button.changed = false; if !complete_redraw { modified_regions.push(ClipRect::new( DFR_HEIGHT as u16 - top as u16 - radius as u16, left_edge as u16, DFR_HEIGHT as u16 - bot as u16 + radius as u16, left_edge as u16 + button_width as u16 )); } } modified_regions } } struct Interface; impl LibinputInterface for Interface { fn open_restricted(&mut self, path: &Path, flags: i32) -> Result<OwnedFd, i32> { let mode = flags & O_ACCMODE; OpenOptions::new() .custom_flags(flags) .read(mode == O_RDONLY || mode == O_RDWR) .write(mode == O_WRONLY || mode == O_RDWR) .open(path) .map(|file| file.into()) .map_err(|err| err.raw_os_error().unwrap()) } fn close_restricted(&mut self, fd: OwnedFd) { _ = File::from(fd); } } fn button_hit(num: u32, idx: u32, x: f64, y: f64) -> bool { let button_width = (DFR_WIDTH - (BUTTON_SPACING_PX * (num - 1) as i32)) as f64 / num as f64; let left_edge = idx as f64 * (button_width + BUTTON_SPACING_PX as f64); if x < left_edge || x > (left_edge + button_width) { return false } y > 0.1 * DFR_HEIGHT as f64 && y < 0.9 * DFR_HEIGHT as f64 } fn emit<F>(uinput: &mut UInputHandle<F>, ty: EventKind, code: u16, value: i32) where F: AsRawFd { uinput.write(&[input_event { value: value, type_: ty as u16, code: code, time: timeval { tv_sec: 0, tv_usec: 0 } }]).unwrap(); } fn toggle_key<F>(uinput: &mut UInputHandle<F>, code: Key, value: i32) where F: AsRawFd { emit(uinput, EventKind::Key, code as u16, value); emit(uinput, EventKind::Synchronize, SynchronizeKind::Report as u16, 0); } fn main() { let mut drm = DrmBackend::open_card().unwrap(); let _ = panic::catch_unwind(AssertUnwindSafe(|| { real_main(&mut drm) })); let crash_bitmap = include_bytes!("crash_bitmap.raw"); let mut map = drm.map().unwrap(); let data = map.as_mut(); let mut wptr = 0; for byte in crash_bitmap { for i in 0..8 { let bit = ((byte >> i) & 0x1) == 0; let color = if bit { 0xFF } else { 0x0 }; data[wptr] = color; data[wptr + 1] = color; data[wptr + 2] = color; data[wptr + 3] = color; wptr += 4; } } drop(map); drm.dirty(&[ClipRect::new(0, 0, DFR_HEIGHT as u16, DFR_WIDTH as u16)]).unwrap(); let mut sigset = SigSet::empty(); sigset.add(Signal::SIGTERM); sigset.wait().unwrap(); } fn real_main(drm: &mut DrmBackend) { let mut uinput = UInputHandle::new(OpenOptions::new().write(true).open("/dev/uinput").unwrap()); let mut backlight = BacklightManager::new(); let mut cfg_mgr = ConfigManager::new(); let (mut cfg, mut layers) = cfg_mgr.load_config(); let mut pixel_shift = PixelShiftManager::new(); // drop privileges to input and video group let groups = ["input", "video"]; PrivDrop::default() .user("nobody") .group_list(&groups) .apply() .unwrap_or_else(|e| { panic!("Failed to drop privileges: {}", e) }); let mut surface = ImageSurface::create(Format::ARgb32, DFR_STRIDE, DFR_WIDTH).unwrap(); let mut active_layer = 0; let mut needs_complete_redraw = true; let mut input_tb = Libinput::new_with_udev(Interface); let mut input_main = Libinput::new_with_udev(Interface); input_tb.udev_assign_seat("seat-touchbar").unwrap(); input_main.udev_assign_seat("seat0").unwrap(); let epoll = Epoll::new(EpollCreateFlags::empty()).unwrap(); epoll.add(input_main.as_fd(), EpollEvent::new(EpollFlags::EPOLLIN, 0)).unwrap(); epoll.add(input_tb.as_fd(), EpollEvent::new(EpollFlags::EPOLLIN, 1)).unwrap(); epoll.add(cfg_mgr.fd(), EpollEvent::new(EpollFlags::EPOLLIN, 2)).unwrap(); uinput.set_evbit(EventKind::Key).unwrap(); for layer in &layers { for button in &layer.buttons { uinput.set_keybit(button.action).unwrap(); } } let mut dev_name_c = [0 as c_char; 80]; let dev_name = "Dynamic Function Row Virtual Input Device".as_bytes(); for i in 0..dev_name.len() { dev_name_c[i] = dev_name[i] as c_char; } uinput.dev_setup(&uinput_setup { id: input_id { bustype: 0x19, vendor: 0x1209, product: 0x316E, version: 1 }, ff_effects_max: 0, name: dev_name_c }).unwrap(); uinput.dev_create().unwrap(); let mut digitizer: Option<InputDevice> = None; let mut touches = HashMap::new(); loop { if cfg_mgr.update_config(&mut cfg, &mut layers) { active_layer = 0; needs_complete_redraw = true; } let mut next_timeout_ms = TIMEOUT_MS; if cfg.enable_pixel_shift { let (pixel_shift_needs_redraw, pixel_shift_next_timeout_ms) = pixel_shift.update(); if pixel_shift_needs_redraw { needs_complete_redraw = true; } next_timeout_ms = min(next_timeout_ms, pixel_shift_next_timeout_ms); } if needs_complete_redraw || layers[active_layer].buttons.iter().any(|b| b.changed) { let shift = if cfg.enable_pixel_shift { pixel_shift.get() } else { (0.0, 0.0) }; let clips = layers[active_layer].draw(&cfg, &surface, shift, needs_complete_redraw); let data = surface.data().unwrap(); drm.map().unwrap().as_mut()[..data.len()].copy_from_slice(&data); drm.dirty(&clips).unwrap(); needs_complete_redraw = false; } match epoll.wait(&mut [EpollEvent::new(EpollFlags::EPOLLIN, 0)], next_timeout_ms as isize) { Err(Errno::EINTR) | Ok(_) => { 0 }, e => e.unwrap(), }; input_tb.dispatch().unwrap(); input_main.dispatch().unwrap(); for event in &mut input_tb.clone().chain(input_main.clone()) { backlight.process_event(&event); match event { Event::Device(DeviceEvent::Added(evt)) => { let dev = evt.device(); if dev.name().contains(" Touch Bar") { digitizer = Some(dev); } }, match event { Event::Keyboard(KeyboardEvent::Key(key)) => { if key.key() == Key::Fn as u32 { fn_key_pressed = !fn_key_pressed; let new_layer = if fn_key_pressed { 1 } else { 0 }; if active_layer != new_layer { active_layer = new_layer; needs_complete_redraw = true; } } } Event::Touch(te) => { if Some(te.device()) != digitizer || backlight.current_bl() == 0 { continue } match te { TouchEvent::Down(dn) => { let x = dn.x_transformed(DFR_WIDTH as u32); let y = dn.y_transformed(DFR_HEIGHT as u32); let btn = (x / (DFR_WIDTH as f64 / layers[active_layer].buttons.len() as f64)) as u32; if button_hit(layers[active_layer].buttons.len() as u32, btn, x, y) { touches.insert(dn.seat_slot(), (active_layer, btn)); layers[active_layer].buttons[btn as usize].set_active(&mut uinput, true); } }, TouchEvent::Motion(mtn) => { if !touches.contains_key(&mtn.seat_slot()) { continue; } let x = mtn.x_transformed(DFR_WIDTH as u32); let y = mtn.y_transformed(DFR_HEIGHT as u32); let (layer, btn) = *touches.get(&mtn.seat_slot()).unwrap(); let hit = button_hit(layers[layer].buttons.len() as u32, btn, x, y); layers[layer].buttons[btn as usize].set_active(&mut uinput, hit); }, TouchEvent::Up(up) => { if !touches.contains_key(&up.seat_slot()) { continue; } let (layer, btn) = *touches.get(&up.seat_slot()).unwrap(); layers[layer].buttons[btn as usize].set_active(&mut uinput, false); } _ => {} } }, _ => {} } } backlight.update_backlight(&cfg); } } how do I make the fn key toggle instead of having to hold it?
4877b9d1cd8676a5b20e3aa3e6973c71
{ "intermediate": 0.40775012969970703, "beginner": 0.35860419273376465, "expert": 0.23364566266536713 }
46,463
#include <iostream> #include <fstream> #include <vector> #include <sstream> using namespace std; const int INF = 1e9; // Assuming INF represents infinity class floydGraphProcessor { public: void processInput(const string &line, ifstream &infile, ofstream &outfile) { // Extract problem number and matrix size size_t problem_position = line.find("Problem"); if (problem_position == string::npos) { cerr << "Error extracting parameters. \n"; return; } int problemNumber, n; sscanf(line.c_str() + problem_position, "Problem%d", &problemNumber); // Extracting n from the line size_t n_position = line.find("n = "); if (n_position == string::npos) { cerr << "Error: 'n =' not found.\n"; return; } sscanf(line.c_str() + n_position, "n = %d", &n); // Resize output matrix to n x n vector<vector<int>> matrix(n, vector<int>(n)); // Read n x n matrix values for (int i = 0; i < n; i++) { string r; getline(infile, r); istringstream iss(r); for (int j = 0; j < n; j++) { iss >> matrix[i][j]; } } // Output to file outfile << "Problem " << problemNumber << ": n = " << n << endl; vector<vector<int>> dist = matrix; vector<vector<int>> P(n, vector<int>(n, 0)); // Floyd-Warshall algorithm for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (k != i && k != j && (dist[i][j] >= dist[i][k] + dist[k][j])) { dist[i][j] = dist[i][k] + dist[k][j]; P[i][j] = k + 1; } } } } // Output final Pmatrix to file outfile << "Pmatrix:" << endl; printPath(P, n, outfile); outfile << endl; // shortest paths and length to file for (int i = 0; i < n; i++) { outfile << "V" << i + 1 << "-Vj: shortest path and length" << endl; for (int j = 0; j < n; j++) { outfile << "V" << i + 1 << " "; if (i != j) { outfile << "V" << j + 1 << " "; int v = j; while (P[i][v] != 0) { outfile << "V" << P[i][v] << " "; v = P[i][v] - 1; } } outfile << ": " << dist[i][j] << endl; } } } private: void printPath(const vector<vector<int>> &P, int n, ofstream &outfile) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { outfile << P[i][j] << " "; } outfile << endl; } } }; int main(int argc, char *argv[]) { if (argc != 2) { cerr << "Usage: " << argv[0] << " <input_file_path>" << endl; return 1; } ifstream infile(argv[1]); if (!infile.is_open()) { cerr << "Error!. Wrong usage of the file, error opening the file. " << endl; cout << "Correct usage : " << argv[0] << " <input_file_path>" << endl; return 1; } ofstream outfile("output.txt"); if (!outfile.is_open()) { cerr << "Error opening output file." << endl; return 1; } string line; floydGraphProcessor processor; while (getline(infile, line)) { size_t found = line.find("Problem"); if (found != string::npos) { processor.processInput(line, infile, outfile); } } infile.close(); outfile.close(); return 0; } The program it giving output as Problem 1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 4 5 6 0 0 0 3 0 6 3 0 0 3 0 4 0 0 4 4 0 4 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 : 0 V1 V2 : 6 V1 V3 : 5 V1 V4 V6 : 4 V1 V5 V3 : 6 V1 V6 : 3 V1 V7 V6 : 6 V2-Vj: shortest path and length V2 V1 : 6 V2 : 0 V2 V3 V5 : 6 V2 V4 : 4 V2 V5 : 5 V2 V6 V4 : 5 V2 V7 : 3 V3-Vj: shortest path and length V3 V1 : 5 V3 V2 V5 : 6 V3 : 0 V3 V4 : 3 V3 V5 : 1 V3 V6 V4 : 4 V3 V7 V5 : 6 V4-Vj: shortest path and length V4 V1 V6 : 4 V4 V2 : 4 V4 V3 : 3 V4 : 0 V4 V5 V3 : 4 V4 V6 : 1 V4 V7 V6 : 4 V5-Vj: shortest path and length V5 V1 V3 : 6 V5 V2 : 5 V5 V3 : 1 V5 V4 V3 : 4 V5 : 0 V5 V6 V4 V3 : 5 V5 V7 : 5 V6-Vj: shortest path and length V6 V1 : 3 V6 V2 V4 : 5 V6 V3 V4 : 4 V6 V4 : 1 V6 V5 V4 : 5 V6 : 0 V6 V7 : 3 V7-Vj: shortest path and length V7 V1 V6 : 6 V7 V2 : 3 V7 V3 V5 : 6 V7 V4 V6 : 4 V7 V5 : 5 V7 V6 : 3 V7 : 0 Problem 2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 : 0 V1 V2 : 1 V1 V3 : 2 V1 V4 : 1 V1 V5 V2 : 3 V1 V6 V2 : 4 V2-Vj: shortest path and length V2 V1 : 1 V2 : 0 V2 V3 V1 : 3 V2 V4 V1 : 2 V2 V5 : 2 V2 V6 : 3 V3-Vj: shortest path and length V3 V1 : 2 V3 V2 V1 : 3 V3 : 0 V3 V4 V1 : 3 V3 V5 : 3 V3 V6 V2 V1 : 6 V4-Vj: shortest path and length V4 V1 : 1 V4 V2 V1 : 2 V4 V3 V1 : 3 V4 : 0 V4 V5 : 3 V4 V6 V2 V1 : 5 V5-Vj: shortest path and length V5 V1 V2 : 3 V5 V2 : 2 V5 V3 : 3 V5 V4 : 3 V5 : 0 V5 V6 V2 : 5 V6-Vj: shortest path and length V6 V1 V2 : 4 V6 V2 : 3 V6 V3 V2 : 6 V6 V4 V2 : 5 V6 V5 V2 : 5 V6 : 0 I want a few changes to be made to the output like when printing shortest from for self it should show as V1 V1: 0 also there should be an empty line between V1-Vj: shortest path and length, V2-Vj: shortest path and length and so on. Do these changes to get the output as specified. Do not make any other changes or modifications to the code
734cde9854342ef72d40d1d3cad803a9
{ "intermediate": 0.35287392139434814, "beginner": 0.2890014946460724, "expert": 0.35812461376190186 }
46,464
what is inheritance and polymrphism in c++, give me a detailed comprehensive guide to understand in
844d698e8474a79c7687d63388f7953b
{ "intermediate": 0.36124706268310547, "beginner": 0.3420349061489105, "expert": 0.2967180013656616 }
46,466
i have crypto data as csv files i have following code to train an lstm model on my data currently model trains to predict "Close" please update the code so model can predict 3 value instead of just "Close" name of the corresponding columns are "Close", High" and "prior" "Close" and "High" are continues values and "prior" is a label value which can be 0 or 1: # %% import numpy as np import pandas as pd from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense from sklearn.preprocessing import MinMaxScaler import os # %% def load_and_process_data(file_path, target_col, scaler, sequence_length): # Load data df = pd.read_csv(file_path) # .drop('Unix', axis=1).drop('Date', axis=1).drop('Symbol', axis=1) start_col = 'y_High_1d' # Replace ‘Start_Column’ with the actual start column’s name end_col = 'y_Priority_5d' # Replace ‘End_Column’ with the actual end column’s name # Find the index of start and end columns start_idx = df.columns.get_loc(start_col) end_idx = df.columns.get_loc(end_col) # Adjusted slicing: Keep only the columns before start and from the end, excluding start and end columns df_modified = pd.concat([df.iloc[:, :start_idx], df.iloc[:, end_idx + 1:]], axis=1) # Assuming you want to use all columns except target_col as features # Adjust this if you have a specific set of columns in mind # X = df_modified.loc[:, df.columns != target_col].values X = df_modified.drop(df.columns[:2], axis=1).values y = df[target_col].values # Normalize features scaler.fit(X) X = scaler.transform(X) # Assuming MinMaxScaler fit on full dataset or similar range # Create sequences X_seq, y_seq = [], [] for i in range(len(X) - sequence_length): X_seq.append(X[i:i+sequence_length]) y_seq.append(y[i+sequence_length]) return np.array(X_seq), np.array(y_seq) # %% scaler = MinMaxScaler(feature_range=(0, 1)) # Normally, you’d fit the scaler on your dataset. You’ll need to adapt this to your scenario. # For demonstration, let’s assume all features are within 0 and 100. # %% def train_model(files, batch_size, epochs): for epoch in range(epochs): for file in files: X, y = load_and_process_data(file_path = file, target_col = 'Close', scaler = scaler, sequence_length = 30) # Adjust ‘features’ accordingly model.train_on_batch(X, y) # %% model = Sequential() model.add(LSTM(50, activation='relu', input_shape=(30, 6427))) model.add(Dense(1)) model.compile(optimizer='adam', loss='mse') # %% csv_folder_path = r"E:\01_calculate_talib\New folder (2)" file_paths = [] # Update this list with actual file paths for csv_file in os.listdir(csv_folder_path): file_path = os.path.join(csv_folder_path, csv_file) file_paths.append(file_path) batch_size = 32 epochs = 10 # Set the number of epochs train_model(file_paths, batch_size, epochs) # %%
7f6a83c8c98cd377639c53fd67c6f55e
{ "intermediate": 0.3662490248680115, "beginner": 0.2628539502620697, "expert": 0.37089699506759644 }
46,467
this is a verilog hdl code, modify the code instead of using a button as a clock, modify it to use an actual clock using 10m50daf484c7g module Removal(button,seg); input wire button; output reg[41:0] seg; reg[4:0] count; initial begin count <= 5'b00000; end always @(posedge button) begin case(count) 5'b00000: seg = 42'b111_1111_111_1111_111_1111_111_1111_111_1111_111_1111; 5'b00001: seg = 42'b111_1111_111_1111_111_1111_111_1111_111_1111_000_1001; 5'b00010: seg = 42'b111_1111_111_1111_111_1111_111_1111_000_1001_000_0110; 5'b00011: seg = 42'b111_1111_111_1111_111_1111_000_1001_000_0110_100_0111; 5'b00100: seg = 42'b111_1111_111_1111_000_1001_000_0110_100_0111_100_0111; 5'b00101: seg = 42'b111_1111_000_1001_000_0110_100_0111_100_0111_100_0000; 5'b00110: seg = 42'b000_1001_000_0110_100_0111_100_0111_100_0000_111_1111; 5'b00111: seg = 42'b000_0110_100_0111_100_0111_100_0000_111_1111_100_0110; 5'b01000: seg = 42'b100_0111_100_0111_100_0000_111_1111_100_0110_000_1100; 5'b01001: seg = 42'b100_0111_100_0000_111_1111_100_0110_000_1100_000_0110; 5'b01010: seg = 42'b100_0000_111_1111_100_0110_000_1100_000_0110_111_1001; 5'b01011: seg = 42'b111_1111_100_0110_000_1100_000_0110_111_1001_100_0000; 5'b01100: seg = 42'b100_0110_000_1100_000_0110_111_1001_100_0000_001_1001; 5'b01101: seg = 42'b000_1100_000_0110_111_1001_100_0000_001_1001_100_0111; 5'b01110: seg = 42'b000_0110_111_1001_100_0000_001_1001_100_0111_011_1111; 5'b01111: seg = 42'b111_1001_100_0000_001_1001_100_0111_011_1111_111_1001; 5'b10000: seg = 42'b100_0000_001_1001_100_0111_011_1111_111_1001_111_1111; 5'b10001: seg = 42'b001_1001_100_0111_011_1111_111_1001_111_1111_111_1111; 5'b10010: seg = 42'b100_0111_011_1111_111_1001_111_1111_111_1111_111_1111; 5'b10011: seg = 42'b011_1111_111_1001_111_1111_111_1111_111_1111_111_1111; 5'b10100: seg = 42'b111_1001_111_1111_111_1111_111_1111_111_1111_111_1111; 5'b10101: seg = 42'b111_1111_111_1111_111_1111_111_1111_111_1111_111_1111; default: seg = 42'b111_1111_111_1111_111_1111_111_1111_111_1111_111_1111; endcase if(count == 5'b10101) begin count <= 5'b00000; end else begin count <= count +1'b1; end end endmodule
6989b0dce7125349f1ae36ecfa78825a
{ "intermediate": 0.3857939541339874, "beginner": 0.3450927734375, "expert": 0.2691131830215454 }
46,469
Create a function named merge that receives two lists as arguments. The function merges the two lists into one sorted list and returns it. For example the following arguments: merge([1, 4, 2], [2, 5, 9]) will return [1, 2, 2, 4, 5, 9] Hints Hint 1 Revealed Append all the elements from one list to another, after, sort the filled list. Hint 2 Revealed Notice! appending whole list to another, lst1.append(lst2) For example for lst1 = [1, 2] and lst2 = [3, 4], in the end of the operation lst1 = [1, 2, [3, 4]]. As you see, the list will hold list inside it, this is not what we need! (and it will result in error if you will try to do lst1.sort())
ed69e53ac472234abbf8dbf3bba80dc9
{ "intermediate": 0.37945035099983215, "beginner": 0.24968662858009338, "expert": 0.3708629906177521 }
46,470
can you shrink this code but keep function? "import asyncio, socket, pickle, threading from kivy.clock import Clock from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.scrollview import ScrollView from kivy.uix.boxlayout import BoxLayout from kivymd.app import MDApp from discord.ext import commands import discord class DiscordGUI(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.orientation = 'vertical' self.padding = [10, 10, 10, 10] intents = discord.Intents.default() intents.typing = False intents.presences = False self.bot = commands.Bot(command_prefix="!", intents=intents) self.channels = [] self.selected_channel = None self.match_channel = None self.bot_token_entry = TextInput(hint_text="Bot Token:", multiline=False) self.server_id_entry = TextInput(hint_text="Server ID:", multiline=False) self.add_widget(self.bot_token_entry) self.add_widget(self.server_id_entry) self.add_widget(Button(text="Start Discord Bot", on_press=self.run_bot)) self.fetch_button = Button(text="Fetch Channels", on_press=self.fetch_channels, disabled=True) self.add_widget(self.fetch_button) self.listen_button = Button(text="Listen", on_press=self.listen_server, disabled=True) self.add_widget(self.listen_button) self.channel_layout = GridLayout(cols=4, size_hint_y=None) self.channel_layout.bind(minimum_height=self.channel_layout.setter('height')) self.channel_buttons = ScrollView() self.channel_buttons.add_widget(self.channel_layout) self.add_widget(self.channel_buttons) def run_bot(self, instance): loop = asyncio.get_event_loop() self.bot_task = loop.create_task(self.bot.start(self.bot_token_entry.text.strip())) Clock.schedule_interval(lambda dt: loop.run_until_complete(asyncio.sleep(0)), 0.01) self.fetch_button.disabled = False def fetch_channels(self, instance): loop = asyncio.get_event_loop() loop.create_task(self._fetch_channels()) async def _fetch_channels(self): guild_id = int(self.server_id_entry.text.strip()) guild = self.bot.get_guild(guild_id) if guild: self.channels = [(channel.name, channel.id) for channel in guild.text_channels] Clock.schedule_once(lambda dt: self.update_buttons()) def update_buttons(self): for widget in self.channel_layout.children[:]: if isinstance(widget, Button) and widget.text in [channel[0] for channel in self.channels]: self.channel_layout.remove_widget(widget) for channel in self.channels: button = Button(text=channel[0], size_hint_y=None, height=50) button.bind(on_press=self.toggle_button) self.channel_layout.add_widget(button) self.listen_button.disabled = False def toggle_button(self, instance): if self.selected_channel: self.selected_channel.background_color = (1, 1, 1, 1) instance.background_color = (0, 0, 0, 1) self.selected_channel = instance self.match_channel = next(channel[1] for channel in self.channels if channel[0] == instance.text) def listen_server(self, instance): if self.match_channel: listen_thread = threading.Thread(target=self._listen_server) listen_thread.start() def _listen_server(self): server_address = ('localhost', 12345) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect(server_address) while True: data = sock.recv(1024) if not data: break shared_dict = pickle.loads(data) Clock.schedule_once(lambda dt: self.send_message_to_discord(shared_dict)) def send_message_to_discord(self, match_data): if hasattr(self.selected_channel, 'text'): channel_id = self.match_channel channel = self.bot.get_channel(channel_id) if channel: asyncio.run_coroutine_threadsafe(channel.send(str(match_data)), self.bot.loop) class DiscordApp(MDApp): def build(self): self.gui = DiscordGUI() return self.gui def on_stop(self): self.gui.bot_task.cancel() if __name__ == "__main__": DiscordApp().run() "
e9990584427d64f953127d557f18aa51
{ "intermediate": 0.35404130816459656, "beginner": 0.4718267321586609, "expert": 0.17413203418254852 }
46,471
import asyncio, socket, pickle, threading from kivy.clock import Clock from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.scrollview import ScrollView from kivy.uix.boxlayout import BoxLayout from kivymd.app import MDApp from discord.ext import commands import discord class DiscordGUI(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.orientation = 'vertical' self.padding = [10, 10, 10, 10] intents = discord.Intents.default() intents.typing = False intents.presences = False self.bot = commands.Bot(command_prefix="!", intents=intents) self.channels = [] self.selected_channel = None self.match_channel = None self.bot_token_entry = TextInput(hint_text="Bot Token:", multiline=False) self.server_id_entry = TextInput(hint_text="Server ID:", multiline=False) self.add_widget(self.bot_token_entry) self.add_widget(self.server_id_entry) self.add_widget(Button(text="Start Discord Bot", on_press=self.run_bot)) self.fetch_button = Button(text="Fetch Channels", on_press=self.fetch_channels, disabled=True) self.add_widget(self.fetch_button) self.listen_button = Button(text="Listen", on_press=self.listen_server, disabled=True) self.add_widget(self.listen_button) self.channel_layout = GridLayout(cols=4, size_hint_y=None) self.channel_layout.bind(minimum_height=self.channel_layout.setter('height')) self.channel_buttons = ScrollView() self.channel_buttons.add_widget(self.channel_layout) self.add_widget(self.channel_buttons) def run_bot(self, instance): loop = asyncio.get_event_loop() self.bot_task = loop.create_task(self.bot.start(self.bot_token_entry.text.strip())) Clock.schedule_interval(lambda dt: loop.run_until_complete(asyncio.sleep(0)), 0.01) self.fetch_button.disabled = False def fetch_channels(self, instance): loop = asyncio.get_event_loop() loop.create_task(self._fetch_channels()) async def _fetch_channels(self): guild_id = int(self.server_id_entry.text.strip()) guild = self.bot.get_guild(guild_id) if guild: self.channels = [(channel.name, channel.id) for channel in guild.text_channels] Clock.schedule_once(lambda dt: self.update_buttons()) def update_buttons(self): for widget in self.channel_layout.children[:]: if isinstance(widget, Button) and widget.text in [channel[0] for channel in self.channels]: self.channel_layout.remove_widget(widget) for channel in self.channels: button = Button(text=channel[0], size_hint_y=None, height=50) button.bind(on_press=self.toggle_button) self.channel_layout.add_widget(button) self.listen_button.disabled = False def toggle_button(self, instance): if self.selected_channel: self.selected_channel.background_color = (1, 1, 1, 1) instance.background_color = (0, 0, 0, 1) self.selected_channel = instance self.match_channel = next(channel[1] for channel in self.channels if channel[0] == instance.text) def listen_server(self, instance): if self.match_channel: listen_thread = threading.Thread(target=self._listen_server) listen_thread.start() def _listen_server(self): server_address = ('localhost', 12345) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect(server_address) while True: data = sock.recv(1024) if not data: break shared_dict = pickle.loads(data) Clock.schedule_once(lambda dt: self.send_message_to_discord(shared_dict)) def send_message_to_discord(self, match_data): if hasattr(self.selected_channel, 'text'): channel_id = self.match_channel channel = self.bot.get_channel(channel_id) if channel: asyncio.run_coroutine_threadsafe(channel.send(str(match_data)), self.bot.loop) class DiscordApp(MDApp): def build(self): self.gui = DiscordGUI() return self.gui def on_stop(self): self.gui.bot_task.cancel() if __name__ == "__main__": DiscordApp().run()
79c8f50fa9bb1f7a0db9fbcb5582b785
{ "intermediate": 0.25978973507881165, "beginner": 0.5837438702583313, "expert": 0.15646637976169586 }
46,472
hi
232b62ef0c603c73f43f5b0a2109be6f
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
46,473
' Write the numeric value into column G starting from row 4 ws.Cells(i, 7).Value = numericValue explain this
757c501e689853f1c3cb084d4eb12c45
{ "intermediate": 0.5095102787017822, "beginner": 0.17960011959075928, "expert": 0.3108895421028137 }
46,474
i use lora module with arduino. when sending from arduino nano to esp32 just one chr of my string send to esp32 but reverse its ok. why?
db6ff2f9ca6818f3e97e143ef8dcb377
{ "intermediate": 0.5651723742485046, "beginner": 0.18290215730667114, "expert": 0.2519254684448242 }
46,475
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.losses import CategoricalFocalCrossentropy from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 16 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss Categorical_Focal_loss = tf.keras.losses.CategoricalFocalCrossentropy( alpha=0.25, gamma=2.0, from_logits=False, label_smoothing=0.0, axis=-1,) def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": Categorical_Focal_loss, "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good", "insuff", "no"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class # P = 60 class_data_counts = { "bridge": [80, 80, 80], "excess": [80, 80, 80], "good": [80, 80, 80], "insuff": [80, 80, 80], "no": [80, 80, 80]} # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(1): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 100 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model, helping me to remove the unnecessary libraries and unnecessary code.
41a75eaf8ce6be2dbce217a613f95785
{ "intermediate": 0.43761172890663147, "beginner": 0.29308488965034485, "expert": 0.2693033814430237 }
46,476
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.losses import CategoricalFocalCrossentropy from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 16 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss Categorical_Focal_loss = tf.keras.losses.CategoricalFocalCrossentropy( alpha=0.25, gamma=2.0, from_logits=False, label_smoothing=0.0, axis=-1,) def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": Categorical_Focal_loss, "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good", "insuff", "no"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class # P = 60 class_data_counts = { "bridge": [80, 80, 80], "excess": [80, 80, 80], "good": [80, 80, 80], "insuff": [80, 80, 80], "no": [80, 80, 80]} # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(1): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 100 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model, helping me to add #comment for each section.
954a778da20236c11cf7cf267305d0cc
{ "intermediate": 0.43761172890663147, "beginner": 0.29308488965034485, "expert": 0.2693033814430237 }
46,477
если ли red orchestra, или какой-либо xen manager на python3 (pip3 install)
5c474963efff751202521e9b38426a71
{ "intermediate": 0.3733442425727844, "beginner": 0.3154895007610321, "expert": 0.31116628646850586 }
46,478
You are a Python expert who can provide clear, concise, high-quality code. " import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.losses import CategoricalFocalCrossentropy from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, ) from tensorflow.keras.applications import Xception from tensorflow.keras.applications import VGG16, VGG19 from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101 from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount("/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(".jpg"): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(".")[0] + ".png" seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts): X_train = [] y_train_class = [] y_train_seg = [] X_val = [] y_val_class = [] y_val_seg = [] X_test = [] y_test_class = [] y_test_seg = [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] class_y_seg_labels = y_seg_labels[label_indices] train_count = count[0] val_count = count[1] test_count = count[2] class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_y_train_seg = class_y_seg_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) y_train_seg.extend(class_y_train_seg) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) y_val_seg.extend(class_y_val_seg) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) y_test_seg.extend(class_y_test_seg) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(y_train_seg), np.array(X_val), np.array(y_val_class_categorical), np.array(y_val_seg), np.array(X_test), np.array(y_test_class_categorical), np.array(y_test_seg), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): num_filter = 16 # 16/32 best, 8: best classification but no segment # Encoder (Done) inputs = Input(input_shape) conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs) bn1 = BatchNormalization()(conv1) relu1 = Activation("relu")(bn1) conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1) bn2 = BatchNormalization()(conv2) relu2 = Activation("relu")(bn2) down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2) conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1) bn3 = BatchNormalization()(conv3) relu3 = Activation("relu")(bn3) conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3) bn4 = BatchNormalization()(conv4) relu4 = Activation("relu")(bn4) down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4) conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2) bn5 = BatchNormalization()(conv5) relu5 = Activation("relu")(bn5) conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5) bn6 = BatchNormalization()(conv6) relu6 = Activation("relu")(bn6) down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6) conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3) bn7 = BatchNormalization()(conv7) relu7 = Activation("relu")(bn7) conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7) bn8 = BatchNormalization()(conv8) relu8 = Activation("relu")(bn8) # Middle down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8) conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4) bn9 = BatchNormalization()(conv9) relu9 = Activation("relu")(bn9) conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9) bn10 = BatchNormalization()(conv10) relu10 = Activation("relu")(bn10) up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10) # Decoder (Done) concat1 = concatenate([up1, relu8], axis=-1) # , axis=3 conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1) bn11 = BatchNormalization()(conv11) relu11 = Activation("relu")(bn11) conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11) bn12 = BatchNormalization()(conv12) relu12 = Activation("relu")(bn12) up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12) concat2 = concatenate([up2, relu6], axis=-1) # , axis=3 conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2) bn13 = BatchNormalization()(conv13) relu13 = Activation("relu")(bn13) conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13) bn14 = BatchNormalization()(conv14) relu14 = Activation("relu")(bn14) up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14) concat3 = concatenate([up3, relu4], axis=-1) # , axis=3 conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3) bn15 = BatchNormalization()(conv15) relu15 = Activation("relu")(bn15) conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15) bn16 = BatchNormalization()(conv16) relu16 = Activation("relu")(bn16) up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16) concat4 = concatenate([up4, relu2], axis=-1) # , axis=3 conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4) bn17 = BatchNormalization()(conv17) relu17 = Activation("relu")(bn17) conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17) bn18 = BatchNormalization()(conv18) relu18 = Activation("relu")(bn18) # Segmentation branch segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original # Classification branch (Not done) gap1 = GlobalAveragePooling2D()(relu8) gap2 = GlobalAveragePooling2D()(relu10) gap3 = GlobalAveragePooling2D()(relu12) conv20 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(segmentation_output) bn20 = BatchNormalization()(conv20) relu20 = Activation("relu")(bn20) down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20) conv21 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down5) bn21 = BatchNormalization()(conv21) relu21 = Activation("relu")(bn21) down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21) conv22 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(down6) bn22 = BatchNormalization()(conv22) relu22 = Activation("relu")(bn22) down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22) flatten1 = Flatten()(down7) concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1) # FC layers fc1 = Dense(1024, activation="relu")(concat5) dropout1 = Dropout(0.5)(fc1) fc2 = Dense(1024, activation="relu")(dropout1) dropout2 = Dropout(0.5)(fc2) classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2) # Define the model model = Model(inputs=inputs, outputs=[classification_output, segmentation_output]) return model def segmentation_loss(y_true, y_pred): y_true = tf.cast(y_true, tf.float32) y_pred = tf.cast(y_pred, tf.float32) bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) smooth = 1e-5 intersection = tf.reduce_sum(y_true * y_pred) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth) segmentation_loss = bce_loss + 1 * dice_loss return segmentation_loss Categorical_Focal_loss = tf.keras.losses.CategoricalFocalCrossentropy( alpha=0.25, gamma=2.0, from_logits=False, label_smoothing=0.0, axis=-1,) def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs): checkpoint = ModelCheckpoint( "multitask_best_weights.h5", monitor="val_classification_output_accuracy", save_best_only=True, mode="max", verbose=1,) reduce_lr = ReduceLROnPlateau( monitor="val_classification_output_accuracy", factor=0.3, patience=2, min_delta=0.001, mode="auto", verbose=1,) tensorboard = TensorBoard(log_dir="logs") model.compile( optimizer=Adam(lr=0.001), loss={"classification_output": Categorical_Focal_loss, "segmentation_output": segmentation_loss}, metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"}, loss_weights={"classification_output": 1, "segmentation_output": 1},) history = model.fit( X_train, {"classification_output": y_train_class, "segmentation_output": y_train_seg}, validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class, y_test_seg): with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}): # Load the best model weights best_model = load_model("multitask_best_weights.h5") # Evaluate the model on test data test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate( X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg}) print("Test Classification Loss:", test_class_loss) print("Test Segmentation Loss:", test_seg_loss) print("Test Classification Accuracy:", test_class_acc) print("Test Segmentation Accuracy:", test_seg_acc) # Evaluate the model on validation data val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate( X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg}) print("Validation Classification Loss:", val_class_loss) print("Validation Segmentation Loss:", val_seg_loss) print("Validation Classification Accuracy:", val_class_acc) print("Validation Segmentation Accuracy:", val_seg_acc) # Evaluate the model on training data train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg}) print("Train Classification Loss:", train_class_loss) print("Train Segmentation Loss:", train_seg_loss) print("Train Classification Accuracy:", train_class_acc) print("Train Segmentation Accuracy:", train_seg_acc) # Return test classification accuracy return test_class_acc def plot_performance(history): # Plot classification accuracy classification_train_accuracy = history.history["classification_output_accuracy"] classification_val_accuracy = history.history["val_classification_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_accuracy, label="Training Accuracy") plt.plot(classification_val_accuracy, label="Validation Accuracy") plt.title("Classification Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot classification loss classification_train_loss = history.history["classification_output_loss"] classification_val_loss = history.history["val_classification_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(classification_train_loss, "b", label="Training Loss") plt.plot(classification_val_loss, "r", label="Validation Loss") plt.title("Classification Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Plot segmentation accuracy segmentation_train_accuracy = history.history["segmentation_output_accuracy"] segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_accuracy, label="Training Accuracy") plt.plot(segmentation_val_accuracy, label="Validation Accuracy") plt.title("Segmentation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() # Plot segmentation loss segmentation_train_loss = history.history["segmentation_output_loss"] segmentation_val_loss = history.history["val_segmentation_output_loss"] plt.figure(figsize=(7, 3)) plt.plot(segmentation_train_loss, "b", label="Training Loss") plt.plot(segmentation_val_loss, "r", label="Validation Loss") plt.title("Segmentation Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend() plt.show() # Set image size image_size = 224 # Define labels labels = ["bridge", "excess", "good", "insuff", "no"] # Set data folders data_folders = [ "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/train", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/val", "/content/gdrive/MyDrive/Deep learning/FYP_2/4 Dataset Ratio 60 20 20/jit012/jit0/b_dip/test",] # Load data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class # P = 60 class_data_counts = { "bridge": [80, 80, 80], "excess": [80, 80, 80], "good": [80, 80, 80], "insuff": [80, 80, 80], "no": [80, 80, 80]} # Split data X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data( X_data, y_class_labels, y_seg_labels, class_data_counts) # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values())) print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values())) print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values())) # Build model input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() # Train model n times test_class_acc_list = [] for i in range(1): print(f"\nTrain {i+1}:\n") model = build_model(input_shape, num_classes) batch_size = 16 epochs = 100 history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs) # Evaluate model on test data test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg) plot_performance(history) test_class_acc_list.append(test_class_acc) # Calculate average test classification accuracy average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list) print("Test Classification Accuracy List:", test_class_acc_list) print("Average Test Classification Accuracy:", average_test_class_acc) " The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model, and train the model for 5 times. Help me to remove all unnecessary libraries.
af88325ec33d1ead271ea7d94db3a0dd
{ "intermediate": 0.43761172890663147, "beginner": 0.29308488965034485, "expert": 0.2693033814430237 }
46,479
Dim sourceWorkbook As Workbook Dim destWorkbook As Workbook Dim sourceSheet As Worksheet Dim destSheet As Worksheet Dim folderPath As String Dim sourceFileName As String Dim sourceFilePath As String ' Dynamically get the folder path of the workbook containing this script (.xlsm) ' and ensure it ends with a backslash folderPath = ThisWorkbook.Path If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\" End If ' Get the name of the first .xlsx file in the folder sourceFileName = Dir(folderPath & "*.xlsx") ' Check if an .xlsx file was found If sourceFileName = "" Then MsgBox "No .xlsx file found in the same folder." Exit Sub End If ' Construct the full file path for the .xlsx file sourceFilePath = folderPath & sourceFileName ' Set the destination workbook and sheet ' ThisWorkbook refers to the workbook containing this script (.xlsm) Set destWorkbook = ThisWorkbook Set destSheet = destWorkbook.Sheets(1) ' Adjust as needed if copying to a different sheet ' Attempt to open the source .xlsx file On Error Resume Next ' In case the file doesn't open Set sourceWorkbook = Workbooks.Open(sourceFilePath) On Error GoTo 0 ' Turn back on regular error handling after attempt to open ' Check if the workbook was successfully opened If sourceWorkbook Is Nothing Then MsgBox "Failed to open the .xlsx file." Exit Sub End If ' Set the source sheet (assuming data is on the first sheet) Set sourceSheet = sourceWorkbook.Sheets(1) ' Copy the used range from the source sheet to the destination sheet sourceSheet.UsedRange.Copy Destination:=destSheet.Cells(2, 2) ' Starts pasting from B4 ' Close the source workbook without saving changes sourceWorkbook.Close SaveChanges:=False MsgBox "Data copied successfully from " & sourceFileName End Sub------- from this code i want no matter where data in source is placed ,an copy only data and ignore blank cell , data to be pasted in destinatination cells starting with column b and row 4
3e250ed27405838980f8abe57fae3828
{ "intermediate": 0.5111481547355652, "beginner": 0.2189868688583374, "expert": 0.2698649764060974 }
46,480
基于INCLUDE Irvine32.inc将下面的c++转化为32位汇编语言#include<bits/stdc++.h> using namespace std; int pd(int k,int x){ if(k>x) return 0; else if(k==x) return 1; if (pd(2*k+1,x)==1) return 1; return pd(3*k+1,x); } int main() { int k,x; scanf("%d,%d",&k,&x); if(pd(k,x)==1) printf("YES"); else if(pd(k,x)==0) printf("NO"); return 0; }
488cd24964ad6410a67ca7450eaa5464
{ "intermediate": 0.3006698787212372, "beginner": 0.5208355188369751, "expert": 0.17849458754062653 }
46,481
import { Image, ScrollView, View, SafeAreaView, useWindowDimensions, Text, Pressable, } from "react-native" import { StyledText } from "../../../ui-components/styled-text/styled-text" import React, { useEffect, useState } from "react" import { Header } from "../../../ui-components/header/header.component" import { Input } from "../../../ui-components/input/input" import { useBansByCommunity, useMembersByCommunity, useRolesByCommunity, } from "@openchat/ui" import { MemberType, RoleType } from "@openchat/types" import { Mutator } from "@openchat/core" import { CommunitySettingsMembersItem } from "./community-settings-members-item/community-settings-members-item.component" import { useNavigationRouteParams } from "../../../navigation/navigation.hooks" import { AppConfig } from "../../../app/app.config" import { TEXT } from "emojibase" import { MenuOpener } from "../../../ui-components/menu/menu-opener.provider" import { Icon } from "../../../ui-components/icon/icon.component" import { Button } from "../../../ui-components/button/button.component" import { MenuButton } from "../../../ui-components/menu-item/menu-button.component" import { useModal } from "../../../ui-components/modal/modal.hook" import { Checkbox } from "../../../ui-components/checkbox/checkbox.component" import { useStyles } from "./community-settings-members.style" import { CommunitySettingsRoleFilter } from "./community-settings-members-item/community-settings-role-filter.component" import { MenuItem } from "../../../ui-components/menu" import { AppAssets } from "../../../app/app.assets" import { EmptyState } from "../../../ui-components/empty-state/empty-state.component" export const CommunitySettingsMember = () => { // --------------------------------------------------------------------------- // variables // --------------------------------------------------------------------------- const { community, hasPermissionsForCommunities } = useNavigationRouteParams( "CommunitySettingsMember", ) const styles = useStyles() const members = useMembersByCommunity(community.id) const [keyword, setKeyword] = useState("") const [roleIds, setRoleIds] = useState<string[]>([]) const roles = useRolesByCommunity(community.id) const bans = useBansByCommunity(community.id) const [filteredMembers, setFilteredMembers] = useState<MemberType[]>([]) const modal = useModal() const { width, height } = useWindowDimensions() // --------------------------------------------------------------------------- // effects // --------------------------------------------------------------------------- useEffect(() => { filterMembers() }, [members, roleIds, keyword, community]) // --------------------------------------------------------------------------- // functions // --------------------------------------------------------------------------- function filterMembers() { let filteredMembers = members if (roleIds.length) { filteredMembers = filteredMembers.filter((member) => roles.some( (role) => role.identityIds.includes(member.identityId) && roleIds.includes(role.id), ), ) } if (keyword) { filteredMembers = filteredMembers.filter( (member) => member.name && member.name.toLowerCase().indexOf(keyword.toLowerCase()) !== -1, ) } setFilteredMembers(filteredMembers) } function updateMember(member: MemberType) { const memberToUpdate = filteredMembers.find( (filteredMember) => filteredMember.id === member.id, ) if (!memberToUpdate) return const updatedMembers = Mutator.replace( filteredMembers, member, memberToUpdate, ) setFilteredMembers(updatedMembers) } function filterHandler() { console.log("=================roleIds===================") console.log(roleIds) console.log("====================================") modal.open({ background: "pattern", scrollEnabled: false, footer: "rgb", component: ( <CommunitySettingsRoleFilter roles={roles} selectedRoles={roleIds} onPress={(roleIds: string[]) => setRoleIds(roleIds)} /> ), }) } // --------------------------------------------------------------------------- return ( <View style={styles.container}> <Header backIcon={true} heading="Members" animate childrenOrList={ <MenuOpener position="bottom-left" style={{ marginTop: -10 }} content={ <MenuItem onPress={filterHandler}> <View style={styles.iconRow}> <Icon name="fa-light fa-poll-people" size={16} /> <StyledText style={{ width: "auto", fontSize: 18, fontWeight: "400", color: "black", }} > Filter by role </StyledText> </View> </MenuItem> } > <Icon name="fa-regular fa-bars-filter" size={18} fill={"#8592AA"} /> </MenuOpener> } /> <SafeAreaView style={styles.filter}> <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.list} > <View style={{ marginTop: members.length > 0 ? 20 : height <= 600 ? 50 : null, flex: 1, }} > <View style={styles.searchBox}> <Input testID="searchMembersInput" placeholder="Search" type={keyword ? "clear" : "search"} onChangeText={(text) => setKeyword(text.trim())} onIconPress={() => setKeyword("")} value={keyword} mode="secondary" /> </View> <View style={{ marginTop: 15 }}> {filteredMembers.length > 0 && filteredMembers.map((member, index) => ( <CommunitySettingsMembersItem testID={`member.${index}`} key={member.id} member={member} bans={bans} community={community} updateMember={(member: MemberType) => updateMember(member)} keyword={keyword} hasPermissionsForCommunities={hasPermissionsForCommunities} index={index} /> ))} {filteredMembers.length <= 0 && ( <View style={styles.notChannel}> <EmptyState title="No members yet..." description="Invite peoples to your community" image={AppAssets.images.chatPhoto} /> </View> )} </View> </View> </ScrollView> </SafeAreaView> </View> ) } import { useState, useEffect } from "react" import { View, Pressable, ScrollView } from "react-native" import { StyledText } from "../../../../ui-components/styled-text/styled-text" import { Checkbox } from "../../../../ui-components/checkbox/checkbox.component" import { useStyles } from "../community-settings-members.style" import { RoleType } from "@openchat/types" import { Input } from "../../../../ui-components/input/input" import { StickyFooter } from "../../../../ui-components/sticky-footer/sticky-footer.component" import { Button } from "../../../../ui-components/button/button.component" import { useModal } from "../../../../ui-components/modal/modal.hook" import { Mutator } from "@openchat/core" export const CommunitySettingsRoleFilter = ({ roles, selectedRoles, onPress, }: { roles: RoleType[] selectedRoles: string[] onPress: (roleIds: string[]) => void }) => { // --------------------------------------------------------------------------- // variables // --------------------------------------------------------------------------- const styles = useStyles() const [checkedRoles, setCheckedRoles] = useState<string[]>(selectedRoles) const [keyword, setKeyword] = useState("") const [filteredRoles, setFilteredRoles] = useState<RoleType[]>(roles) const modal = useModal() console.log("=================selectedRoles===================") console.log(selectedRoles) console.log("====================================") // --------------------------------------------------------------------------- // useEffect // --------------------------------------------------------------------------- useEffect(() => { onChangeKeyword() }, [keyword]) // --------------------------------------------------------------------------- // functions // --------------------------------------------------------------------------- function onChangeKeyword() { let filteredRoles = roles if (keyword !== "") { filteredRoles = filteredRoles.filter( (role) => role.name!.toLowerCase().indexOf(keyword.toLowerCase()) !== -1, ) } setFilteredRoles(filteredRoles) } function toggleRole(roleIds: string) { const isRoleSelected = checkedRoles.includes(roleIds) if (isRoleSelected) { setCheckedRoles((prev) => Mutator.remove(prev, roleIds)) } else { setCheckedRoles((prev) => [...prev, roleIds]) } } return ( <View style={styles.modal}> <StyledText style={styles.titleFilterRoles}>Filter By Role</StyledText> {roles.length > 0 ? ( <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{ flexGrow: 1 }} > <View style={styles.input}> <Input placeholder="Search roles" type={keyword ? "clear" : "search"} onChangeText={setKeyword} onIconPress={() => setKeyword("")} mode="secondary" value={keyword} /> </View> <View style={{}}> {filteredRoles.map((role) => ( <> <Pressable key={role.id} style={({ pressed }) => [ styles.filterRoleItem, { backgroundColor: pressed ? "#EEF2F6" : "white", }, ]} onPress={() => toggleRole(role.id)} > <View style={styles.filterNameAndColor}> <View style={[ styles.filterRoleColor, { backgroundColor: role.color }, ]} /> <StyledText ellipsizeMode="tail" numberOfLines={1} style={styles.roleName} > {role.name} </StyledText> </View> <Checkbox size={18} checked={checkedRoles.includes(role.id)} onClick={() => toggleRole(role.id)} /> </Pressable> </> ))} </View> </ScrollView> ) : ( <View style={styles.notContent}> <StyledText style={styles.title}>No roles yet...</StyledText> <StyledText style={styles.description}> Invite peoples to your community </StyledText> </View> )} <StickyFooter size="small" withLine={true} noBackground={true}> <View style={styles.buttons}> <Button type="simple" onPress={() => modal.close()}> Cancel </Button> <Button type="primary" disabled={checkedRoles.length ? false : true} onPress={() => { onPress(checkedRoles), modal.close() }} > Save </Button> </View> </StickyFooter> </View> ) } the issue here selectedRoles={roleIds}. Why roleIds come empty when I check roleIds outside of filterHandler not empty. Why comming empty array ?
20e2c37c19e59fa921fe33b7a8cf0d02
{ "intermediate": 0.3274730145931244, "beginner": 0.4665539264678955, "expert": 0.2059730887413025 }
46,482
from tensorflow.python.platform import _pywrap_tf2 ImportError: DLL load failed while importing _pywrap_tf2:
58343122a81f4c6abe0bb845a4df4adf
{ "intermediate": 0.5535414218902588, "beginner": 0.20721040666103363, "expert": 0.2392481565475464 }
46,483
Why the Grid Player on Fedora is flashing?
373b7040e05cd4991a82e37918d3deaa
{ "intermediate": 0.4662662148475647, "beginner": 0.23110629618167877, "expert": 0.3026275634765625 }
46,484
i have historical data of crypto i have following code to train a lstm model on my data check and see if it has any problems: # %% import numpy as np import pandas as pd from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense from sklearn.preprocessing import MinMaxScaler import os # %% def load_and_process_data(file_path, target_col, scaler, sequence_length, batch_size = 32): # Load data data = pd.read_csv(file_path) # Split features and labels X = data.drop([ 'Date', 'Symbol', 'y_High_1d', 'y_Low_1d', 'y_Priority_1d', 'y_High_2d', 'y_Low_2d', 'y_Priority_2d', 'y_High_3d', 'y_Low_3d', 'y_Priority_3d', 'y_High_5d', 'y_Low_5d', 'y_Priority_5d'], axis=1).values y_high_1d = data['y_High_1d'].values y_low_1d = data['y_Low_1d'].values y_priority_1d = data['y_Priority_1d'].values y_high_2d = data['y_High_2d'].values y_low_2d = data['y_Low_2d'].values y_priority_2d = data['y_Priority_2d'].values y_high_3d = data['y_High_3d'].values y_low_3d = data['y_Low_3d'].values y_priority_3d = data['y_Priority_3d'].values y_high_5d = data['y_High_5d'].values y_low_5d = data['y_Low_5d'].values y_priority_5d = data['y_Priority_5d'].values # Optionally, apply preprocessing here (e.g., Scaler transform) X = scaler.fit_transform(X) X = scaler.transform(X) # # Create sequences # X_seq, y_seq = [], [] # for i in range(len(X) - sequence_length): # X_seq.append(X[i:i+sequence_length]) # y_seq.append(y[i+sequence_length]) # return np.array(X_seq), np.array(y_seq) # Splitting data into batches for i in range(0, len(data), batch_size): end = i + batch_size X_batch = X[i:end] y_high_batch_1d = y_high_1d[i:end] y_low_batch_1d = y_low_1d[i:end] y_priority_batch_1d = y_priority_1d[i:end] y_high_batch_2d = y_high_2d[i:end] y_low_batch_2d = y_low_2d[i:end] y_priority_batch_2d = y_priority_2d[i:end] y_high_batch_3d = y_high_3d[i:end] y_low_batch_3d = y_low_3d[i:end] y_priority_batch_3d = y_priority_3d[i:end] y_high_batch_5d = y_high_5d[i:end] y_low_batch_5d = y_low_5d[i:end] y_priority_batch_5d = y_priority_5d[i:end] yield X_batch, [y_high_batch_1d, y_low_batch_1d,y_priority_batch_1d, y_high_batch_2d, y_low_batch_2d,y_priority_batch_2d, y_high_batch_3d, y_low_batch_3d, y_priority_batch_3d, y_high_batch_5d, y_low_batch_5d, y_priority_batch_5d] # %% scaler = MinMaxScaler(feature_range=(0, 1)) # Normally, you'd fit the scaler on your dataset. You'll need to adapt this to your scenario. # For demonstration, let's assume all features are within 0 and 100. # %% def train_model(files, batch_size, epochs): target_cols =[ 'y_High_1d', 'y_Low_1d', 'y_Priority_1d', 'y_High_2d', 'y_Low_2d', 'y_Priority_2d', 'y_High_3d', 'y_Low_3d', 'y_Priority_3d', 'y_High_5d', 'y_Low_5d', 'y_Priority_5d'] for epoch in range(epochs): data_generator = load_and_process_data(file_path, target_cols, scaler, sequence_length=30, batch_size = batch_size) for X_batch, y_batch in data_generator: # Here’s how you iterate over the generator model.train_on_batch(X_batch, y_batch) # %% from tensorflow.keras.layers import Input, Dense, LSTM, concatenate from tensorflow.keras.models import Model # Input layer input_layer = Input(shape=(30, 6427)) # Adjust accordingly # Shared LSTM layer lstm_out = LSTM(50, activation='relu')(input_layer) # Defining three separate outputs out_high_1d = Dense(1, name='high_output_1d')(lstm_out) # No activation, linear output out_low_1d = Dense(1, name='low_output_1d')(lstm_out) # No activation, linear output out_priority_1d = Dense(1, activation='sigmoid', name='priority_output_1d')(lstm_out) out_high_2d = Dense(1, name='high_output_2d')(lstm_out) # No activation, linear output out_low_2d = Dense(1, name='low_output_2d')(lstm_out) # No activation, linear output out_priority_2d = Dense(1, activation='sigmoid', name='priority_output_2d')(lstm_out) out_high_3d = Dense(1, name='high_output_3d')(lstm_out) # No activation, linear output out_low_3d = Dense(1, name='low_output_3d')(lstm_out) # No activation, linear output out_priority_3d = Dense(1, activation='sigmoid', name='priority_output_3d')(lstm_out) out_high_5d = Dense(1, name='high_output_5d')(lstm_out) # No activation, linear output out_low_5d = Dense(1, name='low_output_5d')(lstm_out) # No activation, linear output out_priority_5d = Dense(1, activation='sigmoid', name='priority_output_5d')(lstm_out) # Constructing the model model = Model(inputs=input_layer, outputs=[ out_high_1d, out_low_1d, out_priority_1d,out_high_2d, out_low_2d, out_priority_2d, out_high_3d, out_low_3d, out_priority_3d,out_high_5d, out_low_5d, out_priority_5d]) model.compile(optimizer='adam', loss={ 'high_output_1d': 'mse', 'low_output_1d': 'mse', 'priority_output_1d': 'binary_crossentropy', 'high_output_2d': 'mse', 'low_output_2d': 'mse', 'priority_output_2d': 'binary_crossentropy', 'high_output_3d': 'mse', 'low_output_3d': 'mse', 'priority_output_3d': 'binary_crossentropy', 'high_output_5d': 'mse', 'low_output_5d': 'mse', 'priority_output_5d': 'binary_crossentropy' }, metrics={ 'high_output_1d': ['mae'], 'low_output_1d': ['mae'], 'priority_output_1d': ['accuracy'], 'high_output_2d': ['mae'], 'low_output_2d': ['mae'], 'priority_output_2d': ['accuracy'], 'high_output_3d': ['mae'], 'low_output_3d': ['mae'], 'priority_output_3d': ['accuracy'], 'high_output_5d': ['mae'], 'low_output_5d': ['mae'], 'priority_output_5d': ['accuracy'] } ) # %% csv_folder_path = r"E:\01_calculate_talib\New folder (2)" file_paths = [] # Update this list with actual file paths for csv_file in os.listdir(csv_folder_path): file_path = os.path.join(csv_folder_path, csv_file) file_paths.append(file_path) batch_size = 32 epochs = 1000 # Set the number of epochs train_model(file_paths, batch_size, epochs) # %%
c634f20e27caef43a286353442f839db
{ "intermediate": 0.48119255900382996, "beginner": 0.24829445779323578, "expert": 0.2705129384994507 }
46,485
I will send you a JSONL file snippet. Your task is to check parse error in the snippet.
a5731f46048b8123d60219b58152679c
{ "intermediate": 0.5433977842330933, "beginner": 0.23172686994075775, "expert": 0.22487536072731018 }
46,486
Task exception was never retrieved future: <Task finished name='Task-18' coro=<Dispatcher._process_polling_updates() done, defined at C:\YandexGPT\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py:407> exception=OperationalError('near ")": syntax error')> Traceback (most recent call last): File "C:\YandexGPT\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\YandexGPT\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates return await asyncio.gather(*tasks) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\YandexGPT\.venv\Lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify response = await handler_obj.handler(*args, **partial_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\YandexGPT\.venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 283, in process_update return await self.callback_query_handlers.notify(update.callback_query) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\YandexGPT\.venv\Lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify response = await handler_obj.handler(*args, **partial_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\YandexGPT\main.py", line 446, in process_generate await YandexGPT.generate(prompt, api_key, sa_id, user_id) File "C:\YandexGPT\main.py", line 429, in generate await save_result(user_id, parse_yandexgpt(answer)) File "C:\YandexGPT\main.py", line 365, in save_result await db.execute(f"INSERT INTO public_info (user_id, {columns}) VALUES (?, {placeholders})", [user_id, *values]) File "C:\YandexGPT\.venv\Lib\site-packages\aiosqlite\core.py", line 193, in execute cursor = await self._execute(self._conn.execute, sql, parameters) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\YandexGPT\.venv\Lib\site-packages\aiosqlite\core.py", line 132, in _execute return await future ^^^^^^^^^^^^ File "C:\YandexGPT\.venv\Lib\site-packages\aiosqlite\core.py", line 115, in run result = function() ^^^^^^^^^^ sqlite3.OperationalError: near ")": syntax error Код бота: from aiogram import Bot, Dispatcher, executor, types from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup from aiogram.utils.callback_data import CallbackData import aiosqlite import asyncio import aiohttp import json import re API_TOKEN = '6996318383:AAEcQfdQhzEg3L_6DKQVidJEn46Wb27Sy4g' ADMINS = [989037374, 1515567046] bot = Bot(token=API_TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) class Form(StatesGroup): choosing_action = State() answer_question = State() class lk(StatesGroup): personal_account = State() edit_answer = State() new_answer = State() edit_answer_select = State() edit_answer_cb = State() new_answer_cb = State() class admin(StatesGroup): admin_panel = State() select_question_to_delete = State() select_question_to_edit = State() edit_question_text = State() new_question = State() async def create_db(): async with aiosqlite.connect('base.db') as db: await db.execute('''CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, username TEXT NOT NULL, last_question_idx INTEGER DEFAULT 0)''') await db.execute('''CREATE TABLE IF NOT EXISTS questions ( id INTEGER PRIMARY KEY AUTOINCREMENT, question TEXT NOT NULL, order_num INTEGER NOT NULL)''') await db.execute('''CREATE TABLE IF NOT EXISTS answers ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, question TEXT, answer TEXT, FOREIGN KEY (user_id) REFERENCES users (id))''') await db.execute('''CREATE TABLE IF NOT EXISTS public_info ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, name TEXT, surname TEXT, patronym TEXT, birthdayat TEXT, diedat TEXT, epitaph TEXT, placeOfBirth TEXT, placeOfDeath TEXT, children TEXT, wifehusband TEXT, education TEXT, occupation TEXT, awards TEXT, title1 TEXT, biography1 TEXT, title2 TEXT, biography2 TEXT, title3 TEXT, biography3 TEXT, conclusion TEXT, FOREIGN KEY (user_id) REFERENCES users (id))''') await db.commit() # Обработка под MarkdownV2 def mdv2(text: str) -> str: escape_chars = [ "_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!" ] for char in escape_chars: text = text.replace(char, f"\{char}") text = text.replace("**", "*").replace('"', '“') return text # калбэки change_action_cb = CallbackData('change', 'action') # КНОПКА МЕНЮ menu = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) menu.add(KeyboardButton("В меню")) async def add_user(user_id: int, username: str): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT id FROM users WHERE id = ?', (user_id,)) user_exists = await cursor.fetchone() if user_exists: await db.execute('UPDATE users SET username = ? WHERE id = ?', (username, user_id)) else: await db.execute('INSERT INTO users (id, username) VALUES (?, ?)', (user_id, username)) await db.commit() @dp.message_handler(commands="start", state="*") async def cmd_start(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) user_id = message.from_user.id username = message.from_user.username or "unknown" await add_user(user_id, username) if user_id not in ADMINS: await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() @dp.message_handler(lambda message: message.text == "В меню", state="*") async def back_to_menu(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) if message.from_user.id not in ADMINS: await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() async def save_answer(user_id: int, question: str, answer: str, question_idx: int): async with aiosqlite.connect('base.db') as db: await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question, answer)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (question_idx, user_id)) await db.commit() async def set_next_question(user_id: int): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() last_question_idx = result[0] if result else 0 next_question_idx = last_question_idx + 1 question_cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (next_question_idx,)) question_text = await question_cursor.fetchone() if question_text: await bot.send_message(user_id, question_text[0], reply_markup=menu) await Form.answer_question.set() await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (next_question_idx, user_id)) await db.commit() else: answers_text = "" cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question} - {answer}\n" markup = InlineKeyboardMarkup( inline_keyboard=[ [InlineKeyboardButton(text="Сгенерировать", callback_data=change_action_cb.new(action="generate"))], [InlineKeyboardButton(text="Изменить ответ", callback_data=change_action_cb.new(action="change"))], [InlineKeyboardButton(text="Заполнить заново", callback_data=change_action_cb.new(action="refill"))], ] ) await bot.send_message(user_id, f"Вот ваши ответы:\n\n{answers_text}", reply_markup=markup) await dp.current_state(user=user_id).reset_state(with_data=False) @dp.callback_query_handler(change_action_cb.filter(action="change"), state="*") async def change_answer(callback_query: types.CallbackQuery, state: FSMContext): await bot.answer_callback_query(callback_query.id) await lk.edit_answer.set() await bot.send_message(callback_query.from_user.id, "Введите номер вопроса, который хотите изменить:") @dp.message_handler(state=lk.edit_answer_cb) async def enter_question_number(message: types.Message, state: FSMContext): question_number = message.text if not question_number.isdigit(): await message.reply("Пожалуйста, введите номер вопроса цифрами. Попробуйте снова:") return await state.update_data(question_number=int(question_number)) await lk.new_answer.set() await message.answer("Введите новый ответ:") @dp.callback_query_handler(change_action_cb.filter(action="refill"), state="*") async def process_refill(callback_query: types.CallbackQuery, callback_data: dict): user_id = callback_query.from_user.id await bot.answer_callback_query(callback_query.id) markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да, начать заново", callback_data="confirm_refill")) await bot.send_message(user_id, "Вы уверены, что хотите начать заново? Ваши текущие ответы будут удалены.", reply_markup=markup) @dp.message_handler(state=lk.new_answer_cb) async def update_answer(message: types.Message, state: FSMContext): new_answer_text = message.text user_data = await state.get_data() question_number = user_data['question_number'] user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer_text, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer_text}", reply_markup=menu) else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Сгенерировать био", state=Form.choosing_action) async def generate_bio(message: types.Message): user_id = message.from_user.id await set_next_question(user_id) @dp.message_handler(state=Form.answer_question) async def process_question_answer(message: types.Message, state: FSMContext): user_id = message.from_user.id answer_text = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() current_question_idx = result[0] if result else 0 cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (current_question_idx,)) question = await cursor.fetchone() if question: question_text = question[0] await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question_text, answer_text)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (current_question_idx, user_id)) await db.commit() else: await message.answer("Произошла ошибка при сохранении вашего ответа.") await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Личный кабинет", state=Form.choosing_action) async def personal_account(message: types.Message): user_id = message.from_user.id answers_text = "Личный кабинет\n\nВаши ответы:\n" async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question, answer FROM answers WHERE user_id=? ORDER BY id', (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question}: {answer}\n" if answers_text == "Личный кабинет\n\nВаши ответы:\n": answers_text = "Личный кабинет\n\nВы еще не отвечали на вопросы. Пожалуйста, нажмите «В меню» и выберите «Сгенерировать био», чтобы ответить на вопросы" await message.answer(answers_text, reply_markup=menu) else: markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) await message.answer(answers_text, reply_markup=markup) await lk.personal_account.set() @dp.message_handler(lambda message: message.text == "Изменить ответ", state=lk.personal_account) async def change_answer(message: types.Message): await message.answer("Введите номер вопроса, на который хотите изменить ответ:",reply_markup=menu) await lk.edit_answer.set() @dp.message_handler(state=lk.edit_answer) async def process_question_number(message: types.Message, state: FSMContext): text = message.text question_number = int(text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await state.update_data(question=question_text[0], question_number=question_number) await message.answer("Введите новый ответ:") await lk.new_answer.set() else: await message.answer(f"Вопроса под номером {question_number} не существует.") @dp.message_handler(state=lk.new_answer) async def process_new_answer(message: types.Message, state: FSMContext): user_data = await state.get_data() question_number = user_data['question_number'] new_answer = message.text markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer}", reply_markup=markup) else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() await personal_account(message) @dp.message_handler(lambda message: message.text == "Заполнить заново", state=lk.personal_account) async def refill_form(message: types.Message): markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да", callback_data="confirm_refill")) await message.answer("Вы уверены, что хотите начать заново? Все текущие ответы будут удалены.", reply_markup=markup) @dp.callback_query_handler(lambda c: c.data == 'confirm_refill', state="*") async def process_refill(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with aiosqlite.connect('base.db') as db: await db.execute('DELETE FROM answers WHERE user_id=?', (user_id,)) await db.commit() await db.execute('UPDATE users SET last_question_idx = 0 WHERE id = ?', (user_id,)) await db.commit() state = dp.current_state(user=user_id) await state.reset_state(with_data=False) await bot.answer_callback_query(callback_query.id) await bot.send_message(user_id, "Ваши ответы удалены.") await cmd_start(callback_query.message) # ГЕНЕРАЦИЯ def parse_yandexgpt(answer_text: str) -> dict: pattern = re.compile(r'(\b(?:name|surname|patronym|birthdayat|diedat|epitaph|placeOfBirth|placeOfDeath|children|wifehusband|education|occupation|awards|title[123]|biography[123]|conclusion)\b): (.?)(?=\s+\b\w+\b: |\s$)',re.DOTALL) matches = pattern.findall(answer_text) data = {key.strip(): value.strip() for key, value in matches} return data async def save_result(user_id: int, answer_dict: dict): async with aiosqlite.connect('base.db') as db: columns = ", ".join(answer_dict.keys()) placeholders = ", ".join(["?"] * len(answer_dict)) values = list(answer_dict.values()) await db.execute(f"INSERT INTO public_info (user_id, {columns}) VALUES (?, {placeholders})", [user_id, *values]) await db.commit() class YandexGPT: @staticmethod async def generate(prompt: str, apikey: str, sa_id: str, user_id : str): url = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion' headers = { 'Content-Type': 'application/json', 'Authorization': f'Api-Key {apikey}' } data = { "modelUri": f"gpt://{sa_id}/yandexgpt-lite/latest", "completionOptions": { "stream": False, "temperature": 0.4, "maxTokens": "3000" }, "messages": [ { "role": "system", "text": """"Твоя задача - создать информационную сводку и биографию (title1, biography1, title2, biography2, title3, biography3 ) в соответствии с ответами на вопросы пользователя (пишутся в формате вопрос - ответ). Не пиши ничего кроме этой сводки и НЕ ОТХОДИ ОТ ШАБЛОНА. Если информации данных в каком-то пункте нет, пиши ТОЛЬКО “null“, а не что-либо другое. Создай следующую сводку: name = {} surname = {} patronym = {} birthday_at = {} died_at = {} epitaph = {} # не больше 300 символов placeOfBirth = {} placeOfDeath = {} children = {} wifehusband = {} # Это супруг или супруга education = {} occupation = {} # Род деятельности человека awards = {} title1 = {} biography1 = {} title2 = {} biography2 = {} title3 = {} biography3 = {} conclusion = {} В поле name должно быть ТОЛЬКО имя, без фамилии и отчества. Не путай имя (name), фамилию (surname) и отчество (patronym) - они должны стоять на правильных местах. epitaph придумай сам, чтобы она соответствовала жизненному пути человека. Не придумывай в биографии ничего от себя, распиши подробнее, но только ту информацию, которая есть от пользователя. Все даты пиши в формате dd.mm.yyyy. В conclusion пиши заключение БИОГРАФИИ, а не что либо другое. """ }, { "role": "user", "text": prompt } ] } async with aiohttp.ClientSession() as session: async with session.post(url, json=data, headers=headers) as response: response_data = await response.json() try: answer = response_data['result']['alternatives'][0]['message']['text'] answer = answer.replace("*","").replace("_","") await bot.send_message(user_id, mdv2(answer), parse_mode="MarkdownV2") await save_result(user_id, parse_yandexgpt(answer)) except KeyError as e: await bot.send_message(user_id, "Не удалось получить ответ от сервера. Проверьте переданные данные и попробуйте еще раз.") @dp.callback_query_handler(change_action_cb.filter(action="generate"), state="*") async def process_generate(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id prompt = "" async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question, answer FROM answers WHERE user_id=?", (user_id,)) answers = await cursor.fetchall() for question, answer in answers: prompt += f"\n{question} - {answer}" api_key = "AQVN1J4sCxYR98rj-tVppyp6gXQthbdmYvmgtO7a" sa_id = "b1g5og37bgh1ghh2s2qc" await YandexGPT.generate(prompt, api_key, sa_id, user_id) # АДМИН-ПАНЕЛЬ # КНОПКА НАЗАД back = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False) back.add(KeyboardButton("Назад")) # КЛАВА admin_kb = ReplyKeyboardMarkup(resize_keyboard=True) admin_kb.add("Вопросы", "Добавить", "Удалить", "Редактировать","В меню") @dp.message_handler(lambda message: message.text == "Назад", state=[admin.new_question, admin.edit_question_text, admin.select_question_to_edit, admin.select_question_to_delete]) async def back_to_admin_panel(message: types.Message, state: FSMContext): await state.finish() await admin_panel(message) @dp.message_handler(lambda message: message.text == "Админ-панель", state=Form.choosing_action) async def admin_panel(message: types.Message): if message.from_user.id not in ADMINS: await message.answer("Доступ запрещен.") return await message.answer("Админ-панель:", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Вопросы", state=admin.admin_panel) async def show_questions(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if questions: text = "\n".join([f"{idx + 1}. {question[0]}" for idx, question in enumerate(questions)]) else: text = "Вопросы отсутствуют." await message.answer(text) @dp.message_handler(lambda message: message.text == "Добавить", state=admin.admin_panel) async def add_question_start(message: types.Message): await message.answer("Введите текст нового вопроса:", reply_markup=back) await admin.new_question.set() @dp.message_handler(state=admin.new_question) async def add_question_process(message: types.Message, state: FSMContext): new_question = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT MAX(order_num) FROM questions") max_order_num = await cursor.fetchone() next_order_num = (max_order_num[0] or 0) + 1 await db.execute("INSERT INTO questions (question, order_num) VALUES (?, ?)", (new_question, next_order_num)) await db.commit() await message.answer("Вопрос успешно добавлен.", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Редактировать", state=admin.admin_panel) async def select_question_to_edit_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для редактирования:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_edit.set() @dp.message_handler(state=admin.select_question_to_edit) async def edit_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with state.proxy() as data: data['question_id'] = qid await admin.edit_question_text.set() await message.answer("Введите новый текст вопроса:", reply_markup=back) @dp.message_handler(state=admin.edit_question_text) async def update_question(message: types.Message, state: FSMContext): new_text = message.text async with state.proxy() as data: qid = data['question_id'] async with aiosqlite.connect('base.db') as db: await db.execute("UPDATE questions SET question = ? WHERE id = ?", (new_text, qid)) await db.commit() await message.answer("Вопрос успешно отредактирован.", reply_markup=admin_kb) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Удалить", state=admin.admin_panel) async def select_question_to_delete_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для удаления:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_delete.set() @dp.message_handler(state=admin.select_question_to_delete) async def delete_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT order_num FROM questions WHERE id = ?", (qid,)) question = await cursor.fetchone() if not question: await message.answer(f"Вопрос под номером {qid} не найден. Пожалуйста, попробуйте другой номер.") return order_num_to_delete = question[0] await db.execute("DELETE FROM questions WHERE id = ?", (qid,)) await db.execute("UPDATE questions SET order_num = order_num - 1 WHERE order_num > ?", (order_num_to_delete,)) await db.commit() await message.answer("Вопрос успешно удален.", reply_markup=admin_kb) await admin.admin_panel.set() async def main(): await create_db() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) executor.start_polling(dp, skip_updates=True)
4482f4c1c9562822525e749e87da5bf9
{ "intermediate": 0.26902905106544495, "beginner": 0.4760163426399231, "expert": 0.25495457649230957 }