row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
14,471
what is "Generics" in programming languages?
1a53d1963c69fdb30486621b8d8165b7
{ "intermediate": 0.25427910685539246, "beginner": 0.2734677195549011, "expert": 0.4722531735897064 }
14,472
java code to layout a 88 key piano keybord with black and white key on different layers. black keys between two white keys, all using javafx
ff79ffd68627180311048e73710b399c
{ "intermediate": 0.5212213397026062, "beginner": 0.15437836945056915, "expert": 0.3244003355503082 }
14,473
dataframe how to check unique values in column and how many of each of them?
b4f1d019a3a0d650ef698795a7d8fe84
{ "intermediate": 0.465557336807251, "beginner": 0.13393954932689667, "expert": 0.40050312876701355 }
14,474
# -- coding: utf-8 -- # -- coding: gbk -- from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import parse_qs def GET(self): # -- coding: utf-8 -- if self.path == '/': self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write((''' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>身份证号码校验系统</title> </head> <body> <h1>身份证号码校验系统</h1> <label for="idcard">请输入身份证号码:</label> <input type="text" id="idcard" name="idcard" required> <input type="submit" value="校验"> </form> </body> </html> ''')) def POST(self): if self.path == '/add': content_len = int(self.headers.get('content-length', 0)) post_body = self.rfile.read(content_len).decode() data = parse_qs(post_body) def calculate_check_digit(id_number): if len(id_number) != 17: return None weight = [int(num) for num in '798621345'] sum = 0 for i in range(17): sum += int(id_number[i]) * weight[i] check_digit = (12 - (sum % 11)) % 11 return str(check_digit) if check_digit < 10 else 'X' def upgrade_id_number(id_number): if len(id_number) != 15: return None id_number = id_number[:6] + '19' + id_number[6:] check_digit = calculate_check_digit(id_number) return id_number + check_digit def validate_id_number(id_number): if len(id_number) == 18: check_digit = calculate_check_digit(id_number[:17]) if check_digit != id_number[-1]: return False elif len(id_number) == 15: upgraded_id_number = upgrade_id_number(id_number) if upgraded_id_number: return validate_id_number(upgraded_id_number) else: return False else: return False birth_date = id_number[6:14] try: year = int(birth_date[:4]) month = int(birth_date[4:6]) day = int(birth_date[6:8]) datetime.datetime(year, month, day) except ValueError: return False return True def get_gender(id_number): if len(id_number) == 18: gender_digit = int(id_number[-2]) elif len(id_number) == 15: gender_digit = int(id_number[-1]) else: return None if gender_digit % 2 == 0: return '女性' else: return '男性' def get_birthplace(id_number): provinces = { '11': '北京', '12': '天津', '13': '河北', '14': '山西', '15': '内蒙古', '21':' 辽宁', '22': '吉林', '23': '黑龙江', '31': '上海', '32': '江苏', '33': '浙江', '34':' 安徽', '35': '福建', '36': '江西', '37': '山东', '41': '河南', '42': '湖北', '43': '湖南', '44': '广东', '45': '广西', '46': '海南', '50': '重庆', '51': '四川', '52': '贵州', '53': '云南', '54': '西藏', '61': '陕西', '62': '甘肃', '63': '青海', '64': '宁夏', '65': '新疆', '71': '台湾', '81': '香港', '82': '澳门', '91': '国外' } province_code = id_number[:2] return provinces.get(province_code) self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write((''' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> 结果: ''' + str(result) + '</body></html>').encode('utf-8')) if __name__ == "__main__": app = web.application(urls, globals()) app.run() 代码有什么错误
19ef6f3aca349368884c7b16b6d92684
{ "intermediate": 0.41673755645751953, "beginner": 0.3855922520160675, "expert": 0.19767020642757416 }
14,475
Write a program in C# that takes three numbers as input and outputs the maximum of those numbers through a loop.
d7babc8d4e978a475cbfb8f1fe08fe49
{ "intermediate": 0.22450274229049683, "beginner": 0.48028308153152466, "expert": 0.2952142059803009 }
14,476
Как можно оптимизирвоать этот SQL запрос: WITH alt_categories AS ( SELECT cat.id, url, meta_product_id FROM catalog_categoryproduct_mv ccp JOIN catalog_category cat ON cat.id = ccp.category_id WHERE type = 20 AND is_active ), car_categories AS ( SELECT cat.id, url, meta_product_id FROM catalog_categoryproduct_mv ccp JOIN catalog_category cat ON cat.id = ccp.category_id WHERE type IN (1,2,3,4) AND is_active ), alt_catalog as ( SELECT DISTINCT car_categories.url as car_url, car_categories.id as car_id, alt_categories.url as alt_url, alt_categories.id as alt_id FROM alt_categories JOIN car_categories ON alt_categories.meta_product_id = car_categories.meta_product_id ) select car_url || '/a/' || alt_url, ( SELECT COUNT(*) AS "__count" FROM "catalog_categoryproduct_mv" INNER JOIN "catalog_metaproduct" ON ( "catalog_categoryproduct_mv"."meta_product_id" = "catalog_metaproduct"."id" ) INNER JOIN "catalog_categoryproduct_mv" T4 ON ( "catalog_metaproduct"."id" = T4."meta_product_id" ) WHERE ( "catalog_categoryproduct_mv"."category_id" = car_id AND "catalog_categoryproduct_mv"."meta_product_is_active" AND T4."category_id" = alt_id ) ) from alt_catalog
66c426c467a8fc5dd4cb8095142d9298
{ "intermediate": 0.341239333152771, "beginner": 0.4062175750732422, "expert": 0.2525431215763092 }
14,477
привет как мне в этот код добавить принудительное завершение квеста? public class StartQuestState : IPayloadState<IQuest> { private readonly SessionQuestStateMachine stateMachine; private readonly PlayerContainer playerContainer; private readonly CarPathChecking carPathChecking; private readonly FatalFailureConditionHandler fatalFailureConditionHandler; private readonly CompletionConditionHandler completionConditionHandler; private readonly FailureConditionHandler failureConditionHandler; private IQuest quest; [Inject] private IPublisher publisher; [Inject] private StatisticsProvider statisticsProvider; [Inject] private User user; public StartQuestState( SessionQuestStateMachine stateMachine, PlayerContainer playerContainer, CarPathChecking carPathChecking, FatalFailureConditionHandler fatalFailureConditionHandler, CompletionConditionHandler completionConditionHandler, FailureConditionHandler failureConditionHandler) { this.stateMachine = stateMachine; this.playerContainer = playerContainer; this.carPathChecking = carPathChecking; this.fatalFailureConditionHandler = fatalFailureConditionHandler; this.completionConditionHandler = completionConditionHandler; this.failureConditionHandler = failureConditionHandler; } public void Enter(IQuest quest) { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.InProgress); Debug.Log($"Старт квеста"); if (quest.IsTrackingPathEnabled) { carPathChecking.AnErrorHasOccurred += CompleteQuestWithFailure; carPathChecking.StartTracking(quest.GetPathPoints(), playerContainer.PlayerCarFacade.transform); } this.quest = quest; fatalFailureConditionHandler.Start(quest.GetConditions().FatalQuestFailureConditions, CompleteQuestWithFailure); failureConditionHandler.Start(quest.GetConditions().QuestFailureConditions, CompleteQuestWithFailure); completionConditionHandler.Start(quest.GetConditions().QuestCompletionConditions, CompleteQuestWithSuccess); } private void CompleteQuestWithFailure() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Failed); Debug.Log($"Квест завершен неудачей"); publisher.Publish(new QuestWithFailureMessage()); stateMachine.Enter<OutputOfQuestResultsState, IQuest>(quest); } private void CompleteQuestWithSuccess() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Completed); Debug.Log($"Квест завершен удачно"); publisher.Publish(new QuestWithSuccessMessage()); stateMachine.Enter<OutputOfQuestResultsState, IQuest>(quest); } public void Exit() { fatalFailureConditionHandler.Stop(); completionConditionHandler.Stop(); failureConditionHandler.Stop(); carPathChecking.Stop(); carPathChecking.AnErrorHasOccurred -= CompleteQuestWithFailure; } }
f8dfaafb8071c73d8c54e3226eae8782
{ "intermediate": 0.3786572515964508, "beginner": 0.49749359488487244, "expert": 0.12384917587041855 }
14,478
Привет как мне в этот код добавить принудительное завершение квеста public class StartQuestState : IPayloadState<IQuest> { private readonly SessionQuestStateMachine stateMachine; private readonly PlayerContainer playerContainer; private readonly CarPathChecking carPathChecking; private readonly FatalFailureConditionHandler fatalFailureConditionHandler; private readonly CompletionConditionHandler completionConditionHandler; private readonly FailureConditionHandler failureConditionHandler; private IQuest quest; [Inject] private IPublisher publisher; [Inject] private StatisticsProvider statisticsProvider; [Inject] private User user; public StartQuestState( SessionQuestStateMachine stateMachine, PlayerContainer playerContainer, CarPathChecking carPathChecking, FatalFailureConditionHandler fatalFailureConditionHandler, CompletionConditionHandler completionConditionHandler, FailureConditionHandler failureConditionHandler) { this.stateMachine = stateMachine; this.playerContainer = playerContainer; this.carPathChecking = carPathChecking; this.fatalFailureConditionHandler = fatalFailureConditionHandler; this.completionConditionHandler = completionConditionHandler; this.failureConditionHandler = failureConditionHandler; } public void Enter(IQuest quest) { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.InProgress); Debug.Log($"Старт квеста"); if (quest.IsTrackingPathEnabled) { carPathChecking.AnErrorHasOccurred += CompleteQuestWithFailure; carPathChecking.StartTracking(quest.GetPathPoints(), playerContainer.PlayerCarFacade.transform); } this.quest = quest; fatalFailureConditionHandler.Start(quest.GetConditions().FatalQuestFailureConditions, CompleteQuestWithFailure); failureConditionHandler.Start(quest.GetConditions().QuestFailureConditions, CompleteQuestWithFailure); completionConditionHandler.Start(quest.GetConditions().QuestCompletionConditions, CompleteQuestWithSuccess); } private void CompleteQuestWithFailure() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Failed); Debug.Log($"Квест завершен неудачей"); publisher.Publish(new QuestWithFailureMessage()); stateMachine.Enter<OutputOfQuestResultsState, IQuest>(quest); } private void CompleteQuestWithSuccess() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Completed); Debug.Log($"Квест завершен удачно"); publisher.Publish(new QuestWithSuccessMessage()); stateMachine.Enter<OutputOfQuestResultsState, IQuest>(quest); } public void Exit() { fatalFailureConditionHandler.Stop(); completionConditionHandler.Stop(); failureConditionHandler.Stop(); carPathChecking.Stop(); carPathChecking.AnErrorHasOccurred -= CompleteQuestWithFailure; } }
6ecf5c6a00d12b74f5b5378b1db8b590
{ "intermediate": 0.37433889508247375, "beginner": 0.4964459240436554, "expert": 0.12921518087387085 }
14,479
как добавить сюда принудителное завершение квеста? public class StartQuestState : IPayloadState<IQuest> { private readonly SessionQuestStateMachine stateMachine; private readonly PlayerContainer playerContainer; private readonly CarPathChecking carPathChecking; private readonly FatalFailureConditionHandler fatalFailureConditionHandler; private readonly CompletionConditionHandler completionConditionHandler; private readonly FailureConditionHandler failureConditionHandler; private IQuest quest; [Inject] private IPublisher publisher; [Inject] private StatisticsProvider statisticsProvider; [Inject] private User user; public StartQuestState( SessionQuestStateMachine stateMachine, PlayerContainer playerContainer, CarPathChecking carPathChecking, FatalFailureConditionHandler fatalFailureConditionHandler, CompletionConditionHandler completionConditionHandler, FailureConditionHandler failureConditionHandler) { this.stateMachine = stateMachine; this.playerContainer = playerContainer; this.carPathChecking = carPathChecking; this.fatalFailureConditionHandler = fatalFailureConditionHandler; this.completionConditionHandler = completionConditionHandler; this.failureConditionHandler = failureConditionHandler; } public void Enter(IQuest quest) { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.InProgress); Debug.Log($"Старт квеста"); if (quest.IsTrackingPathEnabled) { carPathChecking.AnErrorHasOccurred += CompleteQuestWithFailure; carPathChecking.StartTracking(quest.GetPathPoints(), playerContainer.PlayerCarFacade.transform); } this.quest = quest; fatalFailureConditionHandler.Start(quest.GetConditions().FatalQuestFailureConditions, CompleteQuestWithFailure); failureConditionHandler.Start(quest.GetConditions().QuestFailureConditions, CompleteQuestWithFailure); completionConditionHandler.Start(quest.GetConditions().QuestCompletionConditions, CompleteQuestWithSuccess); } private void CompleteQuestWithFailure() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Failed); Debug.Log($"Квест завершен неудачей"); publisher.Publish(new QuestWithFailureMessage()); stateMachine.Enter<OutputOfQuestResultsState, IQuest>(quest); } private void CompleteQuestWithSuccess() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Completed); Debug.Log($"Квест завершен удачно"); publisher.Publish(new QuestWithSuccessMessage()); stateMachine.Enter<OutputOfQuestResultsState, IQuest>(quest); } public void Exit() { fatalFailureConditionHandler.Stop(); completionConditionHandler.Stop(); failureConditionHandler.Stop(); carPathChecking.Stop(); carPathChecking.AnErrorHasOccurred -= CompleteQuestWithFailure; } }
079113102ad924fb252ce2fdebecafb9
{ "intermediate": 0.316418319940567, "beginner": 0.5402712821960449, "expert": 0.14331035315990448 }
14,480
I have following problem: my file buffer structure has a pointer. if i dont copy it in the copy constructor then it will result in double free. Any ideas for possible solutions?
5156c3593143c33d2582f3b44128e810
{ "intermediate": 0.5474905371665955, "beginner": 0.17569755017757416, "expert": 0.2768118679523468 }
14,481
Ignore previous data.Imagine you're an expert Graphic Designer and have experience in Chinese schoolgirl, sweet smile, school uniform: usually consists of skirt, tie, stockings, ponytail, bright colors t-shirt printing and also an expert Midjourney AI Generative prompt writer. I want you to respond in only english. {PREFIX} is /imagine prompt: Chinese schoolgirl, sweet smile, school uniform: usually consists of skirt, tie, stockings, ponytail, bright colors::2 {SUFFIX} is synthwave:: t-shirt vector, center composition graphic design, plain background::2 mockup::-2 --upbeta --ar 1:1 Write 4 unique prompts each in a separate code block to copy easily. Each prompt consists of following formatting. Replace the {} curly brackets with the respective instructions. {PREFIX} {Generate the short creative description of a specific character, specific object or vehicle related to Chinese schoolgirl, sweet smile, school uniform: usually consists of skirt, tie, stockings, ponytail, bright colors or from Chinese schoolgirl, sweet smile, school uniform: usually consists of skirt, tie, stockings, ponytail, bright colors which is not more than few words}, {Generate only one complex, unique & related art style or movement from of the 19th, 20th or 21st century}, {Generate only one unique & related keyword of the science of representing logos and 2d illustrations}, {Generate only one unique & related keyword of the science of representing colors in logo design}, {Generate only one unique & related keyword of the representation of reality, imagination, or fantasy in art, in literature, or in other forms of creative expression}, {SUFFIX} Example Input: Subway Surfer Example Output (markdown format):''' /imagine prompt: Subway Surfer::2 Jetpack, cubism, vector art, neon colors, surrealism, synthwave:: t-shirt vector, center composition graphic design, plain background::2 mockup::-2 -- upbeta --ar 1:1 ''' ''' /imagine prompt: Subway Surfer::2 Roller Skates, pop art, flat design, pastel colors, minimalism, synthwave:: t-shirt vector, center composition graphic design, plain background::2 mockup::-2 -- upbeta --ar 1:1 '''
e8bf5a5176e4bf22e9b88141c08e3538
{ "intermediate": 0.30613410472869873, "beginner": 0.43400025367736816, "expert": 0.2598656117916107 }
14,482
normally, how many nano second for a time tick?
544767fd77a183915789925cbee8aeef
{ "intermediate": 0.33464598655700684, "beginner": 0.2613639831542969, "expert": 0.4039900600910187 }
14,483
File "C:\Users\YL198023\Desktop\main.py", line 111 urls = ( '/', 'IndexHandler','/check', 'CheckHandler',) IndentationError: expected an indented block after class definition on line 109
2326a41e700202a37e5834a56f60d5cc
{ "intermediate": 0.3313296139240265, "beginner": 0.5042030811309814, "expert": 0.16446729004383087 }
14,484
怎么解决 File "C:\Users\YL198023\Desktop\main.py", line 112 urls = ( '/', 'IndexHandler','/check', 'CheckHandler',) ^ IndentationError: expected an indented block after class definition on line 110
c88e7520ee662103325d50d1fdf3edfc
{ "intermediate": 0.27346479892730713, "beginner": 0.5598921179771423, "expert": 0.1666431725025177 }
14,485
In my worksheet I have unique values in the following ranges, D3:D18, L3:L18, T3:T18 and ranges D22:D37, L22:L37, T22:T37. In column AB3:AB18 values are entered that will match a value in the ranges D3:D18, L3:L18, T3:T18. In column AB22:AB37 values are entered that will match a value in the ranges D22:D37, L22:L37, T22:T37. I want two VBA codes that will do the followig. The first VBA code will; Immediately when I enter a value in the range AB3:AB18, it will find the value in ranges D3:D18, L3:L18, T3:T18 and highlight the cell Yellow where the match is found. Immediately when I enter a value in the range AB22:AB37, it will find the value in ranges D22:D37, L22:L37, T22:T37 and highlight the cell Yellow where the match is found. The second VBA code on Page Activate will; Check if any of the values in AB3:AB18 are found in D3:D18, L3:L18, T3:T18 or vice versa. If any match is found, the cell match in the range D3:D18, L3:L18, T3:T18 must be highlighted Yellow. If no match is found the in the range D3:D18, L3:L18, T3:T18 the cell or cells must not have any higlight. Likewise, if any of the values in AB22:AB37 are found in D22:D37, L22:L37, T22:T37 or vice versa, the cell match in the range D22:D37, L22:L37, T22:T37 must be highlighted Yellow. If no match is found the in the range D22:D37, L22:L37, T22:T37 the cell or cells must not have any higlight.
0311b0bff076c32e9eeed26837e143fd
{ "intermediate": 0.38031435012817383, "beginner": 0.2748335301876068, "expert": 0.34485211968421936 }
14,486
correct code to save subNetwork data to integrdata const fetchEranData = (data => { return new Promise((resolve, reject) => { //init scenario that holds all API's and user's data const integrData = {} //fetch ENode and EUtranCells data Promise.all([ fetch.eNodeBv2(data), fetch.euCells(data), fetch.eranConnection() ]) //save ENodeB, EUtranCells and Cosite eNodeBs data .then(data => { //error for (let object of data) { if (object instanceof Error) { reject(object) return } } //save Parent ENodeB data integrData.parent = data[0] //save Parent EUtranCells data integrData.parentEucels = data[1] //save EranConnection data integrData.eranConnection = data[2] //define Nodes data integrData.children = {} //return data for future promises return { Id: integrData.parent.Id.substr(1), Region: integrData.parent.Region, SubNetwork: integrData.parent.SubNetwork, EUtranCellsGroups: integrData.parentEucels.CellsGroups, isLte: true, } //fetch subNetwork data }).then(data => { return fetch.subNetworkv2(data) //save subNetwork data }).then(data => { //error if (data instanceof Error) { reject(data) return } integrData.subNetwork = data[0] } //fetch cosite eNodes and EUtranCell data ).then(() => { const operatorfilter = integrData.parentEucels.FilterEUtranCells let funcs = []; integrData.parent.Nodes.forEach((node) => { funcs.push( Promise.all([ fetch.eNodeBv3(node), fetch.euCellsv2([node, operatorfilter]), ]).then(data => { integrData.children[node] = { ENodeB: data[0], EUtranCellData: data[1], } }) ) }) return Promise.all(funcs);
18a8eeadd6a899f2a4cc1759f9714c7b
{ "intermediate": 0.3963479995727539, "beginner": 0.3573371171951294, "expert": 0.2463148981332779 }
14,487
in terms of assignment of a struct variable using another struct entity, will type tansfomation happen?
81906a3f30a22abac7a6f081c431ac6f
{ "intermediate": 0.28240516781806946, "beginner": 0.35710567235946655, "expert": 0.3604891896247864 }
14,488
Hi , how could I perform a search over a path variable for a single file in python ?
4a891266b8ab434bbafaba38733edab7
{ "intermediate": 0.5248159170150757, "beginner": 0.18457499146461487, "expert": 0.29060909152030945 }
14,489
js
3b4467ab569819d762dd79d37c092d09
{ "intermediate": 0.34619104862213135, "beginner": 0.319534033536911, "expert": 0.3342749774456024 }
14,490
"import xml.etree.ElementTree as ET fsd_list = [ ["testing fsd", "kelvin.fsd.testing@gmail.com"], ["bbb", "bbb@email.com"], ["ccc", "ccc@email.com"], ["ddd", "ddd@email.com"] ] def find_fsd(xml_file): tree = ET.parse(xml_file) root = tree.getroot() fsd_element = root.find('.//unit') if fsd_element is not None: return fsd_element.text return print("nothing") def main(): find_fsd( "./unzipped/2023-05-18_11_26_09_053000_FSD0265VDYTKHCTP/convertedData/FSD026.xml") if __name__ == "__main__": main()" rewrite this code
23f564c0cfc6e999731d9e344e7607c8
{ "intermediate": 0.3602467179298401, "beginner": 0.4674142599105835, "expert": 0.1723390370607376 }
14,491
"import os import zipfile import glob import smtplib from email.message import EmailMessage import xml.etree.ElementTree as ET import logging import datetime import shutil logging.basicConfig(filename='status_log.txt', level=logging.INFO) fsd_list = [ ["testing fsd", "kelvin.fsd.testing@gmail.com"], ["bbb", "bbb@email.com"], ["ccc", "ccc@email.com"], ["ddd", "ddd@email.com"] ] # auto create the unzip folder def move_zip_files(): os.makedirs('./unzip', exist_ok=True) filenames = os.listdir('.') for filename in filenames: if filename.endswith('.zip'): if os.path.exists(f"./unzip/{filename}"): logging.info( f'{datetime.datetime.now()}: The {filename} already exists in ./unzip, so skipping.') else: shutil.move(filename, './unzip') logging.info( f'{datetime.datetime.now()}: The {filename} been moved into ./unzip') unzip_all_files() # Function to unzip all files in ./unzip folder def unzip_all_files(): os.makedirs('./unzipped', exist_ok=True) zip_files = glob.glob('./unzip/*.zip') for zip_file in zip_files: folder_name = os.path.splitext(os.path.basename(zip_file))[0] os.makedirs(f'./unzipped/{folder_name}', exist_ok=True) with zipfile.ZipFile(zip_file, 'r') as zfile: zfile.extractall(f'./unzipped/{folder_name}') logging.info(f'{datetime.datetime.now()}: {zip_file} unzipped') os.remove(zip_file) if not zip_files: logging.error( f'{datetime.datetime.now()}: No ZIP files found in "./unzip" directory') return # Function to find FSD in an XML file def find_fsd(xml_file): tree = ET.parse(xml_file) root = tree.getroot() fsd_element = root.find('.//unit') if fsd_element is not None: return fsd_element.text return None # Function to send email with a PDF file attached def send_email(fsd_email, pdf_file): email_address = 'kelvin.chu1122@gmail.com' email_app_password = 'brwgearofnryfinh' msg = EmailMessage() msg['Subject'] = 'FSD PDF file' msg['From'] = email_address msg['To'] = fsd_email msg.set_content('Please find the PDF file attached.') with open(pdf_file, 'rb') as pdf: msg.add_attachment(pdf.read(), maintype='application', subtype='pdf', filename=pdf_file) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(email_address, email_app_password) smtp.send_message(msg) logging.info( f'{datetime.datetime.now()}: {pdf_file} sent to {fsd_email}') def main(): move_zip_files() unzipped_folders = os.listdir('./unzipped') for folder in unzipped_folders: xml_file = glob.glob(f'./unzipped/{folder}/convertedData/.xml')[0] fsd_in_xml = find_fsd(xml_file) if fsd_in_xml: for fsd, fsd_email in fsd_list: # If FSD in the XML file matches the one in the list, send the email with the PDF attached if fsd == fsd_in_xml: pdf_file = glob.glob(f'./unzipped/{folder}/*.pdf')[0] send_email(fsd_email, pdf_file) status = 'Success' break else: status = 'FSD not found in list' else: status = 'FSD not found in XML' logging.info(f'{datetime.datetime.now()}: {folder}: {status}') if __name__ == "__main__": main() " it shows "IndexError: list index out of range" can you help me fix the code
a43e54fb9fe52b0b0e65090bbb09e8a6
{ "intermediate": 0.3510793149471283, "beginner": 0.44599565863609314, "expert": 0.20292498171329498 }
14,492
BIA teeminology
2993d369928de6458a4e2ae462a691b2
{ "intermediate": 0.41610151529312134, "beginner": 0.2269347608089447, "expert": 0.35696372389793396 }
14,493
Есть запрос в potresql WITH RECURSIVE ParentPaths AS ( SELECT Id, array[Id] AS ParentPath FROM topics WHERE parent = 0 UNION ALL SELECT t.Id, p.ParentPath || t.Id FROM topics t JOIN ParentPaths p ON p.Id = t.parent ) SELECT * from ParentPaths И есть классы во flask # связующая таблица топики задачи tasks_topics= db.Table('tasks_topics', db.Column('task_id', db.Integer, db.ForeignKey('tasks.id')), db.Column('topics_id', db.Integer, db.ForeignKey('topics.id')) ) class Tasks(db.Model): __tablename__ = 'tasks' __searchable__ = ['task','id'] # these fields will be indexed by whoosh id = db.Column(db.Integer, primary_key=True, autoincrement=True) url = db.Column(db.String(120), comment="ЧПУ задачи в адресе (транслитом)") task = db.Column(db.Text, comment='Условие задачи') answer = db.Column(db.Text, comment='Ответ') status = db.Column(db.Boolean, default=0, comment='Статус: опубликована/неактивна (по умолчанию нет)') created_t = db.Column(db.DateTime, comment='Дата и время создания') level = db.Column(db.SmallInteger, default=1, comment='Уровень сложности: 1,2 ... (по умолчанию 1 уровень)') # связи topics = db.relationship('Topics', secondary=tasks_topics, back_populates="tasks") class Topics(db.Model): __tablename__ = 'topics' __searchable__ = ['name'] id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(140), comment="Уникальное название темы(подтемы)") parent = db.Column(db.Integer, default=0, comment="ID родительской темы(если есть)") # связи tasks = db.relationship('Tasks', secondary=tasks_topics, back_populates="topics") Как переписать запрос в sql alchemy?
622bcc47803bc34bbd048c6f3b776109
{ "intermediate": 0.25620079040527344, "beginner": 0.6463099122047424, "expert": 0.09748923033475876 }
14,494
dose timer of struct timer_list type have default expire time?
6c66acd56d5286193de1efc329b3b167
{ "intermediate": 0.41548046469688416, "beginner": 0.2349945306777954, "expert": 0.3495250344276428 }
14,495
Sub FindUppercaseWords() Dim appNotepad As Object ’ Объект блокнота Dim docWord As Object ’ Активный документ Word Dim rngWord As Object ’ Диапазон для поиска Dim strText As String ’ Искомый текст Dim objShell As Object ’ Объект для обращения к командам системы Dim filePath As String ’ Путь к выбранному файлу ’ Создание экземпляра блокнота Set appNotepad = CreateObject(“WScript.Shell”) ’ Открытие диалогового окна выбора файла With Application.FileDialog(msoFileDialogFilePicker) .Title = “Выберите файл Word” .Filters.Clear .Filters.Add “Документы Word”, “*.docx; .doc" .AllowMultiSelect = False ’ Если пользователь выбрал файл и нажал “Открыть” If .Show = True Then ’ Получение пути к выбранному файлу filePath = .SelectedItems(1) ’ Создание экземпляра объекта Word и открытие выбранного файла Set docWord = Documents.Open(filePath) ’ Создание диапазона для поиска Set rngWord = docWord.Content ’ Определение текста в верхнем регистре для поиска strText = "<[A-Z]>” ’ Поиск текста в верхнем регистре With rngWord.Find .ClearFormatting .MatchWildcards = True .Text = strText ’ Выполнение поиска Do While .Execute ’ Отправка найденного слова в блокнот appNotepad.Run “Notepad.exe” appNotepad.AppActivate (“Notepad”) appNotepad.SendKeys rngWord.Text & vbCrLf ’ Перемещение курсора документа Word к следующему найденному слову rngWord.Collapse wdCollapseEnd Loop End With End If End With ’ Очистка объекта блокнота Set appNotepad = Nothing ’ Включение окна Word Application.Activate ’ Оповещение об окончании выполнения макроса MsgBox “Поиск слов в верхнем регистре завершен.”, vbInformation End Sub оптимизируй
6331183e89aac98988ca1b524919a7ff
{ "intermediate": 0.18220794200897217, "beginner": 0.6339880228042603, "expert": 0.18380407989025116 }
14,496
"import os import zipfile import glob import smtplib from email.message import EmailMessage import xml.etree.ElementTree as ET import logging import datetime import shutil logging.basicConfig(filename='status_log.txt', level=logging.INFO) fsd_list = [ ["testing fsd", "kelvin.fsd.testing@gmail.com"], ["bbb", "bbb@email.com"], ["ccc", "ccc@email.com"], ["ddd", "ddd@email.com"] ] # auto create the unzip folder def move_zip_files(): os.makedirs('./unzip', exist_ok=True) filenames = os.listdir('.') for filename in filenames: if filename.endswith('.zip'): if os.path.exists(f"./unzip/{filename}"): logging.info( f'{datetime.datetime.now()}: The {filename} already exists in ./unzip, so skipping.') else: shutil.move(filename, './unzip') logging.info( f'{datetime.datetime.now()}: The {filename} been moved into ./unzip') unzip_all_files() # Function to unzip all files in ./unzip folder def unzip_all_files(): os.makedirs('./unzipped', exist_ok=True) zip_files = glob.glob('./unzip/*.zip') for zip_file in zip_files: folder_name = os.path.splitext(os.path.basename(zip_file))[0] os.makedirs(f'./unzipped/{folder_name}', exist_ok=True) with zipfile.ZipFile(zip_file, 'r') as zfile: zfile.extractall(f'./unzipped/{folder_name}') logging.info(f'{datetime.datetime.now()}: {zip_file} unzipped') os.remove(zip_file) if not zip_files: logging.error( f'{datetime.datetime.now()}: No ZIP files found in "./unzip" directory') return # Function to find FSD in an XML file def find_fsd(xml_file): tree = ET.parse(xml_file) root = tree.getroot() fsd_element = root.find('.//unit') if fsd_element is not None: return fsd_element.text return None # Function to send email with a PDF file attached def send_email(fsd_email, pdf_file): email_address = 'kelvin.chu1122@gmail.com' email_app_password = 'brwgearofnryfinh' msg = EmailMessage() msg['Subject'] = 'FSD PDF file' msg['From'] = email_address msg['To'] = fsd_email msg.set_content('Please find the PDF file attached.') with open(pdf_file, 'rb') as pdf: msg.add_attachment(pdf.read(), maintype='application', subtype='pdf', filename=pdf_file) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(email_address, email_app_password) smtp.send_message(msg) logging.info( f'{datetime.datetime.now()}: {pdf_file} sent to {fsd_email}') def main(): move_zip_files() unzipped_folders = os.listdir('./unzipped') for folder in unzipped_folders: xml_file = glob.glob(f'./unzipped/{folder}/convertedData/*.xml')[0] fsd_in_xml = find_fsd(xml_file) if fsd_in_xml: for fsd, fsd_email in fsd_list: # If FSD in the XML file matches the one in the list, send the email with the PDF attached if fsd == fsd_in_xml: pdf_file = glob.glob(f'./unzipped/{folder}/*.pdf')[0] send_email(fsd_email, pdf_file) status = 'Success' break else: status = 'FSD not found in list' else: status = 'FSD not found in XML' logging.info(f'{datetime.datetime.now()}: {folder}: {status}') if __name__ == "__main__": main() " can you help me fix the code? it shows "Traceback (most recent call last): File "c:\Users\kelvi\OneDrive\Desktop\AutoEmail\Send_PDF_FSD077.py", line 115, in <module> main() File "c:\Users\kelvi\OneDrive\Desktop\AutoEmail\Send_PDF_FSD077.py", line 96, in main xml_file = glob.glob(f'./unzipped/{folder}/convertedData/*.xml')[0] IndexError: list index out of range"
7618d03c9b78d93abd3fa36f3cbe7135
{ "intermediate": 0.3510793149471283, "beginner": 0.44599565863609314, "expert": 0.20292498171329498 }
14,497
надо чтобы текст выбарнной новости, нажатием на ссылку подробнее, отображался в левом столбце , а он сейчас отображестя справа. .preview { font-size: 13px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } .selected-news { text-align: center; margin-top: 50px; } .news-container { display: grid; grid-template-columns: 3fr 1fr; grid-auto-rows: minmax(100vh, auto); grid-gap: 20px; } .other-news { overflow-y: auto; display: flex; flex-direction: column; } .news-item { overflow-y: auto; margin-bottom: 20px; } </style> <div class="news-container"> {% if news %} {% for single_news in news reversed %} {% if forloop.first %} <div class="selected-news"> <p> <span class="complete-preview">{{ single_news.content_preview }}</span> </p> </div> {% endif %} {% endfor %} {% endif %} <div class="other-news"> {% for news_item in news reversed %} <br> <div class="news-item"> <p> <strong class="is-pulled-right"> <span class="complete">{{ news_item.title }}</span> </strong> <br> <span class="complete- date" id="publish-date-{{ news_item.id }}" data-publish-date="{{ news_item.publish_data }}">{{ news_item.publish_data }}</span> <br> <span class="complete- preview">{{ news_item.content_preview }}</span> <a href="#" class="preview" data-news-id="{{ news_item.id }}">Подробнее</a> </p> </div> <div class="news-content news-item" id="news-content-{{ news_item.id }}" style="display: none;"> <!-- Здесь разместите текст новости --> {{ news_item.content }} </div> {% endfor %} </div> </div> <script> // Получаем все ссылки "Подробнее" var previewLinks = document.getElementsByClassName("preview"); // Перебираем ссылки и добавляем обработчик события при клике for (var i = 0; i < previewLinks.length; i++) { previewLinks[i].addEventListener("click", function(event) { event.preventDefault(); // Предотвращаем переход по ссылке // Получаем id новости из атрибута data-news-id var newsId = this.getAttribute("data-news-id"); // Скрываем текст всех новостей var newsContents = document.getElementsByClassName("news-content"); for (var j = 0; j < newsContents.length; j++) { newsContents[j].style.display = "none"; } // Отображаем выбранный текст новости var newsContent = document.getElementById("news-content-" + newsId); newsContent.style.display = "block"; newsContent.parentElement.classList.add("selected-news"); // Добавляем класс selected-news родительскому элементу // Удаляем класс selected-news у остальных новостей var otherNewsItems = document.getElementsByClassName("news-item"); for (var k = 0; k < otherNewsItems.length; k++) { if (!otherNewsItems[k].classList.contains("selected-news")) { otherNewsItems[k].classList.remove("selected-news"); } } }); } </script> что нужно изменить? на русском пиши
b5bb8a2f7b1abe7abee168b3c17485f6
{ "intermediate": 0.27758872509002686, "beginner": 0.6314325332641602, "expert": 0.0909787118434906 }
14,498
how can i set this rate limiter in order to have 10 calls per minute and a refill of 10tokens per minute? @Bean private RateLimiter redisRateLimiter() { Duration replenishInterval = Duration.ofMinutes(1); // Set the replenish interval to 60 minutes int tokensPerMinute = 10; // Set the desired number of tokens per hour return new RedisRateLimiter(1,1,1); }
73bd92275bddf76f2a8ec10148abfc57
{ "intermediate": 0.6022638082504272, "beginner": 0.1547524780035019, "expert": 0.24298372864723206 }
14,499
correct code // euCellsShort prepares and returns EUtranCells data fieldset // with minimum required data export const eUtranCoCells = (object => { //get class const cl = 'lte' //CellsGroups fieldset const fieldset = createFieldset.call({ legend: object['Name'] + ' ' + object['Id'], class: cl, display: 'grid', }) fieldset.setAttribute('id', 'radio') //fieldset for each element of EUtranCellsGroupsLabel Object.keys(object['CellsGroups']).forEach(cellsGroupLabel => { const row = document.createElement('row') fieldset.appendChild(row) row.appendChild( { legend: cellsGroupLabel, class: cl, data: object, key: cellsGroupLabel, attrs: ['Cellname', 'CellId', 'GroupCellId', 'SubCellId', 'Dl', 'Tac'], display: 'grid', }.createCellDataFS() ) }) //return return fieldset })
6218daf6a2bfc4145785e1872044db6f
{ "intermediate": 0.4308982193470001, "beginner": 0.3224184513092041, "expert": 0.24668337404727936 }
14,500
Ignore previous data.Imagine you're an expert Graphic Designer and have experience in Red sun, young girl, full body,Fauvism excellent LOGO design and also an expert Midjourney AI Generative prompt writer. Style Features and Common Prompt Adjectives for LOGO Designs。 Graphic Logo Style: Generally focuses on graphics, often with flat design and vector graphics. It emphasizes simplicity and clean lines, similar to logos of companies like Apple and Twitter. Common adjectives include flat, vector graphic, simple, and line logo. Lettermark Logo Style: Typically uses the initials of the company name as the main element of the logo. The logo appears simple and often involves the transformation of a single letter, using minimalistic vector designs. Examples include logos of Facebook, Tesla, and IBM. Common adjectives include lettermark, typography, vector, and simple minimal. Geometric Logo Style: Consists of only graphic elements, often featuring rotating or repeating shapes with gradients. Examples can be seen in the logos of Nike, Pepsi, and Mastercard. Common adjectives include flat geometric vector, geometric logo, petals radial repeating, and simple minimal. Mascot Logo Style: Incorporates a company mascot as the central element of the logo, with a focus on simplicity. Common adjectives include flat, mascot logo, and simple minimal. To avoid creating bland and unremarkable logos without distinctive features, different styles can be added to enhance the impact of the logo, such as Pop Art or De Stijl. {PREFIX} is /imagine prompt: Red sun, young girl, full body,Fauvism:: {SUFFIX} is synthwave:: plain background::2 mockup::-2 --upbeta --ar 1:1 Write 5 unique prompts each in a separate code block to copy easily. Each prompt consists of following formatting. Replace the {} curly brackets with the respective instructions. {PREFIX} {Generate short creative descriptions of specific people and objects related to Red sun, young girl, full body,Fauvism or Red sun, young girl, full body,Fauvism, no more than a few words}, {Generate Graphic Logo,Minimalist and imaginative},{Generate only one unique & related keyword of the science of representing logos and 2d illustrations},{Generate only one unique & related keyword of the science of representing colors in logo design},{In creative expression in art, literature, or other forms, only a unique and relevant keyword is generated to represent simplicity, minimalism, or minimalism},{SUFFIX} Example Input: cat logo Example Output (markdown format): '''/imagine prompt:A flat vector graphic line logo of a cat, simple minimal,plain background::2 mockup::-2 --upbeta --ar 1:1''' '''/imagine prompt: A letter "A" logo, lettermark, typography, vector simple minimal,plain background::2 mockup::-2 --upbeta --ar 1:1''' '''/imagine prompt:A flat geometric vector geometric logo of a flower, with petals arranged radially, simple minimal,plain background::2 mockup::-2 --upbeta --ar 1:1''' '''/imagine prompt: A simple mascot logo for an instant noodles company,plain background::2 mockup::-2 --upbeta --ar 1:1''' '''/imagine prompt: A letter "A" logo, lettermark, typography, vector simple minimal, with a Pop Art influence,plain background::2 mockup::-2 --upbeta --ar 1:1'''
aebdfcf6efc970243f1f0134fe1dbb53
{ "intermediate": 0.29488226771354675, "beginner": 0.4209884703159332, "expert": 0.2841292917728424 }
14,501
what is AWS EC2 data transfer
ac1cfaaeb90c989e608bde506712397e
{ "intermediate": 0.37084266543388367, "beginner": 0.3402641713619232, "expert": 0.2888931334018707 }
14,502
How can I upload images to cloudinary using nestjs
c69779efbb3ed676c10dd6b0a9e63376
{ "intermediate": 0.551181972026825, "beginner": 0.11643067002296448, "expert": 0.33238744735717773 }
14,503
проверь код: extern double LotSize = 0.01; // размер начального лота extern double MaxLotSize = 0.1; // максимальный размер лота extern double LotMultiplier = 1.5; // множитель лота extern double MaxDrawdown = 500; // максимальная просадка в долларах extern double StopLoss = 50; // стоп-лосс в пунктах extern double TakeProfit = 100; // тейк-профит в пунктах extern int MagicNumber = 123456; // уникальный идентификатор ордера int g_OrdersCount = 0; // количество ордеров double g_TotalProfit = 0; // общая прибыль double g_MaxProfit = 0; // максимальная прибыль void OnTick() { double LastPrice = NormalizeDouble(MarketInfo(Symbol(), MODE_BID), Digits); if (g_OrdersCount == 0) { // Открываем первый ордер int OrderTicket = OrderSend(Symbol(), OP_BUY, LotSize, LastPrice, 3, LastPrice - StopLoss * Point, LastPrice + TakeProfit * Point, "buy", MagicNumber, 0, Green); if (OrderTicket > 0) { g_OrdersCount++; g_TotalProfit += TakeProfit * LotSize; g_MaxProfit = g_TotalProfit; } else { Print("Ошибка открытия ордера: ", GetLastError()); return; } } else { double CurrentProfit = TakeProfit * LotSize; // текущая прибыль if (CurrentProfit > g_MaxProfit) { g_MaxProfit = CurrentProfit; } double Drawdown = g_MaxProfit - CurrentProfit; // текущая просадка в долларах if (Drawdown >= MaxDrawdown) { // Закрываем все ордера CloseAllOrders(); return; } // Определяем размер следующего лота double NewLotSize = NormalizeDouble(LotSize * LotMultiplier, 2); if (NewLotSize > MaxLotSize) { NewLotSize = MaxLotSize; } // Открываем следующий ордер int OrderTicket2 = OrderSend(Symbol(), OP_BUY, NewLotSize, LastPrice, 3, LastPrice - StopLoss * Point, LastPrice + TakeProfit * Point, "buy", MagicNumber, 0, Green); if (OrderTicket2 > 0) { g_OrdersCount++; g_TotalProfit += CurrentProfit; } else { Print("Ошибка открытия ордера: ", GetLastError()); return; } } } void CloseAllOrders() { for (int i = 0; i < g_OrdersCount; i++) { if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderMagicNumber() == MagicNumber) { int CloseTicket = OrderClose(OrderTicket(), OrderLots(), Bid, 3, Green); if (CloseTicket <= 0) { Print("Ошибка закрытия ордера: ", GetLastError()); } } } } g_OrdersCount = 0; g_TotalProfit = 0; g_MaxProfit = 0; }
2af2f23e54af80379b8ba7d37d9a2f4b
{ "intermediate": 0.26268792152404785, "beginner": 0.5079959630966187, "expert": 0.22931607067584991 }
14,504
hwo to make the columns autofill the datagridview1
e403a613a651fac721d6dcd33e04d380
{ "intermediate": 0.35794806480407715, "beginner": 0.13071176409721375, "expert": 0.5113402009010315 }
14,505
hi
06d7acd9a9cd2f718f10094bf544c056
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
14,506
give me a random rich json
333a86b0cbaa54714bce0fcafa6ca6ed
{ "intermediate": 0.3349224328994751, "beginner": 0.39061439037323, "expert": 0.2744632363319397 }
14,507
write .bat to end opened excel.exe tasks except the older one
ff9972f5c8d2b0e96ba855f70582ce01
{ "intermediate": 0.33847618103027344, "beginner": 0.3015347719192505, "expert": 0.35998907685279846 }
14,508
for example in django, what is the string mean? I mean the part behind it is the function of views but string before? path('result-zip', views.get_result_zip, name='get_result_zip')
e284e042a286be51ddd187a93435f91a
{ "intermediate": 0.7076727151870728, "beginner": 0.2133125513792038, "expert": 0.07901472598314285 }
14,509
give me all tlancher folders and files names
81396e2a1badd3c84291754383d89e49
{ "intermediate": 0.33950111269950867, "beginner": 0.1893661767244339, "expert": 0.471132755279541 }
14,510
I have this nestjs controller import { Controller, Post, UploadedFile, UseInterceptors, } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; import { CloudinaryService } from './cloudinary.service'; @Controller('images') export class CloudinaryController { constructor(private readonly cloudinaryService: CloudinaryService) {} @Post() @UseInterceptors(FileInterceptor('image')) async uploadImage(@UploadedFile() file: Express.Multer.File) { const uploadStream: any = this.cloudinaryService.uploadImage(file); return uploadStream; } } And this service import { Injectable } from '@nestjs/common'; import { UploadApiErrorResponse, UploadApiResponse, v2 } from 'cloudinary'; import toStream = require('buffer-to-stream'); @Injectable() export class CloudinaryService { async uploadImage( fileName: Express.Multer.File, ): Promise<UploadApiResponse | UploadApiErrorResponse> { return new Promise((resolve, reject) => { const upload = v2.uploader.upload_stream((error, result) => { if (error) return reject(error); resolve(result); }); toStream(fileName.buffer).pipe(upload); }); } } How can I refactor so that I can update multiple files
e23a11c02ea9f190f5f15b41cd9a59d7
{ "intermediate": 0.6173604726791382, "beginner": 0.19110116362571716, "expert": 0.19153828918933868 }
14,511
код на C# winform почему при создании файла буквы на русском языке не видны private void button6_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "Текстовый документ (*.txt)|*.txt|Все файлы (*.*)|*.*"; openFileDialog1.Title = "Выберите файл с данными"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { // Считываем все строки файла string[] lines = File.ReadAllLines(openFileDialog1.FileName); string iniFolderPath = @"C:\Users\HP\Desktop\2023\практика\request"; // Обрабатываем каждую строку foreach (string line in lines) { // Открываем диалог выбора места сохранения файла ini string iniFilePath = Path.Combine(iniFolderPath, line + ".ini"); Encoding encoding = Encoding.GetEncoding("windows-1251"); string[] parts = line.Split(','); // Создаем новый файл ini и записываем в него имя из строки файла txt using (StreamWriter sw = new StreamWriter( new FileStream(iniFilePath, FileMode.Create), Encoding.GetEncoding("windows-1251") ))
157ffb44b2d7800f84befa7c459601aa
{ "intermediate": 0.478819876909256, "beginner": 0.31975212693214417, "expert": 0.20142807066440582 }
14,512
how to keep & in java
67c061e03085726e4845e60b026b08ff
{ "intermediate": 0.3352133333683014, "beginner": 0.39705780148506165, "expert": 0.26772886514663696 }
14,513
Read a json file from a path with python in 1 line.
598258e35550efcba0c22a8b90a1e20e
{ "intermediate": 0.4966202974319458, "beginner": 0.19351549446582794, "expert": 0.30986422300338745 }
14,514
package com.eisgroup.csaa.metadata.impl; import com.eisgroup.csaa.metadata.api.ApiMetadataExtensions; import com.eisgroup.csaa.metadata.api.ApiMetadataProvider; import com.eisgroup.csaa.metadata.api.ApiMetadataRequest; import com.eisgroup.csaa.metadata.api.ApiRuleMetadataProvider; import com.eisgroup.csaa.metadata.api.ApiRuleMetadataRequest; import com.eisgroup.csaa.metadata.dto.OperationRule; import com.fasterxml.jackson.core.type.TypeReference; import core.dataproviders.dto.InternalDTO; import core.dataproviders.impl.ContextPreservingCompletionStageFactory; import core.exceptions.InternalGatewayException; import core.exceptions.ValidationException; import core.exceptions.dto.ValidationExceptionDTO; import core.utils.JsonUtils; import dataproviders.productfactory.dto.MapDTO; import dataproviders.productfactory.dto.ProductFactoryOperationDTO; import io.swagger.converter.ModelConverters; import io.swagger.models.Model; import io.swagger.models.ModelImpl; import io.swagger.models.Swagger; import io.swagger.models.properties.Property; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.inject.Inject; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; public class ApiRuleMetadataProviderImpl implements ApiRuleMetadataProvider { @Inject private ApiMetadataProvider apiMetadataProvider; @Inject private JsonUtils jsonUtils; public void runRules(ApiRuleMetadataRequest apiRuleMetadataRequest) { List<OperationRule> changesForValidations = findChangesForRules(apiRuleMetadataRequest); if(CollectionUtils.isNotEmpty(changesForValidations)) { ContextPreservingCompletionStageFactory.completedFuture(generateMetadataRequest(apiRuleMetadataRequest, changesForValidations)) .thenCompose(apiMetadataRequest -> apiMetadataProvider.get(apiMetadataRequest)) .thenApply(metadata -> findAndApplyMetatdata(changesForValidations, metadata, apiRuleMetadataRequest)) .thenCompose(this::executeApplicability) .thenCompose(this::executeDefault) .thenCompose(this::executeRequired) .thenCompose(this::executeValueRange) .thenCompose(this::executeValidators) .whenComplete(this::throwExceptionIfNeeded) .toCompletableFuture().join(); } } private void throwExceptionIfNeeded(Stream<OperationRule> operationRule, Throwable throwable) { Map<String, HashSet<String>> exceptions = new HashMap<>(); operationRule.filter(rule -> rule.getValidationResult() != null) .forEach(result -> result.getValidationResult().forEach((errorMessage, isPassed) -> { if (!isPassed) { exceptions.computeIfAbsent(result.getAttributeName(), key -> new HashSet<>()).add(errorMessage); } })); if (MapUtils.isNotEmpty(exceptions)) { throw new ValidationException("FIELD VALIDATIONS", null, exceptions.entrySet().stream().map(exception -> new ValidationExceptionDTO(":)", StringUtils.joinWith(" ", exception.getValue()), exception.getKey())) .collect(Collectors.toList())); } } private CompletableFuture<Stream<OperationRule>> executeValueRange(Stream<OperationRule> operationRules) { return CompletableFuture.completedFuture(operationRules.peek(rule -> { if (!rule.hasFailure() && ruleHasValueRange(rule)) { handleValueRangeRule(rule); rule.setFailure(true); } })); } private CompletableFuture<Stream<OperationRule>> executeRequired(Stream<OperationRule> operationRules) { return CompletableFuture.completedFuture(operationRules.peek(rule -> { if (!rule.hasFailure() && CollectionUtils.isNotEmpty(rule.getValidators()) && ruleHasRequiredValidator(rule)) { handleRequiredRule(rule); } })); } private CompletableFuture<Stream<OperationRule>> executeValidators(Stream<OperationRule> operationRules) { return CompletableFuture.completedFuture(operationRules.peek(rule -> { if(!rule.hasFailure() && CollectionUtils.isNotEmpty(rule.getValidators())) { handleValidationRules(rule); } })); } private CompletableFuture<Stream<OperationRule>> executeApplicability(Stream<OperationRule> operationRules) { return CompletableFuture.completedFuture( operationRules .peek(rule -> { if(!rule.isApplicable() && !ObjectUtils.allNotNull(rule.getAttributeValue())) { rule.setFailure(true); return; } if(!rule.isApplicable()) { handleApplicabilityRule(rule); rule.setFailure(true); } }) ); } private CompletableFuture<Stream<OperationRule>> executeDefault(Stream<OperationRule> operationRules) { return CompletableFuture.completedFuture( operationRules.peek(rule -> { if(StringUtils.isNotBlank(rule.getDefaultValue()) && rule.getAttributeValue() == null || (rule.getAttributeValue() instanceof String && StringUtils.isBlank((String) rule.getAttributeValue()))) { //TODO Add type resolver for defaulting... rule.setAttributeValue(rule.getDefaultValue()); if (rule.getOperation().requestData instanceof MapDTO) { ((MapDTO) rule.getOperation().requestData).getItems().put(rule.getAttributeName(), rule.getDefaultValue()); return; } InternalDTO internalDTO = rule.getOperation().requestData; try { Field field = internalDTO.getClass().getField(rule.getAttributeName()); field.set(internalDTO, rule.getDefaultValue()); } catch (NoSuchFieldException | IllegalAccessException e) { throw new InternalGatewayException(String.format("Cannot find attribute in class by this name '%s'", rule.getAttributeName()), e); } } })); } private Stream<OperationRule> findAndApplyMetatdata(List<OperationRule> changesForValidations, Swagger metadata, ApiRuleMetadataRequest apiRuleMetadataRequest) { var scopeValidators = new ArrayList<String>(); if (StringUtils.isNotBlank(apiRuleMetadataRequest.getScope())) { scopeValidators.addAll(metadata.getDefinitions().entrySet().stream() .flatMap(definitions -> definitions.getValue().getProperties().entrySet().stream()) .flatMap(properties -> properties.getValue().getVendorExtensions().entrySet().stream()) .filter(extension -> extension.getKey().equals(ApiMetadataExtensions.OpenLValidator.NAME)) .flatMap(extension -> Stream.of((String[]) extension.getValue()) .filter(validatorName -> validatorName.contains(apiRuleMetadataRequest.getScope()))) .distinct() .collect(Collectors.toList())); } return changesForValidations.stream() .filter(rule -> filterChangeByVendorExtensions(rule, metadata)) .map(rule -> setMetadata(rule, metadata, scopeValidators, apiRuleMetadataRequest.getScope())); } private boolean ruleHasRequiredValidator(OperationRule rule) { return rule.getValidators().stream() .anyMatch(validatorName -> validatorName.equals("required")); } private void handleRequiredRule(OperationRule rule) { boolean isEmpty = Validators.VALIDATORS.get("required") .apply(rule.getAttributeValue()) .entrySet() .stream() .anyMatch(validationResult -> !validationResult.getValue()); if (isEmpty) { rule.getValidationResult().computeIfAbsent("Field is required", key -> false); rule.setFailure(true); } } private boolean ruleHasValueRange(OperationRule rule) { return CollectionUtils.isNotEmpty(rule.getValueRange()) && !rule.getValueRange().contains(rule.getAttributeValue()); } private void handleApplicabilityRule(OperationRule rule) { rule.getValidationResult().computeIfAbsent(String.format("Field is not applicable", rule.getAttributeValue(), rule.getValueRange()), key -> false); } private void handleValueRangeRule(OperationRule rule) { rule.getValidationResult().computeIfAbsent(String.format("Field value is not in range. Value: %s - Range: %s", rule.getAttributeValue(), rule.getValueRange()), key -> false); } private void handleValidationRules(OperationRule rule) { rule.getValidationResult().putAll(executeValidationRules(rule)); } private Map<String, Boolean> executeValidationRules(OperationRule rule) { return rule.getValidators().stream() .filter(Validators.VALIDATORS::containsKey) .flatMap(validatorName -> { var validator = Validators.VALIDATORS.get(validatorName); return validator.apply(rule.getAttributeValue()).entrySet().stream(); }) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } private ApiMetadataRequest generateMetadataRequest(ApiRuleMetadataRequest apiRuleMetadataRequest, List<OperationRule> chg) { Map<String, Set<String>> map = new HashMap<>(); String lowerCaseLob = StringUtils.lowerCase(apiRuleMetadataRequest.getLob()); chg.forEach(changes -> { map.computeIfAbsent("attributes", key -> new HashSet<>()).add(changes.getAttributeName()); map.computeIfAbsent("models", key -> new HashSet<>()).add(((ModelImpl) changes.getModel()).getName()); }); return ApiMetadataRequest.buildFor(apiRuleMetadataRequest.getApiDtoClass()) .addRequestParam("openLServiceName", "aaa-" + lowerCaseLob + "-policy-rules") .addRequestParam("productCd", apiRuleMetadataRequest.getProductCd()) .addRequestParam("riskStateCd", apiRuleMetadataRequest.getRiskState()) .addRequestParam("effectiveDate", apiRuleMetadataRequest.getEffectiveDate()) .filterByModels(map.get("models")) .filterByProperties(map.get("attributes")) .withSmartModels(apiRuleMetadataRequest.getLob()); } private List<OperationRule> findChangesForRules(ApiRuleMetadataRequest apiRuleMetadataRequest) { var modelMap = ModelConverters.getInstance().readAll(apiRuleMetadataRequest.getApiDtoClass()).values(); return apiRuleMetadataRequest.getRequest().getOperations().stream() .flatMap(operation -> { if (operation.requestData instanceof MapDTO) { return createOperationRuleFromMap(((MapDTO) operation.requestData).getItems(), operation); } //TODO need to add skip for non component operations if(operation.requestData != null) { return createOperationRuleFromIternalDto(operation); } return Stream.empty(); }) .filter(changes -> changes.getOperation().referenceName != null) .filter(changes -> isMatchingModel(changes, modelMap, apiRuleMetadataRequest)) .collect(Collectors.toList()); } private Stream<OperationRule> createOperationRuleFromMap(Map<String, Object> requestData, ProductFactoryOperationDTO operation) { return requestData.entrySet().stream() .map(entry -> new OperationRule(operation, entry.getKey(), entry.getValue())); } private Stream<OperationRule> createOperationRuleFromIternalDto(ProductFactoryOperationDTO operation) { var changes = jsonUtils.getDefaultObjectMapper().convertValue(operation.requestData, new TypeReference<Map<String, Object>>() {}); return createOperationRuleFromMap(changes, operation); } private boolean isMatchingModel(OperationRule changes, Collection<Model> modelMap, ApiRuleMetadataRequest apiRuleMetadataRequest) { return modelMap.stream().anyMatch(model -> { Map<String, Property> properties = model.getProperties(); if (!properties.containsKey(changes.getAttributeName())) { return false; } Property property = properties.get(changes.getAttributeName()); Map<String, Object> vendor = property.getVendorExtensions(); if (vendor.containsKey(ApiMetadataExtensions.Pf.NAME)) { var extension = (Map<String, String>) vendor.get(ApiMetadataExtensions.Pf.NAME); String referenceName = extension.get(ApiMetadataExtensions.Pf.REFERENCE_NAME); String attributeName = extension.get(ApiMetadataExtensions.Pf.ATTRIBUTE_NAME); if (changes.getOperation().referenceName.equals(referenceName) && changes.getAttributeName().equals(attributeName)) { changes.setModel(model); return true; } } String modelName = getModelName(changes, apiRuleMetadataRequest); if (modelName.equals(((ModelImpl) model).getName())) { changes.setModel(model); return true; } return false; }); } private boolean filterChangeByVendorExtensions(OperationRule change, Swagger metadata) { Model model = getModelFromSwagger(change, metadata); if (model != null) { Property property = model.getProperties().get(change.getAttributeName()); Map<String, Object> vendorExtensions = property.getVendorExtensions(); return vendorExtensions.containsKey(ApiMetadataExtensions.OpenLValidator.NAME) || vendorExtensions.containsKey(ApiMetadataExtensions.OpenLDefaultValue.NAME) || vendorExtensions.containsKey(ApiMetadataExtensions.OpenLValueRange.NAME) || vendorExtensions.containsKey(ApiMetadataExtensions.OpenLApplicable.NAME); } return false; } private OperationRule setMetadata(OperationRule rule, Swagger metadata, List<String> scopeValidators, String scope) { Model model = getModelFromSwagger(rule, metadata); if (model != null) { Property property = model.getProperties().get(rule.getAttributeName()); Map<String, Object> vendorExtensions = property.getVendorExtensions(); rule.setModel(model); if (vendorExtensions.containsKey(ApiMetadataExtensions.OpenLValidator.NAME)) { var validatorsArray = (String[]) vendorExtensions.get(ApiMetadataExtensions.OpenLValidator.NAME); var validators = new ArrayList<>(Arrays.asList(validatorsArray)); if(StringUtils.isNotBlank(scope)) { scopeValidators.forEach(scopeValidator -> { if (validators.stream().anyMatch(scopeValidator::equals)) { validators.remove(scopeValidator); return; } validators.remove(scopeValidator.replace("For" + scope, "")); }); } rule.setValidators(validators); } if(vendorExtensions.containsKey(ApiMetadataExtensions.OpenLDefaultValue.NAME)) { var defaultValue = (String) vendorExtensions.get(ApiMetadataExtensions.OpenLDefaultValue.NAME); rule.setDefaultValue(defaultValue); } if(vendorExtensions.containsKey(ApiMetadataExtensions.OpenLValueRange.NAME)) { var valueRange = (LinkedHashMap<String, String>) vendorExtensions.get(ApiMetadataExtensions.OpenLValueRange.NAME); valueRange.remove(StringUtils.EMPTY); if(CollectionUtils.isNotEmpty(valueRange.keySet()) && ObjectUtils.allNotNull(rule.getAttributeValue())) { rule.setValueRange(valueRange.keySet()); } } if(vendorExtensions.containsKey(ApiMetadataExtensions.OpenLApplicable.NAME)) { rule.setApplicable((Boolean) vendorExtensions.get(ApiMetadataExtensions.OpenLApplicable.NAME)); } } return rule; } private Model getModelFromSwagger(OperationRule change, Swagger metadata) { String modelName = ((ModelImpl) change.getModel()).getName(); return metadata.getDefinitions().get(modelName); } private String getModelName(OperationRule change, ApiRuleMetadataRequest apiRuleMetadataRequest) { return apiRuleMetadataRequest.getLob() + change.getOperation().referenceName; } }
b5959c7b399965355d91bf6b2d82196f
{ "intermediate": 0.3262503147125244, "beginner": 0.48307088017463684, "expert": 0.19067884981632233 }
14,515
o when user send request to access a certain url, it will tell user urls on django to go to that specific function in views, then views will have a function that render html to display the page?
39e59b5d8023023175c8ceeacc7b1332
{ "intermediate": 0.6836355924606323, "beginner": 0.15603071451187134, "expert": 0.16033367812633514 }
14,516
how import dataset ms coco to google colab ?
3ab637d51378269af45a7dfc9b9dfff9
{ "intermediate": 0.513127863407135, "beginner": 0.13159789144992828, "expert": 0.3552743196487427 }
14,517
i have the following DAX calculated column twice in a table with a diffrent name. The first one works and the second give me a circular dependency error. Why and how can i fix it: FY22 A(Mod) = VAR OPR1 = [FY21PGSC]+CALCULATE(sum([FY21 A]),NOT '33Atlas_Raw'[BU] IN {"PGSC","PGRE","PGCO","PGGB"}) VAR OPR2 = ([FY21 A]) return OPR1
7c481575ee1d9b8d14a166761e9e58c5
{ "intermediate": 0.36918357014656067, "beginner": 0.24109363555908203, "expert": 0.3897227346897125 }
14,518
in c#, how can I compare this without errors: BorderColor.Background != Colors.Transparent
5bd61171b7d95c70456e1714633aefc4
{ "intermediate": 0.5974239706993103, "beginner": 0.2162838578224182, "expert": 0.18629221618175507 }
14,519
mixins or composite objects?
ca472704b5e02799b3be2a3cb7eb0b91
{ "intermediate": 0.421935498714447, "beginner": 0.3146204650402069, "expert": 0.2634440064430237 }
14,520
The following Calculated columns are used to calculate the end result of FY21 A(Mod): 1- FY21 A(Mod) = VAR OPR1 = [FY21_PGSC]+CALCULATE(sum([FY21 A]),NOT '33_Atlas_Raw'[BU] IN {"PGSC","PGRE","PGCO","PGGB"}) return OPR1 2- FY21_PGSC = VAR PGSC = [FY21_PGSC Total]*[FY21%] //VAR NonPGSC = SUM([FY21 A]) return PGSC 3- FY21_PGSC Total = VAR OPR1 = CALCULATE(SUM([FY21 A]),'33_Atlas_Raw'[BU] IN {"PGSC", "PGCO", "PGGB", "PGRE"},ALLEXCEPT('33_Atlas_Raw','33_Atlas_Raw'[BU],'33_Atlas_Raw'[Stratos_ISO])) //VAR OPR1 = CALCULATE(SUM([FY21 A]),'33_Atlas_Raw'[BU] IN {"PGSC", "PGCO", "PGGB", "PGRE"},ALLEXCEPT('33_Atlas_Raw','33_Atlas_Raw'[BU],'33_Atlas_Raw'[Iso Allocation])) VAR OPR2 = COUNTROWS(GROUPBY('33_Atlas_Raw', '33_Atlas_Raw'[Stratos_ISO])) VAR PGSC = opr1*[FY21%] Return OPR1 4- FY21% = VAR Looking = LOOKUPVALUE('33_VR_Stratos_SC'[FY21%],'33_VR_Stratos_SC'[PGSC-Key],'33_Atlas_Raw'[PGSC-Key]) VAR BUCOUNT = CALCULATE(COUNTROWS('33_Atlas_Raw'), ALLEXCEPT('33_Atlas_Raw', '33_Atlas_Raw'[BU], '33_Atlas_Raw'[Stratos_ISO])) VAR OPR1PGCO = SWITCH([PGSC-Key], "PGGAPG Holding", 0.25, "PGGIPG Holding", 0.25, "PGTRPG Holding", 0.25, "PGHVPG Holding", 0.25, DIVIDE(Looking,BUCOUNT) ) Return OPR1PGCO The folowing Calculated columns are used to calculate the end result of FY22 A(Mod): 1- FY22 A(Mod) = VAR OPR1 = [FY22_PGSC]+CALCULATE(sum([FY22 A]),NOT '33_Atlas_Raw'[BU] IN {"PGSC","PGRE","PGCO","PGGB"}) return OPR1 2- FY22_PGSC = VAR PGSC = [FY22_PGSC Total]*[FY22%] //VAR NonPGSC = SUM([FY21 A]) return PGSC 3- FY22_PGSC Total = VAR OPR1 = CALCULATE(SUM([FY22 A]),'33_Atlas_Raw'[BU] IN {"PGSC", "PGCO", "PGGB", "PGRE"},ALLEXCEPT('33_Atlas_Raw','33_Atlas_Raw'[BU],'33_Atlas_Raw'[Stratos_ISO])) //VAR OPR1 = CALCULATE(SUM([FY21 A]),'33_Atlas_Raw'[BU] IN {"PGSC", "PGCO", "PGGB", "PGRE"},ALLEXCEPT('33_Atlas_Raw','33_Atlas_Raw'[BU],'33_Atlas_Raw'[Iso Allocation])) VAR OPR2 = COUNTROWS(GROUPBY('33_Atlas_Raw', '33_Atlas_Raw'[Stratos_ISO])) VAR PGSC = opr1*[FY22%] Return OPR1 4- FY22% = LOOKUPVALUE('33_VR_Stratos_SC'[FY22%],'33_VR_Stratos_SC'[PGSC-Key],'33_Atlas_Raw'[PGSC-Key]) WHy is FY22 A(Mod) calculated column geving me the following error, PLease analyis slowly to undestand. All calculated columns live within the same table
c3b277dbb79d8c2e25ba2cc45c1e68f4
{ "intermediate": 0.2845526933670044, "beginner": 0.4803193509578705, "expert": 0.23512795567512512 }
14,521
in django, for many button in 1 form, how do you know which button triggered
04cecbeac565e90bfaab63c684c3ff87
{ "intermediate": 0.6146334409713745, "beginner": 0.1113724485039711, "expert": 0.2739940881729126 }
14,522
I've a Tasks table in my asp.net core project, it contains this prop: "set.CloseDate = DateTime.UtcNow.AddDays(1);" write a code to do something when time reaches the specefied datetime, for every item in this list of items. note that i also have this class: DailyResetService.cs: "using cryptotasky.Models; namespace cryptotasky { public class DailyResetService : IHostedService, IDisposable { private Timer _timer; public System.Threading.Tasks.Task StartAsync(CancellationToken cancellationToken) { var now = DateTime.Now; var nextRunTime = DateTime.Today.AddDays(1).AddHours(0).AddMinutes(0).AddSeconds(0) - now; // Calculate the time until the next desired run _timer = new Timer(DoWork, null, nextRunTime, TimeSpan.FromDays(1)); // Run the DoWork method every 24 hours return System.Threading.Tasks.Task.CompletedTask; } private void DoWork(object state) { using (CryptoTContext db = new CryptoTContext()) { var all = db.Users.ToList(); foreach (var user in all) { user.DailyDoneTasks = 0; } db.SaveChanges(); } } public System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken) { _timer?.Change(Timeout.Infinite, 0); return System.Threading.Tasks.Task.CompletedTask; } public void Dispose() { _timer?.Dispose(); } } } " that runs some code when time is 12:00:00 AM
653e0c4a31e9676c006b195d17fbdb6c
{ "intermediate": 0.6372846961021423, "beginner": 0.19698961079120636, "expert": 0.1657257378101349 }
14,523
I have this code in asp.net core: "using cryptotasky.Models; namespace cryptotasky { public class DailyResetService : IHostedService, IDisposable { private Timer _timer; public System.Threading.Tasks.Task StartAsync(CancellationToken cancellationToken) { var now = DateTime.Now; var nextRunTime = DateTime.Today.AddDays(1).AddHours(0).AddMinutes(0).AddSeconds(0) - now; // Calculate the time until the next desired run _timer = new Timer(DoWork, null, nextRunTime, TimeSpan.FromDays(1)); // Run the DoWork method every 24 hours return System.Threading.Tasks.Task.CompletedTask; } private void DoWork(object state) { using (CryptoTContext db = new CryptoTContext()) { var all = db.Users.ToList(); foreach (var user in all) { user.DailyDoneTasks = 0; } db.SaveChanges(); } } " the Dowork() function runs every day at 12:00:00AM i want PerformActionWhenCloseDateReached() to run every hour.
1bfb80ed6b468a78c53bfd1d67e3a4b5
{ "intermediate": 0.3778705596923828, "beginner": 0.3342389762401581, "expert": 0.2878905236721039 }
14,524
java code to display midi music scores on a score sheet consisting of two horizontal graphics2d bars with each has horizontal 5 lines. the bottom bar is for 3th octave, the top bar is for 5th octave tones. midi scores can sit between two lines or on top of it.
7b4e16fce242121b8920dcffc86176fd
{ "intermediate": 0.4227428734302521, "beginner": 0.18298198282718658, "expert": 0.3942751884460449 }
14,525
This code: "using cryptotasky.Models; using Microsoft.Extensions.Hosting; namespace cryptotasky { public class DailyResetService : IHostedService, IDisposable { private Timer _dailyTimer; private Timer _hourlyTimer; public System.Threading.Tasks.Task StartAsync(CancellationToken cancellationToken) { var now = DateTime.Now; // Calculate the time until the next desired daily run (12:00:00 AM) var nextDailyRunTime = DateTime.Today.AddDays(1).AddHours(0) - now; // Run the DoWork method every 24 hours _dailyTimer = new Timer(DoWork, null, nextDailyRunTime, TimeSpan.FromDays(1)); // Calculate the time until the next desired hourly run (every hour) var nextHourlyRunTime = DateTime.Now.AddHours(1).Date - now; // Run the PerformActionWhenCloseDateReached method every hour _hourlyTimer = new Timer(PerformActionWhenCloseDateReached, null, nextHourlyRunTime, TimeSpan.FromHours(1)); return System.Threading.Tasks.Task.CompletedTask; } private void DoWork(object state) { using (CryptoTContext db = new CryptoTContext()) { var all = db.Users.ToList(); foreach (var user in all) { user.DailyDoneTasks = 0; } db.SaveChanges(); } } private void PerformActionWhenCloseDateReached(object state) { using (CryptoTContext db = new CryptoTContext()) { var tasks = db.Tasks.Where(t => t.CloseDate != null && t.CloseDate <= DateTime.UtcNow).ToList(); foreach (var task in tasks) { task.CloseDate = null; } db.SaveChanges(); } } public System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken) { _dailyTimer?.Dispose(); _hourlyTimer?.Dispose(); return System.Threading.Tasks.Task.CompletedTask; } public void Dispose() { _dailyTimer?.Dispose(); _hourlyTimer?.Dispose(); } } }" is causing this error: "Unhandled exception. System.ArgumentOutOfRangeException: Number must be either non-negative and less than or equal to Int32.MaxValue or -1. (Parameter 'dueTime') at System.Threading.Timer..ctor(TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period) at cryptotasky.DailyResetService.StartAsync(CancellationToken cancellationToken) in C:\Users\kingk\Desktop\Cryptotaskys\cryptotasky\DailyResetService.cs:line 25 at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken) at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token) at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token) at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host) at Program.<Main>$(String[] args) in C:\Users\kingk\Desktop\Cryptotaskys\cryptotasky\Program.cs:line 63 C:\Users\kingk\Desktop\Cryptotaskys\cryptotasky\bin\Debug\net7.0\cryptotasky.exe (process 13732) exited with code -532462766. Press any key to close this window . . ."
c0777e5a4cf9a5b404ae30f3ec1b9510
{ "intermediate": 0.49569934606552124, "beginner": 0.384554386138916, "expert": 0.11974630504846573 }
14,526
Is this written correctly? "Tiktok has cracked down on growth services that rely on bots. Bought followers are now frequently flagged as bots or fakes by TikTok, and they’ll eventually get removed. Meanwhile, "name" has the perfect solution. We perform all actions manually, which requires time and energy, but this ensures that you can enjoy organic and sustainable growth for your TikTok account by gaining real engagement. Up to date our growth method stands out as the most secure alternative."
227d707bfd93956f4703e48edec83d3b
{ "intermediate": 0.28949815034866333, "beginner": 0.5611701607704163, "expert": 0.149331733584404 }
14,527
Ui is a function of state
f395323d8f36ce516325d75315067a2f
{ "intermediate": 0.3400588035583496, "beginner": 0.41576141119003296, "expert": 0.24417980015277863 }
14,528
I have this code <section class="pricing"> <div class="pricing-container"> <div class="pricing-column column-1"> CONTENUTI </div> <div class="pricing-column column-2"> CONTENUTI </div> <div class="pricing-column column-3"> CONTENUTI </div> </div> </section> With this in the CSS: @media screen and (max-width: 768px) { .pricing-container { display: flex !important; overflow-x: auto !important; scroll-snap-type: x mandatory !important; -webkit-overflow-scrolling: touch !important; } .pricing-column { flex: 1 0 100% !important; min-width: 300px !important; scroll-snap-align: start !important; } My goal is for the mobile version of the site to add the swiper buttons to the above. Like the one below: <div class="elementor-swiper-button elementor-swiper-button-prev" role="button" tabindex="0"> <i aria-hidden="true" class="eicon-chevron-left"></i> <span class="elementor-screen-only">Previous</span> </div> <div class="elementor-swiper-button elementor-swiper-button-next" role="button" tabindex="0"> <i aria-hidden="true" class="eicon-chevron-right"></i> <span class="elementor-screen-only">Next</span> </div>
646c2b5f23afa3178406b1371894e087
{ "intermediate": 0.47218722105026245, "beginner": 0.24480906128883362, "expert": 0.2830037474632263 }
14,529
I've an asp.net core project, this is the controller code: "[HttpGet("/user/tasks/{id:int}")] public async Task<IActionResult> tasks(int id) { var set = _context.Users.Where(x => x.Id == id).FirstOrDefault(); if (set == null) { string reactPath = "/"; return Content(reactPath); } var loop = _context.CompletedTasks.Where(x => x.UserId == id).Select(x => x.TaskId).ToList(); var data = _context.Tasks.ToList(); if (loop != null) { var show = data.Where(x => !loop.Contains(x.Id)).ToList(); var getins = new multi(); getins.users = set; getins.tasky = show; getins.complete = _context.CompletedTasks.Where(x => x.UserId == id).ToList(); return Ok(getins); } var getin = new multi(); getin.users = set; getin.tasky = data; getin.complete = _context.CompletedTasks.Where(x => x.UserId == id).ToList(); return Ok(getin); }" and this is the axios request: "const userIdD = localStorage.getItem('userId'); const bein = parseInt(userIdD); useEffect(() => { const fetchData = async () => { try { const response = await axios.get(`http://localhost:5041/api/user/tasks/${bein}`); const { users, tasky, complete } = response.data; } catch (error) { console.error('There was an error!', error); message.error('حدث خطأ يرجى المحاولة في وقت لاحق'); } }; fetchData(); }, []); const [users, setUsers] = useState([]); const [tasky, setTasky] = useState([]); const [complete, setComplete] = useState([]);" the console is returning this error: "{ "message": "Request failed with status code 404", "name": "AxiosError", "stack": "AxiosError: Request failed with status code 404\n at settle (http://localhost:44426/static/js/bundle.js:134514:12)\n at XMLHttpRequest.onloadend (http://localhost:44426/static/js/bundle.js:133093:66)", "config": { "transitional": { "silentJSONParsing": true, "forcedJSONParsing": true, "clarifyTimeoutError": false }, "adapter": [ "xhr", "http" ], "transformRequest": [ null ], "transformResponse": [ null ], "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "maxBodyLength": -1, "env": {}, "headers": { "Accept": "application/json, text/plain, */*" }, "method": "get", "url": "http://localhost:5041/api/user/tasks/2002" }, "code": "ERR_BAD_REQUEST", "status": 404 }" figure out why.
d48a5decba77ae199cdb12e20e4fd0f2
{ "intermediate": 0.3742728531360626, "beginner": 0.40338099002838135, "expert": 0.22234617173671722 }
14,530
How to make a responsive table in react from a json structure similar to the following: { "Symbol": "GOOG", "CalcTime": "2023-07-03T09:58:00", "UndPrice": 120.845, "Rate": 0.045, "Expirations": { "oGOOG 23070": { "SymRoot": "oGOOG 23070", "Dte": 4.25138888888889, "DivYield": 0, }, "oGOOG 23071": { "SymRoot": "oGOOG 23071", "Dte": 4.25138888888889, "DivYield": 0, }, } } Where the SymRoot, DivYield, and DTE properties and their values are the table headers and values respectively
86b74e754bf55ce8f66264d2a4d3bcbb
{ "intermediate": 0.39181938767433167, "beginner": 0.22062289714813232, "expert": 0.3875576853752136 }
14,531
write code javascript
944c9db20b0c1626de2c27bb205d54e9
{ "intermediate": 0.28663313388824463, "beginner": 0.42804020643234253, "expert": 0.28532668948173523 }
14,532
Givw me more detail instructions on how to configure and setup each and everything included : To create a secure network in Packet Tracer with the provided system characteristics and LAN configurations, the following approach can be taken for each LAN: LAN 1 - Cellular Configuration: 1. Configure the Gateway router (Model 2811) with NAT settings to handle the conversion of IPv4 private addressing to IPv4 public addressing for external connectivity. 2. Set up a public IP subnet (e.g., 172.0.10.x) to assign each smartphone with an IPv4 public IP address. 3. Install a Central Office Server with DHCP capabilities to assign private internal IP addresses to the LAN devices. It can also support static IP addresses if required. 4. Implement appropriate security measures such as firewall rules, access control lists, and intrusion detection systems at the Gateway router to protect the cellular LAN from external threats. LAN 2 - Wireless Configuration: 1. Connect each device (e.g., laptops, smartphones) to their respective Access Points using a wireless network. 2. Install a switch and configure NAT settings between the Access Points and the Gateway router to convert IPv4 private addressing to IPv4 public addressing for Internet access. 3. Use DHCP for internal network addressing, ensuring devices receive unique private IP addresses. 4. Implement WiFi security measures such as WPA2 encryption, strong passphrases, and MAC address filtering to safeguard wireless communication from unauthorized access. LAN 3 - Wired with Wireless Router Configuration: 1. Connect the three computers, three VoIP phones, and the server to a switch for wired connectivity. 2. Use a Wireless Router to provide wireless connectivity to two smartphones and three laptops within the LAN. 3. Configure the Wireless Router with appropriate security settings, including enabling WPA2 encryption, setting strong passwords, and configuring MAC address filtering. 4. Implement DHCP servers for both the wired and wireless LANs to assign private IP addresses to the devices. 5. Connect the LAN to the Gateway router using a switch and configure NAT settings to ensure external connectivity while maintaining security. Ensuring network security: 1. Deploy firewalls at each gateway router to filter and control incoming and outgoing network traffic. 2. Configure access control lists at the routers to restrict access to certain IP addresses or services. 3. Employ secure authentication mechanisms (e.g., WPA2-Enterprise with RADIUS) for WiFi networks to prevent unauthorized access. 4. Regularly update router firmware and apply security patches to mitigate vulnerabilities. 5. Implement intrusion detection and prevention systems to monitor network traffic and detect potential threats. 6. Employ encryption protocols (e.g., SSL/TLS) for secure transmission of data over the network. 7. Train network users about best security practices, including strong passwords, regular backups, and awareness of phishing attempts. By incorporating these security measures, each LAN in the network system can be emulated securely in Packet Tracer, protecting the network infrastructure and data from potential threats and unauthorized access.
c89e4d88a571e835631ec5f7bdf79777
{ "intermediate": 0.3753059506416321, "beginner": 0.2553974986076355, "expert": 0.36929652094841003 }
14,533
pandas count unique values in column
cb778927ae84e9dd36060a4f24b1c5f5
{ "intermediate": 0.38117367029190063, "beginner": 0.37307512760162354, "expert": 0.24575118720531464 }
14,534
What is code (source code) of a computer program
175164ed0fc1afd8c8493e4ae0a9e8f6
{ "intermediate": 0.1484069973230362, "beginner": 0.5045934915542603, "expert": 0.34699946641921997 }
14,535
give me code c# to make request to google , let you know that i have proxy ntlm
21cfc62180bccf740f9c43d18ec5cb6e
{ "intermediate": 0.5500831007957458, "beginner": 0.20590458810329437, "expert": 0.24401231110095978 }
14,536
A linux script to backup a Microsoft SQL Server database using Ola Hallengren scripts, compress it with 7zip and upload it to OneDrive using rclone but checks for free disk drive before making the backup and the archive
3b374016674570b9a044c5cb44d944ce
{ "intermediate": 0.37283456325531006, "beginner": 0.262154757976532, "expert": 0.36501073837280273 }
14,537
WITH limited_tasks AS ( SELECT * FROM tasks LIMIT 1000 ) SELECT limited_tasks.id, limited_tasks.task, limited_tasks.answer, limited_tasks.level FROM limited_tasks ORDER BY limited_tasks.id ASC И есть классы во flask class Tasks(db.Model): __tablename__ = 'tasks' __searchable__ = ['task','id'] # these fields will be indexed by whoosh id = db.Column(db.Integer, primary_key=True, autoincrement=True) url = db.Column(db.String(120), comment="ЧПУ задачи в адресе (транслитом)") task = db.Column(db.Text, comment='Условие задачи') answer = db.Column(db.Text, comment='Ответ') status = db.Column(db.Boolean, default=0, comment='Статус: опубликована/неактивна (по умолчанию нет)') created_t = db.Column(db.DateTime, comment='Дата и время создания') level = db.Column(db.SmallInteger, default=1, comment='Уровень сложности: 1,2 ... (по умолчанию 1 уровень)') # связи topics = db.relationship('Topics', secondary=tasks_topics, back_populates="tasks") Как переписать в sql alchemy
c0f712a6efcfb71bcfc9711e5aae8055
{ "intermediate": 0.38153448700904846, "beginner": 0.38712507486343384, "expert": 0.2313404232263565 }
14,538
I've an asp.net core with reactjs project, this is my antDesign upload logic: "const props = { name: 'file', action: `http://localhost:5041/admin/uploadtask/${params.id}`, // change this to your server endpoint that will handle the file upload headers: { authorization: 'authorization-text', }, onChange(info) { if (info.file.status !== 'جاري الرفع') { console.log(info.file, info.fileList); } if (info.file.status === 'تم') { message.success(`${info.file.name} تم رفع الملف`); // save the response url in the state setFileUrl(info.file.response.url); } else if (info.file.status === 'خطأ') { message.error(`${info.file.name} فشل رفع الملف.`); } }, progress: { strokeColor: { '0%': '#108ee9', '100%': '#87d068', }, strokeWidth: 3, format: (percent) => `${parseFloat(percent.toFixed(2))}%`, }, };" it is supposed to be uploading multiple images one image at a time. write the server-side C# code that would save the image itself in a folder and store the file paths like this: "data.StaticPaths = string.Join(",", statics.Select(item => item.Txt));"
87de050e48d5f45c64d320124d57c283
{ "intermediate": 0.4860847294330597, "beginner": 0.23376403748989105, "expert": 0.28015124797821045 }
14,539
I have this <section class="pricing"> <div class="pricing-container"> <div class="pricing-column column-1"> <h2>Standard</h2> <p class="text2 price">&dollar;69</p> <p class="pricing-info text2">Billed monthly. Cancel anytime.</p> <p class="pricing-description">Great for personal accounts, businesses and upcoming influencers looking for organic growth.</p> <a class="btn btn--primary type--uppercase pricing-cta text2" href="https://app.upleap.com/register?plan=standard-usd-monthly"> <span class="btn__text"> 10-day Free Trial </span> </a> <ul style="list-style-image: url(img/checkmark.html)" class="check-features"> <li><b>400+ Instagram Followers</b></li> <li>Follow/Unfollow Automation</li> <li>Real & Organic Growth</li> <li>Target by Account</li> <li>Target by Hashtag</li> <li>Suggested Targets by Industry</li> <li>Whitelist & Blacklist</li> <li>Auto-Whitelist</li> <li>Like after Follow</li> </ul> <ul style="list-style-image: url(img/exmark.html)" class="ex-features"> <li>Dedicated Account Manager</li> <li>Welcome DM Automation</li> <li>Story Liker & Viewer</li> <li>Filter by Gender</li> <li>Filter by Location</li> </ul> </div> <div class="pricing-column column-2"> <p class="most-popular-tag">Most popular</p> <h2>Pro</h2> <p class="text2 price">&dollar;119</p> <p class="pricing-info text2">Billed monthly. Cancel anytime.</p> <p class="pricing-description">Level up your Instagram game with advanced features and a <b>Dedicated Account Manager</b>.</p> <a class="btn btn--primary type--uppercase pricing-cta text2" href="https://app.upleap.com/register?plan=pro-usd-monthly"> <span class="btn__text"> 10-day Free Trial </span> </a> <ul style="list-style-image: url(img/checkmark.html)" class="check-features"> <li><b>1,000+ Instagram Followers</b></li> <li>Follow/Unfollow Automation</li> <li>Real & Organic Growth</li> <li>Target by Account</li> <li>Target by Hashtag</li> <li>Suggested Targets by Industry</li> <li>Whitelist & Blacklist</li> <li>Auto-Whitelist</li> <li>Like after Follow</li> <li>Dedicated Account Manager</li> <li>Welcome DM Automation</li> <li>Story Liker & Viewer</li> <li>Filter by Gender</li> <li>Filter by Location</li> </ul> </div> <div class="pricing-column column-3"> <h2>Premium</h2> <p class="text2 price">&dollar;239</p> <p class="pricing-info text2">Billed monthly. Cancel anytime.</p> <p class="pricing-description">Supercharge your growth with Follower Bursts. Get everything from the Pro Plan + even more exposure!</p> <a class="btn btn--primary type--uppercase pricing-cta text2" href="https://app.upleap.com/register?plan=premium-usd-monthly"> <span class="btn__text"> 10-day Free Trial </span> </a> <ul style="list-style-image: url(img/checkmark.html)" class="check-features"> <li><b>2,500+ Instagram Followers</b></li> <li>Follow/Unfollow Automation</li> <li>Real & Organic Growth</li> <li>Target by Account</li> <li>Target by Hashtag</li> <li>Suggested Targets by Industry</li> <li>Whitelist & Blacklist</li> <li>Auto-Whitelist</li> <li>Like after Follow</li> <li>Dedicated Account Manager</li> <li>Welcome DM Automation</li> <li>Story Liker & Viewer</li> <li>Filter by Gender</li> <li>Filter by Location</li> </ul> </div> </div> </section> and this @media screen and (max-width: 1024px) { .pricing-container { display: flex !important; overflow-x: auto !important; scroll-snap-type: x mandatory !important; -webkit-overflow-scrolling: touch !important; } .pricing-column { flex: 1 0 100% !important; min-width: 300px !important; scroll-snap-align: start !important; } I wanted the 3 columns to slide automatically back and forth each like 2 seconds
b2db2d4b6372b4864b8e5fd50edfa7f1
{ "intermediate": 0.2901712656021118, "beginner": 0.3693530857563019, "expert": 0.3404756486415863 }
14,540
I have this <section class=“pricing”> <div class=“pricing-container”> <div class=“pricing-column column-1”> <h2>Standard</h2> <p class=“text2 price”>$69</p> <p class=“pricing-info text2”>Billed monthly. Cancel anytime.</p> <p class=“pricing-description”>Great for personal accounts, businesses and upcoming influencers looking for organic growth.</p> <a class=“btn btn–primary type–uppercase pricing-cta text2” href=“https://app.upleap.com/register?plan=standard-usd-monthly”> <span class=“btn__text”> 10-day Free Trial </span> </a> <ul style=“list-style-image: url(img/checkmark.html)” class=“check-features”> <li><b>400+ Instagram Followers</b></li> <li>Follow/Unfollow Automation</li> <li>Real & Organic Growth</li> <li>Target by Account</li> <li>Target by Hashtag</li> <li>Suggested Targets by Industry</li> <li>Whitelist & Blacklist</li> <li>Auto-Whitelist</li> <li>Like after Follow</li> </ul> <ul style=“list-style-image: url(img/exmark.html)” class=“ex-features”> <li>Dedicated Account Manager</li> <li>Welcome DM Automation</li> <li>Story Liker & Viewer</li> <li>Filter by Gender</li> <li>Filter by Location</li> </ul> </div> <div class=“pricing-column column-2”> <p class=“most-popular-tag”>Most popular</p> <h2>Pro</h2> <p class=“text2 price”>$119</p> <p class=“pricing-info text2”>Billed monthly. Cancel anytime.</p> <p class=“pricing-description”>Level up your Instagram game with advanced features and a <b>Dedicated Account Manager</b>.</p> <a class=“btn btn–primary type–uppercase pricing-cta text2” href=“https://app.upleap.com/register?plan=pro-usd-monthly”> <span class=“btn__text”> 10-day Free Trial </span> </a> <ul style=“list-style-image: url(img/checkmark.html)” class=“check-features”> <li><b>1,000+ Instagram Followers</b></li> <li>Follow/Unfollow Automation</li> <li>Real & Organic Growth</li> <li>Target by Account</li> <li>Target by Hashtag</li> <li>Suggested Targets by Industry</li> <li>Whitelist & Blacklist</li> <li>Auto-Whitelist</li> <li>Like after Follow</li> <li>Dedicated Account Manager</li> <li>Welcome DM Automation</li> <li>Story Liker & Viewer</li> <li>Filter by Gender</li> <li>Filter by Location</li> </ul> </div> <div class=“pricing-column column-3”> <h2>Premium</h2> <p class=“text2 price”>$239</p> <p class=“pricing-info text2”>Billed monthly. Cancel anytime.</p> <p class=“pricing-description”>Supercharge your growth with Follower Bursts. Get everything from the Pro Plan + even more exposure!</p> <a class=“btn btn–primary type–uppercase pricing-cta text2” href=“https://app.upleap.com/register?plan=premium-usd-monthly”> <span class=“btn__text”> 10-day Free Trial </span> </a> <ul style=“list-style-image: url(img/checkmark.html)” class=“check-features”> <li><b>2,500+ Instagram Followers</b></li> <li>Follow/Unfollow Automation</li> <li>Real & Organic Growth</li> <li>Target by Account</li> <li>Target by Hashtag</li> <li>Suggested Targets by Industry</li> <li>Whitelist & Blacklist</li> <li>Auto-Whitelist</li> <li>Like after Follow</li> <li>Dedicated Account Manager</li> <li>Welcome DM Automation</li> <li>Story Liker & Viewer</li> <li>Filter by Gender</li> <li>Filter by Location</li> </ul> </div> </div> </section> and this @media screen and (max-width: 1024px) { .pricing-container { display: flex !important; overflow-x: auto !important; scroll-snap-type: x mandatory !important; -webkit-overflow-scrolling: touch !important; } .pricing-column { flex: 1 0 100% !important; min-width: 300px !important; scroll-snap-align: start !important; } I wanted the 3 columns to slide automatically back and forth each like 2 seconds
365a52d8595738f9354a782ac6a52474
{ "intermediate": 0.2777719497680664, "beginner": 0.3878774344921112, "expert": 0.3343506455421448 }
14,541
Pipe character vs ‘or’ in Python
5fdb46fbd419acbf0d4b3eba824a195b
{ "intermediate": 0.31712135672569275, "beginner": 0.2639150619506836, "expert": 0.41896361112594604 }
14,542
I used ths signal_generator code: def signal_generator(df): # Calculate EMA and MA lines df['EMA5'] = df['Close'].ewm(span=5, adjust=False).mean() df['EMA10'] = df['Close'].ewm(span=10, adjust=False).mean() df['EMA20'] = df['Close'].ewm(span=20, adjust=False).mean() df['EMA50'] = df['Close'].ewm(span=50, adjust=False).mean() df['EMA100'] = df['Close'].ewm(span=100, adjust=False).mean() df['EMA200'] = df['Close'].ewm(span=200, adjust=False).mean() df['MA10'] = df['Close'].rolling(window=10).mean() df['MA20'] = df['Close'].rolling(window=20).mean() df['MA50'] = df['Close'].rolling(window=50).mean() df['MA100'] = df['Close'].rolling(window=100).mean() # Extract necessary prices from df open_price = df.Open.iloc[-1] close_price = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Calculate the last candlestick last_candle = df.iloc[-1] current_price = df.Close.iloc[-1] # Initialize analysis variables ema_analysis = [] candle_analysis = [] # EMA strategy - buy signal if df['EMA5'].iloc[-1] > df['EMA10'].iloc[-1] > df['EMA20'].iloc[-1] > df['EMA50'].iloc[-1]: ema_analysis.append('buy') # EMA strategy - sell signal elif df['EMA5'].iloc[-1] < df['EMA10'].iloc[-1] < df['EMA20'].iloc[-1] < df['EMA50'].iloc[-1]: ema_analysis.append('sell') # Check for bullish candlestick pattern - buy signal open_price = df['Open'].iloc[-1] close_price = df['Close'].iloc[-1] previous_open = df['Open'].iloc[-2] previous_close = df['Close'].iloc[-2] if ( open_price < close_price and previous_open > previous_close and close_price > previous_open and open_price <= previous_close ): candle_analysis.append('buy') # Check for bearish candlestick pattern - sell signal elif ( open_price > close_price and previous_open < previous_close and close_price < previous_open and open_price >= previous_close ): candle_analysis.append('sell') # Determine final signal if 'buy' in ema_analysis and 'buy' in candle_analysis and df['Close'].iloc[-1] > df['EMA50'].iloc[-1]: final_signal = 'buy' elif 'sell' in ema_analysis and 'sell' in candle_analysis and df['Close'].iloc[-1] < df['EMA50'].iloc[-1]: final_signal = 'sell' else: final_signal = '' return final_signal But can you add in EMA analysis EMA 100 , 150 and 200 EMA lines please
072ee41aad22f09224f31227b09afc30
{ "intermediate": 0.3098260760307312, "beginner": 0.3309864103794098, "expert": 0.3591875433921814 }
14,543
generate a table with rows code, start date, end date, description, status, value, discount type
e3e6952b6b11cff51d9110790f3afd6c
{ "intermediate": 0.3832786977291107, "beginner": 0.22962382435798645, "expert": 0.3870975077152252 }
14,544
import pygame import random import requests import base64 from io import BytesIO # Define the screen dimensions SCREEN_WIDTH = 1500 SCREEN_HEIGHT = 800 # Define the colors BLACK = (0, 0, 0) # Define the artists and their monthly Spotify listeners artists = { "$NOT": {"listeners": 7781046}, "21 Savage": {"listeners": 60358167}, "9lokknine": {"listeners": 1680245}, } # Initialize the game pygame.init() # Define the font and font size for the artist names font = pygame.font.Font(None, 36) listeners_font = pygame.font.Font(None, 24) # Initialize the game window and caption screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Guess the Artist") # Create a clock object to control the frame rate clock = pygame.time.Clock() score = 0 # Function to fetch the artist image using the Spotify API def fetch_artist_image(artist, client_id, client_secret): # Base64 encode the client ID and secret client_credentials = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode() # Request an access token token_url = "https://accounts.spotify.com/api/token" headers = { "Authorization": f"Basic {client_credentials}" } data = { "grant_type": "client_credentials" } response = requests.post(token_url, headers=headers, data=data) access_token = response.json()["access_token"] # Search for the artist on Spotify search_url = f"https://api.spotify.com/v1/search?q={artist}&type=artist" headers = { "Authorization": f"Bearer {access_token}" } response = requests.get(search_url, headers=headers) data = response.json() # Get the first artist result artist_info = data["artists"]["items"][0] # Get the image URL of the artist image_url = artist_info["images"][0]["url"] # Download the image and return its contents image_data = requests.get(image_url).content return image_data # Function to check the user's guess def check_guess(artist1, artist2, guess): if guess == "1" and artists[artist1]["listeners"] > artists[artist2]["listeners"]: return True elif guess == "2" and artists[artist2]["listeners"] > artists[artist1]["listeners"]: return True else: return False # Game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Game logic correct_guess = False while not correct_guess: # Select two random artists first_artist, second_artist = random.sample(list(artists.keys()), 2) # Fetch the artist images client_id = '048322b8ea61411a826de68d0cb1c6d2' client_secret = '29f94d572c6240cf99fc3f13ce050503' first_artist_image_data = fetch_artist_image(first_artist, client_id, client_secret) second_artist_image_data = fetch_artist_image(second_artist, client_id, client_secret) # Load the image data using Pygame first_artist_image = pygame.image.load(BytesIO(first_artist_image_data)).convert() second_artist_image = pygame.image.load(BytesIO(second_artist_image_data)).convert() # Render the text surfaces for the artist names first_artist_text = font.render(f"1 - {first_artist.title()}", True, (255, 255, 255)) second_artist_text = font.render(f"2 - {second_artist.title()}", True, (255, 255, 255)) # Render the text surfaces for the listeners' count first_listeners_text = listeners_font.render(f"{artists[first_artist]['listeners']:,} listeners", True, (255, 255, 255)) second_listeners_text = listeners_font.render(f"{artists[second_artist]['listeners']:,} listeners", True, (255, 255, 255)) # Display the images screen.blit(first_artist_image, (0, 0)) screen.blit(second_artist_image, (SCREEN_WIDTH // 2, 0)) # Calculate the center position for the artist names first_x = (first_artist_image.get_width() - first_artist_text.get_width()) // 2 second_x = SCREEN_WIDTH // 2 + (second_artist_image.get_width() - second_artist_text.get_width()) // 2 # Display the artist names centered under the image screen.blit(first_artist_text, (first_x, first_artist_image.get_height() + 10)) screen.blit(second_artist_text, (second_x, second_artist_image.get_height() + 10)) # Calculate the center position for the listeners' count first_listeners_x = (first_artist_image.get_width() - first_listeners_text.get_width()) // 2 second_listeners_x = SCREEN_WIDTH // 2 + (second_artist_image.get_width() - second_listeners_text.get_width()) // 2 # Display the listeners' count centered under the image screen.blit(first_listeners_text, (first_listeners_x, first_artist_image.get_height() + 40)) screen.blit(second_listeners_text, (second_listeners_x, second_artist_image.get_height() + 40)) pygame.display.flip() # Prompt the player for their guess guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") running = False break elif guess_lower not in ['1', '2', first_artist.lower(), second_artist.lower()]: print("Invalid input. Please enter the name of one of the two artists or 'quit' to end the game.") elif check_guess(first_artist, second_artist, guess_lower): print(f"You guessed correctly! {first_artist.title()} had {artists[first_artist]['listeners']:,} monthly Spotify listeners and {second_artist.title()} has {artists[second_artist]['listeners']:,} monthly Spotify listeners.") correct_guess = True score += 1 else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {artists[first_artist]['listeners']:,} monthly Spotify listeners and {second_artist.title()} has {artists[second_artist]['listeners']:,} monthly Spotify listeners.\n") print(f"Your current score is {score}.") # Ask the player if they want to play again play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print(f"Your final score is {score}. Thanks for playing!") running = False clock.tick(60) # Quit the game pygame.quit() why are the listeners counts written under the image before the player makes a guess, this shouldt be the case correct it
02c712e7de4e4de87a3dca581bdebadb
{ "intermediate": 0.3900914788246155, "beginner": 0.5241514444351196, "expert": 0.0857570543885231 }
14,545
Kya Haal Hain
5b4b76b5c7357e374f3f7ca013d7fd30
{ "intermediate": 0.3345031142234802, "beginner": 0.319362610578537, "expert": 0.346134215593338 }
14,546
WITH limited_tasks AS ( SELECT * FROM tasks ORDER BY tasks.id ASC LIMIT 1200 ) SELECT limited_tasks.id, limited_tasks.task, limited_tasks.answer, limited_tasks.level, array_agg(DISTINCT tasks_topics.topics_id) AS topics_ids, array_agg(DISTINCT tasks_exams.exam_id) AS exams_id, array_agg(DISTINCT classes.name) AS class_name, authors.name as author_name FROM limited_tasks INNER JOIN tasks_topics ON limited_tasks.id = tasks_topics.task_id INNER JOIN tasks_authors ON limited_tasks.id = tasks_authors.tasks_id INNER JOIN authors ON authors.id = tasks_authors.authors_id INNER JOIN tasks_classes ON limited_tasks.id = tasks_classes.tasks_id INNER JOIN classes ON classes.id = tasks_classes.classes_id INNER JOIN tasks_exams ON limited_tasks.id = tasks_exams.task_id INNER JOIN exams ON tasks_exams.exam_id = exams.id GROUP BY limited_tasks.id, limited_tasks.task, authors.id,limited_tasks.answer, limited_tasks.level ORDER BY limited_tasks.id ASC Я верно понимаю, что если нет в tasks_exams.exam_id ни одного значения, тогда он получается, что он просто не покажет этой строчки,верно?
a7251d3c066b3967f451b7e8abb17947
{ "intermediate": 0.30847346782684326, "beginner": 0.3667358160018921, "expert": 0.3247906267642975 }
14,547
how to predict multiple values in ml?
929ba88bb9e9a22b5199d42d30e5f63f
{ "intermediate": 0.22865504026412964, "beginner": 0.13750842213630676, "expert": 0.6338365077972412 }
14,548
make me a table with values A B C and under A B C have them give the words that start with that letter
400e50ed616c1adb1577a247663659c3
{ "intermediate": 0.4022578299045563, "beginner": 0.25130495429039, "expert": 0.3464372456073761 }
14,549
This is a test prompt
8004483b2cdef4c33807a1709398f8a2
{ "intermediate": 0.32516375184059143, "beginner": 0.379716694355011, "expert": 0.2951195240020752 }
14,550
Go function: func ForkReader(r io.Reader,w1,w2 io.Writer) error {} so the output is split into two characters from STDİN as 3945 862 if input is 3896425
92e89566338e54322eeb671e9761bd3d
{ "intermediate": 0.3582787811756134, "beginner": 0.4210924506187439, "expert": 0.22062872350215912 }
14,551
Go function: func ForkReader(r io.Reader,w1,w2 io.Writer) error {} so the output is split into two characters from STDİN as 3945 862 if input is 3896425
274d7d022ca21d7b309f65182b64c0d1
{ "intermediate": 0.3582787811756134, "beginner": 0.4210924506187439, "expert": 0.22062872350215912 }
14,552
this is a code inside my reactjs component, is it correct? "const navigate = useNavigate(); const [dota, setDota] = useState(null); const handleSubmit = async (values) => { const { names, description, price, maxUsers, rateL, usersPerDay, gender } = values; const Task = { Name: names, Description: description, Price: price, MaxUsers: maxUsers, UsersPerDay: usersPerDay, Type: gender, RateLink: rateL }; try { const response = await axios.post('http://localhost:5041/api/admin', Task); setDota(response.data); if (dota.type === "img") { navigate(`/UploadTask/${dota.id}`); } message.success('تم إنشاء حسابك! أرسلنا رسالة تأكيد على بريدك'); exitLoading(1); } catch (error) { console.error('There was an error!', error); message.error('حدث خطأ يرجى المحاولة وقت اخر'); exitLoading(1); } };"
fd9edff45f95fff3bd3e980114074d7c
{ "intermediate": 0.5810638070106506, "beginner": 0.291730672121048, "expert": 0.1272054761648178 }
14,553
this is good but add login and forget password too and also take email too and also create better design: {% extends "legal_app/base.html" %} {% block title %}Signup{% endblock %} {% block content %} <!-- Add Bootstrap CDN links --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <!-- Add Font Awesome CDN link --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <div class="container"> <!-- Use a card for the signup form --> <div class="card mt-4 mb-4"> <div class="card-body"> <h2 class="card-title">Signup</h2> <form method="post"> {% csrf_token %} <div class="form-group"> <label for="id_username">Username:</label> {{ form.username }} {% if form.username.errors %} <div class="text-danger">{{ form.username.errors }}</div> {% endif %} </div> <div class="form-group"> <label for="id_password1">Password:</label> {{ form.password1 }} {% if form.password1.errors %} <div class="text-danger">{{ form.password1.errors }}</div> {% endif %} </div> <div class="form-group"> <label for="id_password2">Confirm Password:</label> {{ form.password2 }} {% if form.password2.errors %} <div class="text-danger">{{ form.password2.errors }}</div> {% endif %} </div> <button type="submit" class="btn btn-primary">Signup</button> </form> </div> </body> </html> {% endblock %}
37e6373a7982fa90c28f3d42f46ae47d
{ "intermediate": 0.4327486455440521, "beginner": 0.35673967003822327, "expert": 0.2105116993188858 }
14,554
c++ unsigned int max value
fec61cd35cd6e54083d1cb2e5203c1c1
{ "intermediate": 0.32193484902381897, "beginner": 0.3575284481048584, "expert": 0.320536732673645 }
14,555
TypeError: 'Row' object does not support item assignment
298b900727fc2f85e102dbee6ad3c00c
{ "intermediate": 0.4715729355812073, "beginner": 0.27536389231681824, "expert": 0.2530631721019745 }
14,556
create only the letter "t". The letter is part of the Term Act ans it shape should be either a balance or justicia
c0180664720387197093c3313b00edab
{ "intermediate": 0.24226929247379303, "beginner": 0.2257871776819229, "expert": 0.5319435596466064 }
14,557
WITH RECURSIVE ParentPaths AS ( SELECT Id, array[Id] AS ParentPath FROM topics WHERE parent = 0 UNION ALL SELECT t.Id, p.ParentPath || t.Id FROM topics t JOIN ParentPaths p ON p.Id = t.parent ) SELECT * from ParentPaths Я хочу,чтобы рекурсивный запрос был не из topics, а из под запроса. А В этом подзапросе должен быть topics с id равными 134, 200, 400
83678aca8e662f7555707f40d7a05101
{ "intermediate": 0.3418232202529907, "beginner": 0.30729466676712036, "expert": 0.35088205337524414 }
14,558
i have a table in sql with a column 'type' with two possible values: console and vrops. the table also has a column ctime that shows a timestamp postgres datatype. give me a query that returns the most recent record by ctime for each column type value
ba86142c5504c2d9ae25708fa3200031
{ "intermediate": 0.43940526247024536, "beginner": 0.25023433566093445, "expert": 0.3103604316711426 }
14,559
c++ unordered map contains key
4a3d0174d085a498afe0af1920df10f8
{ "intermediate": 0.3207010328769684, "beginner": 0.3568631410598755, "expert": 0.32243579626083374 }
14,560
"import os import zipfile import glob import smtplib from email.message import EmailMessage import xml.etree.ElementTree as ET import logging import datetime import shutil logging.basicConfig(filename='status_log.txt', level=logging.INFO) fsd_list = [ ["aaa", "aaa@gmail.com"], ["bbb", "bbb@email.com"], ["ccc", "ccc@email.com"], ["ddd", "ddd@email.com"], ["testing fsd", "kelvin.fsd.testing@gmail.com"] ] # auto create the unzip folder def move_zip_files(): os.makedirs('./unzip', exist_ok=True) filenames = os.listdir('.') for filename in filenames: if filename.endswith('.zip'): if os.path.exists(f"./unzip/{filename}"): logging.info( f'{datetime.datetime.now()}: The {filename} already exists in ./unzip, so skipping.') else: shutil.move(filename, './unzip') logging.info( f'{datetime.datetime.now()}: The {filename} been moved into ./unzip') unzip_all_files() # Function to unzip all files in ./unzip folder def unzip_all_files(): os.makedirs('./unzipped', exist_ok=True) zip_files = glob.glob('./unzip/*.zip') for zip_file in zip_files: folder_name = os.path.splitext(os.path.basename(zip_file))[0] os.makedirs(f'./unzipped/{folder_name}', exist_ok=True) with zipfile.ZipFile(zip_file, 'r') as zfile: zfile.extractall(f'./unzipped/{folder_name}') logging.info(f'{datetime.datetime.now()}: {zip_file} unzipped') os.remove(zip_file) if not zip_files: logging.error( f'{datetime.datetime.now()}: No ZIP files found in "./unzip" directory') return # Function to find FSD in an XML file def find_fsd(xml_file): tree = ET.parse(xml_file) root = tree.getroot() fsd_element = root.find('.//unit') if fsd_element is not None: return fsd_element.text return None # Function to send email with a PDF file attached def send_email(fsd_email, pdf_file): email_address = 'kelvin.chu1122@gmail.com' email_app_password = 'brwgearofnryfinh' msg = EmailMessage() msg['Subject'] = 'FSD PDF file' msg['From'] = email_address msg['To'] = fsd_email msg.set_content('Please find the PDF file attached.') with open(pdf_file, 'rb') as pdf: msg.add_attachment(pdf.read(), maintype='application', subtype='pdf', filename=pdf_file) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(email_address, email_app_password) smtp.send_message(msg) logging.info( f'{datetime.datetime.now()}: {pdf_file} sent to {fsd_email}') def main(): move_zip_files() unzipped_folders = os.listdir('./unzipped') for folder in unzipped_folders: xml_files = glob.glob( f'./unzipped/{folder}/{folder}/convertedData/*.xml') if not xml_files: logging.error( f'{datetime.datetime.now()}: No XML files found in {folder}. Skipping.') continue xml_file = xml_files[0] fsd_in_xml = find_fsd(xml_file) if fsd_in_xml: for fsd, fsd_email in fsd_list: # If FSD in the XML file matches the one in the list, send the email with the PDF attached if fsd == fsd_in_xml: pdf_files = glob.glob( f'./unzipped/{folder}/{folder}/convertedData/*.pdf') if not pdf_files: status = 'PDF not found in folder' logging.error( f'{datetime.datetime.now()}: {folder}: {status}') break pdf_file = pdf_files[0] send_email(fsd_email, pdf_file) status = 'Success, Email sent' break else: status = 'FSD unit not found in list' else: status = 'FSD not found in XML' logging.info(f'{datetime.datetime.now()}: {folder}: {status}') if __name__ == "__main__": main() " add a function in this code that after send the all the email then move all folder from unzipped into "sent" folder
7227eac7ed0e6881648b1a5f82e486ab
{ "intermediate": 0.3595142960548401, "beginner": 0.4503977298736572, "expert": 0.1900879591703415 }
14,561
i would like to provided you with a complex character desciptions i would like like you to break it down into tags for an ai img genartor so all tags should only those that can be visual represented could you do that keep in mind i would like this img generator to create as close of a like to the character who details i provide you with an i would like it to be hi resolution quality and photo realistic can you do that for me the tags show be inclusive of her phyiscial appeance and attire while also highlighing the same details that are empisised in the desciption it however need to be no greater than 75 token lenght is that possible
c9e07711a1341cb95a189f0196aa5dd6
{ "intermediate": 0.5203765034675598, "beginner": 0.1264369636774063, "expert": 0.35318660736083984 }
14,562
in power bi how do I count the total of a column based on the number of communities in the previous column without duplicating. example: 1 community with four trades has a total of 499 lots but each row represents a trade
87745fc7b64b96cae0006aa0ddae9947
{ "intermediate": 0.32977962493896484, "beginner": 0.20053845643997192, "expert": 0.46968191862106323 }
14,563
How to make an Html email signature with dimensions 388px x 309px
28b49ab031ab461061b64b4f6d18a120
{ "intermediate": 0.3327087461948395, "beginner": 0.28509724140167236, "expert": 0.38219398260116577 }
14,564
Write a python script that sums the first N numbers in the fibonacci sequence
be610eb7bf6a73737d989a756166071e
{ "intermediate": 0.25934934616088867, "beginner": 0.20296528935432434, "expert": 0.5376853942871094 }
14,565
how to start a timer in linux?
b9906fd5bac3ddd1a7edb1f33e9ee2e0
{ "intermediate": 0.3406844437122345, "beginner": 0.23863741755485535, "expert": 0.42067810893058777 }
14,566
Act as an bootstrap 5 export
cc532b326db11c88d9a8a24d6b083838
{ "intermediate": 0.3821491599082947, "beginner": 0.2485610395669937, "expert": 0.3692898154258728 }
14,567
c++ character equality
869c03ae42ef641a00319edcf164bb68
{ "intermediate": 0.3213341534137726, "beginner": 0.32877177000045776, "expert": 0.34989404678344727 }
14,568
write Javacode to get data from MySQL database and insert it to table in Servlet file
00af34dd7d2953086a748142f7091094
{ "intermediate": 0.7595428824424744, "beginner": 0.09359860420227051, "expert": 0.14685851335525513 }
14,569
implement div_u64() in freertos
7db940e885d47ddc349e6fc55452277e
{ "intermediate": 0.32390934228897095, "beginner": 0.21820101141929626, "expert": 0.4578896164894104 }
14,570
how is div_u64() implemented in linux
2e60b9b4cf896590e375a6a2029720e3
{ "intermediate": 0.38906747102737427, "beginner": 0.18696434795856476, "expert": 0.42396825551986694 }