row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
47,691
check this code: fn main() { let c_fivends = vec![(5,10),(25,30),(40,45),(60,65)]; let c_exons = vec![(32,37),(47,55),(70,80)]; let tx_5end = (43,45); if let Ok(k) = c_fivends.binary_search_by(|&(start, _)| start.cmp(&tx_5end.0)) { println!("we are inside") } else { println!("we are not inside") }; } current result is "we are not inside". In this case the expected behavior should be "we are inside" because 43 is between 40 and 45. Your solution needs to be the most efficient, fastest and elegant. You are free to use any algorithm, function, crate, trick or unsafe code you want.
f8fa3067a8934456e0f228b5878c9e8d
{ "intermediate": 0.22177115082740784, "beginner": 0.44464609026908875, "expert": 0.3335827887058258 }
47,692
Hi there, please be a senior sapui5 developer and answer my following questions with working code examples.
44609438c16f6709854d2ae25634e206
{ "intermediate": 0.42116406559944153, "beginner": 0.2712341248989105, "expert": 0.3076017498970032 }
47,693
this is my function: pub fn interval_search(intervals: &[(u64, u64)], query: &(u64, u64)) -> Option<(u64, u64)> { let mut start = 0; let mut end = intervals.len(); while start < end { let mid = start + (end - start) / 2; let mid_val = intervals[mid]; if query.1 <= mid_val.0 { end = mid; } else if query.0 >= mid_val.1 { start = mid + 1; } else { return Some(mid_val); } } None } what can i do to make it a method for any vector with tuples inside of the form (number, number)? For example, to do something like this: let x = [(1,6), (10,15), (25,32)]; let y = (26,30); x.interval_search(y)
c184351dfd138a5469b3207251aefe94
{ "intermediate": 0.4487825930118561, "beginner": 0.3419005572795868, "expert": 0.20931686460971832 }
47,694
look at my implementation: trait IntervalSearch<T> { fn interval_search(&self, query: &(T, T)) -> Option<(T, T)> where T: PartialOrd + Copy; } impl<T> IntervalSearch<T> for Vec<(T, T)> { fn interval_search(&self, query: &(T, T)) -> Option<(T, T)> where T: PartialOrd + Copy, { let mut start = 0; let mut end = self.len(); while start < end { let mid = start + (end - start) / 2; let mid_val = self[mid]; if query.1 <= mid_val.0 { end = mid; } else if query.0 >= mid_val.1 { start = mid + 1; } else { return Some(mid_val); } } None } } do you have any idea on how to make crazy faster? You are allowed to use any trick you want
c820e67f5cf65655f5ce40d60bde97c4
{ "intermediate": 0.4128094017505646, "beginner": 0.14692549407482147, "expert": 0.44026514887809753 }
47,695
I have this nest prisma request: async getGroupsByTeacherId(_teacher_id:number){ return this.prisma.studygroups.findMany({ select: { id: true, name: true, // main_schedule: true, }, where: { main_schedule: { some: { teacher_id: Number(_teacher_id), }, }, }, }); } I have table users with this columns: id username password firstname lastname patronymic type_user email studyGroups resetPasswordToken resetPasswordExpires superAdmin teacher_id student_id nik_domic and I have table main_schedule: id group_id time_id weekday_id week subject_id teacher_id classroom_id period type_subject begin_date end_date I need to find entry of table "users" by id = 88, get teacher_id of that entry and then, by that teacher_id get all entries of main_schedule table, where teacher_id = teacher_id
d3e4459be9a3a58bdbbb3d2ac54df636
{ "intermediate": 0.5454025268554688, "beginner": 0.2829682528972626, "expert": 0.17162932455539703 }
47,696
struct wl_registry * registry = wl_display_get_registry(display); wl_registry_add_listener(registry, &registry_listener, NULL); // wait for the "initial" set of globals to appear wl_display_roundtrip(display); need to mock these function using Gtest and Gmock ..
b0be0b81302ca0fbe8de467d4f30bcd5
{ "intermediate": 0.42970162630081177, "beginner": 0.4286656379699707, "expert": 0.14163270592689514 }
47,697
In this clojurescript code, what is the react class I need to have the edit button on the left and the other buttons on the right? [:div.d-flex [:div [:button.btn.btn-danger {:on-click #(ui.new/close-popover! popover-state-atom)} "Edit"]] [:div.align-items-right [:button.btn.btn-primary ;; on-close will be called and handle transfering the local values into re-frame {:on-click #(ui.new/close-popover! popover-state-atom)} "Save"] [:button.btn.btn-link {:on-click #(do (reset! name-atom original-name) (reset! desc-atom original-desc) (ui.new/close-popover! popover-state-atom))} "Cancel"]]]
842ec588e2aefb4f8740782fb57d7585
{ "intermediate": 0.4845345616340637, "beginner": 0.3759177029132843, "expert": 0.1395477056503296 }
47,698
write an Auction Sniper bot using python a python script, for a specific website, prompting for bid price and the time to input the bid, say yes master if you understood
1445f776b3ae46390d93e99c0cb9225a
{ "intermediate": 0.30206623673439026, "beginner": 0.1732521504163742, "expert": 0.524681568145752 }
47,699
привет у меня есть скрипт для увелечения значения сборки как мне сделать так что он увеличивал только если сборка успешно собирается public class VersionIncrementor : IPreprocessBuildWithReport { public int callbackOrder { get { return 0; } } public void OnPreprocessBuild(BuildReport report) { IncrementVersion(); } private static void IncrementVersion() { string[] versionNumbers = PlayerSettings.bundleVersion.Split('.'); if (versionNumbers.Length > 0) { int buildNumber = int.Parse(versionNumbers[versionNumbers.Length - 1]); buildNumber++; versionNumbers[versionNumbers.Length - 1] = buildNumber.ToString(); string newVersion = string.Join(".", versionNumbers); PlayerSettings.bundleVersion = newVersion; Debug.Log("Updated version to " + newVersion); } else { Debug.LogError("Failed to increment version number."); } } }
e2b63240e3882790d40d74e79a952f28
{ "intermediate": 0.4707893133163452, "beginner": 0.37473705410957336, "expert": 0.15447360277175903 }
47,700
привет при сборке вышла такая ошибка Assets\Scripts\Editor\VersionIncrementor.cs(3,19): error CS0234: The type or namespace name 'Build' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
3c20e29cfce3d1330aaf4b59726120df
{ "intermediate": 0.3837953805923462, "beginner": 0.36705929040908813, "expert": 0.2491452842950821 }
47,701
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class Clickable : Interactable { public UnityEvent m_onPressDown; public UnityEvent m_onPressUp; public UnityEvent m_onPress; public override void ClearInteractableEvents() { base.ClearInteractableEvents(); m_onPress.RemoveAllListeners(); m_onPressDown.RemoveAllListeners(); m_onPressUp.RemoveAllListeners(); } public override void OnStartInteract(Touch touch) { base.OnStartInteract(touch); m_onPressDown.Invoke(); OnPressDown(); } public override void OnEndInteract(Touch touch, bool canceled) { base.OnEndInteract(touch); m_onPressUp.Invoke(); OnPressUp(); } public virtual void OnPressDown() { } public virtual void OnPressUp() { } public virtual void OnPress() { // 检测鼠标左键按下 if (Input.GetMouseButtonDown(0)) { Debug.Log("左键"); } // 检测鼠标右键按下 if (Input.GetMouseButtonDown(1)) { Debug.Log("油煎"); } } protected override void VirutalUpdate() { base.VirutalUpdate(); if (Interacting) { m_onPress.Invoke(); OnPress(); } } } 为什么鼠标右键没有反应呢
a31c38c20dd89bf669b014bdb5a805a1
{ "intermediate": 0.373688280582428, "beginner": 0.39526838064193726, "expert": 0.23104339838027954 }
47,702
6 I'm trying to proxy a request to a backend with Next rewrites. next.config.js: async rewrites() { return [ { source: "/api/:path*", destination: "http://somedomain.loc/api/:path*", }, ] }, /etc/host: 127.0.0.1 somedomain.loc and in the end i get this error: Failed to proxy http://somedomain.loc/api/offers Error: connect ECONNREFUSED 127.0.0.1:80 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16) { errno: -111, code: 'ECONNREFUSED', syscall: 'connect', address: '127.0.0.1', port: 80 } error - Error: connect ECONNREFUSED 127.0.0.1:80 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16) { errno: -111, code: 'ECONNREFUSED', syscall: 'connect', address: '127.0.0.1', port: 80 } While if you make a request via postman or directly from the browser, everything works fine. Please help me understand what is the problem here. tried: Proxy request to backend expected: The request is proxied to the backend as a result: Proxy error
3d99bcc1370b8e97f2a9dee9798ea390
{ "intermediate": 0.55784672498703, "beginner": 0.2582094073295593, "expert": 0.18394392728805542 }
47,703
how to write gtest for STATIC void draw_image(struct graphics_priv *gr, struct graphics_gc_priv *fg, struct point *p, struct graphics_image_priv *img) { // draw_image_es(gr, p, img->img->w, img->img->h, img->img->pixels); }
1f453a0aa73a0556d7b63123c785d668
{ "intermediate": 0.34079909324645996, "beginner": 0.3954678177833557, "expert": 0.26373305916786194 }
47,704
Write function on python which have text with \n on input. I need that function split this text by "\n" and make multiline text on output which must be in """ """ without "\n"
b5df040518d7d87e5ca1a2aacc0bac4f
{ "intermediate": 0.4060955345630646, "beginner": 0.3170996308326721, "expert": 0.2768048346042633 }
47,705
vue 3 composition api script setup ts. How to create ref of component with generic
08c3600ced2d17a7fe5102f548e37f6f
{ "intermediate": 0.5820887684822083, "beginner": 0.2532646656036377, "expert": 0.16464661061763763 }
47,706
write a c code for floyd warshall algo in dynamic programming
d435b335c2211ee48561b7cc1304ca15
{ "intermediate": 0.13805843889713287, "beginner": 0.16276834905147552, "expert": 0.6991732120513916 }
47,707
make an array of 3 animals
9db1c022d2b078eb1e682a5b6617418f
{ "intermediate": 0.3331804871559143, "beginner": 0.3962669372558594, "expert": 0.2705525755882263 }
47,708
Mi puoi ottimizzare questa condizione "(showForm && isPrimaryInDocument && doc.entity === DocumentProcessActionRm.Primary) || (isPrimaryInDocument && doc.entity === DocumentProcessActionRm.Primary && selectedDoc?.document?.processInfo?.documentProcessAction !== DocumentProcessActionRm.Primary)"?
0496afa5d72237a0ecf028f5dfba99d0
{ "intermediate": 0.38888710737228394, "beginner": 0.3234640955924988, "expert": 0.2876487672328949 }
47,709
dans le fichier my.load de pgloader comment dire uqe je veux que les tables academies champs departements syndicats syndicats_deps. LOAD DATABASE FROM mysql://ariel@localhost/Anostic INTO postgresql://ariel:5432/Anostic WITH include drop, create tables, create indexes, reset sequences, workers = 8, concurrency = 1, multiple readers per thread, rows per range = 50000 SET PostgreSQL PARAMETERS maintenance_work_mem to '128MB', work_mem to '12MB', SET MySQL PARAMETERS net_read_timeout = '120', net_write_timeout = '120' CAST type bigint when (= precision 20) to bigserial drop typemod, type date drop not null drop default using zero-dates-to-null, type year to integer -- INCLUDING ONLY TABLE NAMES MATCHING ~/film/, 'actor' -- EXCLUDING TABLE NAMES MATCHING ~<ory> -- DECODING TABLE NAMES MATCHING ~/messed/, ~/encoding/ AS utf8 -- ALTER TABLE NAMES MATCHING 'film' RENAME TO 'films' -- ALTER TABLE NAMES MATCHING ~/_list$/ SET SCHEMA 'mv'
b9b58ab1346a67e7bc310e006095a221
{ "intermediate": 0.48315128684043884, "beginner": 0.29879704117774963, "expert": 0.21805167198181152 }
47,710
how can we write statement for nonzero value return in .WillOnce(); statemen
b7d675723d291df7faddcffc21ce5a2c
{ "intermediate": 0.35682186484336853, "beginner": 0.41625985503196716, "expert": 0.22691835463047028 }
47,711
how can we use .WillOnce(SetArgPointee<0>(42)); for an unknown nonzero value
a5554f73f0e6e8857201c6efa2c4f7e1
{ "intermediate": 0.4887596666812897, "beginner": 0.2918165326118469, "expert": 0.2194238007068634 }
47,712
est-ce car la bd postgresql a un mot de passe que ça me fait cette erreur lors de pgloader de my.load ? KABOOM! DB-CONNECTION-ERROR: Failed to connect to pgsql at "ariel" (port 5432) as user "root": Database error: Name service error in "getaddrinfo": -2 (Name or service not known) An unhandled error condition has been signalled: Failed to connect to pgsql at "ariel" (port 5432) as user "root": Database error: Name service error in "getaddrinfo": -2 (Name or service not known) What I am doing here? Failed to connect to pgsql at "ariel" (port 5432) as user "root": Database error: Name service error in "getaddrinfo": -2 (Name or service not known) LOAD DATABASE FROM mysql://ariel@localhost/Anostic INTO postgresql://ariel:5432/Anostic WITH include drop, create tables, create indexes, reset sequences, workers = 8, concurrency = 1, multiple readers per thread, rows per range = 50000 SET MySQL PARAMETERS net_read_timeout = '120', net_write_timeout = '120' CAST type bigint when (= precision 20) to bigserial drop typemod INCLUDING ONLY TABLE NAMES MATCHING 'academies', 'champs', 'departements', 'syndicats', 'syndicats_deps';
7d57d0f2641ecd320445c7a529aed722
{ "intermediate": 0.6152352094650269, "beginner": 0.21226747334003448, "expert": 0.17249737679958344 }
47,713
avec postgresERROR: invalid byte sequence for encoding "UTF8": 0xc3 0x2a bd=# ERROR: invalid byte sequence for encoding "UTF8": 0xc3 0x2a
b1c31fbed1e26d50a6240c12ceb87b3d
{ "intermediate": 0.40680283308029175, "beginner": 0.29852741956710815, "expert": 0.2946697175502777 }
47,714
how can I create a 30x30 1 meter square grid of polygons in geojson
eec5500c11fa0304872d9391b5f7c444
{ "intermediate": 0.3157772719860077, "beginner": 0.2675897777080536, "expert": 0.4166329503059387 }
47,715
how can we define EXPECT_CALL for a function returns noz zero value via argument, if the argument is &ret
70ef2c0a34404ce06990757fe1189214
{ "intermediate": 0.3736134171485901, "beginner": 0.37350183725357056, "expert": 0.25288477540016174 }
47,716
My view code as "from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Uer,Address from .serializers import UerSerializer,AddressSerializer class UsersList(APIView): """ Retrieve all users or create a new user """ def get(self, request,format=None): users = User.objects.all() serializer = UerSerializer(data=request.data,many=True) return Response(serializer.data) def post(self,request,format=None): serializer = UerSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) "
1e5c902901820a3c200cebd642f68258
{ "intermediate": 0.48925742506980896, "beginner": 0.3314541280269623, "expert": 0.17928852140903473 }
47,717
I want to make a cricket project using pyhton that will provide me the details about cricket player when i provide them players name. use web scrapping from https://www.espncricinfo.com/
41a098d742303584aa1caedcf9dcd5c0
{ "intermediate": 0.5723773837089539, "beginner": 0.19025731086730957, "expert": 0.237365260720253 }
47,718
Write function on python which converts input text like "example\ntext" to multiline text without /n
fe77ec619a2c7b820cf7ef61da42cc82
{ "intermediate": 0.38876813650131226, "beginner": 0.24483764171600342, "expert": 0.3663943111896515 }
47,719
donne l'équivalent avec postgresql et plus mysql : connection.execute(text("""CREATE TABLE IF NOT EXISTS 'CS_'""" + nom_os + """("NUMEN" VARCHAR(64) PRIMARY KEY) AS SELECT DISTINCT "NUMEN" FROM public WHERE "NUMEN" IS NOT NULL AND (""" + rg + """)"""))
b76d7f0d47f1a0bb4edc0bb5192b5974
{ "intermediate": 0.36833634972572327, "beginner": 0.3687041103839874, "expert": 0.2629595100879669 }
47,720
donc connection.execute(text("""CREATE TABLE IF NOT EXISTS 'CS_'""" + nom_os + """` ("NUMEN" VARCHAR(64) PRIMARY KEY) AS SELECT DISTINCT "NUMEN" FROM public WHERE "NUMEN" IS NOT NULL AND (""" + rg + """)""")) est équivalent à connection.execute(text(f""" CREATE TABLE IF NOT EXISTS CS_{nom_os} AS SELECT DISTINCT "NUMEN" FROM public WHERE "NUMEN" IS NOT NULL AND ({rg}) """)) connection.execute(text(f""" ALTER TABLE CS_{nom_os} ADD CONSTRAINT CS_{nom_os}_pkey PRIMARY KEY (“NUMEN”); """)) ??
1db91897d659f55e7657e9ec51046fd9
{ "intermediate": 0.34169888496398926, "beginner": 0.4194145202636719, "expert": 0.23888655006885529 }
47,721
Comment passer d'une requete qui utilisait MySQL de cette forme a une requete similaire enutilisant postgres : with engine.begin() as connection: connection.execute(text("""CREATE TABLE IF NOT EXISTS 'CS_'""" + nom_os + """` ("NUMEN" VARCHAR(64) PRIMARY KEY) AS SELECT DISTINCT "NUMEN" FROM public WHERE "NUMEN" IS NOT NULL AND (""" + rg + """)"""))
8cebf0606c21ea5a1f7c40c1e47f1ba3
{ "intermediate": 0.4281786382198334, "beginner": 0.29367363452911377, "expert": 0.27814772725105286 }
47,722
Comment passer d'une requete qui utilisait MySQL de cette forme a une requete similaire enutilisant postgresSQL, j'utilise SQLAlchemy : with engine.begin() as connection: connection.execute(text("""CREATE TABLE IF NOT EXISTS 'CS_'""" + nom_os + """` ("NUMEN" VARCHAR(64) PRIMARY KEY) AS SELECT DISTINCT "NUMEN" FROM public WHERE "NUMEN" IS NOT NULL AND (""" + rg + """)"""))
dd0b65ad526095dd611a99289c3d1fa4
{ "intermediate": 0.4656018316745758, "beginner": 0.27725741267204285, "expert": 0.25714078545570374 }
47,723
Voici une requete depuis SQLAlchemy a une base MySQL correcte, maintenant je voudrais une requete qui fasse la meme chose mais en utilisant PostgreSQL: with engine.begin() as connection: connection.execute(text("""CREATE TABLE IF NOT EXISTS 'CS_'""" + nom_os + """` ("NUMEN" VARCHAR(64) PRIMARY KEY) AS SELECT DISTINCT "NUMEN" FROM public WHERE "NUMEN" IS NOT NULL AND (""" + rg + """)"""))
183e054b8de725ed1b65c811a769b030
{ "intermediate": 0.41606104373931885, "beginner": 0.32172322273254395, "expert": 0.2622157335281372 }
47,724
> git push origin main:main remote: error: Trace: 79660510055d1926b80593f2fcfc68ce21f5f6ee1e78e776b09b5de4b0dc8783 remote: error: See https://gh.io/lfs for more information. remote: error: File data/TinyStories_all_data/data00.json is 133.92 MB; this exceeds GitHub's file size limit of 100.00 MB 但事实上,我的仓库中并没有这个文件, 远程库中也不存在,git rm --cache data/TinyStories_all_data/data00.json 也不行 怎么解决
25d46776f7cba11e671af733fd1ef09f
{ "intermediate": 0.33062541484832764, "beginner": 0.3519754409790039, "expert": 0.3173990845680237 }
47,725
wl_display_connect(NULL);
a7ede8f59e2900cc2633b06bc0eed5ea
{ "intermediate": 0.3706818222999573, "beginner": 0.27008575201034546, "expert": 0.35923242568969727 }
47,726
A single set of typedefs shall be used in place of standard C variable definitions in all modules.
03fbcfc096cd5dfc7734895525625037
{ "intermediate": 0.25033462047576904, "beginner": 0.4437524080276489, "expert": 0.30591297149658203 }
47,727
4Question 2: Need For Speed 4.1Introduction Lukarp has started his own tech company. He received a lot of funding from Igen with which he opened many offices around the world. Each office needs to communicate with one other, for which they’re using high speed connections between the offices. Office number 1 is Lukarp’s HQ. Some offices are important and hence need faster connections to the HQ for which Lukarp has use special fiber connections. Lukarp has already planned the connections but feels some fiber connections are redundant. You have been hired by Lukarp to remove those fiber connections which don’t cause faster connections. 4.2Problem Statement 4.2.1The Problem The offices and (bi-directional) connections (both normal and fiber) are given to you. HQ is numbered as 1. The ith normal connection connects any two offices ai and bi . Normal connections have latency li . The ith fiber connection connects the HQ with the office ci . Fiber connections also come with a latency pi . The total latency of a path is the sum of latencies on the connections. You are to output the maximum number of fiber connections that can be removed, such that the latency of the smallest latency path between the HQ and any other node remains the same as before. • There are n offices with m normal connections and k high-speed fiber connections. • The ith normal connection connects offices ai and bi (bi-directionally) with latency li . • The ith fiber connection connects offices 1 and ci (bi-directionally) with latency pi . 4.2.2 Input Format The first line of the input file will contain three space-separated integers n, m and k, the number of offices, the number of normal connections and the number of fiber connections. There will be m lines after this, the ith line signifying the ith normal connection, each containing three space-separated integers ai , bi and li the two offices that are connected and the latency of the connection respectively. There will be k lines after this, the ith line signifying the ith fiber connection, each containing three space-separated integers ci and pi , the office connected to the HQ and the latency of the fiber connection respectively. 64.2.3 Output Format Output only one integer m - the maximum number of fiber connections that can be removed without changing the latency of smallest latency path from office 1 to any other office. 4.2.4 Constraints • 2 ≤ n ≤ 105 • 1 ≤ m ≤ 2 · 105 • 1 ≤ k ≤ 105 • 1 ≤ ai , bi , ci ≤ n • 1 ≤ li , pi ≤ 109 4.2.5 Example Input: 4 5 2 1 2 2 1 4 9 1 3 3 2 4 4 3 4 5 3 4 4 5 Output: 1 Explanation: In this example, there are five normal connections as shown in the figure below. The fiber connection going from 1 to 3 can be removed because the normal con- nection (3) is faster than the fiber connection (4). However, the fiber connection with 4 cannot be removed.Hence the maximum number of fiber connections that can be removed is 1. give c++ code
e65cd86934291f557e6f081c33241d5d
{ "intermediate": 0.3162199854850769, "beginner": 0.3101998567581177, "expert": 0.3735801875591278 }
47,728
write code to Discuss how asynchronous functions (defined with async def) work in Python and how they differ from synchronous functions. Provide an example of an asynchronous function that makes multiple web requests in parallel and waits for all of them to complete, using asyncio.
904bdde5acadbf13680450703932b336
{ "intermediate": 0.5353137254714966, "beginner": 0.19993337988853455, "expert": 0.26475289463996887 }
47,729
Привет у меня не работает скрипт на увеличение версии приложения при сборки #if UNITY_EDITOR using UnityEngine; using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; using System; public class VersionIncrementor : IPostprocessBuildWithReport { public int callbackOrder { get { return 0; } } public void OnPostprocessBuild(BuildReport report) { if (report.summary.result == BuildResult.Succeeded) { IncrementVersion(); } else { Debug.Log("Build failed, version number was not incremented."); } } private static void IncrementVersion() { string[] versionNumbers = PlayerSettings.bundleVersion.Split('.'); if (versionNumbers.Length > 0) { // Преобразовываем последний элемент в номер сборки и инкрементируем его int buildNumber = int.Parse(versionNumbers[versionNumbers.Length - 1]); buildNumber++; versionNumbers[versionNumbers.Length - 1] = buildNumber.ToString(); string newVersion = string.Join(".", versionNumbers); // Обновляем номер версии в настройках проекта Unity PlayerSettings.bundleVersion = newVersion; Debug.Log("Updated version to " + newVersion); } else { Debug.LogError("Failed to increment version number."); } } } #endif
abf3dbaac87a073cebdd8de48c79553b
{ "intermediate": 0.45722874999046326, "beginner": 0.367343008518219, "expert": 0.17542816698551178 }
47,730
give an example of finding eigen value and eigen vector using python
dc179c113998ea8b76d0a99bfdcbc7c7
{ "intermediate": 0.2872425317764282, "beginner": 0.06788566708564758, "expert": 0.6448718309402466 }
47,731
write me a python script, i want to give an URL to a python script and this script exports me the content of <span> which has this attribute: type="a_title"
a5cb8201d3895876a8e786812ba57bf3
{ "intermediate": 0.3891353905200958, "beginner": 0.23307712376117706, "expert": 0.37778744101524353 }
47,732
#include <bits/stdc++.h> using namespace std; void dijkstra(int s, const vector<vector<pair<long long, int>>>& graph, vector<long long>& dist) { priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq; fill(dist.begin(), dist.end(), 1e18); dist[s] = 0; pq.push({0, s}); while (!pq.empty()) { pair<long long, int> front = pq.top(); pq.pop(); long long d = front.first; int u = front.second; if (d > dist[u]) continue; for (size_t i = 0; i < graph[u].size(); ++i) { long long l = graph[u][i].first; int v = graph[u][i].second; if (dist[v] > d + l) { dist[v] = d + l; pq.push({dist[v], v}); } } } } int main() { int n, m, k; cin >> n >> m >> k; vector<vector<pair<long long, int>>> graph(n + 1); for (int i = 0; i < m; i++) { int a, b; long long l; cin >> a >> b >> l; graph[a].emplace_back(l, b); graph[b].emplace_back(l, a); } vector<pair<int, long long>> fibers(k); for (int i = 0; i < k; i++) { cin >> fibers[i].first >> fibers[i].second; graph[1].emplace_back(fibers[i].second, fibers[i].first); graph[fibers[i].first].emplace_back(fibers[i].second, 1); } vector<long long> dist(n + 1); dijkstra(1, graph, dist); int removable = 0; for (int i = 0; i < k; i++) { int c = fibers[i].first; long long p = fibers[i].second; vector<long long> newDist(n + 1); dijkstra(1, graph, newDist); bool isEssential = false; for (int j = 1; j <= n; ++j) { if (newDist[j] != dist[j]) { isEssential = true; break; } } if (!isEssential) ++removable; } cout << removable; return 0; } avoid using emplace_back
91ce739e7aed4b7eb0d2c1b46541ab2e
{ "intermediate": 0.42958760261535645, "beginner": 0.3955005407333374, "expert": 0.17491184175014496 }
47,733
1_ Translate the following legal text into colloquial Farsi 2_ Place the Persian and English text side by side in the table 3_ From the beginning to the end of the text, there should be an English sentence on the left side and a Persian sentence on the right side. 4- Using legal language for Persian translation ._ Place the Farsi and English text line by line from one point to the first point next to each other in such a way that one line of English text is followed by two empty lines, followed by the Persian translation and continue this process until the end of the text.Consideration As was explained earlier, consideration is tbe technical name given to the contribution each party makes to te bargain- "I promise to pay il you promise to deliver" - "You can be the owner of this car for £1500", and so on. In Dunlop Pneumatic Tyre Co.v.Selfridge (1915), consideration is defined as: An act or forbearance of one party or te promise thereof is te price for which te promise of the other is bougbt and the promise thus given for value is enforceable. In practical terms, consideration is the point of making the bargain. It is wbat you wanted to get out of it. If you do not receive it (if the consideration fails) tben it usually amounts to a breach of contract. Professor Atiyah wrote
ef28033ee9d1f940d823859d7753901b
{ "intermediate": 0.2918255627155304, "beginner": 0.40573588013648987, "expert": 0.30243852734565735 }
47,734
for example I have a page like this -> <div class="card"> <img class="card-img-top mx-auto img-fluid" src="/assets/img/avatar.png" alt="Card image"> <ul class="list-group list-group-flush"> <li class="list-group-item flex-fill">Name: John</li> <li class="list-group-item flex-fill">Surname: Doe</li> <li class="list-group-item flex-fill">Age: 35</li> </ul> <div class="card-body"> <p class="card-text">...</p> </div> </div> </div> </div> <div class="row text-center mt-5"> <div class="col"> <div class="form-group"> <p id="approvalToken" class="d-none">0234789AIKLMNOPSUYZabefmnprsuvwx</p> <p id="rejectToken" class="d-none">0234579ABDGIKPQRSUWYbgknoqstuvyz</p> <a id="approveBtn" data-id="1" class="btn btn-primary" role="button">Approve submission</a> <a id="rejectBtn" data-id="1" class="btn btn-danger" role="button">Reject submission</a> <div id="responseMsg"></div> </div> </div> </div> </div> </main> <script type="text/javascript" src="/assets/js/jquery-3.6.0.min.js"></script> <script type="text/javascript" src="/assets/js/admin.js"></script> And I want to access approvalToken id via CSS to customize its font. How to do this ?
e1d3a55b55f34552ae4151db1f524469
{ "intermediate": 0.49024873971939087, "beginner": 0.3330337107181549, "expert": 0.17671753466129303 }
47,735
When I hover over a video on discord, the preload attribute changes from "none" to "metadata". How do I disable that in Firefox?
6b52bf0d2a16f7c091c3b9d22b0cee08
{ "intermediate": 0.4955331087112427, "beginner": 0.22242611646652222, "expert": 0.2820408046245575 }
47,736
le problème c'est que la syntaxe AS ne fonctionne pas en postgresql : connection.execute(text(f"""DO $$ BEGIN IF NOT EXISTS ( SELECT * FROM pg_tables WHERE schemaname = 'public' AND tablename = 'CS_{nom_os}' ) THEN CREATE TABLE "public.CS_" ("NUMEN" VARCHAR(64) PRIMARY KEY) AS SELECT DISTINCT "NUMEN" FROM public.public WHERE "NUMEN" IS NOT NULL AND ({rg})', %s); END IF; END $$"""))
5fad798758fc3db7889d5577d375b077
{ "intermediate": 0.1771858036518097, "beginner": 0.7130206227302551, "expert": 0.10979359596967697 }
47,737
le problème c'est que la syntaxe AS ne fonctionne pas en postgresql : connection.execute(text(f"""DO $$ BEGIN IF NOT EXISTS ( SELECT * FROM pg_tables WHERE schemaname = 'public' AND tablename = 'CS_{nom_os}' ) THEN CREATE TABLE "public.CS_" ("NUMEN" VARCHAR(64) PRIMARY KEY) AS SELECT DISTINCT "NUMEN" FROM public.public WHERE "NUMEN" IS NOT NULL AND ({rg})', %s); END IF; END $$"""))
7febea08f076db0ae6a1616d11037304
{ "intermediate": 0.1771858036518097, "beginner": 0.7130206227302551, "expert": 0.10979359596967697 }
47,738
le problème c'est que la syntaxe AS ne fonctionne pas en postgresql : connection.execute(text(f"""DO $$ BEGIN IF NOT EXISTS ( SELECT * FROM pg_tables WHERE schemaname = 'public' AND tablename = 'CS_{nom_os}' ) THEN CREATE TABLE "public.CS_" ("NUMEN" VARCHAR(64) PRIMARY KEY) AS SELECT DISTINCT "NUMEN" FROM public.public WHERE "NUMEN" IS NOT NULL AND ({rg})', %s); END IF; END $$"""))
cc4d196a96ee27769686c2f9081b2ced
{ "intermediate": 0.1771858036518097, "beginner": 0.7130206227302551, "expert": 0.10979359596967697 }
47,739
create me a website in html5 and java script. this website should have a news system, admin area, member area, a home area, write news, send news, upload pictures, font size, font type,
cc15a3b5f9f3d2bc7f85c5126e1d0da2
{ "intermediate": 0.4549117088317871, "beginner": 0.225625678896904, "expert": 0.3194626569747925 }
47,740
4Question 2: Need For Speed 4.1Introduction Lukarp has started his own tech company. He received a lot of funding from Igen with which he opened many offices around the world. Each office needs to communicate with one other, for which they’re using high speed connections between the offices. Office number 1 is Lukarp’s HQ. Some offices are important and hence need faster connections to the HQ for which Lukarp has use special fiber connections. Lukarp has already planned the connections but feels some fiber connections are redundant. You have been hired by Lukarp to remove those fiber connections which don’t cause faster connections. 4.2Problem Statement 4.2.1The Problem The offices and (bi-directional) connections (both normal and fiber) are given to you. HQ is numbered as 1. The ith normal connection connects any two offices ai and bi . Normal connections have latency li . The ith fiber connection connects the HQ with the office ci . Fiber connections also come with a latency pi . The total latency of a path is the sum of latencies on the connections. You are to output the maximum number of fiber connections that can be removed, such that the latency of the smallest latency path between the HQ and any other node remains the same as before. • There are n offices with m normal connections and k high-speed fiber connections. • The ith normal connection connects offices ai and bi (bi-directionally) with latency li . • The ith fiber connection connects offices 1 and ci (bi-directionally) with latency pi . 4.2.2 Input Format The first line of the input file will contain three space-separated integers n, m and k, the number of offices, the number of normal connections and the number of fiber connections. There will be m lines after this, the ith line signifying the ith normal connection, each containing three space-separated integers ai , bi and li the two offices that are connected and the latency of the connection respectively. There will be k lines after this, the ith line signifying the ith fiber connection, each containing three space-separated integers ci and pi , the office connected to the HQ and the latency of the fiber connection respectively. 64.2.3 Output Format Output only one integer m - the maximum number of fiber connections that can be removed without changing the latency of smallest latency path from office 1 to any other office. 4.2.4 Constraints • 2 ≤ n ≤ 105 • 1 ≤ m ≤ 2 · 105 • 1 ≤ k ≤ 105 • 1 ≤ ai , bi , ci ≤ n • 1 ≤ li , pi ≤ 109 4.2.5 Example Input: 4 5 2 1 2 2 1 4 9 1 3 3 2 4 4 3 4 5 3 4 4 5 Output: 1 Explanation: In this example, there are five normal connections as shown in the figure below. The fiber connection going from 1 to 3 can be removed because the normal con- nection (3) is faster than the fiber connection (4). However, the fiber connection with 4 cannot be removed. Hence the maximum number of fiber connections that can be removed is 1. also keep into consideration that a fiber path to node A can be a part of the shortest path to node B time complexity is not an issue. give a valid answer that satisfies all cases
87ad0ca1b1055c24f5810fe4cd975aae
{ "intermediate": 0.34173357486724854, "beginner": 0.24726171791553497, "expert": 0.4110047519207001 }
47,741
I have a text area in my react app and when I insert some xss code in there it gets executed. How can I prevent it?
b80cfc907f15ac2486d11fa9f9caa515
{ "intermediate": 0.44861212372779846, "beginner": 0.33028221130371094, "expert": 0.221105694770813 }
47,742
Переменная args получается через parser в питоне Она выдает вот такое значение Namespace(supplier_id='65bd5', json_cfg='[{"tz":"Europe/Moscow","start_time":"10:00","end_time":"21:00","sources":["10.8.6.82_badge.marya2"]}]', mode='select-source', index=None, source=None, max_try=15, high_priority=False, params=None) И потом к нему можно обращаться как args.supplier_id и тд. Как можно задать тоже самое через код
02e124e0fabfe8068e9a8f88239d02eb
{ "intermediate": 0.3584040105342865, "beginner": 0.3344143033027649, "expert": 0.3071817457675934 }
47,743
how to verify in python where symbolic link is pointing
05f17409a5d5eb34554e53d193da1869
{ "intermediate": 0.4130477011203766, "beginner": 0.24358849227428436, "expert": 0.34336382150650024 }
47,744
How to capture the client Ip address on asp.net core
4c0a4bf83452125d91162136eae0ba13
{ "intermediate": 0.3924889862537384, "beginner": 0.19444303214550018, "expert": 0.41306793689727783 }
47,745
I have this data Shift output Scrap Good Units A 85 5 80 A 96 4 92 A 89 7 82 A 84 6 78 A 91 5 86 A 90 6 84 A 79 3 76 A 79 5 74 A 90 6 84 A 87 6 81 A 90 5 85 A 88 6 82 A 98 4 94 A 93 3 90 A 85 6 79 A 90 7 83 A 91 6 85 A 101 5 96 A 98 6 92 A 93 3 90 B 95 7 88 B 78 11 67 B 83 9 74 B 98 10 88 B 96 6 90 B 84 9 75 B 86 6 80 B 98 6 92 B 78 8 70 B 88 9 79 B 89 9 80 B 116 6 110 B 73 11 62 B 90 10 80 B 97 6 91 B 85 10 75 B 109 7 102 B 87 10 77 B 97 7 90 B 71 11 60 C 92 3 89 C 104 0 104 C 88 2 86 C 98 3 95 C 81 0 81 C 79 4 75 C 71 1 70 C 94 4 90 C 82 3 79 C 90 5 85 C 77 5 72 C 65 4 61 C 81 5 76 C 95 0 95 C 87 4 83 C 65 6 59 C 70 3 67 C 90 6 84 C 100 3 97 C 84 5 79 Perform a statistical analysis and come up with a hypothesis and prove it.
b7832ba410b7200d18422dcfa5c716ef
{ "intermediate": 0.2731783092021942, "beginner": 0.30308353900909424, "expert": 0.4237380921840668 }
47,746
在# 将 4输入分开,构建新的相同模态结合的2输入,2分支 import math import logging from functools import partial from collections import OrderedDict from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F from timm.models.layers import to_2tuple from lib.models.layers.patch_embed import PatchEmbed, PatchEmbed_event, xcorr_depthwise from .utils import combine_tokens, recover_tokens from .vit import VisionTransformer from ..layers.attn_blocks import CEBlock from .new_counter_guide import Counter_Guide _logger = logging.getLogger(__name__) class VisionTransformerCE(VisionTransformer): """ Vision Transformer with candidate elimination (CE) module A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` - https://arxiv.org/abs/2010.11929 Includes distillation token & head support for `DeiT: Data-efficient Image Transformers` - https://arxiv.org/abs/2012.12877 """ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=True, representation_size=None, distilled=False, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., embed_layer=PatchEmbed, norm_layer=None, act_layer=None, weight_init='', ce_loc=None, ce_keep_ratio=None): super().__init__() if isinstance(img_size, tuple): self.img_size = img_size else: self.img_size = to_2tuple(img_size) self.patch_size = patch_size self.in_chans = in_chans self.num_classes = num_classes self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models self.num_tokens = 2 if distilled else 1 norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6) act_layer = act_layer or nn.GELU self.patch_embed = embed_layer( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) num_patches = self.patch_embed.num_patches self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.dist_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if distilled else None self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim)) self.pos_drop = nn.Dropout(p=drop_rate) self.pos_embed_event = PatchEmbed_event(in_chans=32, embed_dim=768, kernel_size=4, stride=4) dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule blocks = [] ce_index = 0 self.ce_loc = ce_loc for i in range(depth): ce_keep_ratio_i = 1.0 if ce_loc is not None and i in ce_loc: ce_keep_ratio_i = ce_keep_ratio[ce_index] ce_index += 1 blocks.append( CEBlock( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer, keep_ratio_search=ce_keep_ratio_i) ) self.blocks = nn.Sequential(*blocks) self.norm = norm_layer(embed_dim) self.init_weights(weight_init) # 添加交互模块counter_guide self.counter_guide = Counter_Guide(768, 768) def forward_features(self, z, x, event_z, event_x, mask_z=None, mask_x=None, ce_template_mask=None, ce_keep_rate=None, return_last_attn=False ): # 分支1 处理流程 B, H, W = x.shape[0], x.shape[2], x.shape[3] x = self.patch_embed(x) z = self.patch_embed(z) z += self.pos_embed_z x += self.pos_embed_x if mask_z is not None and mask_x is not None: mask_z = F.interpolate(mask_z[None].float(), scale_factor=1. / self.patch_size).to(torch.bool)[0] mask_z = mask_z.flatten(1).unsqueeze(-1) mask_x = F.interpolate(mask_x[None].float(), scale_factor=1. / self.patch_size).to(torch.bool)[0] mask_x = mask_x.flatten(1).unsqueeze(-1) mask_x = combine_tokens(mask_z, mask_x, mode=self.cat_mode) mask_x = mask_x.squeeze(-1) if self.add_cls_token: cls_tokens = self.cls_token.expand(B, -1, -1) cls_tokens = cls_tokens + self.cls_pos_embed if self.add_sep_seg: x += self.search_segment_pos_embed z += self.template_segment_pos_embed x = combine_tokens(z, x, mode=self.cat_mode) if self.add_cls_token: x = torch.cat([cls_tokens, x], dim=1) x = self.pos_drop(x) lens_z = self.pos_embed_z.shape[1] lens_x = self.pos_embed_x.shape[1] global_index_t = torch.linspace(0, lens_z - 1, lens_z).to(x.device) global_index_t = global_index_t.repeat(B, 1) global_index_s = torch.linspace(0, lens_x - 1, lens_x).to(x.device) global_index_s = global_index_s.repeat(B, 1) removed_indexes_s = [] # # 分支2 处理流程 event_x = self.pos_embed_event(event_x) event_z = self.pos_embed_event(event_z) event_x += self.pos_embed_x event_z += self.pos_embed_z event_x = combine_tokens(event_z, event_x, mode=self.cat_mode) if self.add_cls_token: event_x = torch.cat([cls_tokens, event_x], dim=1) lens_z = self.pos_embed_z.shape[1] lens_x = self.pos_embed_x.shape[1] global_index_t1 = torch.linspace(0, lens_z - 1, lens_z).to(event_x.device) global_index_t1 = global_index_t1.repeat(B, 1) global_index_s1 = torch.linspace(0, lens_x - 1, lens_x).to(event_x.device) global_index_s1 = global_index_s1.repeat(B, 1) removed_indexes_s1 = [] for i, blk in enumerate(self.blocks): # 第一个分支处理 x, global_index_t, global_index_s, removed_index_s, attn = \ blk(x, global_index_t, global_index_s, mask_x, ce_template_mask, ce_keep_rate) # 第二个分支处理 event_x, global_index_t1, global_index_s1, removed_index_s1, attn = \ blk(event_x, global_index_t1, global_index_s1, mask_x, ce_template_mask, ce_keep_rate) if self.ce_loc is not None and i in self.ce_loc: removed_indexes_s.append(removed_index_s) removed_indexes_s1.append(removed_index_s1) # 在第1层和第6层以及最后一层增加counter_guide模块 if i in [0,5,11]: enhanced_x, enhanced_event_x = self.counter_guide(x, event_x) # 将增强后的特征与原特征相加 x = x + enhanced_x event_x = event_x + enhanced_event_x # 应用LayerNorm归一化处理 x = self.norm(x) event_x = self.norm(event_x) x_cat = torch.cat([x,event_x], dim=1) x = x_cat aux_dict = { "attn": attn, "removed_indexes_s": removed_indexes_s, # used for visualization } return x, aux_dict def forward(self, z, x, event_z, event_x, ce_template_mask=None, ce_keep_rate=None, tnc_keep_rate=None, return_last_attn=False): x, aux_dict = self.forward_features(z, x, event_z, event_x, ce_template_mask=ce_template_mask, ce_keep_rate=ce_keep_rate,) return x, aux_dict def _create_vision_transformer(pretrained=False, **kwargs): model = VisionTransformerCE(**kwargs) if pretrained: if 'npz' in pretrained: model.load_pretrained(pretrained, prefix='') else: checkpoint = torch.load(pretrained, map_location="cpu") missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False) print('Load pretrained model from: ' + pretrained) return model def vit_base_patch16_224_ce(pretrained=False, **kwargs): """ ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929). """ model_kwargs = dict( patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) model = _create_vision_transformer(pretrained=pretrained, **model_kwargs) return model def vit_large_patch16_224_ce(pretrained=False, **kwargs): """ ViT-Large model (ViT-L/16) from original paper (https://arxiv.org/abs/2010.11929). """ model_kwargs = dict( patch_size=16, embed_dim=1024, depth=24, num_heads=16, **kwargs) model = _create_vision_transformer(pretrained=pretrained, **model_kwargs) return model中,第12层的处理: if i in [0,5,11]: enhanced_x, enhanced_event_x = self.counter_guide(x, event_x) # 将增强后的特征与原特征相加 x = x + enhanced_x event_x = event_x + enhanced_event_x ,其中import torch import torch.nn as nn import torch.nn.functional as F class Multi_Context(nn.Module): def __init__(self, input_channels, output_channels): # 修正了def init为def init super(Multi_Context, self).__init__() self.linear1 = nn.Linear(input_channels, output_channels) self.linear2 = nn.Linear(input_channels, output_channels) self.linear3 = nn.Linear(input_channels, output_channels) self.linear_final = nn.Linear(output_channels * 3, output_channels) def forward(self, x): x1 = F.relu(self.linear1(x)) x2 = F.relu(self.linear2(x)) x3 = F.relu(self.linear3(x)) x = torch.cat([x1, x2, x3], dim=-1) # Concatenate along the feature dimension x = self.linear_final(x) return x class Adaptive_Weight(nn.Module): def __init__(self, input_channels): # 修正了def init为def init super(Adaptive_Weight, self).__init__() self.fc1 = nn.Linear(input_channels, input_channels // 4) self.fc2 = nn.Linear(input_channels // 4, input_channels) self.sigmoid = nn.Sigmoid() def forward(self, x): x_avg = torch.mean(x, dim=1) # Global Average Pooling along the ‘sequence length’ dimension weight = F.relu(self.fc1(x_avg)) weight = self.fc2(weight) weight = self.sigmoid(weight).unsqueeze(1) out = x * weight # 此处的x是 enhanced_x 和 event_x 相乘的结果 return out class Counter_attention(nn.Module): def __init__(self, input_channels, output_channels): # 修正了def init为def init super(Counter_attention, self).__init__() self.mc = Multi_Context(input_channels, output_channels) # enhanced_x self.ada_w = Adaptive_Weight(output_channels) def forward(self, assistant, present): mc_output = self.mc(assistant) # enhanced_x weighted_present = self.ada_w(present * torch.sigmoid(mc_output)) # enhanced_x → sigmoid → * event_x return weighted_present class Counter_Guide(nn.Module): def __init__(self, input_channels, output_channels): # 简化输入参数 super(Counter_Guide, self).__init__() # 使用单一的Counter_attention模块 self.counter_atten = Counter_attention(input_channels, output_channels) # self.dropout = nn.Dropout(0.1) def forward(self, x, event_x): # 对两种模态特征每种进行一次互相作为assistant和present的增强过程 out_x = self.counter_atten(x, event_x) out_event_x = self.counter_atten(event_x, x) # out_x = self.dropout(out_x) # out_event_x = self.dropout(out_event_x) return out_x, out_event_x。现在分析一下第12层操作,counter_guide和后续的操作分别如何处理的?
c572c747ba4d46fe4c5ae8d61ab86ff1
{ "intermediate": 0.29621145129203796, "beginner": 0.4656831622123718, "expert": 0.2381054162979126 }
47,747
File "/appli/ostic/venv/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1379, in execute meth = statement._execute_on_connection AttributeError: 'Composed' object has no attribute '_execute_on_connection'query = sql.SQL("""CREATE TABLE IF NOT EXISTS "CS_{}" AS SELECT DISTINCT "NUMEN" FROM public WHERE "NUMEN" IS NOT NULL AND {} = %s""").format(sql.Identifier(nom_os), sql.Identifier(" rg")) connection.execute(query, (rg,))
74cc77b202753c05424c9b6862b78553
{ "intermediate": 0.4487437903881073, "beginner": 0.3170483708381653, "expert": 0.2342078685760498 }
47,748
@app.route("/add", methods=["POST"]) def add_annonce(): try: json_data = request.form.get('data') data = json.loads(json_data) if json_data else {} # Initialize a list to hold paths of saved images saved_image_paths = [] saved_video_path = None # Process images images = request.files.getlist("images") for image in images: filename = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f") + secure_filename(image.filename) save_path = os.path.join(app.config['UPLOAD_FOLDER'],filename) image.save(save_path) saved_image_paths.append(os.path.join(filename)) # Process video file, assuming there's one video with the form field name 'video' video = request.files.get('video') if video: video_filename = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f") + secure_filename(video.filename) video_save_path = os.path.join(app.config['UPLOAD_FOLDER'], video_filename) video.save(video_save_path) saved_video_path = video_filename # Or you may customize this path as needed # Update or add the video path to your data structure here data['video'] = saved_video_path data['images'] = saved_image_paths if saved_video_path: data['video'] = saved_video_path # Insert data into MongoDB result = Annonce_collection.insert_one(data) return jsonify({"message": "Data successfully inserted", "id": str(result.inserted_id)}), 201 except Exception as e: return jsonify({"error": str(e)}), 500 dosame thing for update @app.route("/annonce/update/<annonce_id>", methods=["PUT"]) def update_annonce(annonce_id): if not ObjectId.is_valid(annonce_id): return jsonify({"message": "Invalid ID format"}), 400 data = request.json result = Annonce_collection.update_one({"_id": ObjectId(annonce_id)}, {"$set": data}) if result.matched_count == 0: return jsonify({"message": "Announcement not found"}), 404 return jsonify({"message": "Announcement updated successfully"}), 200 do an update
c902f99a1c0b87fda14189677121f824
{ "intermediate": 0.29673638939857483, "beginner": 0.49473080039024353, "expert": 0.20853282511234283 }
47,749
I have csv file containing columns: image name, width, height, class, xmin, ymin, xmax, ymax. Write a python script to generate a text file for each image in yolo annotation format. That is class name x y w h. Here, x,y,w,h are normalized values which are obtained by dividing original x,y,w,h with width and height
026696b219cecfe1f30d2af995ef3deb
{ "intermediate": 0.4110800623893738, "beginner": 0.26471149921417236, "expert": 0.32420846819877625 }
47,750
In python I want to draw a graph using networkx. But I also want a menu on the top with 2 drops downs and a button. I will add code for what they do later.
22af160e5884423bca2ccf862f92b3e9
{ "intermediate": 0.414171427488327, "beginner": 0.13114292919635773, "expert": 0.45468565821647644 }
47,751
Could u rewrite this w/o using this
b4debcc0cda1d98be6331f47371d9965
{ "intermediate": 0.34754088521003723, "beginner": 0.36172211170196533, "expert": 0.29073694348335266 }
47,752
Hi there, please be a senior sapui5 developer and answer my following questions with working code examples.
0e0ceadc9268386c23fb5085dbfa0ac2
{ "intermediate": 0.42116406559944153, "beginner": 0.2712341248989105, "expert": 0.3076017498970032 }
47,753
I have this import tkinter as tk from tkinter import ttk import networkx as nx import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import json def load_network(file_path): # Load network from JSON file with open(file_path, 'r') as file: data = json.load(file) G = nx.Graph() # Add nodes G.add_nodes_from(data["nodes"]) # Add edges with attributes for path in data["paths"]: G.add_edge(path["path"][0], path["path"][1], distance=path["distance"], trafficCondition=path["trafficCondition"], deliveryUrgency=path["deliveryUrgency"]) return G def draw_graph(filePath): plt.clf() G = load_network(filePath) pos = nx.spring_layout(G) fig, ax = plt.subplots() nx.draw(G, pos, with_labels=True, node_color='skyblue', node_size=1200, edge_color='k', linewidths=0.5, font_size=15, ax=ax) canvas.draw() def on_dropdown1_select(event): filepathnum=dropdown1.current()+1 draw_graph("output" + str(filepathnum) +".json") # Create main window root = tk.Tk() root.title("Graph Visualization") # Create graph drawing area figure = plt.figure(figsize=(6, 4)) ax = figure.add_subplot(111) canvas = FigureCanvasTkAgg(figure, master=root) canvas_widget = canvas.get_tk_widget() canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=1) # Create menu widgets frame_menu = tk.Frame(root) frame_menu.pack(side=tk.TOP, pady=10) # Dropdown 1 options1 = ["Output 1", "Output 2", "Output 3", "Output 4", "Output 5"] file_path_var = ["output1.json", "output2.json", "output3.json", "output4.json", "output5.json"] dropdown1 = ttk.Combobox(frame_menu, values=options1, textvariable=file_path_var) dropdown1.set(options1[0]) dropdown1.bind("<<ComboboxSelected>>", on_dropdown1_select) dropdown1.grid(row=0, column=0, padx=5) # Draw initial graph draw_graph("output1.json") # Start GUI event loop root.mainloop() How can I clear what was previously drawn by networkx before I draw something else
704783d1558995d6afa9dfc45bdba2d1
{ "intermediate": 0.6026609539985657, "beginner": 0.23627744615077972, "expert": 0.1610615849494934 }
47,754
4Question 2: Need For Speed 4.1Introduction Lukarp has started his own tech company. He received a lot of funding from Igen with which he opened many offices around the world. Each office needs to communicate with one other, for which they’re using high speed connections between the offices. Office number 1 is Lukarp’s HQ. Some offices are important and hence need faster connections to the HQ for which Lukarp has use special fiber connections. Lukarp has already planned the connections but feels some fiber connections are redundant. You have been hired by Lukarp to remove those fiber connections which don’t cause faster connections. 4.2Problem Statement 4.2.1The Problem The offices and (bi-directional) connections (both normal and fiber) are given to you. HQ is numbered as 1. The ith normal connection connects any two offices ai and bi . Normal connections have latency li . The ith fiber connection connects the HQ with the office ci . Fiber connections also come with a latency pi . The total latency of a path is the sum of latencies on the connections. You are to output the maximum number of fiber connections that can be removed, such that the latency of the smallest latency path between the HQ and any other node remains the same as before. • There are n offices with m normal connections and k high-speed fiber connections. • The ith normal connection connects offices ai and bi (bi-directionally) with latency li . • The ith fiber connection connects offices 1 and ci (bi-directionally) with latency pi . 4.2.2 Input Format The first line of the input file will contain three space-separated integers n, m and k, the number of offices, the number of normal connections and the number of fiber connections. There will be m lines after this, the ith line signifying the ith normal connection, each containing three space-separated integers ai , bi and li the two offices that are connected and the latency of the connection respectively. There will be k lines after this, the ith line signifying the ith fiber connection, each containing three space-separated integers ci and pi , the office connected to the HQ and the latency of the fiber connection respectively. 64.2.3 Output Format Output only one integer m - the maximum number of fiber connections that can be removed without changing the latency of smallest latency path from office 1 to any other office. 4.2.4 Constraints • 2 ≤ n ≤ 105 • 1 ≤ m ≤ 2 · 105 • 1 ≤ k ≤ 105 • 1 ≤ ai , bi , ci ≤ n • 1 ≤ li , pi ≤ 109 4.2.5 Example Input: 4 5 2 1 2 2 1 4 9 1 3 3 2 4 4 3 4 5 3 4 4 5 Output: 1 Explanation: In this example, there are five normal connections as shown in the figure below. The fiber connection going from 1 to 3 can be removed because the normal con- nection (3) is faster than the fiber connection (4). However, the fiber connection with 4 cannot be removed. Hence the maximum number of fiber connections that can be removed is 1. also keep into consideration that a fiber path to node A can be a part of the shortest path to node B give c++ code you can do it using a struct and dijkstra . dont use many advanced functions of c++. try to keep it beginner level code. dont worry about time efficiency.
485b3f391267183b0dccf0234a9e99a0
{ "intermediate": 0.2716849744319916, "beginner": 0.47465693950653076, "expert": 0.25365808606147766 }
47,755
how to extract latitude and longitude from a zipcode in teradata
7dff825944df9b32478b2ad6234d8e72
{ "intermediate": 0.36802762746810913, "beginner": 0.37238091230392456, "expert": 0.2595914900302887 }
47,756
Is this the proper way to use two loras on the same diffusers pipe: pipe = StableDiffusionPipeline.from_pretrained( base_model_path, torch_dtype=torch.float16, scheduler=noise_scheduler, vae=vae, safety_checker=None ).to(device) #pipe.load_lora_weights("h94/IP-Adapter-FaceID", weight_name="ip-adapter-faceid-plusv2_sd15_lora.safetensors") #pipe.fuse_lora() pipe.load_lora_weights("OedoSoldier/detail-tweaker-lora", weight_name="add_detail.safetensors") pipe.fuse_lora() pipe.load_lora_weights("adhikjoshi/epi_noiseoffset", weight_name="epiNoiseoffset_v2.safetensors") pipe.fuse_lora()
c6fbce14ea02c06f09a3a23fcb0aea29
{ "intermediate": 0.3753963112831116, "beginner": 0.3496910333633423, "expert": 0.27491265535354614 }
47,757
I am using diffusers to create images. Is there a way to add 'strength' of the lora when using it in this way: pipe = StableDiffusionPipeline.from_pretrained( base_model_path, torch_dtype=torch.float16, scheduler=noise_scheduler, vae=vae, safety_checker=None ).to(device) pipe.load_lora_weights("OedoSoldier/detail-tweaker-lora", weight_name="add_detail.safetensors") pipe.fuse_lora()
bd8399d7893de659a8f140eb5c803c01
{ "intermediate": 0.4094417095184326, "beginner": 0.2886768579483032, "expert": 0.30188143253326416 }
47,758
write a Rust function to return the network's up usage, the bytes sent by the network interface(s)
997e3b63fcc4cc0a4654932ec46d1eb1
{ "intermediate": 0.3372700810432434, "beginner": 0.28216251730918884, "expert": 0.3805674612522125 }
47,759
I am making a c++ sdl based game engine, currently in an stage of moving all my raw pointers into smart pointers. I already finished several classes, and I already know how to do it. The thing is, when I was revisiting old code to convert, I found out my VertexCollection class (it wraps SDL_Vertex and adds more functionalities to it) has a SetTexture method which use a raw Texture pointer, Texture is my own class which wraps SDL_Texture and adds more functionalities to it and I don't know if I should just use an object and use a make_unique or receive the smart pointer and use std::move. 1) void VertexCollection::SetTexture(std::unique_ptr<Texture> texture) { if (texture) { this->texture = std::move(texture); } } 2) void VertexCollection::SetTexture(const Texture& texture) { this->texture = std::make_unique<Texture>(texture); } Which of these options is better?
966c3aaf6418f8002992a7a88b6177e0
{ "intermediate": 0.4477916359901428, "beginner": 0.40150511264801025, "expert": 0.15070326626300812 }
47,760
模型通过三个head得到响应输出,即Rf(RGB输出);Re(event输出);Rc(融合特征输出)。此时为了探索不同模态信息对跟踪任务的重要程度,设计了自适应模态响应决策机制,使得网络在学习的过程中判断利用RGB模态信息、Event模态信息还是融合模态信息,以提升特征信息利用的灵活性,最大化模型性能。那么基于""" Basic ceutrack model. """ import math import os from typing import List import torch from torch import nn from torch.nn.modules.transformer import _get_clones from lib.models.layers.head import build_box_head from lib.models.ceutrack.vit import vit_base_patch16_224 from lib.models.ceutrack.vit_ce import vit_large_patch16_224_ce, vit_base_patch16_224_ce # from lib.models.ceutrack.vit_ce_BACKUPS import vit_large_patch16_224_ce, vit_base_patch16_224_ce from lib.utils.box_ops import box_xyxy_to_cxcywh class CEUTrack(nn.Module): """ This is the base class for ceutrack """ def __init__(self, transformer, box_head, aux_loss=False, head_type="CORNER"): """ Initializes the model. Parameters: transformer: torch module of the transformer architecture. aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used. """ super().__init__() self.backbone = transformer self.box_head_x = box_head # 新增event模态的head,以输出独立模态响应 self.box_head_event_x = box_head self.aux_loss = aux_loss self.head_type = head_type if head_type == "CORNER" or head_type == "CENTER": self.feat_sz_s = int(box_head.feat_sz) self.feat_len_s = int(box_head.feat_sz ** 2) if self.aux_loss: self.box_head = _get_clones(self.box_head, 6) def forward(self, template: torch.Tensor, search: torch.Tensor, event_template: torch.Tensor, # torch.Size([4, 1, 19, 10000]) event_search: torch.Tensor, # torch.Size([4, 1, 19, 10000]) ce_template_mask=None, ce_keep_rate=None, return_last_attn=False, ): # before feeding into backbone, we need to concat four vectors, or two two concat; x, event_x, aux_dict = self.backbone(z=template, x=search, event_z=event_template, event_x=event_search, ce_template_mask=ce_template_mask, ce_keep_rate=ce_keep_rate, return_last_attn=return_last_attn, ) # Forward head for x feat_last = x if isinstance(x, list): feat_last_x = x[-1] out_x = self.forward_head_x(feat_last_x, None) # Forward head for event_x feat_last_event_x = event_x if isinstance(event_x, list): feat_last_event_x = event_x[-1] out_event_x = self.forward_head_event_x(feat_last_event_x, None) # 新增 fusion of response fused_output = self.fuse_outputs(out_x,out_event_x) # update aux_dict fused_output.update(fused_output) return fused_output # 单独构建forward_head def forward_head_x(self, cat_feature_x, gt_score_map=None): """ Forward pass for the head of x modality. """ # dual head enc_opt1_x = cat_feature_x[:, -self.feat_len_s:] enc_opt2_x = cat_feature_x[:, :self.feat_len_s] enc_opt_x = torch.cat([enc_opt1_x, enc_opt2_x], dim=-1) opt_x = (enc_opt_x.unsqueeze(-1)).permute((0, 3, 2, 1)).contiguous() bs, Nq, C, HW = opt_x.size() opt_feat_x = opt_x.view(-1, C, self.feat_sz_s, self.feat_sz_s) # Forward pass for x modality if self.head_type == "CORNER": pred_box_x, score_map_x = self.box_head_x(opt_feat_x, True) outputs_coord_x = box_xyxy_to_cxcywh(pred_box_x) outputs_coord_new_x = outputs_coord_x.view(bs, Nq, 4) out_x = {'pred_boxes_x': outputs_coord_new_x, 'score_map_x': score_map_x} return out_x elif self.head_type == "CENTER": score_map_ctr_x, bbox_x, size_map_x, offset_map_x = self.box_head_x(opt_feat_x, gt_score_map) outputs_coord_x = bbox_x outputs_coord_new_x = outputs_coord_x.view(bs, Nq, 4) out_x = {'pred_boxes_x': outputs_coord_new_x, 'score_map_x': score_map_ctr_x, 'size_map_x': size_map_x, 'offset_map_x': offset_map_x} return out_x else: raise NotImplementedError # Event模态响应forward head def forward_head_event_x(self, cat_feature_event_x, gt_score_map=None): """ Forward pass for the head of event_x modality. """ # dual head enc_opt1_event_x = cat_feature_event_x[:, -self.feat_len_s:] enc_opt2_event_x = cat_feature_event_x[:, :self.feat_len_s] enc_opt_event_x = torch.cat([enc_opt1_event_x, enc_opt2_event_x], dim=-1) opt_event_x = (enc_opt_event_x.unsqueeze(-1)).permute((0, 3, 2, 1)).contiguous() bs, Nq, C, HW = opt_event_x.size() opt_feat_event_x = opt_event_x.view(-1, C, self.feat_sz_s, self.feat_sz_s) # Forward pass for event_x modality if self.head_type == "CORNER": pred_box_event_x, score_map_event_x = self.box_head_event_x(opt_feat_event_x, True) outputs_coord_event_x = box_xyxy_to_cxcywh(pred_box_event_x) outputs_coord_new_event_x = outputs_coord_event_x.view(bs, Nq, 4) out_event_x = {'pred_boxes_event_x': outputs_coord_new_event_x, 'score_map_event_x': score_map_event_x} return out_event_x elif self.head_type == "CENTER": score_map_ctr_event_x, bbox_event_x, size_map_event_x, offset_map_event_x = self.box_head_event_x( opt_feat_event_x, gt_score_map) outputs_coord_event_x = bbox_event_x outputs_coord_new_event_x = outputs_coord_event_x.view(bs, Nq, 4) out_event_x = {'pred_boxes_event_x': outputs_coord_new_event_x, 'score_map_event_x': score_map_ctr_event_x, 'size_map_event_x': size_map_event_x, 'offset_map_event_x': offset_map_event_x} return out_event_x else: raise NotImplementedError def fuse_outputs(self, out_x, out_event_x): fused_pred_boxes = out_x['pred_boxes'] + out_event_x['pred_boxes'] fused_score_map = out_x['score_map'] + out_event_x['score_map'] fused_output = { 'pred_boxes': fused_pred_boxes, 'score_map': fused_score_map, } return fused_output def build_ceutrack(cfg, training=True): current_dir = os.path.dirname(os.path.abspath(__file__)) # This is your Project Root pretrained_path = os.path.join(current_dir, 'pretrained_models') if cfg.MODEL.PRETRAIN_FILE and ('CEUTrack' not in cfg.MODEL.PRETRAIN_FILE) and training: pretrained = os.path.join(pretrained_path, cfg.MODEL.PRETRAIN_FILE) else: pretrained = '' if cfg.MODEL.BACKBONE.TYPE == 'vit_base_patch16_224': backbone = vit_base_patch16_224(pretrained, drop_path_rate=cfg.TRAIN.DROP_PATH_RATE) hidden_dim = backbone.embed_dim patch_start_index = 1 elif cfg.MODEL.BACKBONE.TYPE == 'vit_base_patch16_224_ce': backbone = vit_base_patch16_224_ce(pretrained, drop_path_rate=cfg.TRAIN.DROP_PATH_RATE, ce_loc=cfg.MODEL.BACKBONE.CE_LOC, ce_keep_ratio=cfg.MODEL.BACKBONE.CE_KEEP_RATIO, ) # hidden_dim = backbone.embed_dim hidden_dim = backbone.embed_dim * 2 patch_start_index = 1 elif cfg.MODEL.BACKBONE.TYPE == 'vit_large_patch16_224_ce': backbone = vit_large_patch16_224_ce(pretrained, drop_path_rate=cfg.TRAIN.DROP_PATH_RATE, ce_loc=cfg.MODEL.BACKBONE.CE_LOC, ce_keep_ratio=cfg.MODEL.BACKBONE.CE_KEEP_RATIO, ) hidden_dim = backbone.embed_dim patch_start_index = 1 else: raise NotImplementedError backbone.finetune_track(cfg=cfg, patch_start_index=patch_start_index) box_head_x = build_box_head(cfg, hidden_dim) box_head_event_x = build_box_head(cfg, hidden_dim) model = CEUTrack( backbone, box_head_x, box_head_event_x, aux_loss=False, head_type=cfg.MODEL.HEAD.TYPE, ) if 'CEUTrack' in cfg.MODEL.PRETRAIN_FILE and training: checkpoint = torch.load(cfg.MODEL.PRETRAIN_FILE, map_location="cpu") missing_keys, unexpected_keys = model.load_state_dict(checkpoint["net"], strict=False) print('Load pretrained model from: ' + cfg.MODEL.PRETRAIN_FILE) return model 按照需求,写一段代码
4d325cbfd188dc949ae1c0242c822f94
{ "intermediate": 0.30486300587654114, "beginner": 0.48184919357299805, "expert": 0.2132878452539444 }
47,761
hi, can you make a ffmpeg 6.0 arg showing for capture of xwininfo using xwininfo: Window id to record a window on with specified id for example you can use this testing id like:xwininfo: Window id: 0x1e0901c
7eebf3702c42c106698825a5d448fc74
{ "intermediate": 0.614904522895813, "beginner": 0.11286090314388275, "expert": 0.27223458886146545 }
47,762
in this code the states is a tuple of containing 'states = (node_features_tensor, edge_feature_tensor, edge_index)' but i need to access the node feature tensor, where it contains the 20 nodes and in each node the 24 feature represents its stability, from the stability information i need to calculate the loss. But i am getting error from the below code please rectify the error. stabilities = states[:, :, 23] stability_loss = self.compute_stability_loss(stabilities, target_stability=1.0) def compute_stability_loss(self, stabilities, target_stability=1.0): """Compute stability loss based on stabilities tensor.""" stability_loss = F.binary_cross_entropy_with_logits(stabilities, torch.full_like(stabilities, fill_value=target_stability)) return stability_loss
e4dec18fa48c178f082c87f2901be8ff
{ "intermediate": 0.3498559594154358, "beginner": 0.2287786900997162, "expert": 0.421365350484848 }
47,763
will this code work and why? explain step by step for a complete beginner: // index.js await async function () { console.log("Hello World!"); };
611fe9bea21107003233d587b808e52c
{ "intermediate": 0.3919016122817993, "beginner": 0.4442380368709564, "expert": 0.16386036574840546 }
47,764
i have this bootstrap nav bar <nav class="navbar navbar-expand-lg navbar-light bg-light"> <nav class="navbar navbar-expand-lg navbar-light bg-light vf-navbar"> <div class="navbar-collapse w-100 dual-collapse2"> <a class="navbar-brand" routerLink="/"><img src="assets/imgs/vf-logo-red.png"></a> <ul class="navbar-nav"> <li class="nav-item"> <h3 class="storeNameTitle">Vodafone OMS</h3> </li> </ul> </div> <div class="w-100"> <ul class="navbar-nav w-100 justify-content-end align-items-baseline"> <li class="nav-item dropdown" ngbDropdown> <a aria-expanded="false" aria-haspopup="true" class="nav-link dropdown-toggle dropdown-toggle-caret" data-toggle="dropdown" href="javascript:void(0)" id="logoutDropdown" ngbDropdownToggle role="button"> <i class="fa-solid fa-user"></i> BindinguserInfo?.username </a> <div aria-labelledby="logoutDropdown" class="dropdown-menu dropdown-menu-end" ngbDropdownMenu> <a class="dropdown-item" ngbDropdownItem>Logout</a> <!--(click)="logOut()" --> </div> </li> </ul> </div> </nav> i want to make the brand logo and name at max left and the username at the max right
3e6b9a7ec3873563eea8fa9c041040e0
{ "intermediate": 0.32471615076065063, "beginner": 0.3943037688732147, "expert": 0.28098002076148987 }
47,765
will you please just take this String as an example and create a generale regexp to extract episode number ?Il.clandestino.S01E01.ITA.WEBDL.1080p.mp4 from this I just want E01 and even better 1
5102689ac7d70056f6b4feb7b40ee2be
{ "intermediate": 0.3938535451889038, "beginner": 0.2430206537246704, "expert": 0.36312583088874817 }
47,766
<ul class="navbar-nav"> <li class="nav-item dropdown" > <a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Osama </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item">Logout</a> </div> </li> </ul> i have this in angular project but dropdown menu didn't work
7fc4eee17f909abd3de3fc53114b05cd
{ "intermediate": 0.486283540725708, "beginner": 0.3025490641593933, "expert": 0.21116742491722107 }
47,767
will you please just take this String as an example and create a generale regexp to extract episode number ?Il.clandestino.S01E01.ITA.WEBDL.1080p.mp4 from this I just want E01 and even better 1
5ec23c437dcdb197e7d5fc626442bbb4
{ "intermediate": 0.3938535451889038, "beginner": 0.2430206537246704, "expert": 0.36312583088874817 }
47,768
I want a script to hide fields inside this form : "name="vat_number" name="company" " just hide them and show a checkbox instead to show them if it is checked "company" <div class="js-address-form"> <form method="POST" action="https://woodiz.fr/commande" data-refresh-url="//woodiz.fr/commande?ajax=1&amp;action=addressForm"> <p> L'adresse sélectionnée sera utilisée à la fois comme adresse personnelle (pour la facturation) et comme adresse de livraison. </p> <div id="delivery-address"> <div class="js-address-form"> <section class="form-fields"> <input type="hidden" name="id_address" value=""> <input type="hidden" name="id_customer" value=""> <input type="hidden" name="back" value=""> <input type="hidden" name="token" value="b9beaf896066c4cebd62b5ce225273d5"> <div class="form-group row "> <label class="col-md-3 form-control-label required"> Prénom </label> <div class="col-md-6"> <input class="form-control" name="firstname" type="text" value="Testing" maxlength="255" required=""> </div> <div class="col-md-3 form-control-comment"> </div> </div> <div class="form-group row "> <label class="col-md-3 form-control-label required"> Nom </label> <div class="col-md-6"> <input class="form-control" name="lastname" type="text" value="Mohamed" maxlength="255" required=""> </div> <div class="col-md-3 form-control-comment"> </div> </div> <div class="form-group row "> <label class="col-md-3 form-control-label"> Société </label> <div class="col-md-6"> <input class="form-control" name="company" type="text" value="" maxlength="255"> </div> <div class="col-md-3 form-control-comment"> Optionnel </div> </div> <div class="form-group row "> <label class="col-md-3 form-control-label"> Numéro de TVA </label> <div class="col-md-6"> <input class="form-control" name="vat_number" type="text" value=""> </div> <div class="col-md-3 form-control-comment"> Optionnel </div> </div> <div class="form-group row "> <label class="col-md-3 form-control-label required"> Adresse </label> <div class="col-md-6"> <input class="form-control" name="address1" type="text" value="" maxlength="128" required=""> </div> <div class="col-md-3 form-control-comment"> </div> </div> <div class="form-group row "> <label class="col-md-3 form-control-label"> Complément d'adresse </label> <div class="col-md-6"> <input class="form-control" name="address2" type="text" value="" maxlength="128"> </div> <div class="col-md-3 form-control-comment"> Optionnel </div> </div> <div class="form-group row "> <label class="col-md-3 form-control-label required"> Code postal </label> <div class="col-md-6"> <input class="form-control" name="postcode" type="text" value="" maxlength="12" required=""> </div> <div class="col-md-3 form-control-comment"> </div> </div> <div class="form-group row "> <label class="col-md-3 form-control-label required"> Ville </label> <div class="col-md-6"> <input class="form-control" name="city" type="text" value="" maxlength="64" required=""> </div> <div class="col-md-3 form-control-comment"> </div> </div> <div class="form-group row "> <label class="col-md-3 form-control-label required"> Pays </label> <div class="col-md-6"> <select class="form-control form-control-select js-country" name="id_country" required=""> <option value="" disabled="" selected="">-- veuillez choisir --</option> <option value="8" selected="">France</option> </select> </div> <div class="col-md-3 form-control-comment"> </div> </div> <div class="form-group row "> <label class="col-md-3 form-control-label required"> Téléphone </label> <div class="col-md-6"> <input class="form-control" name="phone" type="tel" value="" maxlength="32" required=""> </div> <div class="col-md-3 form-control-comment"> </div> </div> <input type="hidden" name="saveAddress" value="delivery"> <div class="form-group row"> <div class="col-md-9 col-md-offset-3"> <input name="use_same_address" type="checkbox" value="1" checked=""> <label>Utiliser aussi cette adresse pour la facturation</label> </div> </div> </section> <footer class="form-footer clearfix"> <input type="hidden" name="submitAddress" value="1"> <button type="submit" class="continue btn btn-primary float-xs-right" name="confirm-addresses" value="1"> Continuer </button> </footer> </div> </div></form> </div>
433a143c51468b21b250969ed4ae11a0
{ "intermediate": 0.3460944890975952, "beginner": 0.4107333719730377, "expert": 0.24317209422588348 }
47,769
<ul class="navbar-nav"> <li class="nav-item dropdown" ngbDropdown> <a aria-expanded="false" aria-haspopup="true" class="nav-link dropdown-toggle dropdown-toggle-caret" data-toggle="dropdown" href="javascript:void(0)" id="logoutDropdown" ngbDropdownToggle role="button"> <i class="fa-solid fa-user"></i> BindinguserInfo?.username </a> <div aria-labelledby="logoutDropdown" class="dropdown-menu dropdown-menu-end" ngbDropdownMenu> <a (click)="logOut()"class="dropdown-item" ngbDropdownItem>Logout</a> <!--(click)="logOut()" --> </div> </li> </ul> drop down didn't work
6b00d5f44c110396525e81278b81cfbb
{ "intermediate": 0.39106059074401855, "beginner": 0.3551487922668457, "expert": 0.25379064679145813 }
47,770
install command in cmake
c9f8622523b9241bb0c61570fba5612b
{ "intermediate": 0.4322913885116577, "beginner": 0.189520925283432, "expert": 0.3781876564025879 }
47,771
In workflow, we notify user via email with a confirmation of yes or no and after that i have a stage called wait for user confirmation and according to user yes or no stage will proceed further, but i want if the user hasnt give confirmation in 1 day , the workflow stage takes the response as yes automatically and proceed the workflow further.
09df80786dbc888a01ecaf812dcdcd70
{ "intermediate": 0.6342465281486511, "beginner": 0.12357044965028763, "expert": 0.24218297004699707 }
47,772
this is my code: pub fn test( c_fivends: &[(u64, u64)], c_exons: &[(u64, u64)], c_introns: &[(u64, u64)], tx_exons: &[&(u64, u64)], id: &Arc<str>, // flags -> (skip_exon [0: true, 1: false], nt_5_end) flags: &HashSet<(u64, u64)>, line: String, ) { let tx_5end = tx_exons[0]; let (skip, _) = flags.iter().next().unwrap(); let status = match c_fivends.interval_search(&tx_5end) { // is inside Some((s, e)) => { // starts differ if s != tx_5end.0 { match skip { 1 => FivePrimeStatus::TruncatedInExon, _ => FivePrimeStatus::Complete, } } else { // starts are equal FivePrimeStatus::Complete } } // is not inside -> check c_exons overlap None => match c_exons.interval_search(&tx_5end) { Some((ex_s, ex_e)) => { if ex_s != tx_5end.0 { match skip { 1 => FivePrimeStatus::TruncatedInExon, _ => FivePrimeStatus::Complete, } } else { // starts are equal FivePrimeStatus::Complete } } None => FivePrimeStatus::Complete, }, }; } pub trait IntervalSearch<T> { fn interval_search(&self, query: &(T, T)) -> Option<(T, T)> where T: PartialOrd + Copy; } impl<T> IntervalSearch<T> for Vec<(T, T)> { fn interval_search(&self, query: &(T, T)) -> Option<(T, T)> where T: PartialOrd + Copy, { let mut start = 0; let mut end = self.len(); while start < end { let mid = start + (end - start) / 2; let mid_val = self[mid]; if query.1 <= mid_val.0 { end = mid; } else if query.0 >= mid_val.1 { start = mid + 1; } else { return Some(mid_val); } } None } } I got this error: error[E0599]: no method named `interval_search` found for reference `&[(u64, u64)]` in the current scope --> src/bif/fivend.rs:186:34 | 186 | let status = match c_fivends.interval_search(&tx_5end) { | ^^^^^^^^^^^^^^^ help: there is a meth od with a similar name: `binary_search` | = help: items from traits can only be used if the trait is implemented a nd in scope note: `IntervalSearch` defines an item `interval_search`, perhaps you need t o implement it --> src/bif/fivend.rs:218:1 | 218 | pub trait IntervalSearch<T> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0599]: no method named `interval_search` found for reference `&[(u64, u64)]` in the current scope --> src/bif/fivend.rs:201:31 | 201 | None => match c_exons.interval_search(&tx_5end) { | ^^^^^^^^^^^^^^^ help: there is a method with a similar name: `binary_search` | = help: items from traits can only be used if the trait is implemented a nd in scope note: `IntervalSearch` defines an item `interval_search`, perhaps you need t o implement it --> src/bif/fivend.rs:218:1 | 218 | pub trait IntervalSearch<T> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
c50325f1bc243662ebe5407a07f8172e
{ "intermediate": 0.3707680404186249, "beginner": 0.38088247179985046, "expert": 0.24834948778152466 }
47,773
i have a stack group <Stack.Group screenOptions={{ presentation: "modal" }}> <Stack.Screen options={{ headerShown: false }} name="Doc" component={Doc} onPress={() => navigation.navigate('Web')} /> </Stack.Group> and i want access in other component with this snippet : <SafeAreaView style={{ flex: 1 }}> <WebView source={{ uri: 'env.urlCompte' }} /> </SafeAreaView>
671568b99f6026ab3a42ed52e06f3367
{ "intermediate": 0.34635117650032043, "beginner": 0.29405003786087036, "expert": 0.3595988154411316 }
47,774
In servicenow, In workflow, we notify user via email with a confirmation of yes or no via create event activity in workflow and after that i have a property called wait for condition in workflow and according to user yes or no stage will proceed further, but i want if the user hasnt give confirmation in 1 day , the workflow stage takes the response as yes automatically and proceed the workflow further.
1bd99564bad956981f7340cfc5552e29
{ "intermediate": 0.6144760847091675, "beginner": 0.16574636101722717, "expert": 0.21977755427360535 }
47,775
Question 2: Need For Speed 4.1 Introduction Lukarp has started his own tech company. He received a lot of funding from Igen with which he opened many offices around the world. Each office needs to communicate with one other, for which they’re using high speed connections between the offices. Office number 1 is Lukarp’s HQ. Some offices are important and hence need faster connections to the HQ for which Lukarp has use special fiber connections. Lukarp has already planned the connections but feels some fiber connections are redundant. You have been hired by Lukarp to remove those fiber connections which don’t cause faster connections. 4.2 Problem Statement 4.2.1 The Problem The offices and (bi-directional) connections (both normal and fiber) are given to you. HQ is numbered as 1. The ith normal connection connects any two offices ai and bi. Normal connections have latency li. The ith fiber connection connects the HQ with the office ci. Fiber connections also come with a latency pi. The total latency of a path is the sum of latencies on the connections. You are to output the maximum number of fiber connections that can be removed, such that the latency of the smallest latency path between the HQ and any other node remains the same as before. • There are n offices with m normal connections and k high-speed fiber connections. • The ith normal connection connects offices ai and bi (bi-directionally) with latency li. • The ith fiber connection connects offices 1 and ci (bi-directionally) with latency pi. 4.2.2 Input Format The first line of the input file will contain three space-separated integers n, m and k, the number of offices, the number of normal connections and the number of fiber connections. There will be m lines after this, the ith line signifying the ith normal connection, each containing three space-separated integers ai, bi and li the two offices that are connected and the latency of the connection respectively. There will be k lines after this, the ith line signifying the ith fiber connection, each containing three space-separated integers ci and pi, the office connected to the HQ and the latency of the fiber connection respectively. 6 4.2.3 Output Format Output only one integer m - the maximum number of fiber connections that can be removed without changing the latency of smallest latency path from office 1 to any other office. 4.2.4 Constraints • 2≤n≤105 • 1≤m≤2·105 • 1≤k≤105 • 1≤ai,bi,ci ≤n • 1≤li,pi ≤109 4.2.5 Example Input: 452 122 149 133 244 345 34 45 Output: 1 Explanation: In this example, there are five normal connections as shown in the figure below. The fiber connection going from 1 to 3 can be removed because the normal con- nection (3) is faster than the fiber connection (4). However, the fiber connection with 4 cannot be removed. Hence the maximum number of fiber connections that can be removed is 1. 7 Figure 3: Normal Connections and their latencies 8
3e75d279a16315d4f7aa5a522d9eb4a9
{ "intermediate": 0.3268553614616394, "beginner": 0.29196256399154663, "expert": 0.3811820447444916 }
47,776
hi, can you correct this arg for linux ffmpeg 6.0: ffmpeg -f x11grab -framerate 30 $(xwininfo | gawk 'match($0, -geometry ([0-9]+x[0-9]+).([0-9]+).([0-9]+)/, a)\{ print "-video_size " a[1] " -i +" a[2] "," a[3] }') -c:v libx264rgb -preset slow -t 5 -pass 1 -an -f null /dev/null && \ ffmpeg -i /dev/null -c:v libx264rgb -preset slow -f alsa -ac 2 -i pulse -t 5 -pass 2 $(date +%Y-%m-%d_%H-%M_%S).mkv
9c23747db3f6b0292f5a880582660f06
{ "intermediate": 0.36336153745651245, "beginner": 0.5234166979789734, "expert": 0.11322171241044998 }
47,777
Hi, cany you correct this ffmpeg 6.0 arg: ffmpeg -f x11grab -framerate 30 $(xwininfo | gawk 'match($0, -geometry ([0-9]+x[0-9]+).([0-9]+).([0-9]+)/, a)\{ print "-video_size " a[1] " -i +" a[2] "," a[3] }') -c:v libx264rgb -preset slow -t 5 -pass 1 -an -f null /dev/null && \ ffmpeg -i /dev/null -c:v libx264rgb -preset slow -f alsa -ac 2 -i pulse -t 5 -pass 2 $(date +%Y-%m-%d_%H-%M_%S).mkv
1ebec0675955acad16d921aa41c3c401
{ "intermediate": 0.3601072430610657, "beginner": 0.48958253860473633, "expert": 0.15031027793884277 }
47,778
hi can you correct this ffmpeg arg: ffmpeg -f x11grab -framerate 30 $(xwininfo | gawk 'match($0, -geometry ([0-9]+x[0-9]+).([0-9]+).([0-9]+)/, a)\{ print "-video_size " a[1] " -i +" a[2] "," a[3] }') -c:v libx264rgb -preset slow -t 5 -pass 1 -an -f null /dev/null && \ ffmpeg -i /dev/null -c:v libx264rgb -preset slow -f alsa -ac 2 -i pulse -t 5 -pass 2 $(date +%Y-%m-%d_%H-%M_%S).mkv
8dfdf0772506d1591a777f0528720e44
{ "intermediate": 0.41401875019073486, "beginner": 0.48244181275367737, "expert": 0.10353948920965195 }
47,779
Write a python script that does the following 1. Ask for two numbers call them "start" and "max". 2. Produce and show a number sequence beginning from "start" and having "max" numbers such that each number in the sequence except the last two numbers is the average of the next two numbers that are right to it in the sequence.
0d8350bcbb911453040901b2db287128
{ "intermediate": 0.4470610022544861, "beginner": 0.19975365698337555, "expert": 0.35318535566329956 }
47,780
Nominal scales Nominal scales are used for naming and categorizing data in a variable - usually in the form of identifying groups into which people fall. Membership in such groups may occur either naturally (as in the sex or nationality groupings just discussed) or artificially (as in a study that assigns students to different experimental and control groups). On a particular nominal scale, each observation usually falls into only one category. The next observation may fall into a different category, but it, too, will fall only into one such category. Examples of variables that group people naturally include sex, nationality, native language, social and economic status, level of study in a language and a specific like or dislike (e.g., whether the subjects like studying grammar rules). Artificially occurring variables might include membership in an experimental or control group and membership in a particular class or language pro-gram. So the essence of the nominal scale is that it names categories into which people fall, naturally or artificially. One source of confusion with this type of scale is that it is variously labeled a discrete, discontinuous, categorical, or even dichotomous scale (in the special case of only two categories). In this book, I will always call this type of scale nominal. Ordinal scales Unlike a nominal scale, an ordinal scale is used to order, or rank, data. For instance, if you were interested in ranking your students from best to worst on the basis of their final examination scores (with 1 representing the best; 2, the next best; and 30 being the worst), you would be dealing with an ordinal scale. In our field, numerous rankings may be of concern, including ranking students in a class, ranking teachers in a center, or even ranking grammatical structures in a language (e.g., in French tenses, subjonctif is more difficult than the passé composé, which is more difficult than the present). In an ordinal scale, then, each point on the scale is ranked as "more than" and "less than" the other points on the scale. The points are then lined up and numbered first, second, third, and so on. Interval scales Interval scales also represent the ordering of things. In addition, they reflect the interval, or distance, between points in the ranking. When you look at the final examination scores in one of your courses, you are dealing with an interval scale. For instance, if Jim scored 90 out of 100, Jack scored 80, and Jill scored 78, you could rank these three students first, second, and third; that would be an ordinal scale. But the scores themselves give you more information than that. They also tell you the interval, or distance, between the performances on the examination: Jim scored 10 points higher than Jack, but Jack only scored 2 points higher than Jill. Thus, an interval scale gives more information than does an ordinal scale. An interval scale gives you the ordering and the distances between points on that ranking. Examples of interval scales include most of the variables measured with tests like language placement, language apti-tude, language proficiency, and so on. But some interval scales are measured in different ways, such as age, number of years of schooling, and years of language study. It is important to note that an interval scale assumes that the intervals between points are equal. Hence, on a 100-point test, the distance between the scores 12 and 14 (2 points) is assumed to be equal to the distance between 98 and 100 (also 2 points). The problem is that some items on a language test may be much more difficult (particularly those that make a difference on high scores like 98 and 100) than are others, so the distances between intervals do not seem equal. Nevertheless, this assumption is one with which most researchers can live - at least until knowledge in the field of language teaching becomes exact enough to provide ratio scales. Ratio scales The discussion of ratio scales will be short because such scales are not generally applied to the behavioral sciences, for two reasons: (1) a ratio scale has a zero value and (2) it can be said that points on the scale are precise multiples of other points on the scale. For example, you can have zero electricity in your house. But if you have a 50-watt bulb burning and then you turn on an additional 100-watt bulb, you can say that you are now using three times as much electricity. Can you, however, say that a person knows no (zero) Spanish? I think not. Even a person who has never studied Spanish will bring certain lexical, phonological, and syntactic information from the native language to bear on the task. Read the text above and create a table. Columns: Name of scale Property Operations Characteristic Example
c237ed428050ec87e4ab7b4281131888
{ "intermediate": 0.3574083745479584, "beginner": 0.37054377794265747, "expert": 0.27204781770706177 }
47,781
I have 6 files .h and .cpp. can i share them w/ u and u can check
4ea753cb7a37fdc58a471bf5738c62b1
{ "intermediate": 0.37581539154052734, "beginner": 0.26994991302490234, "expert": 0.3542346954345703 }
47,782
#include <bits/stdc++.h> using namespace std; int cnt = 0; int min_distance(vector<int> &dist, vector<int> &vis, int n) { int min = 100000; int min_index = -1; for (int v = 1; v <= n; v++) { if (vis[v] == 0 && dist[v] <= min) { min = dist[v], min_index = v; } } return min_index; } void dijkstra(vector<vector<int>> &graph, int src, int n, vector<int> &dist) { vector<int> vis(n + 1, 0); for (int i = 1; i <= n; i++) dist[i] = 100000; dist[src] = 0; for (int count = 0; count < n; count++) { int u = min_distance(dist, vis, n); if (u == -1) break; vis[u] = 1; for (int v = 1; v <= n; v++) { if (vis[v] == 0 && graph[u][v] != 100000 && dist[u] != 100000 && dist[u] + graph[u][v] < dist[v]) { dist[v] = dist[u] + graph[u][v]; } } } } void add_edge(vector<vector<int>> &adj, int u, int v, int l) { if (u >= 1 && u <= adj.size() - 1 && v >= 1 && v <= adj.size() - 1) { adj[u][v] = l; adj[v][u] = l; } } void func(vector<vector<int>> &adj1, vector<int> &dist1, vector<int> &adj2, int n) { // int cnt = 0; for (int i = 1; i <= n; i++) { cout << "adj2[i] is " << adj2[i]<< endl; if (adj2[i]!=100000 && dist1[i] <= adj2[i]) { cnt++; } else { cout << "chsnging dist of " << i << " to " << adj2[i] << "from"<< dist1[i]<< endl; dist1[i] = adj2[i]; add_edge(adj1, 1, i, dist1[i]); cout << "changed dist of " << i << " is " << dist1[i] << endl; dijkstra(adj1, 1, n, dist1); } for (int i = 0; i < dist1.size(); i++) { cout << i << "dist 1 array" << dist1[i] << endl; } cout<<"node is "<<i<<endl; cout<<"count is " <<cnt<<endl; } cout << cnt << endl << endl; } int main() { int n, m, k; cin >> n >> m >> k; vector<vector<int>> adj1(n + 1, vector<int>(n + 1, 100000)); // vector<vector<int>> adj2(n + 1, vector<int>(n + 1, 100000)); vector<int> adj2(n, 100000); vector<int> dist1(n + 1, 100000), dist2(n + 1, 100000); for (int i = 0; i < m; i++) { int u, v, l; cin >> u >> v >> l; add_edge(adj1, u, v, l); } for (int i = 0; i < k; i++) { int v, l; cin >> v >> l; if (adj2[v] != 100000) { cnt++; if (adj2[v] > l) { adj2[v] = l; } } else adj2[v] = l; // add_edge(adj2, 0, v, l); } cout << "count siisisis" << cnt << endl; dijkstra(adj1, 1, n, dist1); // dijkstra(adj2, 1, n, dist2); cout << "initially the shortest paths are" << endl << endl; for (int i = 0; i < dist1.size(); i++) { cout << i << " " << dist1[i] << endl; } cout << endl << endl; for (int i = 0; i < dist1.size(); i++) { cout << i << " " << dist1[i] << endl; } for (int i = 0; i < dist1.size(); i++) { cout << i << "dist 1 array" << dist1[i] << endl; } for (int i = 0; i <= adj2.size(); i++) { cout << i << "adj 2 array" << adj2[i] << endl; } func(adj1, dist1, adj2, n); for (int i = 0; i < dist1.size(); i++) { cout << i << " " << dist1[i] << endl; } return 0; } 4 Question 2: Need For Speed 4.1 Introduction Lukarp has started his own tech company. He received a lot of funding from Igen with which he opened many offices around the world. Each office needs to communicate with one other, for which they’re using high speed connections between the offices. Office number 1 is Lukarp’s HQ. Some offices are important and hence need faster connections to the HQ for which Lukarp has use special fiber connections. Lukarp has already planned the connections but feels some fiber connections are redundant. You have been hired by Lukarp to remove those fiber connections which don’t cause faster connections. 4.2 Problem Statement 4.2.1 The Problem The offices and (bi-directional) connections (both normal and fiber) are given to you. HQ is numbered as 1. The ith normal connection connects any two offices ai and bi. Normal connections have latency li. The ith fiber connection connects the HQ with the office ci. Fiber connections also come with a latency pi. The total latency of a path is the sum of latencies on the connections. You are to output the maximum number of fiber connections that can be removed, such that the latency of the smallest latency path between the HQ and any other node remains the same as before. • There are n offices with m normal connections and k high-speed fiber connections. • The ith normal connection connects offices ai and bi (bi-directionally) with latency li. • The ith fiber connection connects offices 1 and ci (bi-directionally) with latency pi. 4.2.2 Input Format The first line of the input file will contain three space-separated integers n, m and k, the number of offices, the number of normal connections and the number of fiber connections. There will be m lines after this, the ith line signifying the ith normal connection, each containing three space-separated integers ai, bi and li the two offices that are connected and the latency of the connection respectively. There will be k lines after this, the ith line signifying the ith fiber connection, each containing three space-separated integers ci and pi, the office connected to the HQ and the latency of the fiber connection respectively. 6 4.2.3 Output Format Output only one integer m - the maximum number of fiber connections that can be removed without changing the latency of smallest latency path from office 1 to any other office. 4.2.4 Constraints • 2≤n≤105 • 1≤m≤2·105 • 1≤k≤105 • 1≤ai,bi,ci ≤n • 1≤li,pi ≤109 4.2.5 Example Input: 452 122 149 133 244 345 34 45 Output: 1 Explanation: In this example, there are five normal connections as shown in the figure below. The fiber connection going from 1 to 3 can be removed because the normal con- nection (3) is faster than the fiber connection (4). However, the fiber connection with 4 cannot be removed. Hence the maximum number of fiber connections that can be removed is 1. 7 all test cases are working when i check manually but online judje is throwing wrong answer for hidden test case what could be wrong
c96462095b4b61525e6c30bc00169d07
{ "intermediate": 0.3498968780040741, "beginner": 0.42499327659606934, "expert": 0.22510990500450134 }
47,783
#include <bits/stdc++.h> #include <iostream> #include <vector> #include <queue> #include <limits> #include <unordered_map> using namespace std; // int cnt = 0; int min_distance(vector<pair<int, int>> &dist, vector<int> &vis, int n) { int mini = 100000; int min_index = -1; for (int v = 1; v <= n; v++) { if (vis[v] == 0 && dist[v].first <= mini) { mini = dist[v].first, min_index = v; } } return min_index; } void dijkstra(vector<vector<int>> &graph, int src, int n, vector<pair<int, int>> &dist) { vector<int> vis(n + 1, 0); for (int i = 1; i <= n; i++) dist[i].first = 100000; dist[src].first = 0; for (int count = 0; count < n; count++) { int u = min_distance(dist, vis, n); if (u == -1) break; vis[u] = 1; for (int v = 1; v <= n; v++) { if (vis[v] == 0 && graph[u][v] != 100000 && dist[u].first != 100000 && dist[u].first + graph[u][v] < dist[v].first) { dist[v].first = dist[u].first + graph[u][v]; } } } } void add_edge(vector<vector<int>> &adj, int u, int v, int l) { if (u >= 1 && u < adj.size() && v >= 1 && v < adj.size()) { adj[u][v] = l; adj[v][u] = l; } } void func(vector<vector<int>> &adj1, vector<pair<int, int>> &dist1, vector<int> &adj2, int n, int cnt) { // int cnt = 0; // for (int i = 0; i < dist1.size(); i++) // { // cout << i << " " << dist1[i] << endl; // } // cout<<n<<"is n"<<endl; for (int i = 1; i <= n; i++) { cout << adj2[i] << "is my adj of " << i << endl; cout << dist1[i].first << "is my dist1 of " << i << endl; if (adj2[i] != 100000) { if (dist1[i].first <= adj2[i]) { cnt++; cout << cnt << "in func and i is " << i << endl; } else { dist1[i].first = adj2[i]; if (dist1[i].second == 1) { cnt++; cout << "aaaa"; } dist1[i].second = 1; add_edge(adj1, 1, i, dist1[i].first); cout << "changed dist of " << i << " is " << dist1[i].first << endl; dijkstra(adj1, 1, n, dist1); } } } cout << cnt; //<< endl // << endl; } int main() { int cnt = 0; int n, m, k; cin >> n >> m >> k; vector<vector<int>> adj1(n + 1, vector<int>(n + 1, 100000)); // vector<vector<int>> adj2(n + 1, vector<int>(n + 1, 100000)); vector<int> adj2(n, 100000); vector<pair<int, int>> dist1(n + 1, {100000, 0}); // vector<int> dist1(n + 1, 100000); //, dist2(n + 1, 100000); dist1[1].first = 0; for (int i = 0; i < m; i++) { int u, v, l; cin >> u >> v >> l; if (adj1[u][v] != 100000) { if (adj1[u][v] > l) { add_edge(adj1, u, v, l); } } else { add_edge(adj1, u, v, l); } } for (int i = 0; i < k; i++) { int v, l; cin >> v >> l; if (adj2[v] != 100000) { cnt++; if (adj2[v] > l) { adj2[v] = l; } } else if (v == 1) { cnt++; } else adj2[v] = l; // add_edge(adj2, 0, v, l); } dijkstra(adj1, 1, n, dist1); // dijkstra(adj2, 1, n, dist2); cout << "initially the shortest paths are" << endl << endl; for (int i = 0; i < dist1.size(); i++) { cout << i << " " << dist1[i].first << endl; } cout << endl << endl; func(adj1, dist1, adj2, n, cnt); for (int i = 0; i < dist1.size(); i++) { cout << i << " " << dist1[i].first << endl; } return 0; } modify this code to answer these test cases // Test cases // 1 will be connected to all the nodes via normal connection. /* 3 2 2 1 2 3 2 3 4 3 10 3 8 // ans=2 4 5 2 1 2 2 1 4 9 1 3 3 2 4 4 3 4 5 3 4 4 5 // ans =1 3 3 3 1 2 5 1 3 100 2 3 1 2 4 3 2 3 1 //ans 2 4 4 2 1 2 5 2 3 4 3 4 1 1 4 10 2 1 4 8 // ans= 1 */ /* basic cases: 5 6 3 1 4 5 4 5 2 2 4 7 3 1 4 1 5 10 3 2 6 5 3 2 1 4 3 // ans = 0 4 4 1 2 3 2 2 4 8 4 3 1 1 4 5 3 7 // ans = 1 3 3 3 1 2 1 2 3 1 1 3 1 2 1 2 2 3 1 3 // ans 3 4 5 2 1 2 2 1 4 9 1 3 3 2 4 4 3 4 5 3 4 4 5 // ans = 1 4 4 2 2 3 2 2 4 8 4 3 3 1 4 5 3 7 2 9 // ans = 1 4 4 2 1 2 5 2 3 4 3 4 1 1 4 10 2 1 4 8 // ans = 1 3 3 3 1 2 5 1 3 100 2 3 1 2 4 3 2 3 1 // ans = 2 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ // Good testcases 5 6 3 1 4 5 4 5 2 2 4 7 3 1 4 1 5 10 3 2 6 2 1 4 3 5 5 // ans = 1 6 16 19 4 1 6 2 2 19 3 1 14 3 6 14 6 5 17 6 4 2 4 6 7 2 1 7 3 5 4 6 6 13 5 4 7 2 3 6 1 2 19 4 6 14 4 2 16 2 6 13 5 9 1 3 4 12 2 12 4 18 3 17 1 1 4 8 3 15 6 15 3 17 1 18 6 11 1 10 3 16 3 11 5 20 5 3 4 7 // ans = 18 3 9 8 1 1 14 1 3 1 2 2 12 3 1 15 3 1 19 3 3 15 1 3 7 3 1 8 1 2 6 2 18 3 1 2 13 3 2 3 5 1 20 2 8 3 5 // ans = 8 6 5 4 4 4 20 1 4 15 5 3 14 5 5 12 2 6 19 6 3 4 10 1 18 4 4 // ans = 2 8 5 6 1 8 20 3 7 11 5 6 14 2 6 17 7 4 11 8 6 7 19 5 8 6 7 2 13 3 19 // ans = 0 10 10 10 9 8 2 8 8 9 2 8 17 1 1 1 6 6 10 10 8 11 3 9 18 7 1 5 3 2 17 5 5 10 3 16 1 20 8 13 3 7 5 12 1 10 10 14 10 3 4 1 3 3 // ans = 5 10 9 5 9 7 4 1 5 18 6 6 7 7 2 9 2 6 3 8 10 9 10 4 6 6 5 14 5 9 11 2 18 7 1 2 12 5 7 2 4 // ans = 2 */
b9a1cac318a53ba782545fc8a0c0633c
{ "intermediate": 0.34474819898605347, "beginner": 0.49480685591697693, "expert": 0.1604449599981308 }
47,784
The offices and (bi-directional) connections (both normal and fiber) are given to you. HQ is numbered as 1. The ith normal connection connects any two offices ai and bi . Normal connections have latency li . The ith fiber connection connects the HQ with the office ci . Fiber connections also come with a latency pi . The total latency of a path is the sum of latencies on the connections. You are to output the maximum number of fiber connections that can be removed, such that the latency of the smallest latency path between the HQ and any other node remains the same as before. • There are n offices with m normal connections and k high-speed fiber connections. • The ith normal connection connects offices ai and bi (bi-directionally) with latency li . • The ith fiber connection connects offices 1 and ci (bi-directionally) with latency pi . give c++code it should satisfy these test cases 3 2 2 1 2 3 2 3 4 3 10 3 8 // ans=2 4 5 2 1 2 2 1 4 9 1 3 3 2 4 4 3 4 5 3 4 4 5 // ans =1 3 3 3 1 2 5 1 3 100 2 3 1 2 4 3 2 3 1 //ans 2 4 4 2 1 2 5 2 3 4 3 4 1 1 4 10 2 1 4 8 // ans= 1 */ /* basic cases: 5 6 3 1 4 5 4 5 2 2 4 7 3 1 4 1 5 10 3 2 6 5 3 2 1 4 3 // ans = 0 4 4 1 2 3 2 2 4 8 4 3 1 1 4 5 3 7 // ans = 1 3 3 3 1 2 1 2 3 1 1 3 1 2 1 2 2 3 1 3 // ans 3 4 5 2 1 2 2 1 4 9 1 3 3 2 4 4 3 4 5 3 4 4 5 // ans = 1 4 4 2 2 3 2 2 4 8 4 3 3 1 4 5 3 7 2 9 // ans = 1 4 4 2 1 2 5 2 3 4 3 4 1 1 4 10 2 1 4 8 // ans = 1 3 3 3 1 2 5 1 3 100 2 3 1 2 4 3 2 3 1 // ans = 2 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ // Good testcases 5 6 3 1 4 5 4 5 2 2 4 7 3 1 4 1 5 10 3 2 6 2 1 4 3 5 5 // ans = 1 6 16 19 4 1 6 2 2 19 3 1 14 3 6 14 6 5 17 6 4 2 4 6 7 2 1 7 3 5 4 6 6 13 5 4 7 2 3 6 1 2 19 4 6 14 4 2 16 2 6 13 5 9 1 3 4 12 2 12 4 18 3 17 1 1 4 8 3 15 6 15 3 17 1 18 6 11 1 10 3 16 3 11 5 20 5 3 4 7 // ans = 18 3 9 8 1 1 14 1 3 1 2 2 12 3 1 15 3 1 19 3 3 15 1 3 7 3 1 8 1 2 6 2 18 3 1 2 13 3 2 3 5 1 20 2 8 3 5 // ans = 8 6 5 4 4 4 20 1 4 15 5 3 14 5 5 12 2 6 19 6 3 4 10 1 18 4 4 // ans = 2 8 5 6 1 8 20 3 7 11 5 6 14 2 6 17 7 4 11 8 6 7 19 5 8 6 7 2 13 3 19 // ans = 0 10 10 10 9 8 2 8 8 9 2 8 17 1 1 1 6 6 10 10 8 11 3 9 18 7 1 5 3 2 17 5 5 10 3 16 1 20 8 13 3 7 5 12 1 10 10 14 10 3 4 1 3 3 // ans = 5 10 9 5 9 7 4 1 5 18 6 6 7 7 2 9 2 6 3 8 10 9 10 4 6 6 5 14 5 9 11 2 18 7 1 2 12 5 7 2 4 // ans = 2 */
35c9c3a3d4c4fb13c58738bbda5f9503
{ "intermediate": 0.3481638431549072, "beginner": 0.3229636549949646, "expert": 0.3288725018501282 }
47,785
Question 2: Need For Speed 4.1 Introduction Lukarp has started his own tech company. He received a lot of funding from Igen with which he opened many offices around the world. Each office needs to communicate with one other, for which they’re using high speed connections between the offices. Office number 1 is Lukarp’s HQ. Some offices are important and hence need faster connections to the HQ for which Lukarp has use special fiber connections. Lukarp has already planned the connections but feels some fiber connections are redundant. You have been hired by Lukarp to remove those fiber connections which don’t cause faster connections. 4.2 Problem Statement 4.2.1 The Problem The offices and (bi-directional) connections (both normal and fiber) are given to you. HQ is numbered as 1. The ith normal connection connects any two offices ai and bi. Normal connections have latency li. The ith fiber connection connects the HQ with the office ci. Fiber connections also come with a latency pi. The total latency of a path is the sum of latencies on the connections. You are to output the maximum number of fiber connections that can be removed, such that the latency of the smallest latency path between the HQ and any other node remains the same as before. • There are n offices with m normal connections and k high-speed fiber connections. • The ith normal connection connects offices ai and bi (bi-directionally) with latency li. • The ith fiber connection connects offices 1 and ci (bi-directionally) with latency pi. 4.2.2 Input Format The first line of the input file will contain three space-separated integers n, m and k, the number of offices, the number of normal connections and the number of fiber connections. There will be m lines after this, the ith line signifying the ith normal connection, each containing three space-separated integers ai, bi and li the two offices that are connected and the latency of the connection respectively. There will be k lines after this, the ith line signifying the ith fiber connection, each containing three space-separated integers ci and pi, the office connected to the HQ and the latency of the fiber connection respectively. 6 4.2.3 Output Format Output only one integer m - the maximum number of fiber connections that can be removed without changing the latency of smallest latency path from office 1 to any other office. 4.2.4 Constraints • 2≤n≤105 • 1≤m≤2·105 • 1≤k≤105 • 1≤ai,bi,ci ≤n • 1≤li,pi ≤109 4.2.5 Example Input: 452 122 149 133 244 345 34 45 Output: 1 Explanation: In this example, there are five normal connections as shown in the figure below. The fiber connection going from 1 to 3 can be removed because the normal con- nection (3) is faster than the fiber connection (4). However, the fiber connection with 4 cannot be removed. Hence the maximum number of fiber connections that can be removed is 1. 7 / Test cases // 1 will be connected to all the nodes via normal connection. /* 3 2 2 1 2 3 2 3 4 3 10 3 8 // ans=2 4 5 2 1 2 2 1 4 9 1 3 3 2 4 4 3 4 5 3 4 4 5 // ans =1 3 3 3 1 2 5 1 3 100 2 3 1 2 4 3 2 3 1 //ans 2 4 4 2 1 2 5 2 3 4 3 4 1 1 4 10 2 1 4 8 // ans= 1 */ /* basic cases: 5 6 3 1 4 5 4 5 2 2 4 7 3 1 4 1 5 10 3 2 6 5 3 2 1 4 3 // ans = 0 4 4 1 2 3 2 2 4 8 4 3 1 1 4 5 3 7 // ans = 1 3 3 3 1 2 1 2 3 1 1 3 1 2 1 2 2 3 1 3 // ans 3 4 5 2 1 2 2 1 4 9 1 3 3 2 4 4 3 4 5 3 4 4 5 // ans = 1 4 4 2 2 3 2 2 4 8 4 3 3 1 4 5 3 7 2 9 // ans = 1 4 4 2 1 2 5 2 3 4 3 4 1 1 4 10 2 1 4 8 // ans = 1 3 3 3 1 2 5 1 3 100 2 3 1 2 4 3 2 3 1 // ans = 2 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ // Good testcases 5 6 3 1 4 5 4 5 2 2 4 7 3 1 4 1 5 10 3 2 6 2 1 4 3 5 5 // ans = 1 6 16 19 4 1 6 2 2 19 3 1 14 3 6 14 6 5 17 6 4 2 4 6 7 2 1 7 3 5 4 6 6 13 5 4 7 2 3 6 1 2 19 4 6 14 4 2 16 2 6 13 5 9 1 3 4 12 2 12 4 18 3 17 1 1 4 8 3 15 6 15 3 17 1 18 6 11 1 10 3 16 3 11 5 20 5 3 4 7 // ans = 18 3 9 8 1 1 14 1 3 1 2 2 12 3 1 15 3 1 19 3 3 15 1 3 7 3 1 8 1 2 6 2 18 3 1 2 13 3 2 3 5 1 20 2 8 3 5 // ans = 8 6 5 4 4 4 20 1 4 15 5 3 14 5 5 12 2 6 19 6 3 4 10 1 18 4 4 // ans = 2 8 5 6 1 8 20 3 7 11 5 6 14 2 6 17 7 4 11 8 6 7 19 5 8 6 7 2 13 3 19 // ans = 0 10 10 10 9 8 2 8 8 9 2 8 17 1 1 1 6 6 10 10 8 11 3 9 18 7 1 5 3 2 17 5 5 10 3 16 1 20 8 13 3 7 5 12 1 10 10 14 10 3 4 1 3 3 // ans = 5 10 9 5 9 7 4 1 5 18 6 6 7 7 2 9 2 6 3 8 10 9 10 4 6 6 5 14 5 9 11 2 18 7 1 2 12 5 7 2 4 // ans = 2 */ PROVIDE ME C++ IMPLEMENTATION , DONT TALK TOO MUCH OR DONT EXPLAIN ANYTHING
8e33d5df27f2d5a95e611e3c5a805b68
{ "intermediate": 0.30314314365386963, "beginner": 0.3608108460903168, "expert": 0.336046040058136 }
47,786
The offices and (bi-directional) connections (both normal and fiber) are given to you. HQ is numbered as 1. The ith normal connection connects any two offices ai and bi . Normal connections have latency li . The ith fiber connection connects the HQ with the office ci . Fiber connections also come with a latency pi . The total latency of a path is the sum of latencies on the connections. You are to output the maximum number of fiber connections that can be removed, such that the latency of the smallest latency path between the HQ and any other node remains the same as before. • There are n offices with m normal connections and k high-speed fiber connections. • The ith normal connection connects offices ai and bi (bi-directionally) with latency li . • The ith fiber connection connects offices 1 and ci (bi-directionally) with latency pi . give c++code it should satisfy these test cases 20 5 8 2 7 2 7 16 11 7 19 17 1 12 16 16 3 15 16 18 16 19 14 7 5 8 14 12 20 20 3 3 15 1 output: 3 3 9 8 1 1 14 1 3 1 2 2 12 3 1 15 3 1 19 3 3 15 1 3 7 3 1 8 1 2 6 2 18 3 1 2 13 3 2 3 5 1 20 2 8 3 5 output: 8 6 16 19 4 1 6 2 2 19 3 1 14 3 6 14 6 5 17 6 4 2 4 6 7 2 1 7 3 5 4 6 6 13 5 4 7 2 3 6 1 2 19 4 6 14 4 2 16 2 6 13 5 9 1 3 4 12 2 12 4 18 3 17 1 1 4 8 3 15 6 15 3 17 1 18 6 11 1 10 3 16 3 11 5 20 5 3 4 7 output: 18
d68b168e9dc2361802fa84ae23f3f4df
{ "intermediate": 0.27379539608955383, "beginner": 0.363313764333725, "expert": 0.3628908097743988 }
47,787
Suppose I get a quote from a geico entering in the necessary information as well as my email and phone number. I decide I don't want to go with Geico right now, and want to check other companies. Am I stuck with this initial Geico quote or can this be changed later?
d07308680ddc4ae8ef52c77b4ef3c0a4
{ "intermediate": 0.3997032642364502, "beginner": 0.3050665259361267, "expert": 0.2952302098274231 }
47,788
analyze the following code and correct any potential data column naming errors or http errors in dataset construction: # Import necessary libraries import pandas as pd import numpy as np from datetime import datetime from alpha_vantage.timeseries import TimeSeries from textblob import TextBlob from nltk.sentiment import SentimentIntensityAnalyzer # Set the API key for Alpha Vantage api_key = 'OSKT2UIVOS229Q0V' # Replace with your actual API key # Define the cryptocurrency and the time range crypto = 'BTC' # You can change this to other cryptocurrencies start_date = '2018-01-01' end_date = '2023-04-30' # Fetch historical price data from Alpha Vantage def fetch_price_data(api_key, crypto, start_date, end_date): """ Fetches and preprocesses price data from Alpha Vantage. """ ts = TimeSeries(key=api_key, output_format='pandas') data, meta_data = ts.get_daily(symbol=crypto, outputsize='full') data = data.iloc[::-1] # Reverse the order of the data data = data.reset_index() data['date'] = pd.to_datetime(data['date']) data = data[(data['date'] >= start_date) & (data['date'] <= end_date)] return data # Fetch trading volume data from CoinMetrics def fetch_volume_data(crypto, start_date, end_date): """ Fetches and preprocesses volume data from CoinMetrics. """ volume_data = pd.read_csv(f"https://coinmetrics.io/data/{crypto.lower()}.csv") volume_data = volume_data[['date', 'VolumeFromOpt']] volume_data.columns = ['Date', 'Volume'] volume_data['Date'] = pd.to_datetime(volume_data['Date']) volume_data = volume_data[(volume_data['Date'] >= start_date) & (volume_data['Date'] <= end_date)] return volume_data # Scrape news headlines from CryptoPanic def fetch_news_data(auth_token, crypto, start_date, end_date): """ Fetches and preprocesses news sentiment data from CryptoPanic. """ news_data = pd.read_csv(f"https://cryptopanic.com/api/posts/?auth_token={auth_token}&kind=news¤cies={crypto}&public=true") news_data = news_data[['id', 'title', 'published_at']] news_data['published_at'] = pd.to_datetime(news_data['published_at']) news_data = news_data[(news_data['published_at'] >= start_date) & (news_data['published_at'] <= end_date)] sid = SentimentIntensityAnalyzer() news_data['Sentiment'] = news_data['title'].apply(lambda x: sid.polarity_scores(x)['compound']) return news_data[['published_at', 'Sentiment']] # Set parameters api_key = 'OSKT2UIVOS229Q0V' # Replace with your actual Alpha Vantage API key auth_token = '20c5d89ad8d241da6b50d0190c58cdd24f73000c' # Replace with your CryptoPanic API token crypto = 'BTC' start_date = '2018-01-01' end_date = '2023-04-30' # Fetch data price_data = fetch_price_data(api_key, crypto, start_date, end_date) volume_data = fetch_volume_data(crypto, start_date, end_date) news_data = fetch_news_data(auth_token, crypto, start_date, end_date) # Merge data merged_data = pd.merge(price_data, volume_data, on='Date', how='inner') final_data = pd.merge(merged_data, news_data, left_on='Date', right_on='published_at', how='left') final_data = final_data.sort_values(by='Date') final_data = final_data.fillna(0) # Fill missing sentiment scores with 0 # Merge price and volume data merged_data = pd.merge(data, volume_data, on='Date', how='inner') merged_data = merged_data[(merged_data['Date'] >= start_date) & (merged_data['Date'] <= end_date)] # Scrape news headlines from CryptoPanic news_data = pd.read_csv('https://cryptopanic.com/api/posts/?auth_token=20c5d89ad8d241da6b50d0190c58cdd24f73000c&kind=news&currencies=BTC&public=true') news_data = news_data[['id', 'title', 'published_at']] news_data['published_at'] = pd.to_datetime(news_data['published_at']) news_data = news_data[(news_data['published_at'] >= start_date) & (news_data['published_at'] <= end_date)] # Compute sentiment scores for news headlines sid = SentimentIntensityAnalyzer() news_data['Sentiment'] = news_data['title'].apply(lambda x: sid.polarity_scores(x)['compound']) # Merge news sentiment data with price and volume data final_data = pd.merge(merged_data, news_data[['published_at', 'Sentiment']], left_on='Date', right_on='published_at', how='left') final_data = final_data.sort_values(by='Date') final_data = final_data.fillna(0) # Fill missing sentiment scores with 0 # Save the final dataset final_data.to_csv('crypto_dataset.csv', index=False) import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Dense, LSTM, GRU, TimeDistributed, Concatenate, Bidirectional, Attention, Conv1D, Dropout, LayerNormalization, MultiHeadAttention, ConvLSTM2D, Reshape, BatchNormalization from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt from tqdm import tqdm from google.colab import drive import optuna from tensorflow.keras import regularizers from sklearn.metrics import mean_absolute_error, r2_score # Mount Google Drive drive.mount('/content/drive') # Set GPU as the default device with tf.device('/device:GPU:0'): # Load and preprocess the cryptocurrency price data data = pd.read_csv('/content/drive/MyDrive/crypto_prices.csv') prices = data['Price'].values.reshape(-1, 1) volume = data['Volume'].values.reshape(-1, 1) sentiment = data['Sentiment'].values.reshape(-1, 1) # Calculate additional features data['EMA'] = data['Price'].ewm(span=10, adjust=False).mean() data['Upper_BB'] = data['Price'].rolling(window=20).mean() + 2 * data['Price'].rolling(window=20).std() data['Lower_BB'] = data['Price'].rolling(window=20).mean() - 2 * data['Price'].rolling(window=20).std() # Normalize the input features scaler = MinMaxScaler(feature_range=(0, 1)) scaled_prices = scaler.fit_transform(prices) scaled_volume = scaler.fit_transform(volume) scaled_sentiment = scaler.fit_transform(sentiment) scaled_ema = scaler.fit_transform(data['EMA'].values.reshape(-1, 1)) scaled_upper_bb = scaler.fit_transform(data['Upper_BB'].values.reshape(-1, 1)) scaled_lower_bb = scaler.fit_transform(data['Lower_BB'].values.reshape(-1, 1)) # Data augmentation np.random.seed(42) jitter_factor = 0.05 data['Price_Jittered'] = data['Price'] * (1 + np.random.normal(0, jitter_factor, size=len(data))) scaled_price_jittered = scaler.fit_transform(data['Price_Jittered'].values.reshape(-1, 1)) # Create input sequences and corresponding labels sequence_length = 60 num_features = 7 X = [] y = [] for i in range(sequence_length, len(scaled_prices)): X.append(np.hstack((scaled_prices[i-sequence_length:i], scaled_volume[i-sequence_length:i], scaled_sentiment[i-sequence_length:i], scaled_ema[i-sequence_length:i], scaled_upper_bb[i-sequence_length:i], scaled_lower_bb[i-sequence_length:i], scaled_price_jittered[i-sequence_length:i]))) y.append(scaled_prices[i]) X = np.array(X) y = np.array(y) # Reshape the input data for HMSRNN X = X.reshape((X.shape[0], sequence_length, num_features)) # Define the HMSRNN architecture with improvements input_layer = Input(shape=(sequence_length, num_features)) # Residual connections residual = Dense(64, activation='relu')(input_layer) residual = Dense(num_features)(residual) input_layer = tf.keras.layers.Add()([input_layer, residual]) # Layer normalization input_layer = LayerNormalization()(input_layer) # Multi-head attention mechanism attention_output = MultiHeadAttention(num_heads=4, key_dim=64)(input_layer, input_layer) input_layer = tf.keras.layers.Add()([input_layer, attention_output]) input_layer = LayerNormalization()(input_layer) # Convolutional LSTM layers conv_lstm = ConvLSTM2D(filters=64, kernel_size=(3, 3), padding='same', return_sequences=True)(Reshape((sequence_length, num_features, 1))(input_layer)) conv_lstm = TimeDistributed(Dense(64))(conv_lstm) conv_lstm = Reshape((sequence_length, 64))(conv_lstm) # High-frequency component high_freq = Bidirectional(LSTM(256, return_sequences=True))(input_layer) high_freq = Attention()(high_freq) high_freq = Dense(128)(high_freq) high_freq = Dropout(0.3)(high_freq) # Gated recurrent unit (GRU) layers mid_freq = Bidirectional(GRU(128, return_sequences=True))(input_layer) mid_freq = TimeDistributed(Dense(64))(mid_freq) mid_freq = Attention()(mid_freq) mid_freq = Dense(32)(mid_freq) mid_freq = Dropout(0.2)(mid_freq) # Dilated convolutions dilated_conv = Conv1D(128, kernel_size=3, dilation_rate=2, activation='relu', padding='same')(input_layer) dilated_conv = Conv1D(64, kernel_size=3, dilation_rate=4, activation='relu', padding='same')(dilated_conv) dilated_conv = Attention()(dilated_conv) dilated_conv = Dense(32)(dilated_conv) dilated_conv = Dropout(0.2)(dilated_conv) # Low-frequency component low_freq = Conv1D(128, kernel_size=5, activation='relu')(input_layer) low_freq = Bidirectional(LSTM(128, return_sequences=True))(low_freq) low_freq = TimeDistributed(Dense(32))(low_freq) low_freq = Attention()(low_freq) low_freq = Dense(16)(low_freq) low_freq = Dropout(0.2)(low_freq) # Concatenate the frequency components and additional features concat = Concatenate()([high_freq, mid_freq, low_freq, conv_lstm, dilated_conv]) # Batch normalization concat = BatchNormalization()(concat) # Dense layers with dropout regularization and L1/L2 regularization dense = Dense(128, kernel_regularizer=regularizers.l2(0.01))(concat) dense = Dropout(0.4)(dense) dense = Dense(64, kernel_regularizer=regularizers.l2(0.01))(dense) dense = Dropout(0.4)(dense) # Output layer with linear activation output_layer = Dense(1, activation='linear')(dense) # Create the HMSRNN model model = Model(inputs=input_layer, outputs=output_layer) # Compile the model with a custom loss function and learning rate scheduler def custom_loss(y_true, y_pred): mse = tf.reduce_mean(tf.square(y_true - y_pred)) mae = tf.reduce_mean(tf.abs(y_true - y_pred)) return mse + mae lr_schedule = tf.keras.optimizers.schedules.CosineDecay( initial_learning_rate=0.001, decay_steps=10000, alpha=0.001) optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule) model.compile(optimizer=optimizer, loss=custom_loss) # Custom callback for progress monitoring class ProgressCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): print(f"Epoch {epoch+1} - Loss: {logs['loss']:.4f} - Val Loss: {logs['val_loss']:.4f}") # Hyperparameter tuning def objective(trial): # Suggest values for the hyperparameters optimizer = trial.suggest_categorical('optimizer', ['adam', 'rmsprop']) dropout_rate = trial.suggest_uniform('dropout_rate', 0.1, 0.5) num_units = trial.suggest_categorical('num_units', [64, 128, 256]) # Create a new model instance model = create_model(optimizer, dropout_rate, num_units) # Compile the model model.compile(optimizer=optimizer, loss=custom_loss) # Train the model and return the validation loss history = model.fit(X_train, y_train, epochs=100, batch_size=32, validation_split=0.2, verbose=0) return history.history['val_loss'][-1] # Create a study object and optimize the objective function study = optuna.create_study(direction='minimize') study.optimize(objective, n_trials=50) # Print the best trial print("Best trial:") trial = study.best_trial print(" Value: ", trial.value) print(" Params: ") for key, value in trial.params.items(): print(" {}: {}".format(key, value)) # Train the model with early stopping, model checkpointing, and progress monitoring checkpoint_path = '/content/drive/MyDrive/crypto_model_checkpoints/best_model.h5' early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=15, restore_best_weights=True) model_checkpoint = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, save_best_only=True) progress_callback = ProgressCallback() try: history = model.fit(X, y, epochs=100, batch_size=32, validation_split=0.2, callbacks=[early_stopping, model_checkpoint, progress_callback]) except Exception as e: print(f"Error occurred during training: {str(e)}") raise # Visualize training progress try: plt.figure(figsize=(12, 6)) plt.plot(history.history['loss'], label='Training Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend() plt.title('Training Progress') plt.show() except Exception as e: print(f"Error occurred during training progress visualization: {str(e)}") # Load the best model from Google Drive try: model = tf.keras.models.load_model(checkpoint_path, custom_objects={'custom_loss': custom_loss}) except Exception as e: print(f"Error occurred while loading the model: {str(e)}") # Evaluate the model y_pred = model.predict(X_test) mae = mean_absolute_error(y_test, y_pred) r2 = r2_score(y_test, y_pred) print(f"MAE: {mae}, R2 Score: {r2}") # Calculate additional evaluation metrics def mean_absolute_percentage_error(y_true, y_pred): return np.mean(np.abs((y_true - y_pred) / y_true)) * 100 mape = mean_absolute_percentage_error(y_test, y_pred) print(f"MAPE: {mape}")
0595f907e86d673c4c57847448f43055
{ "intermediate": 0.4378766119480133, "beginner": 0.2880159616470337, "expert": 0.2741074562072754 }
47,789
write a program in c using sdl2
ba1da0a6bda2885fcfd08c3f0e4ecc5f
{ "intermediate": 0.3731922209262848, "beginner": 0.2783224582672119, "expert": 0.3484853506088257 }
47,790
├── src/ # Source files │ ├── main.c # Main game loop and initial setup │ ├── game.c # Game state management │ ├── game.h │ ├── init.c # SDL initialization and resource loading │ ├── init.h │ ├── cleanup.c # Resource cleanup functions │ ├── cleanup.h │ ├── input.c # Input handling │ ├── input.h │ ├── graphics.c # Graphics/rendering related functions │ ├── graphics.h │ ├── level.c # Level generation and management │ ├── level.h │ ├── entity.c # Entity management (players, monsters, NPCs) │ └── entity.h
80e5d237adb117047b59c1b8863a128d
{ "intermediate": 0.3449593782424927, "beginner": 0.34233421087265015, "expert": 0.3127064108848572 }