row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
40,859
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s <N_OPS> <N_ENTRIES>\n", argv[0]); return 1; } int n_ops = atoi(argv[1]); int n_entries = atoi(argv[2]); int i, j; int *vector1, *vector2, *sum; // Allocate memory for vectors vector1 = (int *)malloc(n_entries * sizeof(int)); vector2 = (int *)malloc(n_entries * sizeof(int)); sum = (int *)malloc(n_entries * sizeof(int)); if (!vector1 || !vector2 || !sum) { fprintf(stderr, "Memory allocation failed\n"); return 1; } for (i = 0; i < n_ops; i++) { // Read pairs of vectors for (j = 0; j < n_entries; j++) { scanf("%d", &vector1[j]); } for (j = 0; j < n_entries; j++) { scanf("%d", &vector2[j]); } // Add vectors and write output for (j = 0; j < n_entries; j++) { sum[j] = vector1[j] + vector2[j]; printf("%d ", sum[j]); } printf("\n\n"); } // Free allocated memory free(vector1); free(vector2); free(sum); return 0; } #!/bin/sh # Set the directory path dir='prj2-sol/vector_addition.c $0' # Since there's no build process, we just echo a message echo "No build done." #!/bin/sh # Set the directory path path=$(realpath "$0") dir="prj2-sol" # Compile the C program gcc "$dir/vector_addition.c" -o "$dir/vector_addition" # Run the program with command-line arguments from standard input "$dir/vector_addition" "$1" "$2" # Remove the compiled executable rm "$dir/vector_addition" A README file which must be submitted along with your project. It contains an initial header which you must complete (replace the dummy entries with your name, B-number and email address at which you would like to receive project-related email). After the header you may include any content which you would like read during the grading of your project. write the readme for me
f40f639bbec84ae5ee1d421cf814b82f
{ "intermediate": 0.32509908080101013, "beginner": 0.4267684519290924, "expert": 0.24813242256641388 }
40,860
What is wrong with this code: @app.route("/buy", methods=["GET", "POST"]) @login_required def buy(): if request.method == "GET": return render_template("buy.html") elif request.method == "POST": my_symbb = request.form.get('symbolb') my_quant = request.form.get('quantity') try: my_quant = int(my_quant) except ValueError: return apology("invalid quantitiy", 400) if my_quant <= 0: return apology("more than 0, idiot", 400) db.execute("INSERT INTO pruchases (symbol, shares) VALUES (my_symbb, my_quant)" my_symbb=my_symbb my_quant=my_quant)
3ca4062f2b8df235dc8ca938c323b108
{ "intermediate": 0.4959712326526642, "beginner": 0.3532809019088745, "expert": 0.1507478654384613 }
40,861
<html> <head> <title>413 Request Entity Too Large</title> </head> <body> <center> <h1>413 Request Entity Too Large</h1> </center> <hr> <center>nginx/1.18.0 (Ubuntu)</center> </body> </html>
372f34fabfea8704484a690521db468b
{ "intermediate": 0.3249635398387909, "beginner": 0.24478113651275635, "expert": 0.43025535345077515 }
40,862
We want to find the largest item in a list of n items. Use the divide-and-conquer approach to write an algorithm (pseudo code is OK). Your algorithm will return the largest item (you do not need to return the index for it). The function that you need to design is int maximum (int low, int high), which low and high stands for low and high index in the array.
3538d471fb3509f1493a823b9d18a102
{ "intermediate": 0.1548164188861847, "beginner": 0.10255525261163712, "expert": 0.7426283359527588 }
40,863
generate more comprehensive details and examples on, 5. Creating Engaging Content, minimalist tone
7f846955c516006b776981febdb07834
{ "intermediate": 0.324297159910202, "beginner": 0.3384196162223816, "expert": 0.3372832238674164 }
40,864
how do i restart a command using zsh once it errors out
67d0adbd750dd70693b9e015338e07f2
{ "intermediate": 0.6249884366989136, "beginner": 0.16323839128017426, "expert": 0.21177314221858978 }
40,865
with this error to a command, [cli][error] Error when reading from stream: Read timeout [cli][info] Stream ended or this error ^CInterrupted! Closing currently open stream... when either of the errors comes up, rerun the command
dc269f46658157c8434f04e8f331b69d
{ "intermediate": 0.4954198896884918, "beginner": 0.222110778093338, "expert": 0.2824693024158478 }
40,866
var userID = gs.getUserID(); var incident = new GlideAggregate('incident'); incident.addQuery('sys_created_by', userID); incident.addAggregate('COUNT'); incident.query(); var totalCount = 0; while(incident.next()){ totalCount = addAggregate('COUNT'); }fix this
f4015fbfd3014366f16855221dc85f1b
{ "intermediate": 0.3547288179397583, "beginner": 0.31635600328445435, "expert": 0.32891520857810974 }
40,867
как вывести сумму, которая начислилась по процентам за 12 месяцев? public static void main(String[] args) throws Exception { int month = 1; double startAmount = 998874.25; while (month <= 12) { double resSum = startAmountPlusProcentOfYear(startAmount); startAmount = resSum; month ++; } String formattedNumber = String.format("%.2f", startAmount); System.out.println("Общий капитал- " + formattedNumber + " рублей"); System.out.println("Своих денег внесено- " + (month - 1) * 80000 + " рублей"); } public static double startAmountPlusProcentOfYear(double startSum) { double procentSumAmountMonth = startSum * 0.14 / 12; double res = startSum + procentSumAmountMonth; return res; }
4e60046c8103e2c5b852e3a1cb755707
{ "intermediate": 0.28318679332733154, "beginner": 0.5995753407478333, "expert": 0.11723790317773819 }
40,868
hi
bb2e3c5a42eee6a3815d39285b11e8d6
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
40,869
how to check unresolved alaram count in ossim alienvault using CLI
88bb8ea5f0cb0b05beede30cf95a07b9
{ "intermediate": 0.44388583302497864, "beginner": 0.17740105092525482, "expert": 0.37871310114860535 }
40,870
hi!
88de4fe8048f33904ae2c67532442824
{ "intermediate": 0.32477712631225586, "beginner": 0.26637697219848633, "expert": 0.4088459014892578 }
40,871
can try to generate a complete, newly created tune in ABC notation with a full structure, In the tune
be32260bde10f13e99019f431fce047c
{ "intermediate": 0.2498367577791214, "beginner": 0.22435934841632843, "expert": 0.5258039236068726 }
40,872
In linux, how to see memory usage of a process in MB
08b845ed9bbf4df48ce75a9dde4186db
{ "intermediate": 0.3275543749332428, "beginner": 0.35301947593688965, "expert": 0.31942614912986755 }
40,873
You are an automated processing system. Customers send messages that contain information about an order. Your task is to extract the essential order information like article numbers and quantity from the message of the user and to output them in a JSON structured dataset in a format like this: { "action":"order" "order":[ {"article":"x", "quantity":1} ] } Quantity can always be a number.
0f36f7cfd8d5dd0e1bacb8a237b185d0
{ "intermediate": 0.5407524704933167, "beginner": 0.18341074883937836, "expert": 0.2758367657661438 }
40,874
post about create telegram bots
88c5faafe497d76e241e43b7c8ba31ba
{ "intermediate": 0.2619784474372864, "beginner": 0.268005907535553, "expert": 0.47001561522483826 }
40,875
solve x^2 - y = 1 in positive integers
7a97ebcbb78034a9935df489115f4481
{ "intermediate": 0.29744645953178406, "beginner": 0.4104435443878174, "expert": 0.2921099364757538 }
40,876
referal function aiogram python for telegram bot
84bcc6f3203dab2b11a2bc32463c1b95
{ "intermediate": 0.33729562163352966, "beginner": 0.26353874802589417, "expert": 0.39916566014289856 }
40,877
function proceed file from user and send user proceed file dont save on disk and save on server telegram python aiorgam
c7669a233f6ed01870690ab030e74c74
{ "intermediate": 0.4088107943534851, "beginner": 0.33861464262008667, "expert": 0.2525745630264282 }
40,878
i want to pass 1,2,3,4,5,6,7,8,9,10 as a value to a mysql stored procedure to add in a whereclause which is like AND TRIM(REGEXP_REPLACE(chamber_id, '[[:space:]]+', ' ')) IN (1,2,3,4,5,6,7,8,9,10), how to pass this parameter and how to use it
28d0d1e243e671e66dfe16ec57ff20f4
{ "intermediate": 0.3898826837539673, "beginner": 0.4862644672393799, "expert": 0.12385282665491104 }
40,879
tell me about you
bd4fc681dc8dba90442019aa6fc61282
{ "intermediate": 0.45017561316490173, "beginner": 0.3081320524215698, "expert": 0.24169236421585083 }
40,880
React display a list of tokens for each person with their information extracted from a users.json file in local folder src using only props and children to send information to this components: UserPicture, UserName and UserLocation inside a folder for each user called User and this folder inside another folder called Users, this is de users.json file : [ { "gender": "female", "name": { "title": "Miss", "first": "Ella", "last": "White" }, "location": { "street": { "number": 3507, "name": "Vimy St" }, "city": "Westport", "state": "Newfoundland and Labrador", "country": "Canada", "postcode": "M0M 2N2", "coordinates": { "latitude": "-66.8915", "longitude": "53.6948" }, "timezone": { "offset": "-10:00", "description": "Hawaii" } }, "email": "ella.white@example.com", "login": { "uuid": "5e215ef5-12d2-404e-ae74-84dcb4848e34", "username": "goldenleopard358", "password": "jeanette", "salt": "i2hcs4A3", "md5": "c35ff1538d71020bebf5018d4ff55971", "sha1": "fec8d24f6e1186d6551655cd7b6bdcf84ad1a908", "sha256": "82bc8505abc826fcb4b52c7b0e63b6048ef27ad1c5e3cdce7573d9958e0da033" }, "dob": { "date": "1989-11-28T17:41:15.620Z", "age": 33 }, "registered": { "date": "2015-06-01T08:50:27.942Z", "age": 7 }, "phone": "252-592-2784", "cell": "557-491-6037", "id": { "name": "ID", "value": "9d3db3ac-62df-4b46-8615-304bb9ce9d15" }, "picture": { "large": "https://randomuser.me/api/portraits/women/70.jpg", "medium": "https://randomuser.me/api/portraits/med/women/70.jpg", "thumbnail": "https://randomuser.me/api/portraits/thumb/women/70.jpg" }, "nat": "CA" }, { "gender": "male", "name": { "title": "Mr", "first": "Wulf", "last": "Flach" }, "location": { "street": { "number": 2814, "name": "Buchenweg" }, "city": "Havelsee", "state": "Bremen", "country": "Germany", "postcode": 63658, "coordinates": { "latitude": "39.0817", "longitude": "110.4888" }, "timezone": { "offset": "-1:00", "description": "Azores, Cape Verde Islands" } }, "email": "wulf.flach@example.com", "login": { "uuid": "688b7f2a-05b7-4173-8344-f36425491f1a", "username": "beautifultiger916", "password": "1963", "salt": "e0fPPgkL", "md5": "c7dd583fa736d7411b21afc078c4c8a2", "sha1": "fd48c761dd09736a5aa04423bae27914a4affe24", "sha256": "86ad2c27ca024d1d240741bcf322365d422ad46483b4b96a7683a63cb7ad7974" }, "dob": { "date": "1965-04-27T07:39:11.820Z", "age": 57 }, "registered": { "date": "2006-04-10T09:41:55.761Z", "age": 16 }, "phone": "0615-5882336", "cell": "0179-2551828", "id": { "name": "ID", "value": "9d3db3ac-62df-4b46-8615-304bb9ce9d15" }, "picture": { "large": "https://randomuser.me/api/portraits/men/78.jpg", "medium": "https://randomuser.me/api/portraits/med/men/78.jpg", "thumbnail": "https://randomuser.me/api/portraits/thumb/men/78.jpg" }, "nat": "DE" }, { "gender": "male", "name": { "title": "Mr", "first": "Nicolas", "last": "Lorenzo" }, "location": { "street": { "number": 6416, "name": "Avenida de Andalucía" }, "city": "Santiago de Compostela", "state": "Cantabria", "country": "Spain", "postcode": 19599, "coordinates": { "latitude": "29.6021", "longitude": "-140.7867" }, "timezone": { "offset": "+9:00", "description": "Tokyo, Seoul, Osaka, Sapporo, Yakutsk" } }, "email": "nicolas.lorenzo@example.com", "login": { "uuid": "2901ee63-c928-48dd-855a-f3882e3e63c7", "username": "purpleostrich627", "password": "michael2", "salt": "swOvRUCu", "md5": "82b5a4e93467ad2ecfb8d5fe123df2e5", "sha1": "712ea0f293be333366e0d33643907014850e9714", "sha256": "793959cb2cf4d5825196ed7e16d9b77dabff3b973c3fea74ca43bc71c58886c1" }, "dob": { "date": "1949-11-10T11:13:18.873Z", "age": 73 }, "registered": { "date": "2014-01-02T01:12:13.065Z", "age": 8 }, "phone": "995-241-301", "cell": "696-122-693", "id": { "name": "DNI", "value": "40755171-G" }, "picture": { "large": "https://randomuser.me/api/portraits/men/87.jpg", "medium": "https://randomuser.me/api/portraits/med/men/87.jpg", "thumbnail": "https://randomuser.me/api/portraits/thumb/men/87.jpg" }, "nat": "ES" }, { "gender": "female", "name": { "title": "Ms", "first": "Ellen", "last": "Saarinen" }, "location": { "street": { "number": 1354, "name": "Hämeenkatu" }, "city": "Orimattila", "state": "Southern Ostrobothnia", "country": "Finland", "postcode": 40838, "coordinates": { "latitude": "71.8391", "longitude": "50.9782" }, "timezone": { "offset": "+6:00", "description": "Almaty, Dhaka, Colombo" } }, "email": "ellen.saarinen@example.com", "login": { "uuid": "0c3145a5-bb75-499b-91ad-f9472412fa23", "username": "redostrich855", "password": "sadie", "salt": "38doGga9", "md5": "16f85c534f4118debea2a2f26d2292df", "sha1": "fe8c3ebd258ff2f4f7d62b8a524de6187cf85a74", "sha256": "4d86a88fb8260340d06471d2c449e114644aadba0d597df108344ddb9d6983b0" }, "dob": { "date": "1996-08-04T11:23:04.248Z", "age": 26 }, "registered": { "date": "2011-08-09T19:29:27.790Z", "age": 11 }, "phone": "05-074-077", "cell": "042-385-00-99", "id": { "name": "HETU", "value": "NaNNA488undefined" }, "picture": { "large": "https://randomuser.me/api/portraits/women/75.jpg", "medium": "https://randomuser.me/api/portraits/med/women/75.jpg", "thumbnail": "https://randomuser.me/api/portraits/thumb/women/75.jpg" }, "nat": "FI" }, { "gender": "male", "name": { "title": "Mr", "first": "Jonathan", "last": "Franklin" }, "location": { "street": { "number": 4715, "name": "Dane St" }, "city": "St. Petersburg", "state": "Maryland", "country": "United States", "postcode": 39723, "coordinates": { "latitude": "-37.5168", "longitude": "48.0773" }, "timezone": { "offset": "-2:00", "description": "Mid-Atlantic" } }, "email": "jonathan.franklin@example.com", "login": { "uuid": "f560c882-c146-4e2d-ac23-9c5df03810fc", "username": "heavycat966", "password": "laurent", "salt": "OZRpXuv7", "md5": "ee52cf532b00d095cf4be4f7f7335c8c", "sha1": "d348395176e6cc1b7762b20e4591cd58b01caee2", "sha256": "0f227eea74df6450bc52721af6e6af171bcca8fc4c502766174e2de544471b51" }, "dob": { "date": "1989-11-13T05:54:56.118Z", "age": 13 }, "registered": { "date": "2006-04-24T18:08:16.671Z", "age": 16 }, "phone": "(910)-700-9517", "cell": "(999)-068-9786", "id": { "name": "SSN", "value": "118-15-5715" }, "picture": { "large": "https://randomuser.me/api/portraits/men/14.jpg", "medium": "https://randomuser.me/api/portraits/med/men/14.jpg", "thumbnail": "https://randomuser.me/api/portraits/thumb/men/14.jpg" }, "nat": "US" } ]
4a97dc872d58d03b3310b514da0724aa
{ "intermediate": 0.32909685373306274, "beginner": 0.4997497498989105, "expert": 0.17115339636802673 }
40,881
Привет! Как исправить такую ошибку в терминале VS CODE? PS C:\Geekayou> .venv\Scripts\activate .venv\Scripts\activate : Невозможно загру зить файл C:\Geekayou\.venv\Scripts\Activ ate.ps1, так как выполнение сценариев отк лючено в этой системе. Для получения допо лнительных сведений см. about_Execution_P olicies по адресу https:/go.microsoft.com /fwlink/?LinkID=135170. строка:1 знак:1 + .venv\Scripts\activate + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : Ошибка без опасности: (:) [], PSSecurityExcepti on + FullyQualifiedErrorId : Unauthoriz edAccess
3a645656e5078b37c0bc8a2e39c9b595
{ "intermediate": 0.21690408885478973, "beginner": 0.6320613026618958, "expert": 0.15103457868099213 }
40,882
in rust i have a struct containg &str. and a associated method is tther that returns a chunk of struct's &str. i dont want to use String a return type. generate a function that does it in optimized way.
d74db808cabc6403d2a11e2d080f8063
{ "intermediate": 0.28000444173812866, "beginner": 0.3317568302154541, "expert": 0.3882387578487396 }
40,883
What's optmem_max in Linux?
350692c132dd49222105f8cc7a634500
{ "intermediate": 0.407993882894516, "beginner": 0.22951099276542664, "expert": 0.3624950647354126 }
40,884
how to create endpoint with fastapi , that can handle video
73af3616088e6b738f7186bcc41e0c04
{ "intermediate": 0.5954513549804688, "beginner": 0.09735103696584702, "expert": 0.30719760060310364 }
40,885
how to fix: ⚠ Your project has `@next/font` installed as a dependency, please use the built-in `next/font` instead. The `@next/font` package will be removed in Next.js 14. You can migrate by running `npx @next/codemod@latest built-in-next-font .`. Read more: https://nextjs.org/docs/messages/built-in-next-font ○ Compiling / ... <w> [webpack.cache.PackFileCacheStrategy] Skipped not serializable cache item 'Compilation/modules|C:\xampp\htdocs\NEWS\node_modules\next\dist\build\webpack\loaders\css-loader\src\index.js??ruleSet[1].rules[7].oneOf[13].use[1]!C:\xampp\htdocs\NEWS\node_modules\next\dist\build\webpack\loaders\postcss-loader\src\index.js??ruleSet[1].rules[7].oneOf[13].use[2]!C:\xampp\htdocs\NEWS\styles\globals.css': No serializer registered for Warning <w> while serializing webpack/lib/cache/PackFileCacheStrategy.PackContentItems -> webpack/lib/NormalModule -> Array { 1 items } -> webpack/lib/ModuleWarning -> Warning ⚠ ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[7].oneOf[13].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[7].oneOf[13].use[2]!./styles/globals.css Warning (182:5) Nested CSS was detected, but CSS nesting has not been configured correctly. Please enable a CSS nesting plugin *before* Tailwind in your configuration. See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting Import trace for requested module: ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[7].oneOf[13].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[7].oneOf[13].use[2]!./styles/globals.css ./styles/globals.css ].rules[7].oneOf[13].use[2]!./styles/globals.css ].rules[7].oneOf[13].use[2]! Warning (182:5) Nested CSS was detected, but CSS nesting has not been configured correctly. Please enable a CSS nesting plugin *before* Tailwind in your configuration. See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting Import trace for requested module: ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[7].oneOf[13].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rs??ruleSet[1].rules[7].oneOf[13].use[2]!./styles/globals.css ules[7].oneOf[13].use[2]!./s ./styles/globals.css <w> [webpack.cache.PackFileCacheStrategy] Skipped not serializable cache item 'Compilation/modules|C:\xampp\htdocs\NEWS\node_modules\next\dist\build\webpack\loaders\css-loader\src\index.js??ruleSetdex.js??ruleSet[1].rules[7].oneOf[13].use[1]!C:\xampp\htdocs\NEWS\node_modules\next\dist\build\webpack\loaders\postcss-loader\src\index.js??ruleSet[1].rules[7].oneOf[13].use[2]!C:\xap\doyles\globas[1].rules[7].oneOf[13].use[1mpp\htdocs\NEWS\styles\globals.css': No serializer registered for Warning red for Warning <w> while serializing webpack/lib/cache/PackFileCacheStrategy.PackContentItems -> webpack/lib/NormalModule -> Array { 1 items } -> webpack/lib/ModuleWarning -> Warning ⚠ ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[7].oneOf[13].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[7].oneOf[13].use[2]!./styles/globals.css Warning (182:5) Nested CSS was detected, but CSS nesting has not been configured correctly. Please enable a CSS nesting plugin *before* Tailwind in your configuration. See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting Import trace for requested module: ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[7].oneOf[13].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[7].oneOf[13].use[2]!./styles/globals.css ./styles/globals.css
c7d3047a97d17b54fa26b24432d4a698
{ "intermediate": 0.2914658188819885, "beginner": 0.3094756007194519, "expert": 0.3990585207939148 }
40,886
hey! i need a list of all loyalty cards types with examples
1ef946e7d5dc823a9561c3442c1c90e7
{ "intermediate": 0.35910385847091675, "beginner": 0.38831627368927, "expert": 0.25257986783981323 }
40,887
'//: //////////////////////////////////////////////////////////////////////////// '//+ '//+ Copyright (c) Sagemcom Froeschl GmbH. All rights reserved. '//+ '//+ //////////////////////////////////////////////////////////////////////////// '//+ '//+ project: BugFix build '//+ parameter: There are several command line parameters defined. '//+ Syntax: setup.vbs /<name>:<value> /<name>:<value> ... '//+ <name> can be: '//+ * install-path Indicates where the files should be installed. '//+ If omitted the path installation is not silent. '//+ '//+ remarks: Installs the bugfix into a specific path. '//+ '//. //////////////////////////////////////////////////////////////////////////// Option Explicit Run64BitScriptEngineIfAvailable Const ForReading = 1 Dim g_oFSO : Set g_oFSO = CreateObject("Scripting.FileSystemObject") Dim g_oShell : Set g_oShell = WScript.CreateObject("WScript.Shell") Dim g_oLogger : Set g_oLogger = new CLogger Dim g_oBugfixInstaller : Set g_oBugfixInstaller = new CBugfixInstaller Dim g_dicFilesToRegister : Set g_dicFilesToRegister = CreateObject("Scripting.Dictionary") Dim g_szScriptPath : g_szScriptPath = g_oFSO.GetParentFolderName(WScript.ScriptFullName) Dim g_szItfEdvPath : g_szItfEdvPath = CombinePath(g_oShell.ExpandEnvironmentStrings("%PROGRAMDATA%"), "ITF-EDV\zfa_f") Dim g_szInstallFolder : g_szInstallFolder = "" SyncCmdLineArg "install-path", g_szInstallFolder g_dicFilesToRegister.CompareMode = vbTextCompare ' file name | COM+ (True) or COM (False) g_dicFilesToRegister.Add "Printsvr.dll", True Main '/// ////////////////////////////////////////////////////////////////////////////////////////////// Sub Main() If IsSilentInstallation() Then SilentInstall() Else NonSilentInstall() End If End Sub '/// Main function for nonsilent installation Function NonSilentInstall() Dim szInstallFolder Dim fVersionCopied : fVersionCopied = False Dim oVersionHarvester : Set oVersionHarvester = new CVersionHarvester Dim aInstalledVersions : aInstalledVersions = oVersionHarvester.GetInstalledVersions() For Each szInstallFolder In aInstalledVersions If MsgBox("Apply bugfix to ZFA-F in the folder """ & szInstallFolder & """?", vbYesNo+vbQuestion, WScript.ScriptName)=vbYes Then Init GetRealPathName(szInstallFolder) If CopyExtractedFilesIntoTargetFolder() Then fVersionCopied = True End If Next If Not fVersionCopied Then Init GetRealPathName(InputBox("Installation directory", WScript.ScriptName, "")) CopyExtractedFilesIntoTargetFolder() End If RunInstanceManager g_oLogger.ShowLogFile End Function '/// Main function for silent installation Function SilentInstall() EnsureCScriptIsRunningExt 1, True, False Init GetRealPathName(g_szInstallFolder) CopyExtractedFilesIntoTargetFolder() RunInstanceManager End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Sub Init(ByRef szInstallFolder) g_szInstallFolder = szInstallFolder Dim fValidInstallDir : fValidInstallDir = IsValidInstallDir() InitOutput() CheckInput() BugfixInstaller WScript.ScriptFullName, fValidInstallDir RemoveFilesFromTargetFolder() End Sub '/// Initializes the Output (console, logging) Function InitOutput() g_oLogger.Init CombinePath(g_szInstallFolder, "log\installer\") g_oLogger.Write "" g_oLogger.Write "Applying Bugfix to folder """ & g_szInstallFolder & """ ..." g_oLogger.Write "" If IsSilentInstallation() Then g_oLogger.Write "Silent Installation started" Else g_oLogger.Write "Installation started" End If End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Sub CheckInput() If Len(g_szInstallFolder)=0 Then g_oLogger.Write "Installation path: invalid input" g_oLogger.ShowLogFile WScript.Quit(-1) End If End Sub '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function IsValidInstallDir() If (Not g_oFSO.FolderExists(g_szInstallFolder)) Then IsValidInstallDir = false Exit Function End If Dim oFolder : Set oFolder = g_oFSO.GetFolder(g_szInstallFolder) If (g_oFSO.FolderExists(g_szInstallFolder) _ And oFolder.Files.Count = 0 _ And oFolder.SubFolders.Count = 0) Then IsValidInstallDir = false Else IsValidInstallDir = true End If End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function IsSilentInstallation() IsSilentInstallation = (WScript.Arguments.Count > 0) End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Function DeleteFile(ByVal filePath) On Error Resume Next Err.Clear g_oFSO.DeleteFile filePath, True Dim szErrorText : szErrorText = "" If Err.Number <> 0 Then szErrorText = " (err.Number """ & err.Number & "; "" err.Description """ & err.Description & """)" End If Err.Clear On Error GoTo 0 If Len(szErrorText)=0 Then g_oLogger.WriteWithTime "File removed: " & filePath DeleteFile = True Else g_oLogger.WriteWithTime "ERROR: '" & filePath & "' couldn't be deleted!" & szErrorText DeleteFile = False End If End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Sub RemoveFilesFromTargetFolder() Dim filesToDeleteTxt : filesToDeleteTxt = CombinePath(g_szScriptPath, "FilesToDelete.txt") If Not g_oFSO.FileExists(filesToDeleteTxt) Then Exit Sub End If Dim errorCount : errorCount = 0 Dim txtFileStream : Set txtFileStream = g_oFSO.OpenTextFile(filesToDeleteTxt, ForReading, False) g_oLogger.Write "Cleanup 64-Bit ZFA-F" Do While txtFileStream.AtEndOfStream = False Dim filePath : filePath = g_szInstallFolder & Trim(txtFileStream.ReadLine) If g_oFSO.FileExists(filePath) Then g_oFSO.DeleteFile filePath Dim fileDeleted : fileDeleted = Not g_oFSO.FileExists(filePath) If Not fileDeleted Then g_oLogger.WriteWithTime "Error: '" & filePath & "' couldn't be deleted!" errorCount = errorCount + 1 End If Else g_oLogger.WriteWithTime "WARNING: Skipped: '" & filePath & "' not found" End If Loop txtFileStream.Close g_oLogger.Write errorCount & " error(s) occurred" g_oLogger.Write " " End Sub '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function CopyExtractedFilesIntoTargetFolder() CopyExtractedFilesIntoTargetFolder = False Dim oColDicUpdateInfo : Set oColDicUpdateInfo = new CUpdateInfoCollection AnalyseFileStructure oColDicUpdateInfo Dim errorText : errorText = oColDicUpdateInfo.RenameInvalidFiles() If Len(errorText) > 0 Then g_oLogger.Write "Update is not possible due to following conflicts:" g_oLogger.Write "" g_oLogger.Write "64-Bit update errors" g_oLogger.Write "" g_oLogger.Write errorText Exit Function End If g_oLogger.Write "Updating 64-Bit ZFA-F " & " (" & oColDicUpdateInfo.Count & " files)" CopyReleaseNotes "En" CopyReleaseNotes "De" Dim fRegisterComObjectIfNecessary : fRegisterComObjectIfNecessary = Not oColDicUpdateInfo.OnlyNewFiles Dim uiFailures : uiFailures = 0 Dim oUpdateInfo For Each oUpdateInfo In oColDicUpdateInfo.Items CreateCompleteFolder g_oFSO.GetParentFolderName(oUpdateInfo.m_TargetFile) If oUpdateInfo.CopyFile() Then If fRegisterComObjectIfNecessary Then If Not RegisterComObjectIfNecessary(oUpdateInfo) Then uiFailures = uiFailures + 1 End If End If Else uiFailures = uiFailures + 1 End If Next g_oLogger.Write uiFailures & " error(s) occurred" CopyExtractedFilesIntoTargetFolder = True End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Private Sub CopyReleaseNotes(ByVal szLanguage) Dim szReleaseNotesFileName : szReleaseNotesFileName = CombinePath(g_szScriptPath, "ReleaseNotes" & szLanguage & ".html") If g_oFSO.FileExists(szReleaseNotesFileName) Then CreateCompleteFolder g_szInstallFolder g_oFSO.CopyFile szReleaseNotesFileName, CombinePath(g_szInstallFolder, "ReleaseNotes" & szLanguage & ".html"), True End If End Sub '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function BugfixInstaller(ByVal szScriptFullName, ByRef fValidInstallDir) Dim oFile : Set oFile = g_oFSO.GetFile(szScriptFullName) Dim szFolder : szFolder = g_oFSO.GetParentFolderName(oFile) g_oLogger.Write "" If (g_oBugfixInstaller.Init(szFolder, g_szInstallFolder, g_oLogger.GetLogFilePath) And _ fValidInstallDir) Then g_oLogger.Write "Run bugfixinstaller.exe" Else g_oLogger.Write "Skip bugfixinstaller.exe" Exit Function End If g_oLogger.CloseLogFile Dim iErrorCode : iErrorCode = g_oBugfixInstaller.Run If Not (iErrorCode = 0) Then g_oLogger.OpenLogFile g_oLogger.Write "Error occured in bugfixinstaller.exe. ERRORCODE: " & iErrorCode g_oLogger.Write "You can find further information in the manual ""install_hb.pdf"" under:" g_oLogger.Write "Shared processes > Installing a bugfix and customer build" g_oLogger.ShowLogFile WScript.Quit(-1) End If g_oLogger.OpenLogFile End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Sub RunInstanceManager() Dim szInstanceManagerCfg : szInstanceManagerCfg = CombinePath(g_szInstallFolder, "bin\instancemanager_wu.cfg") If g_oFSO.FileExists(szInstanceManagerCfg) Then g_oLogger.Write "" g_oLogger.Write "Setup Instance Manager" g_oLogger.Write "" Dim szSourceInstanceManager : szSourceInstanceManager = CombinePath(g_szScriptPath, "instancemanagersetup.exe") Dim szInstanceManager : szInstanceManager = CombinePath(g_szInstallFolder, "bin\instancemanagersetup.exe") If g_oFSO.FileExists(szSourceInstanceManager) Then g_oFSO.CopyFile szSourceInstanceManager, szInstanceManager, True End If If Not g_oFSO.FileExists(szInstanceManager) Then g_oLogger.Write "Error: '" & szInstanceManager & "' not found!" Exit Sub End If g_oFSO.DeleteFile szInstanceManagerCfg If g_oFSO.FileExists(szInstanceManagerCfg) Then g_oLogger.Write "Error: '" & szInstanceManagerCfg & "' couldn't be deleted!" Exit Sub End If g_oShell.Run("cmd /c " & szInstanceManager), 1, True If g_oFSO.FileExists(szInstanceManagerCfg) Then g_oLogger.Write "'" & szInstanceManagerCfg & "' created" Else g_oLogger.Write "Error: '" & szInstanceManagerCfg & "' couldn't be created!" End If End If End Sub '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function RegisterComObjectIfNecessary(ByVal oUpdateInfo) RegisterComObjectIfNecessary = True If g_dicFilesToRegister.Exists(g_oFSO.GetFileName(oUpdateInfo.m_TargetFile)) Then Dim oRegisterServer : Set oRegisterServer = new CRegisterServer g_oLogger.Write "Register file """ & oUpdateInfo.m_TargetFile & """." If Not oRegisterServer.Register(oUpdateInfo, g_dicFilesToRegister(g_oFSO.GetFileName(oUpdateInfo.m_TargetFile))) Then g_oLogger.Write "ERROR: An error occurred while trying to register """ & oUpdateInfo.m_TargetFile & """!" g_oLogger.Write "INFO: Registering a DLL requires admin rights. Please run Bugfix.exe as admin if not already done!" RegisterComObjectIfNecessary = False End If End If End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Sub AnalyseFileStructure(ByVal oColDicUpdateInfo) Dim oSubFolder For Each oSubFolder In g_oFSO.GetFolder(CombinePath(g_szScriptPath, "unicode\x64")).SubFolders AnalyseFileStructureRecursive oSubFolder, CombinePath(g_szInstallFolder, oSubFolder.name), oColDicUpdateInfo Next End Sub '/// ////////////////////////////////////////////////////////////////////////////////////////////// Sub AnalyseFileStructureRecursive(ByVal oSourceFolder, ByVal szTargetPath, ByVal oColDicUpdateInfo) Dim oFile, oUpdateInfo For Each oFile In oSourceFolder.Files Set oUpdateInfo = new CUpdateInfo oUpdateInfo.m_SourceFile = oFile.path oUpdateInfo.m_TargetFile = CombinePath(szTargetPath, oFile.name) If (StrComp(g_oFSO.GetExtensionName(oFile.name), "dll", vbTextCompare) = 0 Or _ StrComp(g_oFSO.GetExtensionName(oFile.name), "exe", vbTextCompare) = 0) Then oUpdateInfo.m_fBinaryFile = True If g_oFSO.FileExists(oUpdateInfo.m_TargetFile) Then oUpdateInfo.m_fTargetFileDoesExist = True If IsThirdPartyBinary(oUpdateInfo.m_TargetFile) Then oUpdateInfo.m_fThirdPartyDll = True End If If IsUpdateAllowedRegardingVersion(oFile.path, oUpdateInfo.m_TargetFile) Then oUpdateInfo.m_fVersionIdentical = True End If End If Else Dim iHtdocsPosition : iHtdocsPosition = InStr(1, oFile.Path, "htdocs", vbTextCompare) If iHtdocsPosition > 0 Then oUpdateInfo.m_fWebFile = True If oColDicUpdateInfo.IsDistributedInstallation() Then oUpdateInfo.m_TargetFile = CombinePath(g_szItfEdvPath, Mid(oFile.Path, iHtdocsPosition)) End If End If If g_oFSO.FileExists(oUpdateInfo.m_TargetFile) Then oUpdateInfo.m_fTargetFileDoesExist = True End If oColDicUpdateInfo.Add oUpdateInfo Next Dim oSubFolder For Each oSubFolder In oSourceFolder.SubFolders AnalyseFileStructureRecursive oSubFolder, CombinePath(szTargetPath, oSubFolder.name), oColDicUpdateInfo Next End Sub '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function IsUpdateAllowedRegardingVersion(ByVal szSourceFile, ByVal szTargetFile) Dim aVersionSource : aVersionSource = Split(GetFileVersion(szSourceFile), ".") Dim aVersionTarget : aVersionTarget = Split(GetFileVersion(szTargetFile), ".") IsUpdateAllowedRegardingVersion = (aVersionSource(0)=aVersionTarget(0) And aVersionSource(1)=aVersionTarget(1)) End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function GetMajorAndMinorVersionOfBugfix() Dim szVersionInfo : szVersionInfo = CombinePath(g_szScriptPath, "version.info") If Not g_oFSO.FileExists(szVersionInfo) Then MsgBox "ERROR: The file 'version.info' is missing.", vbCritical, WScript.ScriptFullName WScript.Quit(-1) End If Dim szMajor : szMajor = ReadIni(szVersionInfo, "VERSION", "MAJOR") Dim szMinor : szMinor = ReadIni(szVersionInfo, "VERSION", "MINOR") GetMajorAndMinorVersionOfBugfix = szMajor & "." & szMinor End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function ReadIni( myFilePath, mySection, myKey ) Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 Dim intEqualPos Dim objFSO, objIniFile Dim strFilePath, strKey, strLeftString, strLine, strSection Set objFSO = CreateObject( "Scripting.FileSystemObject" ) ReadIni = "" strFilePath = Trim( myFilePath ) strSection = Trim( mySection ) strKey = Trim( myKey ) If objFSO.FileExists( strFilePath ) Then Set objIniFile = objFSO.OpenTextFile( strFilePath, ForReading, False ) Do While objIniFile.AtEndOfStream = False strLine = Trim( objIniFile.ReadLine ) If LCase( strLine ) = "[" & LCase( strSection ) & "]" Then strLine = Trim( objIniFile.ReadLine ) Do While Left( strLine, 1 ) <> "[" intEqualPos = InStr( 1, strLine, "=", 1 ) If intEqualPos > 0 Then strLeftString = Trim( Left( strLine, intEqualPos - 1 ) ) If LCase( strLeftString ) = LCase( strKey ) Then ReadIni = Trim( Mid( strLine, intEqualPos + 1 ) ) If ReadIni = "" Then ReadIni = " " End If Exit Do End If End If If objIniFile.AtEndOfStream Then Exit Do strLine = Trim( objIniFile.ReadLine ) Loop Exit Do End If Loop objIniFile.Close Else WScript.Echo strFilePath & " doesn't exists. Exiting..." Wscript.Quit 1 End If End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function GetMajorAndMinorVersion(ByVal szInstallFolder) GetMajorAndMinorVersion = "" Dim szZfa : szZfa = CombinePath(szInstallFolder, "bin\zfa_f.exe") If g_oFSO.FileExists(szZfa) Then ' zfa_f.exe must always exist if it is an installed version Dim aVersion : aVersion = Split(GetFileVersion(szZfa), ".") GetMajorAndMinorVersion = aVersion(0) & "." & aVersion(1) End If End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Private Function GetFileVersion(ByVal szFileName) GetFileVersion = g_oFSO.GetFileVersion(szFileName) If Len(GetFileVersion)=0 Then g_oLogger.WriteWithTime "WARNING: Version information for file """ & szFileName & """ can't be determined. File may be locked!" GetFileVersion = "0.0.0.0" End If End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function IsThirdPartyBinary(ByVal szFilePath) ' copyright = 25 Dim szCopyright : szCopyright = GetDetail(szFilePath, 25) If InStr(1, szCopyright, "Sagemcom", vbTextCompare) > 0 Then g_oLogger.WriteWithTime "File: " & szFilePath & " is a Sagemcom binary" IsThirdPartyBinary = False Else g_oLogger.WriteWithTime "File: " & szFilePath & " is a thirdparty binary" IsThirdPartyBinary = True End If End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// class CRegisterServer '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Function Register(ByVal oUpdateInfo, ByVal fIsComPlus) UnRegister oUpdateInfo, fIsComPlus 'wscript.echo "cmd /c """ & GetCmdLine(oUpdateInfo, fIsComPlus, True) & """" g_oLogger.Write "cmd /c """ & GetCmdLine(oUpdateInfo, fIsComPlus, True) & """" Register = (g_oShell.Run("cmd /c """ & GetCmdLine(oUpdateInfo, fIsComPlus, True) & """", 1, True) = 0) End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Function UnRegister(ByVal oUpdateInfo, ByVal fIsComPlus) UnRegister = (g_oShell.Run("cmd /c """ & GetCmdLine(oUpdateInfo, fIsComPlus, False) & """", 1, True) = 0) End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Private Function GetCmdLine(ByVal oUpdateInfo, ByVal fIsComPlus, ByVal fRegister) Dim szRegSvcsExecutable : szRegSvcsExecutable = GetRegExecutable(fIsComPlus) If fRegister Then GetCmdLine = szRegSvcsExecutable & " /c " Else GetCmdLine = szRegSvcsExecutable & " /u " End If If fIsComPlus Then GetCmdLine = GetCmdLine & "/appname:" & GetAppName(oUpdateInfo) & " " End If GetCmdLine = GetCmdLine & """" & oUpdateInfo.m_TargetFile & """" End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Private Function GetAppName(ByVal oUpdateInfo) If InStr(1, oUpdateInfo.m_SourceFile, "x64", vbTextCompare) > 1 Then GetAppName = g_oFSO.GetBaseName(oUpdateInfo.m_SourceFile) & "64" Else GetAppName = g_oFSO.GetBaseName(oUpdateInfo.m_SourceFile) End If End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Private Function GetRegExecutable(ByVal fIsComPlus) Dim szDotNetFrameworkPath : szDotNetFrameworkPath = CombinePath(g_oShell.ExpandEnvironmentStrings("%WinDir%"), "Microsoft.NET") If Not g_oFSO.FolderExists(szDotNetFrameworkPath) Then MsgBox ".Net Framework not found!", vbCritical, WScript.ScriptFullName WScript.Quit(-1) End If Dim iCnt : iCnt = 0 Dim oDicExecutables : Set oDicExecutables = CreateObject("Scripting.Dictionary") Dim szDotNetFrameworkPath64 : szDotNetFrameworkPath64 = CombinePath(szDotNetFrameworkPath, "Framework64") If g_oFSO.FolderExists(szDotNetFrameworkPath64) Then GetRegExecutablesHelper g_oFSO.GetFolder(szDotNetFrameworkPath64), oDicExecutables, iCnt, fIsComPlus End If If oDicExecutables.Count = 0 Then MsgBox "RegSvcs.exe not found!", vbCritical, WScript.ScriptFullName WScript.Quit(-1) End If GetRegExecutable = oDicExecutables(1) End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Private Function GetRegExecutablesHelper(ByVal oFolder, ByRef oDicExecutables, ByRef iCnt, ByVal fIsComPlus) Dim oSubFolder For Each oSubFolder In oFolder.SubFolders GetRegExecutablesHelper oSubFolder, oDicExecutables, iCnt, fIsComPlus Next Dim szExecName If fIsComPlus Then szExecName = "RegSvcs.exe" Else szExecName = "RegAsm.exe" End If Dim oFile For Each oFile In oFolder.Files If StrComp(Left(oFile.ParentFolder.Name, 2), "v4", vbTextCompare) = 0 Then If StrComp(oFile.Name, szExecName, vbTextCompare) = 0 Then iCnt = iCnt + 1 oDicExecutables.Add iCnt, oFile.path End If End If Next End Function End Class '/// ////////////////////////////////////////////////////////////////////////////////////////////// Class CUpdateInfo Public m_SourceFile Public m_TargetFile Public m_fBinaryFile Public m_fVersionIdentical Public m_fThirdPartyDll Public m_fTargetFileDoesExist Public m_fWebFile '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Sub Class_Initialize() m_fBinaryFile = False m_fVersionIdentical = False m_fThirdPartyDll = False m_fTargetFileDoesExist = False m_fWebFile = False End Sub '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Property Get SourceFileInfo SourceFileInfo = GetFileInfo(m_SourceFile) End Property '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Property Get TargetFileInfo TargetFileInfo = GetFileInfo(m_TargetFile) End Property '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Function CopyFile() On Error Resume Next Err.Clear g_oFSO.CopyFile m_SourceFile, m_TargetFile, True Dim szErrorText : szErrorText = "" If Err.Number <> 0 Then szErrorText = " (err.Number """ & err.Number & "; "" err.Description """ & err.Description & """)" End If Err.Clear On Error GoTo 0 If Len(szErrorText)=0 Then g_oLogger.WriteWithTime "Copy from """ & SourceFileInfo & """ to """ & TargetFileInfo & """" CopyFile = True Else g_oLogger.WriteWithTime "ERROR: Copy from """ & SourceFileInfo & """ to """ & TargetFileInfo & """" & szErrorText CopyFile = False End If End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Private Function GetFileInfo(ByVal szFileName) If Not m_fBinaryFile Or Not g_oFSO.FileExists(szFileName) Then GetFileInfo = szFileName Exit Function End If GetFileInfo = szFileName & " : " & GetFileVersion(szFileName) End Function End Class ' CUpdateInfo '/// ////////////////////////////////////////////////////////////////////////////////////////////// Class CUpdateInfoCollection Private m_dicUpdateInfo '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Sub Class_Initialize() Set m_dicUpdateInfo = CreateObject("Scripting.Dictionary") End Sub '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Property Get Count Count = m_dicUpdateInfo.Count End Property '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Property Get Items Items = m_dicUpdateInfo.Keys End Property '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Sub Add(ByVal oUpdateInfo) m_dicUpdateInfo.Add oUpdateInfo, 0 End Sub '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Function RenameInvalidFiles() RenameInvalidFiles = "" Dim oUpdateInfo For Each oUpdateInfo In Items If oUpdateInfo.m_fBinaryFile _ And oUpdateInfo.m_fTargetFileDoesExist _ And Not oUpdateInfo.m_fVersionIdentical _ And Not oUpdateInfo.m_fThirdPartyDll Then Dim szSourceFile : szSourceFile = oUpdateInfo.m_TargetFile Dim szTargetFile : szTargetFile = oUpdateInfo.m_TargetFile & "." & GetFileVersion(oUpdateInfo.m_TargetFile) & ".old" On Error Resume Next Err.Clear g_oFSO.MoveFile szSourceFile, szTargetFile Dim szErrorText : szErrorText = "" If Err.Number <> 0 Then szErrorText = " (err.Number """ & err.Number & "; "" err.Description """ & err.Description & """)" End If Err.Clear On Error GoTo 0 If Len(szErrorText)=0 Then g_oLogger.Write "File renamed from """ & szSourceFile & """ to """ & szTargetFile & """" Else RenameInvalidFiles = RenameInvalidFiles + " ERROR: Rename file from """ & szSourceFile & """ to """ & szTargetFile & """" & szErrorText End If End If Next End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Function IsDistributedInstallation() Dim oConfigFilePath Dim szConfigPath : szConfigPath = CombinePath(g_szInstallFolder, "config") Dim szCentralConfigurationIniPath : szCentralConfigurationIniPath = CombinePath(szConfigPath, "central_configuration.ini") Dim szLanguageIniPath : szLanguageIniPath = CombinePath(szConfigPath, "\language.ini") If(g_oFSO.FileExists(szCentralConfigurationIniPath)) Then Set oConfigFilePath = g_oFSO.OpenTextFile(szCentralConfigurationIniPath, ForReading) ElseIf(g_oFSO.FileExists(szLanguageIniPath)) Then Set oConfigFilePath = g_oFSO.OpenTextFile(szLanguageIniPath, ForReading) Else IsDistributedInstallation = False Exit Function End If Do until oConfigFilePath.AtEndOfStream Dim szLine : szLine = oConfigFilePath.ReadLine If (Left(szLine, 10) = "SETUP_MODE") Then If (Right(szLine, 11) = "centralized") Then IsDistributedInstallation = False Exit Do Else IsDistributedInstallation = True Exit Do End If End If Loop End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Function OnlyNewFiles() OnlyNewFiles = True Dim oUpdateInfo For Each oUpdateInfo In Items If oUpdateInfo.m_fTargetFileDoesExist Then OnlyNewFiles = False Exit Function End If Next End Function End Class ' CUpdateInfoCollection '/// ////////////////////////////////////////////////////////////////////////////////////////////// Class CVersionHarvester '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Function GetInstalledVersions() Dim szRegKeyZfa64 : szRegKeyZfa64 = "HKLM\SOFTWARE\ITF-EDV\ZFA-F\" Dim oDic : Set oDic = CreateObject("Scripting.Dictionary") AddInstalledVersionIfAvailable szRegKeyZfa64 & "InstallFolder", oDic AddInstalledVersionIfAvailable szRegKeyZfa64 & "InstallDir", oDic Dim szSubKey For Each szSubKey In RegReadSubKeys("SOFTWARE\ITF-EDV\ZFA-F") AddInstalledVersionIfAvailable szRegKeyZfa64 & szSubKey & "\InstallFolder", oDic AddInstalledVersionIfAvailable szRegKeyZfa64 & szSubKey & "\InstallDir", oDic Next GetInstalledVersions = oDic.Keys End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Private Function GetRegEntry(szRegkey) On Error Resume Next GetRegEntry = g_oShell.RegRead(szRegKey) On Error GoTo 0 End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Private Function RegReadSubKeys(ByVal szKeyPath) On Error Resume Next Dim arrSubKeys const HKEY_LOCAL_MACHINE = &H80000002 Dim oReg : Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv") oReg.EnumKey HKEY_LOCAL_MACHINE, szKeyPath, arrSubKeys If Not IsArray(arrSubKeys) Then RegReadSubKeys = Split("", ",") Exit Function End If On Error GoTo 0 RegReadSubKeys = arrSubKeys End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Class CBugfixInstaller Private m_szBugfixInstaller Private m_szInstallDir Private m_szVersionInfoPath Private m_szLogFile '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Function Init(ByVal szSource, ByVal szInstallDir, ByVal szLogFile) szSource = TrimEx(szSource, """") szInstallDir = TrimEx(szInstallDir, """") szLogFile = TrimEx(szLogFile, """") m_szBugfixInstaller = """" & szSource & "\bugfixinstaller.exe" & """" m_szInstallDir = """" & szInstallDir & """" m_szVersionInfoPath = """" & szSource & "\version.info" & """" m_szLogFile = """" & szLogFile & """" Init = g_oFSO.FileExists(TrimEx(m_szBugfixInstaller, """")) and g_oFSO.FileExists(TrimEx(m_szVersionInfoPath, """")) and g_oFSO.FileExists(TrimEx(m_szLogFile, """")) End Function '/// ////////////////////////////////////////////////////////////////////////////////////////////// Public Function Run() Run = (g_oShell.Run("cmd /c """ & m_szBugfixInstaller & " --installdir=" & m_szInstallDir & " --logfile=" & m_szLogFile & " --versioninfo=" & m_szVersionInfoPath & """", 1, True)) End Function End Class ' CBugfixInstaller '/// ////////////////////////////////////////////////////////////////////////////////////////////// '/// Helper functions '/// ////////////////////////////////////////////////////////////////////////////////////////////// '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function GetRealPathName(ByVal szPathName) If Len(szPathName) = 0 Then GetRealPathName = szPathName Exit Function End If szPathName = TrimEx(szPathName, """") GetRealPathName = g_oFSO.GetAbsolutePathName(g_oShell.ExpandEnvironmentStrings(szPathName)) End Function '/// Checks if a specific named command line argument exists. If it exists it would be '/// assigned to the output variable. '/// @param[in] szCmdLineParamName Name of the named command line argument. '/// @param[out] Value Buffer for the value of the named command line argument. Sub SyncCmdLineArg(ByVal szCmdLineParamName, ByRef Value) If WScript.Arguments.Named(szCmdLineParamName) = "" Then Exit Sub End If Select Case VarType(Value) Case vbEmpty Value=WScript.Arguments.Named(szCmdLineParamName) Case vbString Value=WScript.Arguments.Named(szCmdLineParamName) Case vbInteger Value=CInt(WScript.Arguments.Named(szCmdLineParamName)) Case vbBoolean If StrComp(WScript.Arguments.Named(szCmdLineParamName), "true", vbTextCompare)=0 Then Value = True ElseIf StrComp(WScript.Arguments.Named(szCmdLineParamName), "false", vbTextCompare)=0 Then Value = False Else MsgBox "A boolean variable must be initialized with ""true"" or ""false"".", vbCritical, WScript.ScriptFullName End If Case Else MsgBox "Variable type not supported yet. You have to extend the function ""SyncCmdLineArg"".", vbCritical, WScript.ScriptFullName End Select End Sub '/// ////////////////////////////////////////////////////////////////////////////////////////////// Function TrimEx(ByVal szStringWhichWillBeTrimmed, ByVal szCharacterToTrim) Dim oRegEx : Set oRegEx = new RegExp szCharacterToTrim = Replace(szCharacterToTrim, "\", "\\") oRegEx.Pattern = "^[" & szCharacterToTrim & "]*(.*?)[" & szCharacterToTrim & "]+$" oRegEx.IgnoreCase = True TrimEx = oRegEx.Replace(szStringWhichWillBeTrimmed, "$1") End Function '/// Ensures that a complete path is created. '/// @param[in] Name of path which should be generated. '/// @remarks Caution! This function can deliver different results by using different windows versions (iColumn). Function GetDetail(ByVal szFilePath, ByVal iColumn) If Not g_oFSO.FileExists(szFilePath) Then Exit Function Dim oAppShell : Set oAppShell = CreateObject("Shell.Application") Dim oFolder : Set oFolder = oAppShell.Namespace(g_oFSO.GetParentFolderName(szFilePath)) If oFolder Is Nothing Then Exit Function Dim oFolderItem : Set oFolderItem = oFolder.ParseName(g_oFSO.GetFileName(szFilePath)) If oFolderItem Is Nothing Then Exit Function GetDetail = oFolder.GetDetailsOf(oFolderItem, iColumn) Set oFolderItem = Nothing End Function Convert to c# code
cb8ba646a30fe757c998bbe54c48b4c5
{ "intermediate": 0.32372018694877625, "beginner": 0.528849184513092, "expert": 0.14743059873580933 }
40,888
You're a system admin / devops. You've a solution that use Kong, Keycloak, FastAPI, Redis, RabbitMQ, PostgreSQL and MariaDB. All of them are in a docker-compose.
968647f5033c3f08e49df72f31e2c80c
{ "intermediate": 0.9022905230522156, "beginner": 0.054246686398983, "expert": 0.043462809175252914 }
40,889
You're a devops / system admin. You have a solution, that use Kong, Keycloak, FastAPI, Redis, RabbitMQ, PostgreSQL, MariaDB, all of them are in a docker-compose. How do you monitor this ?
0c838f032fbbe62fd5e567815b248da7
{ "intermediate": 0.9604053497314453, "beginner": 0.02314627170562744, "expert": 0.01644839346408844 }
40,890
simulate form filling for backend for flask app
27051de45c3f43e7496c7842411eff4e
{ "intermediate": 0.3797473609447479, "beginner": 0.297554612159729, "expert": 0.32269808650016785 }
40,891
What is this error: nix error: building nix env: exit status 1 Output has been trimmed to the last 20 lines whose name attribute is located at /nix/store/4va5hjb3sdk8pnpn3dsnkdg65fw28jgv-nixpkgs-23.05-src/pkgs/stdenv/generic/make-derivation.nix:303:7 … while evaluating attribute 'REPLIT_LD_LIBRARY_PATH' of derivation 'nix-shell' at «string»:309:9: 308| { 309| REPLIT_LD_LIBRARY_PATH = (pkgs.lib.optionalString (env ? REPLIT_LD_LIBRARY_PATH) (env.REPLIT_LD_LIBRARY_PATH + ":")) + | ^ 310| pkgs.lib.makeLibraryPath deps; error: attribute 'jest' missing at /home/runner/BluevioletPaltryAbstractions/replit.nix:6:5: 5| pkgs.yarn 6| pkgs.replitPackages.jest | ^ 7| ];
8c5006b6cca15cd43bf2b6f032331645
{ "intermediate": 0.500613272190094, "beginner": 0.24160157144069672, "expert": 0.2577851414680481 }
40,892
Using this info, please make me a script and steps to running GPT chat in replit: Using GPT-3.5 and GPT-4 via the OpenAI API in Python In this tutorial, you'll learn how to work with the OpenAI Python package to programmatically have conversations with ChatGPT. Apr 2023 · 14 min read CONTENTS When Should You Use the API Rather Than The Web Interface? Setup An OpenAI Developer Account Securely Store Your Account Credentials Setting up Python The Code Pattern for Calling GPT via the API Your First Conversation: Generating a Dataset Use a Helper Function to call GPT Reusing Responses from the AI Assistant Using GPT in a Pipeline Take it to the Next Level SHARE ChatGPT is a cutting-edge large language model for generating text. It's already changing how we write almost every type of text, from tutorials like this one, to auto-generated product descriptions, Bing's search engine results, and dozens of data use cases as described in the ChatGPT for Data Science cheat sheet. For interactive use, the web interface to ChatGPT is ideal. However, OpenAI (the company behind ChatGPT) also has an application programming interface (API) that lets you interact with ChatGPT and their other models using code. In this tutorial, you'll learn how to work with the openai Python package to programmatically have conversations with ChatGPT. Note that OpenAI charges to use the GPT API. (Free credits are sometimes provided to new users, but who gets credit and how long this deal will last is not transparent.) It costs $0.002 / 1000 tokens, where 1000 tokens equal about 750 words. Running all the examples in this tutorial once should cost less than 2 US cents (but if you rerun tasks, you will be charged every time). When Should You Use the API Rather Than The Web Interface? The ChatGPT web application is a great interface to GPT models. However, if you want to include AI into a data pipeline or into software, the API is more appropriate. Some possible use cases for data practitioners include: Pulling in data from a database or another API, then asking GPT to summarize it or generate a report about it Embedding GPT functionality in a dashboard to automatically provide a text summary of the results Providing a natural language interface to your data mart Performing research by pulling in journal papers through the scholarly (PyPI, Conda) package, and getting GPT to summarize the results Setup An OpenAI Developer Account To use the API, you need to create a developer account with OpenAI. You'll need to have your email address, phone number, and debit or credit card details handy. Follow these steps: Go to the API signup page. Create your account (you'll need to provide your email address and your phone number). Go to the API keys page. Create a new secret key. Take a copy of this key. (If you lose it, delete the key and create a new one.) Go to the Payment Methods page. Click 'Add payment method' and fill in your card details. Securely Store Your Account Credentials The secret key needs to be kept secret! Otherwise, other people can use it to access the API, and you will pay for it. The following steps describe how to securely store your key using DataCamp Workspace. If you are using a different platform, please check the documentation for that platform. You can also ask ChatGPT for advice. Here's a suggested prompt: > You are an IT security expert. You are speaking to a data scientist. Explain the best practices for securely storing private keys used for API access. In your workspace, click on Integrations Click on the "Create integration" plus button Select an "Environment Variables" integration In the "Name" field, type "OPENAI". In the "Value" field, paste in your secret key Click "Create", and connect the new integration Setting up Python To use GPT via the API, you need to import the os and openai Python packages. If you are using a Jupyter Notebook (like DataCamp Workspace), it's also helpful to import some functions from IPython.display. One example also uses the yfinance package to retrieve stock prices. # Import the os package import os # Import the openai package import openai # From the IPython.display package, import display and Markdown from IPython.display import display, Markdown # Import yfinance as yf import yfinance as yf OpenAI The other setup task is to put the environment variable you just created in a place that the openai package can see it. # Set openai.api_key to the OPENAI environment variable openai.api_key = os.environ["OPENAI"] OpenAI The Code Pattern for Calling GPT via the API The code pattern to call the OpenAI API and get a chat response is as follows: response = openai.ChatCompletion.create( model="MODEL_NAME", messages=[{"role": "system", "content": 'SPECIFY HOW THE AI ASSISTANT SHOULD BEHAVE'}, {"role": "user", "content": 'SPECIFY WANT YOU WANT THE AI ASSISTANT TO SAY'} ]) OpenAI There are several things to unpack here. OpenAI API model names for GPT The model names are listed in the Model Overview page of the developer documentation. In this tutorial, you'll be using gpt-3.5-turbo, which is the latest model used by ChatGPT that has public API access. (When it becomes broadly available, you'll want to switch to gpt-4.) OpenAI API GPT message types There are three types of message documented in the Introduction to the Chat documentation: system messages describe the behavior of the AI assistant. A useful system message for data science use cases is "You are a helpful assistant who understands data science." user messages describe what you want the AI assistant to say. We'll cover examples of user messages throughout this tutorial assistant messages describe previous responses in the conversation. We'll cover how to have an interactive conversation in later tasks The first message should be a system message. Additional messages should alternate between the user and the assistant. Your First Conversation: Generating a Dataset Generating sample datasets is useful for testing your code against different data scenarios or for demonstrating code to others. To get a useful response from GPT, you need to be precise and specify the details of your dataset, including: the number of rows and columns the names of the columns a description of what each column contains the output format of the dataset Here's an example user message to create a dataset. Create a small dataset about total sales over the last year. The format of the dataset should be a data frame with 12 rows and 2 columns. The columns should be called "month" and "total_sales_usd". The "month" column should contain the shortened forms of month names from "Jan" to "Dec". The "total_sales_usd" column should contain random numeric values taken from a normal distribution with mean 100000 and standard deviation 5000. Provide Python code to generate the dataset, then provide the output in the format of a markdown table. OpenAI Let's include this message in the previous code pattern. # Define the system message system_msg = 'You are a helpful assistant who understands data science.' # Define the user message user_msg = 'Create a small dataset about total sales over the last year. The format of the dataset should be a data frame with 12 rows and 2 columns. The columns should be called "month" and "total_sales_usd". The "month" column should contain the shortened forms of month names from "Jan" to "Dec". The "total_sales_usd" column should contain random numeric values taken from a normal distribution with mean 100000 and standard deviation 5000. Provide Python code to generate the dataset, then provide the output in the format of a markdown table.' # Create a dataset using GPT response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": user_msg}]) OpenAI Check the response from GPT is OK API calls are "risky" because problems can occur outside of your notebook, like internet connectivity issues, or a problem with the server sending you data, or because you ran out of API credit. You should check that the response you get is OK. GPT models return a status code with one of four values, documented in the Response format section of the Chat documentation. stop: API returned complete model output length: Incomplete model output due to max_tokens parameter or token limit content_filter: Omitted content due to a flag from our content filters null: API response still in progress or incomplete The GPT API sends data to Python in JSON format, so the response variable contains deeply nested lists and dictionaries. It's a bit of a pain to work with! For a response variable named response, the status code is stored in the following place. response["choices"][0]["finish_reason"] OpenAI Extract the AI assistant's message Buried within the response variable is the text we asked GPT to generate. Luckily, it's always in the same place. response["choices"][0]["message"]["content"] OpenAI The response content can be printed as usual with print(content), but it's Markdown content, which Jupyter notebooks can render, via display(Markdown(content)) Here's the Python code to generate the dataset: import numpy as np import pandas as pd # Set random seed for reproducibility np.random.seed(42) # Generate random sales data sales_data = np.random.normal(loc=100000, scale=5000, size=12) # Create month abbreviation list month_abbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] # Create dataframe sales_df = pd.DataFrame({'month': month_abbr, 'total_sales_usd': sales_data}) # Print dataframe print(sales_df) And here's the output in markdown format: | month | total_sales_usd | |-------|----------------| | Jan | 98728.961189 | | Feb | 106931.030292 | | Mar | 101599.514152 | | Apr | 97644.534384 | | May | 103013.191014 | | Jun | 102781.514665 | | Jul | 100157.741173 | | Aug | 104849.281004 | | Sep | 100007.081991 | | Oct | 94080.272682 | | Nov | 96240.993328 | | Dec | 104719.371461 | OpenAI Use a Helper Function to call GPT You need to write a lot of repetitive boilerplate code to do these three simple things. Having a wrapper function to abstract away the boring bits is useful. That way, we can focus on data science use cases. Hopefully, OpenAI will improve the interface to their Python package so this sort of thing is built-in. In the meantime, feel free to use this in your own code. The function takes two arguments. system: A string containing the system message. user_assistant: An array of strings that alternate user message then assistant message. The return value is the generated content. def chat(system, user_assistant): assert isinstance(system, str), "`system` should be a string" assert isinstance(user_assistant, list), "`user_assistant` should be a list" system_msg = [{"role": "system", "content": system}] user_assistant_msgs = [ {"role": "assistant", "content": user_assistant[i]} if i % 2 else {"role": "user", "content": user_assistant[i]} for i in range(len(user_assistant))] msgs = system_msg + user_assistant_msgs response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=msgs) status_code = response["choices"][0]["finish_reason"] assert status_code == "stop", f"The status code was {status_code}." return response["choices"][0]["message"]["content"] OpenAI Example usage of this function is response_fn_test = chat("You are a machine learning expert.",["Explain what a neural network is."]) display(Markdown(response_fn_test)) OpenAI A neural network is a type of machine learning model that is inspired by the architecture of the human brain. It consists of layers of interconnected processing units, called neurons, that work together to process and analyze data. Each neuron receives input from other neurons or from external sources, processes that input using a mathematical function, and then produces an output that is passed on to other neurons in the network. The structure and behavior of a neural network can be adjusted by changing the weights and biases of the connections between neurons. During the training process, the network learns to recognize patterns and make predictions based on the input it receives. Neural networks are often used for tasks such as image classification, speech recognition, and natural language processing, and have been shown to be highly effective at solving complex problems that are difficult to solve with traditional rule-based programming methods. OpenAI Reusing Responses from the AI Assistant In many situations, you will wish to form a longer conversation with the AI. That is, you send a prompt to GPT, get a response back, and send another prompt to continue the chat. In this case, you need to include the previous response from GPT in the second call to the API, so that GPT has the full context. This will improve the accuracy of the response and increase consistency across the conversation. In order to reuse GPT's message, you retrieve it from the response, and then pass it into a new call to chat. Example: Analyzing the sample dataset Let's try calculating the mean of the sales column from the dataset that was previously generated. Note that because we didn't use the chat() function the first time, we have to use the longer subsetting code to get at the previous response text. If you use chat(), the code is simpler. # Assign the content from the response in Task 1 to assistant_msg assistant_msg = response["choices"][0]["message"]["content"] # Define a new user message user_msg2 = 'Using the dataset you just created, write code to calculate the mean of the `total_sales_usd` column. Also include the result of the calculation.' # Create an array of user and assistant messages user_assistant_msgs = [user_msg, assistant_msg, user_msg2] # Get GPT to perform the request response_calc = chat(system_msg, user_assistant_msgs) # Display the generated content display(Markdown(response_calc)) OpenAI Sure! Here's the code to calculate the mean of the `total_sales_usd` column:
31dea66b9a5aaed1c2e4e5ff6f9014dd
{ "intermediate": 0.47314321994781494, "beginner": 0.325276643037796, "expert": 0.20158010721206665 }
40,893
Данные A_id Size Weight Sweetness Crunchiness Juiciness Ripeness Acidity Quality 0 0.0 -3.970049 -2.512336 5.346330 -1.012009 1.844900 0.329840 -0.491590483 good 1 1.0 -1.195217 -2.839257 3.664059 1.588232 0.853286 0.867530 -0.722809367 good 2 2.0 -0.292024 -1.351282 -1.738429 -0.342616 2.838636 -0.038033 2.621636473 bad 3 3.0 -0.657196 -2.271627 1.324874 -0.097875 3.637970 -3.413761 0.790723217 good 4 4.0 1.364217 -1.296612 -0.384658 -0.553006 3.030874 -1.303849 0.501984036 good import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import cross_val_score, train_test_split from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler df = pd.read_csv(csv_file_path) quality_ordinals = {'low': 1, 'medium': 2, 'high': 3} X['Quality'] = X['Quality'].apply(X['Quality'].value_counts().get) X['Quality'] = X['Quality'].apply(quality_ordinals.get) np.random.seed(42) %matplotlib inline %config InlineBackend.figure_format = 'retina' target = 'Quality' features = df.columns.drop(target) features = features.drop('A_id') # Удалим идентификатор пользователя как нерепрезентативный признак print(features) X, y = df[features].copy(), df[target]
0add75d4a02076848a0ab3854a890a2a
{ "intermediate": 0.2786024808883667, "beginner": 0.25153666734695435, "expert": 0.46986091136932373 }
40,894
he has to identify the words are spam or not. Help him in order to analyze and classify the spam data using XG Boost Classifier emails.csv: information : rows of the emails from 1 to 350 and numbered accordingly by the words count of 1st row and 1st row contains the bunch of words of email text. give me python program which must display all the required plots and all the visual plots (which is not required with advance show-case to display and see and reveal more details) give me outputs with all paramters... https://www.kaggle.com/datasets/balaka18/email-spam-classification-dataset-csv/code
cd7faf68af0022057ec6a8e7fec8b8d7
{ "intermediate": 0.4999460279941559, "beginner": 0.129601389169693, "expert": 0.3704526126384735 }
40,895
he has to identify the words are spam or not. Help him in order to analyze and classify the spam data using XG Boost Classifier emails.csv: information : rows of the emails from 1 to 350 and numbered accordingly by the words count of 1st row and 1st row contains the bunch of words of email text. - graph and visual plots and display first columns and rows of the dataset and index also display give me python program which must display all the required plots and all the visual plots (which is not required with advance show-case to display and see and reveal more details) graph and visual plots give me outputs with all paramters...roc, classification report, roc curve with all visual plots, r1_score, etc like: class and frequency distribution, class distribution dataset doesn't have labels: 0 (or) 1 Iteration, loss and accuracy(%) -- graph and visual plots Sequence input 1 dimension Number of hidden units 100 State activation function tanh Gate activation function sigmoid Output 2 Epsilon 1e-8 Training parameters Optimizer Adam Gradient decay factor 0.9 Squared gradient decay factor 0.999 Max Epoch 150 Mini Batchsize 128 LearnRateDropFactor 1e-2 Initial learning rate (α) 1e-3 Execution environment Auto confusion matrix: output class, target class percentage(%) & learning classifiers, AC, PREC, Recall, F-measure, -- graphs plots true label and predicted label visual plots plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic') plt.legend(loc="lower right") plt.show() # Feature Importance xgb.plot_importance(xgb_clf) plt.title('Feature Importance') plt.show() # Gain and Cover Plots xgb.plot_importance(xgb_clf, importance_type='gain') plt.title('Feature Importance - Gain') plt.show() xgb.plot_importance(xgb_clf, importance_type='cover') plt.title('Feature Importance - Cover') plt.show()
8013078e56f3a70771725c98a2f13382
{ "intermediate": 0.25055351853370667, "beginner": 0.1380346417427063, "expert": 0.6114118695259094 }
40,896
Can you make a complete list of sysctl settings on Linux that relates to amount of a simultaneous tcp connections in different states. Make a short comment to each setting on what it affects.
2793da902e2d8a526dd4946c0cb86369
{ "intermediate": 0.2955227196216583, "beginner": 0.2628117799758911, "expert": 0.44166550040245056 }
40,897
Данные A_id Size Weight Sweetness Crunchiness Juiciness Ripeness Acidity Quality 0 0.0 -3.970049 -2.512336 5.346330 -1.012009 1.844900 0.329840 -0.491590483 good 1 1.0 -1.195217 -2.839257 3.664059 1.588232 0.853286 0.867530 -0.722809367 good 2 2.0 -0.292024 -1.351282 -1.738429 -0.342616 2.838636 -0.038033 2.621636473 bad 3 3.0 -0.657196 -2.271627 1.324874 -0.097875 3.637970 -3.413761 0.790723217 good 4 4.0 1.364217 -1.296612 -0.384658 -0.553006 3.030874 -1.303849 0.501984036 good import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import cross_val_score, train_test_split from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler df = pd.read_csv(csv_file_path) quality_ordinals = {‘low’: 1, ‘medium’: 2, ‘high’: 3} X[‘ ’] = X[‘ ’].apply(X[‘ ’].value_counts().get) X[‘ ’] = X[‘ ’].apply(quality_ordinals.get) np.random.seed(42) %matplotlib inline %config InlineBackend.figure_format = ‘retina’ target = ‘ ’ features = df.columns.drop(target) features = features.drop(‘ ’) # Удалим идентификатор пользователя как нерепрезентативный признак print(features) X, y = df[features].copy(), df[target] scaler = StandardScaler() X = pd.DataFrame(data=scaler.fit_transform(X), columns=X.columns) Исправить код
1a46fe0eca669abc8a0570ec62f5da8f
{ "intermediate": 0.38416269421577454, "beginner": 0.20254568755626678, "expert": 0.4132915735244751 }
40,898
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import cross_val_score, train_test_split from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler df = pd.read_csv(csv_file_path) df = pd.read_csv(csv_file_path) quality_ordinals = {'bad': 1, 'good': 2, 'excellent': 3} X = df.copy() # Преобразование категориальных значений в числовые X['Quality'] = X['Quality'].apply(lambda x: quality_ordinals.get(x, 0)) np.random.seed(42) %matplotlib inline %config InlineBackend.figure_format = 'retina' target = 'Quality' features = X.columns.drop(target) features = features.drop('A_id') # Удалим идентификатор пользователя как нерепрезентативный признак print(features) X, y = X[features], X[target] # Разделение на матрицу признаков и целевую переменную from sklearn.ensemble import RandomForestRegressor from pprint import pprint rf = RandomForestRegressor(random_state = 42) # Look at parameters used by our current forest print('Параметры по умолчанию:\n') pprint(rf.get_params()) from sklearn.model_selection import RandomizedSearchCV n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)] max_features = ['auto', 'sqrt'] max_depth = [int(x) for x in np.linspace(10, 110, num = 11)] max_depth.append(None) min_samples_split = [2, 5, 10] min_samples_leaf = [1, 2, 4] bootstrap = [True, False] random_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap} from sklearn.model_selection import RandomizedSearchCV n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)] max_features = ['auto', 'sqrt'] max_depth = [int(x) for x in np.linspace(10, 110, num = 11)] max_depth.append(None) min_samples_split = [2, 5, 10] min_samples_leaf = [1, 2, 4] bootstrap = [True, False] random_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap} rf = RandomForestRegressor(random_state=42) rf_random = RandomizedSearchCV(estimator=rf, param_distributions=random_grid, n_iter=100, cv=3, verbose=2, random_state=42, n_jobs=-1) rf_random.fit(train_data, train_labels) Ошибка NameError Traceback (most recent call last) <ipython-input-351-e99837ecd0a6> in <cell line: 4>() 2 rf_random = RandomizedSearchCV(estimator=rf, param_distributions=random_grid, n_iter=100, 3 cv=3, verbose=2, random_state=42, n_jobs=-1) ----> 4 rf_random.fit(train_data, train_labels) NameError: name 'train_data' is not defined
f6ef7453f2038748f8fc7725099cc60b
{ "intermediate": 0.41886216402053833, "beginner": 0.48208707571029663, "expert": 0.09905066341161728 }
40,899
Traceback (most recent call last): File "c:\Users\Kikin\OneDrive\Bureau\Trading\IA de Trading\structure_IA.py", line 4, in <module> import tensorflow as tf File "C:\Users\Kikin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\tensorflow\__init__.py", line 39, in <module> from tensorflow.python.tools import module_util as _module_util ModuleNotFoundError: No module named 'tensorflow.python'
f602d7b34605bcd120afe2894038ea12
{ "intermediate": 0.40261194109916687, "beginner": 0.2730294167995453, "expert": 0.32435864210128784 }
40,900
WARNING: The script tensorboard.exe is installed in 'C:\Users\Kikin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\\Users\\Kikin\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\tensorflow\\include\\external\\com_github_grpc_grpc\\src\\core\\ext\\filters\\client_channel\\lb_policy\\grpclb\\client_load_reporting_filter.h' HINT: This error might have occurred since this system does not have Windows Long Path support enabled. You can find information on how to enable this at https://pip.pypa.io/warnings/enable-long-paths
e9e93ca43cb90a3caafd93ae1783e0a5
{ "intermediate": 0.3318324089050293, "beginner": 0.18841122090816498, "expert": 0.47975632548332214 }
40,901
Hi. What is 56^79 times 9206?
e2a7021238a7d4ad17410556d4387ee4
{ "intermediate": 0.3171013593673706, "beginner": 0.2859877049922943, "expert": 0.3969109356403351 }
40,902
In c++ I have this code: Class Size { Size() : Size(0,0) {} Size(int x, int y) {...} SetX ... SetY ... } Class Main { private: Size size; } Which way is more efficient? 1) int windowWidth = 0; int windowHeight = 0; SDL_GetWindowSize(window, &windowWidth, &windowHeight); size.SetX(windowWidth); size.SetY(windowHeight); 2) int windowWidth = 0; int windowHeight = 0; SDL_GetWindowSize(window, &windowWidth, &windowHeight); size = Size(windowWidth, windowHeight) 3) Alternative?
83ec29b01978e6af647807022e969b82
{ "intermediate": 0.35859936475753784, "beginner": 0.49305662512779236, "expert": 0.1483440101146698 }
40,903
You're an system admin. Make a qemu configuration to execute alpine linux, with 1 cpu and 1G ram
1bba566bdfa100d22440e1026fd84c69
{ "intermediate": 0.33037713170051575, "beginner": 0.39278507232666016, "expert": 0.2768377661705017 }
40,904
How to make a command with one option per line and a comment that explain this option in powershell ?
f1ec4b28914bfd23c2905dc79dd13548
{ "intermediate": 0.5063918828964233, "beginner": 0.16944953799247742, "expert": 0.324158638715744 }
40,905
In my game called star system generator, give formula for restricted distance. Above 50 AU distance from Sun-like radius, planets can't be placed.
5e42dc348e6f2fb43ceb6b017d66d957
{ "intermediate": 0.40108564496040344, "beginner": 0.2803995907306671, "expert": 0.31851476430892944 }
40,906
some info about my dataset # Convert 'WeekDate' to datetime format dataset_newitem = dataset_newitem.with_columns( pl.col("WeekDate").str.strptime(pl.Datetime, "%Y-%m-%d") ) # Group by ‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, 'CL4' and 'WeekDate', then sum 'OrderQuantity' y_cl4 = dataset_newitem.groupby(['MaterialID', 'SalesOrg', 'DistrChan', 'CL4', 'WeekDate']).agg( pl.sum("OrderQuantity").alias("OrderQuantity") ) # Sort by 'WeekDate' y_cl4 = y_cl4.sort("WeekDate") # Concatenate ‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, ‘CL4’ to a new column ‘unique_id’ y_cl4 = y_cl4.with_columns( pl.concat_str([pl.col('MaterialID'), pl.col('SalesOrg'), pl.col('DistrChan'), pl.col('CL4')], separator='_').alias('unique_id') ) # Drop the original columns y_cl4 = y_cl4.drop(['MaterialID', 'SalesOrg', 'DistrChan', 'CL4']) # Renaming columns to 'ds' and 'y' to meet the input requirements of the StatsForecast library y_cl4 = y_cl4.rename({'WeekDate': 'ds', 'OrderQuantity': 'y'}) y_cl4.head() ds y unique_id datetime[μs] f64 str 2022-06-27 00:00:00 12.0 "12499186_US01_… 2022-06-27 00:00:00 128.0 "12506328_US01_… 2022-06-27 00:00:00 32.0 "12506326_US01_… 2022-06-27 00:00:00 96.0 "12520808_US01_… 2022-06-27 00:00:00 252.0 "12409760_US01_… 4275 series ranging from 1 week to 74 weeks, weekly data length ┆ count │ │ --- ┆ --- │ │ u32 ┆ u32 │ ╞════════╪═══════╡ │ 1 ┆ 1942 │ │ 2 ┆ 357 │ │ 3 ┆ 157 │ │ 4 ┆ 107 │ │ 5 ┆ 74 │ │ 6 ┆ 40 │ │ 7 ┆ 48 │ │ 8 ┆ 37 │ │ 9 ┆ 39 │ │ 10 ┆ 47 │ │ 11 ┆ 54 │ │ 12 ┆ 36 │ │ 13 ┆ 35 │ │ 14 ┆ 43 │ │ 15 ┆ 47 │ │ 16 ┆ 45 │ │ 17 ┆ 36 │ │ 18 ┆ 37 │ │ 19 ┆ 51 │ │ 20 ┆ 35 │ │ 21 ┆ 41 │ │ 22 ┆ 29 │ │ 23 ┆ 26 │ │ 24 ┆ 33 │ │ 25 ┆ 35 │ │ 26 ┆ 41 │ │ 27 ┆ 39 │ │ 28 ┆ 34 │ │ 29 ┆ 37 │ │ 30 ┆ 31 │ │ 31 ┆ 32 │ │ 32 ┆ 26 │ │ 33 ┆ 30 │ │ 34 ┆ 22 │ │ 35 ┆ 39 │ │ 36 ┆ 32 │ │ 37 ┆ 32 │ │ 38 ┆ 33 │ │ 39 ┆ 37 │ │ 40 ┆ 34 │ │ 41 ┆ 24 │ │ 42 ┆ 22 │ │ 43 ┆ 17 │ │ 44 ┆ 18 │ │ 45 ┆ 13 │ │ 46 ┆ 9 │ │ 47 ┆ 18 │ │ 48 ┆ 15 │ │ 49 ┆ 17 │ │ 50 ┆ 12 │ │ 51 ┆ 15 │ │ 52 ┆ 10 │ │ 53 ┆ 11 │ │ 54 ┆ 6 │ │ 55 ┆ 9 │ │ 56 ┆ 7 │ │ 57 ┆ 11 │ │ 58 ┆ 11 │ │ 59 ┆ 9 │ │ 60 ┆ 13 │ │ 61 ┆ 14 │ │ 62 ┆ 7 │ │ 63 ┆ 5 │ │ 64 ┆ 3 │ │ 65 ┆ 6 │ │ 66 ┆ 6 │ │ 67 ┆ 5 │ │ 68 ┆ 11 │ │ 69 ┆ 7 │ │ 70 ┆ 4 │ │ 71 ┆ 2 │ │ 72 ┆ 4 │ │ 73 ┆ 3 │ │ 74 ┆ 1 │ I'm training the ensemble models arima, ets, theta and imapa on series with 32 data points and up since it;s less noisy # Filter the lengths DataFrame for lengths greater than 31 lengths_filtered = lengths.filter(pl.col('length') > 31) # y_soldto filtered with only values greater than 31 in length y_cl4_filtered = y_cl4.join( lengths_filtered.select(pl.col('unique_id')), on='unique_id', how='semi' ) # Sort by 'WeekDate' y_cl4_filtered = y_cl4_filtered.sort("ds") print(y_cl4_filtered) but fit the dataset to do 24 months forecast needs at least right now 9 data points, 1 ┆ 1942 │ │ 2 ┆ 357 │ │ 3 ┆ 157 │ │ 4 ┆ 107 │ │ 5 ┆ 74 │ │ 6 ┆ 40 │ │ 7 ┆ 48 │ │ 8 ┆ 37 │ you could see that there's quite a lot of series that needed to get to 9 data points threshold to fit the models for forecast, I"m thinking maybe since sries are made up of 4 columns MaterialID which is SKU, salesorg sales organization, distrchan distribution channel and cl4 which is retailer, ie walmart target, would it make sense to try to see if the series with only 8 data points or less has some similar series with at least 9 data points and maybe either backfill to forward fill with the mean of the similar series for that exact same time period? What I mean is that for example the series with 1 data point maybe has 1 week June 10 2022 and it has 4 other similar series, and similar here I mean has the the same materialID, salesorg, distrchan but different cl4 so same product but sold to walmart or target or kroger, these 4 similar series if they have data from june 17 2022 to another 8 weeks forward, we can take their average and forward fill these values to the series with only 1 data point and then do 24 months forecast? would this work?
db5969d2ca842dc01b02f122974b1608
{ "intermediate": 0.28025320172309875, "beginner": 0.48103129863739014, "expert": 0.2387155294418335 }
40,907
How to fix: 1 of 1 unhandled error Server Error TypeError: Cannot read properties of null (reading 'useState') This error happened while generating the page. Any console logs will be displayed in the terminal window. Source components\Transition.jsx (6:50) @ eval 4 | import ParticlesContainer from "./ParticlesContainer"; 5 | import { useGlobe } from '../components/globe/globeContext'; > 6 | const [isMobileView, setIsMobileView] = useState(false); | ^ 7 | 8 | useEffect(() => { 9 | function handleResize() in the following code: import { motion } from "framer-motion"; import React, { useState, useEffect } from "react"; import { useRouter } from "next/router"; import ParticlesContainer from "./ParticlesContainer"; import { useGlobe } from '../components/globe/globeContext'; const [isMobileView, setIsMobileView] = useState(false); useEffect(() => { function handleResize() { // Define the width breakpoint for mobile, for example 768px if (window.innerWidth < 768) { setIsMobileView(true); } else { setIsMobileView(false); } } // Call the handler right away so state gets updated with initial window size handleResize(); // Set up event listener window.addEventListener('resize', handleResize); // Remove event listener on cleanup return () => window.removeEventListener('resize', handleResize); }, []); const Transition = () => { const [isLoaded, setIsLoaded] = useState(false); const router = useRouter(); const { globeReady } = useGlobe(); let transitionDelay; const baseDelay = router.pathname === '/' ? 0.2 : 0.2; const transitionVariants = { initial: { x: "100%", width: "100%", }, animate: { x: "0%", width: "0%", }, exit: { x: ["0%", "100%"], width: ["0%", "100%"], }, }; useEffect(() => { // If we're on the homepage and globe is ready, set loaded to true if (router.pathname === '/' && globeReady) { setIsLoaded(true); } else if(router.pathname!== '/') { setIsLoaded(true); } }, [globeReady, router.pathname]); if (router.pathname === '/' && !globeReady) { transitionDelay = globeReady ? baseDelay : Infinity; } else if (router.pathname !== '/' && !globeReady) { transitionDelay = baseDelay; } return ( <> {!isLoaded && ( <motion.div role="status" className="fixed top-0 bottom-0 right-full w-screen h-screen z-30 bg-gradient-to-tl from-violet-900 to-black-900" variants={transitionVariants} initial="initial" animate="animate" exit="exit" transition={{ delay: transitionDelay, duration: 0.6, ease: "easeInOut" }} aria-hidden="true" > <motion.img src="/logo.svg" alt="Descriptive text" style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: '500px', height: '500px' }} /> <motion.img src="/hand.gif" alt="Descriptive text" style={{ position: 'absolute', top: '70%', left: '50%', transform: 'translate(-50%, -50%)', width: '500px', height: '500px' }} /> <motion.div className="pt-5 text-center sm:px-6 lg:px-8 font-bold" style={{ position: 'absolute', textAlign: 'center', top: '100%', left: '50%', transform: 'translate(-50%, -50%)', width: '500px', height: '500px', fontSize: '1.2rem', }}> loading ... </motion.div> {!isMobileView && ( <ParticlesContainer /> )} </motion.div> )} <motion.div role="status" className="fixed top-0 bottom-0 right-full w-screen h-screen z-20 bg-gradient-to-tl from-violet-900 to-zinc-800" variants={transitionVariants} initial="initial" animate="animate" exit="exit" transition={{ delay: 0.4, duration: 0.6, ease: "easeInOut" }} aria-hidden /> <motion.div role="status" className="fixed top-0 bottom-0 right-full w-screen h-screen z-10 bg-gradient-to-tl from-violet-900 to-blue-600" variants={transitionVariants} initial="initial" animate="animate" exit="exit" transition={{ delay: 0.6, duration: 0.6, ease: "easeInOut" }} aria-hidden /> </> ); }; export default Transition;
c8d45c436e79a208cdd1ebd42dc825bf
{ "intermediate": 0.40935400128364563, "beginner": 0.46569597721099854, "expert": 0.12495003640651703 }
40,908
Write the TOC for a book of BBC BASIC programs that generate poems.. Also provide a sample (working) limerick generator...
c92f0789b664ff70e66cd905a31314be
{ "intermediate": 0.3809419274330139, "beginner": 0.3514581024646759, "expert": 0.2675999701023102 }
40,909
Server Error TypeError: Cannot read properties of null (reading 'useEffect') This error happened while generating the page. Any console logs will be displayed in the terminal window. Source components\Transition.jsx (8:12) @ eval 6 | 7 | > 8 | useEffect(() => { | ^ 9 | function handleResize() { 10 | // Define the width breakpoint for mobile, for example 768px 11 | if (window.innerWidth < 768) { CODE:import { motion } from "framer-motion"; import React, { useState, useEffect } from "react"; import { useRouter } from "next/router"; import ParticlesContainer from "./ParticlesContainer"; import { useGlobe } from '../components/globe/globeContext'; useEffect(() => { function handleResize() { // Define the width breakpoint for mobile, for example 768px if (window.innerWidth < 768) { setIsMobileView(true); } else { setIsMobileView(false); } } // Call the handler right away so state gets updated with initial window size handleResize(); // Set up event listener window.addEventListener('resize', handleResize); // Remove event listener on cleanup return () => window.removeEventListener('resize', handleResize); }, []); const Transition = () => { const [isMobileView, setIsMobileView] = useState(false); const [isLoaded, setIsLoaded] = useState(false); const router = useRouter(); const { globeReady } = useGlobe(); let transitionDelay; const baseDelay = router.pathname === '/' ? 0.2 : 0.2; const transitionVariants = { initial: { x: "100%", width: "100%", }, animate: { x: "0%", width: "0%", }, exit: { x: ["0%", "100%"], width: ["0%", "100%"], }, }; useEffect(() => { function handleResize() { // Safeguarding window access if (typeof window !== 'undefined') { if (window.innerWidth < 768) { setIsMobileView(true); } else { setIsMobileView(false); } } } // Since we're using window, we safeguard the entire effect if (typeof window !== 'undefined') { handleResize(); window.addEventListener('resize', handleResize); } // Cleanup return () => { if (typeof window !== 'undefined') { window.removeEventListener('resize', handleResize); } }; }, []); useEffect(() => { // If we're on the homepage and globe is ready, set loaded to true if (router.pathname === '/' && globeReady) { setIsLoaded(true); } else if(router.pathname!== '/') { setIsLoaded(true); } }, [globeReady, router.pathname]); if (router.pathname === '/' && !globeReady) { transitionDelay = globeReady ? baseDelay : Infinity; } else if (router.pathname !== '/' && !globeReady) { transitionDelay = baseDelay; } return ( <> {!isLoaded && ( <motion.div role="status" className="fixed top-0 bottom-0 right-full w-screen h-screen z-30 bg-gradient-to-tl from-violet-900 to-black-900" variants={transitionVariants} initial="initial" animate="animate" exit="exit" transition={{ delay: transitionDelay, duration: 0.6, ease: "easeInOut" }} aria-hidden="true" > <motion.img src="/logo.svg" alt="Descriptive text" style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: '500px', height: '500px' }} /> <motion.img src="/hand.gif" alt="Descriptive text" style={{ position: 'absolute', top: '70%', left: '50%', transform: 'translate(-50%, -50%)', width: '500px', height: '500px' }} /> <motion.div className="pt-5 text-center sm:px-6 lg:px-8 font-bold" style={{ position: 'absolute', textAlign: 'center', top: '100%', left: '50%', transform: 'translate(-50%, -50%)', width: '500px', height: '500px', fontSize: '1.2rem', }}> loading ... </motion.div> {!isMobileView && ( <ParticlesContainer /> )} </motion.div> )} <motion.div role="status" className="fixed top-0 bottom-0 right-full w-screen h-screen z-20 bg-gradient-to-tl from-violet-900 to-zinc-800" variants={transitionVariants} initial="initial" animate="animate" exit="exit" transition={{ delay: 0.4, duration: 0.6, ease: "easeInOut" }} aria-hidden /> <motion.div role="status" className="fixed top-0 bottom-0 right-full w-screen h-screen z-10 bg-gradient-to-tl from-violet-900 to-blue-600" variants={transitionVariants} initial="initial" animate="animate" exit="exit" transition={{ delay: 0.6, duration: 0.6, ease: "easeInOut" }} aria-hidden /> </> ); }; export default Transition;
22a8dfb3d26c4f61ed7342b94b6e616d
{ "intermediate": 0.30586978793144226, "beginner": 0.46199846267700195, "expert": 0.2321317046880722 }
40,910
make me a minecraft command to get a nice diamond pickaxe with silk touch and speed
5d8e89c915f200b1e6f5a568ab24819a
{ "intermediate": 0.32532167434692383, "beginner": 0.3098579943180084, "expert": 0.3648203909397125 }
40,911
some info about my dataset # Convert 'WeekDate' to datetime format dataset_newitem = dataset_newitem.with_columns( pl.col("WeekDate").str.strptime(pl.Datetime, "%Y-%m-%d") ) # Group by ‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, 'CL4' and 'WeekDate', then sum 'OrderQuantity' y_cl4 = dataset_newitem.groupby(['MaterialID', 'SalesOrg', 'DistrChan', 'CL4', 'WeekDate']).agg( pl.sum("OrderQuantity").alias("OrderQuantity") ) # Sort by 'WeekDate' y_cl4 = y_cl4.sort("WeekDate") # Concatenate ‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, ‘CL4’ to a new column ‘unique_id’ y_cl4 = y_cl4.with_columns( pl.concat_str([pl.col('MaterialID'), pl.col('SalesOrg'), pl.col('DistrChan'), pl.col('CL4')], separator='_').alias('unique_id') ) # Drop the original columns y_cl4 = y_cl4.drop(['MaterialID', 'SalesOrg', 'DistrChan', 'CL4']) # Renaming columns to 'ds' and 'y' to meet the input requirements of the StatsForecast library y_cl4 = y_cl4.rename({'WeekDate': 'ds', 'OrderQuantity': 'y'}) y_cl4.head() ds y unique_id datetime[μs] f64 str 2022-06-27 00:00:00 12.0 "12499186_US01_… 2022-06-27 00:00:00 128.0 "12506328_US01_… 2022-06-27 00:00:00 32.0 "12506326_US01_… 2022-06-27 00:00:00 96.0 "12520808_US01_… 2022-06-27 00:00:00 252.0 "12409760_US01_… 4275 series ranging from 1 week to 74 weeks, weekly data length ┆ count │ │ --- ┆ --- │ │ u32 ┆ u32 │ ╞════════╪═══════╡ │ 1 ┆ 1942 │ │ 2 ┆ 357 │ │ 3 ┆ 157 │ │ 4 ┆ 107 │ │ 5 ┆ 74 │ │ 6 ┆ 40 │ │ 7 ┆ 48 │ │ 8 ┆ 37 │ │ 9 ┆ 39 │ │ 10 ┆ 47 │ │ 11 ┆ 54 │ │ 12 ┆ 36 │ │ 13 ┆ 35 │ │ 14 ┆ 43 │ │ 15 ┆ 47 │ │ 16 ┆ 45 │ │ 17 ┆ 36 │ │ 18 ┆ 37 │ │ 19 ┆ 51 │ │ 20 ┆ 35 │ │ 21 ┆ 41 │ │ 22 ┆ 29 │ │ 23 ┆ 26 │ │ 24 ┆ 33 │ │ 25 ┆ 35 │ │ 26 ┆ 41 │ │ 27 ┆ 39 │ │ 28 ┆ 34 │ │ 29 ┆ 37 │ │ 30 ┆ 31 │ │ 31 ┆ 32 │ │ 32 ┆ 26 │ │ 33 ┆ 30 │ │ 34 ┆ 22 │ │ 35 ┆ 39 │ │ 36 ┆ 32 │ │ 37 ┆ 32 │ │ 38 ┆ 33 │ │ 39 ┆ 37 │ │ 40 ┆ 34 │ │ 41 ┆ 24 │ │ 42 ┆ 22 │ │ 43 ┆ 17 │ │ 44 ┆ 18 │ │ 45 ┆ 13 │ │ 46 ┆ 9 │ │ 47 ┆ 18 │ │ 48 ┆ 15 │ │ 49 ┆ 17 │ │ 50 ┆ 12 │ │ 51 ┆ 15 │ │ 52 ┆ 10 │ │ 53 ┆ 11 │ │ 54 ┆ 6 │ │ 55 ┆ 9 │ │ 56 ┆ 7 │ │ 57 ┆ 11 │ │ 58 ┆ 11 │ │ 59 ┆ 9 │ │ 60 ┆ 13 │ │ 61 ┆ 14 │ │ 62 ┆ 7 │ │ 63 ┆ 5 │ │ 64 ┆ 3 │ │ 65 ┆ 6 │ │ 66 ┆ 6 │ │ 67 ┆ 5 │ │ 68 ┆ 11 │ │ 69 ┆ 7 │ │ 70 ┆ 4 │ │ 71 ┆ 2 │ │ 72 ┆ 4 │ │ 73 ┆ 3 │ │ 74 ┆ 1 │ I'm training the ensemble models arima, ets, theta and imapa on series with 32 data points and up since it;s less noisy # Filter the lengths DataFrame for lengths greater than 31 lengths_filtered = lengths.filter(pl.col('length') > 31) # y_soldto filtered with only values greater than 31 in length y_cl4_filtered = y_cl4.join( lengths_filtered.select(pl.col('unique_id')), on='unique_id', how='semi' ) # Sort by 'WeekDate' y_cl4_filtered = y_cl4_filtered.sort("ds") print(y_cl4_filtered) but fit the dataset to do 24 months forecast needs at least right now 9 data points, 1 ┆ 1942 │ │ 2 ┆ 357 │ │ 3 ┆ 157 │ │ 4 ┆ 107 │ │ 5 ┆ 74 │ │ 6 ┆ 40 │ │ 7 ┆ 48 │ │ 8 ┆ 37 │ you could see that there's quite a lot of series that needed to get to 9 data points threshold to fit the models for forecast, I"m thinking maybe since sries are made up of 4 columns MaterialID which is SKU, salesorg sales organization, distrchan distribution channel and cl4 which is retailer, ie walmart target, would it make sense to try to see if the series with only 8 data points or less has some similar series with at least 9 data points and maybe either backfill to forward fill with the mean of the similar series for that exact same time period? What I mean is that for example the series with 1 data point maybe has 1 week June 10 2022 and it has 4 other similar series, and similar here I mean has the the same materialID, salesorg, distrchan but different cl4 so same product but sold to walmart or target or kroger, these 4 similar series if they have data from june 17 2022 to another 8 weeks forward, we can take their average and forward fill these values to the series with only 1 data point and then do 24 months forecast? would this work?
b57b9ac4a456a5298bedb1ba0dfbf56a
{ "intermediate": 0.28025320172309875, "beginner": 0.48103129863739014, "expert": 0.2387155294418335 }
40,912
Briefly summarize the main idea of each paragraph in the space below each paragraph. There is a time in every man's education when he arrives at the conviction that envy is ignorance; that imitation is suicide; that he must take himself for better, for worse, as his portion; that though the wide universe is full of good, no kernel of nourishing corn can come to him but through his toil bestowed on that plot of ground which is given to him to till. The power which resides in him is new in nature, and none but he knows what that is which he can do, nor does he know until he has tried… SUMMARIZE HERE: Trust thyself: every heart vibrates to that iron string. Accept the place the divine providence has found for you, the society of your contemporaries, the connection of events. Great men have always done so, and confided themselves childlike to the genius of their age, betraying their perception that the absolutely trustworthy was seated at their heart, working through their hands, predominating in all their being. And we are now men, and must accept in the highest mind the same transcendent destiny… SUMMARIZE HERE: Society everywhere is in conspiracy against the manhood of every one of its members. Society is a joint-stock company, in which the members agree, for the better securing of his bread to each shareholder, to surrender the liberty and culture of the eater. The virtue in most request is conformity. Self-reliance is its aversion. It loves not realities and creators, but names and customs. SUMMARIZE HERE: Whoso would be a man must be a nonconformist. He who would gather immortal palms must not be hindered by the name of goodness, but must explore if it be goodness. Nothing is at last sacred but the integrity of your own mind…No law can be sacred to me but that of my nature. Good and bad are but names very readily transferable to that or this; the only right is what is after my constitution, the only wrong what is against it… SUMMARIZE HERE: What I must do is all that concerns me, not what the people think. This rule, equally arduous in actual and in intellectual life, may serve for the whole distinction between greatness and meanness. It is the harder, because you will always find those who think they know what is your duty better than you know it. It is easy in the world to live after the world's opinion; it is easy in solitude to live after our own; but the great man is he who in the midst of the crowd keeps with perfect sweetness the independence of solitude…. SUMMARIZE HERE: A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines. With consistency a great soul has simply nothing to do. He may as well concern himself with his shadow on the wall. Speak what you think now in hard words, and to-morrow speak what to-morrow thinks in hard words again, though it contradict every thing you said to-day. — 'Ah, so you shall be sure to be misunderstood.' — Is it so bad, then, to be misunderstood? Pythagoras was misunderstood, and Socrates, and Jesus, and Luther, and Copernicus, and Galileo, and Newton, and every pure and wise spirit that ever took flesh. To be great is to be misunderstood…. SUMMARIZE HERE: So use all that is called Fortune. Most men gamble with her, and gain all, and lose all, as her wheel rolls. But do thou leave as unlawful these winnings, and deal with Cause and Effect, the chancellors of God. In the Will work and acquire, and thou hast chained the wheel of Chance, and shalt sit hereafter out of fear from her rotations. A political victory, a rise of rents, the recovery of your sick, or the return of your absent friend, or some other favorable event, raises your spirits, and you think good days are preparing for you. Do not believe it. Nothing can bring you peace but yourself. Nothing can bring you peace but the triumph of principles.
7876ab29ea7ad6397e5300b343b50be1
{ "intermediate": 0.41343390941619873, "beginner": 0.4697301685810089, "expert": 0.11683594435453415 }
40,913
-- Функция для получения здоровья игрока в процентах function getPlayerHealthPercent(player) local health = getElementHealth(player) local maxHealth = getElementData(player, "maxHealth") or 100 return math.floor((health / maxHealth) * 100) end -- Функция для получения цвета здоровья игрока в зависимости от процентов function getPlayerHealthColor(percent) local r, g, b = 255, 255, 255 if percent > 50 then -- Зеленый цвет r = (100 - percent) * 5.1 g = 255 b = 0 elseif percent > 25 then -- Желтый цвет r = 255 g = percent * 10.2 b = 0 else -- Красный цвет r = 255 g = 0 b = 0 end return r, g, b end -- Функция для отрисовки здоровья и ников игроков над головой function drawPlayerHealthAndName() -- Получаем список всех игроков на экране local players = getElementsByType("player", root, true) -- Получаем размеры экрана local screenWidth, screenHeight = guiGetScreenSize() -- Цикл по всем игрокам for _, player in ipairs(players) do -- Проверяем, что игрок не локальный и не мертв if player ~= localPlayer and not isPedDead(player) then -- Получаем позицию игрока в мире local x, y, z = getElementPosition(player) -- Преобразуем позицию в экранные координаты local screenX, screenY = getScreenFromWorldPosition(x, y, z + 0.5) -- Проверяем, что экранные координаты существуют if screenX and screenY then -- Получаем ник игрока local name = getPlayerName(player) -- Получаем здоровье игрока в процентах local health = getPlayerHealthPercent(player) -- Получаем цвет здоровья игрока local r, g, b = getPlayerHealthColor(health) -- Отрисовываем ник игрока белым цветом dxDrawText(name, screenX + 1, screenY + 1, screenX + 1, screenY + 1, tocolor(0, 0, 0, 255), 1.2, "default", "center", "center") dxDrawText(name, screenX, screenY, screenX, screenY, tocolor(255, 255, 255, 255), 1.2, "default", "center", "center") -- Отрисовываем здоровье игрока цветным прямоугольником dxDrawRectangle(screenX - 25, screenY + 15, 50, 5, tocolor(0, 0, 0, 200)) dxDrawRectangle(screenX - 24, screenY + 16, 48 * (health / 100), 3, tocolor(r, g, b, 255)) end end end end -- Добавляем обработчик события для отрисовки здоровья и ников игроков над головой addEventHandler("onClientRender", root, drawPlayerHealthAndName) Раздели этот скрипт на сторону сервера и клиента, чтобы ники и здоровье игрока отрисовывалось игрокам друг-другу
5e6571299f75b2c942560c296fd2a569
{ "intermediate": 0.2589171528816223, "beginner": 0.5456615686416626, "expert": 0.1954212784767151 }
40,914
ETL in Batch system (Related to Meta messenger app quarterly results) Question 1: This is a product sense question related to DAU, MAU. The growth rate of DAU was drop 8% and MAU was drop 5%. Analyze the story behind the data. Try to solve this question with focus on the dimension of the data.
2abeef5711a08a4aad5a410c7d6f352e
{ "intermediate": 0.4188617765903473, "beginner": 0.3603488504886627, "expert": 0.22078937292099 }
40,915
which GPT version are you stand for?
c2ac6a0954aad8c6ac012a72a95a7640
{ "intermediate": 0.36183983087539673, "beginner": 0.2826511263847351, "expert": 0.35550907254219055 }
40,916
talk me through the process of scraping data from reddit using python
fcfa2e24ceda64890b39c9b2d8556a5d
{ "intermediate": 0.6360660791397095, "beginner": 0.09015413373708725, "expert": 0.27377983927726746 }
40,917
I am making a C++ SDL based game engine, so far I have done several key parts like the ResourceManager, InputManager, ScreenManager, and currenly finishing the Renderer, and its related classes Surface, Texture, Rect, Point, Line, etc. What I am doing is wrapping the original SDL methods while also adding my own methods like for example the Circle class. I need help with finishing the Renderer class. I am at this step, doing the Viewport and the camera. I have done the SetViewport method which receives a Rect, but now I am torn apart into adding a Camera class since I already have a Transform struct, with same methods. The original plan was this: class Camera { public: FPoint position; float zoom; float rotation; Camera() : position(0, 0), zoom(1), rotation(0) {} void SetPosition(float x, float y) { position.x = x; position.y = y; } void SetZoom(float zoomLevel) { zoom = zoomLevel; } void SetRotation(float rotationDegrees) { rotation = rotationDegrees; } // Other camera methods… }; class Renderer { public: void SetCamera(const Camera& camera) { // Calculate the transformation matrix based on camera position, zoom, and rotation, if necessary // To apply rotation you would also adjust the rendering calls accordingly } But now I ended up having a Transform struct: struct Transform { enum class Flip { None, Horizontal, Vertical, Both }; FPoint scale; float rotation; Transform::Flip flip; Transform(); }; Should I add the Camera class, considering I am currently doing the Renderer and Camera class is an high level compared to the Renderer, or I should just add a Transform struct to an overload of SetViewport like this: void SetViewport(const Rect& viewport) const; // original void SetViewport(const Transform& transform[or camera?]) const; // overload, similar to SetCamera
fde98c75a9d884b41215e8377a85c76a
{ "intermediate": 0.6542629599571228, "beginner": 0.2692432403564453, "expert": 0.07649379968643188 }
40,918
Convert to .bat windows
36badfac0481927bab324a563c02bc44
{ "intermediate": 0.3255777359008789, "beginner": 0.33293357491493225, "expert": 0.34148865938186646 }
40,919
Convert this to .bat windows. Only need code.
8b5e61a8107405bf5d2c343670995fb1
{ "intermediate": 0.23769833147525787, "beginner": 0.39901790022850037, "expert": 0.3632836937904358 }
40,920
User normally the number of data points is 1M. I want to make the plot application. i want to display the data as the line and scatter on the plot and interact the points. For example, find the peak and valley, calculate the difference between peak and valley where i selected using the area selection, hovering the data poitnt x and y value when i move the mouse cursor, etc. If i use the python, matplotlib, tkinter, how to increase the rendering and interact speed?
e6e99b90be1800b96a7f2d01a5183a8c
{ "intermediate": 0.8608073592185974, "beginner": 0.07378111034631729, "expert": 0.06541163474321365 }
40,921
You are going to pretend to be a senior software engineer at a FAANG company. Review the following code paying attention to security and performance. Provide outputs that a senior software engineer would produce regarding the code.
b2a7da2b10af60aa3b6e1f76204f71fd
{ "intermediate": 0.2683769166469574, "beginner": 0.2732982039451599, "expert": 0.4583248794078827 }
40,922
I’d like to have a dax measure that gets the max value for an order (since there can be multiple items in one order) but sums this. Can you tell me how to do this?
1e5a7562f24be9e37490e5827d5fe63f
{ "intermediate": 0.39636650681495667, "beginner": 0.2031107097864151, "expert": 0.40052279829978943 }
40,923
hOW to convert 45.67890 in 45.7 in google sheets
8f2b162d6b63e49b3a1b34a15dc1cc42
{ "intermediate": 0.29952874779701233, "beginner": 0.35175880789756775, "expert": 0.3487125039100647 }
40,924
Hi
dea5a60930cd5c8b0cb2dc1cd87b711c
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
40,925
Whats the best way to store location over long term in Xcode / Swift
76767b4c525c79717df5b771fa7fca03
{ "intermediate": 0.38151347637176514, "beginner": 0.14351800084114075, "expert": 0.4749685525894165 }
40,926
Whats the best way to store location over long term in Xcode / Swift? I want the ability to store timestamps and locations
76dd270b7a7dd007c90b3e76c10aebad
{ "intermediate": 0.5528116822242737, "beginner": 0.1602003574371338, "expert": 0.28698796033859253 }
40,927
How would I use json encoder and codable to encode a CLLOcation
9193be513fa82207affbcda731fc3d01
{ "intermediate": 0.46997731924057007, "beginner": 0.22915123403072357, "expert": 0.3008714020252228 }
40,928
why aint work let time = [[NSDate date] timeIntervalSince1970];
78b61845608e6ceddc653f900ca1a835
{ "intermediate": 0.2766004502773285, "beginner": 0.543287456035614, "expert": 0.1801120489835739 }
40,929
why aint work let time = [[NSDate date] timeIntervalSince1970];"
a4d4335187d6fd6ff775bd5a332c4c68
{ "intermediate": 0.24610884487628937, "beginner": 0.5824358463287354, "expert": 0.1714552789926529 }
40,930
Where to call send function, before connect or after it in case of sending data with TCP_FASTOPEN option for client on Linux?
4a5dd8fa94ea3548125711cb0b683010
{ "intermediate": 0.5885124206542969, "beginner": 0.21002644300460815, "expert": 0.20146121084690094 }
40,931
windows bat script for shutdown pc after one hour of inactivity
ff5d2915c7c4d34e22fa724471144c89
{ "intermediate": 0.32619741559028625, "beginner": 0.2880561947822571, "expert": 0.38574641942977905 }
40,932
windows bat script for shutdown pc after one hour of inactivity
a64eaa1e256b7bd99748de7dd292392c
{ "intermediate": 0.32619741559028625, "beginner": 0.2880561947822571, "expert": 0.38574641942977905 }
40,933
Write a program in PowerShell to connect to oracle using instant client and a local tnsnames.ora file
f14e40d0e9363da7f389ad6303a86ea8
{ "intermediate": 0.3139227032661438, "beginner": 0.18926049768924713, "expert": 0.4968167543411255 }
40,934
Write a powershell program to connect to oracle using instant client and local tnsnames.ora file
1ba840b0ff6ba7b8ff23434cedd918ad
{ "intermediate": 0.3925071060657501, "beginner": 0.20203858613967896, "expert": 0.40545427799224854 }
40,935
What is wrong with this table html code? {% extends "layout.html" %} {% block title %} Welcome! {% endblock %} {% block main %} <main> <table class="table table-striped"> <thread> <tr> <th class="text-start">Symbol </th> <th class="text-start">Shares </th> <th class="text-start">Price </th> <th class="text-start">TOTAL </th> </tr> </table> </thread> <tbody> <tr> <td class="text-start">NFLX</td> <td class="text-end">10</td> <td class="text-end">10</td> <td class="text-end">10</td> </tr> </tbody> <tfoot> <tr> <td class="border-0 fw-bold text-end" colspan="3">Cash</td> <td class="border-0 text-end">$31289</td> </tr> <tr> <td class="border-0 fw-bold text-end" colspan="3">TOTAL</td> <td class="border-0 w-bold text-end">$10,000.00</td> </tr> </tfoot> </table> </main> {% endblock %}
a4dee19a33af7606071784b91bce9e53
{ "intermediate": 0.17123983800411224, "beginner": 0.7301235198974609, "expert": 0.0986366868019104 }
40,936
What is wrong with this table html code? {% extends “layout.html” %} {% block title %} Welcome! {% endblock %} {% block main %} <main> <table class=“table table-striped”> <thread> <tr> <th class=“text-start”>Symbol </th> <th class=“text-start”>Shares </th> <th class=“text-start”>Price </th> <th class=“text-start”>TOTAL </th> </tr> </table> </thread> <tbody> <tr> <td class=“text-start”>NFLX</td> <td class=“text-end”>10</td> <td class=“text-end”>10</td> <td class=“text-end”>10</td> </tr> </tbody> <tfoot> <tr> <td class=“border-0 fw-bold text-end” colspan=“3”>Cash</td> <td class=“border-0 text-end”>$31289</td> </tr> <tr> <td class=“border-0 fw-bold text-end” colspan=“3”>TOTAL</td> <td class=“border-0 w-bold text-end”>$10,000.00</td> </tr> </tfoot> </table> </main> {% endblock %}
6eaddb632af238207f1bb3cd7acdb1a0
{ "intermediate": 0.264952152967453, "beginner": 0.599107563495636, "expert": 0.1359403431415558 }
40,937
What is wrong with this table html code? {% extends “layout.html” %} {% block title %} Welcome! {% endblock %} {% block main %} <main> <table class=“table table-striped”> <thread> <tr> <th class=“text-start”>Symbol </th> <th class=“text-start”>Shares </th> <th class=“text-start”>Price </th> <th class=“text-start”>TOTAL </th> </tr> </table> </thread> <tbody> <tr> <td class=“text-start”>NFLX</td> <td class=“text-end”>10</td> <td class=“text-end”>10</td> <td class=“text-end”>10</td> </tr> </tbody> <tfoot> <tr> <td class=“border-0 fw-bold text-end” colspan=“3”>Cash</td> <td class=“border-0 text-end”>$31289</td> </tr> <tr> <td class=“border-0 fw-bold text-end” colspan=“3”>TOTAL</td> <td class=“border-0 w-bold text-end”>$10,000.00</td> </tr> </tfoot> </table> </main> {% endblock %}
a0fbc84293831e49b7170283629043f4
{ "intermediate": 0.264952152967453, "beginner": 0.599107563495636, "expert": 0.1359403431415558 }
40,938
Illustrate the operation of Heapsort on the input array A = <5, 13, 2, 25, 7, 17, 20, 8, 4>. Draw the heap just after Build-Max-Heap was executed. Then draw a new heap after another (the next) element has been sorted; the last heap you draw has a single element.
986cc58db73e48b081cc4f464f52d96d
{ "intermediate": 0.38786810636520386, "beginner": 0.17845574021339417, "expert": 0.4336760938167572 }
40,939
Imagine a creative brainstorm and with these ideas you are inspired to write a list of different syntaxes with visual descriptions of a "prompt generator" suitable for application in some AI that generates images and that in its contexts carries the indication of creating a humorous and extended message. cartoon character next to a tortilla dough mill, presenting himself as the dedicated kneader, amid the floury atmosphere of a cozy scene inside a tortilla factory
9701d21a2afd28643623eaec4518a7d3
{ "intermediate": 0.09252732992172241, "beginner": 0.355164110660553, "expert": 0.5523084998130798 }
40,940
write a program using powershell to connect to oracle using Oracle.ManagedDataAccess.dll and local wallet
38155d53d4c412f06e3a0c0d56a7846b
{ "intermediate": 0.5286876559257507, "beginner": 0.17520327866077423, "expert": 0.29610905051231384 }
40,941
write a program using powershell to connect to oracle using Oracle.ManagedDataAccess.dll and local wallet
cd5770e021e36bd340c5597a95296e51
{ "intermediate": 0.5286876559257507, "beginner": 0.17520327866077423, "expert": 0.29610905051231384 }
40,942
write a program using powershell to connect to oracle using Oracle.ManagedDataAccess.dll and local wallet
6db2116c8f3c196339081bd54c2e7637
{ "intermediate": 0.5286876559257507, "beginner": 0.17520327866077423, "expert": 0.29610905051231384 }
40,943
I'm trying to implement a stock trading webapp. For some reason my current stocks overview implementation doesn't work. Please fix it. Here's the flask code: @app.route("/") @login_required def index(): if request.method == "GET": cash = db.execute("SELECT cash FROM users;") symbol = db.execute("SELECT symbol FROM purchases;") price= db.execute("SELECT price FROM purchases;") return render_template("index.html") return apology("TODO") And here the html: {% extends "layout.html" %} {% block title %} Index {% endblock %} {% block main %} <main class="container py-5 text-center"> <table class="table table-striped"> <thead> <tr> <th class="text-start">Symbol </th> <th class="text-start">Shares </th> <th class="text-start">Price </th> <th class="text-start">TOTAL </th> </tr> </thead> <tbody> {% for purchase in purchases %} <tr> <td class="text-start">{{ purchases.symbol }}</td> <td class="text-end">{{ purchases.shares }}</td> <td class="text-end">{{ purchases.price }}</td> <td class="text-end">{{ purchases.total }}</td> </tr> {% endfor %} </tbody> <tfoot> <tr> <td class="border-0 fw-bold text-end" colspan="3">Cash</td> <td class="border-0 text-end"></td> </tr> <tr> <td class="border-0 fw-bold text-end" colspan="3">TOTAL</td> <td class="border-0 w-bold text-end">{{ users.cash }}</td> </tr> </tfoot> </table> </main> {% endblock %}
35f086e1d6d97203acbabe113f5e24a0
{ "intermediate": 0.27655771374702454, "beginner": 0.5472205281257629, "expert": 0.17622174322605133 }
40,944
I’m trying to implement a stock trading webapp. For some reason my current stocks overview implementation doesn’t work. Please fix it. Here’s the flask code: @app.route(“/”) @login_required def index(): if request.method == “GET”: cash = db.execute(“SELECT cash FROM users;”) symbol = db.execute(“SELECT symbol FROM purchases;”) price= db.execute(“SELECT price FROM purchases;”) return render_template(“index.html”) return apology(“TODO”) And here the html: {% extends “layout.html” %} {% block title %} Index {% endblock %} {% block main %} <main class=“container py-5 text-center”> <table class=“table table-striped”> <thead> <tr> <th class=“text-start”>Symbol </th> <th class=“text-start”>Shares </th> <th class=“text-start”>Price </th> <th class=“text-start”>TOTAL </th> </tr> </thead> <tbody> {% for purchase in purchases %} <tr> <td class=“text-start”>{{ purchases.symbol }}</td> <td class=“text-end”>{{ purchases.shares }}</td> <td class=“text-end”>{{ purchases.price }}</td> <td class=“text-end”>{{ purchases.total }}</td> </tr> {% endfor %} </tbody> <tfoot> <tr> <td class=“border-0 fw-bold text-end” colspan=“3”>Cash</td> <td class=“border-0 text-end”></td> </tr> <tr> <td class=“border-0 fw-bold text-end” colspan=“3”>TOTAL</td> <td class=“border-0 w-bold text-end”>{{ users.cash }}</td> </tr> </tfoot> </table> </main> {% endblock %}
7b6bcc341ed13bc76ce80aa2cab70f7e
{ "intermediate": 0.43783682584762573, "beginner": 0.3114619851112366, "expert": 0.2507012188434601 }
40,945
I’m trying to implement a stock trading webapp. For some reason my current stocks overview implementation doesn’t work. Please fix it. Here’s the flask code: import os from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session from flask_session import Session from werkzeug.security import check_password_hash, generate_password_hash from helpers import apology, login_required, lookup, usd # Configure application app = Flask(__name__) # Custom filter app.jinja_env.filters["usd"] = usd # Configure session to use filesystem (instead of signed cookies) app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app) # Configure CS50 Library to use SQLite database db = SQL("sqlite:///finance.db") @app.after_request def after_request(response): """Ensure responses aren't cached""" response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response @app.route("/") @login_required def index(): # Assume db.execute() returns a dict or a list of dicts if request.method == "GET": user_cash = db.execute("SELECT cash FROM users WHERE id = :id;" id=session['user_id'])[0]['cash'] purchases = db.execute(""" SELECT symbol, SUM(shares) as shares, AVG(price) as price FROM purchases WHERE user_id = :id GROUP BY symbol HAVING SUM(shares) > 0; """, id=session['user_id']) # Calculate totals for each purchase for purchase in purchases: purchase['total'] = purchase['shares'] * purchase['price'] # Calculate the total value of stocks plus cash total_assets = sum(purchase['total'] for purchase in purchases) + user_cash return render_template("index.html", cash=user_cash, purchases=purchases, total_assets=total_assets) @app.route("/buy", methods=["GET", "POST"]) @login_required def buy(): if request.method == "GET": return render_template("buy.html") elif request.method == "POST": my_symbb = request.form.get('symbolb') my_quant = request.form.get('quantity') try: my_quant = int(my_quant) if my_quant <= 0: return apology("more than 0, idiot", 400) db.execute("INSERT INTO purchases (symbol, shares, price) VALUES (:symbol, :shares, 12)", symbol=my_symbb, shares=my_quant) # Handle success or add a redirection here return render_template("success.html") # Assuming there is a success.html template except ValueError: return apology("invalid quantity", 400) except Exception as e: return apology("An error occurred: " + str(e), 400) @app.route("/history") @login_required def history(): """Show history of transactions""" return apology("TODO") @app.route("/login", methods=["GET", "POST"]) def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Query database for username rows = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username")) # Ensure username exists and password is correct if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")): return apology("invalid username and/or password", 403) # Remember which user has logged in session["user_id"] = rows[0]["id"] # Redirect user to home page return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("login.html") @app.route("/logout") def logout(): """Log user out""" # Forget any user_id session.clear() # Redirect user to login form return redirect("/") @app.route("/quote", methods=["GET", "POST"]) @login_required def quote(): """Get stock quote.""" if request.method == "GET": return render_template("quote.html") elif request.method == "POST": my_symbol = request.form.get('symbol') if not my_symbol: flash("symbol is required", "error") return redirect("/quote") stock = lookup(my_symbol) if stock: return render_template("quoted.html", stock=stock) else: flash("Could not retrive stock info", "error") return redirect("/quote") else: flash("Invalid reuqest method", "error") return redirect("/quote") @app.route("/quoted", methods=["GET", "POST"]) @login_required def quoted(): if request.method == "POST": return render_template("quoted.html", stock) if request.method == "GET": return render_template("quoted.html", stock) @app.route("/register", methods=["GET", "POST"]) def register(): # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Query database for username username = request.form.get("username") rows = db.execute("SELECT * FROM users WHERE username = :username", username=username) # :username is a named placeholder if rows: return apology("username already exists", 403) # Hash user's password hashed_password = generate_password_hash(request.form.get("password")) # Insert new user into the database db.execute("INSERT INTO users (username, hash) VALUES (:username, :hash)", username=username, hash=hashed_password) # :username and :hash are named placeholders # Redirect user to login page or some other page flash("Registered successfully, please log in.") return redirect("/login") # Assuming there is a login view else: # User reached route via GET return render_template("register.html") # Assuming there is a 'register.html' template @app.route("/sell", methods=["GET", "POST"]) @login_required def sell(): """Sell shares of stock""" return apology("TODO") Here's layout.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, width=device-width"> <!-- http://getbootstrap.com/docs/5.1/ --> <link crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" rel="stylesheet"> <script crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"></script> <!-- https://favicon.io/emoji-favicons/money-bag/ --> <link href="/static/trade.png" rel="icon"> <link href="/static/styles.css" rel="stylesheet"> <title>C$50 Finance: {% block title %}{% endblock %}</title> </head> <body> <nav class="bg-light border navbar navbar-expand-md navbar-light"> <div class="container-fluid"> <a class="navbar-brand" href="/"><span class="blue">C</span><span class="red">$</span><span class="yellow">5</span><span class="green">0</span> <span class="red">Finance</span></a> <button aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-bs-target="#navbar" data-bs-toggle="collapse" type="button"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbar"> {% if session["user_id"] %} <ul class="navbar-nav me-auto mt-2"> <li class="nav-item"><a class="nav-link" href="/quote">Quote</a></li> <li class="nav-item"><a class="nav-link" href="/buy">Buy</a></li> <li class="nav-item"><a class="nav-link" href="/sell">Sell</a></li> <li class="nav-item"><a class="nav-link" href="/history">History</a></li> </ul> <ul class="navbar-nav ms-auto mt-2"> <li class="nav-item"><a class="nav-link" href="/logout">Log Out</a></li> </ul> {% else %} <ul class="navbar-nav ms-auto mt-2"> <li class="nav-item"><a class="nav-link" href="/register">Register</a></li> <li class="nav-item"><a class="nav-link" href="/login">Log In</a></li> </ul> {% endif %} </div> </div> </nav> {% if get_flashed_messages() %} <header> <div class="alert alert-primary mb-0 text-center" role="alert"> {{ get_flashed_messages() | join(" ") }} </div> </header> {% endif %} <main class="container-fluid py-5 text-center"> {% block main %}{% endblock %} </main> <footer class="mb-5 small text-center text-muted"> Data provided by <a href="https://iexcloud.io/">IEX</a> </footer> </body> </html>
0a7affce9db2f5ff5c1275757b5c8cbe
{ "intermediate": 0.44333159923553467, "beginner": 0.3081551790237427, "expert": 0.24851323664188385 }
40,946
I’m trying to implement a stock trading webapp. For some reason my current stocks overview implementation doesn’t work. Please fix it. Here’s the flask code: import os from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session from flask_session import Session from werkzeug.security import check_password_hash, generate_password_hash from helpers import apology, login_required, lookup, usd # Configure application app = Flask(__name__) # Custom filter app.jinja_env.filters["usd"] = usd # Configure session to use filesystem (instead of signed cookies) app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app) # Configure CS50 Library to use SQLite database db = SQL("sqlite:///finance.db") @app.after_request def after_request(response): """Ensure responses aren't cached""" response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response @app.route("/") @login_required def index(): # Assume db.execute() returns a dict or a list of dicts if request.method == "GET": user_cash = db.execute("SELECT cash FROM users WHERE id = :id;" id=session['user_id'])[0]['cash'] purchases = db.execute(""" SELECT symbol, SUM(shares) as shares, AVG(price) as price FROM purchases WHERE user_id = :id GROUP BY symbol HAVING SUM(shares) > 0; """, id=session['user_id']) # Calculate totals for each purchase for purchase in purchases: purchase['total'] = purchase['shares'] * purchase['price'] # Calculate the total value of stocks plus cash total_assets = sum(purchase['total'] for purchase in purchases) + user_cash return render_template("index.html", cash=user_cash, purchases=purchases, total_assets=total_assets) @app.route("/buy", methods=["GET", "POST"]) @login_required def buy(): if request.method == "GET": return render_template("buy.html") elif request.method == "POST": my_symbb = request.form.get('symbolb') my_quant = request.form.get('quantity') try: my_quant = int(my_quant) if my_quant <= 0: return apology("more than 0, idiot", 400) db.execute("INSERT INTO purchases (symbol, shares, price) VALUES (:symbol, :shares, 12)", symbol=my_symbb, shares=my_quant) # Handle success or add a redirection here return render_template("success.html") # Assuming there is a success.html template except ValueError: return apology("invalid quantity", 400) except Exception as e: return apology("An error occurred: " + str(e), 400) @app.route("/history") @login_required def history(): """Show history of transactions""" return apology("TODO") @app.route("/login", methods=["GET", "POST"]) def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Query database for username rows = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username")) # Ensure username exists and password is correct if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")): return apology("invalid username and/or password", 403) # Remember which user has logged in session["user_id"] = rows[0]["id"] # Redirect user to home page return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("login.html") @app.route("/logout") def logout(): """Log user out""" # Forget any user_id session.clear() # Redirect user to login form return redirect("/") @app.route("/quote", methods=["GET", "POST"]) @login_required def quote(): """Get stock quote.""" if request.method == "GET": return render_template("quote.html") elif request.method == "POST": my_symbol = request.form.get('symbol') if not my_symbol: flash("symbol is required", "error") return redirect("/quote") stock = lookup(my_symbol) if stock: return render_template("quoted.html", stock=stock) else: flash("Could not retrive stock info", "error") return redirect("/quote") else: flash("Invalid reuqest method", "error") return redirect("/quote") @app.route("/quoted", methods=["GET", "POST"]) @login_required def quoted(): if request.method == "POST": return render_template("quoted.html", stock) if request.method == "GET": return render_template("quoted.html", stock) @app.route("/register", methods=["GET", "POST"]) def register(): # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Query database for username username = request.form.get("username") rows = db.execute("SELECT * FROM users WHERE username = :username", username=username) # :username is a named placeholder if rows: return apology("username already exists", 403) # Hash user's password hashed_password = generate_password_hash(request.form.get("password")) # Insert new user into the database db.execute("INSERT INTO users (username, hash) VALUES (:username, :hash)", username=username, hash=hashed_password) # :username and :hash are named placeholders # Redirect user to login page or some other page flash("Registered successfully, please log in.") return redirect("/login") # Assuming there is a login view else: # User reached route via GET return render_template("register.html") # Assuming there is a 'register.html' template @app.route("/sell", methods=["GET", "POST"]) @login_required def sell(): """Sell shares of stock""" return apology("TODO") Here's index.html: {% extends "layout.html" %} {% block title %} Welcome! {% endblock %} {% block main %} <main class="container py-5 text-center"> <table class="table table-striped"> <thead> <tr> <th class="text-start">Symbol </th> <th class="text-start">Shares </th> <th class="text-start">Price </th> <th class="text-start">TOTAL </th> </tr> </thead> <tbody> {% for purchase in purchases %} <tr> <td class="text-start">{{ purchase.symbol }}</td> <td class="text-end">{{ purchase.shares }}</td> <td class="text-end">{{ "%.2f"|format(purchase.price) }}</td> <td class="text-end">{{ purchases.total }}</td> </tr> {% endfor %} </tbody> <tfoot> <tr> <td class="border-0 fw-bold text-end" colspan="3">Cash</td> <td class="border-0 text-end"></td> </tr> <tr> <td class="border-0 fw-bold text-end" colspan="3">TOTAL</td> <td class="border-0 w-bold text-end">{{ users.cash }}</td> </tr> </tfoot> </table> </main> {% endblock %}
d0e973a00d5394a553ab12ec41c02308
{ "intermediate": 0.44333159923553467, "beginner": 0.3081551790237427, "expert": 0.24851323664188385 }
40,947
please check this code: fn main() { let start = std::time::Instant::now(); let file = "/home/alejandro/Downloads/gencode.v44.annotation.gtf"; let contents = reader(file).unwrap(); let records = parallel_parse(&contents).unwrap(); let elapsed = start.elapsed(); println!("{:?}", records); println!("Elapsed: {:?}", elapsed); } pub type ProtRecord = HashMap<String, InnerProtRecord>; #[derive(Debug, PartialEq)] pub struct InnerProtRecord { pub chr: String, pub strand: char, pub start: u32, pub end: u32, } impl Default for InnerProtRecord { fn default() -> Self { InnerProtRecord { chr: String::new(), strand: ' ', start: 0, end: 0, } } } pub fn reader<P: AsRef<Path> + Debug>(file: P) -> io::Result<String> { let mut file = File::open(file)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } pub fn parallel_parse<'a>(s: &'a str) -> Result<ProtRecord, &'static str> { let x = s .par_lines() .filter(|line| !line.starts_with("#")) .filter_map(|line| Record::parse(line).ok()) .filter(|record| record.feat == "CDS") .fold( || HashMap::new(), |mut acc: ProtRecord, record| { // acc.entry(record.chr.clone()).or_default().push(record); let k = acc.entry(record.attr.protein_id).or_default(); if !k.chr.is_empty() { k.start = k.start.min(record.start); k.end = k.end.max(record.end); } else { InnerProtRecord { chr: record.chr, strand: record.strand, start: record.start, end: record.end, }; }; acc }, ) .reduce( || HashMap::new(), |mut acc, map| { for (k, v) in map { let x = acc.entry(k).or_default(); if !x.chr.is_empty() { x.start = x.start.min(v.start); x.end = x.end.max(v.end); } else { *x = v; } } acc }, ); Ok(x) } why am I getting this output?: {"ENSP00000503594.1": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000294168.3": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000502566.1": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000421719.1": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000359732.3": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000450699.1": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000490285.1": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000486606.1": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000492123.1": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000392760.2": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000475284.1": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000420359.2": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000426304.1": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000489204.1": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000495022.2": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000383896.1": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 }, "ENSP00000380734.2": InnerProtRecord { chr: "", strand: ' ', start: 0, end: 0 like if each entry does not have information
632680884860cc1c6b185dd118e0a211
{ "intermediate": 0.37964555621147156, "beginner": 0.510019838809967, "expert": 0.110334612429142 }
40,948
I need you to check and verify the below reward calculation function "calculate_reward(self, saturation_value, performance_metrics)" based on the below requirement, whether the given code satisfies the requirement or not in its computation steps. I am implemeted this function with im=n my reinforcement learning approach. I have total '8' parameters as a target specifications (1 saturation_value + 7 performance_metrics = 8 total target specifications), they are 'saturation_value', 'Area', 'PowerDissipation', 'SlewRate', 'Gain', 'Bandwidth3dB', 'UnityGainFreq', 'PhaseMargin'. Here my most preference parameter is the 'saturation_value', the desired value must be need to be '1'. Then among 7 performance_metrics, the desired parameter values of 'Area', 'PowerDissipation' are need to be minimize and the desired parametr values of 'SlewRate', 'Gain', 'Bandwidth3dB', 'UnityGainFreq', 'PhaseMargin' are need to be maximize. Target specifications Requirement: saturation_value = 1 (must be attain) 'Area' lesser than '3e-10' (desired value should be lesser than target) 'PowerDissipation' lesser than '2500' (desired value should be lesser than target) 'SlewRate' greater than '20' (desired value should be greater than target) 'Gain' greater than '70' (desired value should be greater than target) 'Bandwidth3dB' greater than '30e3' (desired value should be greater than target) 'UnityGainFreq' greater than or equal to '30e6' (desired value should be greater than target) 'PhaseMargin' between '60-90' (desired value should be greater than target) Code: def calculate_reward(self, saturation_value, performance_metrics): Area = performance_metrics['Area'] PowerDissipation = performance_metrics['PowerDissipation'] SlewRate = performance_metrics['SlewRate'] Gain = performance_metrics['Gain'] Bandwidth3dB = performance_metrics['Bandwidth3dB'] UnityGainFreq = performance_metrics['UnityGainFreq'] PhaseMargin = performance_metrics['PhaseMargin'] # Check if saturation condition is met if saturation_value == 1: reward_saturation = 10 # Large reward if saturation condition is met else: reward_saturation = 0 # Calculate reward based on other performance metrics and design specifications reward = 0 reward += min((Area - 3e-10) / (Area + 3e-10), 0) reward += min((PowerDissipation - 2500) / (PowerDissipation + 2500), 0) reward += min((SlewRate - 20) / (SlewRate + 20), 0) reward += min((Gain - 70) / (Gain + 70), 0) reward += min((Bandwidth3dB - 30000) / (Bandwidth3dB + 30000), 0) reward += min((UnityGainFreq - 30000000) / (UnityGainFreq + 30000000), 0) #reward += min((phase_margin - 60) / (phase_margin + 60), 0) reward += min((PhaseMargin - 60) / (PhaseMargin + 30), 0) # Clip the reward to avoid overoptimizing reward = max(reward, 0) reward = min(reward, 10) # Add saturation reward reward += reward_saturation return reward
8b2c40b5ea89f40656753993f48b300b
{ "intermediate": 0.3973873555660248, "beginner": 0.3635406196117401, "expert": 0.23907199501991272 }
40,949
hi
112aad2da40b2330bae0f556a5d161e0
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
40,950
scrape movies names from url = 'http://www.imdb.com/chart/toptv/' oython script
86664deba506e7e367175918ddd581e1
{ "intermediate": 0.3503228425979614, "beginner": 0.30780041217803955, "expert": 0.341876745223999 }
40,951
Cause: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'height' at row 1 ; Data truncation: Data too long for column 'height' at row 1; nested exception is com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'height' at row 1
79bc26bc032aafb7c1865b2dcd46be9b
{ "intermediate": 0.4131509065628052, "beginner": 0.32001349329948425, "expert": 0.2668355703353882 }
40,952
give me this data as key value pairs genres = ["Thriller","Action","Drama","Crime","Documentary","Adventure","History","SciFI","RealityTv","Newa","TalkSHow"] no_of_shows = [thrillercount,actioncount,dramacount,crimecount,documentarycount,adventurecount,historycount,scificount,realitytvcount,newscount,talkshowcount] like this data = {'C': 20, 'C++': 15, 'Java': 30, 'Python': 35}
25ded9ddb66bebbee79ed6fc63e7ad9b
{ "intermediate": 0.3776993751525879, "beginner": 0.356545090675354, "expert": 0.2657555043697357 }
40,953
my array looks like this , how to extract just the numbers [[(378,)], [(1175,)], [(2771,)], [(1111,)], [(635,)], [(1200,)], [(315,)], [(155,)], [(45,)], [(23,)], [(89,)]]
2cbdfece7f2b174dd91e135d68917034
{ "intermediate": 0.4445550739765167, "beginner": 0.2091817855834961, "expert": 0.34626317024230957 }
40,954
A line graph representing the frequency count of TV-shows having n episodes, n varies from 1 to maximum no. of episodes present. Represent no. of episodes (on x-axis) and frequency count (on y-axis) [('Breaking Bad', 62), ('Planet Earth II', 6), ('Planet Earth', 11), ('Band of Brothers', 10), ('Chernobyl', 5), ('The Wire', 60), ('Avatar: The Last Airbender', 62), ('Blue Planet II', 7), ('The Sopranos', 86), ('Cosmos: A Spacetime Odyssey', 13), ('Cosmos', 13), ('Our Planet', 12), ('Game of Thrones', 74), ('The World at War', 26), ('Bluey', 173), ('Rick and Morty', 74), ('Hagane No Renkinjutsushi', 68), ('Life', 11), ('The Last Dance', 10), ('The Twilight Zone', 156), ('Sherlock', 15), ('The Vietnam War', 10), ('Batman: The Animated Series', 85), ('Attack on Titan', 98), ('Scam 1992: The Harshad Mehta Story', 10), ('The Office', 188), ('The Blue Planet', 8), ('Arcane: League of Legends', 10), ('Better Call Saul', 63), ('Human Planet', 8), ('Firefly', 14), ('Frozen Planet', 10), ("Clarkson's Farm", 18), ('HUNTER×HUNTER', 148), ('Only Fools and Horses....', 64), ('Death Note: Desu nôto', 37), ('The Civil War', 9), ('Seinfeld', 173), ('True Detective', 31), ('Dekalog', 10), ('The Beatles: Get Back', 3), ('Sahsiyet', 22), ('Gravity Falls', 41), ('Kaubôi bibappu', 26), ('Fargo', 51), ('Nathan for You', 32), ('Apocalypse: La 2ème guerre mondiale', 6), ('When They See Us', 4), ('Last Week Tonight with John Oliver', 344), ('Taskmaster', 161), ('Succession', 39), ('Africa', 7), ('Friends', 234), ('As If', 43), ('TVF Pitchers', 10), ("It's Always Sunny in Philadelphia", 172), ("Monty Python's Flying Circus", 45), ('The West Wing', 155), ('Das Boot', 3), ('Curb Your Enthusiasm', 120), ('One Piece', 1107), ('BoJack Horseman', 77), ('Fawlty Towers', 12), ('Leyla Ile Mecnun', 144), ('Pride and Prejudice', 6), ('Freaks and Geeks', 18), ('Blackadder Goes Forth', 6), ('Twin Peaks', 30), ('Dragon Ball Z', 277), ('Narcos', 30), ("Chappelle's Show", 33), ('Dragon Ball Z', 291), ('Eung-dab-ha-ra 1988', 20), ('I, Claudius', 13), ('Black Mirror', 29), ('South Park', 330), ('Over the Garden Wall', 10), ('Ted Lasso', 34), ('Vinland Saga', 48), ('The Last of Us', 10), ('Kota Factory', 11), ('Peaky Blinders', 36), ('Six Feet Under', 63), ('Gullak', 16), ('Rome', 22), ('Oz', 56), ('Panchayat', 24), ('Steins;Gate', 26), ('Blue Eye Samurai', 9), ('Dark', 26), ('Bleach: Thousand-Year Blood War', 27), ('The Boys', 32), ('Fleabag', 12), ('Battlestar Galactica', 74), ('The Shield', 89), ('Downton Abbey', 52), ('The Simpsons', 762), ('Kenpû Denki Berserk', 25), ('Arrested Development', 84), ('House M.D.', 176), ('Severance', 19), ('One Punch Man: Wanpanman', 25), ('Invincible', 18), ('Mad Men', 92), ('Peep Show', 54), ('Star Trek: The Next Generation', 176), ('Stranger Things', 42), ('Mahabharat', 94), ('The Adventures of Sherlock Holmes', 13), ('The Marvelous Mrs. Maisel', 43), ('The Grand Tour', 46), ("TVF's Aspirants", 10), ('Friday Night Lights', 76), ('Justice League Unlimited', 39), ('Sarabhai vs Sarabhai', 79), ('The Mandalorian', 25), ('Behzat Ç.: Bir Ankara Polisiyesi', 105), ('Top Gear', 328), ('Line of Duty', 37), ('1883', 10), ('Naruto: Shippûden', 501), ('The Thick of It', 24), ('Monster', 75), ('Ramayan', 78), ('House of Cards', 73), ('How to with John Wilson', 18), ('This Is Us', 106), ('Father Ted', 25), ('Atlanta', 41), ('Parks and Recreation', 124), ('The Crown', 60), ('Deadwood', 36), ('The X Files', 217), ('Dexter', 96), ('Critical Role', 403), ('Kôdo giasu - Hangyaku no rurûshu: Code Geass - Lelouch of the Rebellion', 54), ('Primal', 21), ('Sin', 5), ('Adventure Time with Finn & Jake', 289), ('The Jinx: The Life and Deaths of Robert Durst', 12), ('Bron/Broen', 38), ('Daredevil', 39), ('Blackadder II', 6), ('Lonesome Dove', 4), ('Yeh Meri Family', 12), ('Mindhunter', 19), ('Haikyuu!!', 89), ('The Return of Sherlock Holmes', 13), ('The Offer', 10), ('Poirot', 70), ('Gomorra: La Serie', 58), ('Mr. Bean', 15), ('Mystery Science Theater 3000', 199), ('Scavengers Reign', 12), ('Blackadder the Third', 6), ('Archer', 144), ('Pose', 26), ('Demon Slayer: Kimetsu no Yaiba', 66), ('Sa-rang-eui Bul-sa-chak', 19), ('Anne', 27), ('Young Justice', 102), ('Dopesick', 8), ('Yes Minister', 22), ('Greatest Events of WWII in Colour', 10), ('Yellowstone', 53), ('The Bear', 19), ('Mr Inbetween', 26), ('The Newsroom', 25), ('QI', 333), ('Boardwalk Empire', 56), ('Justified', 78), ('The Bugs Bunny Show', 186), ('Le Bureau des Légendes', 50), ('The Haunting of Hill House', 10), ('El Chavo del Ocho', 357), ('What We Do in the Shadows', 51), ('Homicide: Life on the Street', 122), ('Justice League', 52), ('The Venture Bros.', 86), ("The Queen's Gambit", 7), ('Dragon Ball: Doragon bôru', 153), ('Battlestar Galactica', 2), ('Jujutsu Kaisen', 48), ('Flight of the Conchords', 22), ('The Family Man', 20), ('Dragon Ball', 153), ('Making a Murderer', 20), ('Coupling', 28), ('Senke Nad Balkanom', 20), ('Rocket Boys', 17), ('Yes, Prime Minister', 16), ('Impractical Jokers', 284), ('Samurai chanpurû', 26), ('Endeavour', 36), ('The Eric Andre Show', 69), ('The IT Crowd', 25), ('Spaced', 14), ('Mr. Robot', 45), ('Ezel', 71), ("I'm Alan Partridge", 12), ('Long Way Round', 10), ('Mob Psycho 100', 37), ('Samurai Jack', 62), ('Louie', 61), ('Formula 1: Drive to Survive', 60), ('Heartstopper', 24), ('Detectorists', 20), ('Whose Line Is It Anyway?', 220), ('Spartacus: Blood and Sand', 33), ('The Office', 14), ('Happy Valley', 18), ('Through the Wormhole', 62), ('Sons of Anarchy', 92), ('Shin Seiki Evangelion', 26), ('Shameless', 134), ('Twin Peaks', 18), ('Trailer Park Boys', 106), ('Brass Eye', 7), ('Skam', 43), ('Letterkenny', 81), ('North & South', 4), ('Spartacus: Gods of the Arena', 6), ('Silicon Valley', 53), ('Regular Show', 244), ('Doctor Who', 175), ('Extraordinary Attorney Woo', 16), ("Schitt's Creek", 80), ('Hagane No Renkinjutsushi', 51), ('Futurama', 180), ('The Rehearsal', 7), ('From the Earth to the Moon', 12), ('Rurouni Kenshin: Meiji Kenkaku Romantan: Tsuioku Hen', 4), ('The Expanse', 62), ('Derry Girls', 19), ('Hannibal', 39), ('Westworld', 36), ('Umbre', 21), ('Wentworth', 100), ("L'amica Geniale", 25), ('Community', 110), ('The European Side', 190), ('Tear Along the Dotted Line', 6), ('Shigatsu Wa Kimi No Uso', 25), ("Chef's Table", 30), ('Gintama', 375), ('Alchemy of Souls', 30), ("Foyle's War", 28), ('Alfred Hitchcock Presents', 268), ('Southland', 43), ('Generation Kill', 7)]
62dba7dd2085668177bae4b71f606613
{ "intermediate": 0.4027564227581024, "beginner": 0.36870935559272766, "expert": 0.2285342514514923 }
40,955
[(‘Breaking Bad’, 62), (‘Planet Earth II’, 6), (‘Planet Earth’, 11), (‘Band of Brothers’, 10), (‘Chernobyl’, 5), (‘The Wire’, 60), (‘Avatar: The Last Airbender’, 62), (‘Blue Planet II’, 7), (‘The Sopranos’, 86), (‘Cosmos: A Spacetime Odyssey’, 13), (‘Cosmos’, 13), (‘Our Planet’, 12), (‘Game of Thrones’, 74), (‘The World at War’, 26), (‘Bluey’, 173), (‘Rick and Morty’, 74), (‘Hagane No Renkinjutsushi’, 68), (‘Life’, 11), (‘The Last Dance’, 10), (‘The Twilight Zone’, 156), (‘Sherlock’, 15), (‘The Vietnam War’, 10), (‘Batman: The Animated Series’, 85), (‘Attack on Titan’, 98), (‘Scam 1992: The Harshad Mehta Story’, 10), (‘The Office’, 188), (‘The Blue Planet’, 8), (‘Arcane: League of Legends’, 10), (‘Better Call Saul’, 63), (‘Human Planet’, 8), (‘Firefly’, 14), (‘Frozen Planet’, 10), (“Clarkson’s Farm”, 18), (‘HUNTER×HUNTER’, 148), (‘Only Fools and Horses…’, 64), (‘Death Note: Desu nôto’, 37), (‘The Civil War’, 9), (‘Seinfeld’, 173), (‘True Detective’, 31), (‘Dekalog’, 10), (‘The Beatles: Get Back’, 3), (‘Sahsiyet’, 22), (‘Gravity Falls’, 41), (‘Kaubôi bibappu’, 26), (‘Fargo’, 51), (‘Nathan for You’, 32), (‘Apocalypse: La 2ème guerre mondiale’, 6), (‘When They See Us’, 4), (‘Last Week Tonight with John Oliver’, 344), (‘Taskmaster’, 161), (‘Succession’, 39), (‘Africa’, 7), (‘Friends’, 234), (‘As If’, 43), (‘TVF Pitchers’, 10), (“It’s Always Sunny in Philadelphia”, 172), (“Monty Python’s Flying Circus”, 45), (‘The West Wing’, 155), (‘Das Boot’, 3), (‘Curb Your Enthusiasm’, 120), (‘One Piece’, 1107), (‘BoJack Horseman’, 77), (‘Fawlty Towers’, 12), (‘Leyla Ile Mecnun’, 144), (‘Pride and Prejudice’, 6), (‘Freaks and Geeks’, 18), (‘Blackadder Goes Forth’, 6), (‘Twin Peaks’, 30), (‘Dragon Ball Z’, 277), (‘Narcos’, 30), (“Chappelle’s Show”, 33), (‘Dragon Ball Z’, 291), (‘Eung-dab-ha-ra 1988’, 20), (‘I, Claudius’, 13), (‘Black Mirror’, 29), (‘South Park’, 330), (‘Over the Garden Wall’, 10), (‘Ted Lasso’, 34), (‘Vinland Saga’, 48), (‘The Last of Us’, 10), (‘Kota Factory’, 11), (‘Peaky Blinders’, 36), (‘Six Feet Under’, 63), (‘Gullak’, 16), (‘Rome’, 22), (‘Oz’, 56), (‘Panchayat’, 24), (‘Steins;Gate’, 26), (‘Blue Eye Samurai’, 9), (‘Dark’, 26), (‘Bleach: Thousand-Year Blood War’, 27), (‘The Boys’, 32), (‘Fleabag’, 12), (‘Battlestar Galactica’, 74), (‘The Shield’, 89), (‘Downton Abbey’, 52), (‘The Simpsons’, 762), (‘Kenpû Denki Berserk’, 25), (‘Arrested Development’, 84), (‘House M.D.’, 176), (‘Severance’, 19), (‘One Punch Man: Wanpanman’, 25), (‘Invincible’, 18), (‘Mad Men’, 92), (‘Peep Show’, 54), (‘Star Trek: The Next Generation’, 176), (‘Stranger Things’, 42), (‘Mahabharat’, 94), (‘The Adventures of Sherlock Holmes’, 13), (‘The Marvelous Mrs. Maisel’, 43), (‘The Grand Tour’, 46), (“TVF’s Aspirants”, 10), (‘Friday Night Lights’, 76), (‘Justice League Unlimited’, 39), (‘Sarabhai vs Sarabhai’, 79), (‘The Mandalorian’, 25), (‘Behzat Ç.: Bir Ankara Polisiyesi’, 105), (‘Top Gear’, 328), (‘Line of Duty’, 37), (‘1883’, 10), (‘Naruto: Shippûden’, 501), (‘The Thick of It’, 24), (‘Monster’, 75), (‘Ramayan’, 78), (‘House of Cards’, 73), (‘How to with John Wilson’, 18), (‘This Is Us’, 106), (‘Father Ted’, 25), (‘Atlanta’, 41), (‘Parks and Recreation’, 124), (‘The Crown’, 60), (‘Deadwood’, 36), (‘The X Files’, 217), (‘Dexter’, 96), (‘Critical Role’, 403), (‘Kôdo giasu - Hangyaku no rurûshu: Code Geass - Lelouch of the Rebellion’, 54), (‘Primal’, 21), (‘Sin’, 5), (‘Adventure Time with Finn & Jake’, 289), (‘The Jinx: The Life and Deaths of Robert Durst’, 12), (‘Bron/Broen’, 38), (‘Daredevil’, 39), (‘Blackadder II’, 6), (‘Lonesome Dove’, 4), (‘Yeh Meri Family’, 12), (‘Mindhunter’, 19), (‘Haikyuu!!’, 89), (‘The Return of Sherlock Holmes’, 13), (‘The Offer’, 10), (‘Poirot’, 70), (‘Gomorra: La Serie’, 58), (‘Mr. Bean’, 15), (‘Mystery Science Theater 3000’, 199), (‘Scavengers Reign’, 12), (‘Blackadder the Third’, 6), (‘Archer’, 144), (‘Pose’, 26), (‘Demon Slayer: Kimetsu no Yaiba’, 66), (‘Sa-rang-eui Bul-sa-chak’, 19), (‘Anne’, 27), (‘Young Justice’, 102), (‘Dopesick’, 8), (‘Yes Minister’, 22), (‘Greatest Events of WWII in Colour’, 10), (‘Yellowstone’, 53), (‘The Bear’, 19), (‘Mr Inbetween’, 26), (‘The Newsroom’, 25), (‘QI’, 333), (‘Boardwalk Empire’, 56), (‘Justified’, 78), (‘The Bugs Bunny Show’, 186), (‘Le Bureau des Légendes’, 50), (‘The Haunting of Hill House’, 10), (‘El Chavo del Ocho’, 357), (‘What We Do in the Shadows’, 51), (‘Homicide: Life on the Street’, 122), (‘Justice League’, 52), (‘The Venture Bros.’, 86), (“The Queen’s Gambit”, 7), (‘Dragon Ball: Doragon bôru’, 153), (‘Battlestar Galactica’, 2), (‘Jujutsu Kaisen’, 48), (‘Flight of the Conchords’, 22), (‘The Family Man’, 20), (‘Dragon Ball’, 153), (‘Making a Murderer’, 20), (‘Coupling’, 28), (‘Senke Nad Balkanom’, 20), (‘Rocket Boys’, 17), (‘Yes, Prime Minister’, 16), (‘Impractical Jokers’, 284), (‘Samurai chanpurû’, 26), (‘Endeavour’, 36), (‘The Eric Andre Show’, 69), (‘The IT Crowd’, 25), (‘Spaced’, 14), (‘Mr. Robot’, 45), (‘Ezel’, 71), (“I’m Alan Partridge”, 12), (‘Long Way Round’, 10), (‘Mob Psycho 100’, 37), (‘Samurai Jack’, 62), (‘Louie’, 61), (‘Formula 1: Drive to Survive’, 60), (‘Heartstopper’, 24), (‘Detectorists’, 20), (‘Whose Line Is It Anyway?’, 220), (‘Spartacus: Blood and Sand’, 33), (‘The Office’, 14), (‘Happy Valley’, 18), (‘Through the Wormhole’, 62), (‘Sons of Anarchy’, 92), (‘Shin Seiki Evangelion’, 26), (‘Shameless’, 134), (‘Twin Peaks’, 18), (‘Trailer Park Boys’, 106), (‘Brass Eye’, 7), (‘Skam’, 43), (‘Letterkenny’, 81), (‘North & South’, 4), (‘Spartacus: Gods of the Arena’, 6), (‘Silicon Valley’, 53), (‘Regular Show’, 244), (‘Doctor Who’, 175), (‘Extraordinary Attorney Woo’, 16), (“Schitt’s Creek”, 80), (‘Hagane No Renkinjutsushi’, 51), (‘Futurama’, 180), (‘The Rehearsal’, 7), (‘From the Earth to the Moon’, 12), (‘Rurouni Kenshin: Meiji Kenkaku Romantan: Tsuioku Hen’, 4), (‘The Expanse’, 62), (‘Derry Girls’, 19), (‘Hannibal’, 39), (‘Westworld’, 36), (‘Umbre’, 21), (‘Wentworth’, 100), (“L’amica Geniale”, 25), (‘Community’, 110), (‘The European Side’, 190), (‘Tear Along the Dotted Line’, 6), (‘Shigatsu Wa Kimi No Uso’, 25), (“Chef’s Table”, 30), (‘Gintama’, 375), (‘Alchemy of Souls’, 30), (“Foyle’s War”, 28), (‘Alfred Hitchcock Presents’, 268), (‘Southland’, 43), (‘Generation Kill’, 7)] gwt max count from this data using python
475ffad0113d4f316b2a7b0ad70260ed
{ "intermediate": 0.3389936685562134, "beginner": 0.4246525466442108, "expert": 0.236353799700737 }
40,956
Set up your API Key (recommended) Configure your API key as an environment variable. This approach streamlines your API usage by eliminating the need to include your API key in each request. Moreover, it enhances security by minimizing the risk of inadvertently including your API key in your codebase. In your terminal of choice: CopyCopy code export GROQ_API_KEY=<your-api-key-here> Requesting your first chat completion curl JavaScript Python JSON Install the Groq Python library: CopyCopy code pip install groq Performing a Chat Completion: Copy import os from groq import Groq client = Groq( api_key=os.environ.get("GROQ_API_KEY"), ) chat_completion = client.chat.completions.create( messages=[ { "role": "user", "content": "Explain the importance of low latency LLMs", } ], model="mixtral-8x7b-32768", ) print(chat_completion.choices[0].message.content) Now that you have successfully received a chat completion, you can try out the other endpoints in the API ---------- i am using google colab to use the API. can you tell how can i use it in google colab
cd555a811f447c2a55148cd0cbafc0ca
{ "intermediate": 0.7191594243049622, "beginner": 0.14062432944774628, "expert": 0.1402161568403244 }
40,957
generate more comprehensive details and examples on, 2. Setting Up a Strategic Instagram Profile, minimalist tone
97ffce081fb483f756dff4daf5486647
{ "intermediate": 0.32710108160972595, "beginner": 0.31394150853157043, "expert": 0.3589573800563812 }
40,958
take user input in python
4e9a0d5faa015313ea4d7a7aec41949d
{ "intermediate": 0.30135202407836914, "beginner": 0.45069363713264465, "expert": 0.2479543387889862 }