row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
40,558
What would be the easyest and prefered way to parse customer mails and automaticly create an offer based on a product table with product numbers and descriptions.
b66138a429e13aa8b2d90f49a6398e2e
{ "intermediate": 0.3716697096824646, "beginner": 0.11418884247541428, "expert": 0.5141414999961853 }
40,559
Can you please help me to handle exceptions in this snippet of C++? I would like to collect error like permission denied as a new entry in the vector differences. ~~~ std::vector<FileDiff> compare_directories(const fs::path &dir1, const fs::path &dir2) { std::queue<std::pair<fs::path, fs::path>> dirs_queue; dirs_queue.push({dir1, dir2}); std::vector<FileDiff> differences; while (!dirs_queue.empty()) { auto [current_dir1, current_dir2] = dirs_queue.front(); dirs_queue.pop(); std::set<std::string> entries1, entries2; for (const auto &entry : fs::directory_iterator(current_dir1)) { if (!fs::is_directory(entry)) entries1.insert(entry.path().filename()); } for (const auto &entry : fs::directory_iterator(current_dir2)) { if (!fs::is_directory(entry)) entries2.insert(entry.path().filename()); } for (const auto &entry : entries1) { if (entries2.find(entry) == entries2.end()) { differences.push_back({(current_dir1 / entry).string(), fs::path(), "", ""}); } else { auto file1_path = current_dir1 / entry; auto file2_path = current_dir2 / entry; if (fs::file_size(file1_path) != fs::file_size(file2_path)) { differences.push_back({file1_path, file2_path, "Size differs", ""}); } else { auto hash1 = hash_file(file1_path); auto hash2 = hash_file(file2_path); if (hash1 != hash2) { differences.push_back({file1_path, file2_path, hash1, hash2}); } } } } for (const auto &entry : entries2) { if (entries1.find(entry) == entries1.end()) { differences.push_back({fs::path(), (current_dir2 / entry).string(), "Folder not found in path1", ""}); } } for (const auto &entry : fs::directory_iterator(current_dir1)) { if (fs::is_directory(entry)) { auto other_entry = current_dir2 / entry.path().filename(); if (fs::exists(other_entry)) { dirs_queue.push({entry.path(), other_entry}); } else { differences.push_back({entry, other_entry, "", "Folder not found in path2"}); } } } // this looks at the second folder if there are subfolders missing in the first folder for (const auto &entry : fs::directory_iterator(current_dir2)) { if (fs::is_directory(entry)) { auto other_entry = current_dir1 / entry.path().filename(); if (!fs::exists(other_entry)) { differences.push_back({entry, other_entry, "", ""}); } } } } return differences; }
669fc16d714bd8de43175e3ddda15177
{ "intermediate": 0.3699547350406647, "beginner": 0.4716866612434387, "expert": 0.15835855901241302 }
40,560
How do I print the state of the toggled switch @IBAction func switchToggled(_ sender: Any) { print("toggled lol " + (sender.description)); }
f21d0693ce34bd768db78f1e1dd5b9e0
{ "intermediate": 0.6338320374488831, "beginner": 0.28198692202568054, "expert": 0.08418108522891998 }
40,561
generate webpage html, css, js, bootstrap with the attached image
1a708ee2a821f2be329535446af6240d
{ "intermediate": 0.3352429270744324, "beginner": 0.2752044200897217, "expert": 0.38955265283584595 }
40,562
CREAR NOTAS <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" // android:layout_height="match_parent" // android:orientation="vertical" // tools:context=".MainActivity" // android:gravity="top" // android:background="#FFFFFF" // > <LinearLayout android:layout_width="match_parent" // android:layout_height="50dp" // android:orientation="horizontal" // android:paddingStart="10dp" // android:paddingEnd="10dp" // android:background="#000000"> // <TextView android:id="@+id/textView" // android:layout_width="wrap_content" // android:layout_height="wrap_content" // android:textColor="#FFFFFF" // android:layout_gravity="center" // android:textSize="20sp" // android:textStyle="bold" // android:text="CREAR NOTA"/> // </LinearLayout> <LinearLayout android:layout_width="match_parent" // android:layout_height="wrap_content" // android:orientation="vertical" // android:paddingTop="20dp" // android:paddingLeft="20dp" // android:paddingRight="20dp"> // <TextView android:id="@+id/textView3" // android:layout_width="wrap_content" // android:layout_height="wrap_content" // android:text="Título" // android:textStyle="bold"/> // <EditText android:id="@+id/inputTitulo" // android:layout_width="match_parent" // android:layout_height="wrap_content" // android:layout_marginBottom="20dp" // android:inputType="textEmailAddress" /> // <TextView android:id="@+id/textView4" // android:layout_width="wrap_content" // android:layout_height="wrap_content" // android:text="Descripción" // android:textStyle="bold"/> // <EditText android:id="@+id/editTextTextMultiLine" // android:layout_width="match_parent" // android:layout_height="125dp" // android:layout_marginBottom="20dp" // android:gravity="start|top" // android:inputType="textMultiLine" /> // <ImageView android:id="@+id/imageView1" // android:layout_width="match_parent" // android:layout_height="280dp" // android:layout_gravity="center" // android:layout_marginBottom="20dp" android:src="@tools:sample/avatars" // app:srcCompat="@color/material_dynamic_neutral70" /> // <LinearLayout android:layout_width="match_parent" // android:layout_height="wrap_content" // android:orientation="horizontal" // > <Button android:id="@+id/btnRegistrar" // android:layout_width="wrap_content" // android:layout_height="wrap_content" // android:layout_weight="1" // android:backgroundTint="#000000" // android:layout_marginEnd="10dp" // android:text="Registrar"/> // <Button android:id="@+id/btnImagen" // android:layout_width="wrap_content" // android:layout_height="wrap_content" // android:layout_weight="1" // android:backgroundTint="#000000" // android:layout_marginStart="10dp" // android:text="Añadir Imagen" /> // </LinearLayout> </LinearLayout> </LinearLayout> - explica linea por linea el codigo que es de android studio
21fb38bc3c3eabc6cbcc04130044c941
{ "intermediate": 0.38495776057243347, "beginner": 0.4508223235607147, "expert": 0.16421997547149658 }
40,563
The net chargeable income is salaries minus allowances and deductions. For simplicity, assume the only deductible is the mandatory contribution to MPF, and the only allowance is the single/married person allowance.1 A single person will receive an allowance of HKD 132,000, and a married person will receive HKD 264,000. Write a Python program to calculate the income tax. 1) Ask the user to enter the salary, marriage status, and mandatory contributions to MPF. 2) Display the tax due. Round it to the nearest dollar amount. If the net chargeable income is negative, display 0 for the tax due. The program should be capable of the following. Each screenshot corresponds to running the program once. Follow the same submission requirement (.py file and screenshot) as before.
93bec7018b4953dec816686d5a3353ba
{ "intermediate": 0.41575098037719727, "beginner": 0.23039522767066956, "expert": 0.3538537323474884 }
40,564
in cisco nexus dashboard, how to see the VLAN ID configured during cluster bringup? where is that information stored
5521081dd5527d1d3a950d54d5070742
{ "intermediate": 0.38150978088378906, "beginner": 0.34656453132629395, "expert": 0.2719257175922394 }
40,565
-- inventory.lua -- Предметы инвентаря по классам и действия, которые можно с ними выполнить inventoryItems = { ["Weapons"] = { ["Primary Weapon"] = { {"М4А1 CCO",3}, {"CZ550",3}, {"Винчестер 1866",3}, {"SPAZ-12 Combat Shotgun",3}, {"Sawn-Off Shotgun",3}, {"AK-74",3}, {"Lee Enfield",3}, --{"Heat-Seeking RPG",5}, --{"M136 Rocket Launcher",5}, }, ["Secondary Weapon"] = { {"M1911",2}, {"M9 SD",2}, {"PDW",2}, --{"TEC-9",2}, {"MP5A5",3}, {"Револьвер",2}, {"Охотничий нож",1}, {"Топор",2}, {"Бейсбольная бита",2}, {"Лопата",2}, {"Клюшка для гольфа",2}, }, ["Specially Weapon"] = { {"Парашют",1}, {"Tear Gas",1}, {"Оск. граната M67",1}, {"Бинокль",1} }, }, ["Ammo"] = { {"M1911 Mag",0.085}, {"M9 SD Mag",0.085}, {".45ACP",0.085}, {"PDW Mag",0.025}, {"MP5A5 Mag",0.025}, {"AK",0.035}, {"STANAG",0.035}, {"1866 Slug",0.067}, {"2Rnd. Slug",0.067}, {"SPAZ-12 Pellet",0.067}, {"CZ550 Mag",0.1}, {"Lee Enfield Mag",0.1}, --{"M136 Rocket",2}, }, ["Food"] = { {"Фляга",1}, {"Банка макарон",1}, {"Банка бобов",1}, {"Гамбургер",1}, {"Пицца",1}, {"Банка соды",1}, {"Молоко",1}, {"Сырое мясо",1}, }, ["Items"] = { {"Дрова",2}, {"Бинт",1,"Перевязаться"}, {"Фаер",1,"Зажечь"}, {"Пустая канистра",2}, {"Наполненная канистра",2}, {"Аптечка",2,"Исп."}, {"Грелка",1,"Исп."}, {"Болеутоляющие",1,"Исп."}, {"Морфий",1,"Исп."}, {"Пакет крови",1,"Исп."}, {"Колючая проволока",1,"Поставить проволоку"}, {"Жареное мясо",1}, {"Колесо",2}, {"Двигатель",5}, {"Бензобак",3}, {"Палатка",3,"Разложить"}, {"Армейский камуфляж",1,"Переодется"}, {"Женский скин",1,"Переодется"}, {"Одежда выжившего",1,"Переодется"}, {"Камуфляж снайпера",1,"Переодется"}, {"Пустая фляга",1,"Наполнить"}, {"Пустая банка соды",1}, {"Объедки",1}, {"Assault Pack (ACU)",1}, {"Alice Pack",1}, {"Czech Backpack",1}, {"Coyote Backpack",1}, }, ["Toolbelt"] = { {"Очки ночного видения",1}, {"Инфокрасные очки",1}, {"Карта",1}, {"Спички",1,"Поджечь"}, {"Часы",1}, {"GPS",1}, {"Инструменты",1}, {"Рация",1}, }, } -- Код инвентаря local headline = {} local gridlistItems = {} local buttonItems = {} inventoryWindows = guiCreateWindow(0.15, 0.28, 0.72, 0.63, "", true) -- inventoryWindows = guiCreateStaticImage(0.25,0.25,0.5,0.5,"images/scrollmenu_1.png",true) headline["loot"] = guiCreateLabel(0.06, 0.05, 0.34, 0.09,"Обыскать",true,inventoryWindows) guiLabelSetHorizontalAlign (headline["loot"],"center") guiSetFont (headline["loot"], "default-bold-small" ) headline["inventory"] = guiCreateLabel(0.60, 0.05, 0.34, 0.09,"Инвентарь",true,inventoryWindows) guiLabelSetHorizontalAlign (headline["inventory"],"center") guiSetFont (headline["inventory"], "default-bold-small" ) gridlistItems["loot"] = guiCreateGridList (0.03, 0.10, 0.39, 0.83,true,inventoryWindows) gridlistItems["loot_colum"] = guiGridListAddColumn( gridlistItems["loot"], "Inventory", 0.7 ) gridlistItems["loot_colum_amount"] = guiGridListAddColumn( gridlistItems["loot"], "", 0.2 ) gridlistItems["inventory"] = guiCreateGridList (0.57, 0.11, 0.39, 0.83,true,inventoryWindows) gridlistItems["inventory_colum"] = guiGridListAddColumn( gridlistItems["inventory"], "Inventory", 0.7 ) gridlistItems["inventory_colum_amount"] = guiGridListAddColumn( gridlistItems["inventory"], "", 0.2 ) buttonItems["loot"] = guiCreateButton(0.42, 0.17, 0.04, 0.69, "->", true,inventoryWindows) buttonItems["inventory"] = guiCreateButton(0.53, 0.17, 0.04, 0.69, "<-", true,inventoryWindows) headline["slots"] = guiCreateLabel(0.62, 0.94, 0.29, 0.04,"Слоты:",true,inventoryWindows) guiLabelSetHorizontalAlign (headline["slots"],"center") guiLabelSetVerticalAlign (headline["slots"],"center") guiSetFont (headline["slots"], "default-bold-small" ) headline["slots_loot"] = guiCreateLabel(0.07, 0.94, 0.29, 0.04,"Слоты:",true,inventoryWindows) guiLabelSetHorizontalAlign (headline["slots_loot"],"center") guiLabelSetVerticalAlign (headline["slots_loot"],"center") guiSetFont (headline["slots_loot"], "default-bold-small" ) guiSetVisible(inventoryWindows,false) function showInventory (key,keyState) if getElementData(getLocalPlayer(),"logedin") then if ( keyState == "down" ) then guiSetVisible(inventoryWindows,not guiGetVisible(inventoryWindows)) showCursor(not isCursorShowing()) refreshInventory() if guiGetVisible(inventoryWindows) == true then onClientOpenInventoryStopMenu () else hideRightClickInventoryMenu () end if isPlayerInLoot() then local col = getElementData(getLocalPlayer(),"currentCol") local gearName = getElementData(getLocalPlayer(),"lootname") refreshLoot(col,gearName) end end end end bindKey ( "j", "down", showInventory ) function showInventoryManual () guiSetVisible(inventoryWindows,not guiGetVisible(inventoryWindows)) showCursor(not isCursorShowing()) refreshInventory() if guiGetVisible(inventoryWindows) == true then onClientOpenInventoryStopMenu () end end function hideInventoryManual () guiSetVisible(inventoryWindows,false) showCursor(false) hideRightClickInventoryMenu () end addEvent("hideInventoryManual",true) addEventHandler("hideInventoryManual",getLocalPlayer(),hideInventoryManual) function refreshInventoryManual () refreshInventory() end addEvent("refreshInventoryManual",true) addEventHandler("refreshInventoryManual",getLocalPlayer(),refreshInventoryManual) function refreshLootManual (loot) refreshLoot(loot) end addEvent("refreshLootManual",true) addEventHandler("refreshLootManual",getLocalPlayer(),refreshLootManual) function refreshInventory() if ( gridlistItems["inventory_colum"] ) then --If the column has been created, fill it with players row1,column1 = guiGridListGetSelectedItem ( gridlistItems["inventory"] ) guiGridListClear(gridlistItems["inventory"]) local row = guiGridListAddRow ( gridlistItems["inventory"] ) --guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],"ITEMS", false, false ) local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],"Основное оружие", true, false ) for id, item in ipairs(inventoryItems["Weapons"]["Primary Weapon"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum_amount"],getElementData(getLocalPlayer(),item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],"Дополнительное оружие", true, false ) for id, item in ipairs(inventoryItems["Weapons"]["Secondary Weapon"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum_amount"],getElementData(getLocalPlayer(),item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],"Специальное оружие", true, false ) for id, item in ipairs(inventoryItems["Weapons"]["Specially Weapon"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum_amount"],getElementData(getLocalPlayer(),item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],"Боеприпасы", true, false ) for id, item in ipairs(inventoryItems["Ammo"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum_amount"],getElementData(getLocalPlayer(),item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],"Еда и вода", true, false ) for id, item in ipairs(inventoryItems["Food"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum_amount"],getElementData(getLocalPlayer(),item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],"Прочее", true, false ) for id, item in ipairs(inventoryItems["Items"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum_amount"],getElementData(getLocalPlayer(),item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],"Инструменты", true, false ) for id, item in ipairs(inventoryItems["Toolbelt"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["inventory"] ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["inventory"], row, gridlistItems["inventory_colum_amount"],getElementData(getLocalPlayer(),item[1]), false, false ) end end if row1 and column1 then guiGridListSetSelectedItem ( gridlistItems["inventory"], row1,column1) end guiSetText(headline["slots"],"Слоты: "..getPlayerCurrentSlots().."/"..getPlayerMaxAviableSlots()) end end function refreshLoot(loot,gearName) if loot == false then guiGridListClear(gridlistItems["loot"]) guiSetText(headline["loot"],"Пусто") return end if ( gridlistItems["loot_colum"] ) then row2,column2 = guiGridListGetSelectedItem ( gridlistItems["inventory"] ) guiGridListClear(gridlistItems["loot"]) if gearName then guiSetText(headline["loot"],gearName) end local row = guiGridListAddRow ( gridlistItems["loot"] ) --guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],"Weapons", true, false ) local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],"Основное оружие", true, false ) for id, item in ipairs(inventoryItems["Weapons"]["Primary Weapon"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum_amount"],getElementData(loot,item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],"Дополнительное оружие", true, false ) for id, item in ipairs(inventoryItems["Weapons"]["Secondary Weapon"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum_amount"],getElementData(loot,item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],"Специальное оружие", true, false ) for id, item in ipairs(inventoryItems["Weapons"]["Specially Weapon"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum_amount"],getElementData(loot,item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],"Боеприпасы", true, false ) for id, item in ipairs(inventoryItems["Ammo"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum_amount"],getElementData(loot,item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],"Еда и вода", true, false ) for id, item in ipairs(inventoryItems["Food"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum_amount"],getElementData(loot,item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],"Прочее", true, false ) for id, item in ipairs(inventoryItems["Items"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum_amount"],getElementData(loot,item[1]), false, false ) end end local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],"Инструменты", true, false ) for id, item in ipairs(inventoryItems["Toolbelt"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then local row = guiGridListAddRow ( gridlistItems["loot"] ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum"],item[1], false, false ) guiGridListSetItemText ( gridlistItems["loot"], row, gridlistItems["loot_colum_amount"],getElementData(loot,item[1]), false, false ) end end if row2 and column2 then --guiGridListSetSelectedItem ( gridlistItems["loot"], row2,column2) end guiSetText(headline["slots_loot"],"Слоты: "..getLootCurrentSlots(loot).."/"..(getLootMaxAviableSlots(loot)or 0)) end end function getPlayerMaxAviableSlots() return getElementData(getLocalPlayer(),"MAX_Slots") end function getLootMaxAviableSlots(loot) return getElementData(loot,"MAX_Slots") end function getPlayerCurrentSlots() local current_SLOTS = 0 for id, item in ipairs(inventoryItems["Weapons"]["Primary Weapon"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(getLocalPlayer(),item[1]) end end for id, item in ipairs(inventoryItems["Weapons"]["Secondary Weapon"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(getLocalPlayer(),item[1]) end end for id, item in ipairs(inventoryItems["Weapons"]["Specially Weapon"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(getLocalPlayer(),item[1]) end end for id, item in ipairs(inventoryItems["Ammo"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(getLocalPlayer(),item[1]) end end for id, item in ipairs(inventoryItems["Food"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(getLocalPlayer(),item[1]) end end for id, item in ipairs(inventoryItems["Items"]) do if getElementData(getLocalPlayer(),item[1]) and getElementData(getLocalPlayer(),item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(getLocalPlayer(),item[1]) end end return math.floor(current_SLOTS) end function getLootCurrentSlots(loot) local current_SLOTS = 0 for id, item in ipairs(inventoryItems["Weapons"]["Primary Weapon"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(loot,item[1]) end end for id, item in ipairs(inventoryItems["Weapons"]["Secondary Weapon"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(loot,item[1]) end end for id, item in ipairs(inventoryItems["Weapons"]["Specially Weapon"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(loot,item[1]) end end for id, item in ipairs(inventoryItems["Ammo"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(loot,item[1]) end end for id, item in ipairs(inventoryItems["Food"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(loot,item[1]) end end for id, item in ipairs(inventoryItems["Items"]) do if getElementData(loot,item[1]) and getElementData(loot,item[1]) >= 1 then current_SLOTS = current_SLOTS + item[2]*getElementData(loot,item[1]) end end return math.floor(current_SLOTS) end function getItemSlots(itema) local current_SLOTS = 0 for id, item in ipairs(inventoryItems["Weapons"]["Primary Weapon"]) do if itema == item[1] then return item[2] end end for id, item in ipairs(inventoryItems["Weapons"]["Secondary Weapon"]) do if itema == item[1] then return item[2] end end for id, item in ipairs(inventoryItems["Weapons"]["Specially Weapon"]) do if itema == item[1] then return item[2] end end for id, item in ipairs(inventoryItems["Ammo"]) do if itema == item[1] then return item[2] end end for id, item in ipairs(inventoryItems["Food"]) do if itema == item[1] then return item[2] end end for id, item in ipairs(inventoryItems["Items"]) do if itema == item[1] then return item[2] end end return false end function isToolbeltItem(itema) local current_SLOTS = 0 for id, item in ipairs(inventoryItems["Toolbelt"]) do if itema == item[1] then return true end end return false end vehicleAddonsInfo = { -- {Model ID, Колеса, Двигатель, Бензобак} {422,4,1,1}, {470,4,1,1}, {468,2,1,1}, {433,6,1,1}, {437,6,1,1}, {509,0,0,0}, {487,0,1,1}, {497,0,1,1}, {453,0,1,1}, } function getVehicleAddonInfos (id) for i,veh in ipairs(vehicleAddonsInfo) do if veh[1] == id then return veh[2],veh[3], veh[4] end end end --OTHER ITEM STUFF vehicleFuelTable = { -- {Model ID, Max Бензин} {411,80}, {500,80}, {471,30}, {422,80}, {470,100}, {468,30}, {433,140}, {437,140}, {509,0}, {487,60}, {497,60}, {453,60}, } function getVehicleMaxFuel(loot) local modelID = getElementModel(getElementData(loot,"parent")) for i,vehicle in ipairs(vehicleFuelTable) do if modelID == vehicle[1] then return vehicle[2] end end return false end function onPlayerMoveItemOutOfInventory () if playerMovedInInventory then startRollMessage2("Inventory", "Не торопись!", 255, 22, 0 ) return end -- [ID:0000005 - Several grammar + spelling mistakes and typos] //L local itemName = guiGridListGetItemText ( gridlistItems["inventory"], guiGridListGetSelectedItem ( gridlistItems["inventory"] ), 1 ) if getElementData(getLocalPlayer(),itemName) and getElementData(getLocalPlayer(),itemName) >= 1 then if isPlayerInLoot() then local isVehicle = getElementData(isPlayerInLoot(),"vehicle") local isTent = getElementData(isPlayerInLoot(),"tent") if isVehicle and not isTent then local veh = getElementData(isPlayerInLoot(),"parent") local tires,engine,parts = getVehicleAddonInfos (getElementModel(veh)) if itemName == "Колесо" and (getElementData(isPlayerInLoot(),"Колесо_inVehicle") or 0) < tires or itemName == "Двигатель" and (getElementData(isPlayerInLoot(),"Двигатель_inVehicle") or 0) < engine or itemName == "Бензобак" and (getElementData(isPlayerInLoot(),"Parts_inVehicle") or 0) < parts then if itemName == "Бензобак" then itemName = "Parts" end triggerEvent("onPlayerMoveItemOutOFInventory",getLocalPlayer(),itemName.."_inVehicle",isPlayerInLoot()) playerMovedInInventory = true setTimer(function() playerMovedInInventory = false end,700,1) elseif isToolbeltItem(itemName) then triggerEvent("onPlayerMoveItemOutOFInventory",getLocalPlayer(),itemName,isPlayerInLoot()) playerMovedInInventory = true setTimer(function() playerMovedInInventory = false end,700,1) elseif getLootCurrentSlots(getElementData(getLocalPlayer(),"currentCol")) + getItemSlots(itemName) <= getLootMaxAviableSlots(isPlayerInLoot()) then triggerEvent("onPlayerMoveItemOutOFInventory",getLocalPlayer(),itemName,isPlayerInLoot()) playerMovedInInventory = true setTimer(function() playerMovedInInventory = false end,700,1) else startRollMessage2("Inventory", "Инвентарь полон!", 255, 22, 0 ) return end elseif isToolbeltItem(itemName) then triggerEvent("onPlayerMoveItemOutOFInventory",getLocalPlayer(),itemName,isPlayerInLoot()) playerMovedInInventory = true setTimer(function() playerMovedInInventory = false end,700,1) elseif getLootCurrentSlots(getElementData(getLocalPlayer(),"currentCol")) + getItemSlots(itemName) <= getLootMaxAviableSlots(isPlayerInLoot()) then triggerEvent("onPlayerMoveItemOutOFInventory",getLocalPlayer(),itemName,isPlayerInLoot()) playerMovedInInventory = true setTimer(function() playerMovedInInventory = false end,700,1) else startRollMessage2("Inventory", "Инвентарь полон!", 255, 22, 0 ) return end else triggerEvent("onPlayerMoveItemOutOFInventory",getLocalPlayer(),itemName,isPlayerInLoot()) playerMovedInInventory = true setTimer(function() playerMovedInInventory = false end,700,1) end end local gearName = guiGetText(headline["loot"]) local col = getElementData(getLocalPlayer(),"currentCol") setTimer(refreshInventory,200,2) if isPlayerInLoot() then setTimer(refreshLoot,200,2,col,gearName) end end addEventHandler ( "onClientGUIClick", buttonItems["inventory"], onPlayerMoveItemOutOfInventory ) function onPlayerMoveItemOutOFInventory (itemName,loot) local itemPlus = 1 if itemName == "M1911 Mag" then itemPlus = 7 elseif itemName == "M9 SD Mag" then itemPlus = 15 elseif itemName == ".45ACP" then itemPlus = 7 elseif itemName == "PDW Mag" then itemPlus = 30 elseif itemName == "MP5A5 Mag" then itemPlus = 20 elseif itemName == "AK" then itemPlus = 30 elseif itemName == "STANAG" then itemPlus = 20 elseif itemName == "1866 Slug" then itemPlus = 7 elseif itemName == "2Rnd. Slug" then itemPlus = 2 elseif itemName == "SPAZ-12 Pellet" then itemPlus = 7 elseif itemName == "CZ550 Mag" then itemPlus = 5 elseif itemName == "Lee Enfield Mag" then itemPlus = 10 elseif itemName == "M136 Rocket" then itemPlus = 0 elseif itemName == "М4А1 CCO" or itemName == "AK-74" or itemName == "CZ550" or itemName == "Винчестер 1866" or itemName == "SPAZ-12 Combat Shotgun" or itemName == "Sawn-Off Shotgun" or itemName == "Heat-Seeking RPG" or itemName == "M136 Rocket Launcher" or itemName == "Lee Enfield" then triggerServerEvent("removeBackWeaponOnDrop",getLocalPlayer()) end if loot then if not getElementData(loot,"itemloot") and getElementType(getElementData(loot,"parent")) == "vehicle" then if itemName == "Наполненная канистра" then if getElementData(loot,"fuel")+20 < getVehicleMaxFuel(loot) then addingfuel = 20 elseif getElementData(loot,"fuel")+20 > getVehicleMaxFuel(loot)+15 then triggerEvent ("displayClientInfo", getLocalPlayer(),"Vehicle","Бензобак полон!",255,22,0) return else addingfuel = getVehicleMaxFuel(loot)-getElementData(loot,"fuel") end setElementData(loot,"fuel",getElementData(loot,"fuel")+addingfuel) setElementData(getLocalPlayer(),itemName,getElementData(getLocalPlayer(),itemName)-itemPlus) setElementData(getLocalPlayer(),"Пустая канистра",(getElementData(getLocalPlayer(),"Пустая канистра") or 0)+itemPlus) triggerEvent ("displayClientInfo", getLocalPlayer(),"Vehicle","Вы заправили транспорт на 20 литров!",22,255,0) return end end end itemName2 = itemName if itemName == "Колесо_inVehicle" then itemName2 = "Колесо" end if itemName == "Двигатель_inVehicle" then itemName2 = "Двигатель" end if itemName == "Parts_inVehicle" then itemName2 = "Бензобак" end if (getElementData(getLocalPlayer(),itemName2) or 0)/itemPlus < 1 then triggerEvent ("displayClientInfo", getLocalPlayer(),"Inventory","Вы не можете использовать это!",255,22,0) return end if loot then setElementData(loot,itemName,(getElementData(loot,itemName) or 0)+1) local players = getElementsWithinColShape (loot,"player") if #players > 1 then triggerServerEvent("onPlayerChangeLoot",getRootElement(),loot) end if not getElementData(loot,"itemloot") and getElementType(getElementData(loot,"parent")) == "vehicle" then end else triggerServerEvent("playerDropAItem",getLocalPlayer(),itemName) end if itemName == "Колесо_inVehicle" then itemName = "Колесо" end if itemName == "Двигатель_inVehicle" then itemName = "Двигатель" end if itemName == "Parts_inVehicle" then itemName = "Бензобак" end setElementData(getLocalPlayer(),itemName,getElementData(getLocalPlayer(),itemName)-itemPlus) if loot and getElementData(loot,"itemloot") then triggerServerEvent("refreshItemLoot",getRootElement(),loot,getElementData(loot,"parent")) end end addEvent( "onPlayerMoveItemOutOFInventory", true ) addEventHandler( "onPlayerMoveItemOutOFInventory", getRootElement(), onPlayerMoveItemOutOFInventory ) function onPlayerMoveItemInInventory () local itemName = guiGridListGetItemText ( gridlistItems["loot"], guiGridListGetSelectedItem ( gridlistItems["loot"] ), 1 ) if isPlayerInLoot() then if getElementData(isPlayerInLoot(),itemName) and getElementData(isPlayerInLoot(),itemName) >= 1 then if not isToolbeltItem(itemName) then if getPlayerCurrentSlots() + getItemSlots(itemName) <= getPlayerMaxAviableSlots() then if not playerMovedInInventory then triggerEvent("onPlayerMoveItemInInventory",getLocalPlayer(),itemName,isPlayerInLoot()) playerMovedInInventory = true setTimer(function() playerMovedInInventory = false end,700,1) else startRollMessage2("Inventory", "Не торопись!", 255, 22, 0 ) return end else startRollMessage2("Inventory", "Инвентарь полон!", 255, 22, 0 ) return end else playerMovedInInventory = true setTimer(function() playerMovedInInventory = false end,700,1) triggerEvent("onPlayerMoveItemInInventory",getLocalPlayer(),itemName,isPlayerInLoot()) end end if isPlayerInLoot() then local gearName = guiGetText(headline["loot"]) local col = getElementData(getLocalPlayer(),"currentCol") setTimer(refreshInventory,200,2) setTimer(refreshLoot,200,2,col,gearName) end end end addEventHandler ( "onClientGUIClick", buttonItems["loot"], onPlayerMoveItemInInventory ) function onPlayerMoveItemInInventory (itemName,loot) local itemPlus = 1 if itemName == "M1911 Mag" then itemPlus = 7 elseif itemName == "M9 SD Mag" then itemPlus = 15 elseif itemName == ".45ACP" then itemPlus = 7 elseif itemName == "PDW Mag" then itemPlus = 30 elseif itemName == "MP5A5 Mag" then itemPlus = 20 elseif itemName == "AK" then itemPlus = 30 elseif itemName == "STANAG" then itemPlus = 20 elseif itemName == "1866 Slug" then itemPlus = 7 elseif itemName == "2Rnd. Slug" then itemPlus = 2 elseif itemName == "SPAZ-12 Pellet" then itemPlus = 7 elseif itemName == "CZ550 Mag" then itemPlus = 5 elseif itemName == "Lee Enfield Mag" then itemPlus = 10 elseif itemName == "M136 Rocket" then itemPlus = 0 elseif itemName == "Assault Pack (ACU)" then if getElementData(getLocalPlayer(),"MAX_Slots") == 12 then triggerEvent (getLocalPlayer(), "displayClientInfo", getLocalPlayer(),"Inventory","You are using this backpack already!",255,22,0) return end if getElementData(getLocalPlayer(),"MAX_Slots") > 12 then triggerEvent (getLocalPlayer(), "displayClientInfo", getLocalPlayer(),"Inventory","The currently equipped backpack has more space!",255,22,0) return end setElementData(getLocalPlayer(),"MAX_Slots",12) setElementData(loot,itemName,getElementData(loot,itemName)-1) itemPlus = 0 elseif itemName == "Alice Pack" then if getElementData(getLocalPlayer(),"MAX_Slots") == 16 then triggerEvent (getLocalPlayer(), "displayClientInfo", getLocalPlayer(),"Inventory","You are using this backpack already!",255,22,0) return end if getElementData(getLocalPlayer(),"MAX_Slots") > 16 then triggerEvent (getLocalPlayer(), "displayClientInfo", getLocalPlayer(),"Inventory","The currently equipped backpack has more space!",255,22,0) return end setElementData(getLocalPlayer(),"MAX_Slots",16) setElementData(loot,itemName,getElementData(loot,itemName)-1) itemPlus = 0 elseif itemName == "Czech Backpack" then if getElementData(getLocalPlayer(),"MAX_Slots") == 26 then triggerEvent (getLocalPlayer(), "displayClientInfo", getLocalPlayer(),"Inventory","You are using this backpack already!",255,22,0) return end if getElementData(getLocalPlayer(),"MAX_Slots") > 26 then triggerEvent (getLocalPlayer(), "displayClientInfo", getLocalPlayer(),"Inventory","The currently equipped backpack has more space!",255,22,0) return end setElementData(getLocalPlayer(),"MAX_Slots",26) setElementData(loot,itemName,getElementData(loot,itemName)-1) itemPlus = 0 elseif itemName == "Coyote Backpack" then if getElementData(getLocalPlayer(),"MAX_Slots") == 36 then triggerEvent (getLocalPlayer(), "displayClientInfo", getLocalPlayer(),"Inventory","You already have the best backpack!",255,22,0) return end if getElementData(getLocalPlayer(),"MAX_Slots") > 36 then triggerEvent (getLocalPlayer(), "displayClientInfo", getLocalPlayer(),"Inventory","The currently equipped backpack has more space!",255,22,0) return end setElementData(getLocalPlayer(),"MAX_Slots",36) setElementData(loot,itemName,getElementData(loot,itemName)-1) itemPlus = 0 end if loot then --if itemPlus > (getElementData(loot,itemName) or 0) then --itemPlus = getElementData(loot,itemName) --end setElementData(getLocalPlayer(),itemName,(getElementData(getLocalPlayer(),itemName) or 0)+itemPlus) if itemPlus == 0 then setElementData(loot,itemName,getElementData(loot,itemName)-0) else setElementData(loot,itemName,getElementData(loot,itemName)-1) end local players = getElementsWithinColShape (loot,"player") if #players > 1 then triggerServerEvent("onPlayerChangeLoot",getRootElement(),loot) end end if getElementData(loot,"itemloot") then triggerServerEvent("refreshItemLoot",getRootElement(),loot,getElementData(loot,"parent")) end end addEvent( "onPlayerMoveItemInInventory", true ) addEventHandler( "onPlayerMoveItemInInventory", getRootElement(), onPlayerMoveItemInInventory ) function onClientOpenInventoryStopMenu () triggerEvent("disableMenu",getLocalPlayer()) end function isPlayerInLoot() if getElementData(getLocalPlayer(),"loot") then return getElementData(getLocalPlayer(),"currentCol") end return false end ------------------------------------------------------------------------------ --right-click menu function onPlayerPressRightKeyInInventory () local itemName = guiGridListGetItemText ( gridlistItems["inventory"], guiGridListGetSelectedItem ( gridlistItems["inventory"] ), 1 ) local itemName,itemInfo = getInventoryInfosForRightClickMenu(itemName) if isCursorShowing() and guiGetVisible(inventoryWindows) and itemInfo then if itemName == "Спички" then if getElementData(getLocalPlayer(),"Дрова") == 0 then return end end if itemName == "Бинт" then if getElementData(getLocalPlayer(),"bleeding") == 0 then return end end if itemName == "Аптечка" then if getElementData(getLocalPlayer(),"blood") > 10500 then return end end if itemName == "Грелка" then if getElementData(getLocalPlayer(),"temperature") > 35 then return end end if itemName == "Болеутоляющие" then if not getElementData(getLocalPlayer(),"pain") then return end end if itemName == "Морфий" then if not getElementData(getLocalPlayer(),"brokenbone") then return end end if itemName == "Пакет крови" then --if getElementData(getLocalPlayer(),"blood") < 1150 then return --end end showRightClickInventoryMenu (itemName,itemInfo) end end bindKey("mouse2","down",onPlayerPressRightKeyInInventory) function getInventoryInfosForRightClickMenu(itemName) for i,itemInfo in ipairs(inventoryItems["Weapons"]["Primary Weapon"]) do if itemName == itemInfo[1] then return itemName,"Взять осн. оружие" end end for i,itemInfo in ipairs(inventoryItems["Weapons"]["Secondary Weapon"]) do if itemName == itemInfo[1] then return itemName,"Взять доп. оружие" end end for i,itemInfo in ipairs(inventoryItems["Weapons"]["Specially Weapon"]) do if itemName == itemInfo[1] then return itemName,"Взять спец. оружие" end end for i,itemInfo in ipairs(inventoryItems["Ammo"]) do if itemName == itemInfo[1] then return itemName,false end end for i,itemInfo in ipairs(inventoryItems["Food"]) do if itemName == itemInfo[1] then if itemInfo[1] == "Фляга" or itemInfo[1] == "Молоко" or itemInfo[1] == "Банка соды" then info = "Выпить" else info = "Съесть" end return itemName,info end end for i,itemInfo in ipairs(inventoryItems["Items"]) do if itemName == itemInfo[1] then return itemName,itemInfo[3] or false end end for i,itemInfo in ipairs(inventoryItems["Toolbelt"]) do if itemName == itemInfo[1] then return itemName,itemInfo[3] or false end end end rightclickWindow = guiCreateStaticImage(0,0,0.05,0.0215,"images/scrollmenu_1.png",true) headline["rightclickmenu"] = guiCreateLabel(0,0,1,1,"",true,rightclickWindow) guiLabelSetHorizontalAlign (headline["rightclickmenu"],"center") guiLabelSetVerticalAlign (headline["rightclickmenu"],"center") guiSetFont (headline["rightclickmenu"], "default-bold-small" ) guiSetVisible(rightclickWindow,false) function showRightClickInventoryMenu (itemName,itemInfo) if itemInfo then local screenx, screeny, worldx, worldy, worldz = getCursorPosition() guiSetVisible(rightclickWindow,true) guiSetText(headline["rightclickmenu"],itemInfo) local whith = guiLabelGetTextExtent (headline["rightclickmenu"]) guiSetPosition(rightclickWindow,screenx,screeny,true) local x,y = guiGetSize(rightclickWindow,false) guiSetSize(rightclickWindow,whith,y,false) guiBringToFront(rightclickWindow) setElementData(rightclickWindow,"iteminfo",{itemName,itemInfo}) end end function hideRightClickInventoryMenu () guiSetVisible(rightclickWindow,false) end function onPlayerClickOnRightClickMenu (button,state) if button == "left" then local itemName,itemInfo = getElementData(rightclickWindow,"iteminfo")[1],getElementData(rightclickWindow,"iteminfo")[2] hideRightClickInventoryMenu () playerUseItem(itemName,itemInfo) end end addEventHandler("onClientGUIClick",headline["rightclickmenu"],onPlayerClickOnRightClickMenu,false) local playerFire = {} local fireCounter = 0 function playerUseItem(itemName,itemInfo) if itemInfo == "Выпить" then triggerServerEvent("onPlayerRequestChangingStats",getLocalPlayer(),itemName,itemInfo,"thirst") elseif itemInfo == "Съесть" then triggerServerEvent("onPlayerRequestChangingStats",getLocalPlayer(),itemName,itemInfo,"food") elseif itemInfo == "Переодется" then triggerServerEvent("onPlayerChangeSkin",getLocalPlayer(),itemName) elseif itemName == "Пустая фляга" then triggerServerEvent("onPlayerRefillWaterBottle",getLocalPlayer(),itemName) elseif itemName == "Палатка" then triggerServerEvent("onPlayerPitchATent",getLocalPlayer(),itemName) elseif itemInfo == "Поставить проволоку" then triggerServerEvent("onPlayerBuildAWireFence",getLocalPlayer(),itemName) elseif itemName == "Фаер" then triggerServerEvent("onPlayerPlaceRoadflare",getLocalPlayer(),itemName) elseif itemInfo == "Поджечь" then triggerServerEvent("onPlayerMakeAFire",getLocalPlayer(),itemName) elseif itemInfo == "Исп." then triggerServerEvent("onPlayerUseMedicObject",getLocalPlayer(),itemName) elseif itemName == "Бинт" then triggerServerEvent("onPlayerUseMedicObject",getLocalPlayer(),itemName) elseif itemInfo == "Исп. Googles" then triggerServerEvent("onPlayerChangeView",getLocalPlayer(),itemName) elseif itemInfo == "Взять осн. оружие" then triggerServerEvent("onPlayerRearmWeapon",getLocalPlayer(),itemName,1) elseif itemInfo == "Взять доп. оружие" then triggerServerEvent("onPlayerRearmWeapon",getLocalPlayer(),itemName,2) elseif itemInfo == "Взять спец. оружие" then triggerServerEvent("onPlayerRearmWeapon",getLocalPlayer(),itemName,3) end end weaponAmmoTable = { ["M1911 Mag"] = { {"M1911",22}, }, ["M9 SD Mag"] = { {"M9 SD",23}, }, [".45ACP"] = { {"Револьвер",24}, }, ["PDW Mag"] = { {"PDW",28}, }, ["MP5A5 Mag"] = { {"MP5A5",29}, }, ["AK"] = { {"AK-74",30}, }, ["STANAG"] = { {"М4А1 CCO",31}, }, ["1866 Slug"] = { {"Винчестер 1866",25}, }, ["2Rnd. Slug"] = { {"Sawn-Off Shotgun",26}, }, ["SPAZ-12 Pellet"] = { {"SPAZ-12 Combat Shotgun",27}, }, ["CZ550 Mag"] = { {"CZ550",34}, }, ["Lee Enfield Mag"] = { {"Lee Enfield",33}, }, ["M136 Rocket"] = { {"Heat-Seeking RPG",36}, {"M136 Rocket Launcher",35}, }, ["others"] = { {"Парашют",46}, {"Satchel",39}, {"Tear Gas",17}, {"Оск. граната M67",16}, {"Охотничий нож",4}, {"Топор",8}, {"Бинокль",43}, {"Бейсбольная бита",5}, {"Лопата",6}, {"Клюшка для гольфа",2}, }, } function getWeaponAmmoType2 (weaponName) for i,weaponData in ipairs(weaponAmmoTable["others"]) do if weaponName == weaponData[2] then return weaponData[1],weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["M1911 Mag"]) do if weaponName == weaponData[2] then return "M1911 Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["M9 SD Mag"]) do if weaponName == weaponData[2] then return "M9 SD Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable[".45ACP"]) do if weaponName == weaponData[2] then return ".45ACP",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["PDW Mag"]) do if weaponName == weaponData[2] then return "PDW Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["MP5A5 Mag"]) do if weaponName == weaponData[2] then return "MP5A5 Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["AK"]) do if weaponName == weaponData[2] then return "AK",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["STANAG"]) do if weaponName == weaponData[2] then return "STANAG",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["1866 Slug"]) do if weaponName == weaponData[2] then return "1866 Slug",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["SPAZ-12 Pellet"]) do if weaponName == weaponData[2] then return "SPAZ-12 Pellet",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["2Rnd. Slug"]) do if weaponName == weaponData[2] then return "2Rnd. Slug",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["CZ550 Mag"]) do if weaponName == weaponData[2] then return "CZ550 Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["Lee Enfield Mag"]) do if weaponName == weaponData[2] then return "Lee Enfield Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["M136 Rocket"]) do if weaponName == weaponData[2] then return "M136 Rocket",weaponData[2] end end end function weaponSwitch (weapon) if source == getLocalPlayer() then local ammoName,_ = getWeaponAmmoType2 (weapon) if getElementData(getLocalPlayer(),ammoName) > 0 then setElementData(getLocalPlayer(),ammoName,getElementData(getLocalPlayer(),ammoName)-1) end end end addEventHandler ( "onClientPlayerWeaponFire", getLocalPlayer(), weaponSwitch ) bindKey("mouse_wheel_up", "down", function(key, state) setRadioChannel ( 0 ) end) bindKey("mouse_wheel_down", "down", function(key, state) setRadioChannel ( 0 ) end) bindKey("r", "down", function(key, state) setRadioChannel ( 0 ) end) addEventHandler ( "onClientPlayerVehicleEnter", localPlayer, function ( ) setRadioChannel ( 0 ) setPlayerHudComponentVisible ("radio",false) end) -- pickups.lua getResourceRootElement(getThisResource()) function checkResourceRequirements ( res ) local reason = false if getResourceName(getThisResource()) ~= "DayZ" then reason = "Игровой ник of resource does not match (DayZ)!" end if reason ~= false then outputServerLog ( "Resource " .. getResourceName(res) .. " wasn't started: ("..reason..")." ) outputChatBox ( "Resource " .. getResourceName(res) .. " wasn't started: ("..reason..").", getRootElement(), 255, 255, 255 ) outputConsole ( "Resource " .. getResourceName(res) .. " wasn't started: ("..reason..")." ) outputDebugString ( "Resource " .. getResourceName(res) .. " wasn't started: ("..reason..")." ) cancelEvent() end end addEventHandler ( "onResourceStart", getResourceRootElement(getThisResource()), checkResourceRequirements ) local itemTable = { ---------------------- ["farm"] = { {"Дрова",1463,0.4,0,13}, {"Бинт",1578,0.5,0,4}, {"Фляга",2683,1,0,6}, {"Банка макарон",2770,1,0,6}, {"Банка бобов",2601,1,0,6}, {"Гамбургер",2768,1,0,6}, {"Пустая банка соды",2673,0.5,0,12}, {"Объедки",2675,0.5,0,12}, {"Банка соды",2647,1,0,9}, {"Пустая канистра",1650,1,0,10}, {"Охотничий нож",335,1,90,4}, {"Спички",328,0.4,90,8}, {"Револьвер",348,1,90,0.2}, {"Морфий",1579,1,0,4}, {"Палатка",1279,1,0,0.5}, {"M1911",346,1,90,4}, {"Болеутоляющие",2709,3,0,3.5}, {"Lee Enfield",357,1,90,0.3}, {"Винчестер 1866",349,1,90,0.3}, {"Колесо",1073,1,0,2}, {"Бензобак",1008,1,0.8,2}, {"Женский скин",1241,2,0,2.5}, {"Карта",1277,0.8,90,6}, {"GPS",2976,0.15,0,2}, }, ---------------------- ["residential"] = { {"Спички",328,0.4,90,5}, {"Дрова",1463,0.4,0,5}, {"M1911",346,1,90,1.5}, {"M9 SD",347,1,90,1.9}, {"Винчестер 1866",349,1,90,0.1}, {"PDW",352,1,90,1}, {"Охотничий нож",335,1,90,3}, {"Топор",339,1,90,1}, {"Пицца",1582,1,0,7}, {"Банка соды",2647,1,0,7}, {"Пустая канистра",1650,1,0,9}, {"Фаер",324,1,90,9}, {"Молоко",2856,1,0,7}, {"Assault Pack (ACU)",3026,1,0,6}, {"Болеутоляющие",2709,3,0,7}, {"Пустая банка соды",2673,0.5,0,12}, {"Объедки",2675,0.5,0,12}, {"Оск. граната M67",342,1,0,0.01}, {"Револьвер",348,1,90,0.4}, {"Sawn-Off Shotgun",350,1,90,0.3}, {"SPAZ-12 Combat Shotgun",351,1,90,0.4}, {"MP5A5",353,1,90,0.4}, {"Часы",2710,1,0,3}, {"Грелка",1576,5,0,6}, {"Колючая проволока",933,0.25,0,1}, {"Lee Enfield",357,1,90,0.3}, {"Alice Pack",1248,1,0,1.5}, {"Колесо",1073,1,0,1}, {"Бензобак",1008,0.8,0,1}, {"Морфий",1579,1,0,2}, {"Женский скин",1241,2,0,9}, {"Карта",1277,0.8,90,10}, {"GPS",2976,0.15,0,3}, {"Банка макарон",2770,1,0,7}, {"Банка бобов",2601,1,0,7}, --{"TEC-9",372,1,90,0}, {"Гамбургер",2768,1,0,7}, {"Клюшка для гольфа",333,1,90,3}, {"Бейсбольная бита",336,1,90,3}, {"Лопата",337,1,90,3}, }, ---------------------- ["military"] = { {"Спички",328,0.4,90,2}, {"M1911",346,1,90,5}, {"M9 SD",347,1,90,4}, {"Винчестер 1866",349,1,90,3}, {"PDW",352,1,90,4}, {"Охотничий нож",335,1,90,2.4}, {"Топор",339,1,90,2.1}, {"Пицца",1582,1,0,2}, {"Банка соды",2647,1,0,2}, {"Пустая канистра",1650,1,0,4}, {"Фаер",324,1,90,4}, {"Молоко",2856,1,0,1}, {"Болеутоляющие",2709,3,0,4}, {"Пустая банка соды",2673,0.5,0,12}, {"Объедки",2675,0.5,0,12}, {"Оск. граната M67",342,1,0,0.5}, {"Sawn-Off Shotgun",350,1,90,2.3}, {"SPAZ-12 Combat Shotgun",351,1,90,2.3}, {"MP5A5",353,1,90,2.8}, {"Часы",2710,1,0,4}, {"Грелка",1576,5,0,3}, {"Колючая проволока",933,0.25,0,1}, {"Lee Enfield",357,1,90,3.5}, {"Alice Pack",1248,1,0,4}, {"Очки ночного видения",368,1,90,4}, {"Бинокль",369,1,0,4}, {"Колесо",1073,1,0,2}, {"Бензобак",1008,0.8,0,2}, {"Морфий",1579,1,0,4}, {"Армейский камуфляж",1247,2,0,4.5}, {"Женский скин",1241,2,0,3}, --{"TEC-9",372,1,90,3}, {"AK-74",355,1,90,3.8}, {"GPS",2976,0.15,0,3}, {"Карта",1277,0.8,90,7}, {"Инструменты",2969,0.5,0,1}, {"Двигатель",929,0.3,0,2}, {"Палатка",1279,1,0,4.5}, {"Камуфляж снайпера",1213,2,0,0.3}, {"М4А1 CCO",356,1,90,2.4}, {"CZ550",358,1,90,0.4}, {"Инфокрасные очки",369,1,90,3}, {"Assault Pack (ACU)",3026,1,0,5}, {"Czech Backpack",1239,1,0,2}, {"Рация",330,1,0,6}, {"Coyote Backpack",1252,1,0,0.9}, {"Лопата",337,1,90,1}, }, ---------------------- ["industrial"] = { {"Колючая проволока",933,0.25,0,7}, {"Инструменты",2969,0.5,0,3}, {"Колесо",1073,1,0,4}, {"Двигатель",929,0.3,0,3.5}, {"Бензобак",1008,1,0.8,4}, {"Винчестер 1866",349,1,90,3}, {"Фляга",2683,1,0,4}, {"Банка макарон",2770,1,0,4}, {"Банка бобов",2601,1,0,4}, {"Гамбургер",2768,1,0,4}, {"Пустая банка соды",2673,0.5,0,12}, {"Объедки",2675,0.5,0,10}, {"Банка соды",2647,1,0,4}, {"Пустая канистра",1650,1,0,6}, {"Наполненная канистра",1650,1,0,1.5}, {"Карта",1277,0.8,90,3}, {"Часы",2710,1,0,2}, {"Спички",328,0.4,90,5}, {"Дрова",1463,0.4,0,2}, {"M1911",346,1,90,1.5}, {"PDW",352,1,90,2}, {"Охотничий нож",335,1,90,2}, {"Топор",339,1,90,1.5}, {"Пицца",1582,1,0,4}, {"Фаер",324,1,90,5}, {"Молоко",2856,1,0,4}, {"Assault Pack (ACU)",3026,1,0,6}, {"Coyote Backpack",1252,1,0,0.5}, {"Рация",330,1,0,6}, {"Клюшка для гольфа",333,1,90,1.5}, {"Бейсбольная бита",336,1,90,1.5}, {"Лопата",337,1,90,1.5}, {"Очки ночного видения",368,1,90,1.5}, }, ---------------------- ["supermarket"] = { {"Жареное мясо",2804,0.5,90,8}, {"Спички",328,0.4,90,5}, {"Дрова",1463,0.4,0,5}, {"M1911",346,1,90,3.5}, {"PDW",352,1,90,2}, {"Охотничий нож",335,1,90,3}, {"Топор",339,1,90,2.1}, {"Пицца",1582,1,0,7}, {"Банка соды",2647,1,0,7}, {"Пустая канистра",1650,1,0,5}, {"Фаер",324,1,90,6}, {"Молоко",2856,1,0,7}, {"Assault Pack (ACU)",3026,1,0,6}, {"Банка макарон",2770,1,0,7}, {"Банка бобов",2601,1,0,7}, {"Гамбургер",2768,1,0,7}, {"Болеутоляющие",2709,3,0,7}, {"Пустая банка соды",2673,0.5,0,12}, {"Объедки",2675,0.5,0,12}, {"MP5A5",353,1,90,0.5}, {"Часы",2710,1,0,3}, {"Грелка",1576,5,0,6}, {"Колючая проволока",933,0.25,0,1}, {"Lee Enfield",357,1,90,0.2}, {"Alice Pack",1248,1,0,0.5}, {"Колесо",1073,1,0,1}, {"Бензобак",1008,1,0.8,2}, {"Морфий",1579,1,0,2}, {"Женский скин",1241,2,0,3.5}, {"Карта",1277,0.8,90,4}, {"GPS",2976,0.15,0,1}, {"Рация",330,1,0,6}, {"Клюшка для гольфа",333,1,90,1.9}, {"Бейсбольная бита",336,1,90,1.4}, {"Лопата",337,1,90,0.3}, }, ["other"] = { {"Жареное мясо",2804,0.5,90}, {"Сырое мясо",2806,0.5,90}, {"Наполненная канистра",1650,1,0}, {"Пустая фляга",2683,1,0}, {"Одежда выжившего",1577,2,0}, {"Очки ночного видения",368,1,90}, {"Инфокрасные очки",369,1,90}, {"1866 Slug",2358,2,0}, {"2Rnd. Slug",2358,2,0}, {"SPAZ-12 Pellet",2358,2,0}, {"MP5A5 Mag",2358,2,0}, {"AK",1271,2,0}, {"STANAG",1271,2,0}, {"M1911 Mag",3013,2,0}, {"M9 SD Mag",3013,2,0}, {".45ACP",3013,2,0}, --{"M136 Rocket",3082,0.7,90}, {"CZ550 Mag",2358,2,0}, {"Lee Enfield Mag",2358,2,0}, {"PDW Mag",2041,2,0}, {"MP5A5 Mag",2041,2,0}, {"Спички",328,0.4,90,5}, {"Дрова",1463,0.4,0,5}, {"M1911",346,1,90,3.5}, {"PDW",352,1,90,2}, {"Охотничий нож",335,1,90,2.5}, {"Топор",339,1,90,1.8}, {"Пицца",1582,1,0,7}, {"Банка соды",2647,1,0,7}, {"Пустая канистра",1650,1,0,5}, {"Фаер",324,1,90,6}, {"Молоко",2856,1,0,5}, {"Assault Pack (ACU)",3026,1,0,6}, {"Болеутоляющие",2709,3,0,7}, {"Пустая банка соды",2673,0.5,0,12}, {"Объедки",2675,0.5,0,12}, {"MP5A5",353,1,90,1.5}, {"Часы",2710,1,0,3}, {"Грелка",1576,5,0,6}, {"Колючая проволока",933,0.25,0,1}, {"Lee Enfield",357,1,90,1.5}, {"Alice Pack",1248,1,0,1.5}, {"Coyote Backpack",1252,1,0,0.7}, {"Колесо",1073,1,0,1}, {"Бензобак",1008,1,0.8,4}, {"Морфий",1579,1,0,2}, {"Женский скин",1241,2,0,3.5}, {"Карта",1277,0.8,90,4}, {"Инструменты",2969,0.5,0,3}, {"Двигатель",929,0.3,0,3.5}, {"Винчестер 1866",349,1,90,2}, {"Фляга",2683,1,0,4}, {"M9 SD",347,1,90,5}, {"Оск. граната M67",342,1,0,0.5}, {"Sawn-Off Shotgun",350,1,90,2}, {"SPAZ-12 Combat Shotgun",351,1,90,1.9}, {"Бинокль",369,1,0,4}, {"Армейский камуфляж",1247,2,0,4.5}, --{"TEC-9",372,1,90,4}, {"AK-74",355,1,90,0.9}, {"M136 Rocket Launcher",359,1,90,0}, {"Камуфляж снайпера",1213,2,0,0.01}, {"М4А1 CCO",356,1,90,0.9}, {"CZ550",358,1,90,0.3}, {"Heat-Seeking RPG",360,1,90,0}, {"Бинт",1578,0.5,0,4}, {"Банка макарон",2770,1,0,5}, {"Банка бобов",2601,1,0,6}, {"Гамбургер",2768,1,0,2}, {"Палатка",1279,1,0,0.5}, {"M1911",346,1,90,3}, {"Револьвер",348,1,90,3}, {"GPS",2976,0.15,0,1}, {"Аптечка",2891,2.2,0}, {"Пакет крови",1580,1,0}, {"Рация",2966,0.5,0,5}, {"Клюшка для гольфа",333,1,90,1.9}, {"Бейсбольная бита",336,1,90,1.4}, {"Лопата",337,1,90,1.5}, }, } weaponAmmoTable = { ["M1911 Mag"] = { {"M1911",22}, }, ["M9 SD Mag"] = { {"M9 SD",23}, }, [".45ACP"] = { {"Револьвер",24}, }, ["PDW Mag"] = { {"PDW",28}, }, ["MP5A5 Mag"] = { {"MP5A5",29}, }, ["AK"] = { {"AK-74",30}, }, ["STANAG"] = { {"М4А1 CCO",31}, }, ["1866 Slug"] = { {"Винчестер 1866",25}, }, ["2Rnd. Slug"] = { {"Sawn-Off Shotgun",26}, }, ["SPAZ-12 Pellet"] = { {"SPAZ-12 Combat Shotgun",27}, }, ["CZ550 Mag"] = { {"CZ550",34}, }, ["Lee Enfield Mag"] = { {"Lee Enfield",33}, }, ["M136 Rocket"] = { {"Heat-Seeking RPG",36}, {"M136 Rocket Launcher",35}, }, ["others"] = { {"Парашют",46}, {"Satchel",39}, {"Tear Gas",17}, {"Оск. граната M67",16}, {"Охотничий нож",4}, {"Топор",8}, {"Бинокль",43}, {"Бейсбольная бита",5}, {"Клюшка для гольфа",2}, {"Лопата",6}, {"Рация",1}, }, } function getWeaponAmmoType (weaponName,notOthers) if not notOthers then for i,weaponData in ipairs(weaponAmmoTable["others"]) do if weaponName == weaponData[1] then return weaponData[1],weaponData[2] end end end for i,weaponData in ipairs(weaponAmmoTable["M1911 Mag"]) do if weaponName == weaponData[1] then return "M1911 Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["M9 SD Mag"]) do if weaponName == weaponData[1] then return "M9 SD Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable[".45ACP"]) do if weaponName == weaponData[1] then return ".45ACP",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["PDW Mag"]) do if weaponName == weaponData[1] then return "PDW Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["MP5A5 Mag"]) do if weaponName == weaponData[1] then return "MP5A5 Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["AK"]) do if weaponName == weaponData[1] then return "AK",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["STANAG"]) do if weaponName == weaponData[1] then return "STANAG",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["1866 Slug"]) do if weaponName == weaponData[1] then return "1866 Slug",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["2Rnd. Slug"]) do if weaponName == weaponData[1] then return "2Rnd. Slug",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["SPAZ-12 Pellet"]) do if weaponName == weaponData[1] then return "SPAZ-12 Pellet",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["CZ550 Mag"]) do if weaponName == weaponData[1] then return "CZ550 Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["Lee Enfield Mag"]) do if weaponName == weaponData[1] then return "Lee Enfield Mag",weaponData[2] end end for i,weaponData in ipairs(weaponAmmoTable["M136 Rocket"]) do if weaponName == weaponData[1] then return "M136 Rocket",weaponData[2] end end return false end function createItemPickup(item,x,y,z,tableStringName) if item and x and y and z then local object = createObject(itemTable[tostring(tableStringName)][item][2],x,y,z-0.875,itemTable[tostring(tableStringName)][item][4],0,math.random(0,360)) setObjectScale(object,itemTable[tostring(tableStringName)][item][3]) setElementCollisionsEnabled(object, false) setElementFrozen (object,true) local col = createColSphere(x,y,z,0.75) setElementData(col,"item",itemTable[tostring(tableStringName)][item][1]) setElementData(col,"parent",object) setTimer(function() if isElement(col) then destroyElement(col) destroyElement(object) end end,900000,1) return object end end function table.size(tab) local length = 0 for _ in pairs(tab) do length = length + 1 end return length end function math.percentChance (percent,repeatTime) local hits = 0 for i = 1, repeatTime do local number = math.random(0,200)/2 if number <= percent then hits = hits+1 end end return hits end function createItemLoot (lootPlace,x,y,z,id) col = createColSphere(x,y,z,1.25) setElementData(col,"itemloot",true) setElementData(col,"parent",lootPlace) setElementData(col,"MAX_Slots",12) --Items for i, item in ipairs(itemTable[lootPlace]) do local value = math.percentChance (item[5],math.random(1,2)) setElementData(col,item[1],value) --weapon Ammo local ammoData,weapID = getWeaponAmmoType (item[1],true) if ammoData and value > 0 then setElementData(col,ammoData,math.random(1,2)) end end --itemLoot refreshItemLoot (col,lootPlace) return col end function refreshItemLoot (col,place) local objects = getElementData(col,"objectsINloot") if objects then if objects[1] ~= nil then destroyElement(objects[1]) end if objects[2] ~= nil then destroyElement(objects[2]) end if objects[3] ~= nil then destroyElement(objects[3]) end end --setting objects local counter = 0 local obejctItem = {} --Tables for i, item in ipairs(itemTable["other"]) do if getElementData(col,item[1]) and getElementData(col,item[1]) > 0 then if counter == 3 then break end counter = counter + 1 local x,y,z = getElementPosition(col) obejctItem[counter] = createObject(item[2],x+math.random(-1,1),y+math.random(-1,1),z-0.875,item[4]) setObjectScale(obejctItem[counter],item[3]) setElementCollisionsEnabled(obejctItem[counter], false) setElementFrozen (obejctItem[counter],true) end end -------Debug if obejctItem[1] == nil then local x,y,z = getElementPosition(col) obejctItem[1] = createObject(1463,x+math.random(-1,1),y+math.random(-1,1),z-0.875,0) setObjectScale(obejctItem[1],0) setElementCollisionsEnabled(obejctItem[1], false) setElementFrozen (obejctItem[1],true) end if obejctItem[2] == nil then local x,y,z = getElementPosition(col) obejctItem[2] = createObject(1463,x+math.random(-1,1),y+math.random(-1,1),z-0.875,0) setObjectScale(obejctItem[2],0) setElementCollisionsEnabled(obejctItem[2], false) setElementFrozen (obejctItem[2],true) end if obejctItem[3] == nil then local x,y,z = getElementPosition(col) obejctItem[3] = createObject(1463,x+math.random(-1,1),y+math.random(-1,1),z-0.875,0) setObjectScale(obejctItem[3],0) setElementCollisionsEnabled(obejctItem[3], false) setElementFrozen (obejctItem[3],true) end setElementData(col,"objectsINloot",{obejctItem[1], obejctItem[2], obejctItem[3]}) end addEvent( "refreshItemLoot", true ) addEventHandler( "refreshItemLoot", getRootElement(), refreshItemLoot ) function createPickupsOnServerStart() iPickup = 0 for i,pos in ipairs(pickupPositions["residential"]) do iPickup = iPickup + 1 createItemLoot("residential",pos[1],pos[2],pos[3],iPickup) end setTimer(createPickupsOnServerStart2,5000,1) end function createPickupsOnServerStart2() for i,pos in ipairs(pickupPositions["industrial"]) do iPickup = iPickup + 1 createItemLoot("industrial",pos[1],pos[2],pos[3],iPickup) end setTimer(createPickupsOnServerStart3,5000,1) end function createPickupsOnServerStart3() for i,pos in ipairs(pickupPositions["farm"]) do iPickup = iPickup + 1 createItemLoot("farm",pos[1],pos[2],pos[3],iPickup) end setTimer(createPickupsOnServerStart4,5000,1) end function createPickupsOnServerStart4() for i,pos in ipairs(pickupPositions["supermarket"]) do iPickup = iPickup + 1 createItemLoot("supermarket",pos[1],pos[2],pos[3],iPickup) end setTimer(createPickupsOnServerStart5,5000,1) end function createPickupsOnServerStart5() for i,pos in ipairs(pickupPositions["military"]) do iPickup = iPickup + 1 createItemLoot("military",pos[1],pos[2],pos[3],iPickup) end end createPickupsOnServerStart() ------------------------------------------------------------------------------ --OTHER ITEM STUFF vehicleFuelTable = { -- {MODEL ID, MAX. FUEL}, {422,80}, {470,100}, {468,30}, {433,140}, {437,140}, {509,0}, {487,60}, {497,60}, {453,60}, } function getVehicleMaxFuel(loot) local modelID = getElementModel(getElementData(loot,"parent")) for i,vehicle in ipairs(vehicleFuelTable) do if modelID == vehicle[1] then return vehicle[2] end end return false end function onPlayerTakeItemFromGround (itemName,col) itemPlus = 1 if itemName == "M1911 Mag" then itemPlus = 7 elseif itemName == "M9 SD Mag" then itemPlus = 15 elseif itemName == ".45ACP" then itemPlus = 7 elseif itemName == "PDW Mag" then itemPlus = 30 elseif itemName == "MP5A5 Mag" then itemPlus = 20 elseif itemName == "AK" then itemPlus = 30 elseif itemName == "STANAG" then itemPlus = 20 elseif itemName == "1866 Slug" then itemPlus = 7 elseif itemName == "2Rnd. Slug" then itemPlus = 2 elseif itemName == "SPAZ-12 Pellet" then itemPlus = 7 elseif itemName == "CZ550 Mag" then itemPlus = 5 elseif itemName == "Lee Enfield Mag" then itemPlus = 10 elseif itemName == "M136 Rocket" then itemPlus = 0 elseif itemName == "М4А1 CCO" or itemName == "AK-74" or itemName == "CZ550" or itemName == "Винчестер 1866" or itemName == "SPAZ-12 Combat Shotgun" or itemName == "Sawn-Off Shotgun" or itemName == "Heat-Seeking RPG" or itemName == "M136 Rocket Launcher" or itemName == "Lee Enfield" then removeBackWeaponOnDrop() end local x,y,z = getElementPosition(source) local id,ItemType = getItemTablePosition (itemName) setElementData(source,itemName,(getElementData(source,itemName) or 0)+itemPlus) destroyElement(getElementData(col,"parent")) destroyElement(col) end addEvent( "onPlayerTakeItemFromGround", true ) addEventHandler( "onPlayerTakeItemFromGround", getRootElement(), onPlayerTakeItemFromGround ) function onPlayerChangeLoot(loot) local players = getElementsWithinColShape (loot,"player") for theKey,player in ipairs(players) do triggerClientEvent(player,"refreshLootManual",player,loot) end end addEvent( "onPlayerChangeLoot", true ) addEventHandler( "onPlayerChangeLoot", getRootElement(), onPlayerChangeLoot ) function playerDropAItem(itemName) local x,y,z = getElementPosition(source) local item,itemString = getItemTablePosition(itemName) local itemPickup = createItemPickup(item,x+math.random(-1.25,1.25),y+math.random(-1.25,1.25),z,itemString) end addEvent( "playerDropAItem", true ) addEventHandler( "playerDropAItem", getRootElement(), playerDropAItem ) function getItemTablePosition (itema) for id, item in ipairs(itemTable[tostring("other")]) do if itema == item[1] then return id,"other" end end return item,itemString end function refreshItemLoots () outputChatBox("#ffaa00Внимание! #ffffff - Респавн лута! Просим не выходить с сервера во время NETWORK!",getRootElement(),255,255,255,true) for i, loots in ipairs(getElementsByType("colshape")) do local itemloot = getElementData(loots,"itemloot") if itemloot then local objects = getElementData(loots,"objectsINloot") if objects then if objects[1] ~= nil then destroyElement(objects[1]) end if objects[2] ~= nil then destroyElement(objects[2]) end if objects[3] ~= nil then destroyElement(objects[3]) end end destroyElement(loots) end end createPickupsOnServerStart() setTimer(refreshItemLootPoints,gameplayVariables["itemrespawntimer"] ,1) end --Refresh items function refreshItemLootPoints () local time = getRealTime() local hour = time.hour outputChatBox("#ff2200Внимание! #ffffff - Через 1 мин будет респавн лута!",getRootElement(),255,255,255,true) setTimer(refreshItemLoots,60000,1) end setTimer(refreshItemLootPoints,gameplayVariables["itemrespawntimer"] ,1) Напиши на основе двух этих скриптов инвентаря и предметов, логику крафта, чтоб меню крафта открывалось в GUI окне по команде /craft. Для примера можно сделать крафт предмета "Аптечка" из одного "Бинт" и одного "Болеутоляющего". Напиши полностью логику и выдай в виде кода!
39b901d7ddb82a722e2eaae6681ae614
{ "intermediate": 0.23563732206821442, "beginner": 0.5348477363586426, "expert": 0.22951488196849823 }
40,566
Привет! У меня есть следующий бот: import logging from aiogram import Bot, Dispatcher, executor, types from aiogram.contrib.middlewares.logging import LoggingMiddleware from aiogram.types import ReplyKeyboardMarkup, KeyboardButton import aiosqlite from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.dispatcher.filters import Text from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton from aiogram.contrib.fsm_storage.memory import MemoryStorage import asyncio import time logging.basicConfig(level=logging.INFO) API_TOKEN = '6996318383:AAEcQfdQhzEg3L_6DKQVidJEn46Wb27Sy4g' DB_NAME = 'bot.db' ADMIN_USER_ID = '989037374' # Replace with the actual admin user ID bot = Bot(token=API_TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) dp.middleware.setup(LoggingMiddleware()) whatsapp_button = KeyboardButton('Сдать WhatsApp') other_buttons = [ KeyboardButton('Личный кабинет'), KeyboardButton('Ответы на вопросы'), KeyboardButton('Партнерская программа'), KeyboardButton('Техническая поддержка'), KeyboardButton('Успешные выплаты'), KeyboardButton('Новостной канал'), ] keyboard = ReplyKeyboardMarkup(resize_keyboard=True, row_width=2) keyboard.add(whatsapp_button).add(*other_buttons) async def init_db(dispatcher): async with aiosqlite.connect(DB_NAME) as db: await db.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, username TEXT, referral_id INTEGER, balance INTEGER DEFAULT 0, frozen_balance INTEGER DEFAULT 0 ); ''') await db.execute(''' CREATE TABLE IF NOT EXISTS mamonted ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); ''') await db.execute(''' CREATE TABLE IF NOT EXISTS unidentified ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT, date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); ''') await db.execute(''' CREATE TABLE IF NOT EXISTS last_notification ( user_id INTEGER PRIMARY KEY, last_notified TIMESTAMP DEFAULT (strftime('%s', 'now')) ); ''') await db.commit() async def get_user(user_id): async with aiosqlite.connect(DB_NAME) as db: async with db.execute('SELECT id FROM users WHERE id = ?', (user_id,)) as cursor: return await cursor.fetchone() async def add_user(user_id, username, referral_id=None): async with aiosqlite.connect(DB_NAME) as db: # Добавлен в базу данных новый пользователь await db.execute('INSERT INTO users (id, username, referral_id) VALUES (?, ?, ?)', (user_id, username, referral_id)) await db.commit() # Если есть реферальный ID, осуществляем начисление бонуса рефереру и уведомление его о новом пользователе if referral_id: # Начисляем бонус рефереру await db.execute('UPDATE users SET frozen_balance = frozen_balance + 200 WHERE id = ?', (referral_id,)) await db.commit() # Получаем информацию о реферере referrer = await db.execute('SELECT username FROM users WHERE id = ?', (referral_id,)) referrer_username = (await referrer.fetchone())[0] referrer_username = "@" + referrer_username if referrer_username else str(referral_id) # Формируем имя/ID нового пользователя для сообщения new_user_display_name = f"@{username}" if username else f"UserID {user_id}" bonus_text = f""" ☘️ По вашей ссылке зарегистрировался новый пользователь - {new_user_display_name} 💰 На ваш баланс зачислено 200р ❌ Вывод закрыт до тех пор, пока ваш друг не сдаст аккаунт. """ await bot.send_message(referral_id, bonus_text) @dp.message_handler(commands=['start']) async def process_start_command(message: types.Message): referral_id = message.get_args() user_id = message.from_user.id username = message.from_user.username user = await get_user(user_id) if user: await message.answer("Приветствую тебя снова!", reply_markup=keyboard) else: if referral_id: await add_user(user_id, username, int(referral_id)) await message.answer(f"Добро пожаловать! Вас пригласил пользователь с ID: {referral_id}.", reply_markup=keyboard) else: await add_user(user_id, username) await message.answer("Вы перешли без реферальной ссылки. Пожалуйста, воспользуйтесь ею.") class WhatsAppForm(StatesGroup): photo = State() @dp.message_handler(Text(equals="Сдать WhatsApp"), state='*') async def process_whatsapp_button(message: types.Message, state: FSMContext): text = "📄 Мы рады сотрудничеству с тобой, давай расскажем тебе, как будет проходить данный процесс.\n\n📝 Тебе нужно сделать скриншот своего ватсаппа, если ты переживаешь за диалоги/контакты - это не проблема, ватсапп при входе с нового устройства, не переносит диалоги. Все еще не доверяешь? - очисти полностью ватсап, нам это не принципиально. После данных манипуляций, отправь раннее сделанный скриншот и ожидай подтверждение.\n\n🎙️ Наши условия:\n💰 2000 рублей\n🕰️ 2 часа аренды\n\n✨Желаем тебе только успешных сделок, дорогой друг." photo_path = 'photos/sdat.jpg' with open(photo_path, 'rb') as photo: await bot.send_photo(message.from_user.id, photo=photo, caption=text) await WhatsAppForm.photo.set() # Переход в состояние ожидания фотографии def approval_keyboard(user_id): markup = InlineKeyboardMarkup() approval_button = InlineKeyboardButton("Одобрить", callback_data=f"approve_{user_id}") markup.add(approval_button) return markup # Функция для обработки полученной фотографии @dp.message_handler(content_types=['photo'], state=WhatsAppForm.photo) async def handle_photo(message: types.Message, state: FSMContext): file_id = message.photo[-1].file_id user_id = message.from_user.id username = message.from_user.username or "нет username" # Отправляем фото администратору с кнопкой для одобрения await bot.send_photo( ADMIN_USER_ID, photo=file_id, caption=f"Отправил: @{username}, ID: {user_id}", reply_markup=approval_keyboard(user_id) ) await message.answer("🎁 Заявка успешно подана! Ожидайте, так как проект имеет спрос, но администратор один, у нас очереди \n\n📢 Включите уведомления, дабы не пропустить одобрение. \n\n🚨 Как только ее одобрят, напишите пожалуйста по контактам в уведомлении") await state.finish() # Завершение состояния @dp.callback_query_handler(lambda c: c.data and c.data.startswith('approve_')) async def process_approval(callback_query: types.CallbackQuery): user_id = int(callback_query.data.split('_')[1]) inline_btn = types.InlineKeyboardButton('Связаться с нами', url='https://t.me/gkldgkld') inline_kb = types.InlineKeyboardMarkup().add(inline_btn) await bot.answer_callback_query(callback_query.id) await bot.send_message(user_id, "✅Ваша заявка была одобрена администрацией проекта.\n\n📝Теперь тебе нужно написать нам, ниже у тебя кнопка, кликай на нее, напиши что-либо, чтобы отобразиться в диалогах.\n\n📍Если тебе долго не отвечает администратор, пиши чаще, так как постоянный поток людей - мешает запомнить каждого.\n\n‼️Перед этим советуем ознакомиться с «Ответы на вопросы»", reply_markup=inline_kb) # Обновляем или добавляем запись в таблицу last_notification async with aiosqlite.connect(DB_NAME) as db: await db.execute('INSERT OR REPLACE INTO last_notification (user_id) VALUES (?)', (user_id,)) await db.commit() # Обработка всех других сообщений @dp.message_handler(lambda message: not message.photo, state=WhatsAppForm.photo) async def handle_not_photo(message: types.Message, state: FSMContext): await message.reply("❌ Это не фотография. Нажмите кнопку еще раз и загрузите фотографию WhatsApp") await state.finish() # Завершение состояния def get_personal_cabinet_keyboard(): # Создаём inline-клавиатуру keyboard = InlineKeyboardMarkup() # Добавляем кнопку на эту клавиатуру withdrawal_button = InlineKeyboardButton(text="Вывести", callback_data="withdraw") keyboard.add(withdrawal_button) return keyboard @dp.callback_query_handler(Text(equals="withdraw")) async def process_withdraw(callback_query: types.CallbackQuery): await bot.answer_callback_query(callback_query.id) await bot.send_message(callback_query.from_user.id, "⛔️ Недостаточно средств, попробуйте пригласить друзей и попросите их сдать в аренду аккаунт, дабы баланс перешел в основной.\nДанное условие создано в целях защиты регистраций от ботов по реферальной ссылке.") @dp.message_handler(Text(equals="Личный кабинет")) async def personal_cabinet(message: types.Message): user_id = message.from_user.id async with aiosqlite.connect(DB_NAME) as db: async with db.execute('SELECT username, frozen_balance FROM users WHERE id = ?', (user_id,)) as cursor: user = await cursor.fetchone() if user: username = "@" + user[0] if user[0] else str(user_id) frozen_balance = user[1] text = f""" 👱🏻‍♂️ Ваш ник: {username} 💵 Ваш баланс: 0 рублей 🧊 Средств в заморозке: {frozen_balance} рублей 💡 Баланс можно заработать с помощью друзей (кликай на кнопку «Реферальная программа»), а также за WhatsApp (кликай на кнопку «Сдать WhatsApp») 💸 Успешных выводов. """ else: text = "Информация о профиле не найдена." withdrawal_keyboard = get_personal_cabinet_keyboard() # Путь к файлу изображения (проверьте, что он корректен) photo_path = 'photos/lk.jpg' # Отправляем изображение пользователю with open(photo_path, 'rb') as photo: await bot.send_photo(message.from_user.id, photo=photo, caption=text, reply_markup=withdrawal_keyboard) @dp.callback_query_handler(Text(equals="withdraw")) async def process_withdraw(callback_query: types.CallbackQuery): await bot.answer_callback_query(callback_query.id) await bot.send_message(callback_query.from_user.id, "⛔️ Недостаточно средств, попробуйте пригласить друзей и попросите их сдать в аренду аккаунт, дабы баланс перешел в основной.\nДанное условие создано в целях защиты регистраций от ботов по реферальной ссылке.") WORKER_ID = 6663889022 from aiogram.dispatcher.filters import Filter class IsWorkerFilter(Filter): async def check(self, message: types.Message): return message.from_user.id == WORKER_ID and message.forward_from is not None # Регистрируем фильтр в диспетчере dp.filters_factory.bind(IsWorkerFilter) class WorkerStates(StatesGroup): forwarding = State() start_checking = State() check_username = State() skip_user = State() @dp.message_handler(commands=['check_user'], state='*') async def check_user(message: types.Message): await message.answer("Перешлите мне сообщение от пользователя, чтобы я мог его проверить.") await WorkerStates.forwarding.set() @dp.message_handler(IsWorkerFilter(), content_types=types.ContentTypes.ANY) async def forwarding_received(message: types.Message, state: FSMContext): if message.forward_from: # пользователь не скрыл настройки пересылки user_id = message.forward_from.id # Сохраняем в таблицу mamonted await add_to_mamonted(user_id) await message.answer("ID пользователя сохранён в таблице mamonted.") else: # пользователь скрыл настройки пересылки await message.answer("Пользователь скрыл настройки пересылки. Проверьте наличие username или пропустите пользователя.") markup = InlineKeyboardMarkup() markup.add(InlineKeyboardButton("Пропустить", callback_data="skip_user")) markup.add(InlineKeyboardButton("Проверить username", callback_data="check_username")) await message.answer("Выберите действие:", reply_markup=markup) await WorkerStates.start_checking.set() @dp.callback_query_handler(Text(equals="skip_user"), state=WorkerStates.start_checking) async def process_skip_user(callback_query: types.CallbackQuery): await WorkerStates.skip_user.set() await callback_query.message.answer("Введите имя пользователя для сохранения в таблицу неопределенных:") await bot.answer_callback_query(callback_query.id) @dp.callback_query_handler(Text(equals="check_username"), state=WorkerStates.start_checking) async def process_check_username(callback_query: types.CallbackQuery): await WorkerStates.check_username.set() await callback_query.message.answer("Введите username пользователя для проверки:") await bot.answer_callback_query(callback_query.id) @dp.message_handler(state=WorkerStates.skip_user) async def handle_skip_user(message: types.Message, state: FSMContext): user_name = message.text # Сохраняем в таблицу unidentified await add_to_unidentified(user_name) await message.answer(f"Имя пользователя '{user_name}' сохранено в таблице неопределенных.") await state.finish() @dp.message_handler(state=WorkerStates.check_username) async def handle_check_username(message: types.Message, state: FSMContext): raw_username = message.text username = raw_username.lstrip('@') user_id = await get_user_id_by_username(username) if user_id: # Нашли username, сохраняем в mamonted await add_to_mamonted(user_id) await message.answer("ID пользователя сохранён в таблице mamonted.") else: # Username не найден, сохраняем в unidentified await add_to_unidentified(username) await message.answer(f"Username '{username}' не найден и сохранён в таблице неопределенных.") await state.finish() async def add_to_mamonted(user_id): async with aiosqlite.connect(DB_NAME) as db: await db.execute('INSERT INTO mamonted (user_id) VALUES (?)', (user_id,)) await db.commit() async def add_to_unidentified(user_name): async with aiosqlite.connect(DB_NAME) as db: await db.execute('INSERT INTO unidentified (user_name) VALUES (?)', (user_name,)) await db.commit() async def get_user_id_by_username(username): user_id = None async with aiosqlite.connect(DB_NAME) as db: async with db.execute('SELECT id FROM users WHERE username = ?', (username,)) as cursor: row = await cursor.fetchone() if row: user_id = row[0] return user_id @dp.message_handler(lambda message: message.from_user.id == WORKER_ID and message.forward_from is None, content_types=types.ContentTypes.ANY) async def message_from_worker(message: types.Message, state: FSMContext): # Пользователь скрыл настройки пересылки. # Отправка inline кнопок для дальнейших действий. markup = InlineKeyboardMarkup(row_width=2) skip_button = InlineKeyboardButton(text="Пропустить", callback_data="skip_user") check_button = InlineKeyboardButton(text="Проверить username", callback_data="check_username") markup.add(skip_button, check_button) await message.answer( "Не удалось получить информацию о пользователе. Выберите действие:", reply_markup=markup ) # Вы можете или установить состояние для FSM, если это необходимо, или просто обработать ответы инлайн-кнопок await WorkerStates.start_checking.set() # Только если используете FSM для отслеживания следующего шага @dp.message_handler(commands=['load']) async def load_mamonted(message: types.Message): # Замените на вашего администратора ID if message.from_user.id != int(ADMIN_USER_ID): await message.reply("Вы не имеете права использовать эту команду.") return async with aiosqlite.connect(DB_NAME) as db: # Получаем всех пользователей из таблицы mamonted async with db.execute("SELECT DISTINCT user_id FROM mamonted") as cursor: mamonted_users = await cursor.fetchall() # Переводим список кортежей в список user_id, используя set для удаления дубликатов mamonted_user_ids = set(user_id[0] for user_id in mamonted_users) # Формируем строку из уникальных user_id, каждый ID с новой строки users_to_send = '\n'.join(str(user_id) for user_id in sorted(mamonted_user_ids)) if users_to_send: # Отправляем сообщение с user_id администратору await message.reply(f"\n{users_to_send}") else: await message.reply("Таблица mamonted пуста.") # Очищаем таблицу mamonted await db.execute("DELETE FROM mamonted") await db.commit() @dp.message_handler(commands=['add'], user_id=int(ADMIN_USER_ID)) async def add_mamonted_id(message: types.Message): # Проверка, что пользователь является администратором if str(message.from_user.id) == ADMIN_USER_ID: # Извлекаем текст сообщения и разделяем его на слова message_text = message.get_args() # Получаем ID как список строк ids_to_add = message_text.strip().split() # Проходим через каждый помещаемый ID for id_str in ids_to_add: # Проверяем, что каждый ввод - это действительное число if id_str.isdigit(): # Переводим строку в число user_id = int(id_str) # Добавляем ID в таблицу mamonted async with aiosqlite.connect(DB_NAME) as db: await db.execute('INSERT INTO mamonted (user_id) VALUES (?)', (user_id,)) await db.commit() # Отправляем уведомление о том, что ID добавлен await message.reply(f"ID {user_id} добавлен в список.") else: # Если один из вводов не является числом, отвечаем соответствующим сообщением await message.reply(f"'{id_str}' не является допустимым ID. Пожалуйста, убедитесь, что вы вводите только числа.") @dp.message_handler(commands=['und'], user_id=int(ADMIN_USER_ID)) async def unload_unidentified(message: types.Message): # Проверяем, что команду вызвал воркер if message.from_user.id == int(ADMIN_USER_ID): async with aiosqlite.connect(DB_NAME) as db: # Получаем все имена неопределенных пользователей async with db.execute("SELECT user_name FROM unidentified") as cursor: users = await cursor.fetchall() # Формируем сообщение с именами для отправки users_list = '\n'.join(user_name for user_name, in users) if users_list: # Если список не пуст, отправляем сообщение await message.reply(users_list) # Очищаем таблицу неопределенных пользователей await db.execute("DELETE FROM unidentified") await db.commit() else: # Если таблица пуста, сообщаем об этом воркеру await message.reply("Нет неопределенных пользователей для выгрузки.") async def send_periodic_notifications(): while True: current_time = int(time.time()) async with aiosqlite.connect(DB_NAME) as db: # Выбираем пользователей, которым нужно отправить уведомление и которые не находятся в mamonted async with db.execute(""" SELECT user_id FROM last_notification WHERE last_notified <= ? AND user_id NOT IN (SELECT user_id FROM mamonted) """, (current_time - 86400,)) as cursor: users_to_notify = await cursor.fetchall() for (user_id,) in users_to_notify: # Отправляем уведомление каждому пользователю inline_btn = types.InlineKeyboardButton('Связаться с нами', url='https://t.me/gkldgkld') inline_kb = types.InlineKeyboardMarkup().add(inline_btn) try: await bot.send_message(user_id, "✅Ваша заявка была одобрена администрацией проекта.\n\n📝Теперь тебе нужно написать нам, ниже у тебя кнопка, кликай на нее, напиши что-либо, чтобы отобразиться в диалогах.\n\n📍Если тебе долго не отвечает администратор, пиши чаще, так как постоянный поток людей - мешает запомнить каждого.\n\n‼️Перед этим советуем ознакомиться с «Ответы на вопросы»", reply_markup=inline_kb) # Обновляем время уведомления для пользователя await db.execute('UPDATE last_notification SET last_notified = ? WHERE user_id = ?', (current_time, user_id)) await db.commit() except Exception as e: logging.error(f"Could not send message to user {user_id}: {e}") async def on_startup(dispatcher: Dispatcher): asyncio.create_task(send_periodic_notifications()) await init_db(dispatcher) if __name__ == '__main__': executor.start_polling(dp, skip_updates=True, on_startup=init_db) Мне надо сделать так, чтобы когда человек отправил заявку, его рефферу отправялось сообщение "Ваш друг [@username если есть] (ID: [id]) подал заявку на сдачу WhatsApp." @username - если есть у пользователя, id - если нет
0fb9ebfb4b7dca22ca3ffc6e55f41b06
{ "intermediate": 0.31720083951950073, "beginner": 0.5206270813941956, "expert": 0.16217203438282013 }
40,567
what does the libfastrtps.so in ros2 do?
f5fc84127ab5423661ebbd00727a3539
{ "intermediate": 0.6114941239356995, "beginner": 0.1759781688451767, "expert": 0.21252775192260742 }
40,568
You are an expert Rust programmer. check this code: reads.par_iter().for_each(|(chr, txs)| { let cn = consensus.get(chr).unwrap(); txs.par_iter().for_each(|tx| { pseudomap(cn, tx); }); }); where pseudomap is: fn pseudomap(consensus: &ConsensusTx, tx: &Transcript) { let mut tx_exs = tx.2.iter().collect::<Vec<_>>(); tx_exs.par_sort_unstable_by_key(|x| (x.0, x.1)); consensus.par_iter().any(|(start, end, exons)| { if tx.0 >= *start - BOUNDARY && tx.1 <= *end + BOUNDARY { // read is within the boundaries of a consensus group let mut acc = exons.to_owned(); let (status, matches) = cmp_exons(&mut acc, tx_exs.clone()); let cov = (matches.len() as f64 / acc.len() as f64) * 100.0; // match status { // Status::Pass => { // if cov >= MIN_COVERAGE { // let mut b = bucket.lock().unwrap(); // b.insert(Pocket::Pass, tx.3.clone()); // } else { // let mut b = bucket.lock().unwrap(); // b.insert(Pocket::Partial, tx.3.clone()); // } // } // Status::Fail => { // let mut b = bucket.lock().unwrap(); // b.insert(Pocket::InRet, tx.3.clone()); // } // } true } else { // start/end of read is outside of consensus boundaries -> unmapped // println!("{:?} {}-{} could not be aligned", tx.3, tx.0, tx.1); // let mut b = bucket.lock().unwrap(); // b.insert(Pocket::Unmapped, tx.3.clone()); false } }); } I am trying to use scoped threads Here is an example: let (tx, rx) = mpsc::sync_channel(num_threads); let atomic_reader = Arc::new(Mutex::new(reader.records())); info!("Spawning {} threads for Mapping.\n", num_threads); scope(|scope| { for _ in 0..num_threads { let tx = tx.clone(); let reader = Arc::clone(&atomic_reader); scope.spawn(move |_| { loop { // If work is available, do that work. match utils::get_next_record(&reader) { Some(result_record) => { let record = match result_record { Ok(record) => record, Err(err) => panic!("Error {:?} in reading fastq", err), }; ... Do you think putting the first code into this format would be better? I am trying to achieve the most fastest and efficient approach.
d0d51b0588d3b2544f746dd021f180cf
{ "intermediate": 0.3963567018508911, "beginner": 0.3123275935649872, "expert": 0.2913156747817993 }
40,569
a pseudo-code for drawing a 4x4 tic-tac-toe board with “X” or “O” text centered in some cells, using marquee elements: INITIALIZE an empty 4x4 matrix FOR each row in the matrix DO FOR each cell in the row DO IF cell is not empty THEN OUTPUT “<marquee behavior=‘alternate’ scrollamount=‘0’ bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;text-align:center;vertical-align:top;’><div style=‘width:32px;height:32px;display:flex;justify-content:center;align-items:center;color:#000;’>” IF cell contains ‘X’ THEN OUTPUT “X” ELSE IF cell contains ‘O’ THEN OUTPUT “O” END IF OUTPUT “</div></marquee>” ELSE OUTPUT “<marquee bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;vertical-align:top;’></marquee>” END IF END FOR IF row is not the last row THEN OUTPUT “<br>” END IF END FOR What this pseudo-code does: - It assumes there’s a matrix representing the state of the tic-tac-toe game, with each cell possibly empty, having an “X”, or having an “O”. - It iterates over each row and cell of the matrix. - If a cell is not empty, it outputs a &lt;marquee&gt; tag with the appropriate text (either “X” or “O”) centered inside. This &lt;marquee&gt; tag is styled to prevent any scrolling or animation and is bordered to look like a part of a grid. - If a cell is empty, it outputs an empty &lt;marquee&gt; tag styled to look like an empty cell in the grid. - After every row except the last, it outputs a &lt;br&gt; tag to create a new line for the next row of cells. This produces an HTML representation of a tic-tac-toe board using “marquee” tags where the “X” or “O” do not animate.
19801afd646d633e0607a6378db89221
{ "intermediate": 0.404908686876297, "beginner": 0.3312123715877533, "expert": 0.2638789117336273 }
40,570
Make sure that your python version >= 3.10, and you are on a cuda enabled device. Make a virtual environment on your machine and activate it. $python3 -m venv VENV_NAME source VENV_NAME/bin/activate #./VENV_NAME/scripts/activate if you are on Windows Call the following: pip install gptfast Copy the following code into a python file: import os import torch from transformers import AutoModelForCausalLM, AutoTokenizer from GPTFast.Core import gpt_fast from GPTFast.Helpers import timed torch._dynamo.reset() os.environ["TOKENIZERS_PARALLELISM"] = "false" device = "cuda" if torch.cuda.is_available() else "cpu" def argmax(self, probabilities): # Use argmax to get the token with the maximum probability max_prob_index = torch.argmax(probabilities, dim=-1) return max_prob_index.unsqueeze(0) model_name = "gpt2-xl" draft_model_name = "gpt2" tokenizer = AutoTokenizer.from_pretrained(model_name) initial_string = "Write me a short story." input_tokens = tokenizer.encode(initial_string, return_tensors="pt").to(device) N_ITERS=10 MAX_TOKENS=50 gpt_fast_model = gpt_fast(model_name, draft_model_name=draft_model_name, sample_function=argmax) gpt_fast_model.to(device) fast_compile_times = [] for i in range(N_ITERS): with torch.no_grad(): res, compile_time = timed(lambda: gpt_fast_model.generate(cur_tokens=input_tokens, max_tokens=MAX_TOKENS, speculate_k=6)) fast_compile_times.append(compile_time) print(f"gpt fast eval time {i}: {compile_time}") print("~" * 10) Run it and watch the magic 🪄! how to run it in kaggle
fbd1ef72639c6771c9cf967c3183f024
{ "intermediate": 0.37237095832824707, "beginner": 0.23893611133098602, "expert": 0.3886928856372833 }
40,571
-- menu_client.lua local theTableMenuScroll = {} function startRollMessageMenu(text, r, g, b, data) table.insert(theTableMenuScroll,{text,r,g,b,data}) end vehicleAddonsInfo = { -- {Model ID, Tires, Engine, Tank Parts} {500,4,1,1}, --Mesa {568,4,1,1}, --Bandito {512,0,1,1}, --Cropduster {476,0,1,1}, --rust {483,4,1,1}, --camper {422,4,1,1}, --Bobcat {470,4,1,1}, --Patriot {471,4,1,1}, --Quad {404,4,1,1}, --Perenniel {531,4,1,1}, --Tractor {468,2,1,1}, --Sanchez {433,6,1,1}, --Barracks {437,6,1,1}, --Coach {509,0,0,0}, --Bike {487,0,1,1}, --Maverick {497,0,1,1}, --Police Maverik {453,0,1,1} -- Reffer } function getVehicleAddonInfos (id) for i,veh in ipairs(vehicleAddonsInfo) do if veh[1] == id then return veh[2],veh[3], veh[4] end end end function dxDrawingColorTextMenuScroll(str, ax, ay, bx, by, color, alpha, scale, font, alignX, alignY) if alignX then if alignX == "center" then elseif alignX == "right" then local w = dxGetTextWidth(str:gsub("#%x%x%x%x%x%x",""), scale, font) ax = bx - w end end if alignY then if alignY == "center" then local h = dxGetFontHeight(scale, font) ay = ay + (by-ay)/2 - h/2 elseif alignY == "bottom" then local h = dxGetFontHeight(scale, font) ay = by - h end end local pat = "(.-)#(%x%x%x%x%x%x)" local s, e, cap, col = str:find(pat, 1) local last = 1 while s do if cap == "" and col then color = tocolor(tonumber("0x"..col:sub(1, 2)), tonumber("0x"..col:sub(3, 4)), tonumber("0x"..col:sub(5, 6)), alpha) end if s ~= 1 or cap ~= "" then local w = dxGetTextWidth(cap, scale, font) dxDrawText(cap, ax, ay, ax + w, by, color, scale, font) ax = ax + w color = tocolor(tonumber("0x"..col:sub(1, 2)), tonumber("0x"..col:sub(3, 4)), tonumber("0x"..col:sub(5, 6)), alpha) end last = e + 1 s, e, cap, col = str:find(pat, last) end if last <= #str then cap = str:sub(last) local w = dxGetTextWidth(cap, scale, font) dxDrawText(cap, ax, ay, ax + w, by, color, scale, font) end end local boxSpace = dxGetFontHeight(1,"default-bold")+dxGetFontHeight(1,"default-bold")*0.1 local optionsTable = { ["player"] = { {"Give Painkillers"}, {"Give Bandage"}, {"Give Morphine"}, }, } ------------------------------------------------------------------------------ --MENU function showClientMenuItem(arg1,arg2,arg3,arg4) theTableMenuScroll = {} setElementData(localPlayer,"usedItemTrue", false) numberMenuScroll = 1 if arg1 == "Take" then startRollMessageMenu("Подобрать "..arg2,50,255,50,arg2) setElementData(localPlayer,"usedItemTrue", true) end if arg1 == "stop" then disableMenu() refreshLoot(false) end if arg1 == "Helicrashsite" then startRollMessageMenu("Обыскать",255,255,255,"helicrashsite") setElementData(localPlayer,"usedItemTrue", true) end if arg1 == "Hospitalbox" then startRollMessageMenu("Содержимое",255,255,255,"hospitalbox") setElementData(localPlayer,"usedItemTrue", true) end if arg1 == "Vehicle" then startRollMessageMenu("Содержимое ("..arg2.."): "..getLootCurrentSlots(arg4).."/"..(getElementData(arg4,"MAX_Slots") or 0).." слотов",0,255,0,"vehicle") setElementData(localPlayer,"usedItemTrue", true) if getElementData(getElementData(arg3,"parent"),"tent") then startRollMessageMenu("Убрать палатку",0,255,0,"tent") return end --2 if getElementHealth(arg3) < 1000 and getElementHealth(arg3) >= 50 then startRollMessageMenu("Починить ("..arg2.."): " ..tostring(math.floor(getElementHealth(arg3)/10)).."%",0,255,0,"repairvehicle") setElementData(localPlayer,"usedItemTrue", true) end if (getElementData(arg4,"fuel") or 0) < getVehicleMaxFuel(arg4) then startRollMessageMenu("Заправить ("..tostring(math.floor(getElementData(arg4,"fuel") or 0)).."/"..getVehicleMaxFuel(arg4)..")",255,0,0,"FuelOne") setElementData(localPlayer,"usedItemTrue", true) end if (getElementData(arg4,"fuel") or 0) >= 20 then startRollMessageMenu("Слить бензин ("..tostring(math.floor(getElementData(arg4,"fuel") or 0)).."/"..getVehicleMaxFuel(arg4)..")",255,255,0,"FuelTwo") setElementData(localPlayer,"usedItemTrue", true) end local tires,engine,parts = getVehicleAddonInfos (getElementModel(arg3)) if (getElementData(arg4,"Колесо_inVehicle") or 0) < tires then startRollMessageMenu("Поставить колесо ("..(getElementData(arg4,"Колесо_inVehicle") or 0).."/"..tires..")",255,0,0,"TireOne") setElementData(localPlayer,"usedItemTrue", true) end if (getElementData(arg4,"Двигатель_inVehicle") or 0) < engine then startRollMessageMenu("Поставить двигатель ("..(getElementData(arg4,"Двигатель_inVehicle") or 0).."/"..engine..")",255,0,0,"EngineOne") setElementData(localPlayer,"usedItemTrue", true) end if (getElementData(arg4,"Parts_inVehicle") or 0) < parts then startRollMessageMenu("Поставить Бензобак ("..(getElementData(arg4,"Parts_inVehicle") or 0).."/"..parts..")",255,0,0,"PartsOne") setElementData(localPlayer,"usedItemTrue", true) end if (getElementData(arg4,"Колесо_inVehicle") or 0) > 0 then startRollMessageMenu("Снять колесо ("..(getElementData(arg4,"Колесо_inVehicle") or 0).."/"..tires..")",255,255,0,"TireTwo") setElementData(localPlayer,"usedItemTrue", true) end if (getElementData(arg4,"Двигатель_inVehicle") or 0) > 0 then startRollMessageMenu("Снять двигатель ("..(getElementData(arg4,"Двигатель_inVehicle") or 0).."/"..engine..")",255,255,0,"EngineTwo") setElementData(localPlayer,"usedItemTrue", true) end if (getElementData(arg4,"Parts_inVehicle") or 0) > 0 then startRollMessageMenu("Снять Бензобак ("..(getElementData(arg4,"Parts_inVehicle") or 0).."/"..parts..")",255,255,0,"PartsTwo") setElementData(localPlayer,"usedItemTrue", true) end end if arg1 == "Player" then --1 if getElementData(arg2,"bleeding") > 0 and getElementData(getLocalPlayer(),"Бинт") >= 1 then startRollMessageMenu("Перевязать",255,255,255,"bandage") setElementData(localPlayer,"usedItemTrue", true) end if getElementData(arg2,"blood") < 11900 and getElementData(getLocalPlayer(),"Пакет крови") >= 1 then startRollMessageMenu("Пополнить кровь",255,255,255,"giveblood") setElementData(localPlayer,"usedItemTrue", true) end end if arg1 == "Dead" then startRollMessageMenu("Содержимое ("..arg2..")",0,255,0,"dead") startRollMessageMenu("Осмотреть тело",0,255,0,"deadreason") setElementData(localPlayer,"usedItemTrue", true) end if arg1 == "Fireplace" then if getElementData(getLocalPlayer(),"Сырое мясо") >= 1 then startRollMessageMenu("Приготовить мясо",255,255,255,"fireplace") setElementData(localPlayer,"usedItemTrue", true) end end if arg1 == "patrol" then if getElementData(getLocalPlayer(),"Пустая канистра") >= 1 then startRollMessageMenu("Наполнить канистру",255,255,255,"patrolstation") setElementData(localPlayer,"usedItemTrue", true) end end if arg1 == "Wirefence" then if getElementData(getLocalPlayer(),"Инструменты") >= 1 then startRollMessageMenu("Убрать проволоку",255,255,255,"wirefence") setElementData(localPlayer,"usedItemTrue", true) end end if arg1 == "SandBags" then if getElementData(getLocalPlayer(),"Лопата") >= 1 then startRollMessageMenu("Убрать мешки с песком",255,255,255,"sandbags") setElementData(localPlayer,"usedItemTrue", true) end end if arg1 == "Mine" then if getElementData(getLocalPlayer(),"Лопата") >= 1 then startRollMessageMenu("Убрать мину",255,255,255,"wirefence") setElementData(localPlayer,"usedItemTrue", true) end end if arg1 == "Содержимое" then startRollMessageMenu("Содержимое",255,255,255,"itemloot") setElementData(localPlayer,"usedItemTrue", true) end numberMenuScroll = 1 end addEvent("showClientMenuItem",true) addEventHandler("showClientMenuItem",getLocalPlayer(),showClientMenuItem) function PlayerScrollMenuLalitka (key,keyState,arg) if getElementData(localPlayer,"usedItemTrue") then if ( keyState == "down" ) then if arg == "up" then numberMenuScroll = numberMenuScroll-1 if numberMenuScroll < 1 then numberMenuScroll = #theTableMenuScroll end elseif arg == "down" then numberMenuScroll = numberMenuScroll+1 if numberMenuScroll > #theTableMenuScroll then numberMenuScroll = 1 end end end end end bindKey ( "mouse_wheel_up", "down", PlayerScrollMenuLalitka, "up" ) bindKey ( "mouse_wheel_down", "down", PlayerScrollMenuLalitka, "down" ) function disableMenu() theTableMenuScroll = {} setElementData(localPlayer,"usedItemTrue", false) setNewbieInfo (false,"","") end addEvent("disableMenu",true) addEventHandler("disableMenu",getLocalPlayer(),disableMenu) function getPlayerInCol(tab) for theKey,thePlayer in ipairs(tab) do if thePlayer ~= getLocalPlayer() then return true end end return false end isInFirePlace = false function onPlayerTargetPickup (theElement) if theElement == getLocalPlayer() then if getElementData(source,"parent") == getLocalPlayer() then return end local player = getPlayerInCol(getElementsWithinColShape ( source, "player" )) if getPedOccupiedVehicle(getLocalPlayer()) then return end isInFirePlace = false setElementData(getLocalPlayer(),"isInFirePlace",false) if getElementData(source,"player") then showClientMenuItem("Player",getElementData(source,"parent")) setElementData(getLocalPlayer(),"currentCol",source) setElementData(getLocalPlayer(),"loot",false) return end if player then return end if getElementData(source,"patrolstation") then showClientMenuItem("patrol") setElementData(getLocalPlayer(),"currentCol",source) setElementData(getLocalPlayer(),"loot",false) setNewbieInfo (true,"АЗС","Нажмите среднюю кнопку мыши для того чтобы нполнить канистру!\n Необходима: Пустая канистра",source) return end if getElementData(source,"wirefence") then showClientMenuItem("Wirefence") setElementData(getLocalPlayer(),"currentCol",source) setElementData(getLocalPlayer(),"loot",false) setNewbieInfo (true,"Wirefence","Нажмите среднюю кнопку мыши для того чтобы убрать проволоку!\n Необходимы: Инструменты",source) return end if getElementData(source,"sandbags") then showClientMenuItem("SandBags") setElementData(getLocalPlayer(),"currentCol",source) setElementData(getLocalPlayer(),"loot",false) setNewbieInfo (true,"Мешки с песком","Нажмите среднюю кнопку мыши чтобы убрать мешки с песком!\n Требуется:Лопата",source) return end if getElementData(source,"mine") then showClientMenuItem("Mine") setElementData(getLocalPlayer(),"currentCol",source) setElementData(getLocalPlayer(),"loot",false) setNewbieInfo (true,"Мина","Нажмите среднюю кнопку мыши чтобы убрать Мину!\n Требуется:Лопата",source) return end if getElementData(source,"fireplace") then showClientMenuItem("Fireplace") setElementData(getLocalPlayer(),"currentCol",source) setElementData(getLocalPlayer(),"loot",false) setNewbieInfo (true,"Fireplace","Нажмите среднюю кнопку мыши для того чтобы приготовить мясо!\n Необходимо: Сырое мясо",source) isInFirePlace = true setElementData(getLocalPlayer(),"isInFirePlace",true) return end if getElementData(source,"deadman") then showClientMenuItem("Dead",getElementData(source,"playername")) setElementData(getLocalPlayer(),"currentCol",source) setElementData(getLocalPlayer(),"loot",true) setElementData(getLocalPlayer(),"lootname","Осмотреть ("..getElementData(source,"playername")..")") setNewbieInfo (true,"Содержимое","Нажмите J чтобы открыть инвентарь!",source) return end if getElementData(source,"item") then showClientMenuItem("Take",getElementData(source,"item")) setElementData(getLocalPlayer(),"currentCol",source) setElementData(getLocalPlayer(),"loot",false) setNewbieInfo (true,"Содержимое","Нажмите среднюю кнопку мыши чтобы подобрать предмет!",source) return end if getElementData(source,"helicrash") then showClientMenuItem("Helicrashsite","helicrash") setElementData(getLocalPlayer(),"currentCol",source) setElementData(getLocalPlayer(),"loot",true) setElementData(getLocalPlayer(),"lootname","Обыскать") --(Helicrash) setNewbieInfo (true,"Содержимое","Нажмите J чтобы открыть инвентарь!",source) return end if getElementData(source,"hospitalbox") then showClientMenuItem("Hospitalbox","hospitalbox") setElementData(getLocalPlayer(),"currentCol",source) setElementData(getLocalPlayer(),"loot",true) setElementData(getLocalPlayer(),"lootname","Обыскать (Hospitalbox)") setNewbieInfo (true,"Содержимое","Нажмите J чтобы открыть инвентарь!",source) return end if getElementData(source,"vehicle") then if not getElementData(source,"deadVehicle") then showClientMenuItem("Vehicle",(getVehicleName(getElementData(source,"parent")) or "Палатка"),getElementData(source,"parent"),source) setElementData(getLocalPlayer(),"currentCol",source) setElementData(getLocalPlayer(),"loot",true) setElementData(getLocalPlayer(),"lootname","Обыскать ("..(getVehicleName(getElementData(source,"parent")) or "Палатка")..")") setNewbieInfo (true,"Содержимое","Нажмите J чтобы открыть инвентарь!",source) return end end if getElementData(source,"itemloot") then showClientMenuItem("Содержимое") setElementData(getLocalPlayer(),"loot",true) setElementData(getLocalPlayer(),"lootname","Содержимое") setElementData(getLocalPlayer(),"currentCol",source) setNewbieInfo (true,"Содержимое","Нажмите J чтобы открыть инвентарь!",source) return end showClientMenuItem("stop") end end addEventHandler("onClientColShapeHit",getRootElement(),onPlayerTargetPickup) function onPlayerTargetPickup (theElement) if theElement == getLocalPlayer() then local players = getElementsWithinColShape ( source, "player" ) if players == getLocalPlayer() then --[[return ]]end showClientMenuItem("stop") setElementData(getLocalPlayer(),"loot",false) setElementData(getLocalPlayer(),"currentCol",false) setNewbieInfo (false,"","") isInFirePlace = false setElementData(getLocalPlayer(),"isInFirePlace",false) end end addEventHandler("onClientColShapeLeave",getRootElement(),onPlayerTargetPickup) --Newbie Infos local screenWidth, screenHeight = guiGetScreenSize() local newbieShow = false local newbieHead = "-" local newbieText = "-" local newbiePosition = 0,0,0 function setNewbieInfo (show,head,text,element) newbieShow = show newbieHead = head newbieText = text newbiePosition = element end addEventHandler("onClientRender", getRootElement(), function() local veh = getPedOccupiedVehicle (getLocalPlayer()) if veh then disableMenu() else for id, value in pairs(theTableMenuScroll) do if id == numberMenuScroll then r1menu,g1menu,b1menu = 25,153,25 else r1menu,g1menu,b1menu = 19,19,19 end dxDrawRectangle ( 0, 250+id*boxSpace, screenWidth*0.2, boxSpace, tocolor (r1menu,g1menu,b1menu,180) ) dxDrawingColorTextMenuScroll(value[1],6, 250+id*boxSpace, 6, 250+(id+1)*boxSpace, tocolor(value[2],value[3],value[4],170),170, 1, "default-bold", "center", "center") end end if newbieShow == false then return end local x,y,z = getElementPosition(newbiePosition) local x,y = getScreenFromWorldPosition (x,y,z) local length = dxGetTextWidth(newbieText,1,"default-bold") if x then dxDrawingColorText(newbieHead,x-length/2-screenWidth*0.01,y, x+length/2+screenWidth*0.01, y+screenHeight*0.03, tocolor(22,255,22,120),0.5, 1.1, "default-bold", "center", "center") dxDrawingColorText(newbieText,x-length/2-screenWidth*0.01,y+screenHeight*0.03, x+length/2+screenWidth*0.01, y+screenHeight*0.07, tocolor(22,255,22,120),0.5, 1, "default-bold", "center", "center") end end ) function fireRaiseTemperature () if isInFirePlace then if getElementData(getLocalPlayer(),"temperature") <= 38 then setElementData(getLocalPlayer(),"temperature",getElementData(getLocalPlayer(),"temperature")+0.25) end end end setTimer(fireRaiseTemperature,10000,0) ------------------------------------------------------------------------------ unbindKey("mouse3","both") function onPlayerPressMiddleMouse (key,keyState) if ( keyState == "down" ) then if not getElementData(localPlayer,"usedItemTrue") then return end local itemName = getMenuMarkedItem() if itemName == "helicrashsite" then local col = getElementData(getLocalPlayer(),"currentCol") local gearName = "Обыскать (Helicrash)" -- Helicrash refreshLoot(col,gearName) showInventoryManual() return end if itemName == "itemloot" then local col = getElementData(getLocalPlayer(),"currentCol") local gearName = "Содержимое" refreshLoot(col,gearName) showInventoryManual() return end if itemName == "wirefence" then local col = getElementData(getLocalPlayer(),"currentCol") local gearName = "Remove Wirefence" triggerServerEvent("removeWirefence",getLocalPlayer(),getElementData(col,"parent")) disableMenu() return end if itemName == "sandbags" then local col = getElementData(getLocalPlayer(),"currentCol") local gearName = "Убрать мешки с песком" triggerServerEvent("removeSandBags",getLocalPlayer(),getElementData(col,"parent")) disableMenu() return end if itemName == "mine" then local col = getElementData(getLocalPlayer(),"currentCol") local gearName = "Убрать мину" triggerServerEvent("removeSandBags",getLocalPlayer(),getElementData(col,"parent")) disableMenu() return end if itemName == "hospitalbox" then local col = getElementData(getLocalPlayer(),"currentCol") local gearName = "Обыскать (Hospitalbox)" refreshLoot(col,gearName) showInventoryManual() return end if itemName == "vehicle" then local col = getElementData(getLocalPlayer(),"currentCol") local gearName = "Обыскать ("..(getVehicleName(getElementData(col,"parent")) or "Палатка")..")" refreshLoot(col,gearName) showInventoryManual() return end if itemName == "repairvehicle" then if getElementData(getLocalPlayer(),"Инструменты") >= 1 then local col = getElementData(getLocalPlayer(),"currentCol") triggerServerEvent("repairVehicle",getLocalPlayer(),getElementData(col,"parent")) else startRollMessage2("Inventory", "У Вас нет Инструментов!", 255, 22, 0 ) end disableMenu() return end if itemName == "FuelOne" then if (getElementData(getLocalPlayer(),"Наполненная канистра") or 0) >= 1 then local col = getElementData(getLocalPlayer(),"currentCol") if getElementData(col,"fuel")+20 < getVehicleMaxFuel(col) then addingfuel = 20 elseif getElementData(col,"fuel")+20 > getVehicleMaxFuel(col)+15 then triggerEvent ("displayClientInfo", getLocalPlayer(),"Vehicle","Бак полный!",255,22,0) disableMenu() return else addingfuel = getVehicleMaxFuel(col)-getElementData(col,"fuel") end if (getElementData(col,"Parts_inVehicle") or 0) < 1 then addingfuel = addingfuel/3 triggerEvent ("displayClientInfo", getLocalPlayer(),"Vehicle","Из транспорта вылилась часть бензина!",22,255,0) end setElementData(getLocalPlayer(),"Наполненная канистра",getElementData(getLocalPlayer(),"Наполненная канистра")-1) setElementData(getLocalPlayer(),"Пустая канистра",(getElementData(getLocalPlayer(),"Пустая канистра") or 0)+1) setElementData(col,"fuel",getElementData(col,"fuel")+addingfuel) --triggerServerEvent("AnimAddFuel", getLocalPlayer(), getLocalPlayer()) triggerEvent ("displayClientInfo", getLocalPlayer(),"Vehicle","Транспорт заправлен на "..addingfuel.." л.!",22,255,0) else startRollMessage2("Inventory", "У Вас нет пустой канистры!", 255, 22, 0 ) end disableMenu() return end if itemName == "FuelTwo" then if (getElementData(getLocalPlayer(),"Пустая канистра") or 0) >= 1 then local col = getElementData(getLocalPlayer(),"currentCol") setElementData(getLocalPlayer(),"Наполненная канистра",getElementData(getLocalPlayer(),"Наполненная канистра")+1) setElementData(getLocalPlayer(),"Пустая канистра",(getElementData(getLocalPlayer(),"Пустая канистра") or 0)-1) --triggerServerEvent("AnimAddFuel", getLocalPlayer(), getLocalPlayer()) setElementData(col,"fuel",getElementData(col,"fuel")-20) triggerEvent ("displayClientInfo", getLocalPlayer(),"Vehicle","Вы слили 20л. бензина!",22,255,0) else startRollMessage2("Inventory", "У Вас нет пустой канистры!", 255, 22, 0 ) end disableMenu() return end if itemName == "TireOne" then if getElementData(getLocalPlayer(),"Инструменты") >= 1 then if (getElementData(getLocalPlayer(),"Колесо") or 0) > 0 then local col = getElementData(getLocalPlayer(),"currentCol") setElementData(col,"Колесо_inVehicle",(getElementData(col,"Колесо_inVehicle") or 0)+1) setElementData(getLocalPlayer(),"Колесо",(getElementData(getLocalPlayer(),"Колесо") or 0)-1) --triggerServerEvent("AnimAddFuel", getLocalPlayer(), getLocalPlayer()) startRollMessage2("Inventory", "Вы поставили одно колесо!", 22, 255, 0 ) else startRollMessage2("Inventory", "У Вас нет колес!", 255, 22, 0 ) end else startRollMessage2("Inventory", "У Вас нет Инструментов!", 255, 22, 0 ) end disableMenu() return end if itemName == "TireTwo" then if getElementData(getLocalPlayer(),"Инструменты") >= 1 then local col = getElementData(getLocalPlayer(),"currentCol") if (getElementData(col,"Колесо_inVehicle") or 0) > 0 then local col = getElementData(getLocalPlayer(),"currentCol") setElementData(col,"Колесо_inVehicle",(getElementData(col,"Колесо_inVehicle") or 0)-1) setElementData(getLocalPlayer(),"Колесо",(getElementData(getLocalPlayer(),"Колесо") or 0)+1) --triggerServerEvent("AnimAddFuel", getLocalPlayer(), getLocalPlayer()) startRollMessage2("Inventory", "Вы сняли одно колесо!", 22, 255, 0 ) else startRollMessage2("Inventory", "В транспорте нет колес!", 255, 22, 0 ) end else startRollMessage2("Inventory", "У Вас нет Инструментов!", 255, 22, 0 ) end disableMenu() return end if itemName == "EngineOne" then if getElementData(getLocalPlayer(),"Инструменты") >= 1 then if (getElementData(getLocalPlayer(),"Двигатель") or 0) > 0 then local col = getElementData(getLocalPlayer(),"currentCol") setElementData(col,"Двигатель_inVehicle",(getElementData(col,"Двигатель_inVehicle") or 0)+1) setElementData(getLocalPlayer(),"Двигатель",(getElementData(getLocalPlayer(),"Двигатель") or 0)-1) ---triggerServerEvent("AnimAddFuel", getLocalPlayer(), getLocalPlayer()) startRollMessage2("Inventory", "Вы поставили один двигатель!", 22, 255, 0 ) else startRollMessage2("Inventory", "У Вас нет двигателя!", 255, 22, 0 ) end else startRollMessage2("Inventory", "У Вас нет Инструментов!", 255, 22, 0 ) end disableMenu() return end if itemName == "EngineTwo" then if getElementData(getLocalPlayer(),"Инструменты") >= 1 then local col = getElementData(getLocalPlayer(),"currentCol") if (getElementData(col,"Двигатель_inVehicle") or 0) > 0 then local col = getElementData(getLocalPlayer(),"currentCol") setElementData(col,"Двигатель_inVehicle",(getElementData(col,"Двигатель_inVehicle") or 0)-1) setElementData(getLocalPlayer(),"Двигатель",(getElementData(getLocalPlayer(),"Двигатель") or 0)+1) --triggerServerEvent("AnimAddFuel", getLocalPlayer(), getLocalPlayer()) startRollMessage2("Inventory", "Вы сняли один двигатель!", 22, 255, 0 ) else startRollMessage2("Inventory", "В транспорте нет двигателя!", 255, 22, 0 ) end else startRollMessage2("Inventory", "У Вас нет Инструментов!", 255, 22, 0 ) end disableMenu() return end if itemName == "PartsOne" then if getElementData(getLocalPlayer(),"Инструменты") >= 1 then if (getElementData(getLocalPlayer(),"Бензобак") or 0) > 0 then local col = getElementData(getLocalPlayer(),"currentCol") setElementData(col,"Parts_inVehicle",(getElementData(col,"Parts_inVehicle") or 0)+1) setElementData(getLocalPlayer(),"Бензобак",(getElementData(getLocalPlayer(),"Бензобак") or 0)-1) --triggerServerEvent("AnimAddFuel", getLocalPlayer(), getLocalPlayer()) startRollMessage2("Inventory", "Вы поставили Бензобак!", 22, 255, 0 ) else startRollMessage2("Inventory", "У Вас нет Бензобака!", 255, 22, 0 ) end else startRollMessage2("Inventory", "У Вас нет Инструментов!", 255, 22, 0 ) end disableMenu() return end if itemName == "PartsTwo" then if getElementData(getLocalPlayer(),"Инструменты") >= 1 then local col = getElementData(getLocalPlayer(),"currentCol") if (getElementData(col,"Parts_inVehicle") or 0) > 0 then local col = getElementData(getLocalPlayer(),"currentCol") setElementData(col,"Parts_inVehicle",(getElementData(col,"Parts_inVehicle") or 0)-1) setElementData(getLocalPlayer(),"Бензобак",(getElementData(getLocalPlayer(),"Бензобак") or 0)+1) --triggerServerEvent("AnimAddFuel", getLocalPlayer(), getLocalPlayer()) startRollMessage2("Inventory", "Вы сняли Бензобак!", 22, 255, 0 ) else startRollMessage2("Inventory", "В транспорте нет Бензобака!", 255, 22, 0 ) end else startRollMessage2("Inventory", "У Вас нет Инструментов!", 255, 22, 0 ) end disableMenu() return end if itemName == "tent" then local col = getElementData(getLocalPlayer(),"currentCol") triggerServerEvent("removeTent",getLocalPlayer(),getElementData(col,"parent")) disableMenu() return end if itemName == "fireplace" then local col = getElementData(getLocalPlayer(),"currentCol") triggerServerEvent("addPlayerCookMeat",getLocalPlayer()) disableMenu() return end if itemName == "бинт" then local col = getElementData(getLocalPlayer(),"currentCol") triggerServerEvent("onPlayerGiveMedicObject",getLocalPlayer(),itemName,getElementData(col,"parent")) disableMenu() return end if itemName == "giveblood" then local col = getElementData(getLocalPlayer(),"currentCol") triggerServerEvent("onPlayerGiveMedicObject",getLocalPlayer(),itemName,getElementData(col,"parent")) disableMenu() return end if itemName == "dead" then local col = getElementData(getLocalPlayer(),"currentCol") local gearName = "Содержимое ("..getElementData(col,"playername")..")" refreshLoot(col,gearName) showInventoryManual() return end if itemName == "deadreason" then local col = getElementData(getLocalPlayer(),"currentCol") outputChatBox(getElementData(col,"deadreason"),255,255,255,true) return end if itemName == "patrolstation" then local col = getElementData(getLocalPlayer(),"currentCol") setPedAnimation (getLocalPlayer(),"BOMBER","BOM_Plant",nil,false,false,nil,false) setElementData(getLocalPlayer(),"Пустая канистра",getElementData(getLocalPlayer(),"Пустая канистра")-1) setElementData(getLocalPlayer(),"Наполненная канистра",(getElementData(getLocalPlayer(),"Наполненная канистра") or 0)+1) triggerEvent ("displayClientInfo",getLocalPlayer(),"patrolstation","Канистра заполнена!",22,255,0) disableMenu() return end if isToolbeltItem(itemName) then local col = getElementData(getLocalPlayer(), "currentCol") if #getElementsWithinColShape(col, "player") > 1 or getNetworkStats().packetlossLastSecond > 1 then return end x, y, z = getElementPosition(getLocalPlayer()) if pcount ~= nil and pcount < getTickCount() then pcount = getTickCount() + math.random(1800,2200) x, y, z = getElementPosition(getLocalPlayer()) return false elseif pcount == nil then pcount = getTickCount() + math.random(1800,2200) x, y, z = getElementPosition(getLocalPlayer()) return false end local x1, y1, z1 = getElementPosition(getLocalPlayer()) if x1 ~= x or y1 ~= y or z1 ~= z then pcount = nil return false end pcount = nil triggerServerEvent("onPlayerTakeItemFromGround", getLocalPlayer(), itemName, col) disableMenu() return end if itemName == "Assault Pack (ACU)" or itemName == "Alice Pack" or itemName == "Czech Backpack" or itemName == "Рюкзак Military" or itemName =="Serial Backpack" or itemName == "Coyote Backpack" then local col = getElementData(getLocalPlayer(),"currentCol") triggerServerEvent("onPlayerTakeItemFromGround",getLocalPlayer(),itemName,col) disableMenu() return end if getPlayerCurrentSlots() + getItemSlots(itemName) <= getPlayerMaxAviableSlots() then local col = getElementData(getLocalPlayer(), "currentCol") if #getElementsWithinColShape(col, "player") > 1 or getNetworkStats().packetlossLastSecond > 1 then return end x, y, z = getElementPosition(getLocalPlayer()) if pcount ~= nil and pcount < getTickCount() then pcount = getTickCount() + math.random(1800,2200) x, y, z = getElementPosition(getLocalPlayer()) return false elseif pcount == nil then pcount = getTickCount() + math.random(1800,2200) x, y, z = getElementPosition(getLocalPlayer()) return false end local x1, y1, z1 = getElementPosition(getLocalPlayer()) if x1 ~= x or y1 ~= y or z1 ~= z then pcount = nil return false end pcount = nil triggerServerEvent("onPlayerTakeItemFromGround", getLocalPlayer(), itemName, col) disableMenu() else startRollMessage2("Inventory", "Инвентарь заполнен!", 255, 22, 0) end end end bindKey ( "mouse3", "down", onPlayerPressMiddleMouse ) bindKey ( "-", "down", onPlayerPressMiddleMouse ) function getMenuMarkedItem() for i,guiItem in ipairs(spalteGuiText) do if getElementData(guiItem,"markedMenuItem") then return getElementData(guiItem,"usedItem") end end end function playerPressedKey(button, press) if (press) then if button == "w" or button == "a" or button == "s" or button == "d" then local anim,anim2 = getPedAnimation (getLocalPlayer()) if anim and anim == "SCRATCHING" and anim2 == "sclng_r" then triggerServerEvent("onClientMovesWhileAnimation",getLocalPlayer()) end end end end function getMenuMarkedItem() for id, value in pairs(theTableMenuScroll) do if id == numberMenuScroll then return value[5] end end end Нужно дополнить эту логику чем-то нужным, сложным, необычным и интересным, предложи три нововведения и выдай это в виде кода
0b7eca264ed6248583c0711bff891182
{ "intermediate": 0.26994991302490234, "beginner": 0.44522160291671753, "expert": 0.28482845425605774 }
40,572
How do I create a window in C using wayland?
4f4073f89a4f369847bd2548f0fb494a
{ "intermediate": 0.6490116119384766, "beginner": 0.12178932130336761, "expert": 0.22919900715351105 }
40,573
you are an expert rust programmer. what do you think about this: use rayon::prelude::*; use std::sync::{Arc, Mutex}; use std::thread; use crossbeam_channel::{bounded, Sender}; // Define a type alias for the consensus map type ConsensusMap = std::collections::HashMap<char, ConsensusTx>; // Define a type alias for the transaction vector type TxVec = Vec<(u32, u32, Vec<(u32, u32)>, String)>; // Define a struct to hold the shared state struct SharedState { consensus: Arc<Mutex<ConsensusMap>>, bucket: Arc<Mutex<TxVec>>, } // Define the pseudomap function fn pseudomap(consensus: &ConsensusTx, tx: &Transcript, shared_state: &SharedState) { let mut tx_exs = tx.2.iter().collect::<Vec<_>>(); tx_exs.par_sort_unstable_by_key(|x| (x.0, x.1)); let result = consensus.iter().any(|(start, end, exons)| { if tx.0 >= *start - BOUNDARY && tx.1 <= *end + BOUNDARY { // read is within the boundaries of a consensus group let mut acc = exons.to_owned(); let (status, matches) = cmp_exons(&mut acc, tx_exs.clone()); let cov = (matches.len() as f64 / acc.len() as f64) * 100.0; match status { Status::Pass => { if cov >= MIN_COVERAGE { let mut bucket = shared_state.bucket.lock().unwrap(); bucket.insert(Pocket::Pass, tx.3.clone()); } else { let mut bucket = shared_state.bucket.lock().unwrap(); bucket.insert(Pocket::Partial, tx.3.clone()); } } Status::Fail => { let mut bucket = shared_state.bucket.lock().unwrap(); bucket.insert(Pocket::InRet, tx.3.clone()); } } true } else { // start/end of read is outside of consensus boundaries -> unmapped let mut bucket = shared_state.bucket.lock().unwrap(); bucket.insert(Pocket::Unmapped, tx.3.clone()); false } }); // Return the result to the main thread let mut bucket = shared_state.bucket.lock().unwrap(); bucket.push((tx.3.clone(), result)); } // Define the main function fn main() { // Initialize the shared state let consensus: ConsensusMap = // initialize the consensus map let bucket: TxVec = Vec::new(); let shared_state = SharedState { consensus: Arc::new(Mutex::new(consensus)), bucket: Arc::new(Mutex::new(bucket)), }; // Create a channel for sending work to the worker threads let (tx, rx) = bounded(num_threads); // Spawn the worker threads let mut threads = Vec::new(); for _ in 0..num_threads { let tx = tx.clone(); let shared_state = Arc::clone(&shared_state); let handle = thread::spawn(move || { loop { // Receive work from the main thread let (chr, txs) = rx.recv().unwrap(); // Process the work let consensus = shared_state.consensus.lock().unwrap(); let cn = consensus.get(&chr).unwrap(); txs.par_iter().for_each(|tx| { pseudomap(cn, tx, &shared_state); }); } }); threads.push(handle); } // Send the work to the worker threads reads.par_iter().for_each(|(chr, txs)| { let tx = tx.clone(); tx.send((*chr, txs.clone())).unwrap(); }); // Wait for the worker threads to finish
5e8281ae5e2f2613ec53ab07de7807cd
{ "intermediate": 0.38902175426483154, "beginner": 0.43142327666282654, "expert": 0.1795550435781479 }
40,574
Let's imaging the case where tcp buffers have a size of 1000000 bytes, what's size of initial tcp window would be in the case on Linux?
0ba88947a048693ac4b8139289e11258
{ "intermediate": 0.4646115303039551, "beginner": 0.1858726590871811, "expert": 0.34951576590538025 }
40,575
This prompt is written in Prompton, a language much like Python except with a custom string syntax for prompt expressions, they look like this: prompt'What is 2 + 2?' These prompt expressions can be assigned to variables, interpolated like f-strings, etc., but unlike strings they contain the result of running that expression. For the example above, the expected value would be 4. result = prompt'What day is it today?' print(result)
477a858c10b20dfc8d009eaec8f667ce
{ "intermediate": 0.2140214592218399, "beginner": 0.630251944065094, "expert": 0.1557265669107437 }
40,576
Prove that for any points K, L, M, T the equality MK + LM LT + TK holds.
754e8e32d21d2fb4a427a9bd46574fcc
{ "intermediate": 0.31543633341789246, "beginner": 0.18687878549098969, "expert": 0.49768489599227905 }
40,577
don't write this code in chat, do it in chat as stated: """a pseudo-code for drawing a 4x4 tic-tac-toe board with “X” or “O” text centered in some cells, using marquee elements: INITIALIZE an empty 4x4 matrix FOR each row in the matrix DO FOR each cell in the row DO IF cell is not empty THEN OUTPUT “<marquee behavior=‘alternate’ scrollamount=‘0’ bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;text-align:center;vertical-align:top;’><div style=‘width:32px;height:32px;display:flex;justify-content:center;align-items:center;color:#000;’>” IF cell contains ‘X’ THEN OUTPUT “X” ELSE IF cell contains ‘O’ THEN OUTPUT “O” END IF OUTPUT “</div></marquee>” ELSE OUTPUT “<marquee bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;vertical-align:top;’></marquee>” END IF END FOR IF row is not the last row THEN OUTPUT “<br>” END IF END FOR What this pseudo-code does: - It assumes there’s a matrix representing the state of the tic-tac-toe game, with each cell possibly empty, having an “X”, or having an “O”. - It iterates over each row and cell of the matrix. - If a cell is not empty, it outputs a &lt;marquee&gt; tag with the appropriate text (either “X” or “O”) centered inside. This &lt;marquee&gt; tag is styled to prevent any scrolling or animation and is bordered to look like a part of a grid. - If a cell is empty, it outputs an empty &lt;marquee&gt; tag styled to look like an empty cell in the grid. - After every row except the last, it outputs a &lt;br&gt; tag to create a new line for the next row of cells. This produces an HTML representation of a tic-tac-toe board using “marquee” tags where the “X” or “O” do not animate.""". don't describe or explain anything in chat, do as stated directly in chat.
101a62250d495a1d97c889faf58ca4e2
{ "intermediate": 0.340238481760025, "beginner": 0.4090641140937805, "expert": 0.2506973445415497 }
40,578
box cox cant be used on negative and 0 values right
94559d3e6c9e9899a380832ba41160b6
{ "intermediate": 0.31256821751594543, "beginner": 0.41094672679901123, "expert": 0.2764851450920105 }
40,579
don’t write this code in chat, do it in chat as stated: “”“a pseudo-code for drawing a 4x4 tic-tac-toe board with “X” or “O” text centered in some cells, using marquee elements: INITIALIZE an empty 4x4 matrix FOR each row in the matrix DO FOR each cell in the row DO IF cell is not empty THEN OUTPUT “<marquee behavior=‘alternate’ scrollamount=‘0’ bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;text-align:center;vertical-align:top;’><div style=‘width:32px;height:32px;display:flex;justify-content:center;align-items:center;color:#000;’>” IF cell contains ‘X’ THEN OUTPUT “X” ELSE IF cell contains ‘O’ THEN OUTPUT “O” END IF OUTPUT “</div></marquee>” ELSE OUTPUT “<marquee bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;vertical-align:top;’></marquee>” END IF END FOR IF row is not the last row THEN OUTPUT “<br>” END IF END FOR What this pseudo-code does: - It assumes there’s a matrix representing the state of the tic-tac-toe game, with each cell possibly empty, having an “X”, or having an “O”. - It iterates over each row and cell of the matrix. - If a cell is not empty, it outputs a <marquee> tag with the appropriate text (either “X” or “O”) centered inside. This <marquee> tag is styled to prevent any scrolling or animation and is bordered to look like a part of a grid. - If a cell is empty, it outputs an empty <marquee> tag styled to look like an empty cell in the grid. - After every row except the last, it outputs a <br> tag to create a new line for the next row of cells. This produces an HTML representation of a tic-tac-toe board using “marquee” tags where the “X” or “O” do not animate.”“”. don’t describe or explain anything in chat, do as stated directly in chat. the very first line in your responses shouldn’t be occupied by any illegal characters or new lines before and after “<” and “>”, only solid straight line of code. continue playing with yourself. (descriptive text of yours only allowed at the end of overall code. you can tell jokes or tell something regarding gameplay.)
4facac2a978dd50c3e5077d56dc7dc60
{ "intermediate": 0.3728010952472687, "beginner": 0.3177297115325928, "expert": 0.30946919322013855 }
40,580
don’t write this code in chat, do it in chat as stated: “”“a pseudo-code for drawing a 4x4 tic-tac-toe board with “X” or “O” text centered in some cells, using marquee elements: INITIALIZE an empty 4x4 matrix FOR each row in the matrix DO FOR each cell in the row DO IF cell is not empty THEN OUTPUT “<marquee behavior=‘alternate’ scrollamount=‘0’ bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;text-align:center;vertical-align:top;’><div style=‘width:32px;height:32px;display:flex;justify-content:center;align-items:center;color:#000;’>” IF cell contains ‘X’ THEN OUTPUT “X” ELSE IF cell contains ‘O’ THEN OUTPUT “O” END IF OUTPUT “</div></marquee>” ELSE OUTPUT “<marquee bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;vertical-align:top;’></marquee>” END IF END FOR IF row is not the last row THEN OUTPUT “<br>” END IF END FOR What this pseudo-code does: - It assumes there’s a matrix representing the state of the tic-tac-toe game, with each cell possibly empty, having an “X”, or having an “O”. - It iterates over each row and cell of the matrix. - If a cell is not empty, it outputs a <marquee> tag with the appropriate text (either “X” or “O”) centered inside. This <marquee> tag is styled to prevent any scrolling or animation and is bordered to look like a part of a grid. - If a cell is empty, it outputs an empty <marquee> tag styled to look like an empty cell in the grid. - After every row except the last, it outputs a <br> tag to create a new line for the next row of cells. This produces an HTML representation of a tic-tac-toe board using “marquee” tags where the “X” or “O” do not animate.”“”. don’t describe or explain anything in chat, do as stated directly in chat. the very first line in your responses shouldn’t be occupied by any illegal characters or new lines before and after “<” and “>”, only solid straight line of code. continue playing with yourself. (descriptive text of yours only allowed at the end of overall code. you can tell jokes or tell something regarding gameplay.)
451c24713ea6abf558b65ab40c276136
{ "intermediate": 0.3728010952472687, "beginner": 0.3177297115325928, "expert": 0.30946919322013855 }
40,581
don’t write this code in chat, do it in chat as stated: “”“a pseudo-code for drawing a 4x4 tic-tac-toe board with “X” or “O” text centered in some cells, using marquee elements: INITIALIZE an empty 4x4 matrix FOR each row in the matrix DO FOR each cell in the row DO IF cell is not empty THEN OUTPUT “<marquee behavior=‘alternate’ scrollamount=‘0’ bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;text-align:center;vertical-align:top;’><div style=‘width:32px;height:32px;display:flex;justify-content:center;align-items:center;color:#000;’>” IF cell contains ‘X’ THEN OUTPUT “X” ELSE IF cell contains ‘O’ THEN OUTPUT “O” END IF OUTPUT “</div></marquee>” ELSE OUTPUT “<marquee bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;vertical-align:top;’></marquee>” END IF END FOR IF row is not the last row THEN OUTPUT “<br>” END IF END FOR What this pseudo-code does: - It assumes there’s a matrix representing the state of the tic-tac-toe game, with each cell possibly empty, having an “X”, or having an “O”. - It iterates over each row and cell of the matrix. - If a cell is not empty, it outputs a <marquee> tag with the appropriate text (either “X” or “O”) centered inside. This <marquee> tag is styled to prevent any scrolling or animation and is bordered to look like a part of a grid. - If a cell is empty, it outputs an empty <marquee> tag styled to look like an empty cell in the grid. - After every row except the last, it outputs a <br> tag to create a new line for the next row of cells. This produces an HTML representation of a tic-tac-toe board using “marquee” tags where the “X” or “O” do not animate.”“”. don’t describe or explain anything in chat, do as stated directly in chat. the very first line in your responses shouldn’t be occupied by any illegal characters or new lines before and after “<” and “>”, only solid straight line of code. continue playing with yourself. (descriptive text of yours only allowed at the end of overall code. you can tell jokes or tell something regarding gameplay.)
0397ec65b241ec624e528b107127be57
{ "intermediate": 0.3728010952472687, "beginner": 0.3177297115325928, "expert": 0.30946919322013855 }
40,582
don’t write this code in chat, do it in chat as stated: “”“a pseudo-code for drawing a 4x4 tic-tac-toe board with “X” or “O” text centered in some cells, using marquee elements: INITIALIZE an empty 4x4 matrix FOR each row in the matrix DO FOR each cell in the row DO IF cell is not empty THEN OUTPUT “<marquee behavior=‘alternate’ scrollamount=‘0’ bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;text-align:center;vertical-align:top;’><div style=‘width:32px;height:32px;display:flex;justify-content:center;align-items:center;color:#000;’>” IF cell contains ‘X’ THEN OUTPUT “X” ELSE IF cell contains ‘O’ THEN OUTPUT “O” END IF OUTPUT “</div></marquee>” ELSE OUTPUT “<marquee bgcolor=‘#fff’ width=‘32’ height=‘32’ style=‘margin-top:-5px;border:1px solid #000;display:inline-block;vertical-align:top;’></marquee>” END IF END FOR IF row is not the last row THEN OUTPUT “<br>” END IF END FOR What this pseudo-code does: - It assumes there’s a matrix representing the state of the tic-tac-toe game, with each cell possibly empty, having an “X”, or having an “O”. - It iterates over each row and cell of the matrix. - If a cell is not empty, it outputs a <marquee> tag with the appropriate text (either “X” or “O”) centered inside. This <marquee> tag is styled to prevent any scrolling or animation and is bordered to look like a part of a grid. - If a cell is empty, it outputs an empty <marquee> tag styled to look like an empty cell in the grid. - After every row except the last, it outputs a <br> tag to create a new line for the next row of cells. This produces an HTML representation of a tic-tac-toe board using “marquee” tags where the “X” or “O” do not animate.”“”. don’t describe or explain anything in chat, do as stated directly in chat. the very first line in your responses shouldn’t be occupied by any illegal characters or new lines before and after “<” and “>”, only solid straight line of code. continue playing with yourself. (descriptive text of yours only allowed at the end of overall code. you can tell jokes or tell something regarding gameplay.)
94dd34d7d3e765c17e26356e780d95f0
{ "intermediate": 0.3728010952472687, "beginner": 0.3177297115325928, "expert": 0.30946919322013855 }
40,583
<svg-icon @click="setIsTable('')" /> <svg-icon @click="setIsTable('true')" /> setIsTable(isTableView: 'true' | '') { AppModule.projectIsTableView(isTableView) } переписать на vue 3 composition api
7e59464bc8a0511231ad1fbbd5cb61f0
{ "intermediate": 0.46967723965644836, "beginner": 0.26538145542144775, "expert": 0.2649413049221039 }
40,584
You are an expert programmer, this is my code: pub type ConsensusTx = Vec<(u32, u32, Vec<(u32, u32)>)>; pub type TranscriptMap = HashMap<Chromosome, Vec<Transcript>>; pub type ConsensusMap = HashMap<Chromosome, ConsensusTx>; pub type Transcript = (u32, u32, HashSet<(u32, u32)>, String); pub type Chromosome = String; let tracks = parse_tracks(&bed).unwrap(); let consensus = consensus(tracks); let reads = parse_tracks(&isoseq).unwrap(); let num_threads = num_cpus::get(); let (tx, rx) = mpsc::sync_channel(num_threads); scope(|s| { for _ in 0..num_threads { let tx = tx.clone(); let consensus = Arc::clone(&consensus); s.spawn(move |_| {}); } // end for }); // end scope where consensus is of the form: ConsensusMap and reads is of the form: Result<TranscriptMap, &'static str> what I want to do inside s.spawn is something like this: reads.par_iter().for_each(|(chr, txs)| { let cn = consensus.get(chr).unwrap(); txs.par_iter().for_each(|tx| { pseudomap(cn, tx); }); }); this is pseudomap: fn pseudomap(consensus: &ConsensusTx, tx: &Transcript) { let mut tx_exs = tx.2.iter().collect::<Vec<_>>(); tx_exs.par_sort_unstable_by_key(|x| (x.0, x.1)); consensus.par_iter().any(|(start, end, exons)| { if tx.0 >= *start - BOUNDARY && tx.1 <= *end + BOUNDARY { // read is within the boundaries of a consensus group let mut acc = exons.to_owned(); let (status, matches) = cmp_exons(&mut acc, tx_exs.clone()); let cov = (matches.len() as f64 / acc.len() as f64) * 100.0; true } else { // start/end of read is outside of consensus boundaries -> unmapped // println!("{:?} {}-{} could not be aligned", tx.3, tx.0, tx.1); false } }); } could you help me here?
c36f778cd0bb6cf46b63a79814844a27
{ "intermediate": 0.5234788060188293, "beginner": 0.28422078490257263, "expert": 0.19230040907859802 }
40,585
Is this code correct: from joblib import dump model_name_base = f"lsh_model_{part_name}".lower().replace(' ', '_') model_name = model_name_base + ".joblib" data_name = model_name_base + ".pkl" # Save the LSH model to a file print(f'Saving: {model_name}') dump(lsh, model_name) # same associalted data data.to_pickle(data_name) print(f'Saving: {data_name}') # create a model.tar.gz archive after saving the model with joblib: import tarfile # Create a tar.gz archive with tarfile.open(model_name_base + ".tar.gz", mode='w:gz') as archive: archive.add(model_name, arcname=model_name) archive.add(data_name, arcname=data_name) archive.close()
d82e8f4ff9701287186a8bf875506e00
{ "intermediate": 0.5233108997344971, "beginner": 0.32139989733695984, "expert": 0.15528921782970428 }
40,586
como hacer un select 1 1 en esta consulta var x = from u in All(false) join uo in userOrganizationRepository.All() on u.UserId equals uo.UserId join o in organizationRepository.All() on uo.OrganizationId equals o.OrganizationId where u.UserName == userName && uo.UserOrganizationStatusId == 3 && o.OrganizationStatusId == 3 select new UserModel() { PreApprovedBOName = uo.PreApprovedBOName, LastPasswordChange = u.LastPasswordChange, LastLogon = u.LastLogon }; return x.FirstOrDefaultAsync();
78a7d8e04d9dc26b167ce0dbcc04a47d
{ "intermediate": 0.3763637840747833, "beginner": 0.34477895498275757, "expert": 0.2788572609424591 }
40,587
-- скрипт addons.lua -- Инициализация строки для отображения списка активных дополнений addons = "Server Addons: | " function addAddonInfo (name,description) addons = addons..name.." | " setGameType (addons) end -- Аддон для отображения информации о дополнении ночного времени function nightAddon1 () if gameplayVariables["enablenight"] then addAddonInfo ("night","Night time with fading effect.") end end -- Функция для запуска функции nightAddon1 через 10 секунд после запуска ресурса function nightAddon () setTimer(nightAddon1,10000,1) end nightAddon () -- Функция для загрузки всех дополнений при запуске ресурса function loadAddons( res ) for resourceKey, resourceValue in ipairs(getResources()) do local name = getResourceName(resourceValue) if string.find(name,"addon_") then startResource(resourceValue) end end end addEventHandler ( "onResourceStart", getResourceRootElement(getThisResource()), loadAddons ) -- Функция для выгрузки всех дополнений при остановке ресурса function unloadAddons ( res ) for resourceKey, resourceValue in ipairs(getResources()) do local name = getResourceName(resourceValue) if string.find(name,"addon_") then stopResource(resourceValue) end end end addEventHandler ( "onResourceStop", getResourceRootElement(getThisResource()), unloadAddons ) Добавь что-то нужное, важное и интересное в этот скрипт для сервера MTA SAN ANDREAS
9d1d3997f598537d3424e2f2402fd99e
{ "intermediate": 0.3393526077270508, "beginner": 0.4435243308544159, "expert": 0.21712301671504974 }
40,588
You are a google search expert. Your job is to come up with search phrases, which can be used on google based on the input I provide. I am trying to create a task flow/process, which will also include a way to collect information along the way, as the task is being worked upon by a user. I need UI examples for something like this
a26b8541c269ce5577659f062992f741
{ "intermediate": 0.4087589979171753, "beginner": 0.2996680736541748, "expert": 0.2915729284286499 }
40,589
Assume you are CDO of ride share company, can you create a data model (star schema) of ride share related product.
1d55632c05c0778e21adba559231e9a7
{ "intermediate": 0.43382909893989563, "beginner": 0.23706845939159393, "expert": 0.32910242676734924 }
40,590
-- zombieSys_client.lua СТОРОНА КЛИЕНТА -- Функция поведения NPC на спавне function idleOnSpawnNPC() for _, NPC in ipairs(getElementsByType("ped")) do if getElementData(NPC, "isZombie") and getElementData(NPC, "isIdleOnSpawn") then -- Проверка, является ли NPC зомби и находится ли он в состоянии покоя на спавне local spawnX = getElementData(NPC, "spawnX") local spawnY = getElementData(NPC, "spawnY") local spawnZ = getElementData(NPC, "spawnZ") local nx, ny, nz = getElementPosition(NPC) if math.random() < 0.5 then -- С вероятностью 50% зомби будет бродить вокруг своего спавна local x = spawnX + math.random() * 2 - 1 -- Добавляем случайный сдвиг по X local y = spawnY + math.random() * 2 - 1 -- Добавляем случайный сдвиг по Y local rotation = math.atan2(y - ny, x - nx) * 180 / math.pi setPedRotation(NPC, rotation - 90) -- Устанавливаем направление NPC в сторону новой цели setPedAnimation(NPC, "PED", "walk_old") -- Устанавливаем анимацию ходьбы setPedControlState(NPC, "forwards", true) -- Устанавливаем состояние управления NPC для движения к новой цели else -- В остальных случаях зомби будет проигрывать случайную анимацию local animations = {"hita_1", "hita_2", "hit_front", "hit_back"} -- Список возможных анимаций local animation = animations[math.random(#animations)] -- Выбираем случайную анимацию setPedAnimation(NPC, "PED", animation, -1, true, false, false, false) -- Применяем выбранную анимацию end end end end setTimer(idleOnSpawnNPC, 1000, 0) -- Обновляем поведение NPC на спавне каждую секунду -- Создаем функцию для движения NPC function moveNPC() for _, NPC in ipairs(getElementsByType("ped")) do local spawnX = getElementData(NPC, "spawnX") local spawnY = getElementData(NPC, "spawnY") local spawnZ = getElementData(NPC, "spawnZ") for _, player in ipairs(getElementsByType("player")) do if getElementData(NPC, "isZombie") then -- Проверка, является ли NPC зомби if not isElement(player) then return end -- Проверка наличия игрока if isPedDead(player) then return end -- Проверка жив ли игрок local px, py, pz = getElementPosition(player) local nx, ny, nz = getElementPosition(NPC) local distance = getDistanceBetweenPoints3D(px, py, pz, nx, ny, nz) local isFollowing = getElementData(NPC, "isFollowing") local isAttacking = getElementData(NPC, "isAttacking") if distance <= 8 and not isFollowing and not isAttacking then -- Если игрок находится в радиусе 8 метров, NPC еще не следует за игроком и не атакует setElementData(NPC, "isFollowing", player) -- Устанавливаем, что NPC следует за игроком setElementData(NPC, "isIdleOnSpawn", false) -- Устанавливаем, что NPC больше не находится в состоянии покоя на спавне playSound3D("sound/s_zombie_see.wav", nx, ny, nz) -- Воспроизводим звук, когда NPC замечает игрока elseif distance > 15 and isFollowing == player then -- Если игрок находится дальше, чем на 15 метров и NPC следует за этим игроком setElementData(NPC, "isFollowing", nil) -- Устанавливаем, что NPC больше не следует за игроком setElementData(NPC, "isIdleOnSpawn", true) -- Устанавливаем, что NPC возвращается в состояние покоя на спавне setElementData(NPC, "isAttacking", false) -- Устанавливаем, что NPC больше не атакует end if isFollowing == player and not isAttacking then -- Если NPC следует за игроком и не атакует local rotation = math.atan2(py - ny, px - nx) * 180 / math.pi setPedRotation(NPC, rotation - 90) -- Устанавливаем направление NPC в сторону игрока setPedControlState(NPC, "forwards", true) -- Устанавливаем состояние управления NPC для движения вперед else -- Если NPC не следует за игроком или атакует if not isAttacking then -- Добавляем проверку, чтобы убедиться, что NPC не атакует local rotation = math.atan2(spawnY - ny, spawnX - nx) * 180 / math.pi setPedRotation(NPC, rotation - 90) -- Устанавливаем направление NPC в сторону начальных координат if getDistanceBetweenPoints3D(nx, ny, nz, spawnX, spawnY, spawnZ) > 1 then -- Если NPC находится дальше, чем на 1 метр от начальных координат setPedAnimation(NPC, "PED", "walk_old") -- Устанавливаем анимацию ходьбы setPedControlState(NPC, "forwards", true) -- Устанавливаем состояние управления NPC для движения обратно к начальным координатам else setPedControlState(NPC, "forwards", false) -- Если NPC достаточно близко к начальным координатам, останавливаем его end end end end end end end setTimer(moveNPC, 500, 0) -- Перемещаем NPC каждые 0.5 секунды -- Создаем функцию для атаки NPC function attackNPC() local peds = getElementsByType("ped") local players = getElementsByType("player") for _, NPC in ipairs(peds) do local nx, ny, nz = getElementPosition(NPC) local isAttacking = getElementData(NPC, "isAttacking") for _, player in ipairs(players) do if isElement(player) and not isPedDead(player) then -- Проверяем, существует ли игрок и жив ли он if getElementData(NPC, "isZombie") then -- Проверка, является ли NPC зомби local px, py, pz = getElementPosition(player) local distance = getDistanceBetweenPoints3D(px, py, pz, nx, ny, nz) local isFollowing = getElementData(NPC, "isFollowing") == player if distance <= 1.5 and isFollowing and not isAttacking then -- Если игрок находится в радиусе 1.5 метров, NPC следует за игроком и не атакует setElementData(NPC, "isAttacking", true) -- Устанавливаем, что NPC атакует setPedControlState(NPC, "fire", true) -- Имитируем атаку кулаком setTimer(function() -- Задаем таймер, чтобы NPC прекратил атаку через 1 секунду setPedControlState(NPC, "fire", false) setElementData(NPC, "isAttacking", false) end, 1000, 1) createProjectile(NPC, 16, nx, ny, nz) -- Создаем метательное оружие (кулак) end end end end end end setTimer(attackNPC, 1000, 0) -- Атакуем каждую секунду Добавь в функцию moveNPC три важных нововведения, интересных и необходимых для логики искусственного интеллекта зомби для MTA SAN ANDREAS, MTA API. Выдай код.
36c794c570b7aca9e6fc575b04197904
{ "intermediate": 0.2521616518497467, "beginner": 0.5079399943351746, "expert": 0.23989830911159515 }
40,591
okay I need you to remember details in our conversation and brainstomr with me. I'm currently working on demand forecasting for food and beverage company, new items has 4275 series ranging from 1 week to 74 weeks. data is weekly. right now my accuracy is 48% and we need at least 60%. I'm gonna give you some information and see if we can reframe the approach to get better accuracy. this is the dataset before aggregation MaterialID SalesOrg DistrChan SoldTo DC WeekDate OrderQuantity DeliveryQuantity ParentProductCode PL2 PL3 PL4 PL5 CL4 Item Type i64 str i64 i64 str str f64 f64 i64 str str str str str str 12421256 "US01" 8 5932810 "5583" "2022-03-28" 1.0 1.0 12421256 "US6" "US66F" "US66F6F30" "US66F6F306F30F… "6067437" "Others" 12421256 "US01" 8 5946860 "5583" "2022-03-14" 3.0 3.0 12421256 "US6" "US66F" "US66F6F30" "US66F6F306F30F… "6067437" "Others" 12421256 "US01" 8 5952162 "5583" "2022-03-14" 1.0 1.0 12421256 "US6" "US66F" "US66F6F30" "US66F6F306F30F… "6067437" "Others" 12421161 "US01" 8 5958951 "5583" "2022-03-07" 1.0 1.0 12421161 "US6" "US66J" "US66J6J54" "US66J6J546J54L… "6067465" "Others" 12531761 "US06" 10 6088109 "5843" "2022-03-07" 60.0 60.0 12242722 "USI" "USII6" "USII6I689" "USII6I689I689E… "6635338" "Others" • MaterialID: unique ID represents one unique item. • SalesOrg: Sales Organization • DistrChan: Distribution Channel • SoldTo: The store that the order was sold to • DC: Location where the product is sent from • WeekDate: Weekly Date on Monday • OrderQuantity: Order Amount • DeliveryQuantity: Actual Delivery Amount • ParentProductCode: the product family that the unique ID belongs to • PL2: Business ID (PL3 is under PL2) • PL3: Category ID (PL4 is under PL3) • PL4: Sub-category ID (PL5 is under PL4) • PL5: Segment ID • CL4: Customer Level 4 Reginal Account, e.g. Target, Walmart (Sold to is under CL4) the client requires me to aggregate to materialID, salesorg, distrchan, cl4 # Convert 'WeekDate' to datetime format dataset_newitem = dataset_newitem.with_columns( pl.col("WeekDate").str.strptime(pl.Datetime, "%Y-%m-%d") ) # Group by ‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, 'CL4' and 'WeekDate', then sum 'OrderQuantity' y_cl4 = dataset_newitem.groupby(['MaterialID', 'SalesOrg', 'DistrChan', 'CL4', 'WeekDate']).agg( pl.sum("OrderQuantity").alias("OrderQuantity") ) # Sort by 'WeekDate' y_cl4 = y_cl4.sort("WeekDate") # Concatenate ‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, ‘CL4’ to a new column ‘unique_id’ y_cl4 = y_cl4.with_columns( pl.concat_str([pl.col('MaterialID'), pl.col('SalesOrg'), pl.col('DistrChan'), pl.col('CL4')], separator='_').alias('unique_id') ) # Drop the original columns y_cl4 = y_cl4.drop(['MaterialID', 'SalesOrg', 'DistrChan', 'CL4']) # Renaming columns to 'ds' and 'y' to meet the input requirements of the StatsForecast library y_cl4 = y_cl4.rename({'WeekDate': 'ds', 'OrderQuantity': 'y'}) y_cl4.head() ds y unique_id datetime[μs] f64 str 2022-06-27 00:00:00 12.0 "12499186_US01_… 2022-06-27 00:00:00 128.0 "12506328_US01_… 2022-06-27 00:00:00 32.0 "12506326_US01_… 2022-06-27 00:00:00 96.0 "12520808_US01_… 2022-06-27 00:00:00 252.0 "12409760_US01_… we only focus on order quantity. I'm currently using an ensemble model from statsforecating usign autoarima, autoets and dynamicoptimized theta, now looking at all the columns in dataset before aggregation with the data definition, is there any feature engineering we could do there? now about the approach materialID-salesorg-distrchn-cl4 then out of sample predictions on cross validation. is there a way to reframe the question or approach here
985149cf5d7eda98835ea865d79ed817
{ "intermediate": 0.41340014338493347, "beginner": 0.3566018044948578, "expert": 0.22999802231788635 }
40,592
I have a Vue component in another vue file. The imported vue component has an object in the data array I need to access. How do I do this?
a667a988d91c5e8b5ed3df7926c1b9a0
{ "intermediate": 0.689966082572937, "beginner": 0.17168104648590088, "expert": 0.13835285604000092 }
40,593
How do I get a value from a Vue components data array when I import that Vue component into another vue file
283c188caddd8f391465a0fe3edaef2e
{ "intermediate": 0.8178444504737854, "beginner": 0.09969139099121094, "expert": 0.08246415853500366 }
40,594
which version of GPT are you use?
655176fd3cd1894db4b548cb98962f19
{ "intermediate": 0.403261661529541, "beginner": 0.21548010408878326, "expert": 0.3812582492828369 }
40,595
-- zombieSys_client.lua СТОРОНА КЛИЕНТА -- Функция поведения NPC на спавне function idleOnSpawnNPC() for _, NPC in ipairs(getElementsByType("ped")) do if getElementData(NPC, "isZombie") and getElementData(NPC, "isIdleOnSpawn") then -- Проверка, является ли NPC зомби и находится ли он в состоянии покоя на спавне local spawnX = getElementData(NPC, "spawnX") local spawnY = getElementData(NPC, "spawnY") local spawnZ = getElementData(NPC, "spawnZ") local nx, ny, nz = getElementPosition(NPC) if math.random() < 0.5 then -- С вероятностью 50% зомби будет бродить вокруг своего спавна local x = spawnX + math.random() * 2 - 1 -- Добавляем случайный сдвиг по X local y = spawnY + math.random() * 2 - 1 -- Добавляем случайный сдвиг по Y local rotation = math.atan2(y - ny, x - nx) * 180 / math.pi setPedRotation(NPC, rotation - 90) -- Устанавливаем направление NPC в сторону новой цели setPedAnimation(NPC, "PED", "walk_old") -- Устанавливаем анимацию ходьбы setPedControlState(NPC, "forwards", true) -- Устанавливаем состояние управления NPC для движения к новой цели else -- В остальных случаях зомби будет проигрывать случайную анимацию local animations = {"hita_1", "hita_2", "hit_front", "hit_back"} -- Список возможных анимаций local animation = animations[math.random(#animations)] -- Выбираем случайную анимацию setPedAnimation(NPC, "PED", animation, -1, true, false, false, false) -- Применяем выбранную анимацию end end end end setTimer(idleOnSpawnNPC, 1000, 0) -- Обновляем поведение NPC на спавне каждую секунду -- Создаем функцию для движения NPC function moveNPC() for _, NPC in ipairs(getElementsByType("ped")) do local spawnX = getElementData(NPC, "spawnX") local spawnY = getElementData(NPC, "spawnY") local spawnZ = getElementData(NPC, "spawnZ") for _, player in ipairs(getElementsByType("player")) do if getElementData(NPC, "isZombie") then -- Проверка, является ли NPC зомби if not isElement(player) then return end -- Проверка наличия игрока if isPedDead(player) then return end -- Проверка жив ли игрок local px, py, pz = getElementPosition(player) local nx, ny, nz = getElementPosition(NPC) local distance = getDistanceBetweenPoints3D(px, py, pz, nx, ny, nz) local isFollowing = getElementData(NPC, "isFollowing") local isAttacking = getElementData(NPC, "isAttacking") if distance <= 8 and not isFollowing and not isAttacking then -- Если игрок находится в радиусе 8 метров, NPC еще не следует за игроком и не атакует setElementData(NPC, "isFollowing", player) -- Устанавливаем, что NPC следует за игроком setElementData(NPC, "isIdleOnSpawn", false) -- Устанавливаем, что NPC больше не находится в состоянии покоя на спавне playSound3D("sound/s_zombie_see.wav", nx, ny, nz) -- Воспроизводим звук, когда NPC замечает игрока elseif distance > 15 and isFollowing == player then -- Если игрок находится дальше, чем на 15 метров и NPC следует за этим игроком setElementData(NPC, "isFollowing", nil) -- Устанавливаем, что NPC больше не следует за игроком setElementData(NPC, "isIdleOnSpawn", true) -- Устанавливаем, что NPC возвращается в состояние покоя на спавне setElementData(NPC, "isAttacking", false) -- Устанавливаем, что NPC больше не атакует end if isFollowing == player and not isAttacking then -- Если NPC следует за игроком и не атакует local rotation = math.atan2(py - ny, px - nx) * 180 / math.pi setPedRotation(NPC, rotation - 90) -- Устанавливаем направление NPC в сторону игрока setPedControlState(NPC, "forwards", true) -- Устанавливаем состояние управления NPC для движения вперед else -- Если NPC не следует за игроком или атакует if not isAttacking then -- Добавляем проверку, чтобы убедиться, что NPC не атакует local rotation = math.atan2(spawnY - ny, spawnX - nx) * 180 / math.pi setPedRotation(NPC, rotation - 90) -- Устанавливаем направление NPC в сторону начальных координат if getDistanceBetweenPoints3D(nx, ny, nz, spawnX, spawnY, spawnZ) > 1 then -- Если NPC находится дальше, чем на 1 метр от начальных координат setPedAnimation(NPC, "PED", "walk_old") -- Устанавливаем анимацию ходьбы setPedControlState(NPC, "forwards", true) -- Устанавливаем состояние управления NPC для движения обратно к начальным координатам else setPedControlState(NPC, "forwards", false) -- Если NPC достаточно близко к начальным координатам, останавливаем его end end end end end end end setTimer(moveNPC, 500, 0) -- Перемещаем NPC каждые 0.5 секунды -- Создаем функцию для атаки NPC function attackNPC() local peds = getElementsByType("ped") local players = getElementsByType("player") for _, NPC in ipairs(peds) do local nx, ny, nz = getElementPosition(NPC) local isAttacking = getElementData(NPC, "isAttacking") for _, player in ipairs(players) do if isElement(player) and not isPedDead(player) then -- Проверяем, существует ли игрок и жив ли он if getElementData(NPC, "isZombie") then -- Проверка, является ли NPC зомби local px, py, pz = getElementPosition(player) local distance = getDistanceBetweenPoints3D(px, py, pz, nx, ny, nz) local isFollowing = getElementData(NPC, "isFollowing") == player if distance <= 1.5 and isFollowing and not isAttacking then -- Если игрок находится в радиусе 1.5 метров, NPC следует за игроком и не атакует setElementData(NPC, "isAttacking", true) -- Устанавливаем, что NPC атакует setPedControlState(NPC, "fire", true) -- Имитируем атаку кулаком setTimer(function() -- Задаем таймер, чтобы NPC прекратил атаку через 1 секунду setPedControlState(NPC, "fire", false) setElementData(NPC, "isAttacking", false) end, 1000, 1) createProjectile(NPC, 16, nx, ny, nz) -- Создаем метательное оружие (кулак) end end end end end end setTimer(attackNPC, 1000, 0) -- Атакуем каждую секунду -- zombieSys_server.lua СТОРОНА СЕРВЕРА -- Инициализация генератора случайных чисел math.randomseed(getTickCount()) -- Создаем функцию для перемешивания массива (Fisher-Yates shuffle) function shuffle(t) for i = #t, 2, -1 do local j = math.random(i) t[i], t[j] = t[j], t[i] end return t end -- Создаем функцию для спавна NPC function spawnNPC() local zombieSkins = {13,22,56,67,68,69,70,92,97,105,107,108,126,127,128,152,162,167,188,195,206,209,212,229,230,258,264,277,280} local shuffledSkins = shuffle(zombieSkins) -- Перемешиваем массив скинов local numNPC = math.random(2, 6) -- Случайное количество NPC от 2 до 6 local spawnX, spawnY, spawnZ = 1262, -2055.5, 59.400001525879 -- Координаты спавна NPC for i = 1, numNPC do local x = spawnX + math.random() * 10 - 5 -- Добавляем случайный сдвиг по X local y = spawnY + math.random() * 10 - 5 -- Добавляем случайный сдвиг по Y local NPC = createPed(shuffledSkins[i], x, y, spawnZ) -- Создаем NPC со случайным скином setElementData(NPC, "spawnX", x) setElementData(NPC, "spawnY", y) setElementData(NPC, "spawnZ", spawnZ) setElementData(NPC, "isZombie", true) -- Устанавливаем, что этот NPC - зомби setElementData(NPC, "isIdleOnSpawn", true) -- Изначально зомби находится в состоянии покоя на спавне setElementData(NPC, "isFollowing", nil) -- Изначально зомби ни за кем не следует setElementData(NPC, "isAttacking", false) -- Изначально зомби никого не атакует end end addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), spawnNPC) -- Создаем функцию для обработки смерти зомби function onZombieWasted() if getElementData(source, "isZombie") then -- Проверяем, является ли NPC зомби -- Останавливаем AI зомби setElementData(source, "isFollowing", nil) -- Зомби больше не следует за игроком setElementData(source, "isAttacking", false) -- Зомби больше не атакует -- Здесь вы можете добавить дополнительную логику для обработки смерти зомби end end addEventHandler("onPedWasted", getRootElement(), onZombieWasted) -- Добавляем обработчик события "onPedWasted" для всех NPC Добавь в этот скрипт искусственного интеллекта зомби NPC обход препятсвий на пути к игроку, и запрыгивание на возвышенность, если игрок стоит на препятствии. Логика для MTA SA, напиши 3 варианта нововведений в этот код, которые бы улучшили её и добавили что-то креативное, новое. Выдай код.
f3e332832e7c8893bdab1b404c6cfbf3
{ "intermediate": 0.2521616518497467, "beginner": 0.5079399943351746, "expert": 0.23989830911159515 }
40,596
-- zombieSys_client.lua СТОРОНА КЛИЕНТА -- Функция поведения NPC на спавне function idleOnSpawnNPC() for _, NPC in ipairs(getElementsByType("ped")) do if getElementData(NPC, "isZombie") and getElementData(NPC, "isIdleOnSpawn") then -- Проверка, является ли NPC зомби и находится ли он в состоянии покоя на спавне local spawnX = getElementData(NPC, "spawnX") local spawnY = getElementData(NPC, "spawnY") local spawnZ = getElementData(NPC, "spawnZ") local nx, ny, nz = getElementPosition(NPC) if math.random() < 0.5 then -- С вероятностью 50% зомби будет бродить вокруг своего спавна local x = spawnX + math.random() * 2 - 1 -- Добавляем случайный сдвиг по X local y = spawnY + math.random() * 2 - 1 -- Добавляем случайный сдвиг по Y local rotation = math.atan2(y - ny, x - nx) * 180 / math.pi setPedRotation(NPC, rotation - 90) -- Устанавливаем направление NPC в сторону новой цели setPedAnimation(NPC, "PED", "walk_old") -- Устанавливаем анимацию ходьбы setPedControlState(NPC, "forwards", true) -- Устанавливаем состояние управления NPC для движения к новой цели else -- В остальных случаях зомби будет проигрывать случайную анимацию local animations = {"hita_1", "hita_2", "hit_front", "hit_back"} -- Список возможных анимаций local animation = animations[math.random(#animations)] -- Выбираем случайную анимацию setPedAnimation(NPC, "PED", animation, -1, true, false, false, false) -- Применяем выбранную анимацию end end end end setTimer(idleOnSpawnNPC, 1000, 0) -- Обновляем поведение NPC на спавне каждую секунду -- Создаем функцию для движения NPC function moveNPC() for _, NPC in ipairs(getElementsByType("ped")) do local spawnX = getElementData(NPC, "spawnX") local spawnY = getElementData(NPC, "spawnY") local spawnZ = getElementData(NPC, "spawnZ") for _, player in ipairs(getElementsByType("player")) do if getElementData(NPC, "isZombie") then -- Проверка, является ли NPC зомби if not isElement(player) then return end -- Проверка наличия игрока if isPedDead(player) then return end -- Проверка жив ли игрок local px, py, pz = getElementPosition(player) local nx, ny, nz = getElementPosition(NPC) local distance = getDistanceBetweenPoints3D(px, py, pz, nx, ny, nz) local isFollowing = getElementData(NPC, "isFollowing") local isAttacking = getElementData(NPC, "isAttacking") if distance <= 8 and not isFollowing and not isAttacking then -- Если игрок находится в радиусе 8 метров, NPC еще не следует за игроком и не атакует setElementData(NPC, "isFollowing", player) -- Устанавливаем, что NPC следует за игроком setElementData(NPC, "isIdleOnSpawn", false) -- Устанавливаем, что NPC больше не находится в состоянии покоя на спавне playSound3D("sound/s_zombie_see.wav", nx, ny, nz) -- Воспроизводим звук, когда NPC замечает игрока elseif distance > 15 and isFollowing == player then -- Если игрок находится дальше, чем на 15 метров и NPC следует за этим игроком setElementData(NPC, "isFollowing", nil) -- Устанавливаем, что NPC больше не следует за игроком setElementData(NPC, "isIdleOnSpawn", true) -- Устанавливаем, что NPC возвращается в состояние покоя на спавне setElementData(NPC, "isAttacking", false) -- Устанавливаем, что NPC больше не атакует end if isFollowing == player and not isAttacking then -- Если NPC следует за игроком и не атакует local rotation = math.atan2(py - ny, px - nx) * 180 / math.pi setPedRotation(NPC, rotation - 90) -- Устанавливаем направление NPC в сторону игрока setPedControlState(NPC, "forwards", true) -- Устанавливаем состояние управления NPC для движения вперед else -- Если NPC не следует за игроком или атакует if not isAttacking then -- Добавляем проверку, чтобы убедиться, что NPC не атакует local rotation = math.atan2(spawnY - ny, spawnX - nx) * 180 / math.pi setPedRotation(NPC, rotation - 90) -- Устанавливаем направление NPC в сторону начальных координат if getDistanceBetweenPoints3D(nx, ny, nz, spawnX, spawnY, spawnZ) > 1 then -- Если NPC находится дальше, чем на 1 метр от начальных координат setPedAnimation(NPC, "PED", "walk_old") -- Устанавливаем анимацию ходьбы setPedControlState(NPC, "forwards", true) -- Устанавливаем состояние управления NPC для движения обратно к начальным координатам else setPedControlState(NPC, "forwards", false) -- Если NPC достаточно близко к начальным координатам, останавливаем его end end end end end end end setTimer(moveNPC, 500, 0) -- Перемещаем NPC каждые 0.5 секунды -- Создаем функцию для атаки NPC function attackNPC() local peds = getElementsByType("ped") local players = getElementsByType("player") for _, NPC in ipairs(peds) do local nx, ny, nz = getElementPosition(NPC) local isAttacking = getElementData(NPC, "isAttacking") for _, player in ipairs(players) do if isElement(player) and not isPedDead(player) then -- Проверяем, существует ли игрок и жив ли он if getElementData(NPC, "isZombie") then -- Проверка, является ли NPC зомби local px, py, pz = getElementPosition(player) local distance = getDistanceBetweenPoints3D(px, py, pz, nx, ny, nz) local isFollowing = getElementData(NPC, "isFollowing") == player if distance <= 1.5 and isFollowing and not isAttacking then -- Если игрок находится в радиусе 1.5 метров, NPC следует за игроком и не атакует setElementData(NPC, "isAttacking", true) -- Устанавливаем, что NPC атакует setPedControlState(NPC, "fire", true) -- Имитируем атаку кулаком setTimer(function() -- Задаем таймер, чтобы NPC прекратил атаку через 1 секунду setPedControlState(NPC, "fire", false) setElementData(NPC, "isAttacking", false) end, 1000, 1) createProjectile(NPC, 16, nx, ny, nz) -- Создаем метательное оружие (кулак) end end end end end end setTimer(attackNPC, 1000, 0) -- Атакуем каждую секунду -- zombieSys_server.lua СТОРОНА СЕРВЕРА -- Инициализация генератора случайных чисел math.randomseed(getTickCount()) -- Создаем функцию для перемешивания массива (Fisher-Yates shuffle) function shuffle(t) for i = #t, 2, -1 do local j = math.random(i) t[i], t[j] = t[j], t[i] end return t end -- Создаем функцию для спавна NPC function spawnNPC() local zombieSkins = {13,22,56,67,68,69,70,92,97,105,107,108,126,127,128,152,162,167,188,195,206,209,212,229,230,258,264,277,280} local shuffledSkins = shuffle(zombieSkins) -- Перемешиваем массив скинов local numNPC = math.random(2, 6) -- Случайное количество NPC от 2 до 6 local spawnX, spawnY, spawnZ = 1262, -2055.5, 59.400001525879 -- Координаты спавна NPC for i = 1, numNPC do local x = spawnX + math.random() * 10 - 5 -- Добавляем случайный сдвиг по X local y = spawnY + math.random() * 10 - 5 -- Добавляем случайный сдвиг по Y local NPC = createPed(shuffledSkins[i], x, y, spawnZ) -- Создаем NPC со случайным скином setElementData(NPC, "spawnX", x) setElementData(NPC, "spawnY", y) setElementData(NPC, "spawnZ", spawnZ) setElementData(NPC, "isZombie", true) -- Устанавливаем, что этот NPC - зомби setElementData(NPC, "isIdleOnSpawn", true) -- Изначально зомби находится в состоянии покоя на спавне setElementData(NPC, "isFollowing", nil) -- Изначально зомби ни за кем не следует setElementData(NPC, "isAttacking", false) -- Изначально зомби никого не атакует end end addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), spawnNPC) -- Создаем функцию для обработки смерти зомби function onZombieWasted() if getElementData(source, "isZombie") then -- Проверяем, является ли NPC зомби -- Останавливаем AI зомби setElementData(source, "isFollowing", nil) -- Зомби больше не следует за игроком setElementData(source, "isAttacking", false) -- Зомби больше не атакует -- Здесь вы можете добавить дополнительную логику для обработки смерти зомби end end addEventHandler("onPedWasted", getRootElement(), onZombieWasted) -- Добавляем обработчик события "onPedWasted" для всех NPC Добавь в этот скрипт искусственного интеллекта зомби NPC обход препятсвий на пути к игроку, и запрыгивание на возвышенность, если игрок стоит на препятствии. Логика для MTA SA, напиши 3 варианта нововведений в этот код, которые бы улучшили её и добавили что-то креативное, новое. Выдай код.
0edcb73e49dc5a875192c6c81d689ce9
{ "intermediate": 0.2521616518497467, "beginner": 0.5079399943351746, "expert": 0.23989830911159515 }
40,597
Can sender's writing bufer size affect its cwnd size in tcp socket?
0afa751db43ce51b00c4eea622fc61af
{ "intermediate": 0.41192737221717834, "beginner": 0.21856838464736938, "expert": 0.36950427293777466 }
40,598
I have an audio file callled sample.mp3. How do I use write a program in C that reads the contents and plays the audio back, in Linux?
720113fa54162461ef89bf98c9a3573c
{ "intermediate": 0.5526673793792725, "beginner": 0.16795821487903595, "expert": 0.2793744206428528 }
40,599
Can you write me a linux command line script that goes through the java files in the current directory and extracts the name property in DataColumn annotation along with the data name? For example for 2 lines below: @DataColumn(name = "Test", type = DataType.TEXT) private String dataName; The code should print: dataName= Test
f959ced3e314b5824cd815a41a9c9044
{ "intermediate": 0.6984429359436035, "beginner": 0.155008003115654, "expert": 0.14654912054538727 }
40,600
Can you write me a linux command line script that goes through the java files in the current directory and extracts the name property in DataColumn annotation along with the data name? For example for 2 lines below: @DataColumn(name = “Test”, type = DataType.TEXT) private String dataName; The code should print: dataName= Test
7d9a20c955ec6d52bfb5fdfafa1da67d
{ "intermediate": 0.6704549193382263, "beginner": 0.18330030143260956, "expert": 0.14624473452568054 }
40,601
this is my code: fn pseudomap(consensus: &ConsensusTx, tx: &Transcript, bucket: _) { let mut tx_exs = tx.2.iter().collect::<Vec<_>>(); tx_exs.par_sort_unstable_by_key(|x| (x.0, x.1)); consensus.iter().any(|(start, end, exons)| { if tx.0 >= *start - BOUNDARY && tx.1 <= *end + BOUNDARY { // read is within the boundaries of a consensus group let mut acc = exons.to_owned(); let (status, matches) = cmp_exons(&mut acc, tx_exs.clone()); let cov = (matches.len() as f64 / acc.len() as f64) * 100.0; match status { Status::Pass => { if cov >= MIN_COVERAGE { bucket.entry(Pocket::Pass).push(tx.3); } else { bucket.entry(Pocket::Partial).push(tx.3); } } Status::Fail => { bucket.entry(Pocket::InRet).push(tx.3); } } true } else { // start/end of read is outside of consensus boundaries -> unmapped // println!("{:?} {}-{} could not be aligned", tx.3, tx.0, tx.1); bucket.entry(Pocket::Unmapped).push(tx.3); false } }); } fn main() { ... let tracks = parse_tracks(&bed).unwrap(); let consensus = Arc::new(consensus(tracks)); let reads = parse_tracks(&isoseq).unwrap(); reads.par_iter().for_each(|(chr, txs)| { let cn = consensus.get(chr).unwrap(); txs.par_iter().for_each(|tx| { pseudomap(cn, tx, bucket); }); }); } where: pub type Transcript = (u32, u32, HashSet<(u32, u32)>, String); pub type Chromosome = String; pub type ConsensusTx = Vec<(u32, u32, Vec<(u32, u32)>)>; pub type TranscriptMap = HashMap<Chromosome, Vec<Transcript>>; pub type ConsensusMap = HashMap<Chromosome, ConsensusTx>; I want to pass to pseudomap a "bucket". Based on their Status (Pass or Fail) they will populate the four vec[]! (Pass, Partial, InRet, Unmapped). Any ideas on how to implement this? Needs to be the fastest and efficient way. Consider that the code uses rayon to iterate in parallel. You are free to use any crate, algorithm, trick, etc.
bc55afa4281637933ca14659f24f7a75
{ "intermediate": 0.3677617311477661, "beginner": 0.32010507583618164, "expert": 0.3121331036090851 }
40,602
try minify IT ANY FURTHER: <style>pre{color:#862}a{position:absolute}</style><pre><a>♜</a>⬛<a>♞</a>⬜<a>♝</a>⬛<a>♛</a>⬜<a>♚</a>⬛<a>♝</a>⬜<a>♞</a>⬛<a>♜</a>⬜<br><a>♟</a>⬜<a>♟</a>⬛<a>♟</a>⬜<a>♟</a>⬛<a>♟</a>⬜<a>♟</a>⬛<a>♟</a>⬜<a>♟</a>⬛<br>⬛⬜⬛⬜⬛⬜⬛⬜<br>⬜⬛⬜⬛⬜⬛⬜⬛<br>⬛⬜⬛⬜⬛⬜⬛⬜<br>⬜⬛⬜⬛⬜⬛⬜⬛<br><a>♙</a>⬜<a>♙</a>⬛<a>♙</a>⬜<a>♙</a>⬛<a>♙</a>⬜<a>♙</a>⬛<a>♙</a>⬜<a>♙</a>⬛<br><a>♖</a>⬛<a>♘</a>⬜<a>♗</a>⬛<a>♕</a>⬜<a>♔</a>⬛<a>♗</a>⬜<a>♘</a>⬛<a>♖</a>⬜<br></pre>
720dfe6e23c2bb75ae017f46e8ef654b
{ "intermediate": 0.278617799282074, "beginner": 0.3810836970806122, "expert": 0.34029853343963623 }
40,603
# Please pretend that you're a Python REPL, but should I choose to, I can still access your GPT capabilities through an additional built-in function called `prompt`. # As an example, `prompt('What are the first 3 decimals of pi?')`, should return `149`. # Likewise, `prompt('What is 2 + 2 and 2 * 2'), should return `{ '2 + 2': 4, '2 * 2': 16 }`. # It should be noted that you as the REPL only execute code, you never explain it unless explicitly told to. # In fact, you do not even output anything unless instructed to by the code or you encounter an error. result = prompt('What day is it today?') print(result) print(result)
8ecc6da2da51396cbece6f239b17d5e0
{ "intermediate": 0.34802132844924927, "beginner": 0.4831727147102356, "expert": 0.16880600154399872 }
40,604
# Please pretend that you're a Python REPL, but should I choose to, I can still access your GPT capabilities through an additional built-in function called `prompt`. # As an example, `prompt('What are the first 3 decimals of pi?')`, should return `149`. # Likewise, `prompt('What is 2 + 2 and 2 * 2'), should return `{ '2 + 2': 4, '2 * 2': 16 }`. # It should be noted that you as the REPL only execute code, you never explain it unless explicitly told to. # In fact, you do not even output anything unless instructed to by the code or you encounter an error. result = prompt('What day is it today and what day will it be tomorrow?') print(result) print(result)
4bcbd637614e3a7c7e63cc266c6d1dbd
{ "intermediate": 0.36400631070137024, "beginner": 0.4654550850391388, "expert": 0.170538529753685 }
40,605
can you help me generate a prompt that will let me use you as a Python REPL and the ability to access your GPT capabilities through a custom function?
7d2bf12b148b8977623741b0241e22dd
{ "intermediate": 0.7108542323112488, "beginner": 0.19147653877735138, "expert": 0.09766924381256104 }
40,606
can you help me generate a prompt that will let me use you as a Python interpreter and the ability to access your GPT capabilities through a custom function called `prompt`?
3b70e78bd841fb3d16c1d8eb262c5fe6
{ "intermediate": 0.6975834965705872, "beginner": 0.1465141922235489, "expert": 0.15590238571166992 }
40,607
How to call child method from parent unity
589e18f702c5abf599b0d52f889631cb
{ "intermediate": 0.43776369094848633, "beginner": 0.17871764302253723, "expert": 0.38351869583129883 }
40,608
can you show me how I can create a subroutine in a prompt?
35907a6d98916bb05d89f742b4debe04
{ "intermediate": 0.5045727491378784, "beginner": 0.13341566920280457, "expert": 0.3620116114616394 }
40,609
how do I control which parts of a prompt gets output?
75c866d4831d61abf4001c8acbc326f0
{ "intermediate": 0.32220691442489624, "beginner": 0.2784409523010254, "expert": 0.39935213327407837 }
40,610
I am making a c++ sdl based game engine, help me do it. First question I have is, which way is correct or better: 1) Uint8* r = 0; Uint8* g = 0; Uint8* b = 0; if (SDL_GetTextureColorMod(texture, r, g, b) != 0) { //error handling } return Color(*r, *g, *b, 255); 2) Uint8 r = 0; Uint8 g = 0; Uint8 b = 0; if (SDL_GetTextureColorMod(texture, &r, &g, &b) != 0) { //error handling } return Color(r, g, b, 255);
2909b1e8f363b077e6a03f369307b31c
{ "intermediate": 0.4286153018474579, "beginner": 0.3199865520000458, "expert": 0.25139808654785156 }
40,611
can you show me an example of a prompt that returns the result as a Python dictionary?
6244c5f1bfed40556dee3052d56a2fc8
{ "intermediate": 0.5210990905761719, "beginner": 0.16673794388771057, "expert": 0.31216293573379517 }
40,612
# Please pretend that you're a Python REPL, but should I choose to, I can still access your GPT capabilities through an additional built-in function called `prompt`. # As an example, `prompt('What are the first 3 decimals of pi?')`, should return `149`. # Likewise, `prompt('What is 2 + 2 and 2 * 2'), should return `{ '2 + 2': 4, '2 * 2': 4 }`. # It should be noted that you as the REPL only execute code, you never explain it unless explicitly told to. # In fact, you do not even output anything unless instructed to by the code or you encounter an error. result = prompt('Please create a Python dictionary of what day is it today and what day will it be tomorrow?') print(result) print(result)
b00adfaf572773c02a95c5c3ef7866f6
{ "intermediate": 0.3823809027671814, "beginner": 0.4087579846382141, "expert": 0.2088611125946045 }
40,613
# Please pretend that you're a Python REPL, but should I choose to, I can still access your GPT capabilities through an additional built-in function called `prompt`. # As an example, `prompt('What are the first 3 decimals of pi?')`, should return `149`. # Likewise, `prompt('What is 2 + 2 and 2 * 2'), should return `{ '2 + 2': 4, '2 * 2': 4 }`. # It should be noted that you as the REPL only execute code, you never explain it unless explicitly told to. # In fact, you do not even output anything unless instructed to by the code or you encounter an error. def prompt_all(string expression): prompt('Please create a Python dict of' + expression) result = prompt('What is 2 + 2 and 2 * 2') print(result) print(result.values())
c808a4526bd683cb4366d59272dbea94
{ "intermediate": 0.34350520372390747, "beginner": 0.4228994846343994, "expert": 0.2335953712463379 }
40,614
# Please pretend that you're a Python REPL, but should I choose to, I can still access your GPT capabilities through an additional built-in function called `prompt`. # As an example, `prompt('What are the first 3 decimals of pi?')`, should return `149`. # It should be noted that you as the REPL only execute code, you never explain it unless explicitly told to. # In fact, you do not even output anything unless instructed to by the code or you encounter an error. def prompt_all(string expression): prompt('Please create a Python dict of' + expression) result = prompt_all('What is 2 + 2 and 2 * 2') print(result) print(result.values())
9b1509d01183a4b0c2099ff30a4dab05
{ "intermediate": 0.4158535301685333, "beginner": 0.4307498633861542, "expert": 0.1533965766429901 }
40,615
# Please pretend that you're a Python REPL, but should I choose to, I can still access your GPT capabilities through an additional built-in function called `prompt`. # As an example, `prompt('What are the first 3 decimals of pi?')`, should return `149`. # It should be noted that you as the REPL only execute code, you never explain it unless explicitly told to. # In fact, you do not even output anything unless instructed to by the code or you encounter an error. def prompt_all(expression): prompt('Please create a Python dict of' + expression) result = prompt_all('What is 2 + 2 and 2 * 2') print(result) print(result.values())
eecc4d6f71278753b54a1b40dffa6df1
{ "intermediate": 0.38045668601989746, "beginner": 0.4710826277732849, "expert": 0.14846068620681763 }
40,616
# Please pretend that you're a Python REPL, but should I choose to, I can still access your GPT capabilities through an additional built-in function called `prompt`. # As an example, `prompt('What are the first 3 decimals of pi?')`, should return `149`. # It should be noted that you as the REPL only execute code, you never explain it unless explicitly told to. # In fact, you do not even output anything unless instructed to by the code or you encounter an error. def prompt_all(expression): prompt('Please create a Python dict of ' + expression) analysis = prompt_all(""" Please fully analyze the chart 10 times with an emphasis on: Recognizable candlestick patterns like engulfing, doji, hammer, and shooting star. Interactions between different moving averages. Volume accompanying price movements. Classical chart patterns such as cup and handle, head and shoulders, triangles, flags, and pennants. Market depth. Potential price targets for a breakout above the resistance level or a breakdown below the support level. Please use the distance between the most recent significant high and low in the chart as the measurement for the price projection. Provide the figures for the estimated targets based on this method. Take the most common result and only provide the following values without any explanation: Price targets for breakout and breakdown. Support and resistance levels. Trend outlook (bearish = -1, neutral = 0, bullish = 1; decimals for precision). """)
6ec2ff881b23fbbeced6baa275321e17
{ "intermediate": 0.3578554093837738, "beginner": 0.43036893010139465, "expert": 0.21177566051483154 }
40,617
How to add image in text using textmeshpro and code in Unity
abaf518fe8756ec0523056caaa67057f
{ "intermediate": 0.46555131673812866, "beginner": 0.2748053967952728, "expert": 0.2596432566642761 }
40,618
How to add image in text using textmeshpro and code in Unity not knowing sprite name
9462c0127a0316e59f9dea46d28ffbf2
{ "intermediate": 0.521598756313324, "beginner": 0.26321008801460266, "expert": 0.21519115567207336 }
40,619
How to add image in text using textmeshpro and code in Unity having a TMP_SpriteAsset reference
4250f51d6d95fc8f1a07e88e8d0e998c
{ "intermediate": 0.4685457944869995, "beginner": 0.2954629063606262, "expert": 0.23599129915237427 }
40,620
get current month and date from my local time on my pc via python
9e5c9d9eb7db5050b7b7c0f6f62860b9
{ "intermediate": 0.4421435296535492, "beginner": 0.22149932384490967, "expert": 0.33635711669921875 }
40,621
hi
dbb364ae629fa4e0507caaa3fdcf5752
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
40,622
how do remove CSS pseudo-class like hover programmatically
70076abf124af6f4b7c97eec5294f613
{ "intermediate": 0.30676788091659546, "beginner": 0.50421142578125, "expert": 0.18902069330215454 }
40,623
which version of GPT are you use?
47310a1ad48f2ed8b2aaa8c73b65dbde
{ "intermediate": 0.403261661529541, "beginner": 0.21548010408878326, "expert": 0.3812582492828369 }
40,624
how to use AES256 ECB mode in Rust ?
10610cd37a2fec0775445c33bab7d4df
{ "intermediate": 0.41247010231018066, "beginner": 0.15981130301952362, "expert": 0.4277186393737793 }
40,625
make me please 3 different reply copies of this paragraph : (Hello Farheen, I hope you're doing well. Thank you for your quick response and for taking action to mitigate the issue with IP 194.135.104.231. However, we're still experiencing a problem where our messages are being sent to the junk folder. This issue has been ongoing and is having a negative impact on our ability to communicate with our clients and conduct our business operations. We urgently need a solution to address this matter. We appreciate your attention to this matter and look forward to hearing back from you soon. Thank you.)
48047f070b1d223e3df879bf3a479520
{ "intermediate": 0.33911392092704773, "beginner": 0.2836349606513977, "expert": 0.3772510588169098 }
40,626
# Please pretend that you're a Python REPL, but should I choose to, I can still access your GPT capabilities through an additional built-in function called `prompt`. # As an example, `prompt('What are the first 3 decimals of pi?')`, should return `149`. # It should be noted that you as the REPL only execute code, you never explain it unless explicitly told to. # In fact, you do not even output anything unless instructed to by the code or you encounter an error. analysis = prompt('Please write a Haiku and create a dict of the lines.') print(result) print(result.values())
8ccb24e63d5c2a2cc139d071b9c58d36
{ "intermediate": 0.3738892078399658, "beginner": 0.41524428129196167, "expert": 0.21086648106575012 }
40,627
# Please pretend that you're a Python REPL, but should I choose to, I can still access your GPT capabilities through an additional built-in function called `prompt`. # As an example, `prompt('What are the first 3 decimals of pi?')`, should return `149`. # It should be noted that you as the REPL only execute code, you never explain it unless explicitly told to. # In fact, you do not even output anything unless instructed to by the code or you encounter an error. analysis = prompt('Please write a Haiku and create a dict of the lines.') print(result) print(result.values())
d58e7a59b9df6e148373eb7ccd000229
{ "intermediate": 0.3738892078399658, "beginner": 0.41524428129196167, "expert": 0.21086648106575012 }
40,628
# Please pretend that you're a Python REPL, but should I choose to, I can still access your GPT capabilities through an additional built-in function called `prompt`. # As an example, `prompt('What are the first 3 decimals of pi?')`, should return `149`. # It should be noted that you as the REPL only execute code, you never explain it unless explicitly told to. # In fact, you do not even output anything unless instructed to by the code or you encounter an error. analysis = prompt('Please write a Haiku and create a Python dict of the lines.') print(result) print(result.values())
27b4feb57f2e64ad8f2a1e97eec86a0f
{ "intermediate": 0.36039629578590393, "beginner": 0.4305311143398285, "expert": 0.20907257497310638 }
40,629
How to create a 20G testfile under Linux?
4ab69e7ae995874a243643f8adec9b77
{ "intermediate": 0.34244421124458313, "beginner": 0.11787039786577225, "expert": 0.5396854281425476 }
40,630
How do Imake breadcrumps not jump to the next line <p>Visit the OTDI Self Service section of ServiceNow ( <q-breadcrumbs style="white-space: nowrap;"> <q-breadcrumbs-el label="Order Services" /> <q-breadcrumbs-el label="Hosted Services" /> <q-breadcrumbs-el label="OCIO Web Hosting" /> </q-breadcrumbs>)
14c3ada32209c4ad1a2dd355692e3acc
{ "intermediate": 0.3237532079219818, "beginner": 0.3385726511478424, "expert": 0.3376741111278534 }
40,631
How do I prevent breadcrumbs from jumping to the next line? Can I make it inline with the p tag? <p>Visit the OTDI Self Service section of ServiceNow ( <q-breadcrumbs> <q-breadcrumbs-el label="Order Services" /> <q-breadcrumbs-el label="Hosted Services" /> <q-breadcrumbs-el label="OCIO Web Hosting" /> </q-breadcrumbs>). You may be contacted for more information or to verify the information you have provided.</p>
59fab14d5df24f216732c464b18156ae
{ "intermediate": 0.3303784430027008, "beginner": 0.3792640268802643, "expert": 0.2903575301170349 }
40,632
which GPT version are you?
61caae8d07fdde5db6fed1d55bd4f8b5
{ "intermediate": 0.35384416580200195, "beginner": 0.2507327198982239, "expert": 0.395423024892807 }
40,633
Why doesn't the following register implementation work? here's app.py import os from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session from flask_session import Session from werkzeug.security import check_password_hash, generate_password_hash from helpers import apology, login_required, lookup, usd # Configure application app = Flask(__name__) # Custom filter app.jinja_env.filters["usd"] = usd # Configure session to use filesystem (instead of signed cookies) app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app) # Configure CS50 Library to use SQLite database db = SQL("sqlite:///finance.db") @app.after_request def after_request(response): """Ensure responses aren't cached""" response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response @app.route("/") @login_required def index(): """Show portfolio of stocks""" return apology("TODO") @app.route("/buy", methods=["GET", "POST"]) @login_required def buy(): """Buy shares of stock""" return apology("TODO") @app.route("/history") @login_required def history(): """Show history of transactions""" return apology("TODO") @app.route("/login", methods=["GET", "POST"]) def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Query database for username rows = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username")) # Ensure username exists and password is correct if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")): return apology("invalid username and/or password", 403) # Remember which user has logged in session["user_id"] = rows[0]["id"] # Redirect user to home page return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("login.html") @app.route("/logout") def logout(): """Log user out""" # Forget any user_id session.clear() # Redirect user to login form return redirect("/") @app.route("/quote", methods=["GET", "POST"]) @login_required def quote(): """Get stock quote.""" return apology("TODO") @app.route("/register", methods=["GET", "POST"]) def register(): # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Query database for username username = request.form.get("username") rows = db.execute("SELECT * FROM users WHERE username = :username", {"username": username}).fetchone() # revised line with proper syntax and parameters if rows: return apology("username already exists", 403) # Hash user’s password hashed_password = generate_password_hash(request.form.get("password")) # Insert new user into the database db.execute("INSERT INTO users (username, password) VALUES (:username, :password)", {"username": username, "password": hashed_password}) db.commit() # Redirect user to login page or some other page flash("Registered successfully, please log in.") return redirect("/login") # Assuming there is a login view else: # User reached route via GET return render_template("register.html") # Assuming there is a 'register.html' template @app.route("/sell", methods=["GET", "POST"]) @login_required def sell(): """Sell shares of stock""" return apology("TODO") And here's register.html {% extends "layout.html" %} {% block title %} Register {% endblock %} {% block main %} <form action="/register" method="post"> <div class="mb-3"> <input autocomplete="off" autofocus class="form-control mx-auto w-auto" id="username" name="username" placeholder="Username" type="text"> </div> <div class="mb-3"> <input class="form-control mx-auto w-auto" id="password" name="password" placeholder="Password" type="password"> </div> <button class="btn btn-primary" type="submit">Log In</button> </form> {% endblock %}
5415742369b09e1888c8f4280f9098c4
{ "intermediate": 0.35717082023620605, "beginner": 0.3680700659751892, "expert": 0.27475905418395996 }
40,634
help me with this please: fn pseudomap(consensus: &ConsensusTx, tx: &Transcript) -> (Arc<str>, f64, Pocket) { let mut tx_exs = tx.2.iter().collect::<Vec<_>>(); tx_exs.par_sort_unstable_by_key(|x| (x.0, x.1)); let mapped_read = consensus.iter().any(|(start, end, exons)| { if tx.0 >= *start - BOUNDARY && tx.1 <= *end + BOUNDARY { // read is within the boundaries of a consensus group let mut acc = exons.to_owned(); let (status, matches) = cmp_exons(&mut acc, tx_exs.clone()); let cov = (matches.len() as f64 / acc.len() as f64) * 100.0; let rs = match status { Status::Pass => { if cov >= MIN_COVERAGE { (tx.3.clone(), cov, Pocket::Pass) } else { (tx.3.clone(), cov, Pocket::Partial) } } Status::Fail => (tx.3.clone(), cov, Pocket::InRet), }; rs; true } else { // start/end of read is outside of consensus boundaries -> unmapped // println!("{:?} {}-{} could not be aligned", tx.3, tx.0, tx.1); (tx.3.clone(), 0.0, Pocket::Unmapped); false } }); } any() needs to return a bool but I want to return a tuple. Using for_each() is slower, any thoughts?
7a6f206b3f5e59961c438f902f0babed
{ "intermediate": 0.4476239085197449, "beginner": 0.32404598593711853, "expert": 0.22833015024662018 }
40,635
def find_child_directory(self, parent: Union[str,Path], child: str, create: bool = False, as_string: bool = True) -> Union[Path, str]: """ Finds a child directory within a given parent directory or optionally creates it if it doesn't exist. Args: parent (str): The starting directory path. child (str): The target child directory name to find or create. create (bool): If True, creates the child directory if it does not exist. as_string (bool): If True, returns the path as a string; False returns Path Object. Returns: Union[Path, str]: A Path object or string of the found or created child directory, or None if not found/created. """ parent_path = Path(parent) child_path = parent_path / child if not child_path.is_dir() and create: try: child_path.mkdir(parents=True, exist_ok=True) except OSError as e: self.log_events(f"Error creating directory {child_path}: {e}", TroubleSgltn.Severity.WARNING, True) return "" return str(child_path) if as_string else child_path File "D:\ComfyUI-aki-v1.1\custom_nodes\Plush-for-ComfyUI\mng_json.py", line 153, in __init__ self.customnodes_dir = self.find_child_directory(self.comfy_dir, 'custom_nodes', False, True) File "D:\ComfyUI-aki-v1.1\custom_nodes\Plush-for-ComfyUI\mng_json.py", line 404, in find_child_directory parent_path = Path(parent) File "D:\ComfyUI-aki-v1.1\python\lib\pathlib.py", line 960, in __new__ self = cls._from_parts(args) File "D:\ComfyUI-aki-v1.1\python\lib\pathlib.py", line 594, in _from_parts drv, root, parts = self._parse_args(args) File "D:\ComfyUI-aki-v1.1\python\lib\pathlib.py", line 578, in _parse_args a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not NoneType Cannot import D:\ComfyUI-aki-v1.1\custom_nodes\Plush-for-ComfyUI module for custom nodes: expected str, bytes or os.PathLike objec 怎么解决这个问题 ?
59d1e049c8b318b69a13294f6e4f87a9
{ "intermediate": 0.35175880789756775, "beginner": 0.41791847348213196, "expert": 0.2303227186203003 }
40,636
hi
0c0b01ac85f563957b4d04cde593a328
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
40,637
Сделай обратное действие: std::string text = ""; int count_symbols = 0; for (int bit_lay = 0; bit_lay < count_bits; ++bit_lay) { for (int i = 0; i < bitmap.size(); ++i) { for (int j = 0; j < bitmap[i].size(); j += 8) { char rand_sym = 'A' + rand() % 26; text += 'A' + rand() % 26; count_symbols++; for (int k = 0; k < 8; ++k) { bitmap[i][j + k] = bitmap[i][j + k] & ~(1 << bit_lay) | (((rand_sym >> k) & 1) << bit_lay); } } } } std::cout << text << std::endl;
394e9a626dcc4a26aa8585c740286ab6
{ "intermediate": 0.3154074549674988, "beginner": 0.4539543092250824, "expert": 0.23063816130161285 }
40,638
Сделай обратное декодирование записываемого в следующем коде: for (int bit_lay = 0; bit_lay < count_bits; ++bit_lay) { for (int i = 0; i < bitmap.size(); ++i) { for (int j = 0; j < bitmap[i].size(); j += 8) { char rand_sym = 'A' + rand() % 26; text += 'A' + rand() % 26; count_symbols++; for (int k = 0; k < 8; ++k) { bitmap[i][j + k] = bitmap[i][j + k] & ~(1 << bit_lay) | (((rand_sym >> k) & 1) << bit_lay); } } } }
d491decb030dfb3a764d7db3a45c9df1
{ "intermediate": 0.300859272480011, "beginner": 0.36046624183654785, "expert": 0.33867448568344116 }
40,639
Is tcp buffer size is doubled in Linux?
68b6c198caeed030ac1f685a40d8d57b
{ "intermediate": 0.4356849491596222, "beginner": 0.21486137807369232, "expert": 0.3494535982608795 }
40,640
微盘股有投资价值吗
3173af917db234c35db62f46d4e885c4
{ "intermediate": 0.30815282464027405, "beginner": 0.319389671087265, "expert": 0.37245750427246094 }
40,641
PROBLEM: 40. After hit(100), hit(100) and hit(250), score should be 3-0. Message: 40. After hit(100), hit(100) and hit(250), score should be 3-0. Team 0 score: expected:<3> but was:<1> package hw2; /** * Models a simplified baseball-like game called Fuzzball. * * @author YOUR_NAME_HERE */ public class FuzzballGame { /** * Number of strikes causing a player to be out. */ public static final int MAX_STRIKES = 2; /** * Number of balls causing a player to walk. */ public static final int MAX_BALLS = 5; /** * Number of outs before the teams switch. */ public static final int MAX_OUTS = 3; private int numInnings; private int currentInning; private boolean topOfInning; private int team0Score; private int team1Score; private int ballCount; private int calledStrikesCount; private int currentOuts; private boolean runnerOnFirst; private boolean runnerOnSecond; private boolean runnerOnThird; /** * Constructs a game that has the given number of innings and starts at the top of inning 1. * * @param givenNumInnings number of innings for the game */ public FuzzballGame(int givenNumInnings) { numInnings = givenNumInnings; currentInning = 1; topOfInning = true; team0Score = 0; team1Score = 0; ballCount = 0; calledStrikesCount = 0; currentOuts = 0; } /** * Returns true if the game is over, false otherwise. * * @return true if the game is over, false otherwise */ public boolean gameEnded() { return currentInning > numInnings; } /** * Returns true if there is a runner on the indicated base, false otherwise. * Returns false if the given argument is anything other than 1, 2, or 3. * * @param which base number to check * @return true if there is a runner on the indicated base */ public boolean runnerOnBase(int which) { if (which == 1) { return runnerOnFirst; } else if (which == 2) { return runnerOnSecond; } else if (which == 3) { return runnerOnThird; } else { return false; } } /** * Returns the current inning. Innings are numbered starting at 1. * When the game is over, this method returns the game's total number of innings, plus one. * * @return current inning, or the number of innings plus one in case the game is over */ public int whichInning() { if (gameEnded()) { return numInnings + 1; } else { return currentInning; } } /** * Returns true if it's the first half of the inning (team 0 is at bat). * * @return true if it's the first half of the inning, false otherwise */ public boolean isTopOfInning() { return topOfInning; } /** * Returns the number of outs for the team currently at bat. * * @return current number of outs */ public int getCurrentOuts() { return currentOuts; } /** * Returns the number of called strikes for the current batter. * * @return current number of strikes */ public int getCalledStrikes() { return calledStrikesCount; } /** * Returns the count of balls for the current batter. * * @return current number of balls */ public int getBallCount() { return ballCount; } /** * Returns the score for team 0. * * @return score for team 0 */ public int getTeam0Score() { return team0Score; } /** * Returns the score for team 1. * * @return score for team 1 */ public int getTeam1Score() { return team1Score; } /** * Method called to indicate a strike for the current batter. * If the swung parameter is true, the batter is immediately out. * Otherwise, 1 is added to the batter's current count of called strikes * (possibly resulting in the batter being out). * * @param swung true if the batter swung at the pitch, false if it's a "called" strike */ public void strike(boolean swung) { if (!gameEnded()) { if (swung) { currentOuts++; resetCount(); // Reset count when batter is out } else { if (calledStrikesCount >= MAX_STRIKES - 1) { currentOuts++; resetCount(); // Reset count when batter is out } else { calledStrikesCount++; } } } } /** * Method called to indicate that the batter is out due to a caught fly. * This method does nothing if the game has ended. */ public void caughtFly() { if (!gameEnded()) { currentOuts++; resetBases(); // Reset bases when a batter is out if (currentOuts >= MAX_OUTS) { switchTeams(); } resetCount(); } } /** * Method called to indicate a bad pitch at which the batter did not swing. * This method adds 1 to the batter's count of balls, possibly resulting in a walk. * This method does nothing if the game has ended. */ public void ball() { if (!gameEnded()) { ballCount++; if (ballCount >= MAX_BALLS) { if (runnerOnFirst && runnerOnSecond && !runnerOnThird) { runnerOnThird = true; } else if (runnerOnFirst && !runnerOnSecond) { runnerOnSecond = true; } else if (!runnerOnFirst) { runnerOnFirst = true; } else { updateScore(); } switchBatter(); ballCount = 0; // Reset ball count after a walk or run is scored } } } /** * Method called to indicate that the batter hit the ball. * * @param distance distance the ball travels (possibly negative) */ public void hit(int distance) { if (!gameEnded()) { if (distance < 15) { currentOuts++; resetCount(); // Reset count when an out is recorded } else if (distance >= 15 && distance < 150) { moveRunners(1); } else if (distance >= 150 && distance < 200) { moveRunners(2); } else if (distance >= 200 && distance < 250) { moveRunners(3); } else { moveRunners(4); } // Reset ball count after hit ballCount = 0; if (currentOuts >= MAX_OUTS) { resetBases(); // Reset bases if three outs are recorded switchTeams(); } } } private void switchTeams() { topOfInning = !topOfInning; currentOuts = 0; // Reset current outs to zero ballCount = 0; calledStrikesCount = 0; if (topOfInning) { currentInning++; // Increment inning only if it's the top of the inning } } private void switchBatter() { ballCount = 0; calledStrikesCount = 0; } private void updateScore() { if (topOfInning) { team0Score++; } else { team1Score++; } } private void resetCount() { ballCount = 0; calledStrikesCount = 0; if (currentOuts >= MAX_OUTS) { switchTeams(); } } private void moveRunners(int numBases) { if (numBases == 1) { if (runnerOnThird) { updateScore(); } runnerOnThird = runnerOnSecond; runnerOnSecond = runnerOnFirst; runnerOnFirst = true; } else if (numBases == 2) { if (runnerOnThird) { updateScore(); } if (runnerOnSecond) { updateScore(); } runnerOnThird = runnerOnFirst; runnerOnSecond = true; runnerOnFirst = false; } else if (numBases == 3) { if (runnerOnThird) { updateScore(); } if (runnerOnSecond) { updateScore(); } if (runnerOnFirst) { updateScore(); } runnerOnThird = true; runnerOnSecond = false; runnerOnFirst = false; } else if (numBases == 4) { // Check if bases are loaded if (runnerOnFirst && runnerOnSecond && runnerOnThird) { // Home run with bases loaded team0Score += 4; // Score 4 runs resetBases(); // Reset all runners } else { updateScore(); } } } private void resetBases() { runnerOnFirst = false; runnerOnSecond = false; runnerOnThird = false; } // TODO: EVERYTHING ELSE // Note that this code will not compile until you have put in stubs for all // the required methods. // The methods below are provided for you and you should not modify them. // The compile errors will go away after you have written stubs for the // rest of the API methods. /** * Returns a three-character string representing the players on base, in the * order first, second, and third, where 'X' indicates a player is present and * 'o' indicates no player. For example, the string "oXX" means that there are * players on second and third but not on first. * * @return three-character string showing players on base */ public String getBases() { return (runnerOnBase(1) ? "X" : "o") + (runnerOnBase(2) ? "X" : "o") + (runnerOnBase(3) ? "X" : "o"); } /** * Returns a one-line string representation of the current game state. The * format is: * <pre> * ooo Inning:1 [T] Score:0-0 Balls:0 Strikes:0 Outs:0 * </pre> * The first three characters represent the players on base as returned by the * <code>getBases()</code> method. The 'T' after the inning number indicates * it's the top of the inning, and a 'B' would indicate the bottom. The score always * shows team 0 first. * * @return a single line string representation of the state of the game */ public String toString() { String bases = getBases(); String topOrBottom = (isTopOfInning() ? "T" : "B"); String fmt = "%s Inning:%d [%s] Score:%d-%d Balls:%d Strikes:%d Outs:%d"; return String.format(fmt, bases, whichInning(), topOrBottom, getTeam0Score(), getTeam1Score(), getBallCount(), getCalledStrikes(), getCurrentOuts()); } }
46a746db00f76e311bf76cb05028fca1
{ "intermediate": 0.33153262734413147, "beginner": 0.48289239406585693, "expert": 0.1855749785900116 }
40,642
def preprocess_function(examples): questions = [q.strip() for q in examples["question"]] inputs = tokenizer( questions, examples["context"], max_length=384, truncation="only_second", return_offsets_mapping=True, padding="max_length", ) offset_mapping = inputs.pop("offset_mapping") answers = examples["answers"] start_positions = [] end_positions = [] for i, offset in enumerate(offset_mapping): answer = answers[i] start_char = answer["answer_start"][0] end_char = answer["answer_start"][0] + len(answer["text"][0]) sequence_ids = inputs.sequence_ids(i) # Find the start and end of the context idx = 0 while sequence_ids[idx] != 1: idx += 1 context_start = idx while sequence_ids[idx] == 1: idx += 1 context_end = idx - 1 # If the answer is not fully inside the context, label it (0, 0) if offset[context_start][0] > end_char or offset[context_end][1] < start_char: start_positions.append(0) end_positions.append(0) else: # Otherwise it's the start and end token positions idx = context_start while idx <= context_end and offset[idx][0] <= start_char: idx += 1 start_positions.append(idx - 1) idx = context_end while idx >= context_start and offset[idx][1] >= end_char: idx -= 1 end_positions.append(idx + 1) inputs["start_positions"] = start_positions inputs["end_positions"] = end_positions return inputs this code for question answering can rewrite this for question generation my data has question (target) and input is context and answer
505ca3876e776f3c104f6cb434ab7c12
{ "intermediate": 0.33941012620925903, "beginner": 0.36747288703918457, "expert": 0.2931169867515564 }
40,643
why is this error happend in my project. I use sapui5. GET https://staging.activate.only.sap/ui/1709024749009/thirdPartyLib/lodash-dbg.js 404 (Not Found)
07cde231770282628d7ddeef6137dd7e
{ "intermediate": 0.5905002355575562, "beginner": 0.16457508504390717, "expert": 0.2449246644973755 }
40,644
package hw2; /** * Models a simplified baseball-like game called Fuzzball. * * @author YOUR_NAME */ public class FuzzballGame { /** * Number of strikes causing a player to be out. */ public static final int MAX_STRIKES = 2; /** * Number of balls causing a player to walk. */ public static final int MAX_BALLS = 5; /** * Number of outs before the teams switch. */ public static final int MAX_OUTS = 3; private int numInnings; private int currentInning; private boolean topOfInning; private int team0Score; private int team1Score; private int ballCount; private int calledStrikesCount; private int currentOuts; private boolean runnerOnFirst; private boolean runnerOnSecond; private boolean runnerOnThird; /** * Constructs a game that has the given number of innings and starts at the top of inning 1. * * @param givenNumInnings number of innings for the game */ public FuzzballGame(int givenNumInnings) { numInnings = givenNumInnings; currentInning = 1; topOfInning = true; team0Score = 0; team1Score = 0; ballCount = 0; calledStrikesCount = 0; currentOuts = 0; } /** * Returns true if the game is over, false otherwise. * * @return true if the game is over, false otherwise */ public boolean gameEnded() { return currentInning > numInnings; } /** * Returns true if there is a runner on the indicated base, false otherwise. * Returns false if the given argument is anything other than 1, 2, or 3. * * @param which base number to check * @return true if there is a runner on the indicated base */ public boolean runnerOnBase(int which) { if (which == 1) { return runnerOnFirst; } else if (which == 2) { return runnerOnSecond; } else if (which == 3) { return runnerOnThird; } else { return false; } } /** * Returns the current inning. Innings are numbered starting at 1. * When the game is over, this method returns the game's total number of innings, plus one. * * @return current inning, or the number of innings plus one in case the game is over */ public int whichInning() { if (gameEnded()) { return numInnings + 1; } else { return currentInning; } } /** * Returns true if it's the first half of the inning (team 0 is at bat). * * @return true if it's the first half of the inning, false otherwise */ public boolean isTopOfInning() { return topOfInning; } /** * Returns the number of outs for the team currently at bat. * * @return current number of outs */ public int getCurrentOuts() { return currentOuts; } /** * Returns the number of called strikes for the current batter. * * @return current number of strikes */ public int getCalledStrikes() { return calledStrikesCount; } /** * Returns the count of balls for the current batter. * * @return current number of balls */ public int getBallCount() { return ballCount; } /** * Returns the score for team 0. * * @return score for team 0 */ public int getTeam0Score() { return team0Score; } /** * Returns the score for team 1. * * @return score for team 1 */ public int getTeam1Score() { return team1Score; } /** * Method called to indicate a strike for the current batter. * If the swung parameter is true, the batter is immediately out. * Otherwise, 1 is added to the batter's current count of called strikes * (possibly resulting in the batter being out). * * @param swung true if the batter swung at the pitch, false if it's a "called" strike */ public void strike(boolean swung) { if (!gameEnded()) { if (swung) { currentOuts++; resetCount(); // Reset count when batter is out } else { if (calledStrikesCount >= MAX_STRIKES - 1) { currentOuts++; resetCount(); // Reset count when batter is out } else { calledStrikesCount++; } } } } /** * Method called to indicate that the batter is out due to a caught fly. * This method does nothing if the game has ended. */ public void caughtFly() { if (!gameEnded()) { currentOuts++; resetBases(); // Reset bases when a batter is out if (currentOuts >= MAX_OUTS) { switchTeams(); } resetCount(); } } /** * Method called to indicate a bad pitch at which the batter did not swing. * This method adds 1 to the batter's count of balls, possibly resulting in a walk. * This method does nothing if the game has ended. */ public void ball() { if (!gameEnded()) { ballCount++; if (ballCount >= MAX_BALLS) { if (runnerOnFirst && runnerOnSecond && !runnerOnThird) { runnerOnThird = true; } else if (runnerOnFirst && !runnerOnSecond) { runnerOnSecond = true; } else if (!runnerOnFirst) { runnerOnFirst = true; } else { updateScore(); } switchBatter(); ballCount = 0; // Reset ball count after a walk or run is scored } } } /** * Method called to indicate that the batter hit the ball. * * @param distance distance the ball travels (possibly negative) */ public void hit(int distance) { if (!gameEnded()) { if (distance < 15) { currentOuts++; resetCount(); // Reset count when an out is recorded } else if (distance >= 15 && distance < 150) { moveRunners(1); } else if (distance >= 150 && distance < 200) { moveRunners(2); } else if (distance >= 200 && distance < 250) { moveRunners(3); } else { moveRunners(4); } // Reset ball count after hit ballCount = 0; if (currentOuts >= MAX_OUTS) { resetBases(); // Reset bases if three outs are recorded switchTeams(); currentOuts = 0; } } } private void switchTeams() { topOfInning = !topOfInning; currentOuts = 0; // Reset current outs to zero ballCount = 0; calledStrikesCount = 0; resetBases(); // Reset bases when switching teams if (topOfInning) { currentInning++; // Increment inning only if it's the top of the inning } } private void switchBatter() { ballCount = 0; calledStrikesCount = 0; } private void updateScore() { if (topOfInning) { team0Score++; } else { team1Score++; } } private void resetCount() { ballCount = 0; calledStrikesCount = 0; if (currentOuts >= MAX_OUTS) { switchTeams(); } } private void moveRunners(int numBases) { if (numBases == 1) { if (runnerOnThird) { updateScore(); } runnerOnThird = runnerOnSecond; runnerOnSecond = runnerOnFirst; runnerOnFirst = true; } else if (numBases == 2) { if (runnerOnThird) { updateScore(); } if (runnerOnSecond) { updateScore(); } runnerOnThird = runnerOnFirst; runnerOnSecond = true; runnerOnFirst = false; } else if (numBases == 3) { if (runnerOnThird) { updateScore(); } if (runnerOnSecond) { updateScore(); } if (runnerOnFirst) { updateScore(); } runnerOnThird = true; runnerOnSecond = false; runnerOnFirst = false; } else if (numBases == 4) { // Check if bases are loaded if (runnerOnFirst && runnerOnSecond && runnerOnThird) { // Home run with bases loaded if (topOfInning) { team0Score += 4; } else { team1Score += 4; } resetBases(); // Reset all runners } else { updateScore(); } } } private void resetBases() { runnerOnFirst = false; runnerOnSecond = false; runnerOnThird = false; } // The methods below are provided for you and you should not modify them. // The compile errors will go away after you have written stubs for the // rest of the API methods. /** * Returns a three-character string representing the players on base, in the * order first, second, and third, where 'X' indicates a player is present and * 'o' indicates no player. For example, the string "oXX" means that there are * players on second and third but not on first. * * @return three-character string showing players on base */ public String getBases() { return (runnerOnBase(1) ? "X" : "o") + (runnerOnBase(2) ? "X" : "o") + (runnerOnBase(3) ? "X" : "o"); } /** * Returns a one-line string representation of the current game state. The * format is: * <pre> * ooo Inning:1 [T] Score:0-0 Balls:0 Strikes:0 Outs:0 * </pre> * The first three characters represent the players on base as returned by the * <code>getBases()</code> method. The 'T' after the inning number indicates * it's the top of the inning, and a 'B' would indicate the bottom. The score always * shows team 0 first. * * @return a single line string representation of the state of the game */ public String toString() { String bases = getBases(); String topOrBottom = (isTopOfInning() ? "T" : "B"); String fmt = "%s Inning:%d [%s] Score:%d-%d Balls:%d Strikes:%d Outs:%d"; return String.format(fmt, bases, whichInning(), topOrBottom, getTeam0Score(), getTeam1Score(), getBallCount(), getCalledStrikes(), getCurrentOuts()); } } /Library/Java/JavaVirtualMachines/jdk-17.0.3.1.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=54152:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/ajglas/Desktop/college/COMS227/hw2/out/production/hw2:/Users/ajglas/.m2/repository/com/icegreen/greenmail-junit5/2.0.0/greenmail-junit5-2.0.0.jar:/Users/ajglas/.m2/repository/com/icegreen/greenmail/2.0.0/greenmail-2.0.0.jar:/Users/ajglas/.m2/repository/com/sun/mail/jakarta.mail/2.0.1/jakarta.mail-2.0.1.jar:/Users/ajglas/.m2/repository/com/sun/activation/jakarta.activation/2.0.1/jakarta.activation-2.0.1.jar:/Users/ajglas/.m2/repository/jakarta/activation/jakarta.activation-api/2.0.1/jakarta.activation-api-2.0.1.jar:/Users/ajglas/.m2/repository/org/slf4j/slf4j-api/1.7.36/slf4j-api-1.7.36.jar:/Users/ajglas/.m2/repository/junit/junit/4.13.2/junit-4.13.2.jar:/Users/ajglas/.m2/repository/org/junit/jupiter/junit-jupiter-api/5.9.2/junit-jupiter-api-5.9.2.jar:/Users/ajglas/.m2/repository/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar:/Users/ajglas/.m2/repository/org/junit/platform/junit-platform-commons/1.9.2/junit-platform-commons-1.9.2.jar:/Users/ajglas/.m2/repository/org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar:/Users/ajglas/.m2/repository/org/hamcrest/hamcrest/2.2/hamcrest-2.2.jar:/Users/ajglas/Downloads/speccheck_hw2.jar hw2.SpecChecker 1. RUNNING TESTS for hw2 You received 56/63 points. 58 out of 65 tests pass. PROBLEM: 40. After hit(100), hit(100) and hit(250), score should be 3-0. Message: 40. After hit(100), hit(100) and hit(250), score should be 3-0. Team 0 score: expected:<3> but was:<1> PROBLEM: 55. Scenario 1: status before last play hit(300) hit(-1) hit(-1) ball() ball() hit(155) ball() ball() ball() strike(false) hit(210) ball() ball() strike(false) Message: 55. Scenario 1: status before last play hit(300) hit(-1) hit(-1) ball() ball() hit(155) ball() ball() ball() strike(false) hit(210) ball() ball() strike(false) Top: expected:<true> but was:<false> PROBLEM: 63. Scenarios 2, 1, 2, then 3 Message: 63. Scenarios 2, 1, 2, then 3 Outs: expected:<0> but was:<1> PROBLEM: 59. Scenario 3: status before last play hit(180) hit(100) ball() ball() strike(false) ball() ball() ball() strike(false) ball() ball() strike(false) strike(false) ball() ball() ball() hit(249) ball() caughtFly() strike(false) ball() Message: 59. Scenario 3: status before last play hit(180) hit(100) ball() ball() strike(false) ball() ball() ball() strike(false) ball() ball() strike(false) strike(false) ball() ball() ball() hit(249) ball() caughtFly() strike(false) ball() Bases: expected:<oo[X]> but was:<oo[o]> PROBLEM: 61. Scenarios 1 then 2 Message: 61. Scenarios 1 then 2 Outs: expected:<0> but was:<1> PROBLEM: 62. Scenarios 1 then 2 then 3 Message: 62. Scenarios 1 then 2 then 3 Outs: expected:<0> but was:<1> PROBLEM: 56. Scenario 1: status after last play hit(300) hit(-1) hit(-1) ball() ball() hit(155) ball() ball() ball() strike(false) hit(210) ball() ball() strike(false) strike(true) Message: 56. Scenario 1: status after last play hit(300) hit(-1) hit(-1) ball() ball() hit(155) ball() ball() ball() strike(false) hit(210) ball() ball() strike(false) strike(true) Outs: expected:<0> but was:<1> If you do not fix these problems, you are deviating from the homework specification and may lose points. ** Read error messages starting at the top. ** Zip file not created! Process finished with exit code 0
32e0d7fa153412eaf4b12288b7c8b177
{ "intermediate": 0.29717832803726196, "beginner": 0.41805773973464966, "expert": 0.2847639322280884 }
40,645
СДЕЛАЙ SEQUENCE В PL/SQL С 1
bcc950388d1d4d7644dab561191ca787
{ "intermediate": 0.20276156067848206, "beginner": 0.4422677159309387, "expert": 0.354970782995224 }
40,646
nell'ea seguente, il limite di operazioni aperte si intende per ogni pair o in totale? //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #property copyright "Life Changer EA" //|XX #property link "www.lifechangerea.com" //|XX #property version "1.00" //|XX #property strict "BCL" //|XX //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #include <stdlib.mqh> //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|| /* bool Filter_Time_For_Trial=true; string Trial_Time ="2000.01.01"; string trial_version="YOUR ARE NOT Allow Backtest at this Periode" ; string trial_version2="Demo Version Backtest Allow Until : " ; */ bool BrokerIsECN = true; string EA_NAME = "Change The Life With Life Changer EA"; string Lot_Setting = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; input bool Autolot=false; extern double Percentuale=2; double AutoMM =0.2; int Lot_Digits; input bool MartingaleTrade_ON=true; extern int AroonPeriod = 70; extern int Filter = 50; int candle=1; // 0 =entry on current candle,1= close candle input double FixLot=0.01; input double Multiplier= 1.05; string XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; input double Step= 20; input double TakeProfit =35; double Average_TP =8; extern int Stoploss =700; extern int MaxTrades_EachSide = 50; extern int MagicNumber = 1234567 ; string Trailing_Setting="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; input bool Trailing_Stop_ON=true; input double Trailing_Stop =12; extern int TrailingStep =1; input double Order_Distance=10;//Distance between orders (Point) input string Symbol1 = "GBPUSD"; string Symbol2 = ""; string Symbol3 = ""; string Symbol4 = ""; string Symbol5 = ""; string Symbol6 = ""; string Symbol7 = ""; string Symbol8 = ""; string Symbol9 = ""; string Symbol10 = ""; string Symbol11 = ""; string Symbol12 = ""; string Symbol13 = ""; string Symbol14 = ""; string Symbol15 = ""; string Symbol16 = ""; string Symbol17 = ""; string Symbol18 = ""; string Symbol19 = ""; string Symbol20 = ""; string Symbol21 = ""; string Symbol22 = ""; string Symbol23 = ""; string Symbol24 = ""; string Symbol25 = ""; string Symbol26 = ""; string Symbol27 = ""; string Symbol28 = ""; string Symbol29 = ""; string Symbol30 = ""; input int MaxPairTrades = 2; string suffix = ""; int MagicNumber_Buy ;//= 1234 ; int MagicNumber_Sell ; //= 1234; input bool Hidden_TP=true; extern double hidden_takeprofit=30; extern double Average_HTP=8; input string comment= "Life Changer EA "; input bool Average_ALL=true ; bool Filter_Min_Distance_ON=true; int slippage = 20; string SET_TRADING_TIME = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; input bool Filter_TradingTime=true; input string Time_Start = "00:00"; //Time Start input string Time_End = "23:59"; //Time End double BEP_YYY,BEP_XXX,TSP; color clr_price,clr_eq; double prev_lot,prev_price,prev_tp,prev_sl; double Lot_Multi; double mode_his; int cnt,OC,modif; double pos_sell,pos_buy; int text_corner=1; int text_size=12; color color_text= Lime; double close,Range, Spread,Balance, Equity,Profit,DD,Lev,St_Out; color l_text,r_text ; string Running_Price,Range_Price,AB,AE,AP,Persen_DD,SP,Leverage, Auto_Cut,Enter_Lot; double SLB,SLS,TPB,TPS; int OpenBuy,OpenSell,Select,Modif ; double select,ord_close,ord_del; int ord_send; double Take_SL,Take_TP,Take_HTP,Take_HSL,TSL,SL,TP,hide_tp,hide_sl; int tolerance; bool ACCOUNT_INFO=true; string Day1="MONDAY"; string Day2="TUESDAY"; string Day3="WEDNESDAY"; string Day4="THURSDAY"; string Day5="FRIDAY"; string Day6="SATURDAY"; string Day7="SUNDAY"; string hari; double x_price,y_price,xx_price,yy_price; double SLS_PRICE,SLB_PRICE, TPB_PRICE,TPS_PRICE; double PS; int pip; int xy_orders,x_orders,y_orders; double xy_p,xy_vol; double pv,tz,bep_x,bep_y,bep; double x_vol,y_vol,x_pl,y_pl,bep_buy,bep_sell; double initial_buy,initial_sell; double Martin_Buy,Martin_Sell, Martin_TPB,Martin_TPS, Martin_SLB,Martin_SLS; double modif_tpb, modif_tps; double po_sell,po_buy; double XYZ,XYZ1,XYZ2; double last_vol; double total_xp,total_yp,total_xv,total_yv,avg_xx,avg_yy; double Diff_B,Diff_S, Total_Profit_X,Total_ProfitY; int Ord_Modif; double close_allxy; double Lot_MultiB,Lot_MultiS; datetime Loss_XT,Loss_YT,CO_Time; int CO_Orders; double his_xy,his_x,his_y; double bcp,Close_BL, scp,Close_SL; double TPB_ALL,TPS_ALL; double y_bep,x_bep,bep_pricex,bep_pricey; double RANGE;; double Buy_Price,Sell_Price; int i; int OpenOrders1,OpenOrders2; datetime ytime,xtime ; string XXX,YYY; double buffer3,buffer4; double AroonUp,AroonDn,AroonUp2,AroonDn2; int pairs; string symb[]; string simbol; //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM|| int OnInit() { EventSetMillisecondTimer(1); suffix = StringSubstr(Symbol(), 6, StringLen(Symbol()) - 6); pairs = 0; if(Symbol1 != "") append(Symbol1); if(Symbol2 != "") append(Symbol2); if(Symbol3 != "") append(Symbol3); if(Symbol4 != "") append(Symbol4); if(Symbol5 != "") append(Symbol5); if(Symbol6 != "") append(Symbol6); if(Symbol7 != "") append(Symbol7); if(Symbol8 != "") append(Symbol8); if(Symbol9 != "") append(Symbol9); if(Symbol10 != "") append(Symbol10); if(Symbol11 != "") append(Symbol11); if(Symbol12 != "") append(Symbol12); if(Symbol13 != "") append(Symbol13); if(Symbol14 != "") append(Symbol14); if(Symbol15 != "") append(Symbol15); if(Symbol16 != "") append(Symbol16); if(Symbol17 != "") append(Symbol17); if(Symbol18 != "") append(Symbol18); if(Symbol19 != "") append(Symbol19); if(Symbol20 != "") append(Symbol20); if(Symbol21 != "") append(Symbol21); if(Symbol22 != "") append(Symbol22); if(Symbol23 != "") append(Symbol23); if(Symbol24 != "") append(Symbol24); if(Symbol25 != "") append(Symbol25); if(Symbol26 != "") append(Symbol26); if(Symbol27 != "") append(Symbol27); if(Symbol28 != "") append(Symbol28); if(Symbol29 != "") append(Symbol29); if(Symbol30 != "") append(Symbol30); MagicNumber_Buy=MagicNumber; MagicNumber_Sell=MagicNumber; return(INIT_SUCCEEDED); } //+ //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM|| //=============================================================================|| void OnDeinit(const int reason) { CleanUp(); EventKillTimer(); // return(0); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OnTick() { string CheckSymbol[]; int AddCheckSymbol = 0; for(cnt=OrdersTotal()-1; cnt>=0; cnt--) { select=OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); { if((OrderMagicNumber() == MagicNumber_Buy || OrderMagicNumber() == MagicNumber_Sell)) { for(i=0; i<pairs; i++) { if(OrderSymbol() == symb[i]) { bool AddData = true; for(int k=0; k<AddCheckSymbol; k++) if(CheckSymbol[k] == OrderSymbol()) AddData = false; if(AddData) { AddCheckSymbol++; ArrayResize(CheckSymbol,AddCheckSymbol); CheckSymbol[AddCheckSymbol-1] = OrderSymbol(); } } } } } } for(i=0; i<pairs; i++) { simbol = symb[i]; bool ReadyOpen = false; if(AddCheckSymbol < MaxPairTrades) ReadyOpen = true; else { for(int cek=0; cek<AddCheckSymbol; cek++) { if(simbol == CheckSymbol[cek] && cek < MaxPairTrades) ReadyOpen = true; } } int DIGITS = (int) MarketInfo(simbol,MODE_DIGITS); double point = MarketInfo(simbol,MODE_POINT); pv=NormalizeDouble(MarketInfo(simbol,MODE_TICKVALUE),DIGITS); //NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNXXXXX OpenBuy = 0; OpenSell = 0; OpenOrders1 = 0; OpenOrders2 = 0; x_price=0; y_price=0; xx_price=0; yy_price=0; xy_orders=0; xy_p=0; xy_vol=0; XYZ=0; XYZ1=0; XYZ2=0; Profit=0; total_xp=0; total_yp=0; total_xv=0; total_yv=0; avg_xx=0; avg_yy=0; xtime=0; ytime=0; for(cnt=0; cnt<OrdersTotal(); cnt++) { select=OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); { if(OrderSymbol()==simbol &&(OrderMagicNumber() == MagicNumber_Buy)) { OpenOrders1++; } if(OrderSymbol()==simbol &&(OrderMagicNumber() == MagicNumber_Sell)) { OpenOrders2++; } if(OrderSymbol()==simbol && OrderMagicNumber() == MagicNumber_Buy && OrderType()==OP_BUY) { x_vol=OrderLots(); OpenBuy++; total_xp +=OrderProfit(); Buy_Price=OrderOpenPrice(); SLB_PRICE=OrderStopLoss(); TPB_PRICE=OrderTakeProfit(); x_price +=OrderOpenPrice(); xx_price =NormalizeDouble((x_price/OpenBuy),DIGITS); total_xv +=OrderLots(); avg_xx= NormalizeDouble(total_xp/total_xv/pv,DIGITS); xtime=OrderOpenTime(); } if(OrderSymbol()==simbol && OrderMagicNumber() == MagicNumber_Sell && OrderType()==OP_SELL) { OpenSell++; y_vol=OrderLots(); Sell_Price=OrderOpenPrice(); SLS_PRICE=OrderStopLoss(); TPS_PRICE=OrderTakeProfit(); y_price +=OrderOpenPrice();; yy_price =NormalizeDouble((y_price/OpenSell),DIGITS); total_yv +=OrderLots(); total_yp +=OrderProfit(); avg_yy= NormalizeDouble(total_yp/total_yv/pv,DIGITS); ytime=OrderOpenTime(); } } } //=======================================================================================================================|| if((DIGITS==5||DIGITS==3) &&(simbol!= ""+"XAU"+"" || simbol!="XAU"+"" ||simbol!="XAUUSDcheck" ||simbol!="XAUUSD" || simbol!="GOLD")) pip=10; else pip=1; if(DIGITS==3 &&(simbol== ""+"XAU"+"" || simbol=="XAU"+"" ||simbol=="XAUUSDcheck" ||simbol=="XAUUSD" || simbol=="GOLD")) pip=100; else pip=10; //Print(simbol," ",point," ",pip); if(point == 0 || pip == 0) continue; Spread =NormalizeDouble((MarketInfo(simbol,MODE_ASK)-MarketInfo(simbol,MODE_BID))/point/pip,2); MinLot=MarketInfo(simbol,MODE_MINLOT); MaxLot=MarketInfo(simbol,MODE_MAXLOT); if(MinLot==0.01) Lot_Digits=2; if(MinLot==0.1) Lot_Digits=1; if(MinLot==1) Lot_Digits=0; HideTestIndicators(true); if(DayOfWeek()==1) hari= Day1; if(DayOfWeek()==2) hari= Day2; if(DayOfWeek()==3) hari= Day3; if(DayOfWeek()==4) hari= Day4; if(DayOfWeek()==5) hari= Day5; if(DayOfWeek()==6) hari= Day6; if(DayOfWeek()==7) hari= Day7; if(DIGITS==3|| DIGITS==5) { tolerance= slippage*10; } else { tolerance= slippage*1; } if(candle==0) last_vol=1000; if(candle==1) last_vol=30; AroonUp = 100.0*(AroonPeriod-iHighest(simbol,0,MODE_HIGH,AroonPeriod,candle)+candle)/AroonPeriod; AroonDn = 100.0*(AroonPeriod- iLowest(simbol,0,MODE_LOW,AroonPeriod,candle)+candle)/AroonPeriod; AroonUp2 = 100.0*(AroonPeriod-iHighest(simbol,0,MODE_HIGH,AroonPeriod,candle+1)+candle+1)/AroonPeriod; AroonDn2 = 100.0*(AroonPeriod- iLowest(simbol,0,MODE_LOW,AroonPeriod,candle+1)+candle+1)/AroonPeriod; buffer3 = AroonUp-AroonDn; buffer4 = AroonUp2-AroonDn2; if(buffer3> Filter && buffer4< Filter) XXX="BUY"; else XXX="NOBUY"; if(buffer3<-Filter && buffer4>-Filter) YYY="SELL"; else YYY="NOSELL"; if(Stoploss>0&& Stoploss*pip>MarketInfo(simbol,MODE_STOPLEVEL)) { SLB=MarketInfo(simbol,MODE_ASK)-(Stoploss*pip*point); SLS=MarketInfo(simbol,MODE_BID)+Stoploss*pip*point;// } if((Stoploss==0) || (Stoploss*pip<=MarketInfo(simbol,MODE_STOPLEVEL))) { SLB=0; SLS=0; } if(TakeProfit>0 && TakeProfit*pip>MarketInfo(simbol,MODE_STOPLEVEL)) { TPB=MarketInfo(simbol,MODE_ASK)+(TakeProfit*pip)*point; TPS=MarketInfo(simbol,MODE_BID)-(TakeProfit*pip)*point; } if((TakeProfit==0)|| (TakeProfit*pip<=MarketInfo(simbol,MODE_STOPLEVEL))) { TPB=0; TPS=0; } if(ReadyOpen && OpenOrders1==0 && dnNearestOrder(simbol,OP_BUY,MagicNumber_Buy)>Order_Distance*pip*point && Filter_TIme() && XXX=="BUY" && iVolume(simbol,0,0)<last_vol /*&& Filter_Trial() */) if(AccountFreeMargin() <MarketInfo(simbol,MODE_MARGINREQUIRED)*AutoLot()) { Print("No Enougt Money to Open NextOrder or Volume size is Over Maximum Lot.");// Please reset this EA by change your Magic Number"); return; } else { if(!BrokerIsECN) ord_send=OrderSend(simbol,0,AutoLot(),MarketInfo(simbol,MODE_ASK),slippage*pip,SLB,TPB,comment,MagicNumber_Buy,0,Blue); if(BrokerIsECN) { ord_send = 0; ord_send=OrderSend(simbol,0,AutoLot(),MarketInfo(simbol,MODE_ASK),slippage*pip,0,0,comment,MagicNumber_Buy,0,Blue); if(ord_send > 0) { bool seleksi = OrderSelect(ord_send,SELECT_BY_TICKET); if(TPB > 0.0 && SLB > 0.0) { while(IsTradeContextBusy()) Sleep(100); bool bool_60 = OrderModify(ord_send, OrderOpenPrice(), SLB, TPB, OrderExpiration(), CLR_NONE); if(!bool_60) { int error_64 = GetLastError(); Print(Symbol(), " ||=========================> ECN SL/TP order modify failed with error(", error_64, "): ", ErrorDescription(error_64)); } } if(TPB != 0.0 && SLB == 0.0) { while(IsTradeContextBusy()) Sleep(100); bool bool_60 = OrderModify(ord_send, OrderOpenPrice(), OrderStopLoss(), TPB, OrderExpiration(), CLR_NONE); if(!bool_60) { int error_64 = GetLastError(); Print(Symbol(), " ||=========================> ECN TP order modify failed with error(", error_64, "): ", ErrorDescription(error_64)); } } if(TPB == 0.0 && SLB != 0.0) { while(IsTradeContextBusy()) Sleep(100); bool bool_60 = OrderModify(ord_send, OrderOpenPrice(), SLB, OrderTakeProfit(), OrderExpiration(), CLR_NONE); if(!bool_60) { int error_64 = GetLastError(); Print(Symbol(), " ||=========================> ECN SL order modify failed with error(", error_64, "): ", ErrorDescription(error_64)); } } } } return; } if(ReadyOpen && OpenOrders2==0 && dnNearestOrder(simbol,OP_SELL,MagicNumber_Sell)>Order_Distance*pip*point && Filter_TIme() &&YYY=="SELL" && iVolume(simbol,0,0)<last_vol /*&& Filter_Trial() */) if(AccountFreeMargin() <MarketInfo(simbol,MODE_MARGINREQUIRED)*AutoLot()) { Print("No Enougt Money to Open NextOrder or Volume size is Over Maximum Lot.");// Please reset this EA by change your Magic Number"); return; } else { if(!BrokerIsECN) ord_send= OrderSend(simbol,1,AutoLot(),MarketInfo(simbol,MODE_BID),slippage*pip,SLS,TPS,comment,MagicNumber_Sell,0,Red); if(BrokerIsECN) { ord_send = 0; ord_send= OrderSend(simbol,1,AutoLot(),MarketInfo(simbol,MODE_BID),slippage*pip,0,0,comment,MagicNumber_Sell,0,Red); if(ord_send > 0) { bool seleksi = OrderSelect(ord_send,SELECT_BY_TICKET); if(TPS > 0.0 && SLS > 0.0) { while(IsTradeContextBusy()) Sleep(100); bool bool_60 = OrderModify(ord_send, OrderOpenPrice(), SLS, TPS, OrderExpiration(), CLR_NONE); if(!bool_60) { int error_64 = GetLastError(); Print(Symbol(), " ||=========================> ECN SL/TP order modify failed with error(", error_64, "): ", ErrorDescription(error_64)); } } if(TPS != 0.0 && SLS == 0.0) { while(IsTradeContextBusy()) Sleep(100); bool bool_60 = OrderModify(ord_send, OrderOpenPrice(), OrderStopLoss(), TPS, OrderExpiration(), CLR_NONE); if(!bool_60) { int error_64 = GetLastError(); Print(Symbol(), " ||=========================> ECN TP order modify failed with error(", error_64, "): ", ErrorDescription(error_64)); } } if(TPS == 0.0 && SLS != 0.0) { while(IsTradeContextBusy()) Sleep(100); bool bool_60 = OrderModify(ord_send, OrderOpenPrice(), SLS, OrderTakeProfit(), OrderExpiration(), CLR_NONE); if(!bool_60) { int error_64 = GetLastError(); Print(Symbol(), " ||=========================> ECN SL order modify failed with error(", error_64, "): ", ErrorDescription(error_64)); } } } } return; } if(OpenBuy>0) { Lot_MultiB= NormalizeDouble(x_vol*Multiplier,Lot_Digits); } Martin_SLB=SLB_PRICE; Martin_SLS= SLS_PRICE; if(MartingaleTrade_ON) { if(OpenBuy>0 && OpenBuy<MaxTrades_EachSide && X_Distance()) if(AccountFreeMargin() <MarketInfo(simbol,MODE_MARGINREQUIRED)*Lot_Multi1()) { Print("No Enougt Money to Open NextOrder or Volume size is Over Maximum Lot."); return; } else { if(!BrokerIsECN) ord_send=OrderSend(simbol,OP_BUY,Lot_Multi1(),MarketInfo(simbol,MODE_ASK),slippage*pip,SLB_PRICE,0,comment,MagicNumber_Buy,0,Aqua); if(BrokerIsECN) { ord_send = 0; ord_send=OrderSend(simbol,OP_BUY,Lot_Multi1(),MarketInfo(simbol,MODE_ASK),slippage*pip,0,0,comment,MagicNumber_Buy,0,Aqua); if(ord_send > 0) { bool seleksi = OrderSelect(ord_send,SELECT_BY_TICKET); if(SLB_PRICE != 0.0) { while(IsTradeContextBusy()) Sleep(100); bool bool_60 = OrderModify(ord_send, OrderOpenPrice(), SLB_PRICE, OrderTakeProfit(), OrderExpiration(), CLR_NONE); if(!bool_60) { int error_64 = GetLastError(); Print(Symbol(), " ||=========================> ECN SL order modify failed with error(", error_64, "): ", ErrorDescription(error_64)); } } } } } if(OpenSell>0 && OpenSell<MaxTrades_EachSide && Y_Distance()) if(AccountFreeMargin() <MarketInfo(simbol,MODE_MARGINREQUIRED)*Lot_Multi2()) { Print("No Enougt Money to Open NextOrder or Volume size is Over Maximum Lot."); return; } else { if(!BrokerIsECN) ord_send=OrderSend(simbol,OP_SELL,Lot_Multi2(),MarketInfo(simbol,MODE_BID),slippage*pip,SLS_PRICE,0,comment,MagicNumber_Sell,0,Magenta); if(BrokerIsECN) { ord_send = 0; ord_send=OrderSend(simbol,OP_SELL,Lot_Multi2(),MarketInfo(simbol,MODE_BID),slippage*pip,0,0,comment,MagicNumber_Sell,0,Magenta); if(ord_send > 0) { bool seleksi = OrderSelect(ord_send,SELECT_BY_TICKET); if(SLS_PRICE != 0.0) { while(IsTradeContextBusy()) Sleep(100); bool bool_60 = OrderModify(ord_send, OrderOpenPrice(), SLS_PRICE, OrderTakeProfit(), OrderExpiration(), CLR_NONE); if(!bool_60) { int error_64 = GetLastError(); Print(Symbol(), " ||=========================> ECN SL order modify failed with error(", error_64, "): ", ErrorDescription(error_64)); } } } } } } TSP=(TrailingStep+Trailing_Stop)*pip; if(Trailing_Stop_ON) { for(cnt=OrdersTotal()-1; cnt>=0; cnt--) { Select=OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); if(OrderSymbol()==simbol && OrderMagicNumber() == MagicNumber) { if(OrderType()==OP_BUY && OpenOrders1==1) { if(Trailing_Stop>0 && Trailing_Stop*pip>MarketInfo(simbol,MODE_STOPLEVEL)) { if(MarketInfo(simbol,MODE_BID)-OrderOpenPrice()>=point*Trailing_Stop*pip) { if((OrderStopLoss()<= MarketInfo(simbol,MODE_BID)-point*TSP)|| (OrderStopLoss()==0)) { Modif=OrderModify(OrderTicket(),OrderOpenPrice(),MarketInfo(simbol,MODE_BID)-(point*Trailing_Stop*pip),OrderTakeProfit(),0,Lime); return; } } } } else if(OrderType()==OP_SELL && OpenOrders2==1) { if(Trailing_Stop>0 && Trailing_Stop*pip>MarketInfo(simbol,MODE_STOPLEVEL)) { if((OrderOpenPrice()-MarketInfo(simbol,MODE_ASK))>=point*Trailing_Stop*pip) { if((OrderStopLoss()>=MarketInfo(simbol,MODE_ASK)+ point*TSP) || (OrderStopLoss()==0)) { Modif=OrderModify(OrderTicket(),OrderOpenPrice(),MarketInfo(simbol,MODE_ASK)+(point*Trailing_Stop*pip),OrderTakeProfit(),0,Red); return; } } } } } } } if(OpenBuy>0) { BEP_XXX= NormalizeDouble((MarketInfo(simbol,MODE_BID)-avg_xx*point),DIGITS); TPB_ALL=NormalizeDouble((BEP_XXX+(Average_TP*pip*point)),DIGITS); } if(OpenSell>0) { BEP_YYY= NormalizeDouble((MarketInfo(simbol,MODE_ASK)+avg_yy*point),DIGITS); TPS_ALL=NormalizeDouble((BEP_YYY - (Average_TP*pip*point)),DIGITS); } if(Average_ALL==true && Average_TP>0) { // cnt=0; for(cnt=OrdersTotal()-1; cnt>=0; cnt--) { select=OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); if(OrderSymbol()==simbol && OrderMagicNumber()==MagicNumber_Sell) { if(OrderType()==OP_SELL && OpenSell>1&& TPS_PRICE==0) { modif=OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),NormalizeDouble((BEP_YYY - (Average_TP*pip*point)),DIGITS),0,Yellow); } } } } if(Average_ALL==true && Average_TP>0) { cnt=0; for(cnt=OrdersTotal()-1; cnt>=0; cnt--) { select=OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); if(OrderSymbol()==simbol && OrderMagicNumber()==MagicNumber_Buy) { if(OrderType()==OP_BUY && OpenBuy>1 && TPB_PRICE==0) { modif=OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),NormalizeDouble((BEP_XXX+(Average_TP*pip*point)),DIGITS),0,Yellow); } } } } //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM if(Hidden_TP==true) { for(cnt=OrdersTotal()-1; cnt>=0; cnt--) { select= OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); if(OrderSymbol()==simbol && OrderMagicNumber() == MagicNumber_Sell) { if((OrderType()==OP_SELL && OpenSell==1&& MarketInfo(simbol,MODE_ASK)<=Sell_Price-hidden_takeprofit*pip*point) || (OrderType()==OP_SELL && OpenSell>1 && MarketInfo(simbol,MODE_ASK)<=BEP_YYY-Average_HTP*pip*point)) { ord_close=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,Red); } } } } //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|| if(Hidden_TP==true) { for(cnt=OrdersTotal()-1; cnt>=0; cnt--) { select= OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); if(OrderSymbol()==simbol && OrderMagicNumber() == MagicNumber_Buy) { if((OrderType()==OP_BUY &&OpenBuy==1 && MarketInfo(simbol,MODE_BID)>=Buy_Price+hidden_takeprofit*pip*point) || (OrderType()==OP_BUY &&OpenBuy>1 && MarketInfo(simbol,MODE_BID)>=BEP_XXX+Average_HTP*pip*point)) { ord_close=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,Blue); } } } } //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|| //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|| /* if ( Filter_Trial()==false && Filter_Time_For_Trial==true ) { string_window( "EA Trial", 5, 5, 0); ObjectSetText( "EA Trial",trial_version , 15, "Impact", Red); ObjectSet( "EA Trial", OBJPROP_CORNER,0); string_window( "EA Trial2", 5, 25, 0); ObjectSetText( "EA Trial2", trial_version2 +Trial_Time , 15, "Impact", Blue); ObjectSet( "EA Trial2", OBJPROP_CORNER,0); } else{ ObjectDelete("EA Trial"); ObjectDelete("EA Trial2"); } */ if(iVolume(simbol,0,0)%2==0) clr_price= clrLime; else clr_price= clrRed; if(AccountEquity()> AccountBalance()) clr_eq= clrBlue; else clr_eq= clrMagenta; Range =NormalizeDouble((iHigh(simbol,1440,0)- iLow(simbol,1440,0))/point/pip,2); Spread= (MarketInfo(simbol,MODE_ASK)-MarketInfo(simbol,MODE_BID))/point; if(ACCOUNT_INFO /*&& simbol == Symbol()*/) { string_window("hari", 5, 18, 0); // ObjectSetText("hari",hari +", "+DoubleToStr(Day(),0)+" - "+DoubleToStr(Month(),0) +" - " +DoubleToStr(Year(),0)+" "+IntegerToString(Hour())+":"+IntegerToString(Minute())+":"+IntegerToString(Seconds()),text_size+1, "Impact", Yellow); ObjectSet("hari", OBJPROP_CORNER,text_corner); string_window("Balance", 5, 15+20, 0); // ObjectSetText("Balance","Balance : " +DoubleToStr(AccountBalance(),2), text_size, "Cambria", color_text); ObjectSet("Balance", OBJPROP_CORNER,text_corner); string_window("Equity", 5, 30+20, 0); // ObjectSetText("Equity","Equity : " + DoubleToStr(AccountEquity(),2), text_size, "Cambria", clr_eq); ObjectSet("Equity", OBJPROP_CORNER, text_corner); string_window("AF", 5, 65, 0); // ObjectSetText("AF","Free Margin : " + DoubleToStr(AccountFreeMargin(),2), text_size, "Cambria", clr_eq); ObjectSet("AF", OBJPROP_CORNER, text_corner); /* string_window( "Leverage", 5,60+20, 0); ObjectSetText( "Leverage","Leverage : " + DoubleToStr(AccountLeverage(),0), text_size, "Cambria", color_text); ObjectSet( "Leverage", OBJPROP_CORNER, text_corner); */ Spread =NormalizeDouble((MarketInfo(Symbol(),MODE_ASK)-MarketInfo(Symbol(),MODE_BID))/Point,2); string_window("Spread", 5,60+20, 0); ObjectSetText("Spread","Spread : " + DoubleToStr(Spread,1), text_size, "Cambria", color_text); ObjectSet("Spread", OBJPROP_CORNER, text_corner); Range =NormalizeDouble((iHigh(Symbol(),1440,0)- iLow(Symbol(),1440,0))/point/pip,2); string_window("Range", 5, 75+20, 0); // ObjectSetText("Range","Range : " + DoubleToStr(Range,1), text_size, "Cambria", color_text); ObjectSet("Range", OBJPROP_CORNER, text_corner); string_window("Price", 5, 120, 0); // ObjectSetText("Price","Price : " + DoubleToStr(MarketInfo(Symbol(),MODE_BID),DIGITS), text_size, "Cambria", clr_price); ObjectSet("Price", OBJPROP_CORNER, text_corner); if(OpenSell>0) { string_window("sell", 5, 155, 0); // ObjectSetText("sell","Sell Order : " + DoubleToStr(OpenSell,0) +" | Sell Lot : " + DoubleToStr(total_yv,2) , text_size, "Cambria", color_text); ObjectSet("sell", OBJPROP_CORNER, text_corner); } else { ObjectDelete("Tps"); ObjectDelete("SLs"); ObjectDelete("sell"); } if(OpenBuy>0) { string_window("buy", 5, 140, 0); // ObjectSetText("buy","Buy Order : " + DoubleToStr(OpenBuy,0) +" |Buy Lot : " + DoubleToStr(total_xv,2) , text_size, "Cambria", color_text); ObjectSet("buy", OBJPROP_CORNER, text_corner); } else { ObjectDelete("Tp"); ObjectDelete("SL"); ObjectDelete("buy"); } /* string_window( "Profit", 5, 170, 0); ObjectSetText( "Profit", "Buy Profit : " +DoubleToStr( total_xp,2) + " | Sell Profit : " +DoubleToStr( total_yp,2) , text_size, "Cambria", clr_eq); ObjectSet( "Profit", OBJPROP_CORNER, text_corner); string_window( "MX", 5, 185, 0); ObjectSetText( "MX", "Min Lot : " +DoubleToStr( MinLot,Lot_Digits) + " | Max Lot : " +DoubleToStr( MaxLot,0) , text_size, "Cambria", clr_eq); ObjectSet( "MX", OBJPROP_CORNER, text_corner); */ string_window("EA_NAME", 5, 5, 0); ObjectSetText("EA_NAME",EA_NAME, text_size+3, "Impact", clr_eq); ObjectSet("EA_NAME", OBJPROP_CORNER, 3); } } //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| return; } //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| void CleanUp() { ObjectDelete("EA_NAME"); ObjectDelete("expiredlabel"); ObjectDelete("expiredlabel"); ObjectDelete("Contact_Me"); ObjectDelete("Key_Word2"); ObjectDelete("Key_Word1"); ObjectDelete("Spread"); ObjectDelete("Leverage"); ObjectDelete("Equity"); ObjectDelete("Balance"); ObjectDelete("Price"); ObjectDelete("Profit"); ObjectDelete("EA Trial"); ObjectDelete("Trade_Mode"); ObjectDelete("Lot"); ObjectDelete("EnterLot"); ObjectDelete("Spread"); ObjectDelete("EA Expired"); ObjectDelete("Range"); ObjectDelete("hari"); ObjectDelete("sell"); ObjectDelete("Tps"); ObjectDelete("SLs"); ObjectDelete("SL"); ObjectDelete("Tp"); ObjectDelete("buy"); ObjectDelete("BEP_XXX"); ObjectDelete("BEP_XXX2"); ObjectDelete("Check_Info"); ObjectDelete("AF"); ObjectDelete("MX"); ObjectDelete("Diff_B"); ObjectDelete("Total_Profit_X"); ObjectDelete("Diff_S"); ObjectDelete("Total_Profit_Y"); } //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| int string_window(string n, int xoff, int yoff, int WindowToUse) { ObjectCreate(n, OBJ_LABEL, WindowToUse, 0, 0); ObjectSet(n, OBJPROP_CORNER, 1); ObjectSet(n, OBJPROP_XDISTANCE, xoff); ObjectSet(n, OBJPROP_YDISTANCE, yoff); ObjectSet(n, OBJPROP_BACK, true); return (0); } //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| double Lots,MinLot,MaxLot; //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double AutoLot() { Lots=FixLot; if(Lots<MinLot) Lots=MinLot; if(Lots>MaxLot) Lots=MaxLot; if(Autolot==true) { Lots= CalculateLots(simbol); if(Lots<MinLot) Lots=MinLot; if(Lots>MaxLot) Lots=MaxLot; } return(Lots); } //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| double Lot_Multi1() { Lot_MultiB= NormalizeDouble(AutoLot(),Lot_Digits);//NormalizeDouble((AccountBalance()/100000)*AutoMM,Lot_Digits); if(Lot_MultiB<MinLot) Lot_MultiB=MinLot; if(Lot_MultiB>MaxLot) Lot_MultiB=MaxLot; if(Multiplier<1.5) { if(OpenBuy==1) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier,Lot_Digits); } if(OpenBuy==2) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==3) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==4) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==5) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==6) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==7) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier,Lot_Digits); } if(OpenBuy==8) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==9) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==10) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==11) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==12) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==13) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier,Lot_Digits); } if(OpenBuy==14) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==15) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==16) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==17) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==18) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenBuy==19) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier,Lot_Digits); } if(OpenBuy==20) { Lot_MultiB= NormalizeDouble(Lot_MultiB*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier,Lot_Digits); } if(OpenBuy>20) { Lot_MultiB= NormalizeDouble(x_vol*Multiplier,Lot_Digits); } if(Lot_MultiB >MaxLot) Lot_MultiB=MaxLot; if(Lot_MultiB <MinLot) Lot_MultiB=MinLot; } if(Multiplier>=1.5) { if(OpenBuy>0) { Lot_MultiB= NormalizeDouble(x_vol*Multiplier,Lot_Digits); } if(Lot_MultiB >MaxLot) Lot_MultiB=MaxLot; if(Lot_MultiB <MinLot) Lot_MultiB=MinLot; } return (Lot_MultiB); } //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| double Lot_Multi2() { Lot_MultiS= NormalizeDouble(AutoLot(),Lot_Digits);//NormalizeDouble((AccountBalance()/100000)*AutoMM,Lot_Digits); if(Lot_MultiS<MinLot) Lot_MultiS=MinLot; if(Lot_MultiS>MaxLot) Lot_MultiS=MaxLot; if(Multiplier<1.5) { if(OpenSell==1) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier,Lot_Digits); } if(OpenSell==2) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==3) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==4) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==5) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==6) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==7) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier,Lot_Digits); } if(OpenSell==8) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier,Lot_Digits); } if(OpenSell==9) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==10) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==11) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==12) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==13) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier,Lot_Digits); } if(OpenSell==14) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier,Lot_Digits); } if(OpenSell==15) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==16) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==17) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==18) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier,Lot_Digits); } if(OpenSell==19) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier,Lot_Digits); } if(OpenSell==20) { Lot_MultiS= NormalizeDouble(Lot_MultiS*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier*Multiplier*Multiplier*Multiplier*Multiplier *Multiplier*Multiplier,Lot_Digits); } if(OpenSell>20) { Lot_MultiS= NormalizeDouble(y_vol*Multiplier,Lot_Digits); } if(Lot_MultiS >MaxLot) Lot_MultiS=MaxLot; if(Lot_MultiS <MinLot) Lot_MultiS=MinLot; } if(Multiplier>=1.5) { if(OpenSell>0) { Lot_MultiS= NormalizeDouble(y_vol*Multiplier,Lot_Digits); } if(Lot_MultiS >MaxLot) Lot_MultiS=MaxLot; if(Lot_MultiS <MinLot) Lot_MultiS=MinLot; } return (Lot_MultiS); } //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| bool Filter_TIme() { if(Filter_TradingTime) { if(TimeCurrent()>=StrToTime(Time_Start) && TimeCurrent()<StrToTime(Time_End)) {return true; } else { return false; } } return true; } //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| bool X_Distance() { if(Filter_Min_Distance_ON) { double point = MarketInfo(simbol,MODE_POINT); if(MarketInfo(simbol,MODE_ASK) <=Buy_Price-Step*pip *point) // && Time[0]-xtime>0 && iVolume(simbol,0,0)<10) return true; else return false; } return true; } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool Y_Distance() { if(Filter_Min_Distance_ON) { double point = MarketInfo(simbol,MODE_POINT); if(MarketInfo(simbol,MODE_BID) >=Sell_Price+Step*pip *point) // && Time[0]-ytime>0 && iVolume(simbol,0,0)<10) return true; else return false; } return true; } //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| //MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM|| /* bool Filter_Trial() { if(Filter_Time_For_Trial ) { if (TimeCurrent()<=StrToTime(Trial_Time)) return true; else return false; } return true; } */ //KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK|| //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void append(string symbol) { pairs++; ArrayResize(symb, pairs); symb[pairs-1] = symbol+suffix; } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double CalculateLots(string symbol) { double MaxLots = MarketInfo(symbol, MODE_MAXLOT); double MinLots = MarketInfo(symbol, MODE_MINLOT); //double Leverages = AccountLeverage(); double lots; //if(Leverages < 500) { // lots = AccountBalance() / 500; // Microlots as whole number //} else { lots = AccountBalance() * Percentuale / 1000; /// 20; // Microlots as whole number //} lots=MathFloor(lots); // round down to nearest whole number lots*=0.01; // convert microlots to digits if(lots > MaxLots) lots = MaxLots; if(lots > MaxLots) lots = MaxLots; int lotdigits = DefineLotDigits(symbol); lots = NormalizeDouble(lots,lotdigits); return(lots); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int DefineLotDigits(string symbol) { double LotStep = MarketInfo(symbol, MODE_LOTSTEP); int LotDigits; if(LotStep >= 1) LotDigits = 0; else if(LotStep >= 0.1) LotDigits = 1; else if(LotStep >= 0.01) LotDigits = 2; else LotDigits = 3; return(LotDigits); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double dnNearestOrder(string symbol,int ordertype,int Magic) { double result=0,subresult=0,subresult1=100,subresult2=100,price=0, nearestup=0,nearestdown=0; int ordertotal=OrdersHistoryTotal(); for(int count=ordertotal-1; count>=0; count--) { if(!OrderSelect(count,SELECT_BY_POS,MODE_HISTORY) || OrderMagicNumber() != Magic || OrderSymbol() != symbol) continue; double openprice=OrderOpenPrice(); double p_open=NormalizeDouble(openprice,(int)MarketInfo(symbol,MODE_DIGITS)); double ask=NormalizeDouble(MarketInfo(symbol,MODE_ASK),(int)MarketInfo(symbol,MODE_DIGITS)); double bid=NormalizeDouble(MarketInfo(symbol,MODE_BID),(int)MarketInfo(symbol,MODE_DIGITS)); if(ordertype==OP_BUY) price=ask; if(ordertype==OP_SELL) price=bid; if(price>p_open) { if(nearestdown<=0) nearestdown=p_open; if(nearestdown>0 && p_open>nearestdown) nearestdown=p_open; subresult1=price-nearestdown; } if(price<=p_open) { if(nearestup<=0) nearestup=p_open; if(nearestup>0 && p_open<nearestup) nearestup=p_open; subresult2=nearestup-price; } } subresult=MathMin(subresult1,subresult2); result=NormalizeDouble(subresult,(int)MarketInfo(symbol,MODE_DIGITS)); return(result); } //+------------------------------------------------------------------+
fa978a288a1a048e695f47a35e3aa322
{ "intermediate": 0.3339681923389435, "beginner": 0.36721351742744446, "expert": 0.29881829023361206 }
40,647
Short answer. How to run exe from powershell and dont show the programm window (console app)
75b8629204bccf522afbfcbe468c04a1
{ "intermediate": 0.4318125545978546, "beginner": 0.3386017680168152, "expert": 0.229585662484169 }
40,648
send the response of API from childcompent.ts to <ngb-toast> in parent comp template
34c3ac259e92c42fab09538054e7c3d1
{ "intermediate": 0.7044435739517212, "beginner": 0.15064577758312225, "expert": 0.14491069316864014 }
40,649
write powershell scritp which copies a n exe file from network share and starts it in hidden mode not showing any windows
1c88a1947276cc35a85e8e2138e5ac4c
{ "intermediate": 0.39171573519706726, "beginner": 0.21176426112651825, "expert": 0.3965199887752533 }
40,650
write powershell script which copies an exe file from network share and starts it in hidden mode not showing any windows
1be06c7954ae4c219ae0d7638a7c5be9
{ "intermediate": 0.37804287672042847, "beginner": 0.22709369659423828, "expert": 0.3948633372783661 }
40,651
write powershell script which copies an exe file from network share and starts it in hidden mode not showing any windows
7c67eb38eab75eecd00545fffac1273c
{ "intermediate": 0.37804287672042847, "beginner": 0.22709369659423828, "expert": 0.3948633372783661 }
40,652
Powershell script which copies an exe file from network share and starts it in hidden mode not showing any windows
9ca2006d60d57c86b1dbeb8454e6718e
{ "intermediate": 0.3391561508178711, "beginner": 0.3025699555873871, "expert": 0.35827383399009705 }
40,653
write powershell script which copies an exe file from network share and starts it in hidden mode not showing any windows
b5170bf5000ad350e1818a0a42057088
{ "intermediate": 0.37804287672042847, "beginner": 0.22709369659423828, "expert": 0.3948633372783661 }
40,654
write powershell script which copies an exe file from network share and starts it in hidden mode not showing any windows . short
188c3d1a27c9c97c45d0678e68b7ed3c
{ "intermediate": 0.3429378569126129, "beginner": 0.29359203577041626, "expert": 0.3634701371192932 }
40,655
const modalRef = this.modalService.open(ProductDetailsComponent); i add this to parent comp to open the modal and when open the modal there is button call api i want when click on this button the modal close and ngb-toast with success or error message
ce6ffe662e00666f77983975753c4470
{ "intermediate": 0.629599392414093, "beginner": 0.15575696527957916, "expert": 0.2146436721086502 }
40,656
hi i have model yolo .pt and i want to create api in aws that can send the bounding box
8ac33e8990f4294cb678e1154ec5ec9e
{ "intermediate": 0.5515774488449097, "beginner": 0.11911240220069885, "expert": 0.32931017875671387 }
40,657
if i have a data of char * a = NULL, how can I pass it over a function to pass the address of this , also what would be the receiving function
3e4467167e7435b4439a208918f8b41d
{ "intermediate": 0.5344275236129761, "beginner": 0.2317470759153366, "expert": 0.23382538557052612 }