row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
12,255
Use Python to perform the following tasks: 1. DS1: (a) Design a dataset with at least 50 points for which the selection of C in a linear SVM makes a difference. (b) Load the data set (your own data set), train an SVM with a linear kernel on the full data set, and plot the data set with the decision boundary. (c) Carry out leave-1-out cross-validation with an SVM on your dataset. Report the train and test performance. Train performance in this case is the performance on the training set, test performance, the performance of the leave-1-out crossvalidation. (d) Improve the SVM by changing C. Plot the data set and resulting decision boundary, give the performance. (e) Explain what C does and how it improved the SVM in this case.
2b994011f3a2feada7ce387f780d8e8c
{ "intermediate": 0.38549914956092834, "beginner": 0.13302470743656158, "expert": 0.48147615790367126 }
12,256
Given the two data sets DS2 and DS3. The DS2 and DS3 are csv files. the last column of each data set, stores the labels of the examples of the dataset. Use Python to perform the following tasks: (a) Load the data set,the file path of DS2 is 'C:\Users\11096\Desktop\Machine Learning\Experiment\lab2\D2.csv' , train an SVM with a linear kernel on the full data set, and plot the data set with the decision boundary. (b) Carry out leave-1-out cross-validation with an SVM on your dataset. Report the train and test performance. Train performance in this case is the performance on the training set, test performance, the performance of the leave-1-out cross-validation. (c) Pick a kernel that will improve the SVM, plot the data set and resulting decision boundary, and give the performance. (d) Explain which kernel you chose and why.
df757d29ee17e60c95c2e2462a2463c5
{ "intermediate": 0.34410330653190613, "beginner": 0.18076962232589722, "expert": 0.47512707114219666 }
12,257
Who is albert einstain
95a7a83dae724752413d0ca036599599
{ "intermediate": 0.38777515292167664, "beginner": 0.20690667629241943, "expert": 0.40531817078590393 }
12,258
void circularShift(char* buff, size_t size, Context *ctx, size_t count) { uint bitShift = ctx->shiftCount; char* temp = (char*)malloc(size); memcpy(temp, buff, size); for (size_t i = 0; i < size; i++) { uint index = i; char byte = temp[index]; char shifted_byte = 0; uint index_neighbor = ctx->isNegShift ? (index + size - 1) % size : (index + 1) % size; char byte_neighbor = temp[index_neighbor]; if (ctx->isNegShift == true) { shifted_byte = (byte << bitShift) | (byte_neighbor >> (8 - bitShift)); if (i == size - 1) { shifted_byte = byte << bitShift | (ctx->tempByte >> (8 - bitShift)); } } else { shifted_byte = (byte >> bitShift) | (byte_neighbor << (8 - bitShift)); if (i == 0 && count == 0) { shifted_byte = byte >> bitShift | (ctx->tempByte << (8 - bitShift)); } } buff[index] = shifted_byte; } if (ctx->isNegShift == false && count == 0) { buff[0] |= (ctx->tempByte << (8 - bitShift)); } else if (ctx->isNegShift == true && ctx->isEnd) { buff[size - 1] |= (ctx->tempByte >> (8 - bitShift)); } fprintf(ctx->tempFile, "%s", buff); free(temp); } почему при запуске данного кода средний байт не возвращается в исходные значения ? $ ./a.out test.any 2 01010100 01100101 01110011 01110100 00100001 01010101 11011001 00011100 01011101 00001000 3LogicGroupEntry(master*)$ ./a.out test.any -2 01010101 11011001 00011100 01011101 00001000 01010100 01100101 11111111 01110100 00100001 отредактируй это код так, чтобы возвращался результат $ ./a.out test.any 2 01010100 01100101 01110011 01110100 00100001 01010101 11011001 00011100 01011101 00001000 3LogicGroupEntry(master*)$ ./a.out test.any -2 01010101 11011001 00011100 01011101 00001000 01010100 01100101 01110011 01110100 00100001
030d6e9ed2eb6078bd480755d1f5353d
{ "intermediate": 0.2864154577255249, "beginner": 0.43710359930992126, "expert": 0.27648088335990906 }
12,259
is it allowed to assign new topic to a kafka consumer after it poll messages from the current assigned topics
38bda8e24f1f3bb4df61e9f03603a35f
{ "intermediate": 0.4238474369049072, "beginner": 0.2184237539768219, "expert": 0.3577288091182709 }
12,260
k-means clustering for 2 column of data, separated by comma, in java code
c4a7b85e401372490f72342dc79a2798
{ "intermediate": 0.3352041244506836, "beginner": 0.10455023497343063, "expert": 0.5602455735206604 }
12,261
make an c++ example that create kafka consumer assigned to topic_1 and start to poll message and after 5 time polling, add topic_2 into the assignment and polling message from both topics
b02132fb0601e271f72f26362f89247c
{ "intermediate": 0.5352131128311157, "beginner": 0.19359545409679413, "expert": 0.2711913585662842 }
12,262
No 'Authorization' header, send 401 and 'WWW-Authenticate Basic' comment regler cette erreur
e83b5ea1945d017dcf97875ebd8ed4d1
{ "intermediate": 0.3478497266769409, "beginner": 0.3211335837841034, "expert": 0.3310166597366333 }
12,263
code me a website using html css etc, i want the website to be a annonyms chat room no name required just a big global chat so every one can send a message.
f0cfb5da4d5ce0be3a146bceb8e41fdc
{ "intermediate": 0.43089520931243896, "beginner": 0.191462904214859, "expert": 0.3776419460773468 }
12,264
LibreOffice SDK C++ как задать Font Name
c82467b99ef10d91f389257f982b7f3f
{ "intermediate": 0.5839470624923706, "beginner": 0.21441251039505005, "expert": 0.20164038240909576 }
12,265
вот эта ЧЕРНАЯ ГОРИЗОНТАЛЬНАЯ полоска, смотри скриншот: https://yadi.sk/d/FejQ4LyoT5cEuA как ее убрать? /* audio player */ .audio-player { margin: 50px auto; max-width: 800px; } .audio-player-inner { display: flex; flex-direction: column; justify-content: center; align-items: center; overflow-x: auto; -webkit-overflow-scrolling: touch; } .audio-tracklist { display: flex; flex-direction: row; justify-content: center; align-items: center; flex-wrap: nowrap; margin: 0; padding: 0; list-style: none; } .audio-track { display: flex; flex-direction: column; justify-content: center; align-items: center; margin-right: 20px; margin-bottom: 20px; max-width: 300px; text-align: center; height: auto; position: relative; transition: transform 0.3s; } .audio-track:hover { transform: scale(1.05); } .audio-track-image { width: 100%; height: 0; padding-bottom: 100%; position: relative; } .audio-track-image img { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; filter: brightness(100%); transition: filter 0.3s; } .audio-track:hover img { filter: brightness(70%); } .audio-track-info { width: 100%; margin-top: 10px; text-align: center; } .audio-track-info h4 { margin-top: 0; font-size: 18px; font-weight: bold; } .audio-track-info p { margin-bottom: 0; font-size: 14px; } .audio-player-wrapper { opacity: 0; transition: opacity 0.3s; } .audio-track:hover .audio-player-wrapper { opacity: 1; } .audio-player-button { display: flex; justify-content: center; align-items: center; border: none; background: none; cursor: pointer; margin: 0 auto; } .audio-player-icon { font-size: 24px; margin-top:-250px; color: #333; position: relative; /* добавить свойство position */ z-index: 1; /* добавить свойство z-index */ } .progress-bar { width: 100%; height: 5px; -webkit-appearance: none; appearance: none; background: #ddd; outline: none; cursor: pointer; } .progress-bar::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 15px; height: 15px; border-radius: 50%; background: #333; cursor: pointer; } .progress-bar::-moz-range-thumb { width: 15px; height: 15px; border-radius: 50%; background: #333; cursor: pointer; } .progress-time { font-size: 12px; margin-left: 10px; color: #666; } input[type=range]::-webkit-slider-runnable-track { background: transparent; border: none; } index: <!-- audio player --> <div class="audio-player"> <div class="audio-player-inner"> <div class="audio-tracklist"> <% tracks.forEach((track, index) => { %> <div class="audio-track"> <div class="audio-track-image"> <img src="/img/<%= track.image_filename || 'default-track-image.png' %>" alt="<%= track.title %>"> </div> <div class="audio-track-info"> <h4><%= track.title %></h4> <p class="album-title"><%= track.album_title || "No Album" %></p> </div> <div class="audio-player-wrapper"> <button class="audio-player-button" onclick="togglePlay(<%= index %>)"> <i class="audio-player-icon fa fa-play"></i> </button> <audio id="audio-<%= index %>" src="/tracks/<%= track.filename %>" ontimeupdate="updateProgress(<%= index %>)"></audio> <input type="range" id="progress-bar-<%= index %>" class="progress-bar" value="0" onchange="setProgress(<%= index %>, this.value)"> <span class="progress-time" id="progress-time-<%= index %>">0:00</span> </div> </div> <% }); %> </div> </div> </div> <!-- end -->
2018b4dc1debb2f88d1f9d684c25c2f5
{ "intermediate": 0.3839663565158844, "beginner": 0.42420080304145813, "expert": 0.19183290004730225 }
12,266
search current char* object in char* array, receive iterator
8baaf1e0c013b502f360a41888a1b0d6
{ "intermediate": 0.4314640462398529, "beginner": 0.20243258774280548, "expert": 0.3661033511161804 }
12,267
Hi, code me in python 3 a databse that can hold any type of documents such as photos, vidéos, webpages so on and so forth
8b63cb6c88956e3663c7a0a01d141e32
{ "intermediate": 0.7687694430351257, "beginner": 0.03732884302735329, "expert": 0.19390171766281128 }
12,268
How do i write a nested prisma transaction with a bunch of nested batch queries? Its need to be able to handle a large amount of data
c57eebd26877c060afdd7264c162bb86
{ "intermediate": 0.5672155618667603, "beginner": 0.10929898917675018, "expert": 0.32348546385765076 }
12,269
Regenerate the last response
522b2aeea03097a4a50dc6a12b81b6fa
{ "intermediate": 0.3308755159378052, "beginner": 0.3274616599082947, "expert": 0.34166282415390015 }
12,270
Is there a way to send multiple websocket messages in one message?
b3861b5953543479e4f38789083889f4
{ "intermediate": 0.38469985127449036, "beginner": 0.23768427968025208, "expert": 0.37761589884757996 }
12,271
How to increase the length of vertical in drawing word
970cef8b8202b2987af47a3f359041f6
{ "intermediate": 0.3531351685523987, "beginner": 0.34781768918037415, "expert": 0.29904717206954956 }
12,272
fix the error function onEdit(e) { addTimestamp1(e); addTimestamp2(e); addTimestamp3(e); addTimestamp4(e); addTimestamp5(e); addTimestamp6(e); addTimestamp7(e); addTimestamp8(e); addTimestamp9(e); } function addTimestamp1(e) { var startRow = 7; var ws = "جدول المتابعة"; var row = e.range.getRow(); var col = e.range.getColumn(); var sheet = e.source.getActiveSheet(); var currentDate = new Date(); if (sheet.getName() === ws && row >= startRow) { var excludedColumns = [10, 18, 26]; if (excludedColumns.indexOf(col) === -1) { var letter = getLetter(col); if (sheet.getRange(letter + "5").getValue() == "") { sheet.getRange(letter + "5").setValue(currentDate); } } } } function getLetter(col) { if (col >= 1 && col <= 26) { return String.fromCharCode(64 + col); } else if (col > 26 && col <= 702) { var firstLetter = String.fromCharCode(64 + parseInt((col - 1) / 26)); var secondLetter = String.fromCharCode(65 + ((col - 1) % 26)); return firstLetter + secondLetter; } else { throw new Error("Column out of range"); } } function addTimestamp2(e) { const timestampCols = [ { col: 3, cell: "C5" },{ col: 5, cell: "E5" },{ col: 7, cell: "G5" },{ col: 9, cell: "I5" },{ col: 11, cell: "K5" },{ col: 13, cell: "M5" },{ col: 15, cell: "O5" },{ col: 17, cell: "Q5" },{ col: 19, cell: "S5" },{ col: 21, cell: "U5" } ]; const ws = "اخراج العيون - الملح"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 6) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp3(e) { const timestampCols = [ { col: 3, cell: "C4" },{ col: 5, cell: "E4" },{ col: 7, cell: "G4" },{ col: 9, cell: "I4" },{ col: 11, cell: "K4" },{ col: 13, cell: "M4" },{ col: 15, cell: "O4" } ]; const ws = "المطعوم - السنامكة"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp4(e) { const timestampCols = [ { col: 2, cell: "B4" },{ col: 4, cell: "D4" },{ col: 6, cell: "F4" },{ col: 8, cell: "H4" },{ col: 10, cell: "J4" },{ col: 12, cell: "L4" },{ col: 14, cell: "N4" },{ col: 16, cell: "P4" },{ col: 18, cell: "R4" },{ col: 20, cell: "T4" } ]; const ws = "المشموم - القسط الهندي"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp5(e) { const timestampCols = [ { col: 3, cell: "C5" },{ col: 5, cell: "E5" },{ col: 7, cell: "G5" },{ col: 9, cell: "I5" },{ col: 11, cell: "K5" },{ col: 13, cell: "M5" },{ col: 15, cell: "O5" },{ col: 17, cell: "Q5" },{ col: 19, cell: "S5" },{ col: 21, cell: "U5" } ]; const ws = "اخراج العيون - الملح"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp5(e) { const timestampCols = [ { col: 3, cell: "C4" },{ col: 5, cell: "E4" },{ col: 7, cell: "G4" },{ col: 9, cell: "I4" },{ col: 11, cell: "K4" },{ col: 13, cell: "M4" },{ col: 15, cell: "O4" } ]; const ws = "اللدود - الفم"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp6(e) { const timestampCols = [ { col: 3, cell: "C4" },{ col: 5, cell: "E4" },{ col: 7, cell: "G4" },{ col: 9, cell: "I4" },{ col: 11, cell: "K4" },{ col: 13, cell: "M4" },{ col: 15, cell: "O4" } ]; const ws = "اللبخة - الشعر"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp7(e) { const timestampCols = [ { col: 2, cell: "B4" },{ col: 4, cell: "D4" },{ col: 6, cell: "F4" },{ col: 8, cell: "H4" },{ col: 10, cell: "J4" },{ col: 12, cell: "L4" },{ col: 14, cell: "N4" },{ col: 16, cell: "P4" },{ col: 18, cell: "R4" },{ col: 20, cell: "T4" } ]; const ws = "أسحار الرحم"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp8(e) { const timestampCols = [ { col: 3, cell: "C5" },{ col: 5, cell: "E5" },{ col: 7, cell: "G5" },{ col: 9, cell: "I5" },{ col: 11, cell: "K5" }, ]; const ws = "جلسة الحجامة"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 6) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp9(e) { const timestampCols = [ { col: 5, cell: "E20" },{ col: 6, cell: "F20" },{ col: 7, cell: "G20" },{ col: 8, cell: "H20" },{ col: 9, cell: "I20" },{ col: 10, cell: "J20" },{ col: 11, cell: "K20" },{ col: 12, cell: "L20" },{ col: 13, cell: "M20" },{ col: 14, cell: "N20" } ]; const ws = "رش البيت"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 22) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }}
cdf7625be83867822c0e9618f6f46b67
{ "intermediate": 0.3473740816116333, "beginner": 0.4568408727645874, "expert": 0.1957850158214569 }
12,273
Can you modify this auto hot key script so that when I press F6 the script finishes? :; Initialize initial value to send numToSend := 0 ; Set the desired coordinates here x1 := 100 y1 := 100 x2 := 200 y2 := 200 ; Loop 10 times (10 as an example, change as necessary) Loop, 10 { ; Move to the first spot MouseMove, %x1%, %y1%, 0 ; Double-click the first spot Click, 2 ; Send the value SendInput %0%0%0%0%0%0%numToSend% ; Increment the value numToSend := numToSend + 1 ; Move to the second spot MouseMove, %x2%, %y2%, 0 ; Click the second spot Click ; Move back to the first spot MouseMove, %x1%, %y1%, 0 ; Double-click the first spot Click, 2 ; Send the incremented value SendInput %0%0%0%0%0%0%numToSend% ; Increment the value numToSend := numToSend + 1 ; Wait for a brief moment (optional) Sleep, 1000 }
11e1dcafbad2c6ba1e147866820c598c
{ "intermediate": 0.3146299719810486, "beginner": 0.47252628207206726, "expert": 0.21284371614456177 }
12,274
can you tell possible ways or what i can do or possible side hustes to do to get 1000 dollars in 2 month starting from zero to 50 dollars
88d62df320c256f8a920af5aab1643e9
{ "intermediate": 0.357571005821228, "beginner": 0.32840412855148315, "expert": 0.3140248656272888 }
12,275
Given the data set DS3. The DS3 is csv file. the last column of each data set, stores the labels of the examples of the dataset. Use Python to perform the following tasks: 3. DS3: (a)Load the data set,the file path of DS3 is 'C:/Users/11096/Desktop/Machine Learning/Experiment/lab2/D3.csv' , train an SVM with a linear kernel on the full data set, and plot the data set with the decision boundary. (b) Carry out leave-1-out cross-validation with an SVM on your dataset. Report the train and test performance. Train performance in this case is the performance on the training set, test performance, the performance of the leave-1-out cross-validation. You can change the leave-1-out cross-validation to something different. If you do so, explain what you did and why you chose this way of evaluating. (b) Pick a kernel and 2 parameters and optimize, optimize the parameters (similar to Assignment 1), plot again data set and decision boundary and give the performance. (c) Explain the results of the previous step.
39a2ed880d9bf1ec58d6952780b4e4ba
{ "intermediate": 0.31845906376838684, "beginner": 0.17664973437786102, "expert": 0.5048911571502686 }
12,276
В html файле <form name="addForm" action="/get_exams_name_from_filter/" method="post" novalidate> <div class="my-3"> <p class="my-2">По экзаменам:</p> <input type="text" name="exam_from_filter" id="exsam_test" placeholder="Выберете вариант"> </div> <button type="submit" class="button is-link is-rounded py-5 is-size-6 my-4" style="width: 100%;">Применить</button> </form> <script type="text/javascript"> let exsam_test = [{'id': 2, 'title': 'Владимир'}, {'id': 7, 'title': 'Владимир_2'}]; document.addEventListener('DOMContentLoaded', function() { $('#exsam_test').comboTree({ source : exsam_test, cascadeSelect: true//, //selected: selected_exams }); }); </script> Во flask у меня работают следующие функции class Getting_exams_filter(FlaskForm): exam_from_filter = StringField("exam_from_filter") ### @bp.route("/get_exams_name_from_filter/", methods=["GET", "POST"]) def get_exams_name_from_filter(): form = Getting_exams_filter() if request.method == "POST": exam_from_filter = request.form.get("exam_from_filter") return redirect('/test_random_2/'+exam_from_filter) При нажатии submit я получаю на сервер, если я выбрал [{'id': 2, 'title': 'Владимир'} только title, т.е. Владимир. Я же хочу получить словарь {'id': 2, 'title': 'Владимир'}. Как я должен поменять свой код?
59764b50f7872a0b7745ebe714fb7485
{ "intermediate": 0.2507249712944031, "beginner": 0.5573770999908447, "expert": 0.19189800322055817 }
12,277
Given the data set DS2. The DS2 is csv file. the last column of each data set, stores the labels of the examples of the dataset. Use Python to perform the following tasks: 2. DS2: (a) Load the data set (your own data set), train an SVM with a linear kernel on the full data set, and plot the data set with the decision boundary. (b) Carry out leave-1-out cross-validation with an SVM on your dataset. Report the train and test performance. Train performance in this case is the performance on the training set, test performance, the performance of the leave-1-out cross validation. You can change the leave-1-out cross-validation to something different. If you do so, explain what you did and why you chose this way of evaluating. (c) Pick a kernel that will improve the SVM, plot the data set and resulting decision boundary, and give the performance. (d) Explain which kernel you chose and why.
249335a2d96727d0ba4b3300f3588c6c
{ "intermediate": 0.3656536936759949, "beginner": 0.24559974670410156, "expert": 0.38874655961990356 }
12,278
Do you know the programming language of X ++
581e66198c84ab5837e5e646c61ffa86
{ "intermediate": 0.13139763474464417, "beginner": 0.6867133975028992, "expert": 0.18188902735710144 }
12,279
can you fix the error in the following code function onEdit(e) { addTimestamp1(e); addTimestamp2(e); addTimestamp3(e); addTimestamp4(e); addTimestamp5(e); addTimestamp6(e); addTimestamp7(e); addTimestamp8(e); addTimestamp9(e); } function addTimestamp1(e) { var startRow = 7; var ws = "جدول المتابعة"; var row = e.range.getRow(); var col = e.range.getColumn(); var sheet = e.source.getActiveSheet(); var currentDate = new Date(); if (sheet.getName() === ws && row >= startRow) { var excludedColumns = [10, 18, 26]; if (excludedColumns.indexOf(col) === -1) { var letter = getLetter(col); if (sheet.getRange(letter + "5").getValue() == "") { sheet.getRange(letter + "5").setValue(currentDate); } } } } function getLetter(col) { if (col >= 1 && col <= 26) { return String.fromCharCode(64 + col); } else if (col > 26 && col <= 702) { var firstLetter = String.fromCharCode(64 + parseInt((col - 1) / 26)); var secondLetter = String.fromCharCode(65 + ((col - 1) % 26)); return firstLetter + secondLetter; } else { throw new Error("Column out of range"); } } function addTimestamp2(e) { const timestampCols = [ { col: 3, cell: "C5" },{ col: 5, cell: "E5" },{ col: 7, cell: "G5" },{ col: 9, cell: "I5" },{ col: 11, cell: "K5" },{ col: 13, cell: "M5" },{ col: 15, cell: "O5" },{ col: 17, cell: "Q5" },{ col: 19, cell: "S5" },{ col: 21, cell: "U5" } ]; const ws = "اخراج العيون - الملح"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 6) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp3(e) { const timestampCols = [ { col: 3, cell: "C4" },{ col: 5, cell: "E4" },{ col: 7, cell: "G4" },{ col: 9, cell: "I4" },{ col: 11, cell: "K4" },{ col: 13, cell: "M4" },{ col: 15, cell: "O4" } ]; const ws = "المطعوم - السنامكة"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp4(e) { const timestampCols = [ { col: 2, cell: "B4" },{ col: 4, cell: "D4" },{ col: 6, cell: "F4" },{ col: 8, cell: "H4" },{ col: 10, cell: "J4" },{ col: 12, cell: "L4" },{ col: 14, cell: "N4" },{ col: 16, cell: "P4" },{ col: 18, cell: "R4" },{ col: 20, cell: "T4" } ]; const ws = "المشموم - القسط الهندي"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp5(e) { const timestampCols = [ { col: 3, cell: "C5" },{ col: 5, cell: "E5" },{ col: 7, cell: "G5" },{ col: 9, cell: "I5" },{ col: 11, cell: "K5" },{ col: 13, cell: "M5" },{ col: 15, cell: "O5" },{ col: 17, cell: "Q5" },{ col: 19, cell: "S5" },{ col: 21, cell: "U5" } ]; const ws = "اخراج العيون - الملح"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp5(e) { const timestampCols = [ { col: 3, cell: "C4" },{ col: 5, cell: "E4" },{ col: 7, cell: "G4" },{ col: 9, cell: "I4" },{ col: 11, cell: "K4" },{ col: 13, cell: "M4" },{ col: 15, cell: "O4" } ]; const ws = "اللدود - الفم"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp6(e) { const timestampCols = [ { col: 3, cell: "C4" },{ col: 5, cell: "E4" },{ col: 7, cell: "G4" },{ col: 9, cell: "I4" },{ col: 11, cell: "K4" },{ col: 13, cell: "M4" },{ col: 15, cell: "O4" } ]; const ws = "اللبخة - الشعر"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp7(e) { const timestampCols = [ { col: 2, cell: "B4" },{ col: 4, cell: "D4" },{ col: 6, cell: "F4" },{ col: 8, cell: "H4" },{ col: 10, cell: "J4" },{ col: 12, cell: "L4" },{ col: 14, cell: "N4" },{ col: 16, cell: "P4" },{ col: 18, cell: "R4" },{ col: 20, cell: "T4" } ]; const ws = "أسحار الرحم"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 5) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp8(e) { const timestampCols = [ { col: 3, cell: "C5" },{ col: 5, cell: "E5" },{ col: 7, cell: "G5" },{ col: 9, cell: "I5" },{ col: 11, cell: "K5" }, ]; const ws = "جلسة الحجامة"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 6) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }} function addTimestamp9(e) { const timestampCols = [ { col: 5, cell: "E20" },{ col: 6, cell: "F20" },{ col: 7, cell: "G20" },{ col: 8, cell: "H20" },{ col: 9, cell: "I20" },{ col: 10, cell: "J20" },{ col: 11, cell: "K20" },{ col: 12, cell: "L20" },{ col: 13, cell: "M20" },{ col: 14, cell: "N20" } ]; const ws = "رش البيت"; const row = e.range.getRow(); const col = e.range.getColumn(); if (e.source.getActiveSheet().getName() === ws) { const currentDate = new Date(); timestampCols.forEach(function (timestampCol) { if (col === timestampCol.col && row >= 22) { const cellValue = e.source.getActiveSheet().getRange(timestampCol.cell).getValue(); if (cellValue === "") { e.source.getActiveSheet().getRange(timestampCol.cell).setValue(currentDate); }} }); }}
f0c2bc2cbdb7e55b5abe7cd9fda681cb
{ "intermediate": 0.31413018703460693, "beginner": 0.5098742246627808, "expert": 0.1759955883026123 }
12,280
in python, write a regular expression to identify patterns \x80, \x93, \xa0
143e408ee900cc6fb26409c2fbdfd99e
{ "intermediate": 0.32550105452537537, "beginner": 0.23566943407058716, "expert": 0.4388294517993927 }
12,281
Write a bot that will allow you to link a cryptocurrency wallet to buy cryptocurrency. The purchase must be made with one click. The sale should be done with one click. Network Bsc/ It should be possible to specify the number of coins for buying and selling
0f70851d77f43f24f6e56768156ecc57
{ "intermediate": 0.31293511390686035, "beginner": 0.18672902882099152, "expert": 0.5003358721733093 }
12,282
function MyBlock(props) { const x = props.x; const [content, setContent] = useState(x.content); const images = [ //Server checks they're correct when submitting a request { url: 'http://localhost:3000/images/rome.jpg', alt: 'Image' }, { url: 'http://localhost:3000/images/brasil.jpg', alt: 'Image' }, ]; const removeFromList = (x) => { props.setList((oldlist) => oldlist.filter((item) => item != x)); }; const handleUp = (x) => { props.setList(oldList => { const index = oldList.indexOf(x); const newList = [...oldList]; [newList[index - 1], newList[index]] = [newList[index], newList[index - 1]]; return newList; }); }; const handleDown = (x) => { props.setList(oldList => { const index = oldList.indexOf(x); const newList = [...oldList]; [newList[index], newList[index + 1]] = [newList[index + 1], newList[index]]; return newList; }); }; return ( <Accordion.Item eventKey={props.list.indexOf(x)}> <Accordion.Header > <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%" }}> {x.blockType} <ButtonGroup style={{ paddingRight: "2%" }} > {props.list.indexOf(x) != 0 && ( //button as div avoid nested buttons error validateDOMnesting - since accordion header is a button itself! <Button as='div' style={{ fontSize: "0.8rem", padding: "0.25rem 0.5rem" }} variant="outline-secondary" onClick={(ev) => { ev.stopPropagation(); handleUp(x) }}> <i className="bi bi-arrow-up"></i> </Button>)} {props.list.indexOf(x) != (props.list.length - 1) && ( <Button as='div' style={{ fontSize: "0.8rem", padding: "0.25rem 0.5rem" }} variant="outline-secondary" onClick={(ev) => { ev.stopPropagation(); handleDown(x) }}> <i className="bi bi-arrow-down"></i> </Button>)} <Button as='div' size="sm" variant="outline-danger" onClick={(ev) => { ev.stopPropagation(); removeFromList(x) }}> <i className="bi bi-x-lg"></i> </Button> </ButtonGroup> </div> </Accordion.Header> <Accordion.Body> {x.blockType != "Image" ? ( <Form.Control as="textarea" value={content} onChange={(ev) => { x.content = ev.target.value; setContent(ev.target.value); }}></Form.Control> ) : ( <div> {images.map((image) => (<ImageForm image={image} key={generatelocalId()}/> ))} </div> )} </Accordion.Body> </Accordion.Item> ); function ImageForm(props) { return ( <label key={generatelocalId()} style={{ paddingRight: "20px" }}> <input value={props.image.url} onChange={(ev) => { x.content = ev.target.value; setContent(ev.target.value); }} checked={x.content == props.image.url} type="radio" name="image" /> <img style={{ borderRadius: "5%", paddingLeft: "5px", width: '256px', height: '144px' }} src={props.image.url} alt={props.image.alt} /> </label> ); } } When I click an accordion and expoand the lower box and select an image all is ok. Then when I open another accordion and select another image everything seems fine. If I check back the first accordion I see x.content is ok but a video I don't see the radiobutton clicked.
da2b866d73f2c42d85b075f9dd404f5a
{ "intermediate": 0.34814730286598206, "beginner": 0.5087393522262573, "expert": 0.14311330020427704 }
12,283
code me pinescript of LuxAlgo Signals & Overlays for tradingview
ac2454e62ae687a3150d83892e33c853
{ "intermediate": 0.26550400257110596, "beginner": 0.21422429382801056, "expert": 0.5202716588973999 }
12,284
sto realizzando un applicazione con angular e mysql. ho questo file: user.model.js const sql = require("./db.js"); const Utility = require("../controllers/utility.controller.js"); const passwordConfig = require("../config/password.config"); const InfoUser = function(dati) { this.idUtente = dati.idUtente; this.passwordUtente=dati.passwordUtente; this.passwordNuova=dati.passwordNuova; }; InfoUser.checkPswUser=(utente,result)=>{ sql.query(`select passwordUtente from utente where utente.id=${utente.idUtente} and passwordUtente=aes_encrypt("${utente.passwordUtente}","${passwordConfig.KEY}")`, (err, res) => { if (err) { console.log("error: ", err); result(err, null); return; } if(JSON.parse(JSON.stringify(res)).length>0) result(null, {status:200}); else result(null, {status:500}); }); } InfoUser.getInfoAccount=(idUtente,result)=>{ sql.query(`select username,email,nome,cognome,dataNascita,comuneNascita, provinciaNascita,capNascita,sesso,cellulare,via,numCivico,cap,provincia,comune from utente inner join residenza on utente.id=residenza.idUtente inner join anagrafica on utente.id=anagrafica.idUtente where utente.id=${idUtente}`, (err, res) => { if (err) { console.log("error: ", err); result(err, null); return; } result(null, res); }); } InfoUser.updateUser=(dati,idUtente,result)=>{ if(dati.utente.passwordNuova!=null && dati.utente.passwordNuova!='' && dati.utente.passwordNuova!=dati.utente.passwordUtente) query=`update utente set username= "${dati.utente.username}" , passwordUtente= aes_encrypt("${dati.utente.passwordNuova}","${passwordConfig.KEY}") , email= "${dati.utente.email}" ,cellulare='${dati.utente.cellulare}' where id = ${idUtente}`; else if(dati.utente.passwordNuova==null) query=`update utente set username= "${dati.utente.username}" , email= "${dati.utente.email}" ,cellulare='${dati.utente.cellulare}' where id = ${idUtente}`; sql.query(query,(err, res) => { if (err) { console.log("error: ", err); result(err, null); return; } result(null, res); }); } InfoUser.getAllUsers = (req, res) => { const query = ` SELECT a.nome, a.cognome, u.email, a.cellulare FROM utente AS u JOIN anagrafica AS a ON u.id = a.idUtente `; sql.query(query, (error, results) => { if (error) { console.error(error); res.status(500).json({ message: 'Errore durante la ricerca degli utenti.' }); } else { console.log(results); res.json(results); } }); }; InfoUser.update=async (body,result)=>{ var risultato= await Utility.isExist(null,body.email,null); var risultatoToken=await Utility.verifyTokenForEmail(body.token); let query; if(risultato.length>0 && risultatoToken.email!=undefined){ if(body.flag!=1) query=`UPDATE utente set utenzaAttiva="${body.utenzaAttiva}" where email="${body.email}"`; else query=`UPDATE utente set passwordUtente=aes_encrypt('${body.passwordUtente}',"${passwordConfig.KEY}") where email="${body.email}"`; sql.query(query,(err, res) => { if (err) { console.log("error: ", err); err.status=500; result(err, null); } if(body.flag!=1) res.message="Utenza aggiornata con successo"; else res.message="Password ripristinata con successo"; result(null,res); }); } else{ if(risultatoToken.email==undefined) result({status:403,message:'link scaduto ripetere la procedura per avere un nuovo link'}); else result({status:500,message:"Utenza non trovata"}); } } module.exports = InfoUser; Ho questo altro file user.controller.js const Utility = require("../controllers/utility.controller.js"); const User = require("../models/user.model.js"); const Utenza = require("../models/creaUtenza.model.js"); const Residenza = require("../models/residenza.model.js"); const Anagrafica = require("../models/creaAnagrafica.model.js"); exports.getInfoAccount=async (req,res)=>{ const utente = new User({ idUtente: await Utility.getIdUtente(req) }); User.getInfoAccount(utente.idUtente,(err, data) => { if (err) res.status(500).send({message:err.message}); else{ res.send(data); } }); } exports.getAllUsers = (req, res) => { User.getAllUsers((err, data) => { if (err) { res.status(500).json({ message: err.message }); } else { console.log(res); res.json(data); } }); }; exports.checkPswUtente=async (req,res)=>{ const utente = new User({ idUtente: await Utility.getIdUtente(req), passwordUtente:req.body.passwordUtente }); if (!req.body) { result.status(400).send({ message: "Content can not be empty!" }); } User.checkPswUser(utente,(err, data) => { if (err) res.status(500).send({message:err.message}); else{ res.send(data); } }); } /** * crea una nuova utenza se non è già esistente * * @param {*} req parametri richiesti * @param {*} res risposta del be */ exports.create = async (req,res) => { // Validate request if (!req.body) res.status(400).send({ message: "Content can not be empty!"}); let dati=req.body; let isExist=await Utility.isExist(null,dati.email,null); if(isExist.length==0){ const utenza = new Utenza(dati); Utenza.create(utenza,async (err, data) => { if (err) res.status(500).send({ message: err.message || "Some error occurred while creating the user."}); else { await createAnagrafica(dati,data.insertId); let risp=await createResidenza(dati,data.insertId); let token = await Utility.createToken({email:utenza.email},'3h'); let subject='Grazie per esserti registrato alla Fattoria Madonna della Querce'; let html=` <h1>Benvenuto ${utenza.email},</h1> <br> <a style="color:blue" href="http://localhost:4200/#/confermaEmail/${utenza.email}/${token}"> clicca qua per confermare la tua email.</a> <br><br> <b>Attenzione il link è valido per 3 ore.</b>`; let rispEmail=await Utility.sendMail(subject,html,utenza.email); if(rispEmail) risp.message="Controlla la posta per conferma la creazione dell'account"; res.send(risp); } }); } else{ res.status(500).send({message:"Utenza già esistente"}); } }; function createAnagrafica(dati,id){ const anagrafica= new Anagrafica(dati); return new Promise(resolve =>{ Anagrafica.create(id,anagrafica,(err,data)=>{ if (err) res.status(500).send({ message:err.message || "Some error occurred while creating the user." }); else resolve(data); }) }); } function updateAnagrafica(dati,idUtente){ const anagrafica= new Anagrafica(dati); return new Promise(resolve =>{ Anagrafica.update(idUtente,anagrafica,(err,data)=>{ if (err) res.status(500).send({ message:err.message || "Some error occurred while update the user." }); else resolve(data); }) }); } function createResidenza(dati,id){ const residenza = new Residenza(dati); return new Promise(resolve =>{ Residenza.create(id,residenza, (err, data) => { if (err) res.status(500).send({ message: err.message || "Some error occurred while creating the user." }); else{ resolve(data); } }); }); } function updateResidenza(dati,idUtente){ const residenza = new Residenza(dati); return new Promise(resolve =>{ Residenza.update(idUtente,residenza,(err, data) => { if (err) res.status(500).send({ message: err.message || "Some error occurred while update the user." }); else{ resolve(data); } }); }); } exports.ripristinaPassword=async (req,result)=>{ let risp=await Utility.isExist(null,req.body.email,null); if(risp.length>0){ let risp=await Utility.isActiveUser(null,req.body.email); if(risp.status==200){ let subject='Riempostare password'; let token = await Utility.createToken({email:req.body.email},'3h'); let html=`<h1>Gentile ${req.body.email},</h1> <br> <a style="color:blue" href="http://localhost:4200/#/ripristinaPassword/${req.body.email}/${token}">clicca qua per ripristinare la password.</a> <br><br> <b>Attenzione il link è valido per 3 ore.</b>` let risposta=await Utility.sendMail(subject,html,req.body.email); if(risposta) result.send({message:"Controlla la posta per conferma la creazione dell'account"}); else result.send(risposta); } else result.status(500).send({message:risp.message}); } else result.status(500).send({message:"Utenza non trovata"}); } /** * per attivare l'utenza/ modificare la password * @param {*} req dati richiesti * @param {*} result risultato query */ exports.update=async (req,result)=>{ if (!req.body) { result.status(400).send({ message: "Content can not be empty!" }); } User.update(req.body,(err, data) => { if (err) result.status(err.status).send({message:err.message}); else result.send(data); }); } exports.updateInfoUser= async (req,res)=>{ if (!req.body) res.status(400).send({ message: "Content can not be empty!"}); let idUtente = await Utility.getIdUtente(req); let dati=JSON.parse(req.body.dati); User.updateUser(dati, idUtente,(err, data) => { if (err) res.status(500).send({message:err.message}); else{ updateAnagrafica(dati.anagrafica,idUtente); updateResidenza(dati.residenza,idUtente); data.message = "informazioni utente aggiornate con successo"; res.send(data); } }); } Ho questo file route.js const express = require('express'); const router = express.Router(); const path = require('path'); // parse requests of content-type - application/json router.use(express.json()); // parse requests of content-type - application/x-www-form-urlencoded router.use(express.urlencoded({ extended: true })); const login = require("../controllers/login.controller"); const utente = require("../controllers/user.controller"); const utility = require("../controllers/utility.controller"); router.get("*",utility.verifyToken); router.post("*",utility.verifyToken); router.put("*",utility.verifyToken); router.delete("*",utility.verifyToken); router.post("/api/auth/createUtenza.json", utente.create); router.post("/api/auth/aggiornaUtenza.json", utente.update); router.post("/api/auth/ripristinaPassword.json", utente.ripristinaPassword); router.post("/api/auth/login.json",login.login); router.get("/api/getInfoUser.json",utente.getInfoAccount); router.put("/api/updateDatiUtente.json", utente.updateInfoUser); router.post("/api/checkPsw.json", utente.checkPswUtente); // Definisci la route per ottenere tutti gli utenti router.get("/api/getAllUsers.json", utente.getAllUsers); module.exports = router; e infinde admindashboardcomponent import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-admin-dashboard', templateUrl: './admin-dashboard.component.html', styleUrls: ['./admin-dashboard.component.css'], }) export class AdminDashboardComponent implements OnInit { users: any[] = []; constructor(private http: HttpClient) { } ngOnInit(): void { this.getUsers(); } getUsers(): void { this.http.get<any[]>('/api/getAllUsers.json') .subscribe( users => { // Assegna la lista degli utenti alla proprietà "users" del tuo componente this.users = users; }, error => { console.log('Error retrieving users:', error); } ); } } Il problema è che quando provo a usare la funzione getUsers() il console.log mi restituisce [ RowDataPacket { nome: 'Lorenzo', cognome: 'Paolucci', email: 'lorenzo.paolucci@studenti.unicam.it', cellulare: 333 } ] e poi ho questo errore: ] C:\Users\jacom\Documents\PiggyFarmWeb\backend\node_modules\mysql\lib\protocol\Parser.js:437 throw err; // Rethrow non-MySQL errors ^ TypeError: Cannot read properties of undefined (reading 'json') at Query.<anonymous> (C:\Users\jacom\Documents\PiggyFarmWeb\backend\models\user.model.js:75:11) at Query.<anonymous> (C:\Users\jacom\Documents\PiggyFarmWeb\backend\node_modules\mysql\lib\Connection.js:526:10) at Query._callback (C:\Users\jacom\Documents\PiggyFarmWeb\backend\node_modules\mysql\lib\Connection.js:488:16) at Sequence.end (C:\Users\jacom\Documents\PiggyFarmWeb\backend\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24) at Query._handleFinalResultPacket (C:\Users\jacom\Documents\PiggyFarmWeb\backend\node_modules\mysql\lib\protocol\sequences\Query.js:149:8) at Query.EofPacket (C:\Users\jacom\Documents\PiggyFarmWeb\backend\node_modules\mysql\lib\protocol\sequences\Query.js:133:8) at Protocol._parsePacket (C:\Users\jacom\Documents\PiggyFarmWeb\backend\node_modules\mysql\lib\protocol\Protocol.js:291:23) at Parser._parsePacket (C:\Users\jacom\Documents\PiggyFarmWeb\backend\node_modules\mysql\lib\protocol\Parser.js:433:10) at Parser.write (C:\Users\jacom\Documents\PiggyFarmWeb\backend\node_modules\mysql\lib\protocol\Parser.js:43:10) at Protocol.write (C:\Users\jacom\Documents\PiggyFarmWeb\backend\node_modules\mysql\lib\protocol\Protocol.js:38:16)
439139b4e231783fd841ecd75792e806
{ "intermediate": 0.36433175206184387, "beginner": 0.4213860332965851, "expert": 0.21428221464157104 }
12,285
Как добавить в грид основанный на material data grid отдельную панель с фильтрами, используя react-hook-form и zod?
5cd9b14162ebd13bf74b2bd07aa50fdb
{ "intermediate": 0.5791627168655396, "beginner": 0.1695820689201355, "expert": 0.2512552738189697 }
12,286
in dao.js exports.publishedPageContent = (pageid) => { return new Promise((resolve, reject) => { const sql = ` SELECT pages.title AS title, pages.authorId AS authorId, users.name AS authorName, pages.creationDate AS creationDate, pages.publishDate AS publishDate, pages.blocks AS blocks FROM pages JOIN users ON pages.authorId = users.id WHERE pages.id=?`; db.get(sql, [pageid], (err, row) => { //db.get returns only the first element matching the query if (err) { reject(err); return; } if (row == undefined) { resolve({ error404: "Page not found." }); //Page not found } else if (dayjs(row.publishDate).isAfter(dayjs()) || !dayjs(row.publishDate).isValid()) { //draft or programmed - dayjs() returns today date resolve({ error403: "Forbidden. FrontOffice-view is unable to access a non-published page. Login to unlock this limitation." }); } else { const info = { title: row.title, authorName: row.authorName, creationDate: row.creationDate, publishDate: row.publishDate, blocks: row.blocks }; resolve(info); } }); }); }; in server.js app.get('/api/view/:pageid', async (req, res) => { try { // If request from auth-user we call pageContent otherwise we call publishedPageContent. Doing this we anable the view of non-published pages to loggedin users. const result = await dao.publishedPageContent(req.params.pageid); if (result.error401) res.status(401).json(result); else if (result.error403) res.status(403).json(result); else if (result.error404) res.status(404).json(result); else res.json(result); } catch (err) { res.status(500).end(); } }); how can I create better error managment?
9c7dc3276738dfd40ba424ad116ada1f
{ "intermediate": 0.3847202658653259, "beginner": 0.21495330333709717, "expert": 0.4003264307975769 }
12,287
SELECT u.DateOfBirth FROM [BillingIn_test_3].[dbo].[Users] u сгруппировать по полю и посчитать знаки зодиака
a63603fc5cc15efb7477b4aa448662ae
{ "intermediate": 0.32562628388404846, "beginner": 0.42713019251823425, "expert": 0.24724358320236206 }
12,288
package clientUtils; import java.io.*; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.charset.StandardCharsets; public class ConnectionManager { String ip; int port; SocketChannel socketChannel; public ConnectionManager(String ip, int port) { this.ip = ip; this.port = port; } void makeRequest(File file, FileInputStream fis) throws IOException { sendFile(file, fis); receiveConfirmation(); } void connect() throws IOException { System.out.println("Connected to the server"); socketChannel = SocketChannel.open(new InetSocketAddress(ip, port)); socketChannel.configureBlocking(true); } void closeConnection() throws IOException { socketChannel.close(); System.out.println("Connection closed"); } private void sendFile(File file, FileInputStream fis) throws IOException { // Создаем байтовый массив для передачи имени файла и его длины byte[] nameBytes = file.getName().getBytes(StandardCharsets.UTF_8); ByteBuffer nameLengthBuffer = ByteBuffer.allocate(Integer.BYTES).putInt(nameBytes.length); nameLengthBuffer.flip(); // Отправляем длину имени файла и само имя socketChannel.write(nameLengthBuffer); ByteBuffer nameBuffer = ByteBuffer.wrap(nameBytes); socketChannel.write(nameBuffer); // Отправляем длину файла int fileLength = (int) file.length(); ByteBuffer fileLengthBuffer = ByteBuffer.allocate(Integer.BYTES).putInt(fileLength); fileLengthBuffer.flip(); socketChannel.write(fileLengthBuffer); // Определяем размер куска int chunkSize = 1024; byte[] buffer = new byte[chunkSize]; // Читаем данные из файла по кускам и отправляем их int totalBytesRead = 0; while (totalBytesRead < fileLength) { int bytesRead = fis.read(buffer, 0, Math.min(chunkSize, fileLength - totalBytesRead)); if (bytesRead > 0) { // если прочитали что-то из файла ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, 0, bytesRead); socketChannel.write(byteBuffer); // отправляем текущий кусок totalBytesRead += bytesRead; // увеличиваем количество переданных байт } } socketChannel.write(ByteBuffer.allocate(Long.BYTES)); // разделитель fis.close(); System.out.println("File " + file.getName() + " sent successfully"); } private void receiveConfirmation() throws IOException { // Читаем длину сообщения ByteBuffer lengthBuffer = ByteBuffer.allocate(Integer.BYTES); socketChannel.read(lengthBuffer); lengthBuffer.flip(); int messageLength = lengthBuffer.getInt(); // Читаем само сообщение ByteBuffer messageBuffer = ByteBuffer.allocate(messageLength); int bytesRead = 0; while (bytesRead < messageLength) { bytesRead += socketChannel.read(messageBuffer); } messageBuffer.rewind(); byte[] messageBytes = new byte[messageBuffer.remaining()]; messageBuffer.get(messageBytes); String message = new String(messageBytes, StandardCharsets.UTF_8); System.out.println("Received file: " + message); } } Добавь в этот java код клиента возможность отправлять большие файлы, больше буффера, но не меняй размер буффера
0635e719ba621901f8e2b9691e9ca38f
{ "intermediate": 0.359846830368042, "beginner": 0.4135202169418335, "expert": 0.2266329824924469 }
12,289
adapta o script de forma a não necessitar clicar no botão Record from microphone nem depois clicar no botão Stop recording ao abrir o gradio inicia a captura de voz simulando o clique no botão Record from microphone e passado 7 segundos é terminada a captura de voz simulando o clique no botão Stop recording : import whisper import gradio as gr model = whisper.load_model("tiny") def transcribe(audio): #time.sleep(3) # load audio and pad/trim it to fit 30 seconds audio = whisper.load_audio(audio) audio = whisper.pad_or_trim(audio) # make log-Mel spectrogram and move to the same device as the model mel = whisper.log_mel_spectrogram(audio).to(model.device) # detect the spoken language #_, probs = model.detect_language(mel) #print(f"Detected language: {max(probs, key=probs.get)}") # decode the audio options = whisper.DecodingOptions(fp16 = False, language="pt") result = whisper.decode(model, mel, options) return result.text gr.Interface( title = 'OpenAI Whisper ASR Gradio Web UI', fn=transcribe, inputs=[ gr.inputs.Audio(source="microphone", type="filepath") ], outputs=[ "textbox" ], live=True).launch()
1c3f7bb941fee4c499e7371bdd89e9e5
{ "intermediate": 0.42884907126426697, "beginner": 0.20438985526561737, "expert": 0.36676105856895447 }
12,290
i'm traying to implement google activty recognition api to to detect my activity i have those classes the app works in the android studio emulator (it detect activity) but not workin on my phone : import android.Manifest; import android.annotation.SuppressLint; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.app.ActivityCompat; import com.google.android.gms.location.ActivityRecognition; import com.google.android.gms.location.ActivityRecognitionClient; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; public class BackgroundDetectedActivity extends Service { private PendingIntent pendingIntent; private ActivityRecognitionClient activityRecognitionClient; IBinder binder = new LocalBinder(); public class LocalBinder extends Binder { public BackgroundDetectedActivity getServerInstance() { return BackgroundDetectedActivity.this; } } public BackgroundDetectedActivity() { } @SuppressLint("UnspecifiedImmutableFlag") @Override @RequiresApi(api = Build.VERSION_CODES.Q) public void onCreate() { super.onCreate(); activityRecognitionClient = ActivityRecognition.getClient(this); Intent intentService = new Intent(this, ActivityRecognitionService.class); // pendingIntent = PendingIntent.getService(this, 1, intentService, PendingIntent.FLAG_UPDATE_CURRENT); pendingIntent = PendingIntent.getService(this, 1, intentService, PendingIntent.FLAG_UPDATE_CURRENT); requestActivityUpdatesButtonHandler(); } @Nullable @Override public IBinder onBind(Intent intent) { return binder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_STICKY; } public void requestActivityUpdatesButtonHandler() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) { return; } Task<Void> task = activityRecognitionClient.requestActivityUpdates(1000, pendingIntent); task.addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void result) { Toast.makeText(getApplicationContext(), "Mises à jour d'activité demandées avec succès", Toast.LENGTH_SHORT).show(); } }); task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getApplicationContext(), "La demande de mises à jour d'activité n'a pas pu démarrer", Toast.LENGTH_SHORT).show(); } }); } @Override public void onDestroy() { super.onDestroy(); removeActivityUpdate(); } public void removeActivityUpdate() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } Task<Void> task = activityRecognitionClient.removeActivityUpdates(pendingIntent); task.addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void result) { Toast.makeText(getApplicationContext(), "Mises à jour d'activité supprimées avec succès !", Toast.LENGTH_SHORT).show(); } }); task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getApplicationContext(), "Échec de la suppression des mises à jour d'activité!", Toast.LENGTH_SHORT).show(); } }); } } import static android.content.ContentValues.TAG; import android.app.IntentService; import android.content.Intent; import android.util.Log; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.google.android.gms.location.ActivityRecognitionResult; import com.google.android.gms.location.DetectedActivity; import java.util.ArrayList; public class ActivityRecognitionService extends IntentService { public ActivityRecognitionService() { super("ActivityRecognitionService"); } @Override protected void onHandleIntent(Intent intent) { ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent); // Get the list of the probable activities associated with the current state of the // device. Each activity is associated with a confidence level, which is an int between // 0 and 100. ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities(); for (DetectedActivity activity : detectedActivities) { Log.e(TAG, "Detection d'activité: " + activity.getType() + ", " + activity.getConfidence()); broadcastActivity(activity); } } private void broadcastActivity(DetectedActivity activity) { Intent intent = new Intent("activity_intent"); intent.putExtra("type", activity.getType()); intent.putExtra("confidence", activity.getConfidence()); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } } @RequiresApi(api = Build.VERSION_CODES.Q) public class ActivityConfidenceActivity extends AppCompatActivity { private Button btnStart, btnStop; private TextView txt_activity, txt_confidence; private ImageView img_activity; DatabaseHelper db; String email; private BroadcastReceiver activityReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_confidence); txt_activity = findViewById(R.id.txt_activity); txt_confidence = findViewById(R.id.txt_confidence); img_activity = findViewById(R.id.img_activity); btnStart = findViewById(R.id.btn_start); btnStop = findViewById(R.id.btn_stop); db = new DatabaseHelper(this); if (ActivityCompat.checkSelfPermission(ActivityConfidenceActivity.this, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED) { // When permission grated // call Method btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt_activity.setText("starting the service may take a while ..."); txt_confidence.setText(""); img_activity.setImageResource(0); requestActivityUpdates(); } }); } else { // When permission denied // Request permission ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.ACTIVITY_RECOGNITION }, 44); } activityReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d("ActivityUpdate", "Received update"); int type = intent.getIntExtra("type", -1); int confidence = intent.getIntExtra("confidence", 0); // Update the TextViews according to the activity type and confidence handleUserActivity(type, confidence); } }; btnStop.setOnClickListener((v) -> { Intent intent1 = new Intent(ActivityConfidenceActivity.this, BackgroundDetectedActivity.class); stopService(intent1); txt_activity.setText("Service stopped"); txt_confidence.setText("To start the service click on start button"); img_activity.setImageResource(0); if (!TextUtils.isEmpty(db.getLastActivity()[4])){ db.updateEndDate(new Date().toString(),Long.parseLong(db.getLastActivity()[0])); } } ); } private void handleUserActivity(int type, int confidence) { String label = "unknown"; int icon = R.drawable.activity_unknown; switch (type) { case DetectedActivity.IN_VEHICLE: { icon = R.drawable.activity_driving; label = "in_vehicle"; break; } case DetectedActivity.ON_BICYCLE: { icon = R.drawable.activity_on_bicycle; label = "on_bicycle"; break; } case DetectedActivity.ON_FOOT: { icon = R.drawable.activity_jumpping; label = "on_foot"; break; } case DetectedActivity.RUNNING: { icon = R.drawable.activity_running; label = "running"; break; } case DetectedActivity.STILL: { icon = R.drawable.activity_still; label = "still"; break; } case DetectedActivity.WALKING: { icon = R.drawable.activity_walking; label = "walking"; break; } case DetectedActivity.UNKNOWN: { icon = R.drawable.activity_unknown; label = "unknown"; break; } } Log.d("ActivityUpdate", "User activity: " + label + ", Confidence: " + confidence); if (confidence > 50) { txt_activity.setText(label); txt_confidence.setText("" + confidence); img_activity.setImageResource(icon); if(!TextUtils.isEmpty(label)){ String []data= db.getLastActivity(); if(data[4]=="" && !data[2].equals(label)){ db.updateEndDate(new Date().toString(),Long.parseLong(data[0])); db.addActivity(new Activity(email,label,new Date().toString(),"")); }else{ db.addActivity(new Activity(email,label,new Date().toString(),"")); } } // notification NotificationCompat.Builder builder = new NotificationCompat.Builder(ActivityConfidenceActivity.this, NotificationManager.EXTRA_NOTIFICATION_CHANNEL_GROUP_ID) .setSmallIcon(icon) .setContentTitle("Activity changed") .setContentText("Activity changed to " + label + " with confidence " + confidence + "%") .setPriority(NotificationCompat.PRIORITY_DEFAULT); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(ActivityConfidenceActivity.this); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "permession den", Toast.LENGTH_SHORT).show(); return; } notificationManager.notify(0, builder.build()); } } @Override protected void onResume() { super.onResume(); LocalBroadcastManager.getInstance(this).registerReceiver(activityReceiver, new IntentFilter("activity_intent")); } @Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(activityReceiver); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 44) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { return; } } } private void requestActivityUpdates() { Intent intent1 = new Intent(ActivityConfidenceActivity.this, BackgroundDetectedActivity.class); startService(intent1); } }
6a5a25cc4c20707c412c6b76121e6c6d
{ "intermediate": 0.34964704513549805, "beginner": 0.4891119599342346, "expert": 0.1612410694360733 }
12,291
Клиент отправляет большие файлы с помощью этого кода package clientUtils; import java.io.*; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.nio.charset.StandardCharsets; public class ConnectionManager { String ip; int port; SocketChannel socketChannel; public ConnectionManager(String ip, int port) { this.ip = ip; this.port = port; } void makeRequest(File file) throws IOException { sendFile(file); receiveConfirmation(); } void connect() throws IOException { System.out.println("Connected to the server"); socketChannel = SocketChannel.open(new InetSocketAddress(ip, port)); socketChannel.configureBlocking(true); } void closeConnection() throws IOException { socketChannel.close(); System.out.println("Connection closed"); } private void sendFile(File file) throws IOException { // Создаем байтовый массив для передачи имени файла и его длины byte[] nameBytes = file.getName().getBytes(StandardCharsets.UTF_8); ByteBuffer nameLengthBuffer = ByteBuffer.allocate(Integer.BYTES).putInt(nameBytes.length); nameLengthBuffer.flip(); // Отправляем длину имени файла и само имя socketChannel.write(nameLengthBuffer); ByteBuffer nameBuffer = ByteBuffer.wrap(nameBytes); socketChannel.write(nameBuffer); // Отправляем длину файла long fileLength = file.length(); ByteBuffer fileLengthBuffer = ByteBuffer.allocate(Long.BYTES).putLong(fileLength); fileLengthBuffer.flip(); socketChannel.write(fileLengthBuffer); // Получаем канал для чтения файла FileChannel fileChannel = new FileInputStream(file).getChannel(); int chunkSize = 1024 * 1024; // 1 МБ // Читаем данные из файла по блокам и отправляем их ByteBuffer buffer = ByteBuffer.allocate(chunkSize); long bytesSent = 0; while (bytesSent < fileLength) { int bytesRead = fileChannel.read(buffer); if (bytesRead == -1) { // конец файла break; } buffer.flip(); while (buffer.hasRemaining()) { socketChannel.write(buffer); // отправляем текущий блок } bytesSent += bytesRead; // увеличиваем количество переданных байт System.out.println(bytesSent + " of " + fileLength); buffer.clear(); // очищаем буфер для следующего чтения } socketChannel.write(ByteBuffer.allocate(Long.BYTES)); // разделитель fileChannel.close(); System.out.println("File " + file.getName() + " sent successfully"); } private void receiveConfirmation() throws IOException { // Читаем длину сообщения ByteBuffer lengthBuffer = ByteBuffer.allocate(Integer.BYTES); socketChannel.read(lengthBuffer); lengthBuffer.flip(); int messageLength = lengthBuffer.getInt(); // Читаем само сообщение ByteBuffer messageBuffer = ByteBuffer.allocate(messageLength); int bytesRead = 0; while (bytesRead < messageLength) { bytesRead += socketChannel.read(messageBuffer); } messageBuffer.rewind(); byte[] messageBytes = new byte[messageBuffer.remaining()]; messageBuffer.get(messageBytes); String message = new String(messageBytes, StandardCharsets.UTF_8); System.out.println("Received file: " + message); } } Исправь код сервера так, чтобы он правильно принимал эти большие файлы. Размер буфера менять нельзя package serverUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.charset.StandardCharsets; public class ConnectionManager { private static final String ACK_MESSAGE_PREFIX = "<%s>Ack"; static final int BUFFER_SIZE = 1024 * 1024; ServerSocketChannel serverSocketChannel; int port; public ConnectionManager(int port) { this.port = port; } public void initialize() throws IOException { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(port)); serverSocketChannel.configureBlocking(false); System.out.println("Server started on port " + port); System.out.println("============ * ============"); } public void registerSelector(Selector selector) throws ClosedChannelException { serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } public void processQuery(Selector selector, SelectionKey key) throws IOException { if (!key.isValid()) { return; } if (key.isAcceptable()) { acceptConnection(key, selector); } else if (key.isReadable()) { handleRead(key); } } private void acceptConnection(SelectionKey key, Selector selector) throws IOException { ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel clientSocketChannel = serverSocketChannel.accept(); clientSocketChannel.configureBlocking(false); // Attach new ConnectionContext instance to the selection key ConnectionContext context = new ConnectionContext(); clientSocketChannel.register(selector, SelectionKey.OP_READ, context); System.out.println("Accepted connection from " + clientSocketChannel.getRemoteAddress()); } private void handleRead(SelectionKey key) throws IOException { SocketChannel clientSocketChannel = (SocketChannel) key.channel(); ConnectionContext connectionContext = (ConnectionContext) key.attachment(); if (connectionContext == null) { connectionContext = new ConnectionContext(); key.attach(connectionContext); } ByteBuffer buffer = connectionContext.buffer; int bytesRead = clientSocketChannel.read(buffer); if (bytesRead < 0) { System.out.println("Closed connection with " + clientSocketChannel.getRemoteAddress()); clientSocketChannel.close(); key.cancel(); System.out.println("============ * ============"); return; } buffer.flip(); // handle file transmission if (connectionContext.fileStarted) { // check if we need more data to continue reading the file if (connectionContext.fileName != null && connectionContext.fileLength >= 0 && buffer.remaining() >= connectionContext.fileLength + Long.BYTES) { // read the file contents byte[] fileContent = new byte[connectionContext.fileLength]; buffer.get(fileContent); // check the separator connectionContext.separator = buffer.getLong(); if (connectionContext.separator != 0L) { throw new RuntimeException("Invalid separator"); } // save the file and send an acknowledgement saveFile(connectionContext.fileName, fileContent); sendAck(clientSocketChannel, connectionContext.fileName); // reset context for next file transfer connectionContext.fileStarted = false; connectionContext.fileCompleted = true; connectionContext.fileName = null; connectionContext.fileLength = -1; // handle any remaining data in buffer if (buffer.remaining() > 0) { handleRead(key); return; } } } else { // read the header of the file transfer while (buffer.hasRemaining() && !connectionContext.fileStarted) { // read the name length if (connectionContext.fileName == null && buffer.remaining() >= Integer.BYTES) { int nameLength = buffer.getInt(); byte[] nameBytes = new byte[nameLength]; buffer.get(nameBytes); connectionContext.fileName = new String(nameBytes, StandardCharsets.UTF_8); } // read the file length if (connectionContext.fileLength < 0 && buffer.remaining() >= Integer.BYTES) { connectionContext.fileLength = buffer.getInt(); if (connectionContext.fileLength < 0) { throw new RuntimeException("Invalid file length"); } connectionContext.fileStarted = true; // check if we need more data to continue reading the file if (buffer.remaining() < connectionContext.fileLength + Long.BYTES) { buffer.compact(); return; } } } } // handle file transmission continued with remaining data in buffer if (connectionContext.fileStarted && !connectionContext.fileCompleted && buffer.remaining() >= connectionContext.fileLength + Long.BYTES) { // read the file contents byte[] fileContent = new byte[connectionContext.fileLength]; buffer.get(fileContent); // check the separator connectionContext.separator = buffer.getLong(); if (connectionContext.separator != 0L) { throw new RuntimeException("Invalid separator"); } // save the file and send an acknowledgement saveFile(connectionContext.fileName, fileContent); sendAck(clientSocketChannel, connectionContext.fileName); // reset context for next file transfer connectionContext.fileStarted = false; connectionContext.fileCompleted = true; connectionContext.fileName = null; connectionContext.fileLength = -1; // handle any remaining data in buffer if (buffer.remaining() > 0) { handleRead(key); return; } } buffer.compact(); } private void saveFile(String filename, byte[] fileContent) throws IOException { File file = new File("files\\" + filename); System.out.println("Saving file " + filename); try (FileOutputStream outputStream = new FileOutputStream(file, true)) { int offset = 0; while (offset < fileContent.length) { int bytesToWrite = Math.min(BUFFER_SIZE, fileContent.length - offset); outputStream.write(fileContent, offset, bytesToWrite); outputStream.flush(); offset += bytesToWrite; } } System.out.println("File " + filename + " saved successfully"); } private void sendAck(SocketChannel clientSocketChannel, String filename) throws IOException { String ackMessage = String.format(ACK_MESSAGE_PREFIX, filename); byte[] ackMessageBytes = ackMessage.getBytes(); ByteBuffer buffer = ByteBuffer.allocate(ackMessageBytes.length + Integer.BYTES); buffer.putInt(ackMessageBytes.length); buffer.put(ackMessageBytes); buffer.flip(); while (buffer.hasRemaining()) { clientSocketChannel.write(buffer); } System.out.println("Sent acknowledgement for " + filename); buffer.clear(); // Очищаем буфер перед чтением новых данных } }
ed6b5ab5a805e4150f47fdb524238bc0
{ "intermediate": 0.33570244908332825, "beginner": 0.45354053378105164, "expert": 0.21075701713562012 }
12,292
# Target rules for targets named starcoder # Build rule for target. starcoder: cmake_check_build_system $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 starcoder .PHONY : starcoder # fast build rule for target. starcoder/fast: $(MAKE) $(MAKESILENT) -f examples/starcoder/CMakeFiles/starcoder.dir/build.make examples/starcoder/CMakeFiles/starcoder.dir/build .PHONY : starcoder/fast What's "fast build for target"?
dfb67cff0b1491f30ea81ffbd6899f70
{ "intermediate": 0.39285218715667725, "beginner": 0.2723763883113861, "expert": 0.3347714841365814 }
12,293
В html файле <form name=“addForm” action=“/get_exams_name_from_filter/” method=“post” novalidate> <div class=“my-3”> <p class=“my-2”>По экзаменам:</p> <input type=“hidden” name=“exam_from_filter_id” value=“{‘id’: 2, ‘title’: ‘Владимир’}” > <input type=“text” name=“exam_from_filter” id=“exsam_test” placeholder=“Выберете вариант”> </div> <button type=“submit” class=“button is-link is-rounded py-5 is-size-6 my-4” style=“width: 100%;”>Применить</button> </form> <script type=“text/javascript”> let exsam_test = [{‘id’: 2, ‘title’: ‘Владимир’}, {‘id’: 7, ‘title’: ‘Владимир_2’}]; document.addEventListener(‘DOMContentLoaded’, function() { $(‘#exsam_test’).comboTree({ source : exsam_test, cascadeSelect: true//, //selected: selected_exams }); }); </script> Во flask у меня работают следующие функции exam_from_filter = StringField(“exam_from_filter”) exam_from_filter_id = StringField(“exam_from_filter_id”) ### @bp.route(“/get_exams_name_from_filter/”, methods=[“GET”, “POST”]) def get_exams_name_from_filter(): form = Getting_exams_filter() if request.method == “POST”: exam_from_filter = request.form.get(“exam_from_filter”) exam_from_filter_id = request.form.get(“exam_from_filter_id”) print(exam_from_filter) print(exam_from_filter_id) return redirect(‘/test_random_2/’+exam_from_filter) Мне нужна функция, которая будет изменять значения value=“{‘id’: 2, ‘title’: ‘Владимир’}” на значение словаря,которое было выбрано из массива exsam_test. Причем функция должна быть написана на js и изменять value до перезагрузки сервера
3b1b98912f02aa4047c7037dcdb258c5
{ "intermediate": 0.2091277539730072, "beginner": 0.5684075951576233, "expert": 0.2224646955728531 }
12,294
В html файле <form name=“addForm” action=“/get_exams_name_from_filter/” method=“post” novalidate> <div class=“my-3”> <p class=“my-2”>По экзаменам:</p> <input type=“hidden” name=“exam_from_filter_id” value=“{‘id’: 2, ‘title’: ‘Владимир’}” > <input type=“text” name=“exam_from_filter” id=“exsam_test” placeholder=“Выберете вариант”> </div> <button type=“submit” class=“button is-link is-rounded py-5 is-size-6 my-4” style=“width: 100%;”>Применить</button> </form> <script type=“text/javascript”> let exsam_test = [{‘id’: 2, ‘title’: ‘Владимир’}, {‘id’: 7, ‘title’: ‘Владимир_2’}]; document.addEventListener(‘DOMContentLoaded’, function() { $(‘#exsam_test’).comboTree({ source : exsam_test, cascadeSelect: true//, //selected: selected_exams }); }); </script> Во flask у меня работают следующие функции exam_from_filter = StringField(“exam_from_filter”) exam_from_filter_id = StringField(“exam_from_filter_id”) ### @bp.route(“/get_exams_name_from_filter/”, methods=[“GET”, “POST”]) def get_exams_name_from_filter(): form = Getting_exams_filter() if request.method == “POST”: exam_from_filter = request.form.get(“exam_from_filter”) exam_from_filter_id = request.form.get(“exam_from_filter_id”) print(exam_from_filter) print(exam_from_filter_id) return redirect(‘/test_random_2/’+exam_from_filter) Мне нужна функция, которая будет изменять значения value=“{‘id’: 2, ‘title’: ‘Владимир’}” на значение словаря,которое было выбрано из массива exsam_test. Причем функция должна быть написана на js и изменять value до перезагрузки сервера
d2e0132f9256be6495ca764568d69b95
{ "intermediate": 0.2091277539730072, "beginner": 0.5684075951576233, "expert": 0.2224646955728531 }
12,295
В html файле <form name=“addForm” action=“/get_exams_name_from_filter/” method=“post” novalidate> <div class=“my-3”> <p class=“my-2”>По экзаменам:</p> <input type=“hidden” name=“exam_from_filter_id” value=“{‘id’: 2, ‘title’: ‘Владимир’}” > <input type=“text” name=“exam_from_filter” id=“exsam_test” placeholder=“Выберете вариант”> </div> <button type=“submit” class=“button is-link is-rounded py-5 is-size-6 my-4” style=“width: 100%;”>Применить</button> </form> <script type=“text/javascript”> let exsam_test = [{‘id’: 2, ‘title’: ‘Владимир’}, {‘id’: 7, ‘title’: ‘Владимир_2’}]; document.addEventListener(‘DOMContentLoaded’, function() { $(‘#exsam_test’).comboTree({ source : exsam_test, cascadeSelect: true//, //selected: selected_exams }); }); </script> Во flask у меня работают следующие функции exam_from_filter = StringField(“exam_from_filter”) exam_from_filter_id = StringField(“exam_from_filter_id”) ### @bp.route(“/get_exams_name_from_filter/”, methods=[“GET”, “POST”]) def get_exams_name_from_filter(): form = Getting_exams_filter() if request.method == “POST”: exam_from_filter = request.form.get(“exam_from_filter”) exam_from_filter_id = request.form.get(“exam_from_filter_id”) print(exam_from_filter) print(exam_from_filter_id) return redirect(‘/test_random_2/’+exam_from_filter) Мне нужна функция, которая будет изменять значения value=“{‘id’: 2, ‘title’: ‘Владимир’}” на значение словаря,которое было выбрано из массива exsam_test. Причем функция должна быть написана на js и изменять value до перезагрузки сервера
9911c0a98bb6bc19dad95365b1350118
{ "intermediate": 0.2507533133029938, "beginner": 0.5743151903152466, "expert": 0.17493151128292084 }
12,296
write a c# routine to extract prompt data from a stable diffusion generated image
9a7e2380910b1f3524df1f4809f8f81d
{ "intermediate": 0.5420939326286316, "beginner": 0.14902877807617188, "expert": 0.30887725949287415 }
12,297
В html файле <form name=“addForm” action=“/get_exams_name_from_filter/” method=“post” novalidate> <div class=“my-3”> <p class=“my-2”>По экзаменам:</p> <input type=“hidden” name=“exam_from_filter_id” value=“{‘id’: 2, ‘title’: ‘Владимир’}” > <input type=“text” name=“exam_from_filter” id=“exsam_test” placeholder=“Выберете вариант”> </div> <button type=“submit” class=“button is-link is-rounded py-5 is-size-6 my-4” style=“width: 100%;”>Применить</button> </form> <script type=“text/javascript”> let exsam_test = [{‘id’: 2, ‘title’: ‘Владимир’}, {‘id’: 7, ‘title’: ‘Владимир_2’}]; document.addEventListener(‘DOMContentLoaded’, function() { $(‘#exsam_test’).comboTree({ source : exsam_test, cascadeSelect: true//, //selected: selected_exams }); }); </script> Во flask у меня работают следующие функции exam_from_filter = StringField(“exam_from_filter”) exam_from_filter_id = StringField(“exam_from_filter_id”) ### @bp.route(“/get_exams_name_from_filter/”, methods=[“GET”, “POST”]) def get_exams_name_from_filter(): form = Getting_exams_filter() if request.method == “POST”: exam_from_filter = request.form.get(“exam_from_filter”) exam_from_filter_id = request.form.get(“exam_from_filter_id”) print(exam_from_filter) print(exam_from_filter_id) return redirect(‘/test_random_2/’+exam_from_filter) Мне нужна функция, которая будет изменять значения value=“{‘id’: 2, ‘title’: ‘Владимир’}” на значение словаря,которое было выбрано из массива exsam_test. Причем функция должна быть написана на js и изменять value до перезагрузки сервера
b2b66ce7a5834b1284ddf994321798bd
{ "intermediate": 0.2091277539730072, "beginner": 0.5684075951576233, "expert": 0.2224646955728531 }
12,298
modify this react antd component to change the language to spanish <TimePicker.RangePicker format="HH:mm" onChange={onChangeTime} />
43862fcb82c172493f8fb8f21f13eb5c
{ "intermediate": 0.35697755217552185, "beginner": 0.4180750548839569, "expert": 0.22494739294052124 }
12,299
I have the code const [startTime, setStartTime] = useState(""); const [endTime, setEndTime] = useState(""); const onChangeTime = (date, dateString) => { console.log(date, dateString); setStartTime(dateString[0]); setEndTime(dateString[1]); }; return ( <Row className="section-modal" style={{ marginTop: "1rem" }}> <Col span={24} style={{ width: "90%", paddingLeft: "2rem", paddingRight: "2rem", }} > <p>HORARIOS DE USO:</p> <div className="time_days"> <p>Lunes:</p> <TimePicker.RangePicker format="HH:mm" onChange={onChangeTime} /> </div> <div className="time_days"> <p>Martes:</p> <TimePicker.RangePicker format="HH:mm" onChange={onChangeTime} /> </div> <div className="time_days"> <p>Miércoles:</p> <TimePicker.RangePicker format="HH:mm" onChange={onChangeTime} /> </div> <div className="time_days"> <p>Jueves:</p> <TimePicker.RangePicker format="HH:mm" onChange={onChangeTime} /> </div> <div className="time_days"> <p>Viernes:</p> <TimePicker.RangePicker format="HH:mm" onChange={onChangeTime} /> </div> <div className="time_days"> <p>Sábado:</p> <TimePicker.RangePicker format="HH:mm" onChange={onChangeTime} /> </div> <div className="time_days"> <p>Domingo:</p> <TimePicker.RangePicker format="HH:mm" onChange={onChangeTime} /> </div> </Col> </Row> ) modify it so I have a function that handles all of the days start and end times without having to write a function for each day in react, components are from antd
6daaa13e1fb216861803b2ad00d2f9c3
{ "intermediate": 0.24483515322208405, "beginner": 0.437167227268219, "expert": 0.31799760460853577 }
12,300
const Cup = () => { cupDrawer.drawFill( context, item, maxVolume, yPosition, realCellHeight, canvasSize.width, dpiScale, darkMode ); export default Cup; const cupDrawer = { drawFill: ( ctx: CanvasRenderingContext2D, cupItem: CupItem, maxVolume: number, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, darkMode: boolean, ) => { ctx.beginPath(); ctx.strokeStyle = "#ffffff00"; ctx.lineWidth = cupOptions().border.width; ctx.fillStyle = cupItem.side === "Buy" ? cupOptions(darkMode).bestBuy.fillColor : cupOptions(darkMode).bestSell.fillColor; drawRoundedRect( ctx, 0, yPosition, cupTools.getCellWidth(fullWidth, cupItem.quantity, maxVolume, false), cellHeight, cupOptions().border.radius * dpiScale, ); ctx.fill(); ctx.stroke(); }, }; export default cupDrawer; const cupOptions = (darkMode?: boolean) => ({ sell: { backgroundColor: darkMode ? "#4A0B09" : "#F3C9CE", priceColor: darkMode ? "#fff" : "#B41C18", quantityColor: darkMode ? "#CA1612" : "#191919", }, bestSell: { backgroundColor: darkMode ? "#4A0B09" : "#d0706d", fillColor: darkMode ? "#CA1612" : "#a5120e", priceColor: "#FFFFFF", quantityColor: "#FFFFFF", }, buy: { backgroundColor: darkMode ? "#0f3b2b" : "#CAD7CD", priceColor: darkMode ? "#fff" : "#006943", quantityColor: darkMode ? "#00923A" : "#191919", }, bestBuy: { backgroundColor: darkMode ? "#006943" : "#4d967b", fillColor: darkMode ? "#00923A" : "#005737", priceColor: "#FFFFFF", quantityColor: "#FFFFFF", }, font: { family: "Mont", sizePx: 11, weight: 400, }, border: { width: 1, color: darkMode ? "#191919" : "#ffffff", radius: 6, }, cell: { paddingX: 4, defaultHeight: 16, }, }); export const drawRoundedRect = ( ctx: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, radius: number, ): void => { ctx.beginPath(); ctx.moveTo(x + radius, y + 1); ctx.lineTo(x + width - radius, y + 1); ctx.lineTo(x + width - radius, y + height - 1); ctx.lineTo(x + radius, y + height - 1); ctx.arcTo(x, y + height - 1, x, y + height - radius - 1, radius); ctx.lineTo(x, y + radius + 1); ctx.arcTo(x, y + 1, x + radius, y + 1, radius); ctx.closePath(); }; export default cupOptions; нужно вместо drawRoundedRect отрисовать прямоугольник и потом скруглить углы цветом светлой/темной темы. думаю нужно путь только построить немного иначе и в два патча (beginPath / closePath)
6b125c4f6844ae49c106ce1d4886d17c
{ "intermediate": 0.20158751308918, "beginner": 0.5648085474967957, "expert": 0.23360387980937958 }
12,301
What is machine learning?
b587a9883873762bc39f09e61d41b76c
{ "intermediate": 0.019281215965747833, "beginner": 0.022544942796230316, "expert": 0.9581738710403442 }
12,302
given ` { "underdog": { "line": 30.0, "true_prob": null, "direction": null, "slip_selections": { "over": { "type": "OverUnderOption", "id": "657b076d-f8be-4179-94b4-33f3cdad7d73" }, "under": { "type": "OverUnderOption", "id": "9b04daf6-25d8-4092-8cf7-04ece63e8e2c" } } }, "prizepicks": { "line": 31.0, "true_prob": null, "direction": null, "slip_selections": { "over": { "wager_type": "over", "projection_id": "1390513" }, "under": { "wager_type": "under", "projection_id": "1390513" } } }, "nohouse": { "line": 31.0, "true_prob": null, "direction": null, "slip_selections": { "over": { "contestId": "48196", "option": "over", "selectionId": "1972063" }, "under": { "contestId": "48196", "option": "under", "selectionId": "1972063" } } }, "player_name": "LEO", "market_name": "Kills Map 1+2" },` I want the key value pair that has the lowest line
31a55e39988b005ef2a351a45de6a7e8
{ "intermediate": 0.2939944863319397, "beginner": 0.5333078503608704, "expert": 0.17269767820835114 }
12,303
Write me a lead matrix code using Shift Register that displays the name of Wassim Darwish in Arabic. I want to put the code on the Arduino Droid program
6afee618797ebf2af4337b822e245af7
{ "intermediate": 0.4522295296192169, "beginner": 0.15357036888599396, "expert": 0.39420005679130554 }
12,304
I enabled long paths on windows by changing the "LongPathsEnabled" value to 1 but it still gives me the error that files aren't found
6803c0897d37aa5136c2c58df8d13b51
{ "intermediate": 0.4224487245082855, "beginner": 0.20053476095199585, "expert": 0.37701651453971863 }
12,305
uno::Referencetable::XColumnRowRange xColumnRange как задать ColumnWidths
f4f492f3dd06201d2875df88d4fac0fd
{ "intermediate": 0.4242999851703644, "beginner": 0.23723676800727844, "expert": 0.33846327662467957 }
12,306
i made a client class and add that class a ship object but that class ship have three differents ships with inheritance. how I know what kind of ship the client has
4e08cdbb3c06ce69e0ed10f2875dff42
{ "intermediate": 0.3918377757072449, "beginner": 0.31352153420448303, "expert": 0.2946406602859497 }
12,307
What is the wrong this code:import requests import base64 import hashlib import hmac import time from urllib.parse import urlsplit from datetime import datetime, timedelta, timezone from dateutil.parser import parse as parse_date class HS256Auth(requests.auth.AuthBase): def __init__(self, api_key: str, secret_key: str): self.api_key = api_key self.secret_key = secret_key def __call__(self, r): url = urlsplit(r.url) message = [r.method, url.path] if url.query: message.append('?') message.append(url.query) if r.body: message.append(r.body) timestamp = str(int(time.time() * 1000)) message.append(timestamp) signature = hmac.new( key=self.secret_key.encode(), msg=''.join(message).encode(), digestmod=hashlib.sha256 ).hexdigest() data = [self.api_key, signature, timestamp] base64_encoded = base64.b64encode(':'.join(data).encode()).decode() r.headers['Authorization'] = f'HS256 {base64_encoded}' return r api_key = 'BcO11TU9d5cOhsmOpIEQbrJwCX208v6W' secret_key = 'fXA_3NOD2WP17PdB8FD2BfeD_kdAmmCI' auth = HS256Auth(api_key=api_key, secret_key=secret_key) # Create an offset-aware datetime for one week ago one_week_ago = datetime.now(timezone.utc) - timedelta(weeks=1) all_trades = [] with requests.Session() as s: page = 1 while True: response = s.get(f'https://api.hitbtc.com/api/3/spot/history/trade?symbol=BTCUSDT&limit=100&page={page}', auth=auth) trades = response.json() if not trades: break # Check if trades response is in expected format if 'data' not in trades: print('Invalid trades response:', trades) break trade_data = trades['data'] # Print trades data for each page print(f'Trades on page {page}:') for trade in trade_data: print(trade) # Filter trades for the past week and add to all_trades one_week_trades = [trade for trade in trade_data if parse_date(trade['timestamp']) > one_week_ago] all_trades.extend(one_week_trades) if len(trades['data']) < 100: break page += 1 print(all_trades)
daf4eea101c61b2986a26f57935032d3
{ "intermediate": 0.3893584609031677, "beginner": 0.4468442499637604, "expert": 0.1637973040342331 }
12,308
Hi there
4ac9fbbb6f1dd1e1f6d5b7d5d0a9b842
{ "intermediate": 0.32728445529937744, "beginner": 0.24503648281097412, "expert": 0.42767903208732605 }
12,309
given this data point `data = { “underdog”: { “line”: 30.0, # … }, “prizepicks”: { “line”: 31.0, # … }, “nohouse”: { “line”: 31.0, # … }, “player_name”: “LEO”, “market_name”: “Kills Map 1+2” }` how do I get the line that doesn't match the other two.... if its greater than the other two throw that whole dictionary in a list callled unders. if its less than the other two throw the whole dictionary in a list called overs
92edd2ea961bd50d5ac5d5935c8a9770
{ "intermediate": 0.3974401652812958, "beginner": 0.279449462890625, "expert": 0.3231104016304016 }
12,310
in python is there a way to do unique min and unique max? for example given 3 values 17, 17 , 18 it should return nothing if there are duplicate numbers for min same thing for max
563036d4c181e487d99754a17345e018
{ "intermediate": 0.4758884906768799, "beginner": 0.0831989198923111, "expert": 0.4409125745296478 }
12,311
Is there a way to create a rapidjson load scene function that dynamically iterates through a bunch of component names dynamically for each object?
9de39f5c8277a96d30342120a224e1d8
{ "intermediate": 0.47860798239707947, "beginner": 0.21889398992061615, "expert": 0.30249807238578796 }
12,312
I have a lambda in one account and I want to acomplish with cloudformation template, I want to create a step function that invokes a lambda in another account.
92c9351db1cae073f87072fe1a16e947
{ "intermediate": 0.39448413252830505, "beginner": 0.2720448672771454, "expert": 0.3334709703922272 }
12,313
So I have the following splunk query for a certain index in quotations “| stats count by cliIP, statusCode | lookup relaysubnet IP_subnet as cliIP OUTPUT IP_subnet as src_match | eval isRelay = if(isnull(src_match), “Other”, “Relay”) | eventstats sum(count) as total by isRelay | stats sum(count) as “count” by isRelay, statusCode, total | where statusCode = 304 | eval percentage = (count/total)*100”. Can you continue this query so that I get a bar graph that has 2 bars: Other and Relay. I want the bars to encompass the total field for both. And inside the bar I want the count represented as a percentage of the total.
12dcc90b34cbed3a35117a7e7ad5179d
{ "intermediate": 0.4492868185043335, "beginner": 0.20219551026821136, "expert": 0.34851765632629395 }
12,314
modulenotfounderror: no module named torch
20fe4cffc7215127083390b043325134
{ "intermediate": 0.3862804174423218, "beginner": 0.2812924385070801, "expert": 0.3324272036552429 }
12,315
create a python script that uses flask and folium and pywebio to display a selection menu with a questionary that filters the results that place markers on the map
6c0c0d7a62bf420334e18a38bfd83999
{ "intermediate": 0.38963815569877625, "beginner": 0.2013375610113144, "expert": 0.40902426838874817 }
12,316
use python3 programming language Write a program that executes the Parse algorithm for the grammar and table (1) below. The program receives a sequence of tokens from user input (only one command from the input like d+d*d) and run parse LL1 on it. If the input string is correct, the program should also display the desired derivation. You have to give the table to the program in a fixed way. 1) E -> TE' 2,3) E' -> +TE'|λ 4) T -> FT' 5,6) T' -> *FT'|λ 7,8) F -> (E)|d +-------+-----+-----+-----+-----+-----+-----+ | | d | + | * | ( | ) | $ | +-------+-----+-----+-----+-----+-----+-----+ | E | 1 | | | 1 | | | +-------+-----+-----+-----+-----+-----+-----+ | E' | | 2 | | | 3 | 3 | +-------+-----+-----+-----+-----+-----+-----+ | T | 4 | | | 4 | | | +-------+-----+-----+-----+-----+-----+-----+ | T' | | 6 | 5 | | 6 | 6 | +-------+-----+-----+-----+-----+-----+-----+ | F | 8 | | | 7 | | | +-------+-----+-----+-----+-----+-----+-----+
588a433f5ac19916b724e98a715bde2b
{ "intermediate": 0.31163662672042847, "beginner": 0.21380653977394104, "expert": 0.4745567739009857 }
12,317
how to put data on mongo db
033798c91109e52d3d971abc57c840c1
{ "intermediate": 0.551988959312439, "beginner": 0.1389392465353012, "expert": 0.309071809053421 }
12,318
what is 2+2
74904e8ea2f8093333782089094f045e
{ "intermediate": 0.32777461409568787, "beginner": 0.2742522358894348, "expert": 0.39797309041023254 }
12,319
PONLE JAVA SCRIPT A ESTE CODIGO <html> <head> <meta charset=“UTF-8”> <title>Quiz</title> <link rel=“stylesheet” href=“style.css”> </head> <body> <div id=“quiz-container”> <div id=“question” class=“question”>Question text goes here</div> <div id=“choices” class=“choices”> <div class=“choice”>Choice 1</div> <div class=“choice”>Choice 2</div> <div class=“choice”>Choice 3</div> <div class=“choice”>Choice 4</div> </div> <div id=“submit-btn” class=“submit-btn”>Submit</div> </div> </body> </html> <style> body { font-family: Arial, sans-serif; background-color: #f2f2f2; } .question { font-size: 24px; margin-bottom: 20px; } .choices { margin-bottom: 20px; } .choice { font-size: 20px; padding: 10px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 5px; cursor: pointer; } .choice:hover { background-color: #f9f9f9; } .selected { background-color: #007bff; color: #fff; } .submit-btn { font-size: 24px; padding: 10px; background-color: #007bff; color: #fff; border-radius: 5px; text-align: center; cursor: pointer; } .submit-btn:hover { background-color: #0069d9; } .hide { display: none; } </style> </body> </html>
82f21d85859689fd4667727a1639f55d
{ "intermediate": 0.12890057265758514, "beginner": 0.7653416991233826, "expert": 0.10575783997774124 }
12,320
can you see any improvement if yes please apply them and if i'm wrong in any stuff please correct me this is my code that detect user activity using sensors : package org.project.ayoub_akanoun_projet; import androidx.appcompat.app.AppCompatActivity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import org.project.ayoub_akanoun_projet.db.DatabaseHelper; import org.project.ayoub_akanoun_projet.entities.Activity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class RecogniweWSensorActivity extends AppCompatActivity implements SensorEventListener { private TextView tvStill, tvStillConfidence, tvWalking, tvWalkingConfidence, tvRunning, tvRunningConfidence, tvJumping, tvJumpingConfidence; private static final float MIN_MOVEMENT_THRESHOLD = 0.3f; // Adjust this value as needed private SensorManager sensorManager; private Sensor accelerometerSensor, gyroscopeSensor, stepCounterSensor, stepDetectorSensor; private float[] accelerometerData = new float[3]; private float[] gyroscopeData = new float[3]; private float[] orientation = new float[3]; private static final float GRAVITY_ALPHA = 0.8f; private static final float GYROSCOPE_ALPHA = 0.98f; private static final float ACCELEROMETER_THRESHOLD = 1.0f; private static final float GYROSCOPE_THRESHOLD = 0.1f; private List<Float> accelerometerValues; private List<Float> gyroscopeValues; String email; private int stepCount; DatabaseHelper db = new DatabaseHelper(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recogniwe_wsensor); // Initialize TextViews tvStill = findViewById(R.id.tv_still); email = getIntent().getStringExtra("email"); // Request permission to use activity recognition and sensors if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, 44); } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 45); } // Initialize sensor manager and sensors sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); gyroscopeSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); stepCounterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER); accelerometerValues = new ArrayList<>(); gyroscopeValues = new ArrayList<>(); stepCount = 0; } @Override protected void onResume() { super.onResume(); // Register sensor listeners sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this, gyroscopeSensor, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this, stepCounterSensor, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { super.onPause(); // Unregister sensor listeners to save battery sensorManager.unregisterListener(this); } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor == accelerometerSensor) { float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; float acceleration = (float) Math.sqrt(x * x + y * y + z * z); accelerometerValues.add(acceleration); } else if (event.sensor == gyroscopeSensor) { float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; float rotation = (float) Math.sqrt(x * x + y * y + z * z); gyroscopeValues.add(rotation); } else if (event.sensor == stepCounterSensor) { // Increment step count stepCount = (int) event.values[0]; } // Update activity based on the latest sensor values updateActivity(getHighestAcceleration(), getHighestRotation(), stepCount); } private long lastCleaningTime= 0; private void updateActivity(float acceleration, float rotation, int stepCount) { String activityText; // Clean sensor values every 20 seconds long currentTime = System.currentTimeMillis(); if (currentTime - lastCleaningTime >= 5000) { Toast.makeText(getApplicationContext(), "Update", Toast.LENGTH_SHORT).show(); accelerometerValues.clear(); gyroscopeValues.clear(); lastCleaningTime = currentTime; } if (acceleration > 15 && rotation > 5) { activityText = "Running"; } else if (acceleration > 10 && rotation > 2) { activityText = "Walking"; } else if (acceleration > 5 && rotation > 1) { activityText = "Standing"; } else { activityText = "Sitting"; } tvStill.setText(activityText); db.addActivity(new Activity(email,activityText, new Date().toString(), new Date().toString())); } private float getHighestAcceleration() { float highestAcceleration = 0; for (float acceleration : accelerometerValues) { if (acceleration > highestAcceleration) { highestAcceleration = acceleration; } } return highestAcceleration; } private float getHighestRotation() { float highestRotation = 0; for (float rotation : gyroscopeValues) { if (rotation > highestRotation) { highestRotation = rotation; } } return highestRotation; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Do nothing } }
45340a05d1814d9e84348dcad8fee107
{ "intermediate": 0.2792828381061554, "beginner": 0.4208188056945801, "expert": 0.2998983561992645 }
12,321
What algorithm does this string appear to be? bec0ac68976ac8f2a6823a03d89bae4390b8b70b34a95769df49147854744648
9a779b00594fe25e5e02a33187a64042
{ "intermediate": 0.08078151941299438, "beginner": 0.08297481387853622, "expert": 0.8362436890602112 }
12,322
use java script in jpg with tracking location
aaa9dbdcd9af04ba5fbf9b6a380dfdbf
{ "intermediate": 0.497104674577713, "beginner": 0.28836309909820557, "expert": 0.21453224122524261 }
12,323
This is my Loader.css: .loader { width: 48px; height: 48px; border-radius: 50%; display: inline-block; border-top: 4px solid #000000; border-right: 4px solid transparent; box-sizing: border-box; animation: rotation 1s linear infinite; } .loader::after { content: ''; box-sizing: border-box; position: absolute; left: 0; top: 0; width: 48px; height: 48px; border-radius: 50%; border-bottom: 4px solid #007bff; border-left: 4px solid transparent; } @keyframes rotation { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
b3859ccceb84c18620a3fd37028c8450
{ "intermediate": 0.39461958408355713, "beginner": 0.3017995357513428, "expert": 0.3035808503627777 }
12,324
build me a react page that has a header with our name and and a button that goes to the next screen
8c974e47691bb6b5de9a8c2ec7471e08
{ "intermediate": 0.40275320410728455, "beginner": 0.19077754020690918, "expert": 0.40646928548812866 }
12,325
generate requirements for taxi booking app like uber
de40263c818fc330472135b2dc55dc32
{ "intermediate": 0.3426910936832428, "beginner": 0.24553637206554413, "expert": 0.41177254915237427 }
12,326
generate requirements for taxi booking app like uber
d35d49f218947224a38bd7aa11793e6c
{ "intermediate": 0.3426910936832428, "beginner": 0.24553637206554413, "expert": 0.41177254915237427 }
12,327
for row in cursor: if(student_id==row[0]): student_name1 = row[1] math_grade1 = row[2] python_grade1 = row[3] modian_grade1 = row[4] shudian_grade1 = row[5] student_name.set(student_name1) math_grade.set(math_grade1) python_grade.set(python_grade1) modian_grade.set(modian_grade1) shudian_grade.set(shudian_grade1) 如何解决
3dc3ab20be3e4d70164a4156f390f5e6
{ "intermediate": 0.3672528862953186, "beginner": 0.34745991230010986, "expert": 0.2852872312068939 }
12,328
generate requirements for a landing page for taxi booking app like uber
3f9a7193cff6e836764d3d8e43a850e6
{ "intermediate": 0.2998182773590088, "beginner": 0.2679636776447296, "expert": 0.43221795558929443 }
12,329
generate html landing page for taxi booking app like uber with mobile responsiveness and best seo
5c193a14e531b8a677f3e95fcaa1480a
{ "intermediate": 0.18616849184036255, "beginner": 0.07730226218700409, "expert": 0.7365292310714722 }
12,330
use this html code for further processing
376522aaa38541887bce04085e911a86
{ "intermediate": 0.3341209590435028, "beginner": 0.2772383391857147, "expert": 0.38864076137542725 }
12,331
take this html as input <head> <title>Taxi Booking App</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;700&display=swap" rel="stylesheet"> <style> body { font-family: "Poppins", sans-serif; font-weight: 400; } h1, h2, h3, h4, h5, h6 { font-weight: 700; } .hero { background-color: #4C6EB1; color: #FFFFFF; } .button { background-color: #DB3737; color: #FFFFFF; } .column { background-color: #FFFFFF; border-radius: 5px; box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1); margin: 20px; padding: 20px; text-align: center; } .footer { background-color: #2E2E2E; color: #FFFFFF; padding: 20px; text-align: center; } .footer p { margin: 0; } .has-background-grey-dark { background-color: #2E2E2E; } </style> </head> <body> <header class="hero"> <div class="hero-body"> <div class="container has-text-centered"> <h1 class="title is-size-3-tablet is-size-2-desktop">Your Reliable Taxi Booking App</h1> <p class="subtitle is-size-5-tablet is-size-4-desktop">Get around town easily and quickly</p> <a href="#" class="button is-danger is-large">Book Now</a> </div> </div> </header> <main class="section"> <div class="container"> <section class="columns is-centered"> <div class="column is-half-tablet is-one-third-desktop"> <h2 class="title is-size-4-tablet is-size-3-desktop">Easy Booking</h2> <figure class="image"> <img src="https://cdn.pixabay.com/photo/2019/12/11/10/39/taxi-4681319_960_720.png" alt="Easy Booking"> </figure> <p class="subtitle is-size-5-tablet is-size-4-desktop">Booking a ride with our app is a breeze. Just enter your pickup location and destination and we’ll take care of the rest.</p> </div> <div class="column is-half-tablet is-one-third-desktop"> <h2 class="title is-size-4-tablet is-size-3-desktop">Fast Response Time</h2> <figure class="image"> <img src="https://cdn.pixabay.com/photo/2018/11/29/09/54/speed-3847227_960_720.jpg" alt="Fast Response Time"> </figure> <p class="subtitle is-size-5-tablet is-size-4-desktop">We know your time is valuable. That’s why we provide fast response times so you can get to your destination quickly and on time.</p> </div> <div class="column is-half-tablet is-one-third-desktop"> <h2 class="title is-size-4-tablet is-size-3-desktop">24/7 Availability</h2> <figure class="image"> <img src="https://cdn.pixabay.com/photo/2016/07/07/20/22/time-1509609_960_720.png" alt="24/7 Availability"> </figure> <p class="subtitle is-size-5-tablet is-size-4-desktop">Don’t wait until the morning to book a ride. We’re available 24/7 to get you where you need to go, no matter the time of day.</p> </div> <div class="column is-half-tablet is-one-third-desktop"> <h2 class="title is-size-4-tablet is-size-3-desktop">Flexible Payment Options</h2> <figure class="image"> <img src="https://cdn.pixabay.com/photo/2017/03/10/13/05/cash-2138594_960_720.png" alt="Flexible Payment Options"> </figure> <p class="subtitle is-size-5-tablet is-size-4-desktop">We offer a variety of payment options so you can choose the method that’s most convenient for you. Pay with cash, card or other payment options and never miss a ride.</p> </div> </section> </div> </main> <footer class="footer has-background-grey-dark"> <div class="container"> <div class="columns"> <div class="column is-half"> <p>© 2021 Taxi Booking App</p> </div> </div> </div> </footer> </body> </html>
f0964fc073e6840cd8f1f36a36aa89b0
{ "intermediate": 0.3597579002380371, "beginner": 0.5055333375930786, "expert": 0.13470880687236786 }
12,332
Please translate this code to C++ with prototypes for Visual Studio. __asm { mov esi, unitaddr; mov eax, player; movzx eax, byte ptr[eax + 0x30]; mov edx, [esi]; push 0x04; push 0x00; push eax; mov eax, [edx + 0x000000FC]; mov ecx, esi; call eax; mov retval, eax; }
087f01e77cce82829d94929671f76c2d
{ "intermediate": 0.31642380356788635, "beginner": 0.4509218633174896, "expert": 0.2326543778181076 }
12,333
generate a terraform code for aws to deploy static file to s3 with cloudfront and route 53
ccdb28214898ed293984e59f01ca8f8d
{ "intermediate": 0.4407902956008911, "beginner": 0.13891270756721497, "expert": 0.4202969968318939 }
12,334
Quero que ao clicar numa tecla de atalho,F3, possa parar(suspender) a execussão do script Python e retomar, cada vez que Clico nesse atalho. OU seja, utiliza a tecla F3, para parar e continuar alternadamente e Insere essa funcionalidade neste script: from scipy.io.wavfile import write import sounddevice as sd import numpy as np import whisper import os import keyboard import json import pyperclip para=0 sair2=1 execao=0 tex="" tex1="" model = 'c:\meu\large.pt' english = False translate = False # Translate non-english to english? samplerate = 44100 # Stream device recording frequency #samplerate = 16000 # Stream device recording frequency #blocksize = 30 # Block size in milliseconds blocksize = 111 # Block size in milliseconds #threshold = 0.25 # Minimum volume threshold to activate listening threshold = 0.0125 # Minimum volume threshold to activate listening #vocals = [50, 1000] # Frequency range to detect sounds that could be speech vocals = [20, 20000] # Frequency range to detect sounds that could be speech #endblocks = 30 # Number of blocks to wait before sending to Whisper endblocks = 8 # Number of blocks to wait before sending to Whisper # com small boas config endblocks = 5 blocksize = 111 pyperclip.copy("limpezaaaa") class StreamHandler: def __init__(self): self.running = True self.padding = 0 self.prevblock = self.buffer = np.zeros((0,1)) self.fileready = False print("\033[96mLoading Whisper Model..\033[0m", end='', flush=True) #self.model = whisper.load_model(f'{model}{".en" if english else ""}') self.model = whisper.load_model(f'{model}') print("\033[90m Done.\033[0m") def callback(self, indata, frames, time, status): #if status: print(status) # for debugging, prints stream errors. if any(indata): freq = np.argmax(np.abs(np.fft.rfft(indata[:, 0]))) * samplerate / frames if indata.max() > threshold and vocals[0] <= freq <= vocals[1]: print('.', end='', flush=True) if self.padding < 1: self.buffer = self.prevblock.copy() self.buffer = np.concatenate((self.buffer, indata)) self.padding = endblocks else: self.padding -= 1 if self.padding > 1: self.buffer = np.concatenate((self.buffer, indata)) elif self.padding < 1 and 1 < self.buffer.shape[0] > samplerate: self.fileready = True write('dictate.wav', samplerate, self.buffer) # I'd rather send data to Whisper directly.. self.buffer = np.zeros((0,1)) elif self.padding < 1 and 1 < self.buffer.shape[0] < samplerate: self.buffer = np.zeros((0,1)) print("\033[2K\033[0G", end='', flush=True) else: self.prevblock = indata.copy() #np.concatenate((self.prevblock[-int(samplerate/10):], indata)) # SLOW else: print("\033[31mNo input or device is muted.\033[0m") self.running = False def process(self): global tex1 if self.fileready: print("\n\033[90mTranscribing..\033[0m") result = self.model.transcribe('dictate.wav',language='pt',task='transcribe') print(f"\033[1A\033[2K\033[0G{result['text']}") tex1= str(result['text']) print('') #print(i,'2 Fala agora, comprimento da frase já reconhecida é ', len(tex1)) print('2 Fala agora, comprimento da frase já reconhecida é ', len(tex1)) print('-----------------------------------------------') print(tex1) print('-----------------------------------------------') print('') print('') #alucinaçoes: Um abraço! e aí E aí Tchau, tchau! Inscreva-se no canal Tchau, tchau! Deus abençoe palavra_a_remover = "..." tex1= tex1.replace(palavra_a_remover, "") #para verificar se uma variável do tipo caracteres tem menos de seis caracteres e contém a cadeira de caracteres “Tchau”. if len(tex1) < 20 and "Tchau" in tex1: # se não há texto, não faz nada tex1 ="" if tex1 =="":# se não há texto, não faz nada tex1 ="" else: #print(tex) #escreve na linha comando if tex1 !='o' or tex1 !='Tchau' or tex1 !='Tchau!' or tex1 !='Tchau.':#evita que quando não se diz nada mas ouve um ruido escreva: o keyboard.write(tex1+" ") #escreve na janela de texto activa tex1 ="" tex1 ="" self.fileready = False def listen(self): print("\033[92mListening.. \033[37m(Ctrl+C to Quit)\033[0m") with sd.InputStream(channels=1, callback=self.callback, blocksize=int(samplerate * blocksize / 1000), samplerate=samplerate): while self.running: self.process() def main(): try: handler = StreamHandler() handler.listen() except (KeyboardInterrupt, SystemExit): pass finally: print("\n\033[93mQuitting..\033[0m") if os.path.exists('dictate.wav'): os.remove('dictate.wav') if __name__ == '__main__': main()
6ae38aad2e812d4fad0bbcfbcc6779b1
{ "intermediate": 0.28125667572021484, "beginner": 0.5678309202194214, "expert": 0.15091238915920258 }
12,335
Quero que ao clicar numa tecla de atalho,F3, possa parar(suspender) a execussão do script Python e retomar, cada vez que Clico nesse atalho. OU seja, utiliza a tecla F3, para parar e continuar alternadamente e Insere essa funcionalidade neste script: from scipy.io.wavfile import write import sounddevice as sd import numpy as np import whisper import os import keyboard import json import pyperclip para=0 sair2=1 execao=0 tex="" tex1="" model = 'c:\meu\large.pt' english = False translate = False # Translate non-english to english? samplerate = 44100 # Stream device recording frequency #samplerate = 16000 # Stream device recording frequency #blocksize = 30 # Block size in milliseconds blocksize = 111 # Block size in milliseconds #threshold = 0.25 # Minimum volume threshold to activate listening threshold = 0.0125 # Minimum volume threshold to activate listening #vocals = [50, 1000] # Frequency range to detect sounds that could be speech vocals = [20, 20000] # Frequency range to detect sounds that could be speech #endblocks = 30 # Number of blocks to wait before sending to Whisper endblocks = 8 # Number of blocks to wait before sending to Whisper # com small boas config endblocks = 5 blocksize = 111 pyperclip.copy("limpezaaaa") class StreamHandler: def __init__(self): self.running = True self.padding = 0 self.prevblock = self.buffer = np.zeros((0,1)) self.fileready = False print("\033[96mLoading Whisper Model..\033[0m", end='', flush=True) #self.model = whisper.load_model(f'{model}{".en" if english else ""}') self.model = whisper.load_model(f'{model}') print("\033[90m Done.\033[0m") def callback(self, indata, frames, time, status): #if status: print(status) # for debugging, prints stream errors. if any(indata): freq = np.argmax(np.abs(np.fft.rfft(indata[:, 0]))) * samplerate / frames if indata.max() > threshold and vocals[0] <= freq <= vocals[1]: print('.', end='', flush=True) if self.padding < 1: self.buffer = self.prevblock.copy() self.buffer = np.concatenate((self.buffer, indata)) self.padding = endblocks else: self.padding -= 1 if self.padding > 1: self.buffer = np.concatenate((self.buffer, indata)) elif self.padding < 1 and 1 < self.buffer.shape[0] > samplerate: self.fileready = True write('dictate.wav', samplerate, self.buffer) # I'd rather send data to Whisper directly.. self.buffer = np.zeros((0,1)) elif self.padding < 1 and 1 < self.buffer.shape[0] < samplerate: self.buffer = np.zeros((0,1)) print("\033[2K\033[0G", end='', flush=True) else: self.prevblock = indata.copy() #np.concatenate((self.prevblock[-int(samplerate/10):], indata)) # SLOW else: print("\033[31mNo input or device is muted.\033[0m") self.running = False def process(self): global tex1 if self.fileready: print("\n\033[90mTranscribing..\033[0m") result = self.model.transcribe('dictate.wav',language='pt',task='transcribe') print(f"\033[1A\033[2K\033[0G{result['text']}") tex1= str(result['text']) print('') #print(i,'2 Fala agora, comprimento da frase já reconhecida é ', len(tex1)) print('2 Fala agora, comprimento da frase já reconhecida é ', len(tex1)) print('-----------------------------------------------') print(tex1) print('-----------------------------------------------') print('') print('') #alucinaçoes: Um abraço! e aí E aí Tchau, tchau! Inscreva-se no canal Tchau, tchau! Deus abençoe palavra_a_remover = "..." tex1= tex1.replace(palavra_a_remover, "") #para verificar se uma variável do tipo caracteres tem menos de seis caracteres e contém a cadeira de caracteres “Tchau”. if len(tex1) < 20 and "Tchau" in tex1: # se não há texto, não faz nada tex1 ="" if tex1 =="":# se não há texto, não faz nada tex1 ="" else: #print(tex) #escreve na linha comando if tex1 !='o' or tex1 !='Tchau' or tex1 !='Tchau!' or tex1 !='Tchau.':#evita que quando não se diz nada mas ouve um ruido escreva: o keyboard.write(tex1+" ") #escreve na janela de texto activa tex1 ="" tex1 ="" self.fileready = False def listen(self): print("\033[92mListening.. \033[37m(Ctrl+C to Quit)\033[0m") with sd.InputStream(channels=1, callback=self.callback, blocksize=int(samplerate * blocksize / 1000), samplerate=samplerate): while self.running: self.process() def main(): try: handler = StreamHandler() handler.listen() except (KeyboardInterrupt, SystemExit): pass finally: print("\n\033[93mQuitting..\033[0m") if os.path.exists('dictate.wav'): os.remove('dictate.wav') if __name__ == '__main__': main()
3f482216047990eb98294f116f3d3df8
{ "intermediate": 0.28125667572021484, "beginner": 0.5678309202194214, "expert": 0.15091238915920258 }
12,336
some research said that DCGAN, GAN with DCNN, often improves the training result when distinguishing chest X-ray of tuberculosis. can you SHOW ME the CODE of DCGAN?
fe976aa58b629c34cda64e6f31237316
{ "intermediate": 0.05153521150350571, "beginner": 0.021669920533895493, "expert": 0.9267948865890503 }
12,337
developerupdates Home Insights Top ChatGPT prompts for programmers with examples Top ChatGPT prompts for programmers with examples #chatgpt#ai#tutorial#programming Top ChatGPT prompts for programmers with examples Chetan Mahajan May 21, 2023 ChatGPT is going to change the world, and programmers also can't avoid this. The developer who uses AI will eventually replace the developer who does not use AI. Because AI will do your 8 hours of coding in just 2–3 hours. As I have a 400K+ audience on Instagram, I decided to write a ChatGPT Guide for Software Developers that will help them use ChatGPT to become more productive and stay ahead of the competition. So let's look at the top useful scenarios and prompts that will help you while coding. Assume you're working on a new project or feature that requires you to write new code. You can cut more than half of your development time by doing the following: Prompt to write a new code for new feature and functionality Prompt: Act as a [Technology Name] developer. [Write a detailed description] Example 1: Act as a Python developer. Write code to read and print duplicate records from the provided CSV file. Example 2: Act as a JavaScript Developer, Write a program that checks the information on a form. Name and email are required, but address and age are not. Example 3: Act as a JavaScript Developer, Write a program that checks if a string contains a substring. Prompt with technology stack and other details Prompt: Act as: [Enter your profile] Technology stack: [Enter your technology stack] Functionality: [Enter functionality] Mandatory Fields: [Enter Fields] Optional fields: [Enter Fields] Task: [Write a task description] Example 1: Act as: Node.js Developer Technology stack: Node.js, Express.js, MongoDB, Mongoose Functionality: Newsletter Mandatory Fields: Email Optional fields: name Task: Make an API that takes a name and an email address as inputs and sends back a success flag.
6a587cd446af14889886e725071b53cf
{ "intermediate": 0.3677820563316345, "beginner": 0.40539535880088806, "expert": 0.22682252526283264 }
12,338
Act as: Node.js Developer Technology stack: Node.js, Express.js, MongoDB, Mongoose Functionality: Newsletter Mandatory Fields: Email Optional fields: name Task: Make an API that takes a name and an email address as inputs and sends back a success flag
a9fc0f83cd6d6ecb94036452ac5c6233
{ "intermediate": 0.899412214756012, "beginner": 0.05229305103421211, "expert": 0.048294734209775925 }
12,339
Act as: Node.js Developer Technology stack: Node.js, Express.js, MongoDB, Mongoose Functionality: Newsletter Mandatory Fields: Email Optional fields: name Task: Make an API that takes a name and an email address as inputs and sends back a success flag. Generate only code with proper filenames and folder structure.
cb58cb3ebe98013b5425c22d1abbc3a2
{ "intermediate": 0.9041466116905212, "beginner": 0.055528830736875534, "expert": 0.04032456502318382 }
12,340
Act as: MERN Developer Technology stack: Node.js, Express.js, MongoDB, Mongoose, ReactJS Functionality: scrape google trends and populate graph in ui Task: Make an API that scrape google trends data and populate graph in UI. Generate only code with file names and folder structure.
79f95d61defddcd18ac6c9eb82e1a414
{ "intermediate": 0.8742482662200928, "beginner": 0.06398838758468628, "expert": 0.06176334619522095 }
12,341
Act as: MERN Developer Technology stack: Node.js, Express.js, MongoDB, Mongoose, ReactJS Functionality: scrape google trends and populate graph in ui Task: Make an API that scrape google trends data and populate graph in UI. Generate only code with file names and folder structure.
e6e65fdceffd78a14cb05987b6e4f4d0
{ "intermediate": 0.8742482662200928, "beginner": 0.06398838758468628, "expert": 0.06176334619522095 }
12,342
Act as: MERN Developer Technology stack: Node.js, Express.js, MongoDB, Mongoose, ReactJS Functionality: scrape google trends and populate graph in ui Task: Make an API that scrape google trends data and populate graph in UI. Generate only code with file names and folder structure. Separate the files by "###$$$###".
c380628bc5105db96ddb06268744a743
{ "intermediate": 0.8271640539169312, "beginner": 0.07392653077840805, "expert": 0.09890937805175781 }
12,343
Act as: MERN Developer Technology stack: Node.js, Express.js, MongoDB, Mongoose, ReactJS Functionality: scrape google trends and populate graph in ui Task: Make an API that scrape google trends data and populate graph in UI. Generate only code with file names and folder structure. Separate files by ###$$$###.
d6997ba2b4b9972d836ba13a16306adf
{ "intermediate": 0.8733184933662415, "beginner": 0.04980672523379326, "expert": 0.0768747553229332 }
12,344
Act as: MERN Developer Technology stack: Node.js, Express.js, MongoDB, Mongoose, ReactJS Functionality: scrape google trends and populate graph in ui Task: Make an API that scrape google trends data and populate graph in UI. Generate only code with file names and folder structure. Separate files by "NEW FILE" separator.
7d733f403f8e1431f1920e68cfa50cd5
{ "intermediate": 0.8696740865707397, "beginner": 0.05733980983495712, "expert": 0.07298615574836731 }
12,345
I am having problems with this code: Sub CopyAllREP() Dim lastRow As Long Dim i As Long Shell "notepad.exe", vbNormalFocus Application.Wait Now + TimeValue("00:00:01") 'Get the last row of data in column C lastRow = Range("C" & Rows.count).End(xlUp).Row 'Loop through each cell in column C For i = 1 To lastRow If Range("C" & i).Value = "REP" Then 'Copy the row values of column A to K Range("A" & i & ":K" & i).Copy SendKeys "^V" SendKeys "{ENTER}" SendKeys vbCrLf End If Next i 'Activate the sheet with the active cell value once the loop is finished Application.Wait Now + TimeValue("00:00:02") ThisWorkbook.Sheets(ActiveCell.Value).Activate End Sub
3ba7be5b7a2a956dfa1cb1bc41104716
{ "intermediate": 0.2955173850059509, "beginner": 0.5654484629631042, "expert": 0.1390341818332672 }
12,346
Act as: MERN Developer Technology stack: Node.js, Express.js, MongoDB, Mongoose, ReactJS Functionality: scrape google trends and populate graph in ui Task: Make an API that scrape google trends data and populate graph in UI. Generate only code. Mention file names with folder structure.
06313a257120937130f5afc3e90c89b2
{ "intermediate": 0.8089097142219543, "beginner": 0.09934523701667786, "expert": 0.09174511581659317 }
12,347
Act as: ReactJS Developer Technology stack: ReactJS Functionality: Drag and Drop Code Generator Task: Make UI to build code using drag and drop. Generate only code with file names and folder structure.
ce752a3a90b8bde5bd5ac48cf331bddb
{ "intermediate": 0.36575061082839966, "beginner": 0.25994420051574707, "expert": 0.37430518865585327 }
12,348
write a python program to solve the eight queens problem
27dead33cbce45f190082b44b4199c56
{ "intermediate": 0.19596080482006073, "beginner": 0.1506907343864441, "expert": 0.6533485054969788 }
12,349
Linux Fedora 38 additional media codecs install
b58abe831e3ce809b14d22dbbc8fc87f
{ "intermediate": 0.3548543155193329, "beginner": 0.25936082005500793, "expert": 0.38578489422798157 }
12,350
create a csv file and store data in that using javascript
c1de39d47f91a354a0de94629faeb3c7
{ "intermediate": 0.5355288982391357, "beginner": 0.16175073385238647, "expert": 0.3027203679084778 }
12,351
Unable to find the ncurses libraries or the
0bd2fb6bdc2218b9254ec196b442ea63
{ "intermediate": 0.5383247137069702, "beginner": 0.23619204759597778, "expert": 0.22548319399356842 }
12,352
I used this signal_generator code: def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Calculate EMA indicators ema_10 = ta.trend.EMAIndicator(df['Close'], window=10) ema_50 = ta.trend.EMAIndicator(df['Close'], window=50) ema_100 = ta.trend.EMAIndicator(df['Close'], window=100) ema_200 = ta.trend.EMAIndicator(df['Close'], window=200) # Calculate MA indicator ma = ta.trend.SMAIndicator(df['Close'], window=20) # Calculate EMA indicator values ema_10_value = ema_10.ema_indicator()[-1] #get the EMA 10 indicator value for the last value in the DataFrame ema_50_value = ema_50.ema_indicator()[-1] #get the EMA 50 indicator value for the last value in the DataFrame ema_100_value = ema_100.ema_indicator()[-1] #get the EMA 100 indicator value for the last value in the DataFrame ema_200_value = ema_200.ema_indicator()[-1] #get the EMA 200 indicator value for the last value in the DataFrame ma_value = ma.sma_indicator()[-1] #get the MA indicator value for the last value in the DataFrame #Bearish pattern with EMA and MA indicators if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close and close<ema_10_value and close<ema_50_value and close<ema_100_value and close<ema_200_value and close<ma_value): return 'sell' #Bullish pattern with EMA and MA indicators elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close and close>ema_10_value and close>ema_50_value and close>ema_100_value and close>ema_200_value and close>ma_value): return 'buy' #No clear pattern with EMA and MA indicators else: return '' But it giveing me wrong signals
7e838cd64ef6173b785e40d572db29ae
{ "intermediate": 0.3128967881202698, "beginner": 0.37003040313720703, "expert": 0.3170727789402008 }
12,353
You didn't continue code, code: def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Calculate EMA and MA indicators ema_10 = talib.EMA(df[‘Close’], timeperiod=10) ema_50 = talib.EMA(df[‘Close’], timeperiod=50) ema_200 = talib.EMA(df[‘Close’], timeperiod=200) ma_20 = talib.SMA(df[‘Close’], timeperiod=20) # Identify Bullish/Bearish Candlestick Patterns bullish_candles = talib.CDLDRAGONFLYDOJI(df[‘Open’], df[‘High’], df[‘Low’], df[‘Close’]) bearish_candles = talib.CDLHAMMER(df[‘Open’], df[‘High’], df[‘Low’], df[‘Close’])
7cbf446e5eb0e2811d861ca3b9d9a131
{ "intermediate": 0.3868474066257477, "beginner": 0.35975784063339233, "expert": 0.2533947825431824 }
12,354
I used this code: # Define function to calculate EMA and SMA def EMA(close, period): ema = close.ewm(span=period, adjust=False).mean() return ema def SMA(close, period): sma = close.rolling(window=period).mean() return sma # Define function to calculate Dragonfly Doji and Hammer patterns def CDLDRAGONFLYDOJI(open, high, low, close): return (high - low) <= 2*(open - close) and high - close <= 0.25*(high - low) and high - open <= 0.25*(high - low) def CDLHAMMER(open, high, low, close): return (high - low) > 3*(open - close) and (close - low) / (0.001 + high - low) > 0.6 and (open - low) / (0.001 + high - low) > 0.6 # Define function to generate signals def signal_generator(df): close = df.Close.iloc[-1] previous_close = df.Close.iloc[-2] # Calculate EMA and MA indicators ema_10 = EMA(df['Close'], 10) ema_50 = EMA(df['Close'], 50) ema_200 = EMA(df['Close'], 200) ma_20 = SMA(df['Close'], 20) # Identify Bullish/Bearish Candlestick Patterns bullish_candles = CDLDRAGONFLYDOJI(df['Open'], df['High'], df['Low'], df['Close']) bearish_candles = CDLHAMMER(df['Open'], df['High'], df['Low'], df['Close']) # Identify Trend trend = "" if ema_10.iloc[-1] > ema_50.iloc[-1] and ema_50.iloc[-1] > ema_200.iloc[-1]: trend = "Bullish" elif ema_10.iloc[-1] < ema_50.iloc[-1] and ema_50.iloc[-1] < ema_200.iloc[-1]: trend = "Bearish" else: trend = "Sideways" # Identify Signal signal = "" if close > previous_close or bullish_candles: signal = "Buy" elif close < previous_close or bearish_candles: signal = "Sell" else: signal = "Hold" return (trend, signal) But I getting ERROR: 06/17/2023 12:47:46 BTC/USDT found in the market Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 316, in <module> signal = signal_generator(df) ^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 194, in signal_generator bullish_candles = CDLDRAGONFLYDOJI(df['Open'], df['High'], df['Low'], df['Close']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 177, in CDLDRAGONFLYDOJI return (high - low) <= 2*(open - close) and high - close <= 0.25*(high - low) and high - open <= 0.25*(high - low) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\pandas\core\generic.py", line 1466, in __nonzero__ raise ValueError( ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
e07bc8895f4f5323148a036fc58a92d8
{ "intermediate": 0.24880345165729523, "beginner": 0.382883220911026, "expert": 0.36831334233283997 }