row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
8,532
this._router.get( "/quotation", verifyRoles([rolesStr.SUPERVISOR, rolesStr["BRANCH STATISTICIAN"]]), this._controller.getQuotations ); the above route handler is used by both supervisor and branch statistician roles to fetch quotations. And the below code is the function used to fetch quotations to the route async getQuotations(req: Request, res: Response, next: NextFunction) { try { const query: any = req.query; const regionCodeOrCodes = await getRegionCodeOrCodes(req.user!); const regionalStatusFilter = getQuestionnaireRegionalStatusFilter(regionCodeOrCodes); const questionnaire = await prisma.questionnaire.findFirst({ orderBy: [{ startDate: "desc" }], where: { designatedRole: rolesNum["DATA COLLECTOR"], approved: true, disabled: false, endDate: { gte: addDays(new Date(), -5), }, startDate: { lte: new Date(), }, isDraft: false, }, include: { questionnaireItems: { where: { disabled: false, }, include: { quotations: { where: { status: { not: QuotationStatus.SUPERVISOR_APPROVED, }, }, }, item: { include: { translation: true, itemMeasurements: true, }, }, }, }, questionnaireRegionStatus: { where: regionalStatusFilter, }, }, }); const datacollectors = await prisma.user.findMany({ where: req.user?.role === rolesNum.SUPERVISOR ? { supervisorId: req.user?.id, } : { marketplace: { branchCode: req.user?.branchCode } }, }); if ( req.user?.role === rolesNum.SUPERVISOR && (!datacollectors || datacollectors.length < 1) ) { return res .status(httpStatusCodes.NOT_FOUND) .json( new ResponseJSON( "Supervisor is not assigned any data collectors", true, httpStatusCodes.NOT_FOUND ) ); } if (!questionnaire) { return res .status(httpStatusCodes.NOT_FOUND) .json( new ResponseJSON( "Not Questionnaires active right now", true, httpStatusCodes.NOT_FOUND ) ); } // if ( // req.user?.role === rolesNum["BRANCH STATISTICIAN"] || // questionnaire.questionnaireRegionStatus === QuotationStatus.SUPERVISOR_APPROVED // ) { // return res // .status(httpStatusCodes.UNAUTHORIZED) // .json( // new ResponseJSON( // "This user is not allowed to update this quotation", // true, // httpStatusCodes.UNAUTHORIZED // ) // ); // } const result = await prisma.quotation.findMany({ where: { questionnaireId: questionnaire?.id, collectorId: { in: datacollectors.map((el) => el.id), }, ...query, }, include: { collector: { select: { fullName: true, id: true, marketplaceCode: true, }, }, quotes: { include: { quoteComments: true, }, }, unfoundQuotes: { include: { quoteComments: true, }, }, }, }); return res .status(httpStatusCodes.OK) .json(new ResponseJSON("Success", false, httpStatusCodes.OK, result)); } catch (error: any) { console.log("Error --- ", error); next( apiErrorHandler( error, req, errorMessages.INTERNAL_SERVER, httpStatusCodes.INTERNAL_SERVER ) ); } } And the schemas ascociated with the above queries are enum QuotationStatus { PENDING SUPERVISOR_APPROVED STATISTICIAN_APPROVED BRANCH_APPROVED REJECTED } model Quotation { id Int @id @default(autoincrement()) status QuotationStatus @default(PENDING) creationStatus QuotationCreationStatus @default(COLLECTED) approverId Int? approver User? @relation("approver", fields: [approverId], references: [id]) marketplaceCode Int marketplace Marketplace @relation(fields: [marketplaceCode], references: [code]) collectorId Int collector User @relation("collector", fields: [collectorId], references: [id]) questionnaireId Int itemCode Int questionnaireItem QuestionnaireItem @relation(fields: [questionnaireId, itemCode], references: [questionnaireId, itemCode]) branchApproverId Int? branchApprover User? @relation("branchApprover", fields: [branchApproverId], references: [id]) quotes Quote[] unfoundQuotes UnfoundQuote[] cleanedQuotes CleanedQuote[] interpolatedQuotes InterpolatedQuote[] // quoteMean QuotesMean? updatedAt DateTime @updatedAt createdAt DateTime @default(now()) @@unique([questionnaireId, itemCode, marketplaceCode]) } model QuestionnaireItem { minPrice Float maxPrice Float itemCode Int item Item @relation(fields: [itemCode], references: [code]) questionnaireId Int questionnaire Questionnaire @relation(fields: [questionnaireId], references: [id], onDelete: Cascade) disabled Boolean @default(false) quotations Quotation[] updatedAt DateTime @updatedAt createdAt DateTime @default(now()) @@id([questionnaireId, itemCode]) } based on all these informations update the getQuotaions function to fetch only quotaitons that have been SUPERVISOR_APPROVED by supervisor for branch statistician role
9b6f43cd3c5693a4cc5305835a9af163
{ "intermediate": 0.40998104214668274, "beginner": 0.4292028546333313, "expert": 0.16081617772579193 }
8,533
Create a clickable region from 2d map in godot
e61020f6cd2a3d795e4a41cddda575e6
{ "intermediate": 0.35981088876724243, "beginner": 0.23718248307704926, "expert": 0.4030066430568695 }
8,534
python3 cloudflare_ddns.py Traceback (most recent call last): File "/home/rootcandy/scripts/ddns/cloudflare_ddns.py", line 11, in <module> from cloudflare import CloudFlare ModuleNotFoundError: No module named 'cloudflare'
61564c75c1cbc9fb2d1662b37656c987
{ "intermediate": 0.49065089225769043, "beginner": 0.31079983711242676, "expert": 0.1985493153333664 }
8,535
I have the highest temperature of 71 years ago for every year, how to forecast this value for 38 years later. the best and fastest way.
03cee9120bb6d4188e1341c65724e52e
{ "intermediate": 0.35576337575912476, "beginner": 0.2915157377719879, "expert": 0.3527209162712097 }
8,536
this is an api to connect and use some of wolf.live functions: “https://github.com/calico-crusade/WolfLive.Api”, How can i use this api to send messages in a specific group given i already have the group ID?
b8c6deec7f8299b3f8fd8d775468e64b
{ "intermediate": 0.8094666004180908, "beginner": 0.10099443793296814, "expert": 0.08953899890184402 }
8,537
pine script code of strategy with high win rate
89bda2709fe09bf4feecfdc6f7325339
{ "intermediate": 0.2455974668264389, "beginner": 0.4118078052997589, "expert": 0.3425946831703186 }
8,538
what is html tag for list
83908eb5fc8d983dece05b1970927d97
{ "intermediate": 0.35625696182250977, "beginner": 0.41919800639152527, "expert": 0.22454498708248138 }
8,539
I want to write me VBA code for a PowerPoint presentation about the history of AI. You are to fill in all the text with your own knowledge, no placeholders. I need 5 slides
e6f03cfd5b238e9bc6ef83e81b03aa4a
{ "intermediate": 0.18377692997455597, "beginner": 0.29449230432510376, "expert": 0.5217308402061462 }
8,540
i have a problem with my kotlin app. Error message: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.edu.put.inf151910/com.edu.put.inf151910.MainActivity}; have you declared this activity in your AndroidManifest.xml, or does your intent not match its declared <intent-filter>? My code: lifecycleScope.launch { val userXMLgame = "https://www.boardgamegeek.com/xmlapi2/collection?username=" + username + "&stats=1&excludesubtype=boardgameexpansion&own=1" val userXMLaddon = "https://www.boardgamegeek.com/xmlapi2/collection?username=" + username + "&stats=1&subtype=boardgameexpansion&own=1" parseAndAddGames(userXMLgame, applicationContext, "gamelist.db") parseAndAddGames(userXMLaddon, applicationContext, "gamelist.db", true) }
519494b1e68d564701d46c59344998a4
{ "intermediate": 0.4978364109992981, "beginner": 0.3428412079811096, "expert": 0.1593223214149475 }
8,541
this error is given by matlab "Unrecognized function or variable 'log_lik'. "
e75268a1925194785e132da6674d48db
{ "intermediate": 0.3090932071208954, "beginner": 0.354369580745697, "expert": 0.3365371823310852 }
8,542
create Gantt chart: Document Sets QCTO Key Docs 1. A Strategic Plan Doc A Strategic Doc: The Strategic Doc must provide an Overview of the qualification, the roll out of the learning program with all the components as prescribed. 2. Programme Strategy Description: The Curriculum Guide (Programme Strategy) serves as a NQF alignment reference that demonstrates the alignment of the Training programme’s outcomes to that of the Qualifications. Consisting of learning outcomes, assessment strategies and alignment references; this document forms a basis of demonstrating the NQF alignment of the Training Programme. Design: The Curriculum Guide follows a systematical design approach to effectively meet the NQF Accreditation Body’s requirements. By utilizing a user-friendly design and through the provision of sufficient alignment information, you are able to demonstrate compliance and alignment towards the Qualification being addressed by the Training programme.  Features: a) Key Elements and Outline b) Alignment Strategy c) Programme Objectives d) Assessment Strategy and Reference e) Delivery Strategy f) Learning Outcomes g) Learning Material Alignment h) Resource requirements and delivery methods 3. Curriculum Alignment Matrix Description and Design Description: The Alignment Matrix serves as a NQF alignment reference that demonstrates the alignment of the Training programme’s outcomes to that of the Unit Standard. Consisting of learning outcomes, assessment strategies and alignment references; this document forms a basis of demonstrating the NQF alignment of the Training Programme. Design: The Alignment Matrix follows a systematical design approach to effectively meet the NQF Accreditation Body’s requirements. By utilizing a user-friendly design and through the provision of sufficient alignment information, you are able to demonstrate compliance and alignment towards the Unit Standard being addressed by the Training programme. Features: a) Clustering Information b) Notional Hour Breakdown c) Programme Objectives d) Unit Standard Information e) Learning Outcomes f) Learning Material Alignment g) Resource requirements and delivery methods h) Assessment Strategy and Reference 4. The Learning Programme Description of a Learning Programme: A Learning Programme is a structured educational offering designed to help learners acquire specific knowledge, skills, and competencies in a particular subject area. Design Issues: Learning Outcomes, Content Sequencing, Assessment Methods, Learning Resources, Learning Activities, High-Level Outline: 1.    Introduction 2.    Learning Outcomes 3.    Program Structure 4.    Assessment and Evaluation 5.    Learning Resources 6.    Program Policies and Procedures 7.    Appendices 5. Learner Guide/Manual  Text Book, covers the information relevant to qualification criteria and assessment aspects been covered. Social Security Law Intermediate Social Security Law Advance Business Administration Intermediate Business Administration Advance Team Leadership Supervision and Management Practical Module Work Experience 6. Facilitators Guide or manul Facilitators Guide/manual provides an overview of how the learning program should be presented. Seee relevant sheet for details Social Security Law Intermediate Social Security Law Advance Business Administration Intermediate Business Administration Advance Team Leadership Supervision and Management Practical Module Work Experience 7. Assessors Guide -  Description: The Assessment Guide serves as a tool for the Assessor to effectively achieve the objectives of the Formative and Summative assessments included in the Training Programme. Consisting of effective guidance towards the assessment approach, methodology and strategy that should be followed to meet the assessment outcomes; this document forms the basis of the guidance required to effectively implement the outcomes-based assessments.  Design: Each Assessment Guide follows a systematical design approach to effectively meet the NQF and outcomes-based assessment standards. By utilizing a user-friendly design and through the provision of sufficient guidance and instructions you are able to complete the assessments to effectively determine the level of competency of the candidate based on the outcomes of the training programme. Features: a) Content Index and Alignment Reference b) Assessment Plan and Appeals Procedures c) Assessment Preparation Checklist d) Assessment Strategy and Process e) Evidence Grid and Memorandum f) Formative Assessment Guidance g) Summative Knowledge Assessment Guidance h) Summative Practical Assessment Guidance i) Workplace Assignment Guidance j) Personal Narrative and Witness Testimonials k) Logbook l) Feedback, Declaration, Evaluation and Review 8. Moderators Guide -  Description: The Moderator Guide Template serves as a tool for the Moderator to customize in order to effectively moderate the Assessments conducted by the Assessor in the Training Programme. Consisting of effective templates and guidance towards the moderation approach, methodology & strategy followed to meet the outcomes; this document forms the basis of the guidance required to effectively moderate the assessments conducted. Design: Each Moderator Guide follows a systematical design approach to effectively meet the NQF Accreditation Body’s requirements. By utilizing a user-friendly design and through the provision of sufficient guidance and instructions you are able to complete the moderation of assessments based on the outcomes of the training programme. Features: a) Content Index and Alignment Reference b) Moderator’s Instructions c) Instructions and Memorandum d) Assessment Strategy e) Assessment Process f) Moderation Report g) Moderation Recording Tool h) Feedback and Judgement Record 9. Learner Induction Guide Description: The learner induction guide serves as an induction tool used to effectively introduce the candidate to the NQF learning approach, design and methods widely used in the Training programmes. Consisting of sufficient instructions, explanations and guidance; this document forms a basis of knowledge and understanding that the candidate requires to complete NQF aligned Training and Assessment processes. Design: The Learner induction guide follows a systematical design approach to effectively meet the candidate’s needs and NQF Accreditation Body’s requirements. By utilizing a user-friendly design and through the provision of sufficient guidance and instructions, the learner is able to effective understand and complete the processes involved to achieve the Training outcomes. Features: a) Learner Workplace Orientation b) Introduction to the National Qualifications Framework c) Rights & Responsibilities and Agreement of parties d) Appeals Procedures & Appeals Form e) Workplace Evaluation and Shift Roster f) Practical Learning Hints g) Disciplinary Procedures h) Certification and Assessment i) Principles of Assessment j) Moderation, Assessment and Feedback k) Breakdown of Qualification l) Learner Declaration of understanding 10. Portfolio of Evidence Guide Description: The Portfolio of Evidence Guide serves as a instructional tool and guide that explains the Assessment types, methods and requirements used for compiling the Portfolio of Evidence. Consisting of clear guidance and explanations, this guide aims to familiarise the learner with the process to follow to build their Portfolio of Evidence.   Design: The Portfolio of Evidence Guide follows a systematical design approach to effectively meet the NQF Accreditation Body’s requirements. By utilizing a user-friendly design and through the provision of sufficient instructional information, you are able to guide the learner into the correct process for collecting and compiling the evidence needed for their Portfolio of Evidence. Features: a) Introduction b) Assessment Types, Methods and Requirements c) Portfolio Building Process d) Assessment Process and Procedure e) Assistance and Support 11. Learner Appeal Policy Description: The Learner Appeal Policy is a set of guidelines and procedures that outline the process for learners to address concerns, disputes, or grievances related to their learning experience or assessment outcomes. Design Issues: Accessibility, Fairness and Impartiality, Confidentiality, Timeliness, Support and Guidance 1.        Introduction 2.      Grounds for Appeal 3.      Appeal Process 4.      Review and Decision 5.      Appeal Outcome 6.      Confidentiality and Privacy 7.       Support and Guidance 8.      Monitoring and Review 12. The Quality Assurance Strategy/Plan/Document Description: The Quality Assurance Strategy/Plan/Document is a comprehensive framework that outlines the organization's approach to ensuring the quality and effectiveness of its learning programs and assessment processes. It serves as a roadmap for implementing quality assurance practices that align with industry standards, regulatory requirements, and the organization's specific goals and objectives Framework Quality Standards, Stakeholder Engagement, Assessment Practices, Continuous Improvement Engagement, Continuous Professional Development, Documentation and Reporting, Review and Improvement 13. Learner management System Learning Management System is a platform that provides the framework to. handle all aspects of the learning process, registration of  learners.  You can used the one as indicated.  learning management system: We have a total interim solution. For that, I will offer a shareholding with a company that is established. Here is the url. https://forge.myvcampus.com/ You should signed an MOU with the myvcampus  to manage the learners information.
55493740c71abea412ff9d689158a6fe
{ "intermediate": 0.3443736433982849, "beginner": 0.3275601267814636, "expert": 0.3280662000179291 }
8,543
My raspberry pi .profile file is configured as such # ~/.profile: executed by the command interpreter for login shells. # This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login # exists. # see /usr/share/doc/bash/examples/startup-files for examples. # the files are located in the bash-doc package. # the default umask is set in /etc/profile; for setting the umask # for ssh logins, install and configure the libpam-umask package. #umask 022 # if running bash if [ -n "$BASH_VERSION" ]; then # include .bashrc if it exists if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc" fi fi # set PATH so it includes user's private bin if it exists if [ -d "$HOME/bin" ] ; then PATH="$HOME/bin:$PATH" fi # set PATH so it includes user's private bin if it exists if [ -d "$HOME/.local/bin" ] ; then PATH="$HOME/.local/bin:$PATH" fi export PYTHONPATH="$PYTHONPATH:/home/rootcandy/.local/lib/python3.9/site-packages/" export PATH="$PATH:/home/rootcandy/.local/bin" where cloudflare folder is stored /home/rootcandy/.local/lib/python3.9/site-packages Is this correct?
d505e93d6844d26e3f87dc9004d1f967
{ "intermediate": 0.3580261170864105, "beginner": 0.3727295398712158, "expert": 0.26924431324005127 }
8,544
استراتژی های مختلف در تریدینگ ویو را بررسی کن و بهترین استراتژِی را بر اساس وین ریت را معرفی ک
391b75cd48a740ed71bdc69b8a1b314c
{ "intermediate": 0.28204110264778137, "beginner": 0.31901055574417114, "expert": 0.3989483416080475 }
8,545
I have my google account's API_Key, does that count as the token for loggin in? if not how can i get it to log in with my C# App?
c5670b0e1113eb87048955b2dcf3dade
{ "intermediate": 0.7010233402252197, "beginner": 0.12438467144966125, "expert": 0.17459197342395782 }
8,546
Write code that scrapes all of https://www.japaneselawtranslation.go.jp for .pdf files and downloads them. It should recursively search the entire site and all directories.
1e49d740d816cef0203537b157ecf7a3
{ "intermediate": 0.29245373606681824, "beginner": 0.2843055725097656, "expert": 0.4232407212257385 }
8,547
من هو تامر حسنى
f36351267108383f1f1f48cb248ad8ad
{ "intermediate": 0.3165590167045593, "beginner": 0.3184189796447754, "expert": 0.3650220036506653 }
8,548
"clear all; close all; clc; %% First, import the data into MATLAB: load Month_data\Data_Temp.mat % Load the data load Month_data\Data_Temp.mat Y = Data; % Define candidate models p = 0:3; % Order of AR (AutoRegressive) process d = 0:1; % Degree of differencing q = 0:3; % Order of MA (Moving Average) process models = cell(length(p)*length(d)*length(q), 1); count = 0; for ii = 1:length(p) for jj = 1:length(d) for kk = 1:length(q) count = count + 1; models{count} = arima(p(ii), d(jj), q(kk)); end end end % Estimate each model and determine its AIC value aic = zeros(length(models), 1); for ii = 1:length(models) estmodel = estimate(models{ii}, Y); [Y_Forecast,~,Y_Forecast_Variance] = forecast(estmodel, length(Y), 'Y0', Y); logL = sum(log(normpdf(Y, Y_Forecast, sqrt(Y_Forecast_Variance)))); % Compute log-likelihood nParams = numel(estmodel.AR) + numel(estmodel.MA) + 1; % Compute number of model parameters nObs = length(Y); % Compute number of observations aic(ii) = ((-2*(logL))/nObs) + ((2*nParams)/nObs) + log(2*pi); % Compute AIC end % Find the model with the lowest AIC value [minAIC,index] = min(aic); bestModel = models{index}; % Forecast horizon = 38; Y_Last = Y(end); Y_Forecast = forecast(bestModel, horizon, 'Name', 'Y0', 'Value', Y_Last); % Plot the forecast figure; plot(Y); hold on; plot(length(Y)+1:length(Y)+horizon, Y_Forecast, 'r–'); xlabel('Year'); ylabel('Average Temperature ©'); legend('Historical Data', 'ARIMA Forecast', 'Location', 'best'); title('ARIMA Forecast for Temperature Data');" this code is giving me this error "Error using NEW 'Name' is not a recognized parameter. For a list of valid name-value pair arguments, see the documentation for this function.""
02e3665fa8c741525a4418a6de5da67a
{ "intermediate": 0.4012323319911957, "beginner": 0.421252965927124, "expert": 0.17751474678516388 }
8,549
Перепиши код на С++ import time import random import math A = 907898232 B = 317181867 def elliptic_curve(x, y, p): return (y ** 2) % p == (x ** 3 + (A % p) * x + (B % p)) % p def print_curve(p): print(f"y^2 = x^3 + {A % p} * x + {B % p} [p = {p}]") def euclidean_algo(a, b): s, old_s = 0, 1 t, old_t = 1, 0 r, old_r = b, a while r != 0: quotient = old_r // r old_r, r = r, old_r - quotient * r old_s, s = s, old_s - quotient * s old_t, t = t, old_t - quotient * t return old_r, old_s, old_t def inverse(n, p): gcd, x, y = euclidean_algo(n, p) assert (n * x + p * y) % p == gcd if gcd != 1: return -1 else: return x % p def add_points(p1, p2, p): if p1 == (0, 0): return p2 elif p2 == (0, 0): return p1 elif p1[0] == p2[0] and p1[1] != p2[1]: return (0, 0) if p1 == p2: s = ((3 * p1[0] ** 2 + (A % p)) * inverse(2 * p1[1], p)) % p else: s = ((p1[1] - p2[1]) * inverse(p1[0] - p2[0], p)) % p x = (s ** 2 - 2 * p1[0]) % p y = (p1[1] + s * (x - p1[0])) % p return (x, -y % p) def order_point(point, p): i = 1 check = add_points(point, point, p) while check != (0, 0): check = add_points(check, point, p) i += 1 return i def is_prime_number(number): if number < 2: return False if number == 2: return True if number % 2 == 0: return False for i in range(3, int(math.sqrt(number)) + 1, 2): if number % i == 0: return False return True def get_next_prime_number(start): number = start while not is_prime_number(number): number += 1 return number def find_opt_p(p, time_limit): last_p = p i = 0 while True: i += 1 print(f'Iteration {i}:') print_curve(p) points = [] start = time.time() cnt = 0 for x in range(0, p): for y in range(0, p): cnt += 1 if elliptic_curve(x, y, p): points.append((x, y)) if cnt % 1000 == 0: cnt = 0 if time.time() - start > time_limit: break if time.time() - start > time_limit: print('------------Selection is over------------') print(f'[RESULT]: y^2 = x^3 + {A % last_p} * x + {B % last_p} [p = {last_p}]') break cnt_points = len(points) print("Order curve = {0}".format(cnt_points)) point = random.choice(points) print("Order point {0}: {1}".format(point, order_point(point, p))) print("Time: {} sec.".format(time.time() - start)) print("-----------------------------------------") last_p = p p = get_next_prime_number(p + 4500) if __name__ == '__main__': start_p = 191 time_lim = 600 find_opt_p(start_p, time_lim)
be873b248364ef53dbc5c0b94d9332d8
{ "intermediate": 0.3152228593826294, "beginner": 0.31333261728286743, "expert": 0.37144458293914795 }
8,550
it still gives me an error utilizing google collab, collab: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-6e7a8f6fa62e> in <cell line: 13>() 12 # Remove the column from the CSV file 13 for row in data: ---> 14 del row[column_to_remove] 15 16 # Write the new CSV file to your Google Drive TypeError: list indices must be integers or slices, not str. for the code i used is : :::::: ---->. import csv # Read the CSV file from your Google Drive csv_file_path = '/content/BTC-USD.csv' with open(csv_file_path, 'r') as csv_file: reader = csv.reader(csv_file) data = list(reader) # Find the column you want to remove column_to_remove = '4' # Remove the column from the CSV file for row in data: del row[column_to_remove] # Write the new CSV file to your Google Drive with open(csv_file_path, 'w') as csv_file: writer = csv.writer(csv_file) writer.writerows(data)
5f4b64bb9aee487940399aa957a56381
{ "intermediate": 0.47735947370529175, "beginner": 0.3776961863040924, "expert": 0.14494436979293823 }
8,551
# Возращает адреса созданных токенов в указанном интревале блоков!!! import asyncio import requests import aiohttp bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' async def get_external_transactions(block_number): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return [] if data['result'] is None or not isinstance(data['result'], dict): print(f"Error: Cannot find the block") return [] return data['result']['transactions'] async def get_contract_address(tx_hash): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return None if data['result'] is None: return None return data['result']['contractAddress'] async def get_contract_name(contract_address): async with aiohttp.ClientSession() as session: method_signature = '0x06fdde03' url = f'https://api.bscscan.com/api?module=proxy&action=eth_call&to={contract_address}&data={method_signature}&tag=latest&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return None if not data.get('result') or data['result'][:2] == '0x': return None return bytes.fromhex(data['result'][2:]).decode('utf-8') async def display_transactions(block_start, block_end): async def process_block(block_number_int): block_number = hex(block_number_int) transactions = await get_external_transactions(block_number) if not transactions: print(f'No transactions found in block {block_number_int}') else: print(f'Transactions in block {block_number_int}:') for tx in transactions: if tx['to'] is None: contract_address = await get_contract_address(tx['hash']) contract_name = await get_contract_name(contract_address) print(f'New contract creation: Contract Address: {contract_address} - Contract Name: {contract_name}') print("\n") # Print an empty line between blocks tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)] await asyncio.gather(*tasks) async def main(): block_start = 28524001 # Replace with your desired starting block number block_end = 28525888 # Replace with your desired ending block number await display_transactions(block_start, block_end) asyncio.run(main()) Above is the code. The answer is below No transactions found in block 28525700 Error: Cannot find the block No transactions found in block 28525360 Error: Cannot find the block No transactions found in block 28525244 Transactions in block 28524587: Error: Cannot find the block No transactions found in block 28525206 Error: Cannot find the block No transactions found in block 28525111 Transactions in block 28524688: Error: Cannot find the block No transactions found in block 28525413 Error: Cannot find the block No transactions found in block 28525191 Error: Cannot find the block No transactions found in block 28525312 Transactions in block 28524657: Error: Cannot find the block No transactions found in block 28525806 Error: Cannot find the block No transactions found in block 28525734 Transactions in block 28524782: Error: Cannot find the block No transactions found in block 28525710 Transactions in block 28524810: Traceback (most recent call last): File "C:\Users\AshotxXx\PycharmProjects\pythonProject21\main.py", line 86, in <module> asyncio.run(main()) File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\pythonProject21\main.py", line 84, in main await display_transactions(block_start, block_end) File "C:\Users\AshotxXx\PycharmProjects\pythonProject21\main.py", line 78, in display_transactions await asyncio.gather(*tasks) File "C:\Users\AshotxXx\PycharmProjects\pythonProject21\main.py", line 71, in process_block contract_address = await get_contract_address(tx['hash']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\pythonProject21\main.py", line 41, in get_contract_address return data['result']['contractAddress'] ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^ TypeError: string indices must be integers, not 'str' Process finished with exit code 1 write code to fix these errors
f037a715ecab65ca9007fa75910b8c24
{ "intermediate": 0.3984734117984772, "beginner": 0.4469735026359558, "expert": 0.15455316007137299 }
8,552
//@version=5 strategy("Fibonacci Strategy - Tesla", overlay=true) // Calculate Fibonacci retracement levels highPrice = ta.highest(high, 50) lowPrice = ta.lowest(low, 50) priceRange = highPrice - lowPrice fibonacciLevels = [0.0, 0.236, 0.382, 0.5, 0.618, 0.786] fibonacciRetracements = [] for i = 0 to 5 level = highPrice - priceRange * fibonacciLevels[i] fibonacciRetracements := array.concat(fibonacciRetracements, [level]) // Plot Fibonacci retracement levels for i = 0 to 5 line.new(x1=bar_index[1], y1=fibonacciRetracements[i], x2=bar_index, y2=fibonacciRetracements[i], color=color.gray, width=1, extend=extend.right) // Define buy and sell conditions buyCondition = ta.crossover(close, fibonacciRetracements[2]) sellCondition = ta.crossunder(close, fibonacciRetracements[4]) // Execute trades strategy.entry("Buy", strategy.long, when=buyCondition) strategy.close("Buy", when=sellCondition) // Plot buy and sell signals plotshape(buyCondition, title="Buy Signal", color=color.green, style=shape.labelup, location=location.belowbar) plotshape(sellCondition, title="Sell Signal", color=color.red, style=shape.labeldown, location=location.abovebar) above is the pine script for tesla stock. Can you please fix the error below: 4:48:19 PM Error at 12:19 Syntax error at input '['
83f3f096e7ded67d4fd8c52b467b2463
{ "intermediate": 0.36572393774986267, "beginner": 0.3140503764152527, "expert": 0.32022565603256226 }
8,553
when i put # or . in html
bd3cee383c06281046fd3f08b889bcb6
{ "intermediate": 0.21396192908287048, "beginner": 0.5503140091896057, "expert": 0.2357240468263626 }
8,554
Word statistics This exercise asks you to use Scala 3 and Apache Spark to study a (small) corpus of text available from Project Gutenberg, namely An Inquiry into the Nature and Causes of the Wealth of Nations by Adam Smith War and Peace by Leo Tolstoy. (The files are provided in UTF-8 plain text and can be found in the data folder of this week's assignment.) Remark. In this exercise we are working with a few megabytes of text (two books) to enable you to use your own laptop (or individual classroom computers) for the task. What you should realize is that from a programming perspective we can easily scale up the amount of data that we process into terabytes (millions of books) or beyond, without breaking sweat. All one needs to do is to run Spark on a compute cluster instead of an individual computer. Task 4 implementation is missing. Implement task 4. Do not import external libraries. Code: package words import org.apache.spark.rdd.RDD import org.apache.spark.SparkContext import org.apache.spark.SparkContext._ @main def main(): Unit = /* * Let us start by setting up a Spark context which runs locally * using two worker threads. * * Here we go: * */ val sc = new SparkContext("local[2]", "words") /* * The following setting controls how ``verbose'' Spark is. * Comment this out to see all debug messages. * Warning: doing so may generate massive amount of debug info, * and normal program output can be overwhelmed! */ sc.setLogLevel("WARN") /* * Next, let us set up our input. */ val path = "a01-words/data/" /* * After the path is configured, we need to decide which input * file to look at. There are two choices -- you should test your * code with "War and Peace" (default below), and then use the code with * "Wealth of Nations" to compute the correct solutions * (which you will submit to A+ for grading). * */ // Tolstoy -- War and Peace (test input) val filename = path ++ "pg3300.txt" // Smith -- Wealth of Nations (uncomment line below to use as input) // val filename = path ++ "pg3300.txt" /* * Now you may want to open up in a web browser * the Scala programming guide for * Spark version 3.3.1: * * http://spark.apache.org/docs/3.3.1/programming-guide.html * */ /* * Let us now set up an RDD from the lines of text in the file: * */ val lines: RDD[String] = sc.textFile(filename) /* The following requirement sanity-checks the number of lines in the file * -- if this requirement fails you are in trouble. */ require((filename.contains("pg2600.txt") && lines.count() == 65007) || (filename.contains("pg3300.txt") && lines.count() == 35600)) /* * Let us make one further sanity check. That is, we want to * count the number of lines in the file that contain the * substring "rent". * */ val lines_with_rent: RDD[String] = lines.filter(line => line.contains("rent")) val rent_count = lines_with_rent.count() println("OUTPUT: \"rent\" occurs on %d lines in \"%s\"" .format(rent_count, filename)) require((filename.contains("pg2600.txt") && rent_count == 360) || (filename.contains("pg3300.txt") && rent_count == 1443)) /* * All right, if the execution continues this far without * failing a requirement, we should be pretty sure that we have * the correct file. Now we are ready for the work that you need * to put in. * */ /* * Spark operates by __transforming__ RDDs. For example, above we * took the RDD 'lines', and transformed it into the RDD 'lines_with_rent' * using the __filter__ transformation. * * Important: * While the code that manipulates RDDs may __look like__ we are * manipulating just another Scala collection, this is in fact * __not__ the case. An RDD is an abstraction that enables us * to easily manipulate terabytes of data in a cluster computing * environment. In this case the dataset is __distributed__ across * the cluster. In fact, it is most likely that the entire dataset * cannot be stored in a single cluster node. * * Let us practice our skills with simple RDD transformations. * */ /* * Task 1: * This task asks you to transform the RDD * 'lines' into an RDD 'depunctuated_lines' so that __on each line__, * all occurrences of any of the punctuation characters * ',', '.', ':', ';', '\"', '(', ')', '{', '}' have been deleted. * * Hint: it may be a good idea to consult * http://www.scala-lang.org/api/3.2.1/scala/collection/StringOps.html * */ def depunctuate(line: String): String = line.replaceAll("[,.:;\"\\(\\)\\{\\}]", "") val depunctuated_lines: RDD[String] = lines.map(depunctuate) /* * Let us now check and print out data that you want to * record (__when the input file is "pg3300.txt"__) into * the file "wordsSolutions.scala" that you need to submit for grading * together with this file. */ val depunctuated_length = depunctuated_lines.map(_.length).reduce(_ + _) println("OUTPUT: total depunctuated length is %d".format(depunctuated_length)) //require(!filename.contains("pg3300.txt") || depunctuated_length == 3069444) /* * Task 2: * Next, let us now transform the RDD of depunctuated lines to * an RDD of consecutive __tokens__. That is, we want to split each * line into zero or more __tokens__ where a __token__ is a * maximal nonempty sequence of non-space (non-' ') characters on a line. * Blank lines or lines with only space (' ') in them should produce * no tokens at all. * * Hint: Use either a map or a flatMap to transform the RDD * line by line. Again you may want to take a look at StringOps * for appropriate methods to operate on each line. Use filter * to get rid of blanks as necessary. * */ def tokenize(line: String): Seq[String] = line.split(" ").filter(_.nonEmpty) val tokens: RDD[String] = depunctuated_lines.flatMap(tokenize).filter(_.nonEmpty) /* ... and here comes the check and the printout. */ val token_count = tokens.count() println("OUTPUT: %d tokens".format(token_count)) //require(!filename.contains("pg3300.txt") || token_count == 566315) /* * Task 3: * Transform the RDD of tokens into a new RDD where all upper case * characters in each token get converted into lower case. Here you may * restrict the conversion to characters in the Roman alphabet * 'A', 'B', ..., 'Z'. * */ def toLowerCase(token: String): String = token.replaceAll("[^a-zA-Z]", "").toLowerCase val tokens_lc: RDD[String] = tokens.map(toLowerCase) /* ... and here comes the check and the printout. */ val tokens_a_count = tokens.flatMap(t => t.filter(_ == 'a')).count() println("OUTPUT: 'a' occurs %d times in tokens".format(tokens_a_count)) //require(!filename.contains("pg3300.txt") || tokens_a_count == 199232) /* * Task 4: * Transform the RDD of lower-case tokens into a new RDD where * all but those tokens that consist only of lower-case characters * 'a', 'b', ..., 'z' in the Roman alphabet have been filtered out. * Let us call the tokens that survive this filtering __words__. * */ val words: RDD[String] = ??? //your solution here /* ... and here comes the check and the printout. */ val words_count = words.count() println("OUTPUT: %d words".format(words_count)) //require(!filename.contains("pg3300.txt") || words_count == 547644) /* * Now let us move beyond maps, filtering, and flatMaps * to do some basic statistics on words. To solve this task you * can consult the Spark programming guide, examples, and API: * * http://spark.apache.org/docs/3.3.1/programming-guide.html * http://spark.apache.org/examples.html * https://spark.apache.org/docs/3.3.1/api/scala/org/apache/spark/index.html */ /* * Task 5: * Count the number of occurrences of each word in 'words'. * That is, create from 'words' by transformation an RDD * 'word_counts' that consists of, ___in descending order___, * pairs (c,w) such that w occurs exactly c times in 'words'. * Then take the 100 most frequent words in this RDD and * answer the following two questions (first is practice with * a given answer for "pg2600.txt", the second question is * the one where you need to find the answer yourself and * submit it for grading). * * Practice question for "pg2600.txt" (answer given below): * What word occurs exactly 1772 times in 'words' ? * (answer: "pierre") * * The question that you need to answer for "pg3300.txt": * What word occurs exactly 777 times in 'words' ? * (give your answer in lower case) * */ val word_groups: RDD[(String, Iterable[String])] = words.groupBy(identity) val word_counts_unsorted: RDD[(Long,String)] = word_groups.map { case (word, group) => (group.size.toLong, word) } val word_counts: RDD[(Long,String)] = word_counts_unsorted.sortBy(x => (-x._1, x._2)) /* ... and here comes a check. */ val top_word = word_counts.take(1)(0) println("OUTPUT: top word is \"%s\" (%d times)".format(top_word._2, top_word._1)) //require(!filename.contains("pg3300.txt") || (top_word._2 == "the" && top_word._1 == 34558)) /* ... print out the 100 most frequent words. */ println("OUTPUT: The 100 most frequent words are, in rank order ...") word_counts.take(100) .zipWithIndex .foreach(x => println("OUTPUT: %3d: \"%s\" with %d occurrences". format(x._2+1,x._1._2,x._1._1))) /* That's it! */ Data: "The Project Gutenberg EBook of An Inquiry into the Nature and Causes of the Wealth of Nations, by Adam Smith This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org Title: An Inquiry into the Nature and Causes of the Wealth of Nations Author: Adam Smith Posting Date: February 28, 2009 [EBook #3300] Release Date: April, 2002 [Last updated: June 5, 2011] Language: English *** START OF THIS PROJECT GUTENBERG EBOOK NATURE AND CAUSES OF THE WEALTH OF NATIONS *** Produced by Colin Muir AN INQUIRY INTO THE NATURE AND CAUSES OF THE WEALTH OF NATIONS. By Adam Smith INTRODUCTION AND PLAN OF THE WORK. The annual labour of every nation is the fund which originally supplies it with all the necessaries and conveniencies of life which it annually consumes, and which consist always either in the immediate produce of that labour, or in what is purchased with that produce from other nations. According, therefore, as this produce, or what is purchased with it, bears a greater or smaller proportion to the number of those who are to consume it, the nation will be better or worse supplied with all the necessaries and conveniencies for which it has occasion. But this proportion must in every nation be regulated by two different circumstances: first, by the skill, dexterity, and judgment with which its labour is generally applied; and, secondly, by the proportion between the number of those who are employed in useful labour, and that" etc
34d41152dce7ea5354a2db0af3f37229
{ "intermediate": 0.5045173764228821, "beginner": 0.2682602107524872, "expert": 0.22722242772579193 }
8,555
# Оптимизированный!!! Возращает адреса созданных токенов в указанном интревале блоков (Обрабатывет множество) # Ограничение до 5 запросов в секунду import asyncio import aiohttp bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' api_semaphore = asyncio.Semaphore(5) async def api_call(session, url): """Wrapper around aiohttp request to add retries with exponential backoff.""" retries = 0 while retries < 5: try: async with session.get(url) as response: data = await response.json() if data.get("status") == "1": return data except Exception as e: print(f"Error in API request: {e}") retries += 1 await asyncio.sleep(2 ** retries) # Exponential backoff raise Exception("Failed API request after retries.") async def get_external_transactions(block_number): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' async with api_semaphore: data = await api_call(session, url) if data['result'] is None or not isinstance(data['result'], dict): print(f"Error: Cannot find the block {block_number}") return [] return data['result']['transactions'] async def get_contract_address(tx_hash): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}' async with api_semaphore: data = await api_call(session, url) if data['result'] is None or not isinstance(data['result'], dict): return None return data['result'].get('contractAddress') async def get_contract_name(contract_address): async with aiohttp.ClientSession() as session: method_signature = '0x06fdde03' url = f'https://api.bscscan.com/api?module=proxy&action=eth_call&to={contract_address}&data={method_signature}&tag=latest&apikey={bscscan_api_key}' async with api_semaphore: data = await api_call(session, url) if not data.get('result') or data['result'][:2] == '0x': return None return bytes.fromhex(data['result'][2:]).decode('utf-8') async def display_transactions(block_start, block_end): async def process_block(block_number_int): block_number = hex(block_number_int) transactions = await get_external_transactions(block_number) if not transactions: print(f'No transactions found in block {block_number_int}') else: print(f'Tokens created in block {block_number_int}:') for tx in transactions: if tx['to'] is None: contract_address = await get_contract_address(tx['hash']) if contract_address: contract_name = await get_contract_name(contract_address) if contract_name: print(f'Contract Address: {contract_address} - Contract Name: {contract_name}') else: print(f'Contract Address: {contract_address} - Contract Name not found') print("\n") # Print an empty line between blocks tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)] await asyncio.gather(*tasks) async def main(): block_start = 28557162 # Replace with your desired starting block number block_end = 28557199 # Replace with your desired ending block number await display_transactions(block_start, block_end) asyncio.run(main()) The above code does not display the generated token addresses in the specified range block. The answer is below C:\Users\AshotxXx\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\pythonProject\main.py Traceback (most recent call last): File "C:\Users\AshotxXx\PycharmProjects\pythonProject\main.py", line 94, in <module> asyncio.run(main()) File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\pythonProject\main.py", line 92, in main await display_transactions(block_start, block_end) File "C:\Users\AshotxXx\PycharmProjects\pythonProject\main.py", line 86, in display_transactions await asyncio.gather(*tasks) File "C:\Users\AshotxXx\PycharmProjects\pythonProject\main.py", line 68, in process_block transactions = await get_external_transactions(block_number) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\pythonProject\main.py", line 31, in get_external_transactions data = await api_call(session, url) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\pythonProject\main.py", line 24, in api_call raise Exception("Failed API request after retries.") Exception: Failed API request after retries. Process finished with exit code 1 Fix it
95347119abe980cb86823379a3bc20aa
{ "intermediate": 0.335866242647171, "beginner": 0.5196230411529541, "expert": 0.14451074600219727 }
8,556
I am trying to make a simulation of bike system in Julia: mutable struct BikeStation id::Int num_bikes::Int incoming_trips::Array{Int, 1} outgoing_trips::Array{Int, 1} end function create_bike_stations(n::Int, bikes_per_station::Int) stations = [BikeStation(i, bikes_per_station, Int[], Int[]) for i in 1:n] return stations end function take_bike(from_station::Int, to_station::Int, bike_stations::Array{BikeStation, 1}) from = bike_stations[from_station] to = bike_stations[to_station] updated_from = BikeStation(from.id, from.num_bikes - 1, from.incoming_trips, push!(from.outgoing_trips, to.id)) updated_to = BikeStation(to.id, to.num_bikes + 1, push!(to.incoming_trips, from.id), to.outgoing_trips) bike_stations[from_station] = updated_from bike_stations[to_station] = updated_to end function simulate_demand(bike_stations::Array{BikeStation, 1}, time_steps::Int, demand_factor_range::Tuple{Float64, Float64}) for _ in 1:time_steps for station in bike_stations demand_factor = rand(demand_factor_range) demand = round(Int, station.num_bikes * demand_factor) for _ in 1:demand to = rand(1:length(bike_stations)) if station.num_bikes > 0 && to != station.id take_bike(station.id, to, bike_stations) end end end end end function print_station_info(bike_stations::Array{BikeStation, 1}) for station in bike_stations println("Station ", station.id, " has ", station.num_bikes, " bikes, with ", length(station.outgoing_trips), " bikes in transit to other stations.") end end bike_stations = create_bike_stations(5, 20) time_steps = 4000 demand_factor_range = (0.05, 0.2) simulate_demand(bike_stations, time_steps, demand_factor_range) print_station_info(bike_stations) but it has many flows, for example output looks like that: Station 1 has 25 bikes, with 8383 bikes in transit to other stations. Station 2 has 20 bikes, with 8312 bikes in transit to other stations. Station 3 has 23 bikes, with 8401 bikes in transit to other stations. Station 4 has 14 bikes, with 8315 bikes in transit to other stations. Station 5 has 18 bikes, with 8366 bikes in transit to other stations. Those resluts make no sense because the sum of bikes at station and currently in travel should be equal to 100. I need toknow how many bikes were on the station at any time moment, whether the demand was reported if the station had no bikes and the whole logs.
fd3180ad966c055a53787148fbd1633d
{ "intermediate": 0.32299312949180603, "beginner": 0.385476291179657, "expert": 0.2915305495262146 }
8,557
What is the error cv2.imshow("D:\\Photos\\Pokeball which is not a pokeball.png", frame) ?
beac1aa24ac648488eda53c19135e5dd
{ "intermediate": 0.43586644530296326, "beginner": 0.2004869133234024, "expert": 0.3636467158794403 }
8,558
A simple GUI in python that takes an input video path, show status of the program (ex: idel/ summarizing) and outputs a summarized video
1e07f6277a8c12d7359be49dfef4db51
{ "intermediate": 0.34207814931869507, "beginner": 0.23458099365234375, "expert": 0.42334091663360596 }
8,559
Есть код,коотрый использует keras для многоклассовой классификации import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences max_len = 600 # максимальная длина последовательности # создаем токенизатор tokenizer = Tokenizer() tokenizer.fit_on_texts(train_df['lemma']) # преобразуем текст в последовательность чисел train_sequences = tokenizer.texts_to_sequences(train_df['lemma']) test_sequences = tokenizer.texts_to_sequences(test_df['lemma']) val_sequences = tokenizer.texts_to_sequences(val_df['lemma']) # добавляем паддинг train_sequences = pad_sequences(train_sequences, maxlen=max_len) test_sequences = pad_sequences(test_sequences, maxlen=max_len) val_sequences = pad_sequences(val_sequences, maxlen=max_len) # создаем модель seq2seq input_dim = len(tokenizer.word_index) + 1 embedding_dim = 50 model = keras.Sequential([ layers.Embedding(input_dim=input_dim, output_dim=embedding_dim, input_length=max_len), layers.LSTM(units=64, dropout=0.2, recurrent_dropout=0.2), layers.Dense(1, activation='sigmoid') ]) model.summary() # выводим информацию о модели from sklearn.metrics import f1_score import tensorflow.keras.backend as K from tensorflow.keras.losses import CategoricalCrossentropy import numpy as np from keras import backend as K def recall_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def f1_m(y_true, y_pred): precision = precision_m(y_true, y_pred) recall = recall_m(y_true, y_pred) return 2*((precision*recall)/(precision+recall+K.epsilon())) model.compile(loss=CategoricalCrossentropy(), optimizer='adam', metrics=['acc',f1_m,precision_m, recall_m]) history = model.fit(train_sequences, train_df['category'], epochs=10, batch_size=1000, validation_data=(val_sequences, val_df['category'])). ОН дает результаты Epoch 1/10 31/31 [==============================] - 326s 10s/step - loss: 0.0000e+00 - acc: 0.0784 - f1_m: 1.0000 - precision_m: 1.0000 - recall_m: 1.0000 - val_loss: 0.0000e+00 - val_acc: 0.0723 - val_f1_m: 1.0000 - val_precision_m: 1.0000 - val_recall_m: 1.0000 Epoch 2/10 31/31 [==============================] - 320s 10s/step - loss: 0.0000e+00 - acc: 0.0784 - f1_m: 1.0000 - precision_m: 1.0000 - recall_m: 1.0000 - val_loss: 0.0000e+00 - val_acc: 0.0723 - val_f1_m: 1.0000 - val_precision_m: 1.0000 - val_recall_m: 1.0000 Epoch 3/10 31/31 [==============================] - 316s 10s/step - loss: 0.0000e+00 - acc: 0.0784 - f1_m: 1.0000 - precision_m: 1.0000 - recall_m: 1.0000 - val_loss: 0.0000e+00 - val_acc: 0.0723 - val_f1_m: 1.0000 - val_precision_m: 1.0000 - val_recall_m: 1.0000 Epoch 4/10 31/31 [==============================] - 315s 10s/step - loss: 0.0000e+00 - acc: 0.0784 - f1_m: 1.0000 - precision_m: 1.0000 - recall_m: 1.0000 - val_loss: 0.0000e+00 - val_acc: 0.0723 - val_f1_m: 1.0000 - val_precision_m: 1.0000 - val_recall_m: 1.0000 Epoch 5/10 31/31 [==============================] - 316s 10s/step - loss: 0.0000e+00 - acc: 0.0784 - f1_m: 1.0000 - precision_m: 1.0000 - recall_m: 1.0000 - val_loss: 0.0000e+00 - val_acc: 0.0723 - val_f1_m: 1.0000 - val_precision_m: 1.0000 - val_recall_m: 1.0000 Вопрос: верно ли составлена модель и правильные ли она рехультаты выдает при обучении?
21ad608558d6b2b2683375ca0136c793
{ "intermediate": 0.2825736403465271, "beginner": 0.35209405422210693, "expert": 0.3653322756290436 }
8,560
Change the code below so that the number of requests is no more than 5 per second import asyncio import aiohttp bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' async def get_external_transactions(block_number): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return [] if data['result'] is None or not isinstance(data['result'], dict): print(f"Error: Cannot find the block {(block_number)}") return [] return data['result']['transactions'] async def get_contract_address(tx_hash): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return None if data['result'] is None or not isinstance(data['result'], dict): return None return data['result'].get('contractAddress') async def get_contract_name(contract_address): async with aiohttp.ClientSession() as session: method_signature = '0x06fdde03' url = f'https://api.bscscan.com/api?module=proxy&action=eth_call&to={contract_address}&data={method_signature}&tag=latest&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return None if not data.get('result') or data['result'][:2] == '0x': return None return bytes.fromhex(data['result'][2:]).decode('utf-8') async def display_transactions(block_start, block_end): async def process_block(block_number_int): block_number = hex(block_number_int) transactions = await get_external_transactions(block_number) if not transactions: print(f'No transactions found in block {block_number_int}') else: print(f'Transactions in block {block_number_int}:') for tx in transactions: if tx['to'] is None: contract_address = await get_contract_address(tx['hash']) if contract_address: contract_name = await get_contract_name(contract_address) print(f'New contract creation: Contract Address: {contract_address} - Contract Name: {contract_name}') print("\n") # Print an empty line between blocks tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)] await asyncio.gather(*tasks) async def main(): block_start = 28557162 # Replace with your desired starting block number block_end = 28557199 # Replace with your desired ending block number await display_transactions(block_start, block_end) asyncio.run(main())
34cd2c59b057d4819be975cf865d004c
{ "intermediate": 0.4550861716270447, "beginner": 0.40462255477905273, "expert": 0.1402912437915802 }
8,561
Expressions continued In this assignment we will continue with the Expr class used in the lecture notes (please take a look at the notes before starting to solve this assignment). We will expand the class with some new operations. The goal of the assignment is to practice recursive traversal of data structures. Programming Style Restrictions In this exercise we practice the use of recursion and immutable data structures. Therefore, you are not allowed to use var declarations, Arrays, or any scala.collection.mutable or java.util classes. The compiler for this exercise will not accept the use of such constructs; if your submitted file contains any such constructs, a compilation error and 0 points will occur. The VS Code environment will help to check this as well. Naturally, the use val declarations and scala.collection.immutable classes is allowed. package expressions: import scala.collection.immutable.Map /** * The abstract base class for expressions. */ abstract class Expr: /* Overriding these operators enable us to construct expressions with infix notation */ def +(other: Expr) = Add(this, other) def -(other: Expr) = Subtract(this, other) def *(other: Expr) = Multiply(this, other) def unary_- = Negate(this) /** * Returns the set of variable names appearing in this expression */ final def vars: Set[String] = this match case Var(n) => Set(n) case Num(v) => Set() case Multiply(l, r) => l.vars ++ r.vars case Add(l, r) => l.vars ++ r.vars case Subtract(l, r) => l.vars ++ r.vars case Negate(t) => t.vars end vars /** The exception returned by "evaluate" when a variable in the expression is not assigned a value. */ class VariableNotAssignedException(message: String) extends java.lang.RuntimeException(message) /** * Evaluate the expression in the point p, where p is a map * associating each variable name in the expression into a Double value. */ final def evaluate(p: Map[String, Double]): Double = this match case Var(n) => p.get(n) match case Some(v) => v case None => throw new VariableNotAssignedException(n) case Num(v) => v case Multiply(l, r) => l.evaluate(p) * r.evaluate(p) case Add(l, r) => l.evaluate(p) + r.evaluate(p) case Subtract(l, r) => l.evaluate(p) - r.evaluate(p) case Negate(t) => -t.evaluate(p) end evaluate /** * Similar to evaluate except that not all the variables names must have * an associated value in p. Therefore, instead of a Double value, a new expression * is returned such that (i) all the variable names who are associated with a value are * replaced with that value, while (ii) all the other variable names stay intact. * For instance, if p maps x to 3.0 but does not mention y, then partialEvaluate(p) * on 2.0*x+y*x should return an expression equivalent to 3.0*y+6.0. */ final def partialEvaluate(p: Map[String, Double]): Expr = this match case Var(n) => p.get(n).map(Num(_)).getOrElse(Var(n)) case Num(v) => Num(v) case Multiply(l, r) => Multiply(l.partialEvaluate(p), r.partialEvaluate(p)) case Add(l, r) => Add(l.partialEvaluate(p), r.partialEvaluate(p)) case Subtract(l, r) => Subtract(l.partialEvaluate(p), r.partialEvaluate(p)) case Negate(t) => Negate(t.partialEvaluate(p)) end partialEvaluate /** * Produce the partial derivative of the expression with respect to the variable v. * Such a partial derivative is the derivative of the expression obtained when considering * the variables other than v as constants. * For instance, the partial derivative of 3*x*x*y+z*x+z*z w.r.t x is 6*x*y+z * and that of y*(x*z + 3*y) w.r.t. y is x*z+6*y. * * If you need to recall the differentiation rules, * please see, for instance, the "sum rule" and "product rule" in * http://en.wikipedia.org/wiki/Differentiation_rules */ final def partialDerivative(v: String): Expr = this match case Var(n) => if (n == v) Num(1) else Num(0) case Num(_) => Num(0) case Multiply(l, r) => Add(Multiply(l.partialDerivative(v), r), Multiply(l, r.partialDerivative(v))) case Add(l, r) => Add(l.partialDerivative(v), r.partialDerivative(v)) case Subtract(l, r) => Subtract(l.partialDerivative(v), r.partialDerivative(v)) case Negate(t) => Negate(t.partialDerivative(v)) end partialDerivative /** * Simplifies the expression with some simple rules like "1.0*r equals r". */ final def simplify: Expr = // First, (recursively) simplify sub-expressions val subresult = this match case Multiply(l, r) => Multiply(l.simplify, r.simplify) case Add(l, r) => Add(l.simplify, r.simplify) case Subtract(l, r) => Subtract(l.simplify, r.simplify) case Negate(t) => Negate(t.simplify) case _ => this // Handles Var and Num // Then simplify this sub-expression by applying some simple rules subresult match case Multiply(Num(1.0), r) => r case Multiply(l, Num(1.0)) => l case Multiply(Num(0.0), _) => Num(0.0) case Multiply(_, Num(0.0)) => Num(0.0) case Multiply(Num(v1), Num(v2)) => Num(v1 * v2) case Add(Num(0.0), r) => r case Add(l, Num(0.0)) => l case Add(Num(v1), Num(v2)) => Num(v1 + v2) case Subtract(Num(0.0), r) => Negate(r) case Subtract(l, Num(0.0)) => l case Subtract(Num(v1), Num(v2)) => Num(v1 - v2) case Negate(Num(v)) => Num(-v) case _ => subresult // Could not simplify end simplify /** * Is this expression a product? ("term" is also sometimes used as a synonum for "product") * An expression is a product if * it is a product of variables, constant numbers, and their negations. * For instance, x*-4*y*x is a product but x*(2+y) is not. */ final def isProduct: Boolean = this match case Multiply(l, r) => l.isProduct && r.isProduct case Negate(Num(_)) => true case Negate(Var(_)) => true case Var(_) => true case Num(_) => true case _ => false end isProduct /** * Check if the expression is a sum of products. * If it is, we say that it is in "sum of products" (SOP) normal form. * For instance, 2*x + 7 + x*-y is in SOP form but 2*(x + y) + 7 is not. */ final def isInSOP: Boolean = this match case Add(l, r) => l.isInSOP && r.isInSOP case _ => this.isProduct end isInSOP /** * Expand this expression into "sum of products" (SOP) normal form (see the definition of * product and SOP above in the documentation of the "isProduct" and "isInSOP" methods). * That is, the expressions x*(3*x - y) should be expanded to x*3*x + -1*x*y, or to something * equivalent, that is a sum (+) of products (x*3*x and 1-*x*y in this case). * * Hint: one way to solve this is to make two inner functions * - one helper function that negates a product (e.g., translates "x*-y*y" to "-x*-y*y"), and * - one that (recursively) forms a list of the products in the SOP form of an expression. * For instance, if the products in the SOP form of e are ("2.0*x*y", "z*-3.0*-y"), * then what are the products in the SOP form of the expression -e? * Perform similar analysis for other operators. * * You do not need to minimize the result expression, * it only has to be in SOP form and equal to the original expression. */ final def expand: Expr = def negateProduct(e: Expr): Expr = e match { case Multiply(Num(c), rest) => Multiply(Num(-c), rest) case Multiply(left, Num(c)) => Multiply(left, Num(-c)) case _ => Multiply(-1.0, e) } def expandHelper(e: Expr): List[Expr] = e match { case Add(left, right) => expandHelper(left) ++ expandHelper(right) case Subtract(left, right) => expandHelper(left) ++ expandHelper(negateProduct(right)) case Multiply(left, right) => val expandedLeft = left.expand val expandedRight = right.expand expandHelper(expandedLeft).flatMap { leftProd => expandHelper(expandedRight).map { rightProd => Multiply(leftProd, rightProd) } } case Negate(innerExpr) => expandHelper(negateProduct(innerExpr)) case _ => List(e) } def collapseSOP(exprs: List[Expr], acc: Expr = Num(0)): Expr = { @scala.annotation.tailrec def collapseSOPHelper(exprs: List[Expr], acc: Expr): Expr = { exprs match { case Nil => acc case head :: tail => head match { case Add(left, right) => collapseSOPHelper(left :: right :: tail, acc) case _ => collapseSOPHelper(tail, Add(acc, head)) } } } collapseSOPHelper(exprs, acc) } val expanded = expandHelper(this) collapseSOP(expanded) end expand end Expr /** Variable expression, like "x" or "y". */ case class Var(name: String) extends Expr: override def toString = name /** Constant expression like "2.1" or "-1.0" */ case class Num(value: Double) extends Expr: override def toString = value.toString /** Expression formed by multiplying two expressions, like "x * (y+3)" */ case class Multiply(left: Expr, right: Expr) extends Expr: override def toString = "(" + left + "*" + right + ")" /** Expression formed by adding two expressions, like "x + (y*3)" */ case class Add(left: Expr, right: Expr) extends Expr: override def toString = "(" + left + " + " + right + ")" /** Expression formed by subtracting an expression from another, "x - (y*3)" */ case class Subtract(left: Expr, right: Expr) extends Expr: override def toString = "(" + left + " - " + right + ")" /** Negation of an expression, like "-((3*y)+z)" */ case class Negate(p: Expr) extends Expr: override def toString = "-" + p /* * These implicit definitions allow us to write "2.0*x" instead of Num(2.0)*x, * where x is a Var object. */ import scala.language.implicitConversions implicit def doubleToNum(v: Double) : Expr = Num(v) implicit def intToNum(v: Int) : Expr = Num(v) This test does not pass: expressionsSpec *** ABORTED *** java.lang.StackOverflowError: 10 at expressions.Expr.expandHelper$1(expressions.scala:184) Testing with the expression expr = -(u - ((x*(((-5.0 - w) + z)*((z + w)*(u - x)))) + -4.0)) Computing the SOP form with exprSOP = expr.expand Got exprSOP = (0.0 + -(u + -((x*(((-5.0 + -w) + z)*((z + w)*(u + -x)))) + -4.0))) The expression is not in SOP form so expandHelper could be erroneous. Fix the code.
934f66899db137eecbad6ca26a459f26
{ "intermediate": 0.37496450543403625, "beginner": 0.32115694880485535, "expert": 0.3038785755634308 }
8,563
In Julia I need to run create simulation. I have 5 bike stations, each containing a bike. Each station has 20 bikes. People can take a bike from one station to other. I need to know how many bikes are currently at each station and how many are on their way to another station. Make problem as complex as possible.
05f7a2d5023047bf46759d2903c0f7f7
{ "intermediate": 0.3845939636230469, "beginner": 0.2581007182598114, "expert": 0.35730525851249695 }
8,564
Мне нужно провести многоклассовую классификацию. Есть массив с текстами с размеченными данными. from sklearn.model_selection import train_test_split # разбиваем выборку на тренировочную и тестовую train_df, test_df = train_test_split(train_data, test_size=0.2, random_state=42) # разбиваем тестовую выборку на тестовую и валидационную test_df, val_df = train_test_split(test_df, test_size=0.5, random_state=42) import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences max_len = 600 # максимальная длина последовательности num_classes = 13 # число классов для классификации # создаем токенизатор tokenizer = Tokenizer() tokenizer.fit_on_texts(train_df['text']) # преобразуем текст в последовательность чисел train_sequences = tokenizer.texts_to_sequences(train_df['text']) test_sequences = tokenizer.texts_to_sequences(test_df['text']) val_sequences = tokenizer.texts_to_sequences(val_df['text']) # добавляем паддинг train_sequences = pad_sequences(train_sequences, maxlen=max_len) test_sequences = pad_sequences(test_sequences, maxlen=max_len) val_sequences = pad_sequences(val_sequences, maxlen=max_len) # создаем модель seq2seq input_dim = len(tokenizer.word_index) + 1 embedding_dim = 50 model = keras.Sequential([ layers.Embedding(input_dim=input_dim, output_dim=embedding_dim, input_length=max_len), layers.LSTM(units=64, dropout=0.2, recurrent_dropout=0.2), layers.Dense(num_classes, activation='softmax') ]) model.summary() # выводим информацию о модели from sklearn.metrics import f1_score import tensorflow.keras.backend as K from tensorflow.keras.losses import CategoricalCrossentropy import numpy as np from keras import backend as K def recall_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def f1_m(y_true, y_pred): precision = precision_m(y_true, y_pred) recall = recall_m(y_true, y_pred) return 2*((precision*recall)/(precision+recall+K.epsilon())) #model.compile(loss=CategoricalCrossentropy(), optimizer='adam', metrics=['acc',f1_m,precision_m, recall_m]) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc',f1_m,precision_m, recall_m]) history = model.fit(train_sequences, train_df['category'], epochs=10, batch_size=1000, validation_data=(val_sequences, val_df['category'])) 31 ---> 32 history = model.fit(train_sequences, train_df['category'], 33 epochs=10, batch_size=1000, 34 validation_data=(val_sequences, val_df['category'])) ValueError: Shapes (None, 1) and (None, 13) are incompatible
3de41e10c7c72e4d9833835bea343b2d
{ "intermediate": 0.3431960940361023, "beginner": 0.39838162064552307, "expert": 0.25842228531837463 }
8,565
problem: One terabyte This exercise asks you to work with a one-terabyte (240 = 1099511627776 bytes) stream of data consisting of 64-bit words. You are to compute the minimum value, the maximum value, and the median value of the data in the stream. The stream is supplied to you via an iterator that delivers 1048576 blocks, each of which consists of one megabyte (220 = 1048576 bytes, or 131072 64-bit words). Perhaps needless to say, one terabyte is already a fair amount of data for a single machine to process, so be prepared to wait some time to finish the computations in this exercise. Precise instructions may be found in the code package. Hint. There is a practice stream with similar structure but less data that delivers a one-megabyte stream in 1024 blocks, each of which consists of one kilobyte (210 = 1024 bytes, or 128 64-bit words). Make sure your code works correctly on the practice stream before scaling up the problem. An amusing contrast is perhaps that if we view the one-megabyte practice stream as having length one centimeter, then the one-terabyte stream is ten kilometers in length! Complete the tasks in Scala 3. Only replace ??? symbols with your solution. Do not leave anything other out. Do not import external libraries. Code: /* * Description: * This assignment asks you to study a stream of locks, each of * which is an array of 64-bit words. The stream is implemented * in the object inputStream, which has been instantiated * from class BlockStream (see below). Access to the stream is by * means of the Iterator interface in Scala, whose two methods * hasNext() and next() tell you whether there are more blocks * available in the stream, and if yes, return the next block in * the stream, respectively. It is also possible to rewind() * the stream back to its start. * * The stream in this assignment is a long one, exactly one terabyte * (1099511627776 bytes) of data, divided into 1048576 blocks of 131072 * 64-bit words each. That is, 1048576 one-megabyte blocks. * * Remark: * Observe that one terabyte of data is too much to store in main memory * on most computers. Thus, whatever you do, keep in mind that it is perhaps * __not__ wise to try to store all the data in memory, or save the data * to disk. * * Hints: * Tasks 1 and 2 should not be extremely challenging. Think how to scan * through the blocks. Task 3 is the most challenging one, most likely * requiring multiple scans through the blocks, using the possibility * to rewind(). Say, what if you looked at the most significant bits to * identify what the values of those bits should be for the value you are * looking for? What you should also observe is that scanning through * one terabyte of data takes time, so perhaps it is a good idea to plan * a bit and test your code with a somewhat smaller stream first. You * should probably reserve at least one hour of computer time to execute * the computations for Task 3. * */ package teraStream: class BlockStream(numblocks: Int, blocklength: Int) extends collection.AbstractIterator[Array[Long]]: val modulus = Array(0, 5, 8, 18, 22, 60).map(1L << _).foldLeft(0L)(_ | _ ) val hi = 0x4000000000000000L val mask = 0x7FFFFFFFFFFFFFFFL val startval = 0xA3A3A3A3A3A3A3A3L & mask var current = startval var blockno = 0 def rewind() : Unit = current = startval blockno = 0 end rewind def hasNext: Boolean = blockno < numblocks def next(): Array[Long] = require(blockno < numblocks) val blk = new Array[Long](blocklength) var i = 0 while i < blocklength do blk(i) = current if (current & hi) != 0L then current = ((current << 1) & mask) ^ modulus else current = current << 1 i = i + 1 blockno = blockno + 1 blk end next val inputStream = new BlockStream(1048576, 131072) // A one-terabyte stream val practiceStream = new BlockStream(1024, 128) // A one-megabyte stream /* * Task 1: * Compute the minimum value in inputStream. * */ def minStream(s: BlockStream) = ??? end minStream // your CODE for computing the minimum value val minValue = ??? // the minimum VALUE that you have computed, e.g. 0x1234567890ABCDEFL /* * Task 2: * Compute the maximum value in inputStream. * */ def maxStream(s: BlockStream) = ??? // your CODE for computing the maximum value val maxValue = ??? // the maximum VALUE that you have computed, e.g. 0x1234567890ABCDEFL /* * Task 3: * Assume that all the blocks in inputStream have been concatenated, * and the resulting array has been sorted to increasing order, * producing a sorted array of length 137438953472L. Compute the value at * position 68719476736L in the sorted array. (The minimum is at position 0L * in the sorted array, the maximum at position 137438953471L.) * * (See the remarks and hints above before attempting this task!) * */ def posStream(s: BlockStream, pos: Long) = ??? // your CODE for computing the value at SORTED position "pos" // in the array obtained by concatenating the blocks of "s" // sorting the resulting array into increasing order val posValue = ??? // the VALUE at SORTED position 68719476736L that you have computed, // e.g. 0x1234567890ABCDEFL Make sure the solution utilizes practiceStream.
0f6dcb7e2b0a0b12d11bae6f6402b5e4
{ "intermediate": 0.43898510932922363, "beginner": 0.281908243894577, "expert": 0.27910664677619934 }
8,566
I have a list of chemical id, such as: T3, T2B, F2A... I want to use the chemical IDs to find the relevant chemical name, synonyms, isometric SMILES from PDB. How to do that using python?
6338ead7c8324d59c3f6a54e8f3f1cf5
{ "intermediate": 0.5507736206054688, "beginner": 0.11408672481775284, "expert": 0.335139662027359 }
8,567
ich brauche eine zusammenfassung von einem essay, ich werde dir kapitel senden auf arabisch und du wirst mir den kapitel zusammenfassen und die wichtigsten infos welche ich als präsentation geben muss geben.
4afa3cb9692a96a1ea47e6213b94f541
{ "intermediate": 0.31002098321914673, "beginner": 0.3994236886501312, "expert": 0.29055532813072205 }
8,568
read this chapter and give me a flowchart with the main informations i need in a advanced mermaid flowchart code: مقدمة سيقدم هذا الفصل نظرة عامة على خطوات تطوير استراتيجية التسويق ، مثل تحديد الأهداف ، والبحث في السوق ، وإنشاء خطة. كما سيناقش أهمية إعداد الميزانية وتتبع الأداء. في عالم الأعمال والتجارة الحديث، تعد الاستراتيجيات التسويقية من العوامل الأساسية التي تحدد نجاح الشركة واستمراريتها في السوق. فالتسويق ليس مجرد بيع منتجات وخدمات، بل إنه علم وفن يتطلب معرفة تامة بأنواع السوق وميزات المستهلكين واحتياجاتهم بالإضافة إلى التنبؤ بالاتجاهات المستقبلية ومدى تغيرها. يتضح أن استراتيجيات التسويق هي عملية مستمرة تتضمن عدة مراحل. حيث تبدأ بوضع أهداف محددة تستند على دراسة متعمقة للسوق والخصوصيات الفريدة لفئة العملاء المستهدفة، تلي ذلك المرحلة الأساسية وهي بحث ودراسة السوق بشكل شامل للتعرف على المنافسين والاتجاهات التي يتبعها السوق. وفي ضوء هذه التحليلات، يقوم الفريق التسويقي بوضع خطة تسويقية شاملة وانطلاقًا منها يتم تصميم الحملات الإعلانية الفعالة التي تساعد في جعل منتجات الشركة أكثر جاذبية في الأسواق. وبعد تنفيذ الخطة الإعلانية، تتم مراقبة وتحليل الأداء من خلال تتبع النتائج التي تحققت، وبناء على النتائج يتم إدخال التعديلات والتغييرات اللازمة لتوجيه بذكاء الخطط والحملات التسويقية في المستقبل. إن الغاية الأساسية من هذا البحث هو توضيح أكثر استراتيجيات التسويق و معرفة الأدوات والأدوات اللازمة لوضع أهداف واضحة ومحددة وصياغة خطة تسويقية ناجحة وكذلك تتبع الأداء لضمان النجاح المستدام في السوق. سنبين من خلال هذا البحث مختلف المراحل الحيوية لاستراتيجيات التسويق، لتأهيله وتمكينه للاستخدام الأفضل للأدوات والتقنيات التسويقية المتاحة حاليًا. وضع اهداف تحديد الأهداف هو الخطوة الأولى في تطوير استراتيجية التسويق. يجب أن تكون الأهداف محددة وقابلة للقياس ويمكن تحقيقها وواقعية وفي الوقت المناسب (SMART)1. SMART: 1. Specific/محدد - الهدف يجب أن يكون واضحًا ومحددا، يجب أن يجيب عن أسئلة من النوع: من؟ ماذا؟ أين؟ متى؟ ولماذا؟ 2. Measurable/قابل للقياس - يجب أن يكون الهدف قابلًا للقياس، ويجب أن يتم تحديد مقياس يمكن تتبعه وقياسه، وذلك لتقييم التقدم والأداء. 3. Achievable/قابل للتحقيق - يجب أن يكون الهدف قابلًا للتحقيق، يجب أن يكون بمتناول يدك ومن الممكن تحقيقه ضمن الإمكانيات الحالية والقيود المتوفرة. 4. Realistic/واقعي - يجب أن يكون الهدف واقعيًا ويأخذ في الحسبان عوامل مثل الموارد المتاحة، والمهارات، والخبرة. 5. Time-bound/محدد بالوقت - يجب أن يكون الهدف محددًا بالوقت ويحتوي على موعد نهائي لإنجازه. يوفر ذلك شعورًا بالعجلة ويحفز فريقك على التركيز على المهمة المحددة. يجب أيضًا أن تتماشى مع المهمة العامة للشركة ورؤيتها. يمكن تقسيم الأهداف إلى أهداف قصيرة وطويلة المدى ، والتي يجب مراقبتها وتعديلها حسب الحاجة. بمجرد تحديد الأهداف ، فإن البحث في السوق هو الخطوة التالية. يتضمن ذلك جمع البيانات عن العملاء الحاليين للشركة والمنافسة وأي أسواق جديدة محتملة. يجب استخدام هذه البيانات لتحديد الفرص والتهديدات في السوق. بمجرد أن يتم البحث في السوق ، فإن إنشاء خطة هو الخطوة الموالية. يجب أن تتضمن الخطة وصفًا للسوق المستهدف ، والنتيجة المرجوة ، والاستراتيجيات والتكتيكات التي سيتم استخدامها لتحقيق النتيجة المرجوة. يجب أن تتضمن أيضًا ميزانية وجدولًا زمنيًا لكل إستراتيجية وتكتيك. تعد الميزانية جزءًا مهمًا من تطوير استراتيجية التسويق. فيجب إنشاء ميزانية لضمان تخصيص الموارد بأكثر الطرق فعالية. وهذا يشمل كلاً من الموارد المالية والبشرية. أخيرًا ، يعد تتبع الأداء أمرًا مهمًا من أجل مراقبة تقدم استراتيجية التسويق. يتضمن ذلك تتبع مؤشرات الأداء الرئيسية مثل المبيعات وحركة المرور على الويب وتعليقات العملاء. يمكن استخدام هذه البيانات لضبط استراتيجية التسويق حسب الحاجة من أجل تعظيم النتيجة المرجوة.
9f86c5f754c403b17751203c0ea368ca
{ "intermediate": 0.19722166657447815, "beginner": 0.4620828330516815, "expert": 0.34069550037384033 }
8,569
Multiplication This assignment asks you to write an assembly-language program that multiplies two integers. Your task is to compute $0 × $1 and store the result in $2. The result is guaranteed to be in the range 0, 1, …, 65535. Both $0 and $1 should be viewed as unsigned integers. Hints: For this exercise you want to use arithmetic instructions (such as add) to accumulate the product one addition at a time, shift instructions (such as lsl and lsr) to shift the bits in the operands, and Boolean instructions (such as ior, and, eor to set, reset, and toggle bits). If you want, it is possible to solve this exercise without comparison, branch and jump instructions. However, it is easier to use these instructions rather than avoid them. You probably want to have at least one loop that shifts the operands, and at least one conditional expression that decides whether to accumulate the product based on the bits of one operand. It may be a good idea to look at the examples of pen and paper multiplication in Round 2 to figure out what needs to be done. If all else fails, write a Scala solution first and then think how to do it in assembly language. (See further hints below.) More hints and notes: Assembly-language programming is a skill that amounts to being able to cast what you want the machine to do in terms of individual machine instructions. One instruction does not accomplish a great deal, so you must be prepared to think in very small steps what you want to be done. Before you start writing an assembly-language program to solve an assignment, it may be useful to think how you would go about solving the assignment using Scala, where you intentionally restrict yourself to using only eight variables (which imitate the eight registers of the armlet), and one array (which imitates the armlet memory). Also, it may be useful to think about a solution in Scala that uses only if-statements and while-loops in Scala, since these are easily implemented using the armlet comparison, branch, and jump instructions. (Branching and jumping is not needed for the first exercises, such as expression evaluation.) The assignment package contains a helper object launchTicker (located in armlet) that launches Ticker where you can load and execute the program to test it. Study the example code for patterns on how to program in assembly language. Make use of Ticker to debug your program. Ticker enables you to execute the program one clock tick at a time, so you can follow with minute precision what your program is actually doing. For exercises that require you to manipulate the bits in a register, observe that Ticker displays the register contents in binary (as well as in hexadecimal and decimal). Mind your registers. When writing your program, for every instruction that you write you should keep in mind exactly which register contains what value for purposes of completing the desired computation. Write comments to keep track of what your program should be doing. Then use Ticker to witness that this is actually what happens. Even with all the hints above, assembly-language programming is tedious. Yet, to be able to write efficient programs (in any programming language), there is no substitute to understanding how the machine operates and how to speak directly to the machine, in its native tongue. You will use armlet assembly. Armlet assembly instruction set: (Instructions controlling the data path) nop # no operation mov $L, $A # $L = $A (copy the value of $A to $L) and $L, $A, $B # $L = bitwise AND of $A and $B ior $L, $A, $B # $L = bitwise (inclusive) OR of $A and $B eor $L, $A, $B # $L = bitwise exclusive-OR of $A and $B not $L, $A # $L = bitwise NOT of $A add $L, $A, $B # $L = $A + $B sub $L, $A, $B # $L = $A - $B neg $L, $A # $L = -$A lsl $L, $A, $B # $L = $A shifted to the left by $B bits lsr $L, $A, $B # $L = $A shifted to the right by $B bits asr $L, $A, $B # $L = $A (arithmetically) shifted to the right by $B bits mov $L, I # $L = I (copy the immediate data I to $L) add $L, $A, I # $L = $A + I sub $L, $A, I # $L = $A - I and $L, $A, I # $L = bitwise AND of $A and I ior $L, $A, I # $L = bitwise (inclusive) OR of $A and I eor $L, $A, I # $L = bitwise exclusive OR of $A and I lsl $L, $A, I # $L = $A shifted to the left by I bits lsr $L, $A, I # $L = $A shifted to the right by I bits asr $L, $A, I # $L = $A (arithmetically) shifted to the right by I bits loa $L, $A # $L = [contents of memory word at address $A] sto $L, $A # [contents of memory word at address $L] = $A (Instruction controlling the flow of execution) cmp $A, $B # compare $A (left) and $B (right) cmp $A, I # compare $A (left) and I (right) jmp $A # jump to address $A beq $A # ... if left == right (in the most recent comparison) bne $A # ... if left != right bgt $A # ... if left > right (signed) blt $A # ... if left < right (signed) bge $A # ... if left >= right (signed) ble $A # ... if left <= right (signed) bab $A # ... if left > right (unsigned) bbw $A # ... if left < right (unsigned) bae $A # ... if left >= right (unsigned) bbe $A # ... if left <= right (unsigned) jmp I # jump to address I beq I # ... if left == right (in the most recent comparison) bne I # ... if left != right bgt I # ... if left > right (signed) blt I # ... if left < right (signed) bge I # ... if left >= right (signed) ble I # ... if left <= right (signed) bab I # ... if left > right (unsigned) bbw I # ... if left < right (unsigned) bae I # ... if left >= right (unsigned) bbe I # ... if left <= right (unsigned) hlt # halt execution Comments are made with # signs. Loops begin with the symbol @. For example @loop: ... When accessing a loop, we use > sign. For example, jmp >loop or bge >loop, ble >loop, etc Do not code hlt. It is already in the task framework.
7d208a6221a4f11f1fd161430aafb2fe
{ "intermediate": 0.49135780334472656, "beginner": 0.30052152276039124, "expert": 0.20812059938907623 }
8,570
generate a mermaid flowchart code for the main ideas in this chapter, it is talking about PESTEL and SWOT البحث في السوق يعد البحث في السوق خطوة مهمة في عملية تطوير استراتيجية التسويق. يتضمن جمع البيانات عن العملاء الحاليين للشركة والأسواق الجديدة المحتملة والمنافسة. يجب استخدام هذه البيانات لتحديد الفرص والتهديدات في السوق و العمل على تطوير الاستراتيجية. عند البحث في السوق ، من المهم مراعاة مجموعة من العوامل. يتضمن ذلك المعلومات الديموغرافية حول الفئة المستهدفة ، مثل العمر والجنس ومستوى الدخل. كما يتضمن معلومات نفسية ، مثل المواقف والقيم ونمط الحياة. بالإضافة إلى ذلك ، يجب أن يتضمن البحث في السوق تحليلاً للمنافسة والأسواق الجديدة المحتملة. عند البحث عن المنافسة ، من المهم مراعاة عوامل مثل التسعير وعروض المنتجات وقنوات التسويق. بالإضافة إلى ذلك ، من المهم فهم نقاط القوة والضعف في المنافسة من أجل تحديد مجالات الميزة المحتملة. عند البحث عن أسواق جديدة محتملة ، من المهم مراعاة عوامل مثل حجم السكان والنمو الاقتصادي والقوة الشرائية. بالإضافة إلى ذلك ، من المهم فهم الاتجاهات الثقافية والاجتماعية في السوق المستهدفة من أجل تحديد الفرص المحتملة للأعمال التجارية. من المهم أيضًا مراعاة البيئة القانونية والتنظيمية في السوق المستهدفة. يتضمن ذلك فهم أي قيود أو متطلبات تتعلق بالإعلان وتغليف المنتج والتسعير.3
5f3c07d609ff28b17f3d3fe32f594e11
{ "intermediate": 0.21453899145126343, "beginner": 0.46653780341148376, "expert": 0.3189232647418976 }
8,571
write for me a mermaid flowchart in mindmap style with the main informations from: تتبع الأداء يعد تتبع الأداء جزءًا مهمًا من أي استراتيجية عمل ناجحة. من خلال تتبع الأداء ، يمكن للشركات تتبع التقدم وتحديد مجالات التحسين وإجراء التعديلات حسب الحاجة. يجب أن يشمل تتبع الأداء كلاً من المقاييس الكمية والنوعية ، كما يجب أن يأخذ في الاعتبار العوامل الخارجية مثل المشهد التنافسي. يجب أن تتضمن مقاييس تتبع الأداء الكمي مؤشرات الأداء الرئيسية (KPIs) ، وهي مقاييس محددة تستخدم لقياس التقدم والنجاح. يجب أن تكون هذه المقاييس مصممة خصيصًا لأهداف العمل ، ويجب تتبعها على أساس منتظم. 1 تتضمن أمثلة مؤشرات الأداء الرئيسية رضا العملاء والمبيعات وحركة مرور موقع الويب وتكلفة الاكتساب. من المهم أيضًا مراعاة الإطار الزمني عند تتبع الأداء ، حيث أن الأداء قصير المدى لا يشير بالضرورة إلى النجاح على المدى الطويل. يجب أن تتضمن مقاييس تتبع الأداء النوعي ملاحظات العملاء وتعليقات الموظفين وأبحاث الصناعة. تعتبر ملاحظات العملاء مهمة لأنها توفر نظرة ثاقبة حول كيفية إدراك العملاء للأعمال ومنتجاتها أو خدماتها. تعتبر ملاحظات الموظف مهمة لأنها توفر نظرة ثاقبة حول شعور الموظفين تجاه الأعمال ومنتجاتها أو خدماتها وبيئة العمل الخاصة بها. عند تتبع الأداء ، من المهم أيضًا مراعاة العوامل الخارجية مثل المشهد التنافسي والظروف الاقتصادية والتغييرات في تفضيلات العملاء. يمكن أن يكون لهذه العوامل تأثير كبير على الأداء ويجب أخذها في الاعتبار عند اتخاذ القرارات. بالإضافة إلى ذلك ، من المهم النظر في تكلفة تتبع الأداء ، حيث يمكن أن يزيد ذلك بسرعة إذا تم استخدام الأدوات الخاطئة. في الختام ، يعد تتبع الأداء جزءًا مهمًا من أي استراتيجية عمل ناجحة. من خلال تتبع الأداء ، يمكن للشركات تتبع التقدم وتحديد مجالات التحسين وإجراء التعديلات حسب الحاجة. يجب أن يشمل تتبع الأداء كلاً من المقاييس الكمية والنوعية ، كما يجب أن يأخذ في الاعتبار العوامل الخارجية مثل المشهد التنافسي. بالإضافة إلى ذلك ، من المهم مراعاة تكلفة تتبع الأداء والإطار الزمني عند اتخاذ القرارات. في الختام ، يتطلب تطوير استراتيجية تسويق ناجحة دراسة متأنية لجميع الخطوات المتضمنة ، من تحديد الأهداف والبحث في السوق إلى إنشاء خطة وميزنة وتتبع الأداء. كل خطوة ضرورية لضمان نجاح الإستراتيجية ، ويجب إعطاء كل خطوة الاهتمام والموارد اللازمة. 2 بالإضافة إلى ذلك ، من المهم أن تظل مرنًا وأن تعدل الإستراتيجية حسب الحاجة من أجل الاستفادة من الفرص الجديدة والاستجابة للتغيرات في السوق. من خلال النهج الصحيح والتفاني ، يمكن للشركات استخدام هذه الخطوات لتطوير استراتيجية تسويق ناجحة ستساعدهم في الوصول إلى أهدافهم والبقاء في صدارة المنافسة.
e4c5012f15c67c025f476288cbe8de3d
{ "intermediate": 0.3045346438884735, "beginner": 0.3962523341178894, "expert": 0.2992129921913147 }
8,572
Problem: I am building my website using Sveltekit / svelte and it does not allow two script tags. Create a component that loads the Native Shopping ad in the location it is placed as a component and allow for the default_search_phrase to be changed. Native Shopping Ads for Amazon Associates: <script type=“text/javascript”> amzn_assoc_placement = “adunit0”; amzn_assoc_search_bar = “false”; amzn_assoc_tracking_id = “aigiftguru-20”; amzn_assoc_ad_mode = “search”; amzn_assoc_ad_type = “smart”; amzn_assoc_marketplace = “amazon”; amzn_assoc_region = “US”; amzn_assoc_title = “Shop Related Products”; amzn_assoc_default_search_phrase = “gift”; amzn_assoc_default_category = “All”; amzn_assoc_linkid = “a7f2ea8b1dcf7f4d6132f79fe5cbd157”; </script> <script src=“//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US”></script>
3dd8b3300261be400ef4497ae01fe9cf
{ "intermediate": 0.43899989128112793, "beginner": 0.2835387885570526, "expert": 0.27746129035949707 }
8,573
What 10/2 plus 5 minus 2.6975
83d7e59e642d476c2ff514b3f845d133
{ "intermediate": 0.347428560256958, "beginner": 0.3074004054069519, "expert": 0.34517109394073486 }
8,574
# Оптимизированный Возращает адреса созданных токенов в указанном интревале блоков (Обрабатывет по одному блоку) import asyncio import requests import aiohttp bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' # Modify the existing functions to use async and aiohttp… async def get_external_transactions(block_number): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return [] if data['result'] is None: print(f"Error: Cannot find the block") return [] return data['result']['transactions'] async def get_contract_address(tx_hash): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return None if data['result'] is None: return None return data['result']['contractAddress'] async def display_transactions(block_start, block_end): for block_number_int in range(block_start, block_end + 1): block_number = hex(block_number_int) transactions = await get_external_transactions(block_number) # Add the ‘await’ keyword here if not transactions: print(f'No transactions found in block {block_number_int}') else: print(f'Transactions in block {block_number_int}:') for tx in transactions: if tx['to'] is None: contract_address = await get_contract_address(tx['hash']) print(f"New contract creation: Contract Address: {contract_address}") print("\n") # Print an empty line between blocks async def main(): block_start = 28558222 # Replace with your desired starting block number block_end = 28559243 # Replace with your desired ending block number await display_transactions(block_start, block_end) asyncio.run(main()) Change the above code to fix the errors reflected in the answer Traceback (most recent call last): File "C:\Users\AshotxXx\PycharmProjects\pythonProject20\main.py", line 66, in <module> asyncio.run(main()) File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\pythonProject20\main.py", line 64, in main await display_transactions(block_start, block_end) File "C:\Users\AshotxXx\PycharmProjects\pythonProject20\main.py", line 48, in display_transactions transactions = await get_external_transactions(block_number) # Add the ‘await’ keyword here ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\pythonProject20\main.py", line 26, in get_external_transactions return data['result']['transactions'] ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^ TypeError: string indices must be integers, not 'str' Process finished with exit code 1
947e244770d67d3596016efe4851de9e
{ "intermediate": 0.30571699142456055, "beginner": 0.6040784120559692, "expert": 0.09020459651947021 }
8,575
Are you Chatgpt 4
9bec11db67749b95f75b6d3218f3f855
{ "intermediate": 0.35579994320869446, "beginner": 0.27074170112609863, "expert": 0.3734583258628845 }
8,576
Create user USER3, add it to the system predefined server role sysadmin, and test the permissions obtained by USER3
adab05a94b691f1c4b14b87790d9ad6c
{ "intermediate": 0.365995854139328, "beginner": 0.2300020307302475, "expert": 0.4040021598339081 }
8,577
I have a few images that has some random letters and numbers (total length is 5). white background and black text and a horizontal line goes through the text. I want to remove that line from each of the images in C#.
c26d61d6499e0eb9e0495ddc1848ed71
{ "intermediate": 0.32932430505752563, "beginner": 0.2474791258573532, "expert": 0.42319655418395996 }
8,578
how to cascading revoke permission in sql server
8f680e73ebb5dd645cdf13fdd463ef26
{ "intermediate": 0.36662840843200684, "beginner": 0.24851670861244202, "expert": 0.38485485315322876 }
8,579
Explain the flexbox order property.
3b6fc040863f2161787331697aa51b79
{ "intermediate": 0.4046233296394348, "beginner": 0.21419373154640198, "expert": 0.3811829686164856 }
8,580
an simple example here,can we do the query below to cascadingly revoke the permission to create tables passed by the user to other users? query: revoke create table from USER2 cascade
df7f8ab79c05678f008aab933810e527
{ "intermediate": 0.5348420739173889, "beginner": 0.2497979998588562, "expert": 0.2153598815202713 }
8,581
What are some home networking uses for a raspberry pi 4? I have already configured pi-hole and will be configuring it as a dynamic DNS updater for my network. I have several cloudflare domains
73f77fe4373bd07a058fa7d7907f5eb2
{ "intermediate": 0.37739893794059753, "beginner": 0.34331610798835754, "expert": 0.2792850136756897 }
8,582
Исправь этот код, чтобы он стал примером паттерна Хранитель (Memento) class Audioplayer { public double Position { get; set; } private bool playing = false; public string path { get; set; } public void Play(double? position) { if (path != null) { playing = true; if (position.HasValue) { //playfromposition } else { //playfromthis.position } } } public void Pause() { playing = false; //playerpause } public Point CloseApp() { return new Point(Position, path); } public void GetLastPlayed(Point point) { this.Position = point.Seconds; this.path = point.Path; } } class LastPlayed { public Point point { get; set; } public LastPlayed() { point = new Point(); } } public class Point { public double Seconds { get; private set; } public string Path { get; private set; } public Point(double seconds, string path) { this.Seconds = seconds; this.Path = path; } }
8ae5f7d411a5ac61123a46aec45f6450
{ "intermediate": 0.27110880613327026, "beginner": 0.5376243591308594, "expert": 0.1912667453289032 }
8,583
Setup golang to implement aws lambda function and api gateway proxy
02f78cf2e5d382238302f04de02e14bf
{ "intermediate": 0.6860070824623108, "beginner": 0.1695970892906189, "expert": 0.1443958282470703 }
8,584
Why does my NekoCat const keep rerendering every time I move the character? I want to be able to have the component fly around the screen without rerendering while i move the character, the inner box import Head from "next/head"; import Image from "next/image"; import React, { useState, useEffect } from "react"; import { Leaderboard } from "./leaderboard.js"; import { AaveStake } from "./aaveStake.js"; import SwapPoolView from "./swapPoolView.js"; import StickyBoard from "./stickyNotes.js"; import leftImage from "../public/assets/left.gif"; import rightImage from "../public/assets/right.gif"; import idleImage from "../public/assets/idle.gif"; import downImage from "../public/assets/down.gif"; import upImage from "../public/assets/up.gif"; import worker from "../public/assets/worker.gif"; import { useMoralis, useWeb3Contract } from "react-moralis"; const BOX_COLOR = "#ccc"; const INNER_BOX_SIZE = 70; const INNER_BOX_COLOR = "blue"; const KEY_CODES = { UP: 38, LEFT: 37, DOWN: 40, RIGHT: 39, }; const OBSTACLE_WIDTH = 75; const OBSTACLE_HEIGHT = 300; const BOARD_WIDTH = 230; const BOARD_HEIGHT = 50; export default function Game() { const { enableWeb3, authenticate, account, isWeb3Enabled } = useMoralis(); useEffect(() => { enableWeb3(); }, []); /////////////////// LOGIN////////////////// // const [showLogin, setShowLogin] = useState(true); // const Login = () => { // return ( // <div style={{color:"white"}}className="container"> // <h1> Login </h1> // Please connect your wallet to continue // <button onClick={() => setShowLogin(false)}> Login </button> // </div> // ); // }; /////////////////////GAME CODE //////////////////// const [innerBoxPosition, setInnerBoxPosition] = useState({ top: 500, left: 255, }); // const [showDEX, setShowDEX] = useState(false); // const [showBoard, setShowBoard] = useState(false); // const [showDEXText, setShowDEXText] = useState(false); // const [showBoardText, setShowBoardText] = useState(false); const [direction, setDirection] = useState("left"); // const [collision, setCollision] = useState(false); const [showControls, setShowControls] = useState(true); const [showRoom1, setShowRoom1] = useState(true); const [showRoom2, setShowRoom2] = useState(false); const [isIdle, setIsIdle] = useState(true); const getImage = () => { if (isIdle) { return idleImage; } else { switch (direction) { case "left": return leftImage; case "right": return rightImage; case "up": return upImage; case "down": return downImage; default: return idleImage; } } }; useEffect(() => { const interval = setInterval(() => { setIsIdle(true); }, 300); return () => clearInterval(interval); }, [innerBoxPosition]); /////////////////////////ROOM 1////////////////////////////// const Room1 = () => { const [showDEX, setShowDEX] = useState(false); const [showBoard, setShowBoard] = useState(false); const [showDEXText, setShowDEXText] = useState(false); const [showBoardText, setShowBoardText] = useState(false); // const [nekoText, setNekoText] = useState(false); // const [showNeko, setShowNeko] = useState(false); const [usingModal, setUsingModal] = useState(false); const BOX_HEIGHT = 600; const BOX_WIDTH = 800; useEffect(() => { function handleKeyPress(event) { const { keyCode } = event; const { top, left } = innerBoxPosition; const maxTop = BOX_HEIGHT - INNER_BOX_SIZE; const maxLeft = BOX_WIDTH - INNER_BOX_SIZE; const minTop = 30; // 30 is the height of the top bar const minLeft = 0; // 0 is the left position of the left bar if (!usingModal) { switch (keyCode) { case KEY_CODES.UP: setInnerBoxPosition({ top: Math.max(minTop + 140, top - 10), left, }); setDirection("up"); setIsIdle(false); setShowControls(false); break; case KEY_CODES.LEFT: setInnerBoxPosition({ top, left: Math.max(minLeft + 185, left - 10), }); setDirection("left"); setIsIdle(false); setShowControls(false); break; case KEY_CODES.DOWN: setInnerBoxPosition({ top: Math.min(maxTop, top + 10), left }); setDirection("down"); setIsIdle(false); setShowControls(false); break; case KEY_CODES.RIGHT: setInnerBoxPosition({ top, left: Math.min(maxLeft, left + 10) }); setDirection("right"); setIsIdle(false); setShowControls(false); break; default: setIsIdle(true); break; } } } window?.addEventListener("keydown", handleKeyPress); return () => { window?.removeEventListener("keydown", handleKeyPress); }; }, [innerBoxPosition]); useEffect(() => { function checkCollision() { const innerBoxRect = document .querySelector(".inner-box") .getBoundingClientRect(); const obstacleRect = document .querySelector(".obstacle") .getBoundingClientRect(); const boardRect = document .querySelector(".board") .getBoundingClientRect(); const table1Rect = document .querySelector(".table1") .getBoundingClientRect(); const leaveRoomRect1 = document .querySelector(".leaveRoom1") .getBoundingClientRect(); // const catRect = document.querySelector(".neko").getBoundingClientRect(); if ( !showDEX && !showBoard && innerBoxRect.left < obstacleRect.right && innerBoxRect.right > obstacleRect.left && innerBoxRect.top < obstacleRect.bottom && innerBoxRect.bottom > obstacleRect.top ) { console.log("testing"); setShowBoardText(false); setShowDEXText(true); } if ( !showDEX && !showBoard && innerBoxRect.left < obstacleRect.right && innerBoxRect.right > obstacleRect.left && innerBoxRect.top < obstacleRect.bottom && innerBoxRect.bottom > obstacleRect.top ) { console.log("testing"); setShowBoardText(false); setShowDEXText(true); } if ( !showDEX && !showBoard && innerBoxRect.left < boardRect.right && innerBoxRect.right > boardRect.left && innerBoxRect.top < boardRect.bottom && innerBoxRect.bottom > boardRect.top ) { setShowDEXText(false); setShowBoardText(true); } if ( innerBoxRect.left < table1Rect.right && innerBoxRect.right > table1Rect.left && innerBoxRect.top < table1Rect.bottom && innerBoxRect.bottom > table1Rect.top ) { } if ( innerBoxRect.left < leaveRoomRect1.right && innerBoxRect.right > leaveRoomRect1.left && innerBoxRect.top < leaveRoomRect1.bottom && innerBoxRect.bottom > leaveRoomRect1.top ) { setShowRoom1(false); setShowRoom2(true); setInnerBoxPosition({ top: 400, left: 20 }); console.log("leave room 1"); } // if ( // innerBoxRect.left < catRect.right && // innerBoxRect.right > catRect.left && // innerBoxRect.top < catRect.bottom && // innerBoxRect.bottom > catRect.top // ) { // setNekoText(true); // } // if ( // !( // innerBoxRect.left < catRect.right && // innerBoxRect.right > catRect.left && // innerBoxRect.top < catRect.bottom && // innerBoxRect.bottom > catRect.top // ) // ) { // setNekoText(false); // setShowNeko(false); // } if ( !showDEX && !showBoard && innerBoxRect.left < obstacleRect.right && innerBoxRect.right > obstacleRect.left && innerBoxRect.top < obstacleRect.bottom && innerBoxRect.bottom > obstacleRect.top ) { setShowBoardText(false); setShowDEXText(true); } if ( !( innerBoxRect.left - 30 < obstacleRect.right && innerBoxRect.right + 30 > obstacleRect.left && innerBoxRect.top - 30 < obstacleRect.bottom && innerBoxRect.bottom + 30 > obstacleRect.top ) ) { setShowDEXText(false); } if ( !( innerBoxRect.left - 30 < boardRect.right && innerBoxRect.right + 30 > boardRect.left && innerBoxRect.top - 30 < boardRect.bottom && innerBoxRect.bottom + 30 > boardRect.top ) ) { setShowBoardText(false); } } checkCollision(); }, [innerBoxPosition]); function showDexFunc() { setShowDEX(true); setShowDEXText(false); } function showBoardFunc() { setShowBoard(true); setShowBoardText(false); } // function Neko() { // setNekoText(false); // setShowNeko(true); // } const DisplayControls = () => { return ( <div className="infoPanelControls"> <div className="typedOutInfo"> <p> Use the arrow keys <br /> to move around </p> </div> </div> ); }; return ( <div className="container"> <div className="box" style={{ height: BOX_HEIGHT, width: BOX_WIDTH, }} > <div className="bottom-right-div"></div> <div className={`inner-box ${direction}`} style={{ height: INNER_BOX_SIZE, width: INNER_BOX_SIZE, backgroundImage: `url(${getImage().src})`, top: innerBoxPosition.top, left: innerBoxPosition.left, backgroundPosition: "0 -10px", }} ></div> <div className="obstacle" style={{ height: OBSTACLE_HEIGHT, width: OBSTACLE_WIDTH, }} ></div> <div className="board" style={{ height: BOARD_HEIGHT, width: BOARD_WIDTH, }} ></div> {showControls && <DisplayControls />} {showDEXText && ( <div className="textBox"> <div className="typedOutWrapper"> <div className="typedOut"> Hello, would you like to access our DEX? </div>{" "} </div> <div className="textSelect" onClick={() => showDexFunc(true)}> {" "} Okay{" "} </div> <div className="textSelect2" onClick={() => setShowDEXText(false)} > {" "} No thanks{" "} </div> </div> )} {showBoardText && ( <div className="textBox"> <div className="typedOutWrapper"> <div className="typedOut">View the sticky notes?</div> </div> <div className="textSelect" onClick={() => showBoardFunc(true)}> {" "} Okay{" "} </div> <div className="textSelect2" onClick={() => setShowBoardText(false)} > {" "} No thanks{" "} </div> </div> )} {/* {nekoText && ( <div className="textBox"> <div className="typedOutWrapper"> <div className="typedOut"> View the leaderboard?</div>{" "} </div> <div className="textSelect" onClick={() => Neko()}> {" "} Okay{" "} </div> <div className="textSelect2" onClick={() => setNekoText(false)}> {" "} No thanks{" "} </div>{" "} </div> )} */} <div className="table1" /> <div className="table2" /> <div className="leaveRoom1"></div> </div> {showDEX && ( <div className="modal"> <div className="modal-content" style={{ position: "relative", }} > <> <SwapPoolView /> </> <button className="modalButton" style={{ position: "absolute", right: "5%", bottom: "10px", zIndex: "999", }} onClick={() => setShowDEX(false)} > Close </button> </div> </div> )} {showBoard && ( <> <div className="modal"> <div style={{ border: "10px solid #954434", background: "#ECA97C", borderRadius: "0", }} className="modal-content" > <StickyBoard /> <button className="modalButton" style={{ zIndex: 11, position: "absolute", bottom: "26%", right: "33%", }} onClick={() => setShowBoard(false)} > Close </button> </div> </div> </> )} {/* {showNeko && ( <> <div className="modal"> <div className="modal-content"> <Leaderboard /> <button className="modalButton" onClick={() => setShowNeko(false)} > Close </button> </div> </div> </> )} */} {/* <Image className="neko" src="https://66.media.tumblr.com/tumblr_ma11pbpN0j1rfjowdo1_500.gif" width={400} height={500} alt="neko" /> */} {/* <Image className="worker" src={worker} alt="worker" /> */} </div> ); }; /////////////////////////ROOM 2////////////////////////////// const Room2 = () => { const BOX_HEIGHT = 600; const BOX_WIDTH = 800; const [nekoText, setNekoText] = useState(false); const [showStaking, setShowStaking] = useState(false); const [showNeko, setShowNeko] = useState(false); const [inModal, setInModal] = useState(false); const [stakeText, setStakeText] = useState(false); useEffect(() => { function handleKeyPress(event) { const { keyCode } = event; const { top, left } = innerBoxPosition; const maxTop = BOX_HEIGHT - INNER_BOX_SIZE; const maxLeft = BOX_WIDTH - INNER_BOX_SIZE; const minTop = 160; const minLeft = 0; switch (keyCode) { case KEY_CODES.UP: setInnerBoxPosition({ top: Math.max(minTop, top - 10), left }); setDirection("up"); setIsIdle(false); break; case KEY_CODES.LEFT: setInnerBoxPosition({ top, left: Math.max(minLeft, left - 10), }); setDirection("left"); setIsIdle(false); break; case KEY_CODES.DOWN: setInnerBoxPosition({ top: Math.min(maxTop, top + 10), left }); setDirection("down"); setIsIdle(false); break; case KEY_CODES.RIGHT: setInnerBoxPosition({ top, left: Math.min(maxLeft, left + 10) }); setDirection("right"); setIsIdle(false); break; setIsIdle(true); break; } } window?.addEventListener("keydown", handleKeyPress); return () => { window?.removeEventListener("keydown", handleKeyPress); }; }, [innerBoxPosition]); function Neko() { setNekoText(false); setShowNeko(true); } function Stake() { setStakeText(false); setShowStaking(true); } useEffect(() => { function checkCollision() { const innerBoxRect = document .querySelector(".inner-box") .getBoundingClientRect(); const leaveRoom2 = document .querySelector(".leaveRoom2") .getBoundingClientRect(); const aaveStake = document .querySelector(".aaveStake") .getBoundingClientRect(); const catRect = document.querySelector(".neko").getBoundingClientRect(); const stakeRect = document .querySelector(".aaveStake") .getBoundingClientRect(); if ( innerBoxRect.left + 50 < leaveRoom2.right && innerBoxRect.right < leaveRoom2.left + 170 && innerBoxRect.top < leaveRoom2.bottom && innerBoxRect.bottom > leaveRoom2.top ) { setShowRoom2(false); setShowRoom1(true); setInnerBoxPosition({ top: 230, left: 600 }); console.log("leave room 2"); } if ( innerBoxRect.left < catRect.right && innerBoxRect.right > catRect.left && innerBoxRect.top < catRect.bottom && innerBoxRect.bottom > catRect.top ) { setNekoText(true); } if ( !( innerBoxRect.left < catRect.right && innerBoxRect.right > catRect.left && innerBoxRect.top < catRect.bottom && innerBoxRect.bottom > catRect.top ) ) { setNekoText(false); setShowNeko(false); } if ( innerBoxRect.left < stakeRect.right && innerBoxRect.right > stakeRect.left && innerBoxRect.top < stakeRect.bottom && innerBoxRect.bottom > stakeRect.top ) { setStakeText(true); } if ( !( innerBoxRect.left < stakeRect.right && innerBoxRect.right > stakeRect.left && innerBoxRect.top < stakeRect.bottom && innerBoxRect.bottom > stakeRect.top ) ) { setStakeText(false); setShowStaking(false); } } checkCollision(); }, [innerBoxPosition]); return ( <div className="container"> <div className="box2" style={{ height: BOX_HEIGHT, width: BOX_WIDTH }}> <div className="leaveRoom2"> <span> <span style={{ fontSize: "1.8rem", fontWeight: "bold", }} ></span> </span> </div> <div className={`inner-box ${direction}`} style={{ height: INNER_BOX_SIZE, width: INNER_BOX_SIZE, backgroundImage: `url(${getImage().src})`, top: innerBoxPosition.top, left: innerBoxPosition.left, backgroundPosition: "0 -10px", }} ></div> <div className="aaveStake" /> {nekoText && ( <div className="textBox"> <div className="typedOutWrapper"> <div className="typedOut"> View the leaderboard?</div>{" "} </div> <div className="textSelect" onClick={() => Neko()}> {" "} Okay{" "} </div> <div className="textSelect2" onClick={() => setNekoText(false)}> {" "} No thanks{" "} </div>{" "} </div> )} {showNeko && ( <> <div style={{ marginTop: "0px" }} className="modal"> <div className="modal-content"> <Leaderboard /> <button className="modalButton" onClick={() => setShowNeko(false)} style={{ position: "absolute", right: "11%", bottom: "12%", zIndex: "999", }} > Close </button> </div> </div> </> )} <Image className="neko" src="https://66.media.tumblr.com/tumblr_ma11pbpN0j1rfjowdo1_500.gif" width={400} height={500} alt="neko" /> <div className="aaveStakeCat" /> <img style={{position: "absolute", bottom: "280px", right: "175px", width: "40px", height: "40px", zIndex: "999"}} src="https://i.pinimg.com/originals/80/7b/5c/807b5c4b02e765bb4930b7c66662ef4b.gif" /> <div className="nekoSparkle"/> {showStaking && ( <> <button className="modalButton" onClick={() => setShowStaking(false)} style={{ position: "absolute", right: "11%", bottom: "8%", zIndex: "999", }} > Close </button>{" "} <AaveStake /> </> )} {stakeText && ( <div className="textBox"> <div className="typedOutWrapper"> <div className="typedOut"> Look at the staking screen?</div>{" "} </div> <div className="textSelect" onClick={() => Stake()}> {" "} Okay{" "} </div> <div className="textSelect2" onClick={() => setStakeText(false)}> {" "} No thanks{" "} </div>{" "} </div> )} <NyanCat/> </div> </div> ); }; ////////////////////// RETURN ////////////////////////////// return ( <> {showRoom1 && <Room1 />} {showRoom2 && <Room2 />} </> ); } const NyanCat = () => { return( <div className="nyanCat"> </div> ) }
d66724ab099f2bc3a65c00698e2f90d4
{ "intermediate": 0.42515209317207336, "beginner": 0.42992502450942993, "expert": 0.14492282271385193 }
8,585
Modify the code below to process blocks and return addresses in real time # Оптимизированный!!! Возращает адреса созданных токенов в указанном интревале блоков (Обрабатывет множество) # Ограничение до 5 запросов в секунду import asyncio import aiohttp bscscan_api_key = ‘CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS’ # Create a semaphore with a limit of n semaphore = asyncio.Semaphore(3) async def get_external_transactions(block_number): async with semaphore: async with aiohttp.ClientSession() as session: url = f’https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}‘ try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f’Error in API request: {e}’) return [] if data[‘result’] is None or isinstance(data[‘result’], str): print(f"Error: Cannot find the block") return [] return data[‘result’].get(‘transactions’, []) async def get_contract_address(tx_hash): async with semaphore: async with aiohttp.ClientSession() as session: url = f’https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}‘ try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f’Error in API request: {e}’) return None if data[‘result’] is None or not isinstance(data[‘result’], dict): return None return data[‘result’].get(‘contractAddress’) async def display_transactions(block_start, block_end): async def process_block(block_number_int): block_number = hex(block_number_int) transactions = await get_external_transactions(block_number) if not transactions: print(f’No transactions found in block {block_number_int}‘) else: print(f’Transactions in block {block_number_int}:’) for tx in transactions: if tx[‘to’] is None: contract_address = await get_contract_address(tx[‘hash’]) if contract_address: print(f’New contract creation: Contract Address: {contract_address}') print(“\n”) # Print an empty line between blocks tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)] await asyncio.gather(*tasks) async def main(): block_start = 28558222 # Replace with your desired starting block number block_end = 28559243 # Replace with your desired ending block number await display_transactions(block_start, block_end) asyncio.run(main())
b969e39bb40d77fe4e5c6a21f0b6814c
{ "intermediate": 0.351855993270874, "beginner": 0.3797559142112732, "expert": 0.268388032913208 }
8,586
write a demo code for me which read json strings from all files in a directory.
b9f33e43706c65534336aa0ca91e2333
{ "intermediate": 0.5514156222343445, "beginner": 0.13044029474258423, "expert": 0.3181440234184265 }
8,587
error during connect: this error may indicate that the docker daemon is not running: Get "http://%2F%2F.%2Fpipe%2Fdocker_engine/_ping": open //./pipe/docker_engine: The system cannot find the file specified
bfe136f96264b0cb738519744e40d687
{ "intermediate": 0.3757946193218231, "beginner": 0.2840493321418762, "expert": 0.34015607833862305 }
8,588
using a bash script on arch linux how can i add non steam game artwork to my shortcuts ive created heres my code i also want it auto matic ..also how can i force a entry to use fforce compatability?
f6197e90db5b52c59a9f737e94091686
{ "intermediate": 0.576139509677887, "beginner": 0.22855742275714874, "expert": 0.1953030526638031 }
8,589
how to start mongodb in kali linux
7e73368188be771e2fd504d0a910bd38
{ "intermediate": 0.499540239572525, "beginner": 0.13546401262283325, "expert": 0.3649957478046417 }
8,590
offer me a batexefile whith would obtain router s system time and date to my computer
015c16125832426c37211215f75c90ce
{ "intermediate": 0.43646663427352905, "beginner": 0.21757149696350098, "expert": 0.34596189856529236 }
8,591
есть код для мультиклассовой классификации import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences max_len = 600 # максимальная длина последовательности num_classes = 13 # число классов для классификации # создаем токенизатор tokenizer = Tokenizer() tokenizer.fit_on_texts(train_df['text']) # преобразуем текст в последовательность чисел train_sequences = tokenizer.texts_to_sequences(train_df['text']) test_sequences = tokenizer.texts_to_sequences(test_df['text']) val_sequences = tokenizer.texts_to_sequences(val_df['text']) # добавляем паддинг train_sequences = pad_sequences(train_sequences, maxlen=max_len) test_sequences = pad_sequences(test_sequences, maxlen=max_len) val_sequences = pad_sequences(val_sequences, maxlen=max_len) # создаем модель seq2seq input_dim = len(tokenizer.word_index) + 1 embedding_dim = 50 model = keras.Sequential([ layers.Embedding(input_dim=input_dim, output_dim=embedding_dim, input_length=max_len), layers.LSTM(units=64, dropout=0.2, recurrent_dropout=0.2), layers.Dense(num_classes, activation='softmax') ]) model.summary() # выводим информацию о модели from sklearn.metrics import f1_score import tensorflow.keras.backend as K from tensorflow.keras.losses import CategoricalCrossentropy import numpy as np from keras import backend as K def recall_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def f1_m(y_true, y_pred): precision = precision_m(y_true, y_pred) recall = recall_m(y_true, y_pred) return 2*((precision*recall)/(precision+recall+K.epsilon())) #model.compile(loss=CategoricalCrossentropy(), optimizer='adam', metrics=['acc',f1_m,precision_m, recall_m]) model.compile(loss=CategoricalCrossentropy(), optimizer='adam', metrics=['acc',f1_m,precision_m, recall_m]) history = model.fit(train_sequences, train_df['category'], epochs=10, batch_size=1000, validation_data=(val_sequences, val_df['category'])) ---> 32 history = model.fit(train_sequences, train_df['category'], 33 epochs=10, batch_size=1000, 34 validation_data=(val_sequences, val_df['category'])) ValueError: Shapes (None, 1) and (None, 13) are incompatible
fb9da620fc3438106a4b5451e242208e
{ "intermediate": 0.2821531891822815, "beginner": 0.37409237027168274, "expert": 0.34375450015068054 }
8,592
Method tx['input'][-3:] == '040' and tx['input'][-3:].lower() == '040', tx['input'][-3:] .lower().endswith('040') and re.search(r'040$', tx['input'].lower()) don't work. They process blocks but cannot return addresses.
48268ad73a7d2acbf491b02ac23e6231
{ "intermediate": 0.4385635256767273, "beginner": 0.20212307572364807, "expert": 0.359313428401947 }
8,593
how can i log in into wolf.live using WolfLive.Api for C#? note that this website now only works with 2Outh apps like google, facebook, twitter not the regular "Email,Password" log in. notice that the developer said this :"" when asked about 2Outh connection. so now i need to log in with my google API_key, which is "AIzaSyBIz668b10qt0GsmmyrkZD340w8GYTb6x8"
44960058668f832b828e4908a8fd4156
{ "intermediate": 0.6069784164428711, "beginner": 0.19222286343574524, "expert": 0.20079876482486725 }
8,594
есть код для многоклассовой классификации from sklearn.model_selection import train_test_split # разбиваем выборку на тренировочную и тестовую train_df, test_df = train_test_split(train_data, test_size=0.2, random_state=42) # разбиваем тестовую выборку на тестовую и валидационную test_df, val_df = train_test_split(test_df, test_size=0.5, random_state=42) import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences max_len = 600 # максимальная длина последовательности num_classes = 13 # число классов для классификации # создаем токенизатор tokenizer = Tokenizer() tokenizer.fit_on_texts(train_df['text']) # преобразуем текст в последовательность чисел train_sequences = tokenizer.texts_to_sequences(train_df['text']) test_sequences = tokenizer.texts_to_sequences(test_df['text']) val_sequences = tokenizer.texts_to_sequences(val_df['text']) # добавляем паддинг train_sequences = pad_sequences(train_sequences, maxlen=max_len) test_sequences = pad_sequences(test_sequences, maxlen=max_len) val_sequences = pad_sequences(val_sequences, maxlen=max_len) # создаем модель seq2seq input_dim = len(tokenizer.word_index) + 1 embedding_dim = 50 model = keras.Sequential([ layers.Embedding(input_dim=input_dim, output_dim=embedding_dim, input_length=max_len), layers.LSTM(units=64, dropout=0.2, recurrent_dropout=0.2), layers.Dense(num_classes, activation='softmax') ]) model.summary() # выводим информацию о модели from sklearn.metrics import f1_score import tensorflow.keras.backend as K from tensorflow.keras.losses import CategoricalCrossentropy import numpy as np from keras import backend as K def recall_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def f1_m(y_true, y_pred): precision = precision_m(y_true, y_pred) recall = recall_m(y_true, y_pred) return 2*((precision*recall)/(precision+recall+K.epsilon())) #model.compile(loss=CategoricalCrossentropy(), optimizer='adam', metrics=['acc',f1_m,precision_m, recall_m]) model.compile(loss=CategoricalCrossentropy(), optimizer='adam', metrics=['acc',f1_m,precision_m, recall_m]) history = model.fit(train_sequences, train_df['category'], epochs=10, batch_size=1000, validation_data=(val_sequences, val_df['category'])) ValueError: Shapes (None, 1) and (None, 13) are incompatible
d002ff6dc3593f0de18584a7ead9588d
{ "intermediate": 0.30352523922920227, "beginner": 0.4215943217277527, "expert": 0.27488046884536743 }
8,595
This is an incomplete version of a script, discover what's wrong with it and fix it to make a functional script. and then convert it to python. "<# Credit Card Bruteforcer by Apoorv Verma [AP] #> param ( [int]$NumCards = 10, [int]$MaxPin = 9999, [Parameter(ValueFromPipeline=$TRUE)] $Hashes ) function GenerateCardNumber() { $digits = 16..1 | ForEach-Object { Get-Random -Minimum 0 -Maximum 10 } $sum = 0 $digitCount = 0 foreach ($digit in $digits) { $digitCount++ $doubledDigit = $digit * 2 $sum += if ($doubledDigit -gt 9) { $doubledDigit - 9 } else { $doubledDigit } if ($digitCount % 2 -eq 0) { $sum += $digit } } $checkDigit = (10 - ($sum % 10)) % 10 $digits += $checkDigit return [string]::Join("", $digits) } $cardNumbers = 1..$NumCards | ForEach-Object { GenerateCardNumber } $pinAttempts = 0 foreach ($cardNumber in $cardNumbers) { Write-Host "Testing card number $cardNumber" for ($pin = 0; $pin -le $MaxPin; $pin++) { $pinAttempts++ $hashedPin = [System.Text.Encoding]::UTF8.GetString([System.Security.Cryptography.SHA256]::Create().ComputeHash([System.Text.Encoding]::UTF8.GetBytes($pin.ToString()))) if ($Hashes -contains $hashedPin) { Write-Host "Found PIN for card number $cardNumber: $pin" break } } } Write-Host "Tried $pinAttempts PINs for $NumCards credit card numbers" "
55ac15231d0a3c14ddba05730412d9aa
{ "intermediate": 0.2969203293323517, "beginner": 0.4686536192893982, "expert": 0.2344261258840561 }
8,596
how can solve this problem in a html, css, js project. Uncaught SyntaxError: Cannot use import statement outside a module
e38a3652d993e09b1a07ef087d89ad5a
{ "intermediate": 0.41368368268013, "beginner": 0.49629926681518555, "expert": 0.09001705050468445 }
8,597
Есть многоклассовая классификация текстов from sklearn.model_selection import train_test_split # разбиваем выборку на тренировочную и тестовую train_df, test_df = train_test_split(train_data, test_size=0.2, random_state=42) # разбиваем тестовую выборку на тестовую и валидационную test_df, val_df = train_test_split(test_df, test_size=0.5, random_state=42) import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences max_len = 600 # максимальная длина последовательности num_classes = 13 # число классов для классификации # создаем токенизатор tokenizer = Tokenizer() tokenizer.fit_on_texts(train_df['text']) # преобразуем текст в последовательность чисел train_sequences = tokenizer.texts_to_sequences(train_df['text']) test_sequences = tokenizer.texts_to_sequences(test_df['text']) val_sequences = tokenizer.texts_to_sequences(val_df['text']) # добавляем паддинг train_sequences = pad_sequences(train_sequences, maxlen=max_len) test_sequences = pad_sequences(test_sequences, maxlen=max_len) val_sequences = pad_sequences(val_sequences, maxlen=max_len) # создаем модель seq2seq input_dim = len(tokenizer.word_index) + 1 embedding_dim = 50 model = keras.Sequential([ layers.Embedding(input_dim=input_dim, output_dim=embedding_dim, input_length=max_len), layers.LSTM(units=64, dropout=0.2, recurrent_dropout=0.2), layers.Dense(num_classes, activation='softmax') ]) model.summary() # выводим информацию о модели from sklearn.metrics import f1_score import tensorflow.keras.backend as K from tensorflow.keras.losses import CategoricalCrossentropy import numpy as np from keras import backend as K def recall_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def f1_m(y_true, y_pred): precision = precision_m(y_true, y_pred) recall = recall_m(y_true, y_pred) return 2*((precision*recall)/(precision+recall+K.epsilon())) #model.compile(loss=CategoricalCrossentropy(), optimizer='adam', metrics=['acc',f1_m,precision_m, recall_m]) model.compile(loss=CategoricalCrossentropy(), optimizer='adam', metrics=['acc',f1_m,precision_m, recall_m]) history = model.fit(train_sequences, train_df['category'], epochs=10, batch_size=1000, validation_data=(val_sequences, val_df['category'])) Получаем ошибку history = model.fit(train_sequences, train_df['category'], 33 epochs=10, batch_size=1000, 34 validation_data=(val_sequences, val_df['category'])) ValueError: Shapes (None, 1) and (None, 13) are incompatible
95c8c009c18a04010fc59c3b146b70eb
{ "intermediate": 0.29092907905578613, "beginner": 0.45694413781166077, "expert": 0.2521268129348755 }
8,598
# Оптимизированный!!! Возвращает адреса созданных токенов из новых блоков в реальном времени import asyncio import aiohttp import time bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' # Create a semaphore with a limit of 3 semaphore = asyncio.Semaphore(1) async def get_latest_block_number(): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_blockNumber&apikey={bscscan_api_key}' async with session.get(url) as response: data = await response.json() return int(data['result'], 16) async def get_external_transactions(block_number): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return [] if data['result'] is None or isinstance(data['result'], str): print(f"Error: Cannot find the block") return [] return data['result'].get('transactions', []) async def get_contract_address(tx_hash): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return None if data['result'] is None or not isinstance(data['result'], dict): print(f"Error: Cannot find the address") return None return data['result'].get('contractAddress') async def contract_id_ends_with_6040(contract_address): async with aiohttp.ClientSession() as session: url = f"https://api.bscscan.com/api?module=contract&action=getsourcecode&address={contract_address}&apikey={bscscan_api_key}" try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f"Error in API request: {e}") return False if data["result"]: contract_id = data["result"][0].get("ContractName", "") return contract_id.lower().endswith("6040") return False async def process_block(block_number_int): block_number = hex(block_number_int) transactions = await get_external_transactions(block_number) if not transactions: print(f'No transactions found in block {block_number_int}') else: print(f'Transactions in block {block_number_int}:') for tx in transactions: if tx['to'] is None: contract_address = await get_contract_address(tx['hash']) if contract_address: print(f'New contract creation: Contract Address: {contract_address}') print("\n") # Print an empty line between blocks async def display_transactions(block_start, block_end): tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)] await asyncio.gather(*tasks) async def main(): block_start = await get_latest_block_number() # Start with the latest block number block_end = block_start + 10 # Process 10 blocks initially while True: await display_transactions(block_start, block_end) # Update block_start and block_end to check for new blocks every 5 seconds block_start = block_end + 1 block_end = await get_latest_block_number() time.sleep(5) asyncio.run(main()) In the code above, returns all generated tokens, not just those with a method id that ends in 6040. Fix this
2446ad9674c6c41ecac6c720c2a23fbd
{ "intermediate": 0.5044476985931396, "beginner": 0.3545597791671753, "expert": 0.1409924477338791 }
8,599
give me the html code for a simple webpage home page
ed48c4f9ca5eed17987a7be0916eed63
{ "intermediate": 0.3861823081970215, "beginner": 0.3570995330810547, "expert": 0.25671815872192383 }
8,600
This is a C# code to connect to one account on wolf.live using WolfLive.Api: “using System; using System.Threading.Tasks; using WolfLive.Api; namespace MyFirstBot { public class Program { public static Task Main(string[] args) { var client = new WolfClient(); var loggedIn = await client.Login(“email”, “password”); if (!loggedIn) { Console.WriteLine(“Failed to login!”); return; } Console.WriteLine(“Login successfull!”); await Task.Delay(-1); } } }”, Modify the code to make it connect to multiple accounts at once from a list called AccountsList and stay connected to all of them.
778676e63b9ed9f89a8ee2eb29a6dc93
{ "intermediate": 0.46595463156700134, "beginner": 0.3332931101322174, "expert": 0.20075222849845886 }
8,601
Hellow
5201907926a5cf752cc3308ce9a0b1f4
{ "intermediate": 0.34572020173072815, "beginner": 0.32247650623321533, "expert": 0.33180323243141174 }
8,602
اكتب لى code flutter يقوم بعمل service not stop
457838e0911be2857daaf99ad0021a0e
{ "intermediate": 0.403771311044693, "beginner": 0.2839323580265045, "expert": 0.3122963011264801 }
8,603
This code is right ? Code: order_quantity = min(max_trade_quantity, float(long_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'LONG'), None) if long_position: else: print("No open long position found")))
932d54890afa0d8ba73ac41518dcd697
{ "intermediate": 0.3133937120437622, "beginner": 0.3885316848754883, "expert": 0.2980746328830719 }
8,604
What is the example food which the person who do the keto diet eat in one day?
b1982ffbf3e45d3f425a523be64325f6
{ "intermediate": 0.3336547613143921, "beginner": 0.3346744775772095, "expert": 0.33167073130607605 }
8,605
software implementation of image quality improvement in raw format using neural networks
4fe57a3a1d479ab76d08d51ae1e84fda
{ "intermediate": 0.07176967710256577, "beginner": 0.06889776885509491, "expert": 0.8593325614929199 }
8,606
%{ #include <stdio.h> #include <stdlib.h> int yylex(); void yyerror(char const* s); %} %token IDENTIFIER %token NUMBER %token IF %token ELSE %token FOR %token ADD %token SUB %token MUL %token DIV %token MOD %token ASSIGN %token EQ %token LT %token GT %token LE %token GE %token NEQ %token AND %token OR %token NOT %token SEMICOLON %token LPAREN %token RPAREN %token LBRACE %token RBRACE %token PACKAGE MAIN IMPORT FUNC VAR PRINTLN PRINT %token STRING_LITERAL %token INT %start program %% program: package_declaration import_declaration func_declaration ; package_declaration: PACKAGE MAIN SEMICOLON ; import_declaration: IMPORT STRING_LITERAL SEMICOLON ; func_declaration: FUNC MAIN LPAREN RPAREN LBRACE statements RBRACE ; statements: statement | statements statement ; statement: | var_declaration SEMICOLON { printf("variable declaration and assignment\n"); } | print_statement | assignment_statement | IF LPAREN expression RPAREN LBRACE statements RBRACE { printf("if statement\n"); } | IF LPAREN expression RPAREN LBRACE statements RBRACE ELSE LBRACE statements RBRACE { printf("if-else statement\n"); } | FOR LPAREN IDENTIFIER ASSIGN expression SEMICOLON expression SEMICOLON IDENTIFIER ADD ASSIGN expression RPAREN LBRACE statements RBRACE { printf("for loop\n"); } ; var_declaration: VAR IDENTIFIER data_type ASSIGN expression ; print_statement: PRINTLN LPAREN expression RPAREN SEMICOLON { printf("println statement\n"); } | PRINT LPAREN expression RPAREN SEMICOLON { printf("print statement\n"); } ; assignment_statement: IDENTIFIER ASSIGN expression SEMICOLON { printf("%d = %d\n", $1, $3); } ; data_type: INT ; expression: expression ADD term { $$ = $1 + $3; } | expression SUB term { $$ = $1 - $3; } | term { $$ = $1; } ; term: term MUL factor { $$ = $1 * $3; } | term DIV factor { $$ = $1 / $3; } | factor { $$ = $1; } ; factor: NUMBER { $$ = $1; } | IDENTIFIER { printf("identifier: %d\n", $1); } | LPAREN expression RPAREN { $$ = $2; } ; %% int main() { yyparse(); return 0; } void yyerror(char const* s) { fprintf(stderr, "%s\n", s); } gptparser.y: warning: shift/reduce conflict on token IF [-Wcounterexamples] Example: • IF LPAREN expression RPAREN LBRACE RBRACE Shift derivation statements ↳ 5: statement ↳ 11: • IF LPAREN expression RPAREN LBRACE statements RBRACE ↳ 11: ε Reduce derivation statements ↳ 6: statements statement ↳ 5: statement ↳ 11: IF LPAREN expression RPAREN LBRACE statements RBRACE ↳ 7: ε •
973b4cb76bae2f3af5886b2d267cf24f
{ "intermediate": 0.3323717713356018, "beginner": 0.5451579093933105, "expert": 0.12247030436992645 }
8,607
This is a C# code to connect to one account on wolf.live using WolfLive.Api: “using System; using System.Threading.Tasks; using WolfLive.Api; namespace MyFirstBot { public class Program { public static Task Main(string[] args) { var client = new WolfClient(); var loggedIn = await client.Login(“email”, “password”); if (!loggedIn) { Console.WriteLine(“Failed to login!”); return; } Console.WriteLine(“Login successfull!”); await Task.Delay(-1); } } }”, Modify the code to make it connect to multiple accounts at once from a list called AccountsList and stay connected to all of them.
512e59a73e5860b87b0492cb0861fc9a
{ "intermediate": 0.46595463156700134, "beginner": 0.3332931101322174, "expert": 0.20075222849845886 }
8,608
%{ #include <stdio.h> #include <stdlib.h> int yylex(); void yyerror(char const* s); %} %token IDENTIFIER %token NUMBER %token IF %token ELSE %token FOR %token ADD %token SUB %token MUL %token DIV %token MOD %token ASSIGN %token EQ %token LT %token GT %token LE %token GE %token NEQ %token AND %token OR %token NOT %token SEMICOLON %token LPAREN %token RPAREN %token LBRACE %token RBRACE %token PACKAGE MAIN IMPORT FUNC VAR PRINTLN PRINT %token STRING_LITERAL %token INT %start program %% program: package_declaration import_declaration func_declaration ; package_declaration: PACKAGE MAIN SEMICOLON ; import_declaration: IMPORT STRING_LITERAL SEMICOLON ; func_declaration: FUNC MAIN LPAREN RPAREN LBRACE statements RBRACE ; statements: statement | statements statement ; statement: | var_declaration SEMICOLON { printf("variable declaration and assignment\n"); } | print_statement | assignment_statement | IF LPAREN expression RPAREN LBRACE statements RBRACE { printf("if statement\n"); } | IF LPAREN expression RPAREN LBRACE statements RBRACE ELSE LBRACE statements RBRACE { printf("if-else statement\n"); } | FOR LPAREN IDENTIFIER ASSIGN expression SEMICOLON expression SEMICOLON IDENTIFIER ADD ASSIGN expression RPAREN LBRACE statements RBRACE { printf("for loop\n"); } ; var_declaration: VAR IDENTIFIER data_type ASSIGN expression ; print_statement: PRINTLN LPAREN expression RPAREN SEMICOLON { printf("println statement\n"); } | PRINT LPAREN expression RPAREN SEMICOLON { printf("print statement\n"); } ; assignment_statement: IDENTIFIER ASSIGN expression SEMICOLON { printf("%d = %d\n", $1, $3); } ; data_type: INT ; expression: expression ADD term { $$ = $1 + $3; } | expression SUB term { $$ = $1 - $3; } | term { $$ = $1; } ; term: term MUL factor { $$ = $1 * $3; } | term DIV factor { $$ = $1 / $3; } | factor { $$ = $1; } ; factor: NUMBER { $$ = $1; } | IDENTIFIER { printf("identifier: %d\n", $1); } | LPAREN expression RPAREN { $$ = $2; } ; %% int main() { yyparse(); return 0; } void yyerror(char const* s) { fprintf(stderr, "%s\n", s); } gptparser.y: warning: shift/reduce conflict on token IF [-Wcounterexamples] Example: • IF LPAREN expression RPAREN LBRACE RBRACE Shift derivation statements ↳ 5: statement ↳ 11: • IF LPAREN expression RPAREN LBRACE statements RBRACE ↳ 11: ε Reduce derivation statements ↳ 6: statements statement ↳ 5: statement ↳ 11: IF LPAREN expression RPAREN LBRACE statements RBRACE ↳ 7: ε •
022240ecd1d484ac7486c47e3abd3aee
{ "intermediate": 0.3323717713356018, "beginner": 0.5451579093933105, "expert": 0.12247030436992645 }
8,609
application of neural networks to the bayer filter code on Python
28fab80ea741b90fcc58fd71f9a033c4
{ "intermediate": 0.12767459452152252, "beginner": 0.06958601623773575, "expert": 0.8027393221855164 }
8,610
This is a C# code to connect to one account on wolf.live using WolfLive.Api: “using System; using System.Threading.Tasks; using WolfLive.Api; namespace MyFirstBot { public class Program { public static Task Main(string[] args) { var client = new WolfClient(); var loggedIn = await client.Login(“email”, “password”); if (!loggedIn) { Console.WriteLine(“Failed to login!”); return; } Console.WriteLine(“Login successfull!”); await Task.Delay(-1); } } }”, Modify the code to make it connect to multiple accounts at once from a list called AccountsList and stay connected to all of them. You can skip making the list part.
74c403a8cd5a4d1894212047c3702e51
{ "intermediate": 0.38191479444503784, "beginner": 0.40362292528152466, "expert": 0.2144623100757599 }
8,611
This is a C# code to connect to one account on wolf.live using WolfLive.Api: “using System; using System.Threading.Tasks; using WolfLive.Api; namespace MyFirstBot { public class Program { public static Task Main(string[] args) { var client = new WolfClient(); var loggedIn = await client.Login(“email”, “password”); if (!loggedIn) { Console.WriteLine(“Failed to login!”); return; } Console.WriteLine(“Login successfull!”); await Task.Delay(-1); } } }”, Modify the code to make it connect to multiple accounts at once from a list called AccountsList and stay connected to all of them.
c57adfa3999e1c24b2baa95f8977d02d
{ "intermediate": 0.46595463156700134, "beginner": 0.3332931101322174, "expert": 0.20075222849845886 }
8,612
你好,我的代码报错了,麻烦您帮我看一下。 代码如下:import keras from keras.models import Model from keras.layers import Dense, Input, Lambda import tensorflow as tf import numpy as np # 模型的输入是 cx,cp,cs,t 模型的输出是 y= [k1 ,k2 ,k3]. # 实际的输出是 z = odeint(mechanistic_model, [cx,cp,cs],2,args = (y,)) def mechanistic_model_for_p(y, t, para): alpha, beta, gamma,dcxdt,cx = para cp= y dcpdt = alpha * dcxdt + beta * cx + gamma * cp return [dcpdt] def func(x, k): # 你的实际函数,现在同时接受 x 和 k 作为输入 t,cx_t,cs_t,cp_t = x t, cx_t, cs_t, cp_t = tf.unstack(t,cx_t,cs_t,cp_t, axis=1) alpha, beta, gamma, = k cx_tp1 = xgboost_model.predict([t,cx_t,cs_t,cp_t], verbose=0) dcxdt = (cx_tp1 - cx_t)/1 cp_tp1 = mechanistic_model_for_p([cp_t],t,[alpha, beta, gamma,dcxdt,cx_t])[0] return cp_tp1 def func_layer(tensors): # 使用 Tensorflow 在 Lambda 层中实现 func 函数,现在接受 x 和 k 作为输入 x, k = tensors return func(x, k) # 创建从 x 到 k 的模型 input_x = Input(shape=(4,)) hidden = Dense(units=4, activation="sigmoid")(input_x) output_y = Dense(units=3, activation="linear")(hidden) x_to_k_model = Model(inputs=input_x, outputs=output_y) # 创建 func 函数的模型,现在接受 x 和 y 作为输入 input_x_for_func = Input(shape=(4,)) input_k_for_func = Input(shape=(3,)) output_z = Lambda(func_layer)([input_x_for_func, input_k_for_func]) func_model = Model(inputs=[input_x_for_func, input_k_for_func], outputs=output_z) # 将 x 到 k 的模型与 func 模型连接 output_z_from_x_and_y = func_model([input_x, x_to_k_model.output]) x_to_z_model = Model(inputs=input_x, outputs=output_z_from_x_and_y) # 用已知的 x 和 z 数据训练完整的模型 X_For_ANN_Cp = pd.DataFrame({ 'Time':xgboost_df['Time'], 'Biomass_t':xgboost_df['Biomass_t'], 'Substrate_t':xgboost_df['Substrate_t'], 'Product_t':xgboost_df['Product_t'], } ) Z_For_ANN_Cp = pd.DataFrame({ 'Cp_t+1':xgboost_df['Product_t+1'], } ) x_train, x_test, z_train, z_test = train_test_split(X_For_ANN_Cp, Z_For_ANN_Cp, test_size=0.2, random_state=4) x_to_z_model.compile(optimizer="adam", loss="mse") x_to_z_model.fit(x_train, z_train) 报错信息如下: --------------------------------------------------------------------------- OperatorNotAllowedInGraphError Traceback (most recent call last) Cell In[105], line 42 40 input_x_for_func = Input(shape=(4,)) 41 input_k_for_func = Input(shape=(3,)) ---> 42 output_z = Lambda(func_layer)([input_x_for_func, input_k_for_func]) 43 func_model = Model(inputs=[input_x_for_func, input_k_for_func], outputs=output_z) 45 # 将 x 到 k 的模型与 func 模型连接 File c:\Users\29252\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\utils\traceback_utils.py:70, in filter_traceback..error_handler(*args, **kwargs) 67 filtered_tb = _process_traceback_frames(e.__traceback__) 68 # To get the full stack trace, call: 69 # `tf.debugging.disable_traceback_filtering()` ---> 70 raise e.with_traceback(filtered_tb) from None 71 finally: 72 del filtered_tb Cell In[105], line 31, in func_layer(tensors) 27 def func_layer(tensors): 28 # 使用 Tensorflow 在 Lambda 层中实现 func 函数,现在接受 x 和 k 作为输入 29 x, k = tensors ---> 31 return func(x, k) Cell In[105], line 18, in func(x, k) 16 def func(x, k): 17 # 你的实际函数,现在同时接受 x 和 k 作为输入 ---> 18 t,cx_t,cs_t,cp_t = x 19 t, cx_t, cs_t, cp_t = tf.unstack(t,cx_t,cs_t,cp_t, axis=1) 20 alpha, beta, gamma, = k OperatorNotAllowedInGraphError: Exception encountered when calling layer "lambda_4" (type Lambda). Iterating over a symbolic `tf.Tensor` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function. Call arguments received by layer "lambda_4" (type Lambda): • inputs=['tf.Tensor(shape=(None, 4), dtype=float32)', 'tf.Tensor(shape=(None, 3), dtype=float32)'] • mask=None • training=None
411668399512f55cdf0afdab3d681475
{ "intermediate": 0.3472786843776703, "beginner": 0.4303829073905945, "expert": 0.22233839333057404 }
8,613
how can solve this problem in a html, css, js project. Uncaught SyntaxError: Cannot use import statement outside a module
d31f9a61f5ec71b3853d95604ea0ad26
{ "intermediate": 0.3997662365436554, "beginner": 0.5095109343528748, "expert": 0.09072279185056686 }
8,614
Modify the code below in such a way that you get only those token addresses whose last digits of the function executed on the basis of the decoded input are 6040. We are talking about the method id column # Оптимизированный!!! Возвращает адреса созданных токенов из новых блоков в реальном времени import asyncio import aiohttp import time bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' # Create a semaphore with a limit of 3 semaphore = asyncio.Semaphore(1) async def get_latest_block_number(): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_blockNumber&apikey={bscscan_api_key}' async with session.get(url) as response: data = await response.json() return int(data['result'], 16) async def get_external_transactions(block_number): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return [] if data['result'] is None or isinstance(data['result'], str): print(f"Error: Cannot find the block") return [] return data['result'].get('transactions', []) async def get_contract_address(tx_hash): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return None if data['result'] is None or not isinstance(data['result'], dict): print(f"Error: Cannot find the address") return None return data['result'].get('contractAddress') async def process_block(block_number_int): block_number = hex(block_number_int) transactions = await get_external_transactions(block_number) if not transactions: print(f'No transactions found in block {block_number_int}') else: print(f'Transactions in block {block_number_int}:') for tx in transactions: if tx['to'] is None: contract_address = await get_contract_address(tx['hash']) print(f"New contract creation: Contract Address: {contract_address}") print("\n") # Print an empty line between blocks async def display_transactions(block_start, block_end): tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)] await asyncio.gather(*tasks) async def main(): block_start = await get_latest_block_number() # Start with the latest block number block_end = block_start + 10 # Process 10 blocks initially while True: await display_transactions(block_start, block_end) # Update block_start and block_end to check for new blocks every 5 seconds block_start = block_end + 1 block_end = await get_latest_block_number() time.sleep(5) asyncio.run(main())
954c9b8c1063a0fd2b7d945666af7370
{ "intermediate": 0.40851926803588867, "beginner": 0.5083084106445312, "expert": 0.08317238837480545 }
8,615
You're teaching a beginner. Describe in detail what the OpenAI API is and how to use it.
178bd32584f488308fcead13ff5afd6f
{ "intermediate": 0.6237999796867371, "beginner": 0.09298522770404816, "expert": 0.283214807510376 }
8,616
hi
c1a3da9c0c9caa1b3218de0403a182e4
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
8,617
from sklearn.metrics import r2_score,classification_report y_pred = model.predict(test_sequences) y_test = test_labels print(classification_report(y_test.tolist(), y_pred.tolist())) print(r2_score(y_test, y_pred)) ValueError: Classification metrics can't handle a mix of multilabel-indicator and continuous-multioutput targets
77d5e8f393e4bf038d983a39a0c7ed36
{ "intermediate": 0.38683924078941345, "beginner": 0.23129993677139282, "expert": 0.3818608224391937 }
8,618
openbsd install asks for timezone for us
182f0071befca5a10f0f76dc599ed15e
{ "intermediate": 0.41328170895576477, "beginner": 0.2638472616672516, "expert": 0.3228711187839508 }
8,619
static int status(int argc, char **argv, void *userdata) { cleanup(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; cleanup(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL; pid_t pid; int r; r = acquire_bus(false, &bus); if (r < 0) return r; pager_open(arg_pager_flags); if (!isempty(argv[1])) { r = parse_pid(argv[1], &pid); if (r < 0) r = sd_bus_get_name_creds( bus, argv[1], (arg_augment_creds ? SD_BUS_CREDS_AUGMENT : 0) | _SD_BUS_CREDS_ALL, &creds); else r = sd_bus_creds_new_from_pid( &creds, pid, _SD_BUS_CREDS_ALL); } else { const char *scope, *address; sd_id128_t bus_id; r = sd_bus_get_address(bus, &address); if (r >= 0) printf(“BusAddress=%s%s%s\n”, ansi_highlight(), address, ansi_normal()); r = sd_bus_get_scope(bus, &scope); if (r >= 0) printf(“BusScope=%s%s%s\n”, ansi_highlight(), scope, ansi_normal()); r = sd_bus_get_bus_id(bus, &bus_id); if (r >= 0) printf(“BusID=%s” SD_ID128_FORMAT_STR “%s\n”, ansi_highlight(), SD_ID128_FORMAT_VAL(bus_id), ansi_normal()); r = sd_bus_get_owner_creds( bus, (arg_augment_creds ? SD_BUS_CREDS_AUGMENT : 0) | _SD_BUS_CREDS_ALL, &creds); } if (r < 0) return log_error_errno(r, “Failed to get credentials: %m”); bus_creds_dump(creds, NULL, false); return 0; } - как написать аналогичную функцию используя GIO ?
c2bece0de856e78f5362658dc09d552c
{ "intermediate": 0.4101661741733551, "beginner": 0.40850943326950073, "expert": 0.18132437765598297 }
8,620
Complete the code below so that the response shows the age of the token contract and the age of the start of trading on the decentralized exchange (listing) import asyncio import aiohttp from web3 import Web3 bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' # Create a semaphore with a limit of n semaphore = asyncio.Semaphore(5) token_abi = [{"constant": True, "inputs": [], "name": "name", "outputs": [{"name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function"}, {"constant": True, "inputs": [], "name": "decimals", "outputs": [{"name": "", "type": "uint8"}], "payable": False, "stateMutability": "view", "type": "function"}, {"constant": True, "inputs": [], "name": "symbol", "outputs": [{"name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function"}] async def get_external_transactions(block_number): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return [] if data['result'] is None or isinstance(data['result'], str): print(f"Error: Cannot find the block") return [] return data['result'].get('transactions', []) async def get_contract_address(tx_hash): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return None if data['result'] is None or not isinstance(data['result'], dict): return None return data['result'].get('contractAddress') def check_method_id(input_data): method_id = input_data[:10] return method_id[-4:] == '6040' async def get_token_info(contract_address): w3 = Web3(Web3.HTTPProvider('https://bsc-dataseed1.binance.org:443')) checksum_address = Web3.to_checksum_address(contract_address) try: token_contract = w3.eth.contract(address=checksum_address, abi=token_abi) name = token_contract.functions.name().call() symbol = token_contract.functions.symbol().call() decimals = token_contract.functions.decimals().call() return name, symbol, decimals except Exception as e: print(f'Error fetching token info: {e}') return None, None, None async def display_transactions(block_start, block_end): async def process_block(block_number_int): block_number = hex(block_number_int) transactions = await get_external_transactions(block_number) if not transactions: print(f'No transactions found in block {block_number_int}') else: print(f'Transactions in block {block_number_int}:') for tx in transactions: if tx['to'] is None: if check_method_id(tx['input']): contract_address = await get_contract_address(tx['hash']) if contract_address: name, symbol, decimals = await get_token_info(contract_address) print(f'New contract creation: Contract Address: {contract_address}, Name: {name}, Symbol: {symbol}, Decimals: {decimals}') print("\n") # Print an empty line between blocks tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)] await asyncio.gather(*tasks) async def main(): block_start = 28466587 # Replace with your desired starting block number block_end = 28466640 # Replace with your desired ending block number await display_transactions(block_start, block_end) asyncio.run(main())
2341963075377c0a3643f4ae2431225f
{ "intermediate": 0.3957785665988922, "beginner": 0.3717724680900574, "expert": 0.232449010014534 }
8,621
wrap elements in flex 4 by 4 bootstrap5
8534b8ef5289437d5e6b3f40d04ae3f1
{ "intermediate": 0.4277614653110504, "beginner": 0.27628952264785767, "expert": 0.2959490418434143 }
8,622
I have this class in C#: "class AccountsList { public string Email { get; set; } public string Password { get; set; } }" I wanna use it as a list to store data in it, Write a code to store items from this list into a JSON file, and call that file back to use data in it.
cb4942074c03bfb952d44df3a8b69aac
{ "intermediate": 0.5254436731338501, "beginner": 0.35480064153671265, "expert": 0.11975566297769547 }
8,623
How can I install node packages manually?
624be6f01589660536c32c6f649d3b6d
{ "intermediate": 0.48458340764045715, "beginner": 0.2049352079629898, "expert": 0.31048130989074707 }
8,624
This is the program.cs class for a C# app the uses telegram.bot, wolflive.api, newtonsoft.json. check the code for any errors and fix them. notice that there's already an error at line 92: "object not set to an instance of an object" this is the code: "using Telegram.Bot.Exceptions; using Telegram.Bot.Polling; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types; using Telegram.Bot; using WolfLive.Api; using WolfLive.Api.Commands; using Newtonsoft.Json; using System.IO; namespace WolfyMessagesBot { internal class Program { public async static Task Main(string[] args) { var botClient = new TelegramBotClient("5860497272:AAGP5OqCiUFA-lIXVBwbkymtF60H9utp-Xw"); using CancellationTokenSource cts = new(); // StartReceiving does not block the caller thread. Receiving is done on the ThreadPool. ReceiverOptions receiverOptions = new() { AllowedUpdates = Array.Empty<UpdateType>() // receive all update types except ChatMember related updates }; botClient.StartReceiving( updateHandler: HandleUpdateAsync, pollingErrorHandler: HandlePollingErrorAsync, receiverOptions: receiverOptions, cancellationToken: cts.Token ); var me = await botClient.GetMeAsync(); Console.WriteLine($"Start listening for @{me.Username}"); Console.ReadLine(); // Send cancellation request to stop bot cts.Cancel(); async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) { // Only process Message updates: https://core.telegram.org/bots/api#message if (update.Message is not { } message) return; // Only process text messages if (message.Text is not { } messageText) return; var chatId = message.Chat.Id; Console.WriteLine($"Received a '{messageText}' message in chat {chatId}."); // Echo received message text if (messageText.StartsWith("/اضف")) { string[] parts = messageText.Split(); // The first line contains the command (“/add”) string command = parts[0]; // The second line contains the email address string email = parts[1]; // The third line contains the password string password = parts[2]; if (email != null || password != null) { var data = new AccountsList(); data.Email = email; data.Password = password; string jsonFromFile = System.IO.File.ReadAllText("accounts.json"); if (jsonFromFile == null) { var set = new List<AccountsList>(); set.Add(data); string jsonString = JsonConvert.SerializeObject(set); System.IO.File.WriteAllText("accounts.json", jsonString); Message sentMessage = await botClient.SendTextMessageAsync( chatId: chatId, text: "تم اضافة الحساب " + email + "\n هذه هي القائمة الحالية بالحسابات الخاصة بك:" + set.ToList(), cancellationToken: cancellationToken); } else { List<AccountsList> accountsFromFile = JsonConvert.DeserializeObject<List<AccountsList>>(jsonFromFile); // Add new accounts to the list accountsFromFile.Add(data); string jsonString = JsonConvert.SerializeObject(accountsFromFile); System.IO.File.WriteAllText("accounts.json", jsonString); Message sentMessage = await botClient.SendTextMessageAsync( chatId: chatId, text: "تم اضافة الحساب " + email + "\n هذه هي القائمة الحالية بالحسابات الخاصة بك:" + accountsFromFile.ToList(), cancellationToken: cancellationToken); } } else { Message sentMessage = await botClient.SendTextMessageAsync( chatId: chatId, text: "يوجد خطأ في الإيعاز.", cancellationToken: cancellationToken); } } else if (messageText == "/تشغيل") { string jsonFromFile = System.IO.File.ReadAllText("accounts.json"); List<AccountsList> accountsFromFile = JsonConvert.DeserializeObject<List<AccountsList>>(jsonFromFile); Parallel.ForEach(accountsFromFile, async item => { var client = new WolfClient(); var loggedIn = await client.Login(item.Email, item.Password); if (!loggedIn) { Message senddMessage = await botClient.SendTextMessageAsync( chatId: chatId, text: "فشل تسجيل الدخول على حساب: " + item.Email, cancellationToken: cancellationToken); return; } Message sentMessage = await botClient.SendTextMessageAsync( chatId: chatId, text: "تم بنجاح تسجيل الدخول على حساب: : " + item.Email, cancellationToken: cancellationToken); await Task.Delay(-1); }); } else if (messageText.StartsWith("/ارسل")) { string[] parts = messageText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // The first line contains the command (“/add”) string command = parts[0]; string text = parts[1]; string GroupID = parts[2]; string Times = parts[3]; string seconds = parts[4]; if (text != null || GroupID != null || Times != null || seconds != null) { string jsonFromFile = System.IO.File.ReadAllText("accounts.json"); List<AccountsList> accountsFromFile = JsonConvert.DeserializeObject<List<AccountsList>>(jsonFromFile); Parallel.ForEach(accountsFromFile, async item => { var client = new WolfClient(); var loggedIn = await client.Login(item.Email, item.Password); if (!loggedIn) { Message senddMessage = await botClient.SendTextMessageAsync( chatId: chatId, text: "فشل تسجيل الدخول على حساب: " + item.Email, cancellationToken: cancellationToken); return; } for (int i = 1; i < Convert.ToInt32(Times); i++) { await client.GroupMessage(GroupID, text); int waiting = Convert.ToInt32(seconds) * 1000; Thread.Sleep(waiting); } Message sentMessage = await botClient.SendTextMessageAsync( chatId: chatId, text: "أرسل " + item.Email + "الرسالة بنجاح.", cancellationToken: cancellationToken); await Task.Delay(-1); }); } else { Message sentMessage = await botClient.SendTextMessageAsync( chatId: chatId, text: "يوجد خطأ في الإيعاز.", cancellationToken: cancellationToken); } } else if (messageText.StartsWith("/انضم")) { string[] parts = messageText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // The first line contains the command (“/add”) string command = parts[0]; string GroupID = parts[1]; string Password = parts[2]; if (GroupID != null) { string jsonFromFile = System.IO.File.ReadAllText("accounts.json"); List<AccountsList> accountsFromFile = JsonConvert.DeserializeObject<List<AccountsList>>(jsonFromFile); Parallel.ForEach(accountsFromFile, async item => { var client = new WolfClient(); var loggedIn = await client.Login(item.Email, item.Password); if (!loggedIn) { Message senddMessage = await botClient.SendTextMessageAsync( chatId: chatId, text: "فشل تسجيل الدخول على حساب: " + item.Email, cancellationToken: cancellationToken); return; } if (Password == null) { await client.JoinGroup(GroupID); } else { await client.JoinGroup(GroupID, Password); } Message sentMessage = await botClient.SendTextMessageAsync( chatId: chatId, text: "إنضم " + item.Email + "للروم بنجاح.", cancellationToken: cancellationToken); await Task.Delay(-1); }); } else { Message sentMessage = await botClient.SendTextMessageAsync( chatId: chatId, text: "يوجد خطأ في الإيعاز.", cancellationToken: cancellationToken); } } } Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) { var ErrorMessage = exception switch { ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}", _ => exception.ToString() }; Console.WriteLine(ErrorMessage); return Task.CompletedTask; } } } class AccountsList { public string Email { get; set; } public string Password { get; set; } } }"
068e1526893c830d3e6db553495883cb
{ "intermediate": 0.35316672921180725, "beginner": 0.48001420497894287, "expert": 0.1668190360069275 }
8,625
I need to input a string in this format: "/add 'text' GroupID Times Seconds" and i need to store a variable foreach element, one for 'text' without the (''), GroupID, Times and Seconds. in C#
bad62d291af13d349456141f29548a90
{ "intermediate": 0.33134761452674866, "beginner": 0.4770602285861969, "expert": 0.19159215688705444 }
8,626
C:\Users\AshotxXx\PycharmProjects\pythonProject3\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\pythonProject3\main.py Transactions in block 28466589: Transactions in block 28466590: Transactions in block 28466588: Transactions in block 28466591: Transactions in block 28466587: Transactions in block 28466592: Transactions in block 28466593: Transactions in block 28466595: Transactions in block 28466596: Transactions in block 28466594: New contract creation: ContractAddress: 0x42ee2ae7f02694c73a5a5e10ca20a1cf8dba8e0f, Name: ShanghaiPepe, Symbol: SHP, Decimals: 9 Transactions in block 28466597: Transactions in block 28466598: Transactions in block 28466599: Transactions in block 28466600: Error fetching token info: execution reverted New contract creation: ContractAddress: 0xd4de25d7adde33e40f64b3965855c733e750ce5a, Name: None, Symbol: None, Decimals: None New contract creation: ContractAddress: 0x8e4505b6d6beaae4853d795092a4340c2b0ff373, Name: META TOKEN, Symbol: META2, Decimals: 18 Error fetching token info: execution reverted New contract creation: ContractAddress: 0x705e2e18d4c2da352cefd396868a482c2dc18437, Name: None, Symbol: None, Decimals: None New contract creation: ContractAddress: 0x2ce0a5e4f58110c40f198aac55b7841bf3dab582, Name: BABY MRF, Symbol: BABYMRF, Decimals: 9 New contract creation: ContractAddress: 0x39c23cbac6329f29da1b8755a3907e5a76716872, Name: BitLink, Symbol: BTL, Decimals: 12 Traceback (most recent call last): File "C:\Users\AshotxXx\PycharmProjects\pythonProject3\main.py", line 150, in <module> asyncio.run(main()) File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\pythonProject3\main.py", line 139, in main if info['first_trade_bloc'] \ ~~~~^^^^^^^^^^^^^^^^^^^^ KeyError: 'first_trade_bloc' Process finished with exit code 1 Fix it
f1cf7d76fd84cc3a9b5fc62a8d6fbe02
{ "intermediate": 0.3764142692089081, "beginner": 0.44905760884284973, "expert": 0.17452818155288696 }
8,627
read title of a button in js
69cef594ed1fbb692413f2f343d1babe
{ "intermediate": 0.29993683099746704, "beginner": 0.2937782406806946, "expert": 0.406284898519516 }
8,628
in unreal engine 4, create an scope material that magnify or zoom in what ever that's in its view without using a render target.
ae5204ee94ca343514a82976abe16194
{ "intermediate": 0.27549073100090027, "beginner": 0.2167418897151947, "expert": 0.507767379283905 }
8,629
I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt date = dt.datetime.now().strftime(“%m/%d/%Y %H:%M:%S”) print(date) url = “https://api.binance.com/api/v1/time” t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) # API keys and other configuration API_KEY = ‘’ API_SECRET = ‘’ client = Client(API_KEY, API_SECRET) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = ‘SELL’ POSITION_SIDE_LONG = ‘BUY’ symbol = ‘BTCUSDT’ quantity = 0.27 order_type = ‘MARKET’ leverage = 125 max_trade_quantity_percentage = 10 client = Client(API_KEY, API_SECRET) def getminutedata(symbol, interval, lookback): frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+‘min ago UTC’)) frame = frame.iloc[:60,:6] frame.columns = [‘Time’,‘Open’,‘High’,‘Low’,‘Close’,‘Volume’] frame = frame.set_index(‘Time’) today = dt.date.today() frame.index = pd.to_datetime(frame.index, unit=‘ms’).tz_localize(‘UTC’).tz_convert(‘Etc/GMT+3’).strftime(f"{today} %H:%M:%S") frame = frame.astype(float) return frame def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] #Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return ‘sell’ #Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return ‘buy’ #No clear pattern else: return ‘’ df = getminutedata(‘BTCUSDT’, ‘15m’, ‘44640’) signal = [“” for i in range(len(df))] # initialize signal as a list of empty strings for i in range(1, len(df)): df_temp = df[i-1:i+1] signal[i] = signal_generator(df_temp) df[“signal”] = signal def order_execution(symbol, signal, max_trade_quantity_percentage): max_trade_quantity_percentage = 10 buy = signal == “buy” sell = signal == “sell” signal = buy or sell symbol = ‘BTCUSDT’ account_balance = client.futures_account_balance() usdt_balance = float([x[‘balance’] for x in account_balance if x[‘asset’] == ‘USDT’][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 POSITION_SIDE_SHORT = SIDE_SELL POSITION_SIDE_LONG = SIDE_BUY long_position = POSITION_SIDE_LONG short_position = POSITION_SIDE_SHORT symbol = ‘BTCUSDT’ max_trade_quantity = 100 positions = client.futures_position_information(symbol=symbol) long_position = next((p for p in positions if p[‘symbol’] == symbol and p[‘positionSide’] == ‘LONG’), None) if long_position: # Close long position if signal is opposite if signal == “sell”: order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position[‘positionAmt’], reduceOnly=True ) print(f"Closed long position with order ID {order[‘orderId’]}“) time.sleep(1) else: order_quantity = min(max_trade_quantity, float(long_position) if long_position is None else 0 ) if long_position in None: print(“No open long position found”) order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT, leverage=leverage ) print(f"Placed short order with order ID {order[‘orderId’]} and quantity {order_quantity})”) time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order[‘avgPrice’] * (1 + STOP_LOSS_PERCENTAGE / 100) take_profit_price = order[‘avgPrice’] * (1 + TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}“) time.sleep(1) short_position = next((p for p in positions if p[‘symbol’] == symbol and p[‘positionSide’] == ‘SHORT’), None) if short_position: # Close short position if signal is opposite if signal == “buy”: order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position[‘positionAmt’], reduceOnly=True ) print(f"Closed short position with order ID {order[‘orderId’]}”) time.sleep(1) else: order_quantity = min(max_trade_quantity, float(short_position[‘maxNotionalValue’]) / leverage) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG, leverage=leverage ) print(f"Placed long order with order ID {order[‘orderId’]} and quantity {order_quantity}“) time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order[‘avgPrice’] * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order[‘avgPrice’] * (1 - TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}”) time.sleep(1) while True: current_time = dt.datetime.now().strftime(“%Y-%m-%d %H:%M:%S”) current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution(symbol, current_signal,max_trade_quantity_percentage) time.sleep(1) # Add a delay of 1 second But I getting ERROR: Traceback (most recent call last): File “c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py”, line 214, in <module> order_execution(symbol, current_signal,max_trade_quantity_percentage) File “c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py”, line 115, in order_execution order_quantity = min(max_trade_quantity, float(long_position) ^^^^^^^^^^^^^^^^^^^^ TypeError: float() argument must be a string or a real number, not ‘NoneType’
f5f0a2922967f8db02881c60f1a84cfe
{ "intermediate": 0.29698067903518677, "beginner": 0.4802083969116211, "expert": 0.22281098365783691 }
8,630
This code is right? If no give me just right code . Code:import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt date = dt.datetime.now().strftime(“%m/%d/%Y %H:%M:%S”) print(date) url = “https://api.binance.com/api/v1/time” t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) # API keys and other configuration API_KEY = ‘’ API_SECRET = ‘’ client = Client(API_KEY, API_SECRET) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = ‘SELL’ POSITION_SIDE_LONG = ‘BUY’ symbol = ‘BTCUSDT’ quantity = 0.27 order_type = ‘MARKET’ leverage = 125 max_trade_quantity_percentage = 10 client = Client(API_KEY, API_SECRET) def getminutedata(symbol, interval, lookback): frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+‘min ago UTC’)) frame = frame.iloc[:60,:6] frame.columns = [‘Time’,‘Open’,‘High’,‘Low’,‘Close’,‘Volume’] frame = frame.set_index(‘Time’) today = dt.date.today() frame.index = pd.to_datetime(frame.index, unit=‘ms’).tz_localize(‘UTC’).tz_convert(‘Etc/GMT+3’).strftime(f"{today} %H:%M:%S") frame = frame.astype(float) return frame def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] #Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return ‘sell’ #Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return ‘buy’ #No clear pattern else: return ‘’ df = getminutedata(‘BTCUSDT’, ‘15m’, ‘44640’) signal = [“” for i in range(len(df))] # initialize signal as a list of empty strings for i in range(1, len(df)): df_temp = df[i-1:i+1] signal[i] = signal_generator(df_temp) df[“signal”] = signal def order_execution(symbol, signal, max_trade_quantity_percentage): max_trade_quantity_percentage = 10 buy = signal == “buy” sell = signal == “sell” signal = buy or sell symbol = ‘BTCUSDT’ account_balance = client.futures_account_balance() usdt_balance = float([x[‘balance’] for x in account_balance if x[‘asset’] == ‘USDT’][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 POSITION_SIDE_SHORT = SIDE_SELL POSITION_SIDE_LONG = SIDE_BUY long_position = POSITION_SIDE_LONG short_position = POSITION_SIDE_SHORT symbol = ‘BTCUSDT’ max_trade_quantity = 100 positions = client.futures_position_information(symbol=symbol) long_position = next((p for p in positions if p[‘symbol’] == symbol and p[‘positionSide’] == ‘LONG’), None) if long_position: # Close long position if signal is opposite if signal == “sell”: order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position[‘positionAmt’], reduceOnly=True ) print(f"Closed long position with order ID {order[‘orderId’]}“) time.sleep(1) else: if long_position is not None: order_quantity = min(max_trade_quantity, float(long_position[‘positionAmt’])) else: print(“No open long position found”) order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT, leverage=leverage ) print(f"Placed short order with order ID {order[‘orderId’]} and quantity {order_quantity})”) time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order[‘avgPrice’] * (1 + STOP_LOSS_PERCENTAGE / 100) take_profit_price = order[‘avgPrice’] * (1 + TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}“) time.sleep(1) short_position = next((p for p in positions if p[‘symbol’] == symbol and p[‘positionSide’] == ‘SHORT’), None) if short_position: # Close short position if signal is opposite if signal == “buy”: order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position[‘positionAmt’], reduceOnly=True ) print(f"Closed short position with order ID {order[‘orderId’]}”) time.sleep(1) else: order_quantity = min(max_trade_quantity, float(short_position[‘maxNotionalValue’]) / leverage) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG, leverage=leverage ) print(f"Placed long order with order ID {order[‘orderId’]} and quantity {order_quantity}“) time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order[‘avgPrice’] * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order[‘avgPrice’] * (1 - TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}”) time.sleep(1) while True: current_time = dt.datetime.now().strftime(“%Y-%m-%d %H:%M:%S”) current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution(symbol, current_signal,max_trade_quantity_percentage) time.sleep(1) # Add a delay of 1 second
27fbe1c1aa4ecfc37928db189f203fea
{ "intermediate": 0.4015175998210907, "beginner": 0.3636261224746704, "expert": 0.23485632240772247 }
8,631
5- 0.5m3 rigid tank containing R134a initially at 160 kPa and quality 0.4. The heat is transmitted to the coolant until the pressure reaches 700 kPa. Determine: (a) the mass of the refrigerant in the tank [10.03 kg]. (b) The amount of transported [2,707 kJ]. Also show the process on a t - v diagram.
e616a09dd120b6e2a36404a49ab7d5b2
{ "intermediate": 0.41235315799713135, "beginner": 0.30768585205078125, "expert": 0.2799609899520874 }
8,632
in unreal engine 4, how to create an scope material that magnify or zoom in what ever that’s in its view without using a render target.
9627524cb2654a02ddfdf222f1f620b3
{ "intermediate": 0.2858138978481293, "beginner": 0.21923676133155823, "expert": 0.4949493110179901 }