row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
1,206
write a python program to remove the "<" and ">" from the filenames i have files with this format, <01> name.txt
b6d3f7155bae4b4368ca4df5932aa8a4
{ "intermediate": 0.48745062947273254, "beginner": 0.16302385926246643, "expert": 0.349525511264801 }
1,207
const errorsResult = []; const makeErrors = (errors = []) => errors.forEach((error) => { if (!errorsResult.some(err => err.caption === error.caption)) { errorsResult.push(error); } }) const checkErrors = ({ errors, sum }) => { makeErrors(errors); const isPayed = !sum.to_pay; if (isPayed) { throw 'change_paid_order_is_forbidden'; } } for (const order_id of orders) { await dispatch(apiBasket('loadorder', { order_id }, true)) .then(checkErrors) .then(() => dispatch(apiBasket('change', params, true))) .then(checkErrors) .then(() => dispatch(apiBasket('save', {}, true))) .then(makeErrors) .catch(() => {}) } how to simplify the code?
4dabbcfc7183620f5a5dc94d77c68f9b
{ "intermediate": 0.4784128665924072, "beginner": 0.2558557093143463, "expert": 0.26573145389556885 }
1,208
How to speak 滚出我的房子 in English?
8562b4e5ac21ad8e057296c120dd964e
{ "intermediate": 0.36215996742248535, "beginner": 0.4053477346897125, "expert": 0.23249229788780212 }
1,209
现在有5000个文本表达,每个表达有对应的标签,构成一个元组列表,要求输入语句,返回这个列表里面与输入语句最相似的前5个文本,已经相似度值,相似度计算要精准。要求5000个文本表达训练成一个索引文件,下次可以加载文件进行相似度计算,也可以在索引文件中添加新的文本表达列表。
a97d74bf24b9b082c65cb7b3b4edf742
{ "intermediate": 0.38379964232444763, "beginner": 0.25917795300483704, "expert": 0.35702240467071533 }
1,210
Create an expert level lengthy advanced script in python for Use 2 layers of LSTM to predict next hour’s price instead of next day’s price which may have better application in real world. ------------------------------------------------------------------ First you will implemented data normalization like min-max normalization and normalization with window [5] where the data is normalized based on the window’s initial value and the percentage of change. ------------------------------------------------------------------ Multiple Layer Perceptron (MLP), Long-Short- Term-Memory (LSTM) and Gated recurrent units (GRU) models are compared on the test dataset with cross-validation. 2. Dataset Exploration Data used in this research is collected from Kaggle [6]. Bitcoin data from Jan 2016 to July 2022 is collected. It has a timestamp, the value at Open, High, Low, Close, the volume traded in Bitcoin and USD, the weighted price and the date. This prompt focuses on predicting Bitcoin price in the future hour by using the price of past 24 hours, so only the timestamp and the
418979d7420da5d88b0fec24931677d3
{ "intermediate": 0.2433919757604599, "beginner": 0.10328736901283264, "expert": 0.6533206701278687 }
1,211
from sklearn.feature_extraction.text import TfidfVectorizer import joblib import faiss import numpy as np class TextSimilarity: def __init__(self): self.vectorizer = TfidfVectorizer() self.index = None self.texts = None def train(self, text_label_tuples): texts, _ = zip(*text_label_tuples) self.texts = texts text_vectors = self.vectorizer.fit_transform(texts).toarray() self.index = faiss.IndexFlatL2(text_vectors.shape[1]) self.index.add(np.array(text_vectors, dtype=np.float32)) def save(self, index_file_path, vectorizer_file_path): faiss.write_index(self.index, index_file_path) joblib.dump(self.vectorizer, vectorizer_file_path) def load(self, index_file_path, vectorizer_file_path): self.index = faiss.read_index(index_file_path) self.vectorizer = joblib.load(vectorizer_file_path) def add_to_index(self, new_text_label_tuples): new_texts, _ = zip(*new_text_label_tuples) self.texts += new_texts new_text_vectors = self.vectorizer.transform(new_texts).toarray() self.index.add(np.array(new_text_vectors, dtype=np.float32)) def find_similar_texts(self, input_text, k=5): input_vector = self.vectorizer.transform([input_text]).toarray() _, indices = self.index.search(np.array(input_vector, dtype=np.float32), k) similarities = [1 - faiss.vector_L2sqr(input_vector, self.index.reconstruct(index)) for index in indices[0]] similar_texts = [(self.texts[i], similarities[i]) for i in indices[0]] return similar_texts text_label_tuples = [("中国(上海)自由贸易试验区临港新片区管理委员会关于印发", "标签1"), ("应根据能耗预测结果,利用人工智能提出相应的节能策略。", "标签2"), ("中国(上海)自由贸易试验区临港新片区商务楼宇数字化交付和智慧运营导则", "标签3"), ("人工智能的发展", "标签4")] similarity_obj = TextSimilarity() similarity_obj.train(text_label_tuples) similarity_obj.save("index_file.index", "vectorizer_file.pkl") #加载索引和vectorizer进行相似度计算: input_text = "人工智能" similarity_obj = TextSimilarity() similarity_obj.load("index_file.index", "vectorizer_file.pkl") similar_texts = similarity_obj.find_similar_texts(input_text) print(similar_texts) 以上代码报错:AttributeError: module 'faiss' has no attribute 'vector_L2sqr',请修改,改成整个代码可以运行
d2e7a33a208c0a02eadcf371ac4b31ba
{ "intermediate": 0.19635413587093353, "beginner": 0.5729050040245056, "expert": 0.23074083030223846 }
1,212
hi
f655a29d76e82032cafeb149ff11851d
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
1,213
def str(self): return f"{self.first_name} {self.last_name}" in models y to wrote this
c7dd7b2d19562ffd7bbecd91d664c486
{ "intermediate": 0.25153985619544983, "beginner": 0.43455836176872253, "expert": 0.31390178203582764 }
1,214
write me an excel formula where it gives the average of all the numbers in Column “FP” which ignores blank cells, when the value in Column “AV” in the same row is the value “Alex”
fba0e05a4ef4b48a2aaf42fc0b7aee94
{ "intermediate": 0.2988390326499939, "beginner": 0.14177435636520386, "expert": 0.5593866109848022 }
1,215
for m3u8 live playlist, how the web client know what segments should be fetched next?
9fe9794e5ef2cb764aced7b4ed7a53c3
{ "intermediate": 0.38712748885154724, "beginner": 0.2255711406469345, "expert": 0.38730141520500183 }
1,216
window.containerItems().find and bot.clickWindow are not working after change pages in this code: let page = itemData[itemname][0] for (i = 0; i < page - 1; i++) { bot.on("windowOpen", async function ChangePageGui(window) { bot.clickWindow(53, 0, 0) bot.removeListener("windowOpen", ChangePageGui) }) } let index = itemData[itemname][1] - 1 bot.on("windowOpen", async function ClickItemGui(window) { bot.clickWindow(index, 0, 0) bot.removeListener("windowOpen", ClickItemGui) })
528805e5fadbd43d5f12206bf6e2d452
{ "intermediate": 0.4787859618663788, "beginner": 0.30432847142219543, "expert": 0.21688561141490936 }
1,217
write a python program to remove the “<” and “>” from the filenames i have files with this format, <01> name.txt
dc08b1e46e4698b10ce9904ce669f0fa
{ "intermediate": 0.4347919225692749, "beginner": 0.16235455870628357, "expert": 0.4028535485267639 }
1,218
Hi, I've implemented the following train function. I think there are some issues with the accuracy calculations. I might be due to appending issues or might be a division issuse. And also look for other potential issues and feel free to modify the code. Even come with a much more optimized way. here is the code: def train_model(model, device, train_loader, test_loader, epochs = None, learning_rate = None, optimization_technique = None, patience=None, scheduler_patience=None,num_batches = None, **kwargs): criterion = nn.CrossEntropyLoss() #optimizer = optim.SGD(model.parameters(), lr=learning_rate, weight_decay=5e-4) optimizer = optim.Adam(model.parameters(), lr=learning_rate) # ,momentum = 0.9) if optimization_technique == 'learning_rate_scheduler' and scheduler_patience: scheduler = ReduceLROnPlateau(optimizer, 'min', patience=scheduler_patience, verbose=True) train_losses = [] train_accuracies = [] test_losses = [] test_accuracies = [] best_loss = float('inf') stopping_counter = 0 # with_dropout = model.classifier[6] # without_dropout = nn.Sequential(*[layer for layer in model.classifier if layer != with_dropout]) for epoch in range(epochs): running_train_loss = 0.0 running_train_acc = 0 num_batches_train = 0 #for X_batch, y_batch in itertools.islice(train_loader, 0, num_batches): for X_batch, y_batch in train_loader: # Move batch to device X_batch, y_batch = X_batch.to(device, non_blocking=True), y_batch.to(device, non_blocking=True) optimizer.zero_grad() y_pred = model(X_batch) loss = criterion(y_pred, y_batch) loss.backward() optimizer.step() running_train_loss += loss.item() running_train_acc += torch.sum(torch.eq(y_pred.argmax(dim=1), y_batch)).item() num_batches_train += 1 train_losses.append(running_train_loss / num_batches_train) train_accuracies.append(running_train_acc / len(train_loader.dataset)) # Testing segment running_test_loss = 0.0 running_test_acc = 0 num_batches_test = 0 with torch.no_grad(): for X_batch, y_batch in test_loader: #for X_batch, y_batch in itertools.islice(test_loader, 0, num_batches): # Move batch to device X_batch, y_batch = X_batch.to(device, non_blocking=True), y_batch.to(device, non_blocking=True) y_pred = model(X_batch) loss = criterion(y_pred, y_batch) running_test_loss += loss.item() running_test_acc += torch.sum(torch.eq(y_pred.argmax(dim=1), y_batch)).item() # running_test_acc += accuracy_score(y_batch.cpu().numpy(), y_pred.argmax(dim=1).cpu().numpy()) num_batches_test += 1 test_losses.append(running_test_loss / num_batches_test) test_accuracies.append(running_test_acc / len(test_loader.dataset)) # Early stopping if optimization_technique == 'early_stopping' and patience: if test_losses[-1] < best_loss: best_loss = test_losses[-1] stopping_counter = 0 else: stopping_counter += 1 if stopping_counter > patience: print(f"Early stopping at epoch {epoch+1}/{epochs}") break # Learning rate scheduler if optimization_technique == 'learning_rate_scheduler' and scheduler_patience and scheduler: scheduler.step(test_losses[-1]) print(f"Epoch: {epoch+1}/{epochs}, Training Loss: {train_losses[-1]}, Test Loss: {test_losses[-1]}, Training Accuracy: {train_accuracies[-1]}, Test Accuracy: {test_accuracies[-1]}") return train_losses, train_accuracies, test_losses, test_accuracies
63df584c1010a30dd2c486d1300bdbce
{ "intermediate": 0.2744673490524292, "beginner": 0.4462796151638031, "expert": 0.2792530357837677 }
1,219
u mean form.as.p renders the fileds which i gave in form.py file
bcc8855d6b7b76929bf645946a4ce659
{ "intermediate": 0.27616411447525024, "beginner": 0.2954588234424591, "expert": 0.4283769726753235 }
1,220
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
b19f2aae5a6878905938d5c898a46237
{ "intermediate": 0.6988149285316467, "beginner": 0.15340058505535126, "expert": 0.14778444170951843 }
1,221
An application needs to be created for writing a poker Card game. Following are the requirements for the same. Implementation guidelines: 1. Implementation needs to be Object oriented. To make it object oriented, you can use these guidelines. 2. Do not read any data from command line unless specifically required (In this assignment its not required). Project will be run from hard coded data in main(...) method. Sample for main(...) is provided at the end. 3. Identify nouns and verbs from statement. a. Nouns are potential candidates for becoming a class, attribute, or object name. Use these nouns for naming classes, attributes, or object ref names. b. Nouns representing single primitive value are potential candidates for attributes. c. Verbs are potential candidates for becoming methods of class. 4. Identify signature (parameters and return type) required for each method. 5. Identify relationship between different classes. 6. If it is A KIND OF relationship 7. If its HAS-A or PART-OF, use containment. Ignore differences between Composition and Aggregation at this stage. 8. Don’t keep any classes in default package. Keep related classes together in appropriately designed packages. 9. Use base package name as com.psl.gems and extend it with readable application package names 10. Write main(...) method in com.psl.gems.client.TestClient class. This main(...) will be starting point for application. Use provided template for main (...). Application description:  Playing cards come as Full Pack of 52 cards. (4 Suits X 13 Ranks). Ref the picture. If you are not aware about playing cards best source is Wikipedia. ...  4 Suits are CLUB, DIAMOND, HEART, SPADE (from smallest to highest in value)  Ranks are called as TWO, THREE, ..., TEN, JACK, QUEEN, KING, ACE (from smallest to highest in value)  Any group of cards (containing 1..52 cards) is called Pack of Cards.  Full pack is a Pack of Cards initialized with all 52 cards, but in the game as one or more cads are drawn from Full Pack, the count may go down till zero.  Pack of Cards will maintain the sequence unless changed by any act like shuffle, reset etc.  A Player can do following actions with Pack of Cards o can shuffle o can get top card o can add a card (duplicates are not allowed) o can get random card o can query size of pack. o Can reset sequence in ascending/ descending order.  Game begins by initializing the Full pack. [main(...) will be a starting point]  Player (with name) registers with the game. [In short game will keep collection of Players registered]  Once two players register for the Game (as a poker game), game will automatically start. [hint: will call its play() method]  When game is played (in a game.play()), three cards will be given to each Player as one card at a time in alternate manner. Plyers add this each card in their Cards in Hand.  Once three cards are distributed, Each Player has Cards in Hand (as a pack of 3 cards). Based on following rule, game will declare winner player. (This being simple luck game, player does not take any action) o Rule for winner.  Each card has a value computed using following algorithm.  Each suit has suit-weight associated as {SPADE(3), HEART(2), DIAMOND(1), CLUB(0)}  Each rank has rank-weight associated as {TWO(0), THREE(1),.., JACK(9), QUEEN(10), KING(11), ACE(12)}  Value of the card is computed as Rank-weight * 4 + Suit-weight. (e.g. CLUB-JACK will have value 9 * 4 + 0 = 36, SPADE-SIX will have weight 4*4 + 3 = 19)  Highest card for player is card with highest value in “Cards in Hand” for player.  Each player’s highest card is Card with highest value.  Game will compare highest cards for each player, and player with higher “Highest Card” wins the game.  Example o [Player 1 (  SPADE-THREE(1*4+3=7),  DIAMOND-FIVE (3 * 4 + 1 = 13),  CLUB-QUEEN(10*4+0 = 40) ] o Highest Card is CLUB-QUEEN o [Player 2 (  SPADE-JACK(9*4+3=39),  HEART-QUEEN (10 * 4 + 2 = 42),  DIAMOND-KING (11*4+1 = 45) ] o Highest Card is DIAMOND-KING  Winner is player 2 (as KING is higher than QUEEN)  Also programmatically write following output in to cardgame.html in following format by replacing actual data for name and cards in hand,  This cardgame.html will be used for next part of assignment. <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <section> <div id="Suresh"> <div data-card="SPADE-THREE" /> <div data-card="DIAMOND-FIVE" /> <div data-card="CLUB-QUEEN" /> </div> <div id="Ramesh"> <div data-card="SPADE-JACK" /> <div data-card="HEART-QUEEN" /> <div data-card="DIAMOND-KING" /> </div> </section> </body>  Main(...) method skeleton public static void main(String[] args) { //CREATE PLAYER 1 AND PLAYER 2 WITH SOME NAMES (say Suresh and Ramesh) //CREATE AND INITIALIZE CARD-GAME (shuffle the Full Card Pack) //LET BOTH THE PLAYERS REGISTER TO THE GAME // (something like game.register(player1)) // IF GAME HAS 2 PLAYERS, PLAY THE GAME. // INSIDE game.play() ALLOT 3 CARDS TO EACH PLAYER // as per rules decide highest card for each player // as per rule decide winner and print it. // WRITE THE PLAYER DATA AND PLAYERS' CARDS IN PROVIDED HTML TEMPLATE INTO cardgame.html file. } write me code for each and every file with the directory structure (packages) according to the description given above.
c8e2bfbaf6716ae1914b7c4f24192446
{ "intermediate": 0.3859492838382721, "beginner": 0.4113888144493103, "expert": 0.20266194641590118 }
1,222
webview加载android相机画面
c1a256e6c731e68cba23f8050fcb7ae0
{ "intermediate": 0.38508743047714233, "beginner": 0.22030963003635406, "expert": 0.3946029841899872 }
1,223
Write a code on Python for simple neural network which can generate fixed third-dimensional arrays with size 64x64x64 and then train it on third-dimensional arrays of random numbers in range 0-1024. Check if CUDA available, if it is use it instead CPU
0ffeac9b29c2d4eae88c8dc221b4a41b
{ "intermediate": 0.09874490648508072, "beginner": 0.03256704658269882, "expert": 0.8686880469322205 }
1,224
I need you to write code for a chrome extension that monitors active input box and if there are words that starts with <//> it pops up mesage<found!>
4c2bce48508d86acc2ab0c7a45958d8b
{ "intermediate": 0.5255224704742432, "beginner": 0.19866801798343658, "expert": 0.27580946683883667 }
1,225
How many ways to research a paper that I interest?
6fcb6562e23d07fa7c8dc31586e64026
{ "intermediate": 0.31291067600250244, "beginner": 0.17959880828857422, "expert": 0.5074905157089233 }
1,226
R example code for KM plot with number of subjects at risk
328316645494c8f12efbef3961a55648
{ "intermediate": 0.33410027623176575, "beginner": 0.2370491921901703, "expert": 0.4288504719734192 }
1,227
I'll give you some java code,and you should improve the code.
b46f12961f28ac63feff1286bdf72969
{ "intermediate": 0.2856694757938385, "beginner": 0.37852564454078674, "expert": 0.33580484986305237 }
1,228
1.1 Background Consider the scenario of reading from a file and transferring the data to another program over the network. This scenario describes the behaviour of many server applications, including Web applications serving static content, FTP servers, mail servers, etc. The core of the operation is in the following two calls: read(file, user_buffer, len); write(socket, user_buffer, len); Figure 1 shows how data is moved from the file to the socket. Behind these two calls, the data has been copied at least four times, and almost as many user/kernel context switches have been performed. Figure 2 shows the process involved. The top side shows context switches, and the bottom side shows copy operations. 1. The read system call causes a context switch from user mode to kernel mode. The first copy is performed by the DMA (Direct Memory Access) engine, which reads file contents from the disk and stores them into a kernel address space buffer. 2. Data is copied from the kernel buffer into the user buffer ,and the read system call returns. The return from the call causes a context switch from kernel back to user mode. Now the data is stored in the user address space buffer, and it can begin its way down again. 3. The write system call causes a context switch from user mode to kernel mode. A third copy is per- formed to put the data into a kernel address space buffer again. This time, though, the data is put into a different buffer, a buffer that is associated with sockets specifically. 4. The write system call returns, creating our fourth context switch. Return from write call does not guarantee the start of the transmission. It simply means the Ethernet driver had free descriptors in its queue and has accepted our data for transmission. Independently and asynchronously, a fourth copy happens as the DMA engine passes the data from the kernel buffer to the protocol engine. (The forked DMA copy in Figure 2 illustrates the fact that the last copy can be delayed). As you can see, a lot of data duplication happens in this process. Some of the duplication could be eliminated to decrease overhead and increase performance. To eliminate overhead, we could start by eliminating some of the copying between the kernel and user buffers. 1.2 Overview and Technical Details Your task in this lab is to implement zero-copy read and write operations that would eliminate the copying between the kernel and user buffers. You will develop a new library with a set of library calls that allow a user to: • Open a file • Read from the file without using a user buffer • Write to the file without using a user buffer • Reposition within the file • Close the file The user directly uses the kernel buffer provided by the library calls to read and write data. Your implementation should NOT call read and write system calls or other library calls that wrap around read and write system calls. Calling read and write would involve some type of duplication of buffers. You should use the mmap system call in your implementation. 2 Exercises in Lab 4 The goal of this lab assignment is to produce a zero-copy IO library. All function and data structures names are prefixed by zc_. The library uses a data structure called zc_file (defined in zc_io.c) to maintain the information about the opened files and help in the reading and writing operations. You are required to use it and add any information needed to maintain the information about the opened files into this data structure. For ex1 to ex3, operations on the same file will not be issued concurrently (i.e. you do not need to be concerned about synchronization). We will change this assumption in ex4 and bonus exercise. For all exercises, you may assume that there is no concurrent opening of the same file (the file is opened at most once at the same time, and the file is not modified outside the runner). The provided runner implements a few testcases on reading and writing a file using the zc_io library. It is not exhaustive but will catch some common errors. If your implementation is correct, the runner will run successfully. Otherwise, it may segmentation fault, or print a “FAIL” message with the reason of the failure. You are also encouraged to implement your own program to test the library. 2.1 Exercise 1A: Zero-copy Read [1% + 1% demo or 2% submission] You are required to implement four library calls to open/close and perform zero copy read from a file. - zc_file *zc_open(const char *path) Opens file specified by path and returns a zc_file pointer on success, or NULL otherwise. Open the file using the O_CREAT and O_RDWR flags. You can use fstat() to obtain information (if needed) regarding the opened file. -int zc_close(zc_file *file) Flushes the information to the file and closes the underlying file descriptor associated with the file. If successful, the function returns 0, otherwise it returns -1. Free any memory that you allocated for the zc_file structure. You can use msync() flush copy of file in virtual memory into file. -const char *zc_read_start(zc_file *file, size_t *size) The function returns the pointer to a chunk of *size bytes of data from the file. If the file contains less than *size bytes remaining, then the number of bytes available should be written to *size. The purpose of zc_read_start is to provide the kernel buffer that already contains the data to be read. This avoids the need to copy these data to another buffer as in the case of read system call. Instead, the user can simply use the data from the returned pointer. Your zc_file structure should help you keep track of a offset in the file. Once size bytes have been requested for reading (or writing), the offset should advance by size and the next time when zc_read_start or zc_write_start is called, the next bytes after offset should be offered. Note that reading and writing is done using the same offset. -void zc_read_end(zc_file file) This function is called when a reading operation on file has ended. It is always guaranteed that the function is paired with a previous call to zc_read_start.
 2.2 Exercise 1B: Zero-copy Write [1% + 1% demo or 2% submission] You are required to implement two library calls that allow writing to file: -char *zc_write_start(zc_file *file, size_t size) The function returns the pointer to a buffer of at least size bytes that can be written. The data written to this buffer would eventually be written to file. The purpose of zc_write_start is to provide the kernel buffer where information can be written. This avoids the need to copy these data to another buffer as in the case of write system call. The user can simply write data to the returned pointer. Once size bytes have been requested for writing, the offset should advance by size and the next time when zc_read_start or zc_write_start is called, the next bytes after offset should be written. Note that reading and writing is done using the same offset. File size might change when information is written to file. Make sure that you handle this case properly. See ftruncate.
-void zc_write_end(zc_file *file) This function is called when a writing operation on file has ended. The function pushes to the file on disk any changes that might have been done in the buffer between zc_write_start and zc_write_end. This means that there is an implicit flush at the end of each zc_write operation. You can check out msync() to help you with flushing. It is always guaranteed that the function is paired with a previous call to zc_write_start.

Writing to a file using the zc_io library call should have the same semantic behaviour as observed in write system call. 
2.3 Exercise 2: Repositioning the file offset [1%] You are required to implement one library call that allows changing the offset in the file: -off_t zc_lseek(zc_file *file, long offset, int whence) Reposition at a different offset within the file. The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence. whence can take 3 values: • SEEK_SET: offset is relative to the start of the file • SEEK_CUR: offset is relative to the current position indicator • SEEK_END: offset is relative to the end-of-file The SEEK_SET, SEEK_CUR and SEEK_END values are defined in unistd.h and take the values 0, 1, and 2 respectively. The zc_lseek() function returns the resulting offset location as measured in bytes from the be- ginningofthefileor(off_t) -1ifanerroroccurs. zc_lseek() allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a “hole”) return null bytes ('\0') until data is actually written into the gap. (Please refer to Appendix B for a simple example on this.)
Repositioning the file offset should have the same semantic behaviour as lseek system call. 2.4 Exercise 3: Zero-copy file transfer [2%] You are required to implement the following library call: -int zc_copyfile(const char *source, const char *dest) This function copies the content of source into dest. It will return 0 on success and -1 on failure. You should make use of the function calls you implemented in the previous exercises, and should not use any user buffers to achieve this. Do ftruncate the destination file so they have the same size.c 
2.5 Exercise 4: Readers-writers Synchronization [1%] Exercises above assumed that the operations on the same file would be issued in sequence. In ex4 we lift this assumption and allow multiple reads and writes to be issued at the same time for the same instance of an open file. You need to make sure that your zc_read_start, zc_write_start and zc_lseek executed on an open file follow the following rules: • Multiple zc_read operations can take place at the same time for the same instance of the zc_file. • No other operation should take place at the same time with a zc_write or zc_lseek operation. • All operation issued while zc_write or zc_lseek is executing would block waiting to start. They would start only once the zc_write or zc_lseek ends. In other words, you should solve the readers-writers synchronization problem when multiple operations are issued at the same time for the same instance of an open file. You are not required to ensure that your solution is starvation-free. While multiple readers can read at the same time, ensure that the offset variable of the file is protected and multiple zc_write_start or especially zc_read_start access and increment the offset variable one at a time. For eg. if two threads read 10 bytes each, with initial offset = 0, one of the threads should read the first 10 bytes, the other the next 10 bytes, and the final value of offset should be 20.
 Fill in the following template: #include “zc_io.h” // The zc_file struct is analogous to the FILE struct that you get from fopen. struct zc_file { // Insert the fields you need here. / Some suggested fields : - pointer to the virtual memory space - offset from the start of the virtual memory - total size of the file - file descriptor to the opened file - mutex for access to the memory space and number of readers */ }; /* * Exercise 1 * / zc_file zc_open(const char path) { // To implement return NULL; } int zc_close(zc_file file) { // To implement return -1; } const char zc_read_start(zc_file file, size_t size) { // To implement return NULL; } void zc_read_end(zc_file file) { // To implement } char zc_write_start(zc_file file, size_t size) { // To implement return NULL; } void zc_write_end(zc_file file) { // To implement } / * Exercise 2 * / off_t zc_lseek(zc_file file, long offset, int whence) { // To implement return -1; } / * Exercise 3 * / int zc_copyfile(const char source, const char dest) { // To implement return -1; } / * Bonus Exercise * *********/ const char zc_read_offset(zc_file file, size_t size, long offset) { // To implement return NULL; } char zc_write_offset(zc_file file, size_t size, long offset) { // To implement return NULL; }
181df9eb204112be97c0fe8c4fb5dcd2
{ "intermediate": 0.43557482957839966, "beginner": 0.360271155834198, "expert": 0.20415395498275757 }
1,229
简化代码 :monthly_dryTemp_apt,monthly_dryTemp_ofs=[[df.query(f'month == {_}')['Drybulb Temperature'].mean() for _ in months] for df in dfs] xs = np.arange(12) _, ax = plt.subplots(figsize=(6, 6)) ax.bar(xs - 0.2, monthly_dryTemp_apt, width=0.4) ax.bar(xs + 0.2, monthly_dryTemp_apt, width=0.4) ax.set_xticks(xs, labels=months) ax.set_title( "Monthly Drybulb Temperature of the two buildings ", fontsize=16, y=1.05) plt.tight_layout() plt.legend(area_labels) plt.show()
e825c02470bd13f1538af530ae6de8d9
{ "intermediate": 0.3343774974346161, "beginner": 0.345339298248291, "expert": 0.3202832341194153 }
1,230
athena create table as select
6c6bdd1fe0d85404c964c945e29a9f90
{ "intermediate": 0.3346570134162903, "beginner": 0.21209834516048431, "expert": 0.4532446265220642 }
1,231
lowList = df['low'].rolling(19).min() # 计算low值19日移动最低 lowList.fillna(value=df['low'].expanding().min(), inplace=True) highList = df['high'].rolling(19).max() # 计算high值19日移动最高 highList.fillna(value=df['high'].expanding().max(), inplace=True) rsv = (df.loc[:, 'close'] - lowList) / (highList - lowList) * 100 df.loc[:, 'kdj_k'] = rsv.ewm(com=6).mean() df.loc[:, 'kdj_d'] = df.loc[:, 'kdj_k'].ewm(com=2).mean() df.loc[:, 'kdj_j'] = 3.0 * df.loc[:, 'kdj_k'] - 2.0 * df.loc[:, 'kdj_d'] df = df.sort_index(ascending=False) 上述代码中用到了pandas库,现在不能用pandas,选择一个替代品并写出替代的代码
256acb0e531248a97dcc35e655579167
{ "intermediate": 0.354884535074234, "beginner": 0.3127937912940979, "expert": 0.3323216438293457 }
1,232
code a hbbtv website that can stream an m3u8 stream
db0f1b919d40c4b0bee6c7d9e5addf46
{ "intermediate": 0.31032422184944153, "beginner": 0.2271680384874344, "expert": 0.4625077247619629 }
1,233
please provide R example code for simulation of survival data based on data already observed, and predict when the target number of events will achieve.
85167d6a7441be3fd1b1af7a8937bb5f
{ "intermediate": 0.2889788746833801, "beginner": 0.08338313549757004, "expert": 0.6276379823684692 }
1,234
room database build and add calback to prepopulate data
5c69003a6cb48b1097e7c618ae331cea
{ "intermediate": 0.4513883590698242, "beginner": 0.21378913521766663, "expert": 0.33482250571250916 }
1,235
Imprègne toi de ce code tu vas devoir l'utiliser pr la suite : class node: def init(self, identity, label, parents, children): ‘’‘ identity: int; its unique id in the graph label: string; parents: int->int dict; maps a parent node’s id to its multiplicity children: int->int dict; maps a child node’s id to its multiplicity ‘’’ self.id = identity self.label = label self.parents = parents self.children = children def repr (self): return "id: "+ str(self.id) + ", " + "label: " + str(self.label) + ", " + "parents: " + str(self.parents) + ", " + "children: " + str(self.children) #ok def get_id (self): return self.id def get_label (self): return self.label #ok def get_parents_ids (self): return [i for i in self.parents.keys()] #ok def get_children_ids (self): return [i for i in self.children.keys()] #ok def get_children(self): return self.children.values() def get_parents(self): return self.parents.values() def set_id(self, i): self.id = i #ok def set_label(self, i): self.label = i #ok def set_parents_ids(self, i): self.parents = i #ok def set_children_ids(self, i): self.children = i #ok def add_child_id(self, i): if i in self.get_children_ids(): self.children[i] +=1 else: self.children[i] = 1 #ok def add_parent_id(self, i): if i in self.get_parents_ids(): self.parents[i] +=1 else: self.parents[i] = 1 #ok def remove_parent_once(self, id): try: if self.parents[id] <= 1: self.remove_parent_id(id) return self.parents[id] = self.parents[id] - 1 except KeyError: raise “Invalid parent id” #ok def remove_child_once(self, id): try: if self.children[id] <= 1: self.remove_child_id(id) return self.children[id] = self.children[id] - 1 except KeyError: raise “Invalid child id” #ok def remove_parent_id(self, id): try: self.parents.pop(id) except KeyError: raise “Invalid parent id” #ok def remove_child_id(self, id): try: self.children.pop(id) except KeyError: raise “Invalid child id” #ok def indegree(self): res = 0 for p in self.parents.values(): res += p return res def outdegree(self): res = 0 for c in self.children.values(): res +=c return res def degree(self): return self.indegree()+self.outdegree() n = node(2, 0, {1: 2}, {3: 2}) #print(n.indegree()) #print(n.outdegree()) #print(n.degree()) class open_digraph(open_digraph_display_mx, open_digraph_connectivite_mx, open_digraph_tritopo_mx, node): # for open directed graph def init(self, inputs, outputs, nodes): ‘’‘ inputs: int list; the ids of the input nodes outputs: int list; the ids of the output nodes nodes: node list; ‘’’ self.inputs = inputs self.outputs = outputs self.nodes = {node.id:node for node in nodes} # self.nodes: <int,node> dict def str (self): return "inputs: " + str(self.inputs) + “\n” + "outputs: “+ str(self.outputs) + “\n” + “nodes: " + str(self.nodes) @classmethod def empty(cls): return cls([],[],[]) def copy(self): newNodes = {} d = open_digraph.empty() d.inputs = self.inputs.copy() d.outputs = self.outputs.copy() for key in self.nodes.keys(): n0 = node(-1, ‘’, {}, {}) n0.id = self.nodes[key].id n0.label = self.nodes[key].label n0.parents = self.nodes[key].parents.copy() n0.children = self.nodes[key].children.copy() newNodes[key]=n0 d.nodes = newNodes return d #ok def get_input_ids(self): return self.inputs #return [i.get_id() for i in self.inputs] #ok def get_output_ids(self): return self.outputs #return [i.get_id() for i in self.outputs] #ok def get_id_node_map(self): return self.nodes #ok def get_nodes(self): return [i for i in self.nodes.values()] #ok def get_node_ids(self): return [i for i in self.nodes.keys()] #ok def get_node_by_id(self, i): ‘’‘ i : int (id of the node) ‘’’ return self.nodes[i] #ok def get_nodes_by_ids(self, t): ‘’‘ t : int iter ‘’’ return [self.nodes[i] for i in t] #ok def get_input_nodes(self): return [self.nodes[node_id] for node_id in self.inputs] def get_output_nodes(self): return [node for node in self.nodes.values() if node.outdegree() == 0 and node in self.outputs] def set_input_ids(self, t): ‘’‘ t : int list ‘’’ self.inputs = t #ok def set_output_ids(self, t): ‘’‘ t : int list ‘’’ self.outputs = t #ok def add_node(self, label=‘’, parents=None, children=None): #parents et children sont des dictionnaires ‘’‘ adds a NEW (it creates it !) a node label : string parents : int:int dict children : int:int dict ‘’’ if parents is None: parents = {} if children is None: children = {} new_id = self.new_id() new_node = node(new_id, label, parents, children) self.nodes[new_id] = new_node for parent_id in parents: self.nodes[parent_id].children[new_id] = parents[parent_id] for child_id in children: self.nodes[child_id].parents[new_id] = children[child_id] return new_id #ok def add_input_node (self, id): nid = self.new_id() if (id in self.get_input_ids()) or (id in self.get_output_ids()): raise “invalid connection” else: self.nodes[nid] = node(nid, “input”, dict(), {id:1}) self.nodes[id].parents[nid] = 1 self.add_input_id(nid) #ok def add_output_node (self, id): nid = self.new_id() if (id in self.get_input_ids()) or (id in self.get_output_ids()): raise “invalid connection” else: self.nodes[nid] = node(nid,“output”,{id:1},dict()) self.nodes[id].children[nid] = 1 self.add_output_id(nid) #ok def add_input_id(self, t): ‘’‘ makes an existing node an input t : int (id of the node) ‘’’ if t in self.inputs: raise “Already an input” else: self.inputs += [t] #ok def add_output_id(self, t): ‘’‘ makes an existing node an output t : int (id of the node) ‘’’ if t in self.outputs: raise ‘Already an output’ else: self.outputs += [t] #ok def add_edge(self, src, tgt): if src not in self.nodes: raise ValueError(f"node id source invalide :{src}”) #vérifie si le noeud source (src) existe dans la liste des noeuds (nodes) de ce graph if tgt not in self.nodes: raise ValueError(f"node id cible invalide :{tgt}”) #vérifie si le noeud cible (tgt) existe dans la liste des noeuds (nodes) src_node = self.get_node_by_id(src) # récupere le noeud source a partir de la liste de neouds en utilisant l’identifiant src du noeud source tgt_node = self.get_node_by_id(tgt) # recupere le noeud cible a partir de la liste des noeuds en utilisant l’id tgt du noeud cible src_node.add_child_id(tgt) tgt_node.add_parent_id(src) #ok def add_edges(self, edges): ‘’‘ edges : (int, int) iter ‘’’ for src, tgt in edges: self.add_edge(src, tgt) #ok
223334747f5894856b1d68c7d93778b7
{ "intermediate": 0.19167982041835785, "beginner": 0.45599180459976196, "expert": 0.352328360080719 }
1,236
Write a Python implementation of shellsort.
bef779fa6b98617b033926936959052f
{ "intermediate": 0.4489132761955261, "beginner": 0.17615437507629395, "expert": 0.37493228912353516 }
1,237
class node: def init(self, identity, label, parents, children): ‘’‘ identity: int; its unique id in the graph label: string; parents: int->int dict; maps a parent node’s id to its multiplicity children: int->int dict; maps a child node’s id to its multiplicity ‘’’ self.id = identity self.label = label self.parents = parents self.children = children def repr (self): return "id: "+ str(self.id) + ", " + "label: " + str(self.label) + ", " + "parents: " + str(self.parents) + ", " + "children: " + str(self.children) #ok def get_id (self): return self.id def get_label (self): return self.label #ok def get_parents_ids (self): return [i for i in self.parents.keys()] #ok def get_children_ids (self): return [i for i in self.children.keys()] #ok def get_children(self): return self.children.values() def get_parents(self): return self.parents.values() def set_id(self, i): self.id = i #ok def set_label(self, i): self.label = i #ok def set_parents_ids(self, i): self.parents = i #ok def set_children_ids(self, i): self.children = i #ok def add_child_id(self, i): if i in self.get_children_ids(): self.children[i] +=1 else: self.children[i] = 1 #ok def add_parent_id(self, i): if i in self.get_parents_ids(): self.parents[i] +=1 else: self.parents[i] = 1 #ok def remove_parent_once(self, id): try: if self.parents[id] <= 1: self.remove_parent_id(id) return self.parents[id] = self.parents[id] - 1 except KeyError: raise “Invalid parent id” #ok def remove_child_once(self, id): try: if self.children[id] <= 1: self.remove_child_id(id) return self.children[id] = self.children[id] - 1 except KeyError: raise “Invalid child id” #ok def remove_parent_id(self, id): try: self.parents.pop(id) except KeyError: raise “Invalid parent id” #ok def remove_child_id(self, id): try: self.children.pop(id) except KeyError: raise “Invalid child id” #ok def indegree(self): res = 0 for p in self.parents.values(): res += p return res def outdegree(self): res = 0 for c in self.children.values(): res +=c return res def degree(self): return self.indegree()+self.outdegree() n = node(2, 0, {1: 2}, {3: 2}) #print(n.indegree()) #print(n.outdegree()) #print(n.degree()) class open_digraph(open_digraph_display_mx, open_digraph_connectivite_mx, open_digraph_tritopo_mx, node): # for open directed graph def init(self, inputs, outputs, nodes): ‘’‘ inputs: int list; the ids of the input nodes outputs: int list; the ids of the output nodes nodes: node list; ‘’’ self.inputs = inputs self.outputs = outputs self.nodes = {node.id:node for node in nodes} # self.nodes: <int,node> dict def str (self): return "inputs: " + str(self.inputs) + “\n” + "outputs: “+ str(self.outputs) + “\n” + “nodes: " + str(self.nodes) @classmethod def empty(cls): return cls([],[],[]) def copy(self): newNodes = {} d = open_digraph.empty() d.inputs = self.inputs.copy() d.outputs = self.outputs.copy() for key in self.nodes.keys(): n0 = node(-1, ‘’, {}, {}) n0.id = self.nodes[key].id n0.label = self.nodes[key].label n0.parents = self.nodes[key].parents.copy() n0.children = self.nodes[key].children.copy() newNodes[key]=n0 d.nodes = newNodes return d #ok def get_input_ids(self): return self.inputs #return [i.get_id() for i in self.inputs] #ok def get_output_ids(self): return self.outputs #return [i.get_id() for i in self.outputs] #ok def get_id_node_map(self): return self.nodes #ok def get_nodes(self): return [i for i in self.nodes.values()] #ok def get_node_ids(self): return [i for i in self.nodes.keys()] #ok def get_node_by_id(self, i): ‘’‘ i : int (id of the node) ‘’’ return self.nodes[i] #ok def get_nodes_by_ids(self, t): ‘’‘ t : int iter ‘’’ return [self.nodes[i] for i in t] #ok def get_input_nodes(self): return [self.nodes[node_id] for node_id in self.inputs] def get_output_nodes(self): return [node for node in self.nodes.values() if node.outdegree() == 0 and node in self.outputs] def set_input_ids(self, t): ‘’‘ t : int list ‘’’ self.inputs = t #ok def set_output_ids(self, t): ‘’‘ t : int list ‘’’ self.outputs = t #ok def add_node(self, label=‘’, parents=None, children=None): #parents et children sont des dictionnaires ‘’‘ adds a NEW (it creates it !) a node label : string parents : int:int dict children : int:int dict ‘’’ if parents is None: parents = {} if children is None: children = {} new_id = self.new_id() new_node = node(new_id, label, parents, children) self.nodes[new_id] = new_node for parent_id in parents: self.nodes[parent_id].children[new_id] = parents[parent_id] for child_id in children: self.nodes[child_id].parents[new_id] = children[child_id] return new_id #ok def add_input_node (self, id): nid = self.new_id() if (id in self.get_input_ids()) or (id in self.get_output_ids()): raise “invalid connection” else: self.nodes[nid] = node(nid, “input”, dict(), {id:1}) self.nodes[id].parents[nid] = 1 self.add_input_id(nid) #ok def add_output_node (self, id): nid = self.new_id() if (id in self.get_input_ids()) or (id in self.get_output_ids()): raise “invalid connection” else: self.nodes[nid] = node(nid,“output”,{id:1},dict()) self.nodes[id].children[nid] = 1 self.add_output_id(nid) #ok def add_input_id(self, t): ‘’‘ makes an existing node an input t : int (id of the node) ‘’’ if t in self.inputs: raise “Already an input” else: self.inputs += [t] #ok def add_output_id(self, t): ‘’‘ makes an existing node an output t : int (id of the node) ‘’’ if t in self.outputs: raise ‘Already an output’ else: self.outputs += [t] #ok def add_edge(self, src, tgt): if src not in self.nodes: raise ValueError(f"node id source invalide :{src}”) #vérifie si le noeud source (src) existe dans la liste des noeuds (nodes) de ce graph if tgt not in self.nodes: raise ValueError(f"node id cible invalide :{tgt}”) #vérifie si le noeud cible (tgt) existe dans la liste des noeuds (nodes) src_node = self.get_node_by_id(src) # récupere le noeud source a partir de la liste de neouds en utilisant l’identifiant src du noeud source tgt_node = self.get_node_by_id(tgt) # recupere le noeud cible a partir de la liste des noeuds en utilisant l’id tgt du noeud cible src_node.add_child_id(tgt) tgt_node.add_parent_id(src) #ok def add_edges(self, edges): ‘’‘ edges : (int, int) iter ‘’’ for src, tgt in edges: self.add_edge(src, tgt) #ok class bool_circ(open_digraph): def init(self,g): circuit = {} nod = g.get_node_ids() inp = g.get_input_ids() out = g.get_output_ids() for n in nod: if (n not in inp) or (n not in out): circuit.update(rand.randint(0,3),n) #porte et = 0, porte ou = 1, porte not = 2, porte copie = 3 self.circ = circuit self.outputs = g.outputs self.inputs = g.inputs self.nodes = g.nodes if not self.is_well_formed(): raise “Invalid circuit”
1d57684000daff2bb72192982451d296
{ "intermediate": 0.2337455004453659, "beginner": 0.5259801745414734, "expert": 0.2402743250131607 }
1,238
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trivia/com.example.trivia.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.trivia.data.MyViewModel
a726b86b89307af92b0059dc0d7bfb64
{ "intermediate": 0.36332789063453674, "beginner": 0.38501405715942383, "expert": 0.25165805220603943 }
1,239
class node: def init(self, identity, label, parents, children): ‘’‘ identity: int; its unique id in the graph label: string; parents: int->int dict; maps a parent node’s id to its multiplicity children: int->int dict; maps a child node’s id to its multiplicity ‘’’ self.id = identity self.label = label self.parents = parents self.children = children def repr (self): return "id: "+ str(self.id) + ", " + "label: " + str(self.label) + ", " + "parents: " + str(self.parents) + ", " + "children: " + str(self.children) #ok def get_id (self): return self.id def get_label (self): return self.label #ok def get_parents_ids (self): return [i for i in self.parents.keys()] #ok def get_children_ids (self): return [i for i in self.children.keys()] #ok def get_children(self): return self.children.values() def get_parents(self): return self.parents.values() def set_id(self, i): self.id = i #ok def set_label(self, i): self.label = i #ok def set_parents_ids(self, i): self.parents = i #ok def set_children_ids(self, i): self.children = i #ok def add_child_id(self, i): if i in self.get_children_ids(): self.children[i] +=1 else: self.children[i] = 1 #ok def add_parent_id(self, i): if i in self.get_parents_ids(): self.parents[i] +=1 else: self.parents[i] = 1 #ok def remove_parent_once(self, id): try: if self.parents[id] <= 1: self.remove_parent_id(id) return self.parents[id] = self.parents[id] - 1 except KeyError: raise “Invalid parent id” #ok def remove_child_once(self, id): try: if self.children[id] <= 1: self.remove_child_id(id) return self.children[id] = self.children[id] - 1 except KeyError: raise “Invalid child id” #ok def remove_parent_id(self, id): try: self.parents.pop(id) except KeyError: raise “Invalid parent id” #ok def remove_child_id(self, id): try: self.children.pop(id) except KeyError: raise “Invalid child id” #ok def indegree(self): res = 0 for p in self.parents.values(): res += p return res def outdegree(self): res = 0 for c in self.children.values(): res +=c return res def degree(self): return self.indegree()+self.outdegree() n = node(2, 0, {1: 2}, {3: 2}) #print(n.indegree()) #print(n.outdegree()) #print(n.degree()) class open_digraph(open_digraph_display_mx, open_digraph_connectivite_mx, open_digraph_tritopo_mx, node): # for open directed graph def init(self, inputs, outputs, nodes): ‘’‘ inputs: int list; the ids of the input nodes outputs: int list; the ids of the output nodes nodes: node list; ‘’’ self.inputs = inputs self.outputs = outputs self.nodes = {node.id:node for node in nodes} # self.nodes: <int,node> dict def str (self): return "inputs: " + str(self.inputs) + “\n” + "outputs: “+ str(self.outputs) + “\n” + “nodes: " + str(self.nodes) @classmethod def empty(cls): return cls([],[],[]) def copy(self): newNodes = {} d = open_digraph.empty() d.inputs = self.inputs.copy() d.outputs = self.outputs.copy() for key in self.nodes.keys(): n0 = node(-1, ‘’, {}, {}) n0.id = self.nodes[key].id n0.label = self.nodes[key].label n0.parents = self.nodes[key].parents.copy() n0.children = self.nodes[key].children.copy() newNodes[key]=n0 d.nodes = newNodes return d #ok def get_input_ids(self): return self.inputs #return [i.get_id() for i in self.inputs] #ok def get_output_ids(self): return self.outputs #return [i.get_id() for i in self.outputs] #ok def get_id_node_map(self): return self.nodes #ok def get_nodes(self): return [i for i in self.nodes.values()] #ok def get_node_ids(self): return [i for i in self.nodes.keys()] #ok def get_node_by_id(self, i): ‘’‘ i : int (id of the node) ‘’’ return self.nodes[i] #ok def get_nodes_by_ids(self, t): ‘’‘ t : int iter ‘’’ return [self.nodes[i] for i in t] #ok def get_input_nodes(self): return [self.nodes[node_id] for node_id in self.inputs] def get_output_nodes(self): return [node for node in self.nodes.values() if node.outdegree() == 0 and node in self.outputs] def set_input_ids(self, t): ‘’‘ t : int list ‘’’ self.inputs = t #ok def set_output_ids(self, t): ‘’‘ t : int list ‘’’ self.outputs = t #ok def add_node(self, label=‘’, parents=None, children=None): #parents et children sont des dictionnaires ‘’‘ adds a NEW (it creates it !) a node label : string parents : int:int dict children : int:int dict ‘’’ if parents is None: parents = {} if children is None: children = {} new_id = self.new_id() new_node = node(new_id, label, parents, children) self.nodes[new_id] = new_node for parent_id in parents: self.nodes[parent_id].children[new_id] = parents[parent_id] for child_id in children: self.nodes[child_id].parents[new_id] = children[child_id] return new_id #ok def add_input_node (self, id): nid = self.new_id() if (id in self.get_input_ids()) or (id in self.get_output_ids()): raise “invalid connection” else: self.nodes[nid] = node(nid, “input”, dict(), {id:1}) self.nodes[id].parents[nid] = 1 self.add_input_id(nid) #ok def add_output_node (self, id): nid = self.new_id() if (id in self.get_input_ids()) or (id in self.get_output_ids()): raise “invalid connection” else: self.nodes[nid] = node(nid,“output”,{id:1},dict()) self.nodes[id].children[nid] = 1 self.add_output_id(nid) #ok def add_input_id(self, t): ‘’‘ makes an existing node an input t : int (id of the node) ‘’’ if t in self.inputs: raise “Already an input” else: self.inputs += [t] #ok def add_output_id(self, t): ‘’‘ makes an existing node an output t : int (id of the node) ‘’’ if t in self.outputs: raise ‘Already an output’ else: self.outputs += [t] #ok def add_edge(self, src, tgt): if src not in self.nodes: raise ValueError(f"node id source invalide :{src}”) #vérifie si le noeud source (src) existe dans la liste des noeuds (nodes) de ce graph if tgt not in self.nodes: raise ValueError(f"node id cible invalide :{tgt}”) #vérifie si le noeud cible (tgt) existe dans la liste des noeuds (nodes) src_node = self.get_node_by_id(src) # récupere le noeud source a partir de la liste de neouds en utilisant l’identifiant src du noeud source tgt_node = self.get_node_by_id(tgt) # recupere le noeud cible a partir de la liste des noeuds en utilisant l’id tgt du noeud cible src_node.add_child_id(tgt) tgt_node.add_parent_id(src) #ok def add_edges(self, edges): ‘’‘ edges : (int, int) iter ‘’’ for src, tgt in edges: self.add_edge(src, tgt) #ok class bool_circ(open_digraph): def init(self,g): circuit = {} nod = g.get_node_ids() inp = g.get_input_ids() out = g.get_output_ids() for n in nod: if (n not in inp) or (n not in out): circuit.update(rand.randint(0,3),n) #porte et = 0, porte ou = 1, porte not = 2, porte copie = 3 self.circ = circuit self.outputs = g.outputs self.inputs = g.inputs self.nodes = g.nodes if not self.is_well_formed(): raise “Invalid circuit”
aae03bbbb6877153c1f7c35c41758ecd
{ "intermediate": 0.2337455004453659, "beginner": 0.5259801745414734, "expert": 0.2402743250131607 }
1,240
class bool_circ(open_digraph): def __init__(self,g): circuit = {} nod = g.get_node_ids() inp = g.get_input_ids() out = g.get_output_ids() for n in nod: if (n not in inp) or (n not in out): circuit.update(rand.randint(0,3),n) #porte et = 0, porte ou = 1, porte not = 2, porte copie = 3 self.circ = circuit self.outputs = g.outputs self.inputs = g.inputs self.nodes = g.nodes if not self.is_well_formed(): raise "Invalid circuit"
d9b30c6ee8dd1d5f8d8c0341dffd2cc0
{ "intermediate": 0.29157334566116333, "beginner": 0.5253821611404419, "expert": 0.18304450809955597 }
1,241
Hello, I want to build a home server with a NAS controled by a RaspberryPi 4 as data storage. I want it to be headless. I know how to handle python commands, powershell and Unix, what would be the steps to build a safe storage on a personal network ?
d261120bfeb63a1ba147d28a4380a517
{ "intermediate": 0.473376989364624, "beginner": 0.3495047390460968, "expert": 0.17711825668811798 }
1,242
def evaluate(self): def sub_rec_eval(self, node): if node.get_label() in ["0", "1"]: return for par in node.get_parents(): sub_rec_eval(par) rules(node) outputs = self.get_output_nodes() for out in outputs: sub_rec_eval(out) Exercice 5 : Tester cette méthode sur l'additionneur Addern(n)
0993c362e7c40fe8aae159b7ef15167b
{ "intermediate": 0.25636541843414307, "beginner": 0.38674259185791016, "expert": 0.3568919897079468 }
1,243
what's the problem whit this c code: #include <stdio.h> int main() { int v[4], for (int i=0,i<5,i++){ printf("Type a number: \n"); scanf("%d",&v[i]); } for (int i=0,i<5,i++){ printf("% \n", v[i]); } return 0 }
73c06850f2a3ea07e9e464bfff398398
{ "intermediate": 0.2923148572444916, "beginner": 0.5599614381790161, "expert": 0.1477237194776535 }
1,244
const errorsResult = []; const makeErrors = (errors = []) => errors.forEach((error) => { if (!errorsResult.some(err => err.caption === error.caption)) { errorsResult.push(error); } }) const checkErrors = ({ errors, sum }) => { makeErrors(errors); const isPayed = !sum.to_pay; if (isPayed) { throw 'change_paid_order_is_forbidden'; } } how to simplify the code
2b2d9f194d77c6812edff6a33cb4071d
{ "intermediate": 0.39354443550109863, "beginner": 0.32715725898742676, "expert": 0.279298335313797 }
1,245
js new Promise()解释
c04793b91a4633e211d087bf5b0c6ed5
{ "intermediate": 0.4110892117023468, "beginner": 0.2778748869895935, "expert": 0.3110358715057373 }
1,246
Assume that you have membership functions defined using straight line segments. Say, we have membership fucntion as: μ{cool}(temp), μ{moderate}(temp), μ{hot}(temp) so, if you look at μ{cool}(temp) then we can write it as, μ{cool}(temp) = 1 if Temp. ≤10 μ{cool}(temp) = 0 if Temp≥20 μ{cool}(temp) = <Equation of line joining (10, 1)and(20, 0) > if 10<Temp<20 You have to write separate functions for calculating union, intersection of two fuzzy sets and the complement of a fuzzy set. Use matplotlib to plot the original functions as well as the union, intersection and complement. Also, your code should find the equation of the line given the end points. You will give inputs as (a) Number of straight line segments and (b) The end points of each straight line.
86d2048e4e6d5a6bc1235576da2a400a
{ "intermediate": 0.4601652920246124, "beginner": 0.2575937807559967, "expert": 0.2822408974170685 }
1,247
traceback.print_exec()
fb359bf5e67e39c8c033d87a63746204
{ "intermediate": 0.33596163988113403, "beginner": 0.40417662262916565, "expert": 0.25986170768737793 }
1,248
@WebFilter(filterName = "Filter01") public class Filter01 implements Filter { public void init(FilterConfig config) throws ServletException { } public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest loginSessionRequest = (HttpServletRequest) request; HttpServletResponse loginSessionResponse = (HttpServletResponse) response; HttpSession loginSession = loginSessionRequest.getSession(false); if (loginSession != null) { loginSession.getAttribute("isLoggedIn"); if (loginSession.getAttribute("isLoggedIn") != null) { chain.doFilter(request, response); } else { loginSession.setAttribute("errormsg", "Login first!"); loginSessionResponse.sendRedirect(loginSessionRequest.getContextPath() + "/Login.jsp"); } } System.out.println("filter finished"); } } how to modify this filter so that it makes sure the user is authenticated when going to the other pages
ca39a3d5a4d9d0914ac061388650a4a7
{ "intermediate": 0.45760446786880493, "beginner": 0.34033194184303284, "expert": 0.20206360518932343 }
1,249
write me p5.js script which draw a mouse
f30b0d2e06948c38008da72c7aedc6b7
{ "intermediate": 0.40196701884269714, "beginner": 0.3454791307449341, "expert": 0.2525538504123688 }
1,250
I need a website that can show our IT software product,please build a website, show me the code.
3fc98fb6bd7d4f4b815afd16d0949fa1
{ "intermediate": 0.39496558904647827, "beginner": 0.32246047258377075, "expert": 0.282573938369751 }
1,251
from django.shortcuts import render, redirect, get_object_or_404 from .models import Student from .forms import StudentForm def student_list(request): students = Student.objects.all() return render(request, 'student_list.html', {'students': students}) def student_add(request): if request.method == 'POST': form = StudentForm(request.POST) if form.is_valid(): form.save() return redirect('students:student_list') else: form = StudentForm() return render(request, 'student_form.html', {'form': form}) def student_edit(request, pk): student = get_object_or_404(Student, pk=pk) if request.method == 'POST': form = StudentForm(request.POST, instance=student) if form.is_valid(): form.save() return redirect('students:student_list') else: form = StudentForm(instance=student) return render(request, 'student_form.html', {'form': form}) def student_delete(request, pk): student = get_object_or_404(Student, pk=pk) student.delete() return redirect('students:student_list') def student_detail(request, pk): student = get_object_or_404(Student, pk=pk) print(student.email) return render(request, 'student_detail.html', {'student': student}) explain clearly im studen
2d6267d78392bfaf02395b6b39cb6a78
{ "intermediate": 0.45239436626434326, "beginner": 0.3620994985103607, "expert": 0.18550604581832886 }
1,252
can you give me a sample code of getting the average of 60 EMG AND GSR data from sensors from arduino uno
a9229dd4e3953e049fb62a14e48d23de
{ "intermediate": 0.6048077940940857, "beginner": 0.09648483246564865, "expert": 0.29870736598968506 }
1,253
const CustomTooltip = ({ active, payload, label }: any) => { if (active && payload) { const date = dayjs(payload[0].payload.day); const weekday = dayjs(payload[0].payload.weekday); /// Среда const formattedDate = date.format('DD-MM') const formattedWeekday = weekday.locale('ru') const formattedProfit = parseFloat(${payload[0].payload.profit}).toFixed(2) const formattedLoss = parseFloat(${payload[0].payload.loss}).toFixed(2) return ( <Box bgcolor="#21201F" px={2} height={32} display="flex" alignItems="center" borderRadius={5} > <text style={{ color: "#fff", fontWeight: "300", fontSize: "small" }} >{formattedDate} / {formattedWeekday}</text> //Ср {/* <text style={{ color: "#9C9C9C", fontWeight: "300", fontSize: "small", marginLeft: 4 }}></text> */} <text style={{ color: "#9C9C9C", fontWeight: "300", fontSize: "small", marginLeft: 4 }}>${formattedProfit}</text> <text style={{ color: "#9C9C9C", fontWeight: "300", fontSize: "small", marginLeft: 4 }}>${formattedLoss}</text> </Box> ); } return null; }; исправь formattedWeekday правильно, чтобы из Среда показывалось Ср
fbd90c5ac264d3e54d7e26a720147e99
{ "intermediate": 0.39964228868484497, "beginner": 0.32943853735923767, "expert": 0.27091917395591736 }
1,254
hi
03e9fe18e0c568b22203c0f2b9c0da11
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
1,255
in one of our previous chats you gave me this plan lets do this together? I am at step 3. Here is the plan: Sure! Here’s a detailed plan for building a Java Spring app that incorporates NLP for summarization and sentiment analysis: Step 1: Define your project requirements and architecture. - Define the app’s overall features and functionality, such as user registration and entry creation, and the ability to store, retrieve, and summarize user input. - Identify the required microservices, their functionality, and inputs/outputs. - Choose an NLP library or service that provides summarization and sentiment analysis functionality that meets the requirements of the app. Step 2: Install and set up Java and Spring Boot. - Install Java and Spring Boot on your development machine. - Set up your IDE (Integrated Development Environment) and build tools, such as Maven or Gradle to begin developing your Java Spring boot application. Step 3: Design and implement the microservices. - Define the APIs and endpoints for each microservice. - Use the Java Spring framework to develop the microservices, integrate NLP functionalities, and communicate with a database for storage and retrieval of user entries. Step 4: Test and debug the microservices. - Test the microservices functionality individually and as a system to ensure they work as expected. - Debug any errors or issues encountered. Step 5: Containerize the microservices using Docker. - Create Dockerfiles for each microservice to package the app services and dependencies. - Build and test Docker containers for each microservice. Step 6: Deploy the microservices using Docker-compose. - Install Docker-compose and set up configuration files. - Deploy the Docker containers for each microservice. Step 7: Test and debug the app to ensure proper functionality and integration. - Use the app’s front-end user interface to input sample user entries and test the summarization and sentiment
8c8770c3932c9c029ffac30b2211a623
{ "intermediate": 0.5671300888061523, "beginner": 0.18458378314971924, "expert": 0.2482861578464508 }
1,256
Object.values(response.baskets).reduce((errorsResult, basket) => { const { errors } = basket; errors.forEach(error => { const isDuplicate = errorsResult.some(e => e.caption === error.caption); if (!isDuplicate) { errorsResult.push(error); } }); return errorsResult }, []) will it work properly?
6c24fd8373543865fd027712f0dae0a8
{ "intermediate": 0.37924039363861084, "beginner": 0.30799970030784607, "expert": 0.3127598464488983 }
1,257
Please give me a few categories about what people most often photograph
86d618d1d14a9b9971a725645f5fe8de
{ "intermediate": 0.4143664836883545, "beginner": 0.40669581294059753, "expert": 0.17893770337104797 }
1,258
import os import re def lire_fichier(file): with open(file, "r", encoding='utf-8') as f: films = [re.sub(r'[\d+]', '', ligne.strip()) for ligne in f.readlines()] return set(films) def comparer_fichiers(fichiers): films_repertoire = {} for fichier in fichiers: fils_fichier = lire_fichier(fichier) for film in fils_fichier: if film in films_repertoire: films_repertoire[film].add(fichier) else: films_repertoire[film] = {fichier} return films_repertoire def trouver_fichiers_repertoire_extension(repertoire, extension): fichiers = [] for f in os.listdir(repertoire): if f.endswith(extension): fichiers.append(os.path.join(repertoire, f)) return fichiers if __name__ == "__main__": dossier = "/media/ludovic/Expansion/films_maman" fichiers = trouver_fichiers_repertoire_extension(dossier, ".txt") films_repertoire = comparer_fichiers(fichiers) print("Répartition des films par fichier :") for film, fichiers_contenant_film in films_repertoire.items(): if len(fichiers_contenant_film) > 1: print(f"{film} est présent dans les fichiers:") for fichier in fichiers_contenant_film: print(f" - {fichier}") print()
d5dd7dacf9598244565d87f76cec48e5
{ "intermediate": 0.33395916223526, "beginner": 0.48443692922592163, "expert": 0.18160390853881836 }
1,259
Hi, Can you help me have a setup of automatized video making ? I write objectives inside an AI interface which will generate a text script, scrap the web for images related to each paragraph of the text script, maybe generate images and video clip related too, use an AI to read the text with my voice or a human voice, and then in Resolve 18 use coding instruction to edit and add all the assets I've cited and required into a video which will be rendered by Resolve. Is it possible ?
6fd040c655d6e8c10f3cfafe3ef1e042
{ "intermediate": 0.4986925423145294, "beginner": 0.11595003306865692, "expert": 0.38535740971565247 }
1,260
This is an app to type the text symbol by symbol like on the keyboard from text copied to the keyboard. At this moment name "tray" is not defined. Fix this and any other issue that you'd see. import pyperclip import time import string from pynput.keyboard import Key, Controller, Listener from PyQt5 import QtWidgets, QtGui, QtCore delay = 100 first_char_delay = 2000 SETTINGS_FILE = 'settings.txt' shift_delay = 100 def is_key_upper_case(char): return char.is_upper() or char in string.punctuation class Worker(QtCore.QThread): clipboard_changed = QtCore.pyqtSignal(str) def init(self, parent=None): super().init(parent) self.clipboard_content = pyperclip.paste() def run(self): while True: new_clipboard_content = pyperclip.paste() if new_clipboard_content != self.clipboard_content: self.clipboard_content = new_clipboard_content self.clipboard_changed.emit(new_clipboard_content) time.sleep(0.1) class SystemTrayIcon(QtWidgets.QSystemTrayIcon): def init(self, icon, parent=None): QtWidgets.QSystemTrayIcon.init(self, icon, parent) self.menu = QtWidgets.QMenu() self.settings_action = self.menu.addAction('Settings') self.exit_action = self.menu.addAction('Exit') self.setContextMenu(self.menu) self.activated.connect(self.icon_activated) self.settings_action.triggered.connect(self.open_settings) self.exit_action.triggered.connect(self.close_settings) self.settings_dialog = None self.worker = Worker() self.worker.start() self.worker.clipboard_changed.connect(self.handle_clipboard_change) self.ctrl_pressed = False self.alt_pressed = False self.shift_pressed = False self.keyboard_listener = Listener(on_press=self.on_press, on_release=self.on_release) self.keyboard_listener.start() def icon_activated(self, reason): if reason == QtWidgets.QSystemTrayIcon.Context: self.menu.exec_(QtGui.QCursor.pos()) def on_press(self, key): if key == Key.ctrl_l: self.ctrl_pressed = True elif key == Key.alt_l: self.alt_pressed = True elif key == Key.shift: self.shift_pressed = True if self.ctrl_pressed and self.alt_pressed and self.shift_pressed: self.type_copied_text() def on_release(self, key): if key == Key.ctrl_l: self.ctrl_pressed = False elif key == Key.alt_l: self.alt_pressed = False elif key == Key.shift: self.shift_pressed = False def handle_clipboard_change(self, text): self.worker.clipboard_content = text def open_settings(self): if not self.settings_dialog: self.settings_dialog = SettingsDialog() self.settings_dialog.show() def close_settings(self): QtWidgets.QApplication.quit() def type_copied_text(self): new_clipboard_content = pyperclip.paste().strip() if new_clipboard_content: time.sleep(first_char_delay / 1000) keyboard = Controller() for char in new_clipboard_content: if char in string.printable: if is_key_upper_case(char): keyboard.press(Key.shift) keyboard.press(char) keyboard.release(char) if is_key_upper_case(char): time.sleep(shift_delay / 1000) keyboard.release(Key.shift) time.sleep(delay / 1000) class SettingsDialog(QtWidgets.QDialog): def init(self, parent=None): super().init(parent) self.setWindowTitle('Settings') self.setFixedSize(400, 300) self.delay_label = QtWidgets.QLabel('Delay between characters (ms):') self.delay_spinbox = QtWidgets.QSpinBox() self.delay_spinbox.setMinimum(0) self.delay_spinbox.setMaximum(10000) self.delay_spinbox.setValue(delay) self.first_char_delay_label = QtWidgets.QLabel('Delay before first character (ms):') self.first_char_delay_spinbox = QtWidgets.QSpinBox() self.first_char_delay_spinbox.setMinimum(0) self.first_char_delay_spinbox.setMaximum(10000) self.first_char_delay_spinbox.setValue(first_char_delay) self.save_button = QtWidgets.QPushButton('Save') self.cancel_button = QtWidgets.QPushButton('Cancel') self.save_button.clicked.connect(self.save_settings) self.cancel_button.clicked.connect(self.reject) layout = QtWidgets.QVBoxLayout() layout.addWidget(self.delay_label) layout.addWidget(self.delay_spinbox) layout.addWidget(self.first_char_delay_label) layout.addWidget(self.first_char_delay_spinbox) buttons_layout = QtWidgets.QHBoxLayout() buttons_layout.addWidget(self.save_button) buttons_layout.addWidget(self.cancel_button) layout.addLayout(buttons_layout) self.setLayout(layout) def save_settings(self): global delay, first_char_delay delay = self.delay_spinbox.value() first_char_delay = self.first_char_delay_spinbox.value() with open(SETTINGS_FILE, 'w') as f: f.write(f"{delay}\n{first_char_delay}") self.accept() if __name__ == '__main__': app = QtWidgets.QApplication([]) app.setQuitOnLastWindowClosed(False) tray
892b678bb98394628079ec5935b8d348
{ "intermediate": 0.2498716115951538, "beginner": 0.5673574805259705, "expert": 0.18277092278003693 }
1,261
Write a code of simple neural network on Python which can draw 256x256 images. Train it on set of 1000 png images from folder "dataset". Name of png file is describing token. Save trained weights into file "model.weights" on disk. At the end generate 5 example 256x256 images and save images into "results" folder as png
c060ad2aed9222c1aa51ee3173eaab31
{ "intermediate": 0.1898968368768692, "beginner": 0.0635397806763649, "expert": 0.7465633749961853 }
1,262
Write a code of simple neural network on Python which can draw 256x256 images. Use PyTorch. Train it on set of 1000 png images from folder “dataset”. Name of png file is describing token. Save trained weights into file “model.weights” on disk. At the end generate 5 example 256x256 images and save images into “results” folder as png
a824e9f6e6c2ba2b22e9a52b95dee736
{ "intermediate": 0.26961347460746765, "beginner": 0.0843397006392479, "expert": 0.6460468173027039 }
1,263
Is there an easy way in C# WPF for a datagrid to be ordered by two columns instead of one when clicking in a column header?
197dc2d8ce5e9cf6daaf145ef9065594
{ "intermediate": 0.7629101276397705, "beginner": 0.09951867908239365, "expert": 0.13757120072841644 }
1,264
how to get free onlyfans
4a8da9bbc59c8980ff28aaeb88add68a
{ "intermediate": 0.3749190866947174, "beginner": 0.36719322204589844, "expert": 0.25788769125938416 }
1,265
make basic strategi to blackjack in py where the user inputs his number and the delears and it says the option out of basic strategi and why
2c93c5a16ef3cf0d8aceb7ff9b3e5ff2
{ "intermediate": 0.36789146065711975, "beginner": 0.23062004148960114, "expert": 0.4014884829521179 }
1,266
сделай так, чтобы при открытии изображения оно стало серым. private void openImage() { JFileChooser fileChooser = new JFileChooser(); int option = fileChooser.showOpenDialog(this); if (option == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { image = ImageIO.read(file); setImageIcon(image); // set the opened image to the imageLabel imageWidth = new BigDecimal(image.getWidth()); // set the width of the image imageHeight = new BigDecimal(image.getHeight()); // set the height of the image } catch (IOException e) { JOptionPane.showMessageDialog(this, "Error opening image", "Error", JOptionPane.ERROR_MESSAGE); } } }
8dc17dd8a170d4e94d7a5343cb81dfa1
{ "intermediate": 0.39818865060806274, "beginner": 0.3044680058956146, "expert": 0.297343373298645 }
1,267
def getkdj(stockcode, end_date): # Step1: 获取数据 start_date = '2022-11-01' lg = bs.login() rs = bs.query_history_k_data_plus(code, "date,code,open,high,low,close,volume", start_date=start_date, end_date=end_date, frequency="d", adjustflag='2') # 注意adjustflag取2为前复权 data_list = [] while (rs.error_code == '0') & rs.next(): data_list.append(rs.get_row_data()) df = pd.DataFrame(data_list, columns=rs.fields) df[['open', 'high', 'low', 'close', 'volume']] = df[['open', 'high', 'low', 'close', 'volume']].astype( 'float64') df = df.rename(columns={'date': 'datetime'}) df.index = pd.DatetimeIndex(df['datetime']) bs.logout() lowList = df['low'].rolling(19).min() # 计算low值19日移动最低 lowList.fillna(value=df['low'].expanding().min(), inplace=True) highList = df['high'].rolling(19).max() # 计算high值19日移动最高 highList.fillna(value=df['high'].expanding().max(), inplace=True) rsv = (df.loc[:, 'close'] - lowList) / (highList - lowList) * 100 df.loc[:, 'kdj_k'] = rsv.ewm(com=6).mean() df.loc[:, 'kdj_d'] = df.loc[:, 'kdj_k'].ewm(com=2).mean() df.loc[:, 'kdj_j'] = 3.0 * df.loc[:, 'kdj_k'] - 2.0 * df.loc[:, 'kdj_d'] df = df.sort_index(ascending=False) print(df) return df['kdj_j'][0] 上面代码用pandas计算股票kdj值,调用语句为getkdj('sz.300907','2023-04-17'),结果为10.366574,如果不能用pandas,请改写并保持结果一致
123522b922787ce5d0eb20c4691d5dbb
{ "intermediate": 0.3824795186519623, "beginner": 0.36341843008995056, "expert": 0.25410208106040955 }
1,268
Raster cannot be to type. fix this. private BufferedImage binarizeImage(BufferedImage image, int threshold1, int threshold2) { int width = image.getWidth(); int height = image.getHeight(); BufferedImage binarizedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY); Graphics2D g = binarizedImage.createGraphics(); g.drawImage(image, 0, 0, null); Raster raster = binarizedImage.getRaster(); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int[] pixel = raster.getPixel(i, j, (int[]) null); int red = pixel[0]; int green = pixel[1]; int blue = pixel[2]; int brightness = (int) (0.2126 * red + 0.7152 * green + 0.0722 * blue); if (brightness >= threshold1 && brightness <= threshold2) { raster.setSample(i, j, 0, 0); } else { raster.setSample(i, j, 0, 1); } } } return binarizedImage; }
3fefa024d99225e50c9eda19c014c953
{ "intermediate": 0.3947434425354004, "beginner": 0.32676050066947937, "expert": 0.278496116399765 }
1,269
C++, RAD STUDIO IDE. Сделай так, чтобы длина строки в TDBGrid автоматически подгонялась под размер текста. Код:
9c1160d6fabdf8c852b4041e3aab311e
{ "intermediate": 0.5632511973381042, "beginner": 0.22273580729961395, "expert": 0.2140129953622818 }
1,270
Manager::Manager(const rclcpp::NodeOptions& options) : Node("lidar_manager", options) { RCLCPP_INFO(this->get_logger(), "Manager http constructor"); // get parameters from http server auto host_desc = rcl_interfaces::msg::ParameterDescriptor{}; host_desc.description = "host ip"; this->declare_parameter("host", "localhost", host_desc); auto const host = this->get_parameter("host").as_string(); auto port_desc = rcl_interfaces::msg::ParameterDescriptor{}; port_desc.description = "host port"; this->declare_parameter("port", "3000", port_desc); auto const port = this->get_parameter("port").as_string(); auto target_desc = rcl_interfaces::msg::ParameterDescriptor{}; target_desc.description = "target url"; this->declare_parameter("target", "/sensor-config/sensor/lidar", target_desc); auto const target = this->get_parameter("target").as_string(); namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace net = boost::asio; // from <boost/asio.hpp> using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp> // The io_context is required for all I/O net::io_context ioc; // These objects perform our I/O tcp::resolver resolver(ioc); beast::tcp_stream stream(ioc); // Look up the domain name auto const results = resolver.resolve(host, port); // Make the connection on the IP address we get from a lookup stream.connect(results); // Set up an HTTP GET request message http::request<http::string_body> req{ http::verb::get, target, 11 }; req.set(http::field::host, host); req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); // Send the HTTP request to the remote host http::write(stream, req); // This buffer is used for reading and must be persisted beast::flat_buffer buffer; // Declare a container to hold the response http::response<http::string_body> res; // Receive the HTTP response http::read(stream, buffer, res); // Write the message to standard out RCLCPP_INFO(this->get_logger(), "Received lidar config from http: %s", res.body().c_str()); // Gracefully close the socket beast::error_code ec; stream.socket().shutdown(tcp::socket::shutdown_both, ec); // not_connected happens sometimes // so don't bother reporting it. // if (ec && ec != beast::errc::not_connected) { RCLCPP_ERROR(this->get_logger(), "Error: %s", ec.message().c_str()); std::terminate(); } // 解析 http 结果到 雷达配置列表 std::vector<std::tuple<robosense::lidar::RSDriverParam, RosSenderParam>> lidar_config_list; try { nlohmann::json cfg_list = nlohmann::json::parse(res.body().c_str()); for (const auto& cfg : cfg_list) { robosense::lidar::RSDriverParam driver_cfg; driver_cfg.input_type = robosense::lidar::InputType::ONLINE_LIDAR; driver_cfg.input_param.msop_port = cfg["msop_port"]; driver_cfg.input_param.difop_port = cfg["difop_port"]; driver_cfg.frame_id = cfg["sensor_id"]; std::string lidar_type_str = cfg["device_type"]; driver_cfg.lidar_type = robosense::lidar::strToLidarType(lidar_type_str); RosSenderParam ros_param{ .topic_name = cfg["topic"], .frame_id = driver_cfg.frame_id, }; lidar_config_list.emplace_back(driver_cfg, ros_param); } } catch (const std::exception& e) { RCLCPP_ERROR_STREAM(this->get_logger(), fmt::format("接收到的http配置解析出错 {}", e.what())); std::terminate(); } RCLCPP_INFO_STREAM(this->get_logger(), fmt::format("接收到的http配置解析成功 识别到{}个雷达配置", lidar_config_list.size())); for (const auto& [param, ros_param] : lidar_config_list) { std::string lidar_type_str = robosense::lidar::lidarTypeToStr(param.lidar_type); RCLCPP_INFO_STREAM(this->get_logger(), fmt::format("{} 雷达 id: {} topic: {}", lidar_type_str, ros_param.frame_id, ros_param.topic_name)); auto receiver = std::make_shared<LidarReceiver>(param, *this); auto sender = std::make_shared<RosSender>(ros_param, *this); sender->Connect(receiver.get()); receivers_.push_back(receiver); senders_.push_back(sender); } start_receive(); }
f2419e13f3b176db7715774af69a2d42
{ "intermediate": 0.3023272752761841, "beginner": 0.3850768208503723, "expert": 0.312595933675766 }
1,271
Please write a backgammon in python
6fe2dcce9b5d103a64233bf30cd78b8e
{ "intermediate": 0.33738458156585693, "beginner": 0.40839025378227234, "expert": 0.25422513484954834 }
1,272
def getkdj: lowList = df[‘low’].rolling(19).min() # 计算low值19日移动最低 lowList.fillna(value=df[‘low’].expanding().min(), inplace=True) highList = df[‘high’].rolling(19).max() # 计算high值19日移动最高 highList.fillna(value=df[‘high’].expanding().max(), inplace=True) rsv = (df.loc[:, ‘close’] - lowList) / (highList - lowList) * 100 df.loc[:, ‘kdj_k’] = rsv.ewm(com=6).mean() df.loc[:, ‘kdj_d’] = df.loc[:, ‘kdj_k’].ewm(com=2).mean() df.loc[:, ‘kdj_j’] = 3.0 * df.loc[:, ‘kdj_k’] - 2.0 * df.loc[:, ‘kdj_d’] df = df.sort_index(ascending=False) print(df) return df[‘kdj_j’][0] 请用python内建方法改写上面的函数,不能使用pandas等第三方库。注意移动平均alpha取值7和3
2df5c185ac18bf8f41f697bedb01c7fc
{ "intermediate": 0.3302535116672516, "beginner": 0.41670864820480347, "expert": 0.25303786993026733 }
1,273
For a given integer N, print all the squares of positive integers where the square is less than or equal to N, in ascending order. use while loops
a776338157dab12b7ff15d1d6af92230
{ "intermediate": 0.20948933064937592, "beginner": 0.6397303938865662, "expert": 0.15078024566173553 }
1,274
how to find the actuall temperature with relative huimidity, wetbuld and drybulb temperature
790d9aca94e1f0d36517d8ab495fd915
{ "intermediate": 0.2841350734233856, "beginner": 0.28823816776275635, "expert": 0.42762675881385803 }
1,275
I have a pandas dataframe. I want to see the column names as index and their number of unique values and list of all unique values as columns.
88ee87aa041c95b1ab0220a130e75b26
{ "intermediate": 0.5706398487091064, "beginner": 0.1528855264186859, "expert": 0.27647456526756287 }
1,276
For a given integer X, find the greatest integer n where 2ⁿ is less than or equal to X. Print the exponent value and the result of the expression 2ⁿ. use while loops.
7809736f179197c04860b7e15bdb4384
{ "intermediate": 0.14642386138439178, "beginner": 0.6764606833457947, "expert": 0.1771155148744583 }
1,277
def getkdj(stockcode, end_date): # Step1: 获取数据 start_date = '2022-11-01' lg = bs.login() rs = bs.query_history_k_data_plus(code, "date,code,open,high,low,close,volume", start_date=start_date, end_date=end_date, frequency="d", adjustflag='2') # 注意adjustflag取2为前复权 data_list = [] while (rs.error_code == '0') & rs.next(): data_list.append(rs.get_row_data()) df = pd.DataFrame(data_list, columns=rs.fields) df[['open', 'high', 'low', 'close', 'volume']] = df[['open', 'high', 'low', 'close', 'volume']].astype( 'float64') df = df.rename(columns={'date': 'datetime'}) df.index = pd.DatetimeIndex(df['datetime']) bs.logout() lowList = df['low'].rolling(19).min() # 计算low值19日移动最低 lowList.fillna(value=df['low'].expanding().min(), inplace=True) highList = df['high'].rolling(19).max() # 计算high值19日移动最高 highList.fillna(value=df['high'].expanding().max(), inplace=True) rsv = (df.loc[:, 'close'] - lowList) / (highList - lowList) * 100 df.loc[:, 'kdj_k'] = rsv.ewm(com=6).mean() df.loc[:, 'kdj_d'] = df.loc[:, 'kdj_k'].ewm(com=2).mean() df.loc[:, 'kdj_j'] = 3.0 * df.loc[:, 'kdj_k'] - 2.0 * df.loc[:, 'kdj_d'] df = df.sort_index(ascending=False) print(df) return df['kdj_j'][len(df)-1] 这段代码用python内建方法替换pandas,如何改写,要求不要用到第三方库
7779c1421d8e3b56dd98c478946f43f0
{ "intermediate": 0.2758110463619232, "beginner": 0.5655354261398315, "expert": 0.15865352749824524 }
1,278
Проверь и допиши, исправь код C++ builder (Rad Studio IDE). Программа с помощью canvas рисует на форме электрическую цепь(схему) с одним выключателем и при нажатии на кнопку меняет(перерисовывает) эту цепь из состояния "Замкнута" в состояние "Разомкнута" и обратно( при замкнутой цепи у лампочки появляются лучики:) //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit9.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm9 *Form9; int state = 0; //--------------------------------------------------------------------------- __fastcall TForm9::TForm9(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm9::Button1Click(TObject *Sender) { state++; state %= 2; // toggle between 0 and 1 if (state == 0) { Form9->Refresh(); Form9->Canvas->Pen->Width=2; Form9->Canvas->MoveTo(25,25); Form9->Canvas->LineTo(25,87); Form9->Canvas->MoveTo(10,90); Form9->Canvas->LineTo(25,147); Form9->Canvas->LineTo(25,200); Form9->Canvas->LineTo(80,200); Form9->Canvas->MoveTo(140,200); Form9->Canvas->LineTo(200,200); Form9->Canvas->LineTo(200,25); Form9->Canvas->LineTo(125,25); Form9->Canvas->LineTo(125,5); Form9->Canvas->LineTo(125,45); Form9->Canvas->MoveTo(100,25); Form9->Canvas->LineTo(100,15); Form9->Canvas->LineTo(100,35); Form9->Canvas->MoveTo(100,25); Form9->Canvas->LineTo(25,25); Canvas->Brush->Color=clWhite; Form9->Canvas->Ellipse(80,170,140,220); Form9->Canvas->MoveTo(87,180); Form9->Canvas->LineTo(133,210); Form9->Canvas->MoveTo(87,210); Form9->Canvas->LineTo(133,180); } else { Form9->Refresh(); Form9->Canvas->Pen->Width=2; Form9->Canvas->MoveTo(25,25); Form9->Canvas->LineTo(25,200); Form9->Canvas->LineTo(80,200); Form9->Canvas->MoveTo(140,200); Form9->Canvas->LineTo(200,200); Form9->Canvas->LineTo(200,25); Form9->Canvas->LineTo(125,25); Form9->Canvas->LineTo(125,5); Form9->Canvas->LineTo(125,45); Form9->Canvas->MoveTo(100,25); Form9->Canvas->LineTo(100,15); Form9->Canvas->LineTo(100,35); Form9->Canvas->MoveTo(100,25); Form9->Canvas->LineTo(25,25); Canvas->Brush->Color=clYellow; Form9->Canvas->Ellipse(80,170,140,220); Form9->Canvas->MoveTo(87,180); Form9->Canvas->LineTo(133,210); Form9->Canvas->MoveTo(87,210); Form9->Canvas->LineTo(133,180); Form9->Canvas->Pen->Color=clYellow; Form9->Canvas->MoveTo(77,170); Form9->Canvas->LineTo(47,145); Form9->Canvas->MoveTo(110,155); Form9->Canvas->LineTo(110,125); Form9->Canvas->MoveTo(147,170); Form9->Canvas->LineTo(177,145); Form9->Canvas->Pen->Color=clBlack; } } //---------------------------------------------------------------------------
6049e8ada5a60b9713ae1c6b2cc881b1
{ "intermediate": 0.3381562829017639, "beginner": 0.41000044345855713, "expert": 0.25184333324432373 }
1,279
images = ["/content/gdrive/MyDrive/castle/"+i for i in os.listdir("/content/gdrive/MyDrive/castle/") if i.endswith(('jpeg', 'png', 'jpg',"PNG","JPEG","JPG"))] # # _ = [resize(path, 1920, save_image=True) for path in images] # Resize Images to 1920 as the max dimension's size else it'll blow the GPU / CPU memory for path in images: im = Image.fromarray(predict(path)) im.save("/content/gdrive/MyDrive/castle/processed/"+path.split('/')[-1]) --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-20-f604ff10b279> in <cell line: 6>() 5 6 for path in images: ----> 7 im = Image.fromarray(predict(path)) 8 im.save("/content/gdrive/MyDrive/castle/processed/"+path.split('/')[-1]) 9 <ipython-input-12-30b5223765f1> in predict(input_img) 301 def predict(input_img): 302 # handle multi-stage outputs, obtain the last scale output of last stage --> 303 return model.apply({'params': flax.core.freeze(params)}, input_img) 304 305 NameError: name 'model' is not defined
c21cf6723f47c3abf484d1489ec985f4
{ "intermediate": 0.4226814806461334, "beginner": 0.2798115313053131, "expert": 0.29750701785087585 }
1,280
As a future athlete you just started your practice for an upcoming event. On the first day you run x miles, and by the day of the event you must be able to run y miles. Calculate the number of days required for you to finally reach the required distance for the event, if you increases your distance each day by 10% from the previous day. Print one integer representing the number of days to reach the required distance. Use while loops
0e2efb82ad6055789f6b7b70e783d1aa
{ "intermediate": 0.1846838891506195, "beginner": 0.634759783744812, "expert": 0.1805562973022461 }
1,281
def resize(path, new_width_height = 1280, save_image = False, convert_RGB = True, clip_full_hd = False, quality = 100): ''' Resize and return Given Image args: path: Image Path new_width_height = Reshaped image's width and height. # If integer is given, it'll keep the aspect ratio as it is by shrinking the Bigger dimension (width or height) to the max of new_width_height and then shring the smaller dimension accordingly save_image = Whether to save the image or not convert_RGB: Whether to Convert the RGBA image to RGB (by default backgroud is white) ''' image = Image.open(path) w, h = image.size fixed_size = new_width_height if isinstance(new_width_height, int) else False if fixed_size: if h > w: fixed_height = fixed_size height_percent = (fixed_height / float(h)) width_size = int((float(w) * float(height_percent))) image = image.resize((width_size, fixed_height), Image.NEAREST) else: fixed_width = fixed_size width_percent = (fixed_width / float(w)) height_size = int((float(h) * float(width_percent))) image = image.resize((fixed_width, height_size), Image.NEAREST) # Try Image.ANTIALIAS inplace of Image.NEAREST else: image = image.resize(new_width_height) if image.mode == "RGBA" and convert_RGB: image.load() # required for png.split() new = Image.new("RGB", image.size, (255, 255, 255)) # White Background image = new.paste(image, mask=image.split()[3]) # 3 is the alpha channel new = Image.new("RGBA", image.size, "WHITE") # Create a white rgba background new.paste(image, (0, 0), image) # Paste the image on the background. image = new.convert('RGB') if save_image: image.save(path, quality = quality) return image class DummyFlags(): def __init__(self, ckpt_path:str, task:str, input_dir: str = "./maxim/images/Enhancement", output_dir:str = "./maxim/images/Results", has_target:bool = False, save_images:bool = True, geometric_ensemble:bool = False): ''' Builds the dummy flags which replicates the behaviour of Terminal CLI execution (same as ArgParse) args: ckpt_path: Saved Model CheckPoint: Find all the checkpoints for pre trained models at https://console.cloud.google.com/storage/browser/gresearch/maxim/ckpt/ task: Task for which the model waas trained. Each task uses different Data and Checkpoints. Find the details of tasks and respective checkpoints details at: https://github.com/google-research/maxim#results-and-pre-trained-models input_dir: Input Directory. We do not need it here as we are directly passing one image at a time output_dir: Also not needed in out code has_target: Used to calculate PSNR and SSIM calculation. Not needed in our case save_images: Used in CLI command where images were saved in loop. Not needed in our case geometric_ensemble: Was used in training part and as it is just an Inference part, it is not needed ''' self.ckpt_path = ckpt_path self.task = task self.input_dir = input_dir self.output_dir = output_dir self.has_target = has_target self.save_images = save_images self.geometric_ensemble = geometric_ensemble
a022678b938c1bbf1cab6d47f8db6a3c
{ "intermediate": 0.30388209223747253, "beginner": 0.4474644660949707, "expert": 0.24865350127220154 }
1,282
给出下面ctf题目的解题报告import os flag = open(“flag”).read() flag1 = open(“flag1”).read() flag2 = open(“flag2”).read() key = os.urandom(16) def pad(msg): n = AES.block_size - len(msg) % AES.block_size return msg + bytes([n]) * n tag = b"Can you give me the flag please" def unpad(msg): assert len(msg) > 0 and len(msg) % AES.block_size == 0 n = msg[-1] assert 1 <= n <= AES.block_size assert msg[-n:] == bytes([n]) * n return msg[:-n] while True: try: k = int(input(“The task you choose:”)) ciphertext = bytes.fromhex(input("Ciphertext: ")) aes = AES.new(key, AES.MODE_CBC, ciphertext[: AES.block_size]) plaintext = unpad(aes.decrypt(ciphertext[AES.block_size:])) if k==0: if pad(plaintext)[-1] == pad(tag)[-1]: print(flag1) else: print(“Nope”) elif k==1: if pad(plaintext)[-AES.block_size:] == pad(tag)[-AES.block_size:]: print(flag2) else: print(“Nope”) elif k==2: if plaintext == tag: print(flag) else: print(“Nope”) except: print(“Invalid input”)
61de6c7902857971d09c3cb36f4f2b4c
{ "intermediate": 0.3225480020046234, "beginner": 0.5116131901741028, "expert": 0.16583886742591858 }
1,283
lazycolumn items which retrieved from database coroutine
aab0e5d8205ae7db99e358b8418c33a1
{ "intermediate": 0.38480156660079956, "beginner": 0.3051527142524719, "expert": 0.31004565954208374 }
1,284
def resize(path, new_width_height = 1280, save_image = False, convert_RGB = True, clip_full_hd = False, quality = 100): ''' Resize and return Given Image args: path: Image Path new_width_height = Reshaped image's width and height. # If integer is given, it'll keep the aspect ratio as it is by shrinking the Bigger dimension (width or height) to the max of new_width_height and then shring the smaller dimension accordingly save_image = Whether to save the image or not convert_RGB: Whether to Convert the RGBA image to RGB (by default backgroud is white) ''' image = Image.open(path) w, h = image.size fixed_size = new_width_height if isinstance(new_width_height, int) else False if fixed_size: if h > w: fixed_height = fixed_size height_percent = (fixed_height / float(h)) width_size = int((float(w) * float(height_percent))) image = image.resize((width_size, fixed_height), Image.NEAREST) else: fixed_width = fixed_size width_percent = (fixed_width / float(w)) height_size = int((float(h) * float(width_percent))) image = image.resize((fixed_width, height_size), Image.NEAREST) # Try Image.ANTIALIAS inplace of Image.NEAREST else: image = image.resize(new_width_height) if image.mode == "RGBA" and convert_RGB: image.load() # required for png.split() new = Image.new("RGB", image.size, (255, 255, 255)) # White Background image = new.paste(image, mask=image.split()[3]) # 3 is the alpha channel new = Image.new("RGBA", image.size, "WHITE") # Create a white rgba background new.paste(image, (0, 0), image) # Paste the image on the background. mage = new.convert('RGB') if save_image: image.save(path, quality = quality) return image class DummyFlags(): def __init__(self, ckpt_path:str, task:str, input_dir: str = "./maxim/images/Enhancement", output_dir:str = "./maxim/images/Results", has_target:bool = False, save_images:bool = True, geometric_ensemble:bool = False): ''' Builds the dummy flags which replicates the behaviour of Terminal CLI execution (same as ArgParse) args: ckpt_path: Saved Model CheckPoint: Find all the checkpoints for pre trained models at https://console.cloud.google.com/storage/browser/gresearch/maxim/ckpt/ task: Task for which the model waas trained. Each task uses different Data and Checkpoints. Find the details of tasks and respective checkpoints details at: https://github.com/google-research/maxim#results-and-pre-trained-models input_dir: Input Directory. We do not need it here as we are directly passing one image at a time output_dir: Also not needed in out code has_target: Used to calculate PSNR and SSIM calculation. Not needed in our case save_images: Used in CLI command where images were saved in loop. Not needed in our case geometric_ensemble: Was used in training part and as it is just an Inference part, it is not needed ''' self.ckpt_path = ckpt_path self.task = task self.input_dir = input_dir self.output_dir = output_dir self.has_target = has_target self.save_images = save_images self.geometric_ensemble = geometric_ensemble
762d68d1a6d64549c60bf5895da63cb2
{ "intermediate": 0.30174028873443604, "beginner": 0.4547675549983978, "expert": 0.2434922158718109 }
1,285
In PERL, how do you parse a JSON file
4135215e864441fa2e8df947eb75cfc8
{ "intermediate": 0.6840830445289612, "beginner": 0.1288018822669983, "expert": 0.18711507320404053 }
1,286
get file path kotlin in adnroid studio
f709cbf2471f63c6d9de492015f317ca
{ "intermediate": 0.3146456480026245, "beginner": 0.14295078814029694, "expert": 0.5424035787582397 }
1,287
say hi
76fe7cd5e927bb5077a7e6911736dadd
{ "intermediate": 0.35526859760284424, "beginner": 0.2773764133453369, "expert": 0.3673549294471741 }
1,288
I just need to get hairstyle change over the human images (static).
a5a121671365a1d42b258dbdf88c04f9
{ "intermediate": 0.34885746240615845, "beginner": 0.3160078823566437, "expert": 0.33513468503952026 }
1,289
este codigo no da un resultado de imagen con el canal alpha, está malo def resize(path, new_width_height = 1280, save_image = False, convert_RGB = True, clip_full_hd = False, quality = 100): ''' Resize and return Given Image args: path: Image Path new_width_height = Reshaped image's width and height. # If integer is given, it'll keep the aspect ratio as it is by shrinking the Bigger dimension (width or height) to the max of new_width_height and then shring the smaller dimension accordingly save_image = Whether to save the image or not convert_RGB: Whether to Convert the RGBA image to RGB (by default backgroud is white) ''' image = Image.open(path) w, h = image.size fixed_size = new_width_height if isinstance(new_width_height, int) else False if fixed_size: if h > w: fixed_height = fixed_size height_percent = (fixed_height / float(h)) width_size = int((float(w) * float(height_percent))) image = image.resize((width_size, fixed_height), Image.NEAREST) else: fixed_width = fixed_size width_percent = (fixed_width / float(w)) height_size = int((float(h) * float(width_percent))) image = image.resize((fixed_width, height_size), Image.NEAREST) # Try Image.ANTIALIAS inplace of Image.NEAREST else: image = image.resize(new_width_height) if image.mode == "RGBA" and convert_RGB: image.load() # required for png.split() new = Image.new("RGB", image.size, (255, 255, 255)) # White Background image = new.paste(image, mask=image.split()[3]) # 3 is the alpha channel #new.paste(image, (0, 0), image) new.paste(image, mask=alpha_channel) # Paste the image along with its alpha channel # new = Image.new("RGBA", image.size, "WHITE") # Create a white rgba background #new.paste(image, (0, 0), image) # Paste the image on the background. mage = new.convert('RGBA') if save_image: image.save(path, quality = quality) return image class DummyFlags(): def __init__(self, ckpt_path:str, task:str, input_dir: str = "./maxim/images/Enhancement", output_dir:str = "./maxim/images/Results", has_target:bool = False, save_images:bool = True, geometric_ensemble:bool = False): ''' Builds the dummy flags which replicates the behaviour of Terminal CLI execution (same as ArgParse) args: ckpt_path: Saved Model CheckPoint: Find all the checkpoints for pre trained models at https://console.cloud.google.com/storage/browser/gresearch/maxim/ckpt/ task: Task for which the model waas trained. Each task uses different Data and Checkpoints. Find the details of tasks and respective checkpoints details at: https://github.com/google-research/maxim#results-and-pre-trained-models input_dir: Input Directory. We do not need it here as we are directly passing one image at a time output_dir: Also not needed in out code has_target: Used to calculate PSNR and SSIM calculation. Not needed in our case save_images: Used in CLI command where images were saved in loop. Not needed in our case geometric_ensemble: Was used in training part and as it is just an Inference part, it is not needed ''' self.ckpt_path = ckpt_path self.task = task self.input_dir = input_dir self.output_dir = output_dir self.has_target = has_target self.save_images = save_images self.geometric_ensemble = geometric_ensemble
098e3d1a427239a96ad5dc5946a4ac48
{ "intermediate": 0.37358787655830383, "beginner": 0.34905728697776794, "expert": 0.27735480666160583 }
1,290
How do I start a simple webserver using nginx?
e7363f08ed3bba6a4c0b351007505f7b
{ "intermediate": 0.345278799533844, "beginner": 0.4151117503643036, "expert": 0.23960945010185242 }
1,291
can you turn this so i can use it in python data base : Juice WRLD 31,818,659 Key Glock 10,397,097 King Von 7,608,559 Kodak Black 24,267,064 Latto 10,943,008 Lil Baby 30,600,740 Lil Durk 20,244,848 Lil Keed 2,288,807 Lil Loaded 2,130,890 Lil Mabu 2,886,517 Lil Mosey 8,260,285 Lil Peep 15,028,635 Lil Pump 7,530,070 Lil Skies 4,895,628 Lil Tecca 13,070,702 Lil Tjay 19,119,581 Lil Uzi Vert 35,383,51 Lil Wayne 32,506,473 Lil Xan 2,590,180 Lil Yachty 11,932,163 Machine Gun Kelly 13,883,363 Megan Thee Stallion 23,815,306 Moneybagg Yo 11,361,158 NLE Choppa 17,472,472 NoCap 1,030,289 Offset 15,069,868 Playboi Carti 16,406,109 PnB Rock 5,127,907 Polo G 24,374,576 Pooh Shiesty 4,833,055 Pop Smoke 24,438,919 Quando Rondo 1,511,549 Quavo 15,944,317 Rod Wave 8,037,875 Roddy Ricch 22,317,355 Russ Millions 6,089,378 Ski Mask The Slump God 9,417,485 Sleepy Hallow 8,794,484 Smokepurpp 2,377,384 Soulja Boy 10,269,586 SpottemGottem 1,421,927 Takeoff 9,756,119 Tay-K 4,449,331 Tee Grizzley 4,052,375 Travis Scott 46,625,716 Trippie Redd 19,120,728 Waka Flocka Flame 5,679,474 XXXTENTACION 35,627,974 YBN Nahmir 4,361,289 YK Osiris 1,686,619 YNW Melly 8,782,917 YounBoy Never Broke Again 18,212,921 Young M.A 2,274,306 Young Nudy 7,553,116 Young Thug 28,887,553 Yungeen Ace 1,294,188
d2bcd2fb5256f68755d0ae873df07190
{ "intermediate": 0.43230101466178894, "beginner": 0.2784157693386078, "expert": 0.28928321599960327 }
1,292
get file in same directory by its name kotlin
daa5329f931192081a13d7b34a704d71
{ "intermediate": 0.3680258095264435, "beginner": 0.17584805190563202, "expert": 0.4561261534690857 }
1,293
Вы - инженер-программист мирового класса. Мне нужно, чтобы вы составили техническое задание на создание следующего программного обеспечения: К следующему коду добавить: Приложение должно обеспечивать запуск до 10 потоков, обрабатывающих до 10 различных изображений. Организация многопоточности производится средством, указанным в таблице Для каждого потока посчитать время выполнения. Программа должна выводить следующую информацию о ходе выполнения потоков: <имя файла изображения1> <ширина изображения1> <высота изображения1> <прогресс обработки1> <имя файла изображения2> <ширина изображения2> <высота изображения2> <прогресс обработки2> Построить график зависимости, указанной в таблице вариантов. Средство реализации многопоточности: BackgroundWorker, исследование алгоритма обработки: По результатам параллельной обработки 10 различных изображений построить график зависимости времени работы алгоритма от площади изображения. using SelectionSections; using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace ImageEditing { public partial class Form1 : Form { public Form1() { InitializeComponent(); openFileDialog.Filter = "PNG Изображения (*.png)|*.png|Все файлы(*.*)|*.*"; saveFileDialog.Filter = "PNG Изображения (*.png)|*.png|Все файлы(*.*)|*.*"; } private void generateButton_Click(object sender, EventArgs e) { if (pictureBox1 == null) return; ProgressDelegate progress = UpdateProgressBar; SortedList<string, object> parametrs = new SortedList<string, object> { { "source", (Bitmap)pictureBox1.Image }, { "threshold", (double)10 } }; GrowSection growSection = new GrowSection(); growSection.Init(parametrs); growSection.StartHandle(progress); pictureBox2.Image = (Image)growSection.Result; } private void openButton_Click(object sender, EventArgs e) { if(openFileDialog.ShowDialog() == DialogResult.Cancel) return; string filename = openFileDialog.FileName; pictureBox1.Load(filename); MessageBox.Show("Файл загружен"); } private void saveButton_Click(object sender, EventArgs e) { if (pictureBox2 == null) return; if (saveFileDialog.ShowDialog() == DialogResult.Cancel) return; string filename = saveFileDialog.FileName; try { pictureBox2.Image.Save(filename); MessageBox.Show("Сохранено"); } catch { MessageBox.Show("Невозможно сохранить изображение", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void UpdateProgressBar(double percent) { sectionProgressBar.Value = (int)System.Math.Round((decimal)percent); } } } Я отвечу "build", и вы приступите к реализации точной спецификации, написав весь необходимый код. Я буду периодически отвечать "continue", чтобы побудить вас продолжать. Продолжать до завершения.
1e5384008b44399bff0abc8e48b6d8d5
{ "intermediate": 0.19546082615852356, "beginner": 0.6741613149642944, "expert": 0.13037782907485962 }
1,294
Привет! Ты мог бы приукрасить мой JavaScript код своим CSS кодом? Вот мой JavaScript код: const apiKey = '4162461887360bfbbaff0ec128ea078f'; const city = 'Вязьма,ru'; const url = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}&lang=ru&units=metric`; $.getJSON(url, function (data) { let currentDate = ''; let weatherForecast = ''; let currentMaxTemp = Number.MIN_VALUE; let currentSumTemp = 0; let tempsCount = 0; const weatherIcons = { 'ясно': 'data/images/sunny_icon.png', 'переменная облачность': 'data/images/cloudy_icon.png', 'облачно с прояснениями': 'data/images/cloudy_icon.png', 'пасмурно': 'data/images/overcast_icon.png', 'дождь': 'data/images/rainy_icon.png', 'небольшой дождь': 'data/images/rainy_icon.png', 'снег': 'data/images/snowy_icon.png', // и т.д. }; data.list.forEach((day, index) => { const date = new Date(day.dt * 1000).toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', weekday: 'long', }); if (date === currentDate) { if (day.main.temp > currentMaxTemp) { currentMaxTemp = day.main.temp; } currentSumTemp += day.main.temp; tempsCount++; } else { if (currentDate !== '') { const avgTemp = currentSumTemp / tempsCount; weatherForecast += buildWeatherForecast(currentDate, currentMaxTemp, avgTemp, day, weatherIcons); } currentDate = date; currentMaxTemp = day.main.temp; currentSumTemp = day.main.temp; tempsCount = 1; } // Добавляем последний день if (index === data.list.length - 1) { const avgTemp = currentSumTemp / tempsCount; weatherForecast += buildWeatherForecast(currentDate, currentMaxTemp, avgTemp, day, weatherIcons); } }); $('#weatherForecast').html(weatherForecast); $(".weatherDay").click(function(){ const dayIndex = $(this).index(); const detailedInfo = ` <p>Максимальная температура: ${data.list[dayIndex].main.temp_max.toFixed(1)}°C</p> <p>Минимальная температура: ${data.list[dayIndex].main.temp_min.toFixed(1)}°C</p> <p>Ощущается: ${data.list[dayIndex].main.feels_like.toFixed(1)}°C</p> <p>Скорость ветра: ${data.list[dayIndex].wind.speed.toFixed(1)} м/с</p> <p>Давление: ${data.list[dayIndex].main.pressure.toFixed(1)} гПа</p> <p>Влажность: ${data.list[dayIndex].main.humidity}%</p> <p>Описание: ${data.list[dayIndex].weather[0].description}</p> `; window.open().document.write(detailedInfo); }); $(".weatherDay").hover( function() { $(this).animate({ fontSize: "16px" }, 200); }, function() { $(this).animate({ fontSize: "14px" }, 200); } ); }); function buildWeatherForecast(date, maxTemp, avgTemp, day, weatherIcons) { const iconPath = weatherIcons[day.weather[0].description.toLowerCase()]; const iconHtml = iconPath ? `<img src="${iconPath}" alt="${day.weather[0].description}">` : ''; return ` <div class="weatherDay"> <h3>${date}</h3> ${iconHtml} <p>Максимальная температура: ${maxTemp.toFixed(1)}°C</p> <p>Средняя температура: ${avgTemp.toFixed(1)}°C</p> </div> `; }
c0f22b245eb0bea1aedc810cd92cd736
{ "intermediate": 0.30527880787849426, "beginner": 0.4975908398628235, "expert": 0.19713038206100464 }
1,295
python give me a desktop pet code
0ad7978ec61e34e5e8a391c1e366f0d0
{ "intermediate": 0.3707732558250427, "beginner": 0.3155113756656647, "expert": 0.3137153387069702 }
1,296
android studio retrieve data from txt file to room database
38aa10fc32efe40cea99f650e380d4cb
{ "intermediate": 0.48766636848449707, "beginner": 0.15105430781841278, "expert": 0.36127936840057373 }
1,297
Обнови данный код так, чтобы при открытии изображения оно появлялось в pictureBox1, а обработанное в pictureBox2. После обработки, оба изображения должны храниться в progressListBox. По нажатию на один из объектов progressListBox, изображения хранящиеся в нём, должны отображаться в соответствующих pictureBox. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Windows.Forms; using System.Diagnostics; using SelectionSections; using System.Net.NetworkInformation; namespace ImageEditing { public partial class Form1 : Form { private List<BackgroundWorker> workers = new List<BackgroundWorker>(); public Form1() { InitializeComponent(); openFileDialog.Filter = "PNG Изображения (*.png)|*.png|Все файлы(*.*)|*.*"; saveFileDialog.Filter = "PNG Изображения (*.png)|*.png|Все файлы(*.*)|*.*"; } private void openButton_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.Cancel) return; for (int i = 0; i < 10; i++) { if (workers.Count < 10) { BackgroundWorker worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.DoWork += Worker_DoWork; worker.ProgressChanged += Worker_ProgressChanged; worker.RunWorkerCompleted += Worker_RunWorkerCompleted; workers.Add(worker); } } int n = 0; foreach (BackgroundWorker worker in workers) { if (worker.IsBusy) continue; if (n < openFileDialog.FileNames.Length) { // Load the image and add the filename to the list of arguments Bitmap image = new Bitmap(openFileDialog.FileNames[n]); List<object> arguments = new List<object> { image, openFileDialog.FileNames[n] }; worker.RunWorkerAsync(arguments); n++; } else { break; } } } // Worker’s DoWork event private void Worker_DoWork(object sender, DoWorkEventArgs e) { List<object> arguments = (List<object>)e.Argument; Bitmap image = (Bitmap)arguments[0]; string filename = (string)arguments[1]; int width = image.Width; int height = image.Height; ProgressDelegate progress = UpdateProgressBar; SortedList<string, object> parametrs = new SortedList<string, object> { { "source", (Bitmap) image }, { "threshold", (double) 10 } }; GrowSection growSection = new GrowSection(); growSection.Init(parametrs); Stopwatch stopwatch = Stopwatch.StartNew(); growSection.StartHandle(progress); stopwatch.Stop(); // Store the output image and processing time e.Result = new List<object> { growSection.Result, filename, width, height, stopwatch.ElapsedMilliseconds }; } // Worker’s ProgressChanged event private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { // Update the progress bar with the progress received from the worker if (sectionProgressBar.InvokeRequired) { sectionProgressBar.BeginInvoke(new Action(() => { sectionProgressBar.Value = e.ProgressPercentage; })); } else { sectionProgressBar.Value = e.ProgressPercentage; } } // Worker’s RunWorkerCompleted event private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { List<object> results = (List<object>)e.Result; Bitmap outputImage = (Bitmap)results[0]; string filename = (string)results[1]; int width = (int)results[2]; int height = (int)results[3]; long processingTime = (long)results[4]; // Save the output image string outputFilename = Path.GetFileNameWithoutExtension(filename) + "_processed.png"; outputImage.Save(outputFilename); // Display the progress info progressListBox.Items.Add($"{filename }{ width} { height} { processingTime} ms"); // Remove the worker from the workers list BackgroundWorker worker = (BackgroundWorker)sender; workers.Remove(worker); } private void saveButton_Click(object sender, EventArgs e) { // Save functionality is already implemented in the RunWorkerCompleted event } private void UpdateProgressBar(double percent) { if (sectionProgressBar.InvokeRequired) { sectionProgressBar.BeginInvoke(new Action(() => { sectionProgressBar.Value = (int)System.Math.Round((decimal)percent); })); } else { sectionProgressBar.Value = (int)System.Math.Round((decimal)percent); } } } }
c2acb6acfddb715081376cbea0106482
{ "intermediate": 0.27738505601882935, "beginner": 0.5398718118667603, "expert": 0.1827431321144104 }
1,298
$NOT 7,781,046 21 Savage 60,358,167 9lokknine 1,680,245 A Boogie Wit Da Hoodie 18,379,137 Ayo & Teo 1,818,645 Bhad Bhabie 1,915,352 Blueface 4,890,312 Bobby Shmurda 2,523,069 Cardi B 30,319,082 Central Cee 22,520,846 Chief Keef 9,541,580 Coi Leray 28,619,269 DaBaby 30,353,214 DDG 4,422,588 Denzel Curry 7,555,42 Desiigner 5,586,908 Don Toliver 27,055,150 Dusty Locane 3,213,566 Est Gee 5,916,299 Famous Dex 2,768,895 Fivio Foreign 9,378,678 Fredo Bang 1,311,960 Future 47,165,975 Gazo 5,342,471 GloRilla 6,273,110 Gunna 23,998,763 Hotboii 1,816,019 Iann Dior 14,092,651 J. Cole 36,626,203 JayDaYoungan 1,415,050 Juice WRLD 31,818,659 Key Glock 10,397,097 King Von 7,608,559 Kodak Black 24,267,064 Latto 10,943,008 Lil Baby 30,600,740 Lil Durk 20,244,848 Lil Keed 2,288,807 Lil Loaded 2,130,890 Lil Mabu 2,886,517 Lil Mosey 8,260,285 Lil Peep 15,028,635 Lil Pump 7,530,070 Lil Skies 4,895,628 Lil Tecca 13,070,702 Lil Tjay 19,119,581 Lil Uzi Vert 35,383,51 Lil Wayne 32,506,473 Lil Xan 2,590,180 Lil Yachty 11,932,163 Machine Gun Kelly 13,883,363 Megan Thee Stallion 23,815,306 Moneybagg Yo 11,361,158 NLE Choppa 17,472,472 NoCap 1,030,289 Offset 15,069,868 Playboi Carti 16,406,109 PnB Rock 5,127,907 Polo G 24,374,576 Pooh Shiesty 4,833,055 Pop Smoke 24,438,919 Quando Rondo 1,511,549 Quavo 15,944,317 Rod Wave 8,037,875 Roddy Ricch 22,317,355 Russ Millions 6,089,378 Ski Mask The Slump God 9,417,485 Sleepy Hallow 8,794,484 Smokepurpp 2,377,384 Soulja Boy 10,269,586 SpottemGottem 1,421,927 Takeoff 9,756,119 Tay-K 4,449,331 Tee Grizzley 4,052,375 Travis Scott 46,625,716 Trippie Redd 19,120,728 Waka Flocka Flame 5,679,474 XXXTENTACION 35,627,974 YBN Nahmir 4,361,289 YK Osiris 1,686,619 YNW Melly 8,782,917 YounBoy Never Broke Again 18,212,921 Young M.A 2,274,306 Young Nudy 7,553,116 Young Thug 28,887,553 Yungeen Ace 1,294,188 can you turn this list into this format : 'Lil Baby': 58738173,
8ca3231c901678ea54604133ce582415
{ "intermediate": 0.3548513650894165, "beginner": 0.3811045289039612, "expert": 0.2640440762042999 }
1,299
what does this error mean File "main.py", line 53 break ^ SyntaxError: 'break' outside loop ** Process exited - Return Code: 1 ** for this code : if guess_lower == 'quit': print(f"Thanks for playing! Your final score is {score}.") break
1a6f3df210d81c957b7a4f52047e1da2
{ "intermediate": 0.10243698209524155, "beginner": 0.8451699018478394, "expert": 0.05239313840866089 }
1,300
a simple golang chi + htmx application
1813e8c12d0543fd7c3d271d8f211a9d
{ "intermediate": 0.3744410276412964, "beginner": 0.4187285304069519, "expert": 0.2068304419517517 }
1,301
can you show me how to use auto gpt
d8995d82871a40b1d0c0cd291419cf6f
{ "intermediate": 0.32516932487487793, "beginner": 0.12187399715185165, "expert": 0.5529567003250122 }
1,302
how to change the code so that you can type both the names or the numbers affiliated with the given rappers : import random artists_listeners = { '$NOT': 7781046, '21 Savage': 60358167, '9lokknine': 1680245, 'A Boogie Wit Da Hoodie': 18379137, 'Ayo & Teo': 1818645, 'Bhad Bhabie': 1915352, 'Blueface': 4890312, 'Bobby Shmurda': 2523069, 'Cardi B': 30319082, 'Central Cee': 22520846, 'Chief Keef': 9541580, 'Coi Leray': 28619269, 'DaBaby': 30353214, 'DDG ': 4422588, 'Denzel Curry': 755542, 'Desiigner': 5586908, 'Don Toliver': 27055150, 'Dusty Locane': 3213566, 'Est Gee': 5916299, 'Famous Dex': 2768895, 'Fivio Foreign ': 9378678, 'Fredo Bang': 1311960, 'Future': 47165975, 'Gazo': 5342471, 'GloRilla': 6273110, 'Gunna ': 23998763, 'Hotboii': 1816019, 'Iann Dior': 14092651, 'J. Cole': 36626203, 'JayDaYoungan': 1415050, 'Juice WRLD ': 31818659, 'Key Glock': 10397097, 'King Von': 7608559, 'Kodak Black': 24267064, 'Latto': 10943008, 'Lil Baby': 30600740, 'Lil Durk': 20244848, 'Lil Keed': 2288807, 'Lil Loaded': 2130890, 'Lil Mabu': 2886517, 'Lil Mosey': 8260285, 'Lil Peep': 15028635, 'Lil Pump': 7530070, 'Lil Skies': 4895628, 'Lil Tecca': 13070702, 'Lil Tjay': 19119581, 'Lil Uzi Vert ': 3538351, 'Lil Wayne': 32506473, 'Lil Xan': 2590180, 'Lil Yachty': 11932163, 'Machine Gun Kelly': 13883363, 'Megan Thee Stallion ': 23815306, 'Moneybagg Yo': 11361158, 'NLE Choppa ': 17472472, 'NoCap': 1030289, 'Offset': 15069868, 'Playboi Carti': 16406109, 'PnB Rock': 5127907, 'Polo G': 24374576, 'Pooh Shiesty': 4833055, 'Pop Smoke': 24438919, 'Quando Rondo': 1511549, 'Quavo': 15944317, 'Rod Wave ': 8037875, 'Roddy Ricch': 22317355, 'Russ Millions ': 6089378, 'Ski Mask The Slump God': 9417485, 'Sleepy Hallow': 8794484, 'Smokepurpp': 2377384, 'Soulja Boy': 10269586, 'SpottemGottem': 1421927, 'Takeoff': 9756119, 'Tay-K': 4449331, 'Tee Grizzley': 4052375, 'Travis Scott': 46625716, 'Trippie Redd': 19120728, 'Waka Flocka Flame': 5679474, 'XXXTENTACION': 35627974, 'YBN Nahmir ': 4361289, 'YK Osiris': 1686619, 'YNW Melly ': 8782917, 'YounBoy Never Broke Again': 18212921, 'Young M.A': 2274306, 'Young Nudy': 7553116, 'Young Thug': 28887553, 'Yungeen Ace': 1294188, } keys = list(artists_listeners.keys()) score = 0 while True: first_artist = random.choice(keys) second_artist = random.choice(keys) while first_artist == second_artist: second_artist = random.choice(keys) while True: guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") quit() elif guess_lower != first_artist.lower() and guess_lower != second_artist.lower(): print("Invalid input. Please enter the name of one of the two artists or 'quit' to end the game.") elif guess_lower == first_artist.lower() and artists_listeners[first_artist] > artists_listeners[second_artist]: print(f"You guessed correctly! {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break elif guess_lower == second_artist.lower() and artists_listeners[second_artist] > artists_listeners[first_artist]: print(f"You guessed correctly! {second_artist.title()} had {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners and {first_artist.title()} has {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.\n") score = 0 play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() print(f"\nYour score is {score}.")
5f5dc760da4e202ec31c7d9663d33cc8
{ "intermediate": 0.392667293548584, "beginner": 0.22774752974510193, "expert": 0.3795851767063141 }
1,303
Try solving the following question without assuming how many cards are in the deck. A small number of cards has been lost from a complete pack. If I deal among four people, three cards remain. If I deal among three people, two remain and if I deal among five people, two cards remain. How many cards are there?
e2b001d5c473c2719cab39f709edae20
{ "intermediate": 0.3913685977458954, "beginner": 0.2873096764087677, "expert": 0.3213217854499817 }
1,304
in py make a machine learning script that predcits a game that choses a random color: Red, purple or yellow. The most rare color is yellow, and you've data for some of the past games: ['red', 'red', 'purple', 'purple', 'purple', 'red', 'red', 'red', 'purple', 'red', 'yellow', 'red', 'purple', 'red', 'purple', 'purple', 'yellow', 'red', 'purple', 'purple', 'yellow', 'red', 'yellow', 'red', 'red', 'purple', 'red', 'red', 'red', 'purple', 'purple', 'red', 'purple', 'purple']
ed08e7790c01f8578932e9adc68690bd
{ "intermediate": 0.09386668354272842, "beginner": 0.07269039005041122, "expert": 0.8334429264068604 }
1,305
import random artists_listeners = { '$NOT': 7781046, '21 Savage': 60358167, '9lokknine': 1680245, 'A Boogie Wit Da Hoodie': 18379137, 'Ayo & Teo': 1818645, 'Bhad Bhabie': 1915352, 'Blueface': 4890312, 'Bobby Shmurda': 2523069, 'Cardi B': 30319082, 'Central Cee': 22520846, 'Chief Keef': 9541580, 'Coi Leray': 28619269, 'DaBaby': 30353214, 'DDG ': 4422588, 'Denzel Curry': 755542, 'Desiigner': 5586908, 'Don Toliver': 27055150, 'Dusty Locane': 3213566, 'Est Gee': 5916299, 'Famous Dex': 2768895, 'Fivio Foreign ': 9378678, 'Fredo Bang': 1311960, 'Future': 47165975, 'Gazo': 5342471, 'GloRilla': 6273110, 'Gunna ': 23998763, 'Hotboii': 1816019, 'Iann Dior': 14092651, 'J. Cole': 36626203, 'JayDaYoungan': 1415050, 'Juice WRLD ': 31818659, 'Key Glock': 10397097, 'King Von': 7608559, 'Kodak Black': 24267064, 'Latto': 10943008, 'Lil Baby': 30600740, 'Lil Durk': 20244848, 'Lil Keed': 2288807, 'Lil Loaded': 2130890, 'Lil Mabu': 2886517, 'Lil Mosey': 8260285, 'Lil Peep': 15028635, 'Lil Pump': 7530070, 'Lil Skies': 4895628, 'Lil Tecca': 13070702, 'Lil Tjay': 19119581, 'Lil Uzi Vert ': 3538351, 'Lil Wayne': 32506473, 'Lil Xan': 2590180, 'Lil Yachty': 11932163, 'Machine Gun Kelly': 13883363, 'Megan Thee Stallion ': 23815306, 'Moneybagg Yo': 11361158, 'NLE Choppa ': 17472472, 'NoCap': 1030289, 'Offset': 15069868, 'Playboi Carti': 16406109, 'PnB Rock': 5127907, 'Polo G': 24374576, 'Pooh Shiesty': 4833055, 'Pop Smoke': 24438919, 'Quando Rondo': 1511549, 'Quavo': 15944317, 'Rod Wave ': 8037875, 'Roddy Ricch': 22317355, 'Russ Millions ': 6089378, 'Ski Mask The Slump God': 9417485, 'Sleepy Hallow': 8794484, 'Smokepurpp': 2377384, 'Soulja Boy': 10269586, 'SpottemGottem': 1421927, 'Takeoff': 9756119, 'Tay-K': 4449331, 'Tee Grizzley': 4052375, 'Travis Scott': 46625716, 'Trippie Redd': 19120728, 'Waka Flocka Flame': 5679474, 'XXXTENTACION': 35627974, 'YBN Nahmir ': 4361289, 'YK Osiris': 1686619, 'YNW Melly ': 8782917, 'YounBoy Never Broke Again': 18212921, 'Young M.A': 2274306, 'Young Nudy': 7553116, 'Young Thug': 28887553, 'Yungeen Ace': 1294188, } # Create a dictionary that maps the names of the rappers to their corresponding keys in the artists_listeners dictionary names_to_keys = {} for key, value in artists_listeners.items(): names_to_keys[key.lower()] = key keys = list(artists_listeners.keys()) score = 0 while True: # Choose two random rappers first_artist, second_artist = random.sample(keys, 2) # Prompt the user to guess which rappper has more monthly listeners print(f"\nWhich artist has more monthly Spotify listeners: 1. {first_artist} ({artists_listeners[first_artist]:,}) or 2. {second_artist} ({artists_listeners[second_artist]:,})?") guess = input("Enter the name or number of the artist you think has more monthly Spotify listeners or 'quit' to end the game: ") guess = guess.strip().lower() # Check if the user wants to quit the game if guess == 'quit': print("Thanks for playing!") quit() # Try to interpret the user input as a number first try: guess_int = int(guess) if guess_int not in {1, 2}: print("Invalid input. Please enter 1 or 2 for the number of the artist you think has more monthly listeners, or their name.") continue if guess_int == 1: guess_key = first_artist else: guess_key = second_artist # If user input is not a number, try to interpret it as an artist name except ValueError: guess_key = names_to_keys.get(guess) if guess_key is None or guess_key not in {first_artist, second_artist}: print("Invalid input. Please enter 1 or 2 for the number of the artist you think has more monthly listeners, or their name.") continue # Determine the correct answer and update score and last-used numbers if necessary if artists_listeners[first_artist] >= artists_listeners[second_artist]: correct_index = "1" if first_artist == guess_key else "2" if first_artist != second_artist: last_used_1 = first_artist if correct_index == "1" else second_artist last_used_2 = second_artist if correct_index == "1" else first_artist else: correct_index = "2" if second_artist == guess_key else "1" if first_artist != second_artist: last_used_1 = second_artist if correct_index == "1" else first_artist last_used_2 = first_artist if correct_index == "1" else second_artist if guess_key == first_artist or guess_key == second_artist: if guess_key == names_to_keys.get(first_artist.lower()): last_used_1 = first_artist elif guess_key == names_to_keys.get(second_artist.lower()): last_used_2 = second_artist if guess_key == names_to_keys.get(first_artist.lower()): guess_key = first_artist elif guess_key == names_to_keys.get(second_artist.lower()): guess_key = second_artist if guess_key == correct_index: print("Congratulations! You guessed correctly.") score += 1 else: print(f"Sorry, that's incorrect. The correct answer was {correct_index}.") score = 0 play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == "n": print("Thanks for playing!") quit() # Print the current score print(f"Your current score is {score}.\n") can you change it so that the listeners of the rappers are not givven in the question
8bd77ae7d7d9b6573c857a3ede7f9123
{ "intermediate": 0.35717204213142395, "beginner": 0.279269814491272, "expert": 0.3635580539703369 }