content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
30
130
Q: Obtaining data from both token and word objects in a Stanza Document / Sentence I am using a Stanford STANZA pipeline on some (italian) text. Problem I'm grappling with is that I need data from BOTH the Token and Word objects. While I'm able to access one or the other separately I'm not wrapping my head on how to get data from both in a single loop over the Document -> Sentence Specifically I need both some Word data (such as lemma, upos and head) but I also need to know the corresponding start and end position, which in my understanding I can find in the token.start_char and token.end_char. Here's my code to test what I've achieved: import stanza IN_TXT = '''Il paziente Rossi e' stato ricoverato presso il nostro reparto a seguito di accesso al pronto soccorso con diagnosi sospetta di aneurisma aorta addominale sottorenale. In data 12/11/2022 e' stato sottoposto ad asportazione dell'aneurisma con anastomosi aorto aortica con protesi in dacron da 20mm. Paziente dimesso in data odierna in condizioni stabili.''' stanza.download('it', verbose=False) it_nlp = stanza.Pipeline('it', processors='tokenize,lemma,pos,depparse,ner', verbose=False, use_gpu=False) it_doc = it_nlp(IN_TXT) # iterate through the Token objects T = 0 for token in it_doc.iter_tokens(): T += 1 token_id = 'T' + str((T)) token_start = token.start_char token_end = token.end_char token_text = token.text print(f"{token_id}\t{token_start} {token_end} {token_text}") # iterate through Word objects print(*[f'word: {word.text}\t\t\tupos: {word.upos}\txpos: {word.xpos}\tfeats: {word.feats if word.feats else "_"}' for sent in it_doc.sentences for word in sent.words], sep='\n') Here is the documentation of these objects: https://stanfordnlp.github.io/stanza/data_objects.html A: To access data from both the Word and Token objects in a single loop, you can simply loop through the Sentence objects in the document, and then within each sentence loop through the Word objects. For each Word object, you can access its associated Token object through the .token attribute. Here is an example of how you might do this: for sentence in it_doc.sentences: for word in sentence.words: # Get the Word object's data word_text = word.text word_upos = word.upos word_xpos = word.xpos word_feats = word.feats # Get the Token object's data token = word.token token_start = token.start_char token_end = token.end_char token_text = token.text # Use the data as needed print(f"Word: {word_text}\nUPOS: {word_upos}\nXPOS: {word_xpos}\nFeats: {word_feats}\nToken: {token_text}\nToken start: {token_start}\nToken end: {token_end}") Alternatively, you can access the Token object directly from the Sentence object, using the sentence.tokens property, which is a list of Token objects. Here is an example of how you might do this: for sentence in it_doc.sentences: # Get the Sentence object's tokens tokens = sentence.tokens for token in tokens: token_start = token.start_char token_end = token.end_char token_text = token.text # Use the data as needed print(f"Token: {token_text}\nToken start: {token_start}\nToken end: {token_end}") Either of these approaches should allow you to access data from both the Word and Token objects in a single loop. A: I just discovered the zip function which returns an iterator of tuples in Python 3. Therefore to iterate in parallel through the Words and Tokens of a sentence you can code: for sentence in it_doc.sentences: for t, w in zip(sentence.tokens, sentence.words): print(f"Text->{w.text}\tLemma->{w.lemma}\tStart->{t.start_char}\tStop->{t.end_char}")
Obtaining data from both token and word objects in a Stanza Document / Sentence
I am using a Stanford STANZA pipeline on some (italian) text. Problem I'm grappling with is that I need data from BOTH the Token and Word objects. While I'm able to access one or the other separately I'm not wrapping my head on how to get data from both in a single loop over the Document -> Sentence Specifically I need both some Word data (such as lemma, upos and head) but I also need to know the corresponding start and end position, which in my understanding I can find in the token.start_char and token.end_char. Here's my code to test what I've achieved: import stanza IN_TXT = '''Il paziente Rossi e' stato ricoverato presso il nostro reparto a seguito di accesso al pronto soccorso con diagnosi sospetta di aneurisma aorta addominale sottorenale. In data 12/11/2022 e' stato sottoposto ad asportazione dell'aneurisma con anastomosi aorto aortica con protesi in dacron da 20mm. Paziente dimesso in data odierna in condizioni stabili.''' stanza.download('it', verbose=False) it_nlp = stanza.Pipeline('it', processors='tokenize,lemma,pos,depparse,ner', verbose=False, use_gpu=False) it_doc = it_nlp(IN_TXT) # iterate through the Token objects T = 0 for token in it_doc.iter_tokens(): T += 1 token_id = 'T' + str((T)) token_start = token.start_char token_end = token.end_char token_text = token.text print(f"{token_id}\t{token_start} {token_end} {token_text}") # iterate through Word objects print(*[f'word: {word.text}\t\t\tupos: {word.upos}\txpos: {word.xpos}\tfeats: {word.feats if word.feats else "_"}' for sent in it_doc.sentences for word in sent.words], sep='\n') Here is the documentation of these objects: https://stanfordnlp.github.io/stanza/data_objects.html
[ "To access data from both the Word and Token objects in a single loop, you can simply loop through the Sentence objects in the document, and then within each sentence loop through the Word objects. For each Word object, you can access its associated Token object through the .token attribute. Here is an example of how you might do this:\nfor sentence in it_doc.sentences:\n for word in sentence.words:\n # Get the Word object's data\n word_text = word.text\n word_upos = word.upos\n word_xpos = word.xpos\n word_feats = word.feats\n\n # Get the Token object's data\n token = word.token\n token_start = token.start_char\n token_end = token.end_char\n token_text = token.text\n \n # Use the data as needed\n print(f\"Word: {word_text}\\nUPOS: {word_upos}\\nXPOS: {word_xpos}\\nFeats: {word_feats}\\nToken: {token_text}\\nToken start: {token_start}\\nToken end: {token_end}\")\n\nAlternatively, you can access the Token object directly from the Sentence object, using the sentence.tokens property, which is a list of Token objects. Here is an example of how you might do this:\nfor sentence in it_doc.sentences:\n # Get the Sentence object's tokens\n tokens = sentence.tokens\n \n for token in tokens:\n token_start = token.start_char\n token_end = token.end_char\n token_text = token.text\n\n # Use the data as needed\n print(f\"Token: {token_text}\\nToken start: {token_start}\\nToken end: {token_end}\")\n\nEither of these approaches should allow you to access data from both the Word and Token objects in a single loop.\n", "I just discovered the zip function which returns an iterator of tuples in Python 3.\nTherefore to iterate in parallel through the Words and Tokens of a sentence you can code:\nfor sentence in it_doc.sentences:\n for t, w in zip(sentence.tokens, sentence.words):\n print(f\"Text->{w.text}\\tLemma->{w.lemma}\\tStart->{t.start_char}\\tStop->{t.end_char}\")\n\n" ]
[ 0, 0 ]
[]
[]
[ "nlp", "python", "stanford_nlp" ]
stackoverflow_0074668152_nlp_python_stanford_nlp.txt
Q: Composite Primary key, using @IdClass - Column 'id' cannot be null I have an entity with a composite primary key. id - version will be the primary key. id version column A 1 1 some data 1 2 some data 2 1 some data 2 2 some data I am using @IdClass for handling the composite primary key. @Entity @IdClass(MyKey.class) public class YourEntity { @Id private int id; @Id private int version; } public class MyKey implements Serializable { private int id; private int version; } When I want to insert new row to the table, in other words I want to add new id, it complains that Column 'id' cannot be null. I don't want id be null. According to my table, when I insert new row, it should add new id with value 3. A: If I understand you correctly, you want to use AUTO_INCREMENT for id column. You should be able to use @GeneratedValue(strategy = GenerationType.IDENTITY) for id field of your entity. But, unfortunately, you can not do it due to HHH-9662. And this is not critical bug as it is not violate jpa specification. As workaround, you can use an approach that was described in Vlad Mihalcea's article. Assuming that you have the following table: create table test_my_entity ( id int not null AUTO_INCREMENT, version int, name varchar(50), primary key (id, version) ); You can use the following mapping: import org.hibernate.annotations.SQLInsert; import javax.persistence.EmbeddedId; // ... @Entity @Table(name = "test_my_entity") @SQLInsert(sql = "insert into test_my_entity(name, id, version) values (?, ?, ?)") public class MyEntity { @EmbeddedId private MyEntityPk pk; @Column(name = "name") private String name; // getters and setters ... } @Embeddable public class MyEntityPk implements Serializable { private int id; private int version; public MyEntityPk() { } public MyEntityPk(int version) { this.version = version; } public MyEntityPk(int id, int version) { this.id = id; this.version = version; } public int getId() { return id; } public int getVersion() { return version; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MyEntityPk that = (MyEntityPk) o; return version == that.version && id == that.id; } @Override public int hashCode() { return Objects.hash(id, version); } } and example how you can insert new row: MyEntity myEntity = new MyEntity(); myEntity.setPk(new MyEntityPk(5)); myEntity.setName("Yulia"); entityManager.persist(myEntity);
Composite Primary key, using @IdClass - Column 'id' cannot be null
I have an entity with a composite primary key. id - version will be the primary key. id version column A 1 1 some data 1 2 some data 2 1 some data 2 2 some data I am using @IdClass for handling the composite primary key. @Entity @IdClass(MyKey.class) public class YourEntity { @Id private int id; @Id private int version; } public class MyKey implements Serializable { private int id; private int version; } When I want to insert new row to the table, in other words I want to add new id, it complains that Column 'id' cannot be null. I don't want id be null. According to my table, when I insert new row, it should add new id with value 3.
[ "If I understand you correctly, you want to use AUTO_INCREMENT for id column. You should be able to use @GeneratedValue(strategy = GenerationType.IDENTITY) for id field of your entity. But, unfortunately, you can not do it due to HHH-9662. And this is not critical bug as it is not violate jpa specification.\nAs workaround, you can use an approach that was described in Vlad Mihalcea's article.\nAssuming that you have the following table:\ncreate table test_my_entity (\n id int not null AUTO_INCREMENT,\n version int,\n name varchar(50),\n\n primary key (id, version)\n);\n\nYou can use the following mapping:\nimport org.hibernate.annotations.SQLInsert;\nimport javax.persistence.EmbeddedId;\n// ...\n\n@Entity\n@Table(name = \"test_my_entity\")\n@SQLInsert(sql = \"insert into test_my_entity(name, id, version) values (?, ?, ?)\")\npublic class MyEntity {\n\n @EmbeddedId\n private MyEntityPk pk;\n\n @Column(name = \"name\")\n private String name;\n\n // getters and setters ...\n}\n\n\n@Embeddable\npublic class MyEntityPk implements Serializable {\n private int id;\n private int version;\n\n public MyEntityPk() {\n }\n\n public MyEntityPk(int version) {\n this.version = version;\n }\n\n public MyEntityPk(int id, int version) {\n this.id = id;\n this.version = version;\n }\n\n public int getId() {\n return id;\n }\n\n public int getVersion() {\n return version;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n MyEntityPk that = (MyEntityPk) o;\n return version == that.version && id == that.id;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, version);\n }\n\n}\n\nand example how you can insert new row:\nMyEntity myEntity = new MyEntity();\nmyEntity.setPk(new MyEntityPk(5));\nmyEntity.setName(\"Yulia\");\nentityManager.persist(myEntity);\n\n" ]
[ 0 ]
[]
[]
[ "composite_primary_key", "database", "hibernate", "jpa", "spring" ]
stackoverflow_0074655346_composite_primary_key_database_hibernate_jpa_spring.txt
Q: Swapping elements from an array that are prime numbers I need to input my own array and give it's own elements, from that array i need to print the same one but if theres a number that is prime, it needs to switch it with the next number. Example: My array: 4 6 3 5 7 11 13 The new array: 4 6 5 3 11 7 13 Here prime numbers are, 3 5 7 and 13, but 13 doesnt have an element to switch itself, so it stays the same. #include <stdio.h> #define array 100 int prime(int b ) { int i; for (i = 2; i <= b / 2; i++) { if (b % i == 0) { return b; // not prime } break; } return b; } int main() { int n, i, a[array]; printf("How many elements does the array have?\n"); scanf("%d", &n); printf("Put in %d elements from the array!\n", n); for (i = 0; i < n; i++) { scanf("%d", &a[i]); } printf("My array is: \n"); for (i = 0; i < n; i++) { printf("%d ", a[i]); } for (i = 0; i < n; i++) { if (prime(a[i])) { int temp; temp = prost(a[i]); prime(a[i]) == prime(a[i + 1]); } } printf("\nThe new array is:\n"); printf("%d ", prime(a[i])); return 0; } I haven't learned pointers so is there a way without it or? A: First of all, you have a for loop that only makes one iteration because of a break keyword, also in main in a for loop with your swapping you need to assign return values from the prime function to variables, and in the same function, you should use singe '=' because you want to assign value but not to compare. Also in your same for loop, you should check if(prime(a[i+1])) so there won't be any segfaults.
Swapping elements from an array that are prime numbers
I need to input my own array and give it's own elements, from that array i need to print the same one but if theres a number that is prime, it needs to switch it with the next number. Example: My array: 4 6 3 5 7 11 13 The new array: 4 6 5 3 11 7 13 Here prime numbers are, 3 5 7 and 13, but 13 doesnt have an element to switch itself, so it stays the same. #include <stdio.h> #define array 100 int prime(int b ) { int i; for (i = 2; i <= b / 2; i++) { if (b % i == 0) { return b; // not prime } break; } return b; } int main() { int n, i, a[array]; printf("How many elements does the array have?\n"); scanf("%d", &n); printf("Put in %d elements from the array!\n", n); for (i = 0; i < n; i++) { scanf("%d", &a[i]); } printf("My array is: \n"); for (i = 0; i < n; i++) { printf("%d ", a[i]); } for (i = 0; i < n; i++) { if (prime(a[i])) { int temp; temp = prost(a[i]); prime(a[i]) == prime(a[i + 1]); } } printf("\nThe new array is:\n"); printf("%d ", prime(a[i])); return 0; } I haven't learned pointers so is there a way without it or?
[ "First of all, you have a for loop that only makes one iteration because of a break keyword, also in main in a for loop with your swapping you need to assign return values from the prime function to variables, and in the same function, you should use singe '=' because you want to assign value but not to compare. Also in your same for loop, you should check if(prime(a[i+1])) so there won't be any segfaults.\n" ]
[ 0 ]
[]
[]
[ "arrays", "c", "primes", "swap" ]
stackoverflow_0074680355_arrays_c_primes_swap.txt
Q: Protected route with react router v6 What is correct way to write a ProtectedRoute with new version 6 of react-router? I wrote this one, but it's not a route const PrivateRoute = ({ component: Component, ...props }) => { if (!Component) return null; return props.isAuthenticated ? <Component /> : <Navigate to={props.redirectLink} /> } export default PrivateRoute; A: Here is my working example for implementing private routes by using useRoutes. App.js import routes from './routes'; import { useRoutes } from 'react-router-dom'; function App() { const { isLoggedIn } = useSelector((state) => state.auth); const routing = useRoutes(routes(isLoggedIn)); return ( <> {routing} </> ); } routes.js import { Navigate,Outlet } from 'react-router-dom'; const routes = (isLoggedIn) => [ { path: '/app', element: isLoggedIn ? <DashboardLayout /> : <Navigate to="/login" />, children: [ { path: '/dashboard', element: <Dashboard /> }, { path: '/account', element: <Account /> }, { path: '/', element: <Navigate to="/app/dashboard" /> }, { path: 'member', element: <Outlet />, children: [ { path: '/', element: <MemberGrid /> }, { path: '/add', element: <AddMember /> }, ], }, ], }, { path: '/', element: !isLoggedIn ? <MainLayout /> : <Navigate to="/app/dashboard" />, children: [ { path: 'login', element: <Login /> }, { path: '/', element: <Navigate to="/login" /> }, ], }, ]; export default routes; A: I took this example from react-router-dom: https://github.com/remix-run/react-router/blob/main/examples/auth/README.md Then modify into this https://stackblitz.com/edit/github-5kknft?file=src%2FApp.tsx export default function App() { return ( <AuthProvider> <Routes> <Route element={<Layout />}> <Route path="/" element={<PublicPage />} /> <Route path="/public" element={<PublicPage />} /> <Route path="/login" element={<LoginPage />} /> <Route element={<RequireAuth />}> <Route path="/protected" element={<ProtectedPage />} /> <Route path="/dashboard" element={<Dashboard />} /> </Route> </Route> <Route path="*" element={<NotFound />} /> </Routes> </AuthProvider> ); } function RequireAuth() { let auth = useAuth(); let location = useLocation(); if (!auth.user) { // Redirect them to the /login page, but save the current location they were // trying to go to when they were redirected. This allows us to send them // along to that page after they login, which is a nicer user experience // than dropping them off on the home page. return <Navigate to="/login" state={{ from: location }} />; } return <Outlet />; } A: Here is an official guideline from React Router documentation. Instead of creating wrappers for your <Route> elements to get the functionality you need, you should do all your own composition in the <Route element> prop. Taking the example from above, if you wanted to protect certain routes from non-authenticated users in React Router v6, you could do something like this: import { Routes, Route, Navigate } from "react-router-dom"; function App() { return ( <Routes> <Route path="/public" element={<PublicPage />} /> <Route path="/protected" element={ // Good! Do your composition here instead of wrapping <Route>. // This is really just inverting the wrapping, but it's a lot // more clear which components expect which props. <RequireAuth redirectTo="/login"> <ProtectedPage /> </RequireAuth> } /> </Routes> ); } function RequireAuth({ children, redirectTo }) { let isAuthenticated = getAuth(); return isAuthenticated ? children : <Navigate to={redirectTo} />; } Notice how in this example the RequireAuth component doesn't expect any of <Route>'s props. This is because it isn't trying to act like a <Route>. Instead, it's just being rendered inside a <Route>. A: Here's my latest working implementation with react-router v6 beta. I don't know how to implement a protected routes with useRoutes though. Their documentation should add an example on how to implement protected/private routes in both ways. ProtectedRoute component import React from 'react'; import PropTypes from 'prop-types'; import { Route } from 'react-router-dom'; import Forbidden from '../../views/errors/Forbidden'; import { useAuth } from '../../contexts/AuthContext'; const ProtectedRoute = ({ roles, element, children, ...rest }) => { const { user, login } = useAuth(); if (!user) { login(); return <></>; } if (roles.length > 0) { const routeRoles = roles.map((role) => role.toLowerCase()); const userRoles = (user && user.roles ? user.roles : []).map((role) => role.toLowerCase()); if (miscUtils.intersection(routeRoles, userRoles).length === 0) { return <Forbidden />; } } return ( <Route element={element} {...rest}> {children} </Route> ); }; ProtectedRoute.propTypes = { roles: PropTypes.arrayOf(PropTypes.string), element: PropTypes.element, children: PropTypes.node, }; ProtectedRoute.defaultProps = { roles: [], element: null, children: null, }; export default ProtectedRoute; AppRoutes component import React from 'react'; import { Routes, Route, Navigate, Outlet } from 'react-router-dom'; import Login from './components/oauth/Login'; import Logout from './components/oauth/Logout'; import RenewToken from './components/oauth/RenewToken'; import ProtectedRoute from './components/ProtectedRoute'; import NotFound from './views/errors/NotFound'; import Index from './views/Index'; import MainContainer from './views/MainContainer'; import ViewUserProfile from './views/user/profile/ViewUserProfile'; import CreateUserProfile from './views/user/profile/CreateUserProfile'; import UpdateUserProfile from './views/user/profile/UpdateUserProfile'; import PartnerProfile from './views/partner/profile/PartnerProfile'; const AppRoutes = () => { return ( <Routes> {/* auth pages (important: do not place under /auth path) */} <Route path="oauth/login" element={<Login />} /> <Route path="oauth/logout" element={<Logout />} /> <Route path="oauth/renew" element={<RenewToken />} /> <Route element={<MainContainer />}> <Route path="/" element={<Index />} /> {/* protected routes */} <ProtectedRoute path="user" element={<Outlet />}> <Route path="/" element={<Navigate to="profile" replace />} /> <Route path="profile" element={<Outlet />}> <Route path="/" element={<ViewUserProfile />} /> <Route path="create" element={<CreateUserProfile />} /> <Route path="update" element={<UpdateUserProfile />} /> </Route> </ProtectedRoute> <ProtectedRoute path="partner" roles={['partner']} element={<Outlet />}> <Route path="/" element={<Navigate to="profile" replace />} /> <Route path="profile" element={<PartnerProfile />} /> </ProtectedRoute> </Route> <Route path="*" element={<NotFound />} /> </Routes> ); }; export default AppRoutes; A: You would need to write a small wrapper and use Navigate component to redirect. Also you need to render a route const Container = ({Component, redirectLink, isAuthenticated, ...props}) => { if(!isAuthenticated) { return <Navigate to={redirectLink} />; } return <Component {...props} /> } const PrivateRoute = ({ component: Component, redirectLink, isAuthenticated, path, ...props }) => { return ( <Route path={path} element={<Container redirectLink={redirectLink} isAuthenticate={isAuthenticated} Component={Component} />} /> ) export default PrivateRoute; You can find the migration guidelines here on the github docs A: All good options. You can also simply render different route handling based on auth state (or any other state). You don't have to use the raw Javascript object method. Don't forget you can use an immediately invoked anonymous inner function (() => COMPONENT)() to dynamically decide what component handles a particular <Route/>. The examples may not yet be in the preliminary documentation for v6 because handling private <Route/>s is actually surprisingly simple. E.g. <Routes> {state.authed ? // Wait until we have the current user... currentUser ? <Route path='/' element={(() => { // Show a "no access" message if the user is NOT an App Admin doesn't have access to any schools at all (which includes not having access to anything INSIDE any school either) if (!currentUser.appAdministrator && currentUser.schoolIds?.length === 0) return <AdminNoAccess /> return <Outlet /> })()} > <Route path='/' element={(() => { // If the user is a super user, we return the <SuperAdmin /> component, which renders some of its own routes/nav. if (currentUser.appAdministrator) return <SuperAdmin /> return <Outlet /> })()} > <Route path='schools' element={(() => { if (currentUser.schoolIds?.length === 1) { return <Navigate to={`schools/schoolId`} /> } else { return <AdminSchools /> } })()} /> <Route path='users' children={<Users />} /> </Route> <Route path={`schools/:schoolId`} element={<AdminSchool />} /> <Route path='*' element={<Navigate to='schools' />} /> </Route> : null : <> <Route path='login' element={<Login />} /> <Route path='signup' element={<Signup />} /> <Route path='forgot-password' element={<ForgotPassword />} /> <Route path='reset-password' element={<ResetPassword />} /> <Route path='*' element={<Navigate to='login' />} /> </> } </Routes> A: Here's a slightly more TypeScript friendly implementation that reuses RouteProps from react-router v6: import React from 'react'; import { RouteProps } from 'react-router'; import { Route, Navigate } from 'react-router-dom'; import { useAuthState } from '../../contexts'; export interface PrivateRouteProps extends RouteProps { redirectPath: string; } export const PrivateRoute = ({ redirectPath, ...props }: PrivateRouteProps) => { const { user } = useAuthState(); if (!user) { return <Navigate to={redirectPath} />; } return <Route {...props} />; }; useAuthState is a hook that is able to retrieve the user if one is logged in. This is how I use it: <Routes> <Route path="/" element={<Home />} /> <PrivateRoute path="/admin" redirectPath="/signin" element={<Admin />} /> <Route path="*" element={<NotFound />} /> </Routes> A: Here is a working example. import React from 'react'; import { Route, Navigate } from 'react-router-dom'; const PrivateRoute = ({ component: Component, redirectTo, isAuth, path, ...props }) => { if(!isAuth) { return <Navigate to={redirectTo} />; } return <Route path={path} element={<Component />} /> }; export default PrivateRoute; Usage: <Routes> <Route path="app" element={<DashboardLayout />}> <PrivateRoute isAuth={true} path="account" component={AccountView} redirectTo='/login'/> </Route> </Routes> A: This is the structure for the BrowserRouter as Router: const AppRouter = () => { return ( <Router> <Layout> <Routes> <Route exact path="" element={<Home />} /> <Route exact path="login" element={<Login />} /> <Route exact path="register" element={<Register />} /> // These are the Private Components <Route exact path="/account" element={ <PrivateRoute> <Account /> </PrivateRoute> } /> <Route exact path="/quizzes" element={ <PrivateRoute> <Quizzes /> </PrivateRoute> } /> <Route exact path="/quizz/:quizzid" element={ <PrivateRoute> <Quizz /> </PrivateRoute> } /> <Route exact path="/admin/users" element={ <PrivateRoute> <Users /> </PrivateRoute> } /> <Route exact path="*" element={<NotFound />} /> </Routes> </Layout> </Router> ); }; This is the PrivateRoute: import { Navigate } from "react-router-dom"; import { useAuth } from "../auth/useAuth"; function PrivateRoute({ children }) { const auth = useAuth(); return auth.user ? children : <Navigate to="/login" />; } export default PrivateRoute; A: I don't know if this is the right way to do it but you don't actually need a private route component. You can just put all the private routes inside a component and render it conditionally as follows. In the below code, I put all the private routes inside the Private component and all the open routes inside the Public component. function RootRouter() { return ( <div> <Router> {isLoggedIn ? <PrivateRouter /> : <PublicRouter />} </Router> </div> ); } function PrivateRouter(props) { return ( <div> <ToastContainer autoClose={3000} hideProgressBar /> <NavBar /> <Routes> <Route path="/" exact element={<Home />} /> <Route path="/add" element={<Add />} /> <Route path="/update/:id" element={<Add />} /> <Route path="/view/:id" element={<Employee />} /> </Routes> </div> ); } function PublicRouter() { return ( <Routes> <Route path="/" element={<Login />} /> </Routes> ); } You can also use switch cases to allow access based on the role of the user. Note: you dont have a create a seperate components, you can actually put all the routes in a single component and render it using same conditions. A: By using replace attribute we prevent the user to use the Back browser button. PrivateRoute.js import { Navigate } from 'react-router-dom'; const PrivateRoute = ({ currentUser, children, redirectTo }) => { if (!currentUser) return <Navigate to={redirectTo} replace />; return children; }; export default PrivateRoute; Implementation: <Routes> <Route path='signIn' element={ <PrivateRoute currentUser={currentUser} redirectTo='/'> <SignInAndSignUpPage /> </PrivateRoute> } /> <Routes/> A: The correct way to write PrivateRoute code for version 6 of react-router-dom is as follows: The PrivateRoute.js file: import React from "react"; import { Navigate } from "react-router-dom"; import { useAuth } from "./contexts/AuthContext"; export { PrivateRoute }; function PrivateRoute({ children }) { const { currentUser } = useAuth(); if (!currentUser) { return <Navigate to="/" /> } return children; } The Routing in App.js file: import { Routes, Route, Navigate } from 'react-router-dom'; import { PrivateRoute } from '_components'; import { Home } from 'home'; import { Login } from 'login'; export { App }; function App() { return ( <div className="app-container bg-light"> <div className="container pt-4 pb-4"> <Routes> <Route path="/" element={ <PrivateRoute> <Home /> </PrivateRoute> } /> <Route path="/login" element={<Login />} /> <Route path="*" element={<Navigate to="/" />} /> </Routes> </div> </div> ); } A: You could use auth-react-router package https://www.npmjs.com/package/auth-react-router It provides a really simple API to define your routes and few more configurations (like redirect routes for authorized and unauthorized routes, fallback component for each of the routes) usage: define routes // routes.tsx import React from 'react'; import { IRoutesConfig } from 'auth-react-router'; import LoginPage from '../pages/LoginPage.tsx'; // public lazy loaded pages const LazyPublicPage = React.lazy(() => import('../pages/PublicPage.tsx')); // private lazy loaded pages const LazyPrivatePage = React.lazy(() => import('../pages/PrivatePage.tsx')); const LazyProfilePage = React.lazy(() => import('../pages/ProfilePage.tsx')); export const routes: IRoutesConfig = { publicRedirectRoute: '/profile', // redirect to `/profile` when authorized is trying to access public routes privateRedirectRoute: '/login', // redirect to `/login` when unauthorized user access a private route defaultFallback: <MyCustomSpinner />, public: [ { path: '/public', component: <LazyPublicPage />, }, { path: '/login', component: <LoginPage />, }, ], private: [ { path: '/private', component: <LazyPrivatePage />, }, { path: '/profile', component: <LazyProfilePage /> }, ], common: [ { path: '/', component: <p>common</p>, }, { path: '*', component: <p>page not found 404</p>, }, ], }; link them to your application import { AppRouter, Routes } from 'auth-react-router'; import { BrowserRouter } from 'react-router-dom'; import { routes } from './routes'; export const App = () => { const { isAuth } = useAuthProvider(); return ( <BrowserRouter> <AppRouter isAuth={isAuth} routes={routes}> {/* Wrap `Routes` component into a Layout component or add Header */} <Routes /> </AppRouter> </BrowserRouter> ); }; A: I tried to use all the above stated ways but don't know why nothing worked for me. Finally i solved it and here is my solution to the same: First make one file of name AdminRoute.js in "routes" folder somewhere in src. import { Typography } from "@mui/material"; import React, { useEffect, useState } from "react"; import { useSelector } from "react-redux"; import { Navigate } from "react-router-dom"; import { currentAdmin } from "../../functions/auth"; import LoadingToRedirect from "./LoadingToRedirect"; const AdminRoute = ({ children }) => { const { user } = useSelector((state) => ({ ...state, })); const [ok, setOk] = useState(false); useEffect(() => { if (user && user.token) { currentAdmin(user.token) .then((res) => { console.log("CURRENT ADMIN RES", res); setOk(true); }) .catch((err) => { console.log("ADMIN ROUTE ERR", err); setOk(false); }); } }, [user]); return ok ? children : <LoadingToRedirect />; }; export default AdminRoute; Here you can have your own logic to decide when will user e redirected and when he will not.Like in my case i'm Checking if role of user is admin or not by making one api call. Then make one LoadingToRedirect.js file in the same "routes" folder. import React, { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; const LoadingToRedirect = () => { const [count, setCount] = useState(5); let navigate = useNavigate(); useEffect(() => { const interval = setInterval(() => { setCount((currentCount) => --currentCount); }, 1000); // redirect once count is equal to 0 count === 0 && navigate("/"); // cleanup return () => clearInterval(interval); }, [count, navigate]); return ( <div className="container p-5 text-center"> <p>Redirecting you in {count} seconds</p> </div> ); }; export default LoadingToRedirect; Now set up your App.js in your app.js: Here when you go to '/check' url, the private route functionalities will come in action and it will check if the user is 'admin' or not.Here is the page which is to be protected and it acts as 'children' to <Routes> <Route path="/check" element={ <AdminRoute> <Check /> </AdminRoute> } /> <Route path="*" element={<NotFound />} /> </Routes> That's it You are ready to go. Cheers!! A: This has worked for me. const protectedPages = [ { path: '/packages', page: <PackagesPage /> }, { path: '/checkout', page: <CheckoutPage /> }, { path: '/checkout/success', page: <CheckoutSuccessPage /> }, ]; function App() { return ( <BrowserRouter> <Routes> <Route path='/' element={<AuthPage />} /> {/* Programmatically protect routes */} {protectedPages.map((p, i) => ( <Route path={p.path} element={<RequireAuth>{p.page}</RequireAuth>} key={i} /> ))} <Route path='*' element={<PageNotFound />}></Route> </Routes> </BrowserRouter> ); } const RequireAuth = ({ children }) => { const navigate = useNavigate(); const { id } = useSelector(selectUser); React.useEffect(() => { if (!id) { navigate('/'); } }, [id, navigate]); return children; }; export default App; A: if you want to remove route itself from main routes if user is not authenticated then u can use this // dummy routes const domainRoutes = [ { index: true, path: "Profile", element: <Profile/>, hidden: true, }, { path: "*", element: <AuthGuard />, }, ]; // recursive function which remove routes from default which has hidden key as true, so if user tried to access routes that is not defined we can so then auth gurad or forbidden page const Auth = ({ routes }) => { const removeisHiddenItems = (array) => { const validateHidden = (item) => { return item.isHidden; }; return array.reduce((acc, item) => { // acc -> short for "accumulator" (array) // item -> the current array item if (validateHidden(item)) { return acc; } else if (item.children) { var children = removeisHiddenItems(item.children); if (children.length) acc.push(Object.assign({}, item, { children })); } else { if (!validateHidden(item)) { acc.push(item); } } return acc; }, []); }; const filterRoutes = removeisHiddenItems(routes); const content = useRoutes(filterRoutes); return content; }; const App = () => { return ( <> <CssBaseline /> <ThemeProvider theme={currentTheme}> <Auth routes={currentContent} /> </ThemeProvider> </> ); }; export default App; A: Instead of wrapping routes, you could use wrapper component like this: index.js const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <StoreProvider> <BrowserRouter> <Routes> <Route path="/" element={<App />}> <Route index element={<Home />} /> <Route path="/login" element={<Login />} /> <Route path="/register" element={<Registration />} /> <Route path="/account" element={<Account />}> <Route index element={<AccountUser />} /> <Route path="garage" element={<AccountGarage />} /> <Route path="garage/addcar" element={<Guard component={<AddCar />} userRole="USER" />} /> <Route path="garage/mycars" element={<Guard component={<MyCars />} userRole="USER" />} /> <Route path="garage/addrepair" element={<Guard component={<AddRepair />} userRole="SERVICE" />} /> <Route path="garage/myshop" element={<Guard component={<MyShop />} userRole="SERVICE" />} /> <Route path="help" element={<AccountHelp />} /> <Route path="settings" element={<AccountSettings />} /> </Route> <Route path="/response" element={<Response />} /> <Route path="password-reset/:token" element={<Reset />} /> <Route path="*" element={<Navigate to="/" />} /> </Route> </Routes> </BrowserRouter> </StoreProvider> Guard.jsx import React from 'react'; import { Navigate } from 'react-router-dom'; import { useStore } from '../utils/store'; export default function Guard({component, userRole}) { const [{ user: { role}},] = useStore(); return role === userRole ? component : <Navigate to="/"/> } A: Recently I was also faced with the problem of protecting the routes in react-router version 6. And I was using AUth0 for the user authentication process. So, I fixed that in 3 steps. Created a page of History.js and use createBrowserHistory- import { createBrowserHistory } from "history"; export default createBrowserHistory(); Then in PrivateRoute.js I checked if the use is logged in or not using "isAuthenticated" Then in App.js I used Route and Routes like this- <Routes> <Route path="/" exact element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> <Route path="/blog" element={<Posts />} /> <Route element={<PrivateRoute/>}> <Route path="/dashboard" element={<Profile/>} /> {/* Other Routes you want to protect */} </Route> </Routes> Here I've documented that solution in my blog- Implementing Auth0 protected route
Protected route with react router v6
What is correct way to write a ProtectedRoute with new version 6 of react-router? I wrote this one, but it's not a route const PrivateRoute = ({ component: Component, ...props }) => { if (!Component) return null; return props.isAuthenticated ? <Component /> : <Navigate to={props.redirectLink} /> } export default PrivateRoute;
[ "Here is my working example for implementing private routes by using useRoutes.\nApp.js\nimport routes from './routes';\nimport { useRoutes } from 'react-router-dom';\n\nfunction App() {\n const { isLoggedIn } = useSelector((state) => state.auth);\n\n const routing = useRoutes(routes(isLoggedIn));\n\n return (\n <>\n {routing}\n </>\n );\n}\n\nroutes.js\nimport { Navigate,Outlet } from 'react-router-dom';\n\nconst routes = (isLoggedIn) => [\n {\n path: '/app',\n element: isLoggedIn ? <DashboardLayout /> : <Navigate to=\"/login\" />,\n children: [\n { path: '/dashboard', element: <Dashboard /> },\n { path: '/account', element: <Account /> },\n { path: '/', element: <Navigate to=\"/app/dashboard\" /> },\n {\n path: 'member',\n element: <Outlet />,\n children: [\n { path: '/', element: <MemberGrid /> },\n { path: '/add', element: <AddMember /> },\n ],\n },\n ],\n },\n {\n path: '/',\n element: !isLoggedIn ? <MainLayout /> : <Navigate to=\"/app/dashboard\" />,\n children: [\n { path: 'login', element: <Login /> },\n { path: '/', element: <Navigate to=\"/login\" /> },\n ],\n },\n];\n\nexport default routes;\n\n", "I took this example from react-router-dom: https://github.com/remix-run/react-router/blob/main/examples/auth/README.md\nThen modify into this https://stackblitz.com/edit/github-5kknft?file=src%2FApp.tsx\nexport default function App() {\n return (\n <AuthProvider>\n <Routes>\n <Route element={<Layout />}>\n <Route path=\"/\" element={<PublicPage />} />\n <Route path=\"/public\" element={<PublicPage />} />\n <Route path=\"/login\" element={<LoginPage />} />\n <Route element={<RequireAuth />}>\n <Route path=\"/protected\" element={<ProtectedPage />} />\n <Route path=\"/dashboard\" element={<Dashboard />} />\n </Route>\n </Route>\n <Route path=\"*\" element={<NotFound />} />\n </Routes>\n </AuthProvider>\n );\n}\n\nfunction RequireAuth() {\n let auth = useAuth();\n let location = useLocation();\n\n if (!auth.user) {\n // Redirect them to the /login page, but save the current location they were\n // trying to go to when they were redirected. This allows us to send them\n // along to that page after they login, which is a nicer user experience\n // than dropping them off on the home page.\n return <Navigate to=\"/login\" state={{ from: location }} />;\n }\n\n return <Outlet />;\n}\n\n\n", "Here is an official guideline from React Router documentation.\n\nInstead of creating wrappers for your <Route> elements to get the functionality you need, you should do all your own composition in the <Route element> prop.\nTaking the example from above, if you wanted to protect certain routes from non-authenticated users in React Router v6, you could do something like this:\n\nimport { Routes, Route, Navigate } from \"react-router-dom\";\n\nfunction App() {\n return (\n <Routes>\n <Route path=\"/public\" element={<PublicPage />} />\n <Route\n path=\"/protected\"\n element={\n // Good! Do your composition here instead of wrapping <Route>.\n // This is really just inverting the wrapping, but it's a lot\n // more clear which components expect which props.\n <RequireAuth redirectTo=\"/login\">\n <ProtectedPage />\n </RequireAuth>\n }\n />\n </Routes>\n );\n}\n\nfunction RequireAuth({ children, redirectTo }) {\n let isAuthenticated = getAuth();\n return isAuthenticated ? children : <Navigate to={redirectTo} />;\n}\n\n\nNotice how in this example the RequireAuth component doesn't expect any of <Route>'s props. This is because it isn't trying to act like a <Route>. Instead, it's just being rendered inside a <Route>.\n\n", "Here's my latest working implementation with react-router v6 beta. I don't know how to implement a protected routes with useRoutes though. Their documentation should add an example on how to implement protected/private routes in both ways.\nProtectedRoute component\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport { Route } from 'react-router-dom';\nimport Forbidden from '../../views/errors/Forbidden';\nimport { useAuth } from '../../contexts/AuthContext';\n\nconst ProtectedRoute = ({ roles, element, children, ...rest }) => {\n const { user, login } = useAuth();\n\n if (!user) {\n login();\n return <></>;\n }\n\n if (roles.length > 0) {\n const routeRoles = roles.map((role) => role.toLowerCase());\n const userRoles = (user && user.roles ? user.roles : []).map((role) => role.toLowerCase());\n if (miscUtils.intersection(routeRoles, userRoles).length === 0) {\n return <Forbidden />;\n }\n }\n\n return (\n <Route element={element} {...rest}>\n {children}\n </Route>\n );\n};\n\nProtectedRoute.propTypes = {\n roles: PropTypes.arrayOf(PropTypes.string),\n element: PropTypes.element,\n children: PropTypes.node,\n};\n\nProtectedRoute.defaultProps = {\n roles: [],\n element: null,\n children: null,\n};\n\nexport default ProtectedRoute;\n\nAppRoutes component\nimport React from 'react';\nimport { Routes, Route, Navigate, Outlet } from 'react-router-dom';\nimport Login from './components/oauth/Login';\nimport Logout from './components/oauth/Logout';\nimport RenewToken from './components/oauth/RenewToken';\nimport ProtectedRoute from './components/ProtectedRoute';\nimport NotFound from './views/errors/NotFound';\nimport Index from './views/Index';\nimport MainContainer from './views/MainContainer';\nimport ViewUserProfile from './views/user/profile/ViewUserProfile';\nimport CreateUserProfile from './views/user/profile/CreateUserProfile';\nimport UpdateUserProfile from './views/user/profile/UpdateUserProfile';\nimport PartnerProfile from './views/partner/profile/PartnerProfile';\n\nconst AppRoutes = () => {\n return (\n <Routes>\n {/* auth pages (important: do not place under /auth path) */}\n <Route path=\"oauth/login\" element={<Login />} />\n <Route path=\"oauth/logout\" element={<Logout />} />\n <Route path=\"oauth/renew\" element={<RenewToken />} />\n <Route element={<MainContainer />}>\n <Route path=\"/\" element={<Index />} />\n\n {/* protected routes */}\n <ProtectedRoute path=\"user\" element={<Outlet />}>\n <Route path=\"/\" element={<Navigate to=\"profile\" replace />} />\n\n <Route path=\"profile\" element={<Outlet />}>\n <Route path=\"/\" element={<ViewUserProfile />} />\n <Route path=\"create\" element={<CreateUserProfile />} />\n <Route path=\"update\" element={<UpdateUserProfile />} />\n </Route>\n </ProtectedRoute>\n\n <ProtectedRoute path=\"partner\" roles={['partner']} element={<Outlet />}>\n <Route path=\"/\" element={<Navigate to=\"profile\" replace />} />\n <Route path=\"profile\" element={<PartnerProfile />} />\n </ProtectedRoute>\n </Route>\n <Route path=\"*\" element={<NotFound />} />\n </Routes>\n );\n};\n\nexport default AppRoutes;\n\n", "You would need to write a small wrapper and use Navigate component to redirect. Also you need to render a route\nconst Container = ({Component, redirectLink, isAuthenticated, ...props}) => {\n if(!isAuthenticated) {\n return <Navigate to={redirectLink} />;\n }\n \n return <Component {...props} />\n}\nconst PrivateRoute = ({ component: Component, redirectLink, isAuthenticated, path, ...props }) => { \n\n return (\n <Route\n path={path}\n element={<Container redirectLink={redirectLink} isAuthenticate={isAuthenticated} Component={Component} />}\n />\n)\n\nexport default PrivateRoute;\n\nYou can find the migration guidelines here on the github docs\n", "All good options. You can also simply render different route handling based on auth state (or any other state). You don't have to use the raw Javascript object method.\nDon't forget you can use an immediately invoked anonymous inner function (() => COMPONENT)() to dynamically decide what component handles a particular <Route/>.\nThe examples may not yet be in the preliminary documentation for v6 because handling private <Route/>s is actually surprisingly simple.\nE.g.\n<Routes>\n {state.authed ?\n // Wait until we have the current user...\n currentUser ?\n <Route\n path='/'\n element={(() => {\n // Show a \"no access\" message if the user is NOT an App Admin doesn't have access to any schools at all (which includes not having access to anything INSIDE any school either)\n if (!currentUser.appAdministrator && currentUser.schoolIds?.length === 0) return <AdminNoAccess />\n return <Outlet />\n })()}\n >\n <Route\n path='/'\n element={(() => {\n // If the user is a super user, we return the <SuperAdmin /> component, which renders some of its own routes/nav.\n if (currentUser.appAdministrator) return <SuperAdmin />\n return <Outlet />\n })()}\n >\n <Route\n path='schools'\n element={(() => {\n if (currentUser.schoolIds?.length === 1) {\n return <Navigate to={`schools/schoolId`} />\n } else {\n return <AdminSchools />\n }\n })()}\n />\n\n <Route path='users' children={<Users />} />\n </Route>\n\n <Route path={`schools/:schoolId`} element={<AdminSchool />} />\n\n <Route path='*' element={<Navigate to='schools' />} />\n </Route>\n :\n null\n :\n <>\n <Route path='login' element={<Login />} />\n <Route path='signup' element={<Signup />} />\n <Route path='forgot-password' element={<ForgotPassword />} />\n <Route path='reset-password' element={<ResetPassword />} />\n\n <Route path='*' element={<Navigate to='login' />} />\n </>\n }\n </Routes>\n\n", "Here's a slightly more TypeScript friendly implementation that reuses RouteProps from react-router v6:\nimport React from 'react';\nimport { RouteProps } from 'react-router';\nimport { Route, Navigate } from 'react-router-dom';\nimport { useAuthState } from '../../contexts';\n\nexport interface PrivateRouteProps extends RouteProps {\n redirectPath: string;\n}\n\nexport const PrivateRoute = ({ redirectPath, ...props }: PrivateRouteProps) => {\n const { user } = useAuthState();\n if (!user) {\n return <Navigate to={redirectPath} />;\n }\n return <Route {...props} />;\n};\n\nuseAuthState is a hook that is able to retrieve the user if one is logged in.\nThis is how I use it:\n<Routes>\n <Route path=\"/\" element={<Home />} />\n <PrivateRoute path=\"/admin\" redirectPath=\"/signin\" element={<Admin />} />\n <Route path=\"*\" element={<NotFound />} />\n</Routes>\n\n", "Here is a working example.\nimport React from 'react';\nimport { Route, Navigate } from 'react-router-dom';\n\nconst PrivateRoute = ({ component: Component, redirectTo, isAuth, path, ...props }) => {\n if(!isAuth) {\n return <Navigate to={redirectTo} />;\n }\n return <Route path={path} element={<Component />} />\n};\n\nexport default PrivateRoute;\n\nUsage:\n<Routes>\n <Route path=\"app\" element={<DashboardLayout />}>\n <PrivateRoute isAuth={true} path=\"account\" component={AccountView} redirectTo='/login'/>\n </Route>\n </Routes>\n\n", "This is the structure for the BrowserRouter as Router:\nconst AppRouter = () => {\n return (\n <Router>\n <Layout>\n <Routes>\n <Route exact path=\"\" element={<Home />} />\n <Route exact path=\"login\" element={<Login />} />\n <Route exact path=\"register\" element={<Register />} />\n\n // These are the Private Components\n <Route\n exact\n path=\"/account\"\n element={\n <PrivateRoute>\n <Account />\n </PrivateRoute>\n }\n />\n\n <Route\n exact\n path=\"/quizzes\"\n element={\n <PrivateRoute>\n <Quizzes />\n </PrivateRoute>\n }\n />\n\n <Route\n exact\n path=\"/quizz/:quizzid\"\n element={\n <PrivateRoute>\n <Quizz />\n </PrivateRoute>\n }\n />\n\n <Route\n exact\n path=\"/admin/users\"\n element={\n <PrivateRoute>\n <Users />\n </PrivateRoute>\n }\n />\n <Route exact path=\"*\" element={<NotFound />} />\n </Routes>\n </Layout>\n </Router>\n );\n};\n\nThis is the PrivateRoute:\nimport { Navigate } from \"react-router-dom\";\nimport { useAuth } from \"../auth/useAuth\";\n\nfunction PrivateRoute({ children }) {\n const auth = useAuth();\n return auth.user ? children : <Navigate to=\"/login\" />;\n}\n\nexport default PrivateRoute;\n\n", "I don't know if this is the right way to do it but you don't actually need a private route component. You can just put all the private routes inside a component and render it conditionally as follows. In the below code, I put all the private routes inside the Private component and all the open routes inside the Public component.\n\n\nfunction RootRouter() {\n\n return (\n <div>\n <Router>\n {isLoggedIn ? <PrivateRouter /> : <PublicRouter />}\n </Router>\n </div>\n );\n}\n\nfunction PrivateRouter(props) {\n return (\n <div>\n <ToastContainer autoClose={3000} hideProgressBar />\n <NavBar />\n <Routes>\n <Route path=\"/\" exact element={<Home />} />\n <Route path=\"/add\" element={<Add />} />\n <Route path=\"/update/:id\" element={<Add />} />\n <Route path=\"/view/:id\" element={<Employee />} />\n </Routes>\n </div>\n );\n}\n\nfunction PublicRouter() {\n return (\n <Routes>\n <Route path=\"/\" element={<Login />} />\n </Routes>\n );\n}\n\n\n\nYou can also use switch cases to allow access based on the role of the user.\nNote: you dont have a create a seperate components, you can actually put all the routes in a single component and render it using same conditions.\n", "By using replace attribute we prevent the user to use the Back browser button.\nPrivateRoute.js\nimport { Navigate } from 'react-router-dom';\n\nconst PrivateRoute = ({ currentUser, children, redirectTo }) => {\n if (!currentUser) return <Navigate to={redirectTo} replace />;\n\n return children;\n};\n\nexport default PrivateRoute;\n\nImplementation:\n<Routes>\n <Route path='signIn' element={\n <PrivateRoute currentUser={currentUser} redirectTo='/'>\n <SignInAndSignUpPage />\n </PrivateRoute>\n }\n />\n<Routes/>\n\n", "The correct way to write PrivateRoute code for version 6 of react-router-dom is as follows:\nThe PrivateRoute.js file:\nimport React from \"react\";\nimport { Navigate } from \"react-router-dom\";\nimport { useAuth } from \"./contexts/AuthContext\";\n\nexport { PrivateRoute };\n\nfunction PrivateRoute({ children }) {\n\nconst { currentUser } = useAuth();\n\nif (!currentUser) {\n return <Navigate to=\"/\" />\n}\nreturn children;\n}\n\nThe Routing in App.js file:\nimport { Routes, Route, Navigate } from 'react-router-dom';\n\nimport { PrivateRoute } from '_components';\nimport { Home } from 'home';\nimport { Login } from 'login';\n\nexport { App };\n\nfunction App() {\nreturn (\n <div className=\"app-container bg-light\">\n <div className=\"container pt-4 pb-4\">\n <Routes>\n <Route\n path=\"/\"\n element={\n <PrivateRoute>\n <Home />\n </PrivateRoute>\n }\n />\n <Route path=\"/login\" element={<Login />} />\n <Route path=\"*\" element={<Navigate to=\"/\" />} />\n </Routes>\n </div>\n </div>\n);\n}\n\n", "You could use auth-react-router package https://www.npmjs.com/package/auth-react-router\nIt provides a really simple API to define your routes and few more configurations (like redirect routes for authorized and unauthorized routes, fallback component for each of the routes)\nusage:\n\ndefine routes\n\n// routes.tsx\n\nimport React from 'react';\nimport { IRoutesConfig } from 'auth-react-router';\nimport LoginPage from '../pages/LoginPage.tsx';\n\n// public lazy loaded pages\nconst LazyPublicPage = React.lazy(() => import('../pages/PublicPage.tsx'));\n\n// private lazy loaded pages\nconst LazyPrivatePage = React.lazy(() => import('../pages/PrivatePage.tsx'));\nconst LazyProfilePage = React.lazy(() => import('../pages/ProfilePage.tsx'));\n\n\nexport const routes: IRoutesConfig = {\n publicRedirectRoute: '/profile', // redirect to `/profile` when authorized is trying to access public routes\n privateRedirectRoute: '/login', // redirect to `/login` when unauthorized user access a private route\n defaultFallback: <MyCustomSpinner />,\n public: [\n {\n path: '/public',\n component: <LazyPublicPage />,\n },\n {\n path: '/login',\n component: <LoginPage />,\n },\n ],\n private: [\n {\n path: '/private',\n component: <LazyPrivatePage />,\n },\n {\n path: '/profile',\n component: <LazyProfilePage />\n },\n ],\n common: [\n {\n path: '/',\n component: <p>common</p>,\n },\n {\n path: '*',\n component: <p>page not found 404</p>,\n },\n ],\n};\n\n\nlink them to your application\n\nimport { AppRouter, Routes } from 'auth-react-router';\nimport { BrowserRouter } from 'react-router-dom';\nimport { routes } from './routes';\n\nexport const App = () => {\n const { isAuth } = useAuthProvider();\n return (\n <BrowserRouter>\n <AppRouter isAuth={isAuth} routes={routes}>\n {/* Wrap `Routes` component into a Layout component or add Header */}\n <Routes />\n </AppRouter>\n </BrowserRouter>\n );\n};\n\n", "I tried to use all the above stated ways but don't know why nothing worked for me.\nFinally i solved it and here is my solution to the same:\nFirst make one file of name AdminRoute.js in \"routes\" folder somewhere in src.\nimport { Typography } from \"@mui/material\";\nimport React, { useEffect, useState } from \"react\";\nimport { useSelector } from \"react-redux\";\nimport { Navigate } from \"react-router-dom\";\nimport { currentAdmin } from \"../../functions/auth\";\nimport LoadingToRedirect from \"./LoadingToRedirect\";\n\nconst AdminRoute = ({ children }) => {\n const { user } = useSelector((state) => ({\n ...state,\n }));\n const [ok, setOk] = useState(false);\n\n useEffect(() => {\n if (user && user.token) {\n currentAdmin(user.token)\n .then((res) => {\n console.log(\"CURRENT ADMIN RES\", res);\n setOk(true);\n })\n .catch((err) => {\n console.log(\"ADMIN ROUTE ERR\", err);\n setOk(false);\n });\n }\n }, [user]);\n return ok ? children : <LoadingToRedirect />;\n};\n\nexport default AdminRoute;\n\nHere you can have your own logic to decide when will user e redirected and when he will not.Like in my case i'm Checking if role of user is admin or not by making one api call.\nThen make one LoadingToRedirect.js file in the same \"routes\" folder.\nimport React, { useState, useEffect } from \"react\";\nimport { useNavigate } from \"react-router-dom\";\n\nconst LoadingToRedirect = () => {\n const [count, setCount] = useState(5);\n let navigate = useNavigate();\n\n useEffect(() => {\n const interval = setInterval(() => {\n setCount((currentCount) => --currentCount);\n }, 1000);\n // redirect once count is equal to 0\n count === 0 && navigate(\"/\");\n // cleanup\n return () => clearInterval(interval);\n }, [count, navigate]);\n\n return (\n <div className=\"container p-5 text-center\">\n <p>Redirecting you in {count} seconds</p>\n </div>\n );\n};\n\nexport default LoadingToRedirect;\n\nNow set up your App.js\nin your app.js:\nHere when you go to '/check' url, the private route functionalities will come in action and it will check if the user is 'admin' or not.Here is the page which is to be protected and it acts as 'children' to \n<Routes>\n <Route\n path=\"/check\"\n element={\n <AdminRoute>\n <Check />\n </AdminRoute>\n }\n />\n\n \n <Route path=\"*\" element={<NotFound />} />\n </Routes>\n\nThat's it You are ready to go.\nCheers!!\n", "This has worked for me.\nconst protectedPages = [\n { path: '/packages', page: <PackagesPage /> },\n { path: '/checkout', page: <CheckoutPage /> },\n { path: '/checkout/success', page: <CheckoutSuccessPage /> },\n];\n\nfunction App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path='/' element={<AuthPage />} />\n\n {/* Programmatically protect routes */}\n {protectedPages.map((p, i) => (\n <Route\n path={p.path}\n element={<RequireAuth>{p.page}</RequireAuth>}\n key={i}\n />\n ))}\n\n <Route path='*' element={<PageNotFound />}></Route>\n </Routes>\n </BrowserRouter>\n );\n}\n\nconst RequireAuth = ({ children }) => {\n const navigate = useNavigate();\n const { id } = useSelector(selectUser);\n\n React.useEffect(() => {\n if (!id) {\n navigate('/');\n }\n }, [id, navigate]);\n\n return children;\n};\n\nexport default App;\n\n", "if you want to remove route itself from main routes if user is not authenticated then u can use this\n// dummy routes\nconst domainRoutes = [\n {\n index: true,\n path: \"Profile\",\n element: <Profile/>,\n hidden: true,\n },\n {\n path: \"*\",\n element: <AuthGuard />,\n },\n];\n\n// recursive function which remove routes from default which has hidden key as true, so if user tried to access routes that is not defined we can so then auth gurad or forbidden page\n\nconst Auth = ({ routes }) => {\n const removeisHiddenItems = (array) => {\n const validateHidden = (item) => {\n return item.isHidden;\n };\n return array.reduce((acc, item) => {\n // acc -> short for \"accumulator\" (array)\n // item -> the current array item\n if (validateHidden(item)) {\n return acc;\n } else if (item.children) {\n var children = removeisHiddenItems(item.children);\n if (children.length) acc.push(Object.assign({}, item, { children }));\n } else {\n if (!validateHidden(item)) {\n acc.push(item);\n }\n }\n return acc;\n }, []);\n };\n\n const filterRoutes = removeisHiddenItems(routes);\n const content = useRoutes(filterRoutes);\n return content;\n};\n\nconst App = () => {\n return (\n <>\n <CssBaseline />\n <ThemeProvider theme={currentTheme}>\n <Auth routes={currentContent} />\n </ThemeProvider>\n </>\n );\n};\n\nexport default App;\n\n", "Instead of wrapping routes, you could use wrapper component like this:\nindex.js\nconst root = ReactDOM.createRoot(document.getElementById(\"root\"));\nroot.render(\n <StoreProvider>\n <BrowserRouter>\n <Routes>\n <Route path=\"/\" element={<App />}>\n <Route index element={<Home />} />\n <Route path=\"/login\" element={<Login />} />\n <Route path=\"/register\" element={<Registration />} />\n <Route path=\"/account\" element={<Account />}>\n <Route index element={<AccountUser />} />\n <Route path=\"garage\" element={<AccountGarage />} />\n <Route path=\"garage/addcar\" element={<Guard component={<AddCar />} userRole=\"USER\" />} />\n <Route path=\"garage/mycars\" element={<Guard component={<MyCars />} userRole=\"USER\" />} />\n <Route path=\"garage/addrepair\" element={<Guard component={<AddRepair />} userRole=\"SERVICE\" />} />\n <Route path=\"garage/myshop\" element={<Guard component={<MyShop />} userRole=\"SERVICE\" />} />\n <Route path=\"help\" element={<AccountHelp />} />\n <Route path=\"settings\" element={<AccountSettings />} />\n </Route>\n <Route path=\"/response\" element={<Response />} />\n <Route path=\"password-reset/:token\" element={<Reset />} />\n <Route path=\"*\" element={<Navigate to=\"/\" />} />\n </Route>\n </Routes>\n </BrowserRouter>\n </StoreProvider>\n\nGuard.jsx\nimport React from 'react';\nimport { Navigate } from 'react-router-dom';\nimport { useStore } from '../utils/store';\n\nexport default function Guard({component, userRole}) {\n const [{ user: { role}},] = useStore();\n return role === userRole ? component : <Navigate to=\"/\"/>\n}\n\n", "Recently I was also faced with the problem of protecting the routes in react-router version 6. And I was using AUth0 for the user authentication process.\nSo, I fixed that in 3 steps.\n\nCreated a page of History.js and use createBrowserHistory-\n\nimport { createBrowserHistory } from \"history\";\nexport default createBrowserHistory();\n\n\nThen in PrivateRoute.js I checked if the use is logged in or not using \"isAuthenticated\"\nThen in App.js I used Route and Routes like this-\n\n <Routes>\n <Route path=\"/\" exact element={<Home />} />\n <Route path=\"/about\" element={<About />} />\n <Route path=\"/contact\" element={<Contact />} />\n <Route path=\"/blog\" element={<Posts />} />\n <Route element={<PrivateRoute/>}>\n <Route path=\"/dashboard\" element={<Profile/>} />\n {/* Other Routes you want to protect */}\n </Route>\n </Routes>\n\nHere I've documented that solution in my blog-\nImplementing Auth0 protected route\n" ]
[ 101, 58, 28, 7, 6, 5, 4, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "react_router", "react_router_dom", "reactjs" ]
stackoverflow_0062384395_react_router_react_router_dom_reactjs.txt
Q: (Java) Letting a program display every possible combination of hex color codes. Is it possible to sometimes let a string display char and int? I know the title isn't very well asked...sorry. As you may know, a hex color code can have numbers and characters in it (#ff0000) I started by writing a little program which lists all possible combinations (16^6) and writes them in the console. This does work. Now I wanted to change the background of a j frame to the color that's currently written in the console as a hex code. Java seems to only accepts RGB combinations, so I used Color col = Color.decode(HexCode) to get these RGB values, which worked to. Now I wanted to combine these to "program" as at this point the j frame only displayed one color i place directly in the code Color col = Color.decode(#ff0000) which was not my end goal. I have the hex code positions defined as #abcdef (as ints) but for the decoding to work sometimes they don't only need to be numbers but characters. And that's my question, how does one do that ? This is my code at this point: package main; import java.awt.*; import javax.swing.*; public class Test3 { public static void main(String[] args) { int a,b,c,d,e,f; JFrame jf = new JFrame("Dima"); jf.setVisible(true); jf.setSize(100,100); jf.setLocationRelativeTo(null); for(a=0;a<=15;a++) { for(b=0;b<=15;b++) { for(c=0;c<=15;c++) { for(d=0;d<=15;d++) { for(e=0;e<=15;e++) { for(f=0;f<=15;f++) { //Hex Indikator System.out.print("#"); //Konsolenprint von a if( a == 15 ) { System.out.print("f");}else if ( a == 14 ) { System.out.print("e");}else if ( a == 13 ) { System.out.print("d");}else if ( a == 12 ) { System.out.print("c");}else if ( a == 11 ) { System.out.print("b");}else if ( a == 10 ) { System.out.print("a");}else{ System.out.print(a); } //Konsolenprint von b if( b == 15 ) { System.out.print("f");}else if ( b == 14 ) { System.out.print("e");}else if ( b == 13 ) { System.out.print("d");}else if ( b == 12 ) { System.out.print("c");}else if ( b == 11 ) { System.out.print("b");}else if ( b == 10 ) { System.out.print("a");}else { System.out.print(b); } //Konsolenprint von c if( c == 15 ) { System.out.print("f");}else if ( c == 14 ) { System.out.print("e");}else if ( c == 13 ) { System.out.print("d");}else if ( c == 12 ) { System.out.print("c");}else if ( c == 11 ) { System.out.print("b");}else if ( c == 10 ) { System.out.print("a");}else { System.out.print(c); } //Konsolenprint von d if( d == 15 ) { System.out.print("f");}else if ( d == 14 ) { System.out.print("e");}else if ( d == 13 ) { System.out.print("d");}else if ( d == 12 ) { System.out.print("c");}else if ( d == 11 ) { System.out.print("b");}else if ( d == 10 ) { System.out.print("a");}else { System.out.print(d); } //Konsolenprint von e if( e == 15 ) { System.out.print("f");}else if ( e == 14 ) { System.out.print("e");}else if ( e == 13 ) { System.out.print("d");}else if ( e == 12 ) { System.out.print("c");}else if ( e == 11 ) { System.out.print("b");}else if ( e == 10 ) { System.out.print("a");}else { System.out.print(e); } //Konsolenprint von f if( f == 15 ) { System.out.println("f");}else if ( f == 14 ) { System.out.println("e");}else if ( f == 13 ) { System.out.println("d");}else if ( f == 12 ) { System.out.println("c");}else if ( f == 11 ) { System.out.println("b");}else if ( f == 10 ) { System.out.println("a");}else { System.out.println(f); } String ColorCode = "#"; //System.out.println(" Hier ist das Problem : " + ColorCode); //Color col = Color.decode(HexCode); //jf.getContentPane().setBackground(col); } } } } } } } } I hope you understand my problem, it is a little difficult to describe it for me :/ I tried making Strings refer to other strings and tried to set strings in the if functions to a character, but it didn't work out. A: This works, I will try g00se idea later, but this works fine: import java.awt.Color; import javax.swing.*; class Test4 { public static void main(String[] args) { JFrame jf = new JFrame(); jf.setVisible(true); jf.setSize(500,500); for (int red = 0; red <= 255; red++) { for (int green = 0; green <= 255; green++) { for (int blue = 0; blue <= 255; blue++) { String redHex = String.format("%02x", red); String greenHex = String.format("%02x", green); String blueHex = String.format("%02x", blue); String colorCode = "#" + redHex + greenHex + blueHex; System.out.println(colorCode); Color col = Color.decode(colorCode); jf.getContentPane().setBackground(col); } } } } } Thanks for your help and ideas :)
(Java) Letting a program display every possible combination of hex color codes. Is it possible to sometimes let a string display char and int?
I know the title isn't very well asked...sorry. As you may know, a hex color code can have numbers and characters in it (#ff0000) I started by writing a little program which lists all possible combinations (16^6) and writes them in the console. This does work. Now I wanted to change the background of a j frame to the color that's currently written in the console as a hex code. Java seems to only accepts RGB combinations, so I used Color col = Color.decode(HexCode) to get these RGB values, which worked to. Now I wanted to combine these to "program" as at this point the j frame only displayed one color i place directly in the code Color col = Color.decode(#ff0000) which was not my end goal. I have the hex code positions defined as #abcdef (as ints) but for the decoding to work sometimes they don't only need to be numbers but characters. And that's my question, how does one do that ? This is my code at this point: package main; import java.awt.*; import javax.swing.*; public class Test3 { public static void main(String[] args) { int a,b,c,d,e,f; JFrame jf = new JFrame("Dima"); jf.setVisible(true); jf.setSize(100,100); jf.setLocationRelativeTo(null); for(a=0;a<=15;a++) { for(b=0;b<=15;b++) { for(c=0;c<=15;c++) { for(d=0;d<=15;d++) { for(e=0;e<=15;e++) { for(f=0;f<=15;f++) { //Hex Indikator System.out.print("#"); //Konsolenprint von a if( a == 15 ) { System.out.print("f");}else if ( a == 14 ) { System.out.print("e");}else if ( a == 13 ) { System.out.print("d");}else if ( a == 12 ) { System.out.print("c");}else if ( a == 11 ) { System.out.print("b");}else if ( a == 10 ) { System.out.print("a");}else{ System.out.print(a); } //Konsolenprint von b if( b == 15 ) { System.out.print("f");}else if ( b == 14 ) { System.out.print("e");}else if ( b == 13 ) { System.out.print("d");}else if ( b == 12 ) { System.out.print("c");}else if ( b == 11 ) { System.out.print("b");}else if ( b == 10 ) { System.out.print("a");}else { System.out.print(b); } //Konsolenprint von c if( c == 15 ) { System.out.print("f");}else if ( c == 14 ) { System.out.print("e");}else if ( c == 13 ) { System.out.print("d");}else if ( c == 12 ) { System.out.print("c");}else if ( c == 11 ) { System.out.print("b");}else if ( c == 10 ) { System.out.print("a");}else { System.out.print(c); } //Konsolenprint von d if( d == 15 ) { System.out.print("f");}else if ( d == 14 ) { System.out.print("e");}else if ( d == 13 ) { System.out.print("d");}else if ( d == 12 ) { System.out.print("c");}else if ( d == 11 ) { System.out.print("b");}else if ( d == 10 ) { System.out.print("a");}else { System.out.print(d); } //Konsolenprint von e if( e == 15 ) { System.out.print("f");}else if ( e == 14 ) { System.out.print("e");}else if ( e == 13 ) { System.out.print("d");}else if ( e == 12 ) { System.out.print("c");}else if ( e == 11 ) { System.out.print("b");}else if ( e == 10 ) { System.out.print("a");}else { System.out.print(e); } //Konsolenprint von f if( f == 15 ) { System.out.println("f");}else if ( f == 14 ) { System.out.println("e");}else if ( f == 13 ) { System.out.println("d");}else if ( f == 12 ) { System.out.println("c");}else if ( f == 11 ) { System.out.println("b");}else if ( f == 10 ) { System.out.println("a");}else { System.out.println(f); } String ColorCode = "#"; //System.out.println(" Hier ist das Problem : " + ColorCode); //Color col = Color.decode(HexCode); //jf.getContentPane().setBackground(col); } } } } } } } } I hope you understand my problem, it is a little difficult to describe it for me :/ I tried making Strings refer to other strings and tried to set strings in the if functions to a character, but it didn't work out.
[ "This works, I will try g00se idea later, but this works fine:\nimport java.awt.Color;\nimport javax.swing.*;\n\nclass Test4 {\n public static void main(String[] args) {\n JFrame jf = new JFrame();\n jf.setVisible(true);\n jf.setSize(500,500);\n for (int red = 0; red <= 255; red++) {\n for (int green = 0; green <= 255; green++) {\n for (int blue = 0; blue <= 255; blue++) {\n String redHex = String.format(\"%02x\", red);\n String greenHex = String.format(\"%02x\", green);\n String blueHex = String.format(\"%02x\", blue);\n\n String colorCode = \"#\" + redHex + greenHex + blueHex;\n System.out.println(colorCode);\n \n Color col = Color.decode(colorCode);\n jf.getContentPane().setBackground(col);\n }\n }\n }\n }\n}\n\nThanks for your help and ideas :)\n" ]
[ 0 ]
[]
[]
[ "hex", "integer", "java", "string" ]
stackoverflow_0074662006_hex_integer_java_string.txt
Q: Change nav bar text color in react I want to update the text color of the content inside the bar, but for some reason it doesn't work. What I've tried so far: Link a css stylesheet (it doesn't work for some reason) inline style (it only works for the company name and the cart, not for the user's name) Here is the code to my header: import React from 'react' import { Route } from 'react-router-dom' import { useDispatch, useSelector } from 'react-redux' import { LinkContainer } from 'react-router-bootstrap' import { Navbar, Nav, Container, NavDropdown } from 'react-bootstrap' import SearchBox from './SearchBox' import { logout } from '../actions/userActions' import '../index.css' //changes in index.css do not update in header.js const Header = () => { const dispatch = useDispatch() const userLogin = useSelector((state) => state.userLogin) const { userInfo } = userLogin const logoutHandler = () => { dispatch(logout()) } return ( <header> <Navbar style={{ backgroundColor: '#0a4275' }} variant="light" expand='lg' collapseOnSelect > <Container > <LinkContainer to='/'> <Navbar.Brand><span style={{ color: 'white' }}> CFM Système</span></Navbar.Brand> </LinkContainer> <Navbar.Toggle aria-controls='basic-navbar-nav' /> <Navbar.Collapse id='basic-navbar-nav'> <Route render={({ history }) => <SearchBox history={history} />} /> <Nav className='ml-auto'> <LinkContainer to='/cart'> <Nav.Link> <span style={{ color: 'white' }}> <i className='fas fa-shopping-cart'></i> Panier</span> </Nav.Link> </LinkContainer> {userInfo ? ( <NavDropdown title={userInfo.name} id='username'> <LinkContainer to='/profile'> <NavDropdown.Item>Profil</NavDropdown.Item> </LinkContainer> <NavDropdown.Item onClick={logoutHandler}> Se déconnecter </NavDropdown.Item> </NavDropdown> ) : ( <LinkContainer to='/login'> <Nav.Link> <i className='fas fa-user'></i> Se connecter </Nav.Link> </LinkContainer> )} {userInfo && userInfo.isAdmin && ( <NavDropdown title='Admin' id='adminmenu'> <LinkContainer to='/admin/userlist'> <NavDropdown.Item>Utilisateurs</NavDropdown.Item> </LinkContainer> <LinkContainer to='/admin/productlist'> <NavDropdown.Item>Produits</NavDropdown.Item> </LinkContainer> <LinkContainer to='/admin/orderlist'> <NavDropdown.Item>Commandes</NavDropdown.Item> </LinkContainer> </NavDropdown> )} </Nav> </Navbar.Collapse> </Container> </Navbar> </header> ) } export default Header I'm clearly missing something, but I'm out of solutions? Any help will be greatly appreciated :) A: To change the text color of the navigation links in the header component, you can use the color property in the inline styles applied to the a elements. Here is an example of how you could update the Header component to set the text color to white: const Header = () => { // ... return ( <header> <Navbar style={{ backgroundColor: '#0a4275' }} variant="light" expand='lg' collapseOnSelect > <Container > <LinkContainer to='/'> <Navbar.Brand><span style={{ color: 'white' }}> CFM Système</span></Navbar.Brand> </LinkContainer> <Navbar.Toggle aria-controls='basic-navbar-nav' /> <Navbar.Collapse id='basic-navbar-nav'> <Route render={({ history }) => <SearchBox history={history} />} /> <Nav className='ml-auto'> <LinkContainer to='/cart'> <Nav.Link> <span style={{ color: 'white' }}> <i className='fas fa-shopping-cart'></i> Panier</span> </Nav.Link> </LinkContainer> {userInfo ? ( <NavDropdown title={userInfo.name} id='username'> <LinkContainer to='/profile'>
Change nav bar text color in react
I want to update the text color of the content inside the bar, but for some reason it doesn't work. What I've tried so far: Link a css stylesheet (it doesn't work for some reason) inline style (it only works for the company name and the cart, not for the user's name) Here is the code to my header: import React from 'react' import { Route } from 'react-router-dom' import { useDispatch, useSelector } from 'react-redux' import { LinkContainer } from 'react-router-bootstrap' import { Navbar, Nav, Container, NavDropdown } from 'react-bootstrap' import SearchBox from './SearchBox' import { logout } from '../actions/userActions' import '../index.css' //changes in index.css do not update in header.js const Header = () => { const dispatch = useDispatch() const userLogin = useSelector((state) => state.userLogin) const { userInfo } = userLogin const logoutHandler = () => { dispatch(logout()) } return ( <header> <Navbar style={{ backgroundColor: '#0a4275' }} variant="light" expand='lg' collapseOnSelect > <Container > <LinkContainer to='/'> <Navbar.Brand><span style={{ color: 'white' }}> CFM Système</span></Navbar.Brand> </LinkContainer> <Navbar.Toggle aria-controls='basic-navbar-nav' /> <Navbar.Collapse id='basic-navbar-nav'> <Route render={({ history }) => <SearchBox history={history} />} /> <Nav className='ml-auto'> <LinkContainer to='/cart'> <Nav.Link> <span style={{ color: 'white' }}> <i className='fas fa-shopping-cart'></i> Panier</span> </Nav.Link> </LinkContainer> {userInfo ? ( <NavDropdown title={userInfo.name} id='username'> <LinkContainer to='/profile'> <NavDropdown.Item>Profil</NavDropdown.Item> </LinkContainer> <NavDropdown.Item onClick={logoutHandler}> Se déconnecter </NavDropdown.Item> </NavDropdown> ) : ( <LinkContainer to='/login'> <Nav.Link> <i className='fas fa-user'></i> Se connecter </Nav.Link> </LinkContainer> )} {userInfo && userInfo.isAdmin && ( <NavDropdown title='Admin' id='adminmenu'> <LinkContainer to='/admin/userlist'> <NavDropdown.Item>Utilisateurs</NavDropdown.Item> </LinkContainer> <LinkContainer to='/admin/productlist'> <NavDropdown.Item>Produits</NavDropdown.Item> </LinkContainer> <LinkContainer to='/admin/orderlist'> <NavDropdown.Item>Commandes</NavDropdown.Item> </LinkContainer> </NavDropdown> )} </Nav> </Navbar.Collapse> </Container> </Navbar> </header> ) } export default Header I'm clearly missing something, but I'm out of solutions? Any help will be greatly appreciated :)
[ "To change the text color of the navigation links in the header component, you can use the color property in the inline styles applied to the a elements. Here is an example of how you could update the Header component to set the text color to white:\nconst Header = () => {\n // ...\n\n return (\n <header>\n <Navbar style={{ backgroundColor: '#0a4275' }} variant=\"light\" expand='lg' collapseOnSelect >\n <Container >\n <LinkContainer to='/'>\n <Navbar.Brand><span style={{ color: 'white' }}> CFM Système</span></Navbar.Brand>\n </LinkContainer>\n <Navbar.Toggle aria-controls='basic-navbar-nav' />\n <Navbar.Collapse id='basic-navbar-nav'>\n <Route render={({ history }) => <SearchBox history={history} />} />\n <Nav className='ml-auto'>\n <LinkContainer to='/cart'>\n <Nav.Link>\n <span style={{ color: 'white' }}> <i className='fas fa-shopping-cart'></i> Panier</span>\n </Nav.Link>\n </LinkContainer>\n {userInfo ? (\n <NavDropdown title={userInfo.name} id='username'>\n <LinkContainer to='/profile'>\n \n\n" ]
[ 0 ]
[]
[]
[ "colors", "navbar", "reactjs" ]
stackoverflow_0074680373_colors_navbar_reactjs.txt
Q: Determine whether a vertex is self loop in graph I am struggling with a problem that I haven't found a solution by searching, I hope someone can help me to unblock me : Given a vertex, I want to check if it form a self loop in a directed graph or not in O(|V|). Here s a brief implementation of my graph Class : template <class T> class Digraph { public: Digraph(); ~Digraph(); bool loop(T u) const; private: std::map<T, std::set<T>> graph; } A: You could try searching for topological sorting of directed graphs. As far as I know, if a directed graph has a cycle, it cannot be topologically sorted, so the topological sorting algorithm can be used to detect whether there is a cycle. The following is a possible implementation, where adj is an array in the form of an adjacency linked list. adj[i] is a vector that represents all neighbor nodes of node i. s is the current node recSt is a stack. bool DFSRec(vector<vector<int>> adj, int s, vector<bool> visited, vector<bool> recSt) { visited[s] = true; recSt[s] = true; for (int u : adj[s]) { if (visited[u] == false && DFSRec(adj, u, visited, recSt) == true) return true; else if (recSt[u] == true) return true; } recSt[s] = false; return false; } bool DFS(vector<vector<int>> adj, int V) { vector<bool> visited(V, false); vector<bool> recSt(V, false); for (int i = 0; i < V; i++) if (visited[i] == false) if (DFSRec(adj, i, visited, recSt) == true) return true; return false; } and there is another one vector<int>kahns(vector<vector<int>> g) { int n = g.size(); vector<int> inDegree(n); for (auto edges : g) for (int to : edges) inDegree[to]++; queue<int> q; //q里包含的永远是入度为0的node for (int i = 0; i < n; i++) if (inDegree[i] == 0) q.push(i); int index = 0; vector<int> order(n); while (!q.empty()) { int at = q.front(); q.pop(); order[index++] = at; for (int to : g[at]) { inDegree[to]--; if (inDegree[to] == 0) q.push(to); } } if (index != n)return {}; //has cycle return order; } Here is a link that might be useful here is some video that may related https://www.youtube.com/watch?v=eL-KzMXSXXI https://www.youtube.com/watch?v=cIBFEhD77b4 A: Self loop means that vetrex is connected to itself by a single edge. Your graph is represented with adjacency list which means that for each vertex it contains a list (std::set in your case) of connected vertices. So, we can implement check for a self loop like this: template <class T> class Digraph { public: Digraph(); ~Digraph(); bool loop(T u) const { const auto it = graph.find(u); if (it == graph.end()) { return false; // there is no such vertex in the graph at all } return it->second.find(u) != it->second.end(); } private: std::map<T, std::set<T>> graph; } Out of your question, but I want to mention that usually to implement adjacency list representation of graph, std::unordered_map and std::unordered_set are used as those have faster lookups comparing to std::map and std::set, but keep in mind that your type T should have std::hash implemented in this case. Moreover, I'd suggest to pass u param as const reference const T& u to loop method. So with all the suggestions your class can look like next: template <class T> class Digraph { public: Digraph(); ~Digraph(); bool loop(const T& u) const { const auto it = graph.find(u); if (it == graph.end()) { return false; // there is no such vertex in the graph at all } return it->second.find(u) != it->second.end(); } private: std::unordered_map<T, std::unordered_set<T>> graph; }
Determine whether a vertex is self loop in graph
I am struggling with a problem that I haven't found a solution by searching, I hope someone can help me to unblock me : Given a vertex, I want to check if it form a self loop in a directed graph or not in O(|V|). Here s a brief implementation of my graph Class : template <class T> class Digraph { public: Digraph(); ~Digraph(); bool loop(T u) const; private: std::map<T, std::set<T>> graph; }
[ "You could try searching for topological sorting of directed graphs.\nAs far as I know, if a directed graph has a cycle, it cannot be topologically sorted, so the topological sorting algorithm can be used to detect whether there is a cycle.\nThe following is a possible implementation, where adj is an array in the form of an adjacency linked list.\nadj[i] is a vector that represents all neighbor nodes of node i.\ns is the current node\nrecSt is a stack.\nbool DFSRec(vector<vector<int>> adj, int s, vector<bool> visited, vector<bool> recSt)\n{\n visited[s] = true;\n recSt[s] = true;\n for (int u : adj[s]) {\n if (visited[u] == false && DFSRec(adj, u, visited, recSt) == true)\n return true;\n else if (recSt[u] == true)\n return true;\n }\n recSt[s] = false;\n return false;\n}\nbool DFS(vector<vector<int>> adj, int V) {\n vector<bool> visited(V, false);\n vector<bool> recSt(V, false);\n for (int i = 0; i < V; i++)\n if (visited[i] == false)\n if (DFSRec(adj, i, visited, recSt) == true)\n return true;\n return false;\n}\n\nand there is another one\n\nvector<int>kahns(vector<vector<int>> g) {\n int n = g.size();\n vector<int> inDegree(n);\n for (auto edges : g)\n for (int to : edges)\n inDegree[to]++;\n queue<int> q; //q里包含的永远是入度为0的node\n for (int i = 0; i < n; i++)\n if (inDegree[i] == 0)\n q.push(i);\n int index = 0;\n vector<int> order(n);\n while (!q.empty()) {\n int at = q.front(); q.pop();\n order[index++] = at;\n for (int to : g[at]) {\n inDegree[to]--;\n if (inDegree[to] == 0)\n q.push(to);\n }\n }\n if (index != n)return {}; //has cycle\n return order;\n}\n\nHere is a link that might be useful\nhere is some video that may related\nhttps://www.youtube.com/watch?v=eL-KzMXSXXI\nhttps://www.youtube.com/watch?v=cIBFEhD77b4\n", "Self loop means that vetrex is connected to itself by a single edge. Your graph is represented with adjacency list which means that for each vertex it contains a list (std::set in your case) of connected vertices.\nSo, we can implement check for a self loop like this:\ntemplate <class T>\nclass Digraph\n{\npublic:\n Digraph();\n ~Digraph();\n\n bool loop(T u) const {\n const auto it = graph.find(u);\n if (it == graph.end()) {\n return false; // there is no such vertex in the graph at all\n }\n return it->second.find(u) != it->second.end();\n }\nprivate:\n std::map<T, std::set<T>> graph;\n}\n\nOut of your question, but I want to mention that usually to implement adjacency list representation of graph, std::unordered_map and std::unordered_set are used as those have faster lookups comparing to std::map and std::set, but keep in mind that your type T should have std::hash implemented in this case. Moreover, I'd suggest to pass u param as const reference const T& u to loop method. So with all the suggestions your class can look like next:\ntemplate <class T>\nclass Digraph\n{\npublic:\n Digraph();\n ~Digraph();\n\n bool loop(const T& u) const {\n const auto it = graph.find(u);\n if (it == graph.end()) {\n return false; // there is no such vertex in the graph at all\n }\n return it->second.find(u) != it->second.end();\n }\nprivate:\n std::unordered_map<T, std::unordered_set<T>> graph;\n}\n\n\n" ]
[ 0, 0 ]
[]
[]
[ "algorithm", "c++", "graph" ]
stackoverflow_0074650717_algorithm_c++_graph.txt
Q: Python Add 2 Lists (Arrays) in Python How can i add 2 numbers in a List. I am trying to add 2 numbers in an array, it just shows None on the response box. The code is looking thus : def add2NumberArrays(a,b): res = [] for i in range(0,len(a)): return res.append(a[i] + b[i]) a = [4,4,7] b = [2,1,2] print(add2NumberArrays(a,b)) Why does this return none? Please help. Edits My code looks thus : def add2NumberArrays(a,b): for i in range(0,len(a)): res = [] ans = res.append(a[i]+b[i]) return ans a = [4,4,7] b = [2,1,2] print(add2NumberArrays(a,b)) A: You can use itertools.zip_longest to handle different length of two lists. from itertools import zip_longest def add2NumberArrays(a,b): # Explanation: # list(zip_longest(a, b, fillvalue=0)) # [(4, 2), (4, 1), (7, 2), (0, 2)] return [i+j for i,j in zip_longest(a, b, fillvalue=0)] a = [4,4,7] b = [2,1,2,2] print(add2NumberArrays(a,b)) # [6, 5, 9, 2] Your code need to change like below: def add2NumberArrays(a,b): res = [] for i in range(0,len(a)): res.append(a[i]+b[i]) return res # As a list comprehension # return [a[i]+b[i] for i in range(0,len(a))] a = [4,4,7] b = [2,1,2] print(add2NumberArrays(a,b)) # [6, 5, 9]
Python Add 2 Lists (Arrays) in Python
How can i add 2 numbers in a List. I am trying to add 2 numbers in an array, it just shows None on the response box. The code is looking thus : def add2NumberArrays(a,b): res = [] for i in range(0,len(a)): return res.append(a[i] + b[i]) a = [4,4,7] b = [2,1,2] print(add2NumberArrays(a,b)) Why does this return none? Please help. Edits My code looks thus : def add2NumberArrays(a,b): for i in range(0,len(a)): res = [] ans = res.append(a[i]+b[i]) return ans a = [4,4,7] b = [2,1,2] print(add2NumberArrays(a,b))
[ "You can use itertools.zip_longest to handle different length of two lists.\nfrom itertools import zip_longest\ndef add2NumberArrays(a,b):\n # Explanation: \n # list(zip_longest(a, b, fillvalue=0))\n # [(4, 2), (4, 1), (7, 2), (0, 2)]\n return [i+j for i,j in zip_longest(a, b, fillvalue=0)]\n \n\na = [4,4,7]\nb = [2,1,2,2]\n\nprint(add2NumberArrays(a,b))\n# [6, 5, 9, 2]\n\nYour code need to change like below:\ndef add2NumberArrays(a,b):\n res = []\n for i in range(0,len(a)):\n res.append(a[i]+b[i])\n return res\n\n # As a list comprehension\n # return [a[i]+b[i] for i in range(0,len(a))]\n\n\na = [4,4,7]\nb = [2,1,2]\n\nprint(add2NumberArrays(a,b))\n# [6, 5, 9]\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074680339_python.txt
Q: Data Stuctures: DFS Traversal through Simple Graph not Working c++ I am making a graph class for my data structures class and am running into problems when trying to traverse through it using a depth first search algorithm. ` class Graph{ private: int size; vector<bool> mVisited; vector<LinkedList<string> *> mGraph; int hash(string str) const; public: Graph(); Graph(int size); void insert(string sourceCity,string destinationCity); void dfs(int index); void dfs(string start); void dfs(); }; void Graph::insert(string sourceCity, string destinationCity){ int x = hash(sourceCity); string str = sourceCity; //if x space is empty create new LinkedList if(mGraph[x] == NULL){ mGraph[x] = new LinkedList<string>; mGraph[x]->addNode(sourceCity); mGraph[x]->addNode(destinationCity); return; } //if x space is alreaedy filled and is == to sourceCity add destinationCity else if(mGraph[x]->returnHead() == sourceCity){ mGraph[x]->addNode(destinationCity); return; } //if x space is filled but isn't == to sourceCity(collision) hash until empty space is found and create new Linked List else{ while(mGraph[x] != NULL){ str += "a"; x = hash(str); } mGraph[x] = new LinkedList<string>; mGraph[x]->addNode(sourceCity); mGraph[x]->addNode(destinationCity); return; } } void Graph::dfs(int index){ //makes the index in bool array = true this->mVisited[index] = true; //prints out the head city cout << mGraph[index]->returnHead() << "->"; for(int i = 0; i < mGraph[index]->size(); i++){ //if not visited do recursion if(!mVisited[i]){ dfs(i); } } } ` When I try to run it, it goes through the beginning of the lists but not anything further in. For example ` Graph g(5); g.insert("Canyon Lake", "Sun City"); g.insert("Sun City", "Menifee"); g.insert("Menifee", "Murrieta"); g.insert("Menifee", "Temecula"); g.insert("Canyon Lake", "Lake Elsinore"); g.dfs(0); ` prints out Sun City->Menifee->Canyon Lake-> While instead I want it to print out Sun City->Menifee->Murrieta->Temecula->Canyon Lake->Lake Elsinore A: I think there might be an issue with the way you are calling the dfs() function in the Graph class. In the Graph::dfs(int index) function, you are calling dfs(i) in the for loop but you are not passing the index of the linked list to the dfs() function. This might be causing it to only traverse the first linked list and not any of the other linked lists in the mGraph vector. Here is how you can fix the issue: void Graph::dfs(int index){ //makes the index in bool array = true this->mVisited[index] = true; //prints out the head city cout << mGraph[index]->returnHead() << "->"; //Iterate through the linked list starting at the head auto head = mGraph[index]->returnHead(); while (head != nullptr) { //Hash the city name and get the index of the linked list in the mGraph vector int i = hash(head->data); //If the linked list at index i has not been visited, call dfs on it if (!mVisited[i]) { dfs(i); } //Move to the next node in the linked list head = head->next; } } You can then call the dfs() function like this: //Instantiate the graph with a size of 5 Graph g(5); g.insert("Canyon Lake", "Sun City"); g.insert("Sun City", "Menifee"); g.insert("Menifee", "Murrieta"); g.insert("Menifee", "Temecula"); g.insert("Canyon Lake", "Lake Elsinore"); //Hash the start city and get the index of the linked list in the mGraph vector int start = g.hash("Canyon Lake"); //Call dfs on the linked list at index start g.dfs(start); This should print out the cities in the correct order.
Data Stuctures: DFS Traversal through Simple Graph not Working c++
I am making a graph class for my data structures class and am running into problems when trying to traverse through it using a depth first search algorithm. ` class Graph{ private: int size; vector<bool> mVisited; vector<LinkedList<string> *> mGraph; int hash(string str) const; public: Graph(); Graph(int size); void insert(string sourceCity,string destinationCity); void dfs(int index); void dfs(string start); void dfs(); }; void Graph::insert(string sourceCity, string destinationCity){ int x = hash(sourceCity); string str = sourceCity; //if x space is empty create new LinkedList if(mGraph[x] == NULL){ mGraph[x] = new LinkedList<string>; mGraph[x]->addNode(sourceCity); mGraph[x]->addNode(destinationCity); return; } //if x space is alreaedy filled and is == to sourceCity add destinationCity else if(mGraph[x]->returnHead() == sourceCity){ mGraph[x]->addNode(destinationCity); return; } //if x space is filled but isn't == to sourceCity(collision) hash until empty space is found and create new Linked List else{ while(mGraph[x] != NULL){ str += "a"; x = hash(str); } mGraph[x] = new LinkedList<string>; mGraph[x]->addNode(sourceCity); mGraph[x]->addNode(destinationCity); return; } } void Graph::dfs(int index){ //makes the index in bool array = true this->mVisited[index] = true; //prints out the head city cout << mGraph[index]->returnHead() << "->"; for(int i = 0; i < mGraph[index]->size(); i++){ //if not visited do recursion if(!mVisited[i]){ dfs(i); } } } ` When I try to run it, it goes through the beginning of the lists but not anything further in. For example ` Graph g(5); g.insert("Canyon Lake", "Sun City"); g.insert("Sun City", "Menifee"); g.insert("Menifee", "Murrieta"); g.insert("Menifee", "Temecula"); g.insert("Canyon Lake", "Lake Elsinore"); g.dfs(0); ` prints out Sun City->Menifee->Canyon Lake-> While instead I want it to print out Sun City->Menifee->Murrieta->Temecula->Canyon Lake->Lake Elsinore
[ "I think there might be an issue with the way you are calling the dfs() function in the Graph class. In the Graph::dfs(int index) function, you are calling dfs(i) in the for loop but you are not passing the index of the linked list to the dfs() function. This might be causing it to only traverse the first linked list and not any of the other linked lists in the mGraph vector.\nHere is how you can fix the issue:\nvoid Graph::dfs(int index){\n //makes the index in bool array = true\n this->mVisited[index] = true;\n //prints out the head city\n cout << mGraph[index]->returnHead() << \"->\";\n //Iterate through the linked list starting at the head\n auto head = mGraph[index]->returnHead();\n while (head != nullptr) {\n //Hash the city name and get the index of the linked list in the mGraph vector\n int i = hash(head->data);\n //If the linked list at index i has not been visited, call dfs on it\n if (!mVisited[i]) {\n dfs(i);\n }\n //Move to the next node in the linked list\n head = head->next;\n }\n}\n\nYou can then call the dfs() function like this:\n//Instantiate the graph with a size of 5\nGraph g(5);\ng.insert(\"Canyon Lake\", \"Sun City\");\ng.insert(\"Sun City\", \"Menifee\");\ng.insert(\"Menifee\", \"Murrieta\");\ng.insert(\"Menifee\", \"Temecula\");\ng.insert(\"Canyon Lake\", \"Lake Elsinore\");\n//Hash the start city and get the index of the linked list in the mGraph vector\nint start = g.hash(\"Canyon Lake\");\n//Call dfs on the linked list at index start\ng.dfs(start);\n\nThis should print out the cities in the correct order.\n" ]
[ 0 ]
[]
[]
[ "c++", "data_structures", "graph", "linked_list" ]
stackoverflow_0074680115_c++_data_structures_graph_linked_list.txt
Q: How to change the size of a TableRow in Flutter I have created a method to automatically create a weekly table, which has a row for each hour, from 7 to 22. The size of the hourly squares is too big by default, and I can't get it smaller. I would like them to be the same height as the row for the days of the week. I would also like to know how to give the TextField an id and a backgroundColor. Imagen view List<TableRow> getFilas(Size size) { List<TableRow> childs = []; childs.add(TableRow(children: [ Text("Domingo", textAlign: TextAlign.center), Text("Sábado", textAlign: TextAlign.center), Text("Viernes", textAlign: TextAlign.center), Text("Jueves", textAlign: TextAlign.center), Text("Miércoles", textAlign: TextAlign.center), Text("Martes", textAlign: TextAlign.center), Text("Lunes", textAlign: TextAlign.center), Text(" "), ])); for (int i = 7; i <= 22; i++) { childs.add(TableRow(children: [ TextField(), TextField(), TextField(), TextField(), TextField(), TextField(), TextField(), Text("${i.toString()}:00", textAlign: TextAlign.center), ])); } return childs; } I have tried with "TextScaleFactor", "maxLines" and "height". Both editing the TableRow and the TextField. A: You can set the height of each individual child in the TableRow by wrapping each child in a Container and setting the height property of the Container. TableRow( children: [ Container( height: 50, child: TextField(), ), Container( height: 50, child: TextField(), ), Container( height: 50, child: TextField(), ), // ...add other children here ], ) To give a TextField an ID, you can use the key property. This property can be used to identify and reference the TextField in your code. TextField( key: ValueKey('my_text_field'), // give the TextField an ID ) To set the background color of a TextField, you can use the decoration property and specify the fillColor property of the InputDecoration object. TextField( decoration: InputDecoration( fillColor: Colors.red ))
How to change the size of a TableRow in Flutter
I have created a method to automatically create a weekly table, which has a row for each hour, from 7 to 22. The size of the hourly squares is too big by default, and I can't get it smaller. I would like them to be the same height as the row for the days of the week. I would also like to know how to give the TextField an id and a backgroundColor. Imagen view List<TableRow> getFilas(Size size) { List<TableRow> childs = []; childs.add(TableRow(children: [ Text("Domingo", textAlign: TextAlign.center), Text("Sábado", textAlign: TextAlign.center), Text("Viernes", textAlign: TextAlign.center), Text("Jueves", textAlign: TextAlign.center), Text("Miércoles", textAlign: TextAlign.center), Text("Martes", textAlign: TextAlign.center), Text("Lunes", textAlign: TextAlign.center), Text(" "), ])); for (int i = 7; i <= 22; i++) { childs.add(TableRow(children: [ TextField(), TextField(), TextField(), TextField(), TextField(), TextField(), TextField(), Text("${i.toString()}:00", textAlign: TextAlign.center), ])); } return childs; } I have tried with "TextScaleFactor", "maxLines" and "height". Both editing the TableRow and the TextField.
[ "You can set the height of each individual child in the TableRow by wrapping each child in a Container and setting the height property of the Container.\nTableRow(\n children: [\n Container(\n height: 50,\n child: TextField(),\n ),\n Container(\n height: 50,\n child: TextField(),\n ),\n Container(\n height: 50,\n child: TextField(),\n ),\n // ...add other children here\n ],\n)\n\n\nTo give a TextField an ID, you can use the key property. This property can be used to identify and reference the TextField in your code.\nTextField(\n key: ValueKey('my_text_field'), // give the TextField an ID\n)\n\nTo set the background color of a TextField, you can use the decoration property and specify the fillColor property of the InputDecoration object.\nTextField(\n decoration: InputDecoration(\n fillColor: Colors.red\n))\n\n" ]
[ 0 ]
[]
[]
[ "flutter", "tablerow" ]
stackoverflow_0074679865_flutter_tablerow.txt
Q: C# Change value on List within class it may looks some stupid but i stopped coding for a while. I have a class 'employee' looks like this: public class Employee { public string Name { get; set; } public List<task> tasks {get; set;} public Employee(string name, List<task> ListTasks) { Name = name; tasks = new List<task>(); //tasks=ListTasks; tasks.AddRange(ListTasks); } } and a class of task: public class task { public string Titel { get; set; } public int duration { get; set; } = 0; public int maxDuration { get; set; } } after the creation of 2 (employee-)objects i try to add them to a empList and change the duration of 1 employes (task-)duration, but i always change both, what am i doing wrong ? private static void Main(string[] args) { var taskList = new List<task> { new task { Titel = "Bumm", maxDuration = 4 }, new task { Titel = "Kaban", maxDuration = 8 } }; Employee bla1 = new Employee("werner", taskList); Employee bla2 = new Employee("ecki", taskList); var empListe = new List<Employee> { bla1, bla2 }; // bla2.tasks[1].Dauer = 2; empListe[1].tasks[1].duration = 2; foreach (var name in empListe) { Console.WriteLine(name.Name); foreach (var line in name.tasks) { Console.WriteLine("{0}: {1}/{2}",line.Titel, line.duration, line.maxDuration); } } } i tried differnt ways of initiaon and linking the taskList, I wanted to use a basic tasklist for all employees, but change the value of only eg one employees tasklist independently of the rest A: Employee bla1 = new Employee("werner", taskList); Employee bla2 = new Employee("ecki", taskList); Both employees reference the same list. Passing the list does not copy it. The list only exists once. Changing it will be reflected in both employees, which reference the same list. If you want independent lists, create two separate lists with separate instances as elements: var taskList1 = new List<task> { new task { Titel = "Bumm", maxDuration = 4 }, new task { Titel = "Kaban", maxDuration = 8 } }; var taskList2 = new List<task> { new task { Titel = "Bumm", maxDuration = 4 }, new task { Titel = "Kaban", maxDuration = 8 } }; Employee bla1 = new Employee("werner", taskList1); Employee bla2 = new Employee("ecki", taskList2);
C# Change value on List within class
it may looks some stupid but i stopped coding for a while. I have a class 'employee' looks like this: public class Employee { public string Name { get; set; } public List<task> tasks {get; set;} public Employee(string name, List<task> ListTasks) { Name = name; tasks = new List<task>(); //tasks=ListTasks; tasks.AddRange(ListTasks); } } and a class of task: public class task { public string Titel { get; set; } public int duration { get; set; } = 0; public int maxDuration { get; set; } } after the creation of 2 (employee-)objects i try to add them to a empList and change the duration of 1 employes (task-)duration, but i always change both, what am i doing wrong ? private static void Main(string[] args) { var taskList = new List<task> { new task { Titel = "Bumm", maxDuration = 4 }, new task { Titel = "Kaban", maxDuration = 8 } }; Employee bla1 = new Employee("werner", taskList); Employee bla2 = new Employee("ecki", taskList); var empListe = new List<Employee> { bla1, bla2 }; // bla2.tasks[1].Dauer = 2; empListe[1].tasks[1].duration = 2; foreach (var name in empListe) { Console.WriteLine(name.Name); foreach (var line in name.tasks) { Console.WriteLine("{0}: {1}/{2}",line.Titel, line.duration, line.maxDuration); } } } i tried differnt ways of initiaon and linking the taskList, I wanted to use a basic tasklist for all employees, but change the value of only eg one employees tasklist independently of the rest
[ " Employee bla1 = new Employee(\"werner\", taskList);\n Employee bla2 = new Employee(\"ecki\", taskList);\n\nBoth employees reference the same list. Passing the list does not copy it. The list only exists once. Changing it will be reflected in both employees, which reference the same list.\nIf you want independent lists, create two separate lists with separate instances as elements:\n var taskList1 = new List<task> { \n new task\n {\n Titel = \"Bumm\",\n maxDuration = 4\n }, \n new task\n {\n Titel = \"Kaban\",\n maxDuration = 8\n } };\n\n var taskList2 = new List<task> { \n new task\n {\n Titel = \"Bumm\",\n maxDuration = 4\n }, \n new task\n {\n Titel = \"Kaban\",\n maxDuration = 8\n } };\n\n Employee bla1 = new Employee(\"werner\", taskList1);\n Employee bla2 = new Employee(\"ecki\", taskList2);\n\n" ]
[ 1 ]
[ "@knittl is correct - this is a reference issue - the lists are the same list, not copies of each other.\nOne way to fix it might look like this:\n Employee bla1 = new Employee(\"werner\", new List<task>(taskList));\n Employee bla2 = new Employee(\"ecki\", new List<task>(taskList));\n\n" ]
[ -1 ]
[ "c#", "list" ]
stackoverflow_0074680357_c#_list.txt
Q: Remove first line from a variable string, while still keeping that first line i have an array and each value of that array contains a name that i need that's located in the first line, so i need to be able to take that name, while still deleting the first line. This is what the array should look like `[0] => "name texttexttexttexttexttexttexttext texttext" [1] => "name texttexttexttexttexttexttexttext texttexttexttext"` and what i expect to have is either have the name be the key of the array like so [name] => "texttexttexttexttexttext" [name] => "texttexttexttexttexttexttext" or another array that has only has the names in it. I checked out other similar answered questions already but i hardly see how i could use explode and implode or any sort of regex on an array. A: Here is one way you can do it in PHP: $names = array(); foreach ($array as $line) { // Use the explode function to split the line into words $words = explode(" ", $line); // The name will be the first word in the line, so we get it with array_shift $name = array_shift($words); // The rest of the words in the line are the text, so we use implode to join them back into a string $text = implode(" ", $words); // Add the name and text to the $names array $names[$name] = $text; } This will loop through each line in the original array, extract the name from the first word in the line, and add it to the $names array along with the rest of the text. The resulting array will have the name as the key and the text as the value. Alternatively, if you only want an array of the names and not the text, you can just add the name to the $names array without the text: $names = array(); foreach ($array as $line) { // Use the explode function to split the line into words $words = explode(" ", $line); // The name will be the first word in the line, so we get it with array_shift $name = array_shift($words); // Add the name to the $names array $names[] = $name; } This will create an array of names without the corresponding text.
Remove first line from a variable string, while still keeping that first line
i have an array and each value of that array contains a name that i need that's located in the first line, so i need to be able to take that name, while still deleting the first line. This is what the array should look like `[0] => "name texttexttexttexttexttexttexttext texttext" [1] => "name texttexttexttexttexttexttexttext texttexttexttext"` and what i expect to have is either have the name be the key of the array like so [name] => "texttexttexttexttexttext" [name] => "texttexttexttexttexttexttext" or another array that has only has the names in it. I checked out other similar answered questions already but i hardly see how i could use explode and implode or any sort of regex on an array.
[ "Here is one way you can do it in PHP:\n$names = array();\nforeach ($array as $line) {\n // Use the explode function to split the line into words\n $words = explode(\" \", $line);\n\n // The name will be the first word in the line, so we get it with array_shift\n $name = array_shift($words);\n\n // The rest of the words in the line are the text, so we use implode to join them back into a string\n $text = implode(\" \", $words);\n\n // Add the name and text to the $names array\n $names[$name] = $text;\n}\n\nThis will loop through each line in the original array, extract the name from the first word in the line, and add it to the $names array along with the rest of the text. The resulting array will have the name as the key and the text as the value.\nAlternatively, if you only want an array of the names and not the text, you can just add the name to the $names array without the text:\n$names = array();\nforeach ($array as $line) {\n // Use the explode function to split the line into words\n $words = explode(\" \", $line);\n\n // The name will be the first word in the line, so we get it with array_shift\n $name = array_shift($words);\n\n // Add the name to the $names array\n $names[] = $name;\n}\n\nThis will create an array of names without the corresponding text.\n" ]
[ 1 ]
[]
[]
[ "arrays", "php" ]
stackoverflow_0074680427_arrays_php.txt
Q: How do I change the directory that unity is looking in for these files? So I updated my version of the unity editor and I had to delete some old ones to save space on my laptop. Unity keeps giving me this error: Image of the error because it won't let me include it for some reason Is there anyway that I can change the directory that it's looking for the missing files in? the folder it's looking for doesn't exist anymore but I should have the files in the new version of unity that I installed. A: Install all android modules when installing the editor from unity hub
How do I change the directory that unity is looking in for these files?
So I updated my version of the unity editor and I had to delete some old ones to save space on my laptop. Unity keeps giving me this error: Image of the error because it won't let me include it for some reason Is there anyway that I can change the directory that it's looking for the missing files in? the folder it's looking for doesn't exist anymore but I should have the files in the new version of unity that I installed.
[ "Install all android modules when installing the editor from unity hub\n" ]
[ 0 ]
[]
[]
[ "unity3d" ]
stackoverflow_0074680092_unity3d.txt
Q: Use of auxiliary tables in Postgresql if temporary tables don't work I'm trying to implement properly a trigger function in Postgresql. The database consists of three tables, two of which are connected by a third one which is an intermediary: Table MUSICIAN (PK = id_musician) id_musician name birth death gender nationality num_awards 1 John Lennon 1940-10-09 1980-12-08 M British 0 2 Paul McCartney 1942-06-18 NULL M British 0 3 Joep Beving 1976-01-09 NULL M Dutch 0 4 Amy Winehouse 1983-09-14 2011-07-23 F British 0 5 Wim Mertens 1953-05-14 NULL M Belgian 0 TABLE COMPOSER (PK = FK = id_musician, id_song) id_musician id_song 1 1 2 1 3 2 4 3 4 4 5 5 TABLE SONG (PK = id_song; FK = id_album) id_song title duration id_album awards 1 A Hard Day's Night 00:02:34 1 1 2 Henosis 00:06:44 2 1 3 Rehab 00:03:34 3 6 4 Back To Black 00:04:01 3 2 5 Close Cover 00:03:31 4 0 The trigger function is implemented on the table SONG for calculating the column num_awards in the table MUSICIAN and the results expected are as follows: id_musician name birth death gender nationality num_awards 1 John Lennon 1940-10-09 1980-12-08 M British 1 2 Paul McCartney 1942-06-18 NULL M British 1 3 Joep Beving 1976-01-09 NULL M Dutch 1 4 Amy Winehouse 1983-09-14 2011-07-23 F British 8 5 Wim Mertens 1953-05-14 NULL M Belgian 0 As you can see, the column num_awards sums the awards from all the songs present in the table SONG for each composer. For that purpose I've coded the following trigger function: CREATE OR REPLACE FUNCTION update_num_awards() RETURNS trigger AS $$ BEGIN CREATE TABLE IF NOT EXISTS bakcomp AS TABLE COMPOSER; CREATE TABLE IF NOT EXISTS baksong AS TABLE SONG; IF (TG_OP = 'INSERT') THEN UPDATE MUSICIAN SET num_awards = num_awards + NEW.awards WHERE id_musician IN (SELECT c.id_musician FROM COMPOSER AS c JOIN SONG ON(c.id_song = NEW.id_song)); ELSIF (TG_OP = 'UPDATE') THEN UPDATE MUSICIAN SET num_awards = num_awards + NEW.awards WHERE id_musician IN (SELECT c.id_musician FROM COMPOSER AS c JOIN SONG ON(c.id_song = NEW.id_song)); UPDATE MUSICIAN SET num_awards = num_awards - OLD.awards WHERE id_musician IN (SELECT c.id_musician FROM bakcomp AS c JOIN baksong ON(c.id_song = OLD.id_song)); ELSIF (TG_OP = 'DELETE') THEN UPDATE MUSICIAN SET num_awards = num_awards - OLD.awards WHERE id_musician IN (SELECT c.id_musician FROM bakcomp AS c JOIN baksong ON(c.id_song = OLD.id_song)); END IF; RETURN NULL; END; $$ LANGUAGE plpgsql; CREATE CONSTRAINT TRIGGER trigger_update_num_awards AFTER INSERT OR DELETE OR UPDATE ON SONG DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE PROCEDURE update_num_awards(); The function is triggered AFTER insert, delete or update in the table SONG. When inserting, coding seems pretty straightforward but when it comes to deleting things start to get difficult - the subquery I've coded doesn't work because rows may have already disappeared from the COMPOSER and SONG tables. I've tried to use temporary tables but they don't seem to work - somehow they vanish before the delete operation begins. So the only solution I've got through with is creating two permanent auxiliary tables, bakcomp and baksong, to make a copy of COMPOSER and SONG with before each delete operation. And my question is, how could temporary tables be performed in this case? Personally, despite my piece of code working correctly for what I want, I would like to improve it or to make it more simple and elegant. Any help would be greatly appreciated. Regards A: It seems like doing this on song is doing it the hard way. It's composer that has most of the effects. Delete and insert are easy. Update can be treated as a delete + insert. Composer on delete: musician.num_awards = musician.num_awards - song.awards on insert: musician.num_awards = musician.num_awards + song.awards on update old.musician.num_awards = old.musician.num_awards - old.song.awards new.musician.num_awards = new.musician.num_awards + new.song.awards When a song is inserted, it doesn't matter because it is not associated with a musician. When a song is deleted, it will cascade to delete the associated composers (assuming you've set up cascade deletes). That leaves one trigger, when a song is updated. Song on update: for all musicians who composed the song, musician.num_awards = musician.num_awards - old.awards + new.awards No temp tables should be necessary.
Use of auxiliary tables in Postgresql if temporary tables don't work
I'm trying to implement properly a trigger function in Postgresql. The database consists of three tables, two of which are connected by a third one which is an intermediary: Table MUSICIAN (PK = id_musician) id_musician name birth death gender nationality num_awards 1 John Lennon 1940-10-09 1980-12-08 M British 0 2 Paul McCartney 1942-06-18 NULL M British 0 3 Joep Beving 1976-01-09 NULL M Dutch 0 4 Amy Winehouse 1983-09-14 2011-07-23 F British 0 5 Wim Mertens 1953-05-14 NULL M Belgian 0 TABLE COMPOSER (PK = FK = id_musician, id_song) id_musician id_song 1 1 2 1 3 2 4 3 4 4 5 5 TABLE SONG (PK = id_song; FK = id_album) id_song title duration id_album awards 1 A Hard Day's Night 00:02:34 1 1 2 Henosis 00:06:44 2 1 3 Rehab 00:03:34 3 6 4 Back To Black 00:04:01 3 2 5 Close Cover 00:03:31 4 0 The trigger function is implemented on the table SONG for calculating the column num_awards in the table MUSICIAN and the results expected are as follows: id_musician name birth death gender nationality num_awards 1 John Lennon 1940-10-09 1980-12-08 M British 1 2 Paul McCartney 1942-06-18 NULL M British 1 3 Joep Beving 1976-01-09 NULL M Dutch 1 4 Amy Winehouse 1983-09-14 2011-07-23 F British 8 5 Wim Mertens 1953-05-14 NULL M Belgian 0 As you can see, the column num_awards sums the awards from all the songs present in the table SONG for each composer. For that purpose I've coded the following trigger function: CREATE OR REPLACE FUNCTION update_num_awards() RETURNS trigger AS $$ BEGIN CREATE TABLE IF NOT EXISTS bakcomp AS TABLE COMPOSER; CREATE TABLE IF NOT EXISTS baksong AS TABLE SONG; IF (TG_OP = 'INSERT') THEN UPDATE MUSICIAN SET num_awards = num_awards + NEW.awards WHERE id_musician IN (SELECT c.id_musician FROM COMPOSER AS c JOIN SONG ON(c.id_song = NEW.id_song)); ELSIF (TG_OP = 'UPDATE') THEN UPDATE MUSICIAN SET num_awards = num_awards + NEW.awards WHERE id_musician IN (SELECT c.id_musician FROM COMPOSER AS c JOIN SONG ON(c.id_song = NEW.id_song)); UPDATE MUSICIAN SET num_awards = num_awards - OLD.awards WHERE id_musician IN (SELECT c.id_musician FROM bakcomp AS c JOIN baksong ON(c.id_song = OLD.id_song)); ELSIF (TG_OP = 'DELETE') THEN UPDATE MUSICIAN SET num_awards = num_awards - OLD.awards WHERE id_musician IN (SELECT c.id_musician FROM bakcomp AS c JOIN baksong ON(c.id_song = OLD.id_song)); END IF; RETURN NULL; END; $$ LANGUAGE plpgsql; CREATE CONSTRAINT TRIGGER trigger_update_num_awards AFTER INSERT OR DELETE OR UPDATE ON SONG DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE PROCEDURE update_num_awards(); The function is triggered AFTER insert, delete or update in the table SONG. When inserting, coding seems pretty straightforward but when it comes to deleting things start to get difficult - the subquery I've coded doesn't work because rows may have already disappeared from the COMPOSER and SONG tables. I've tried to use temporary tables but they don't seem to work - somehow they vanish before the delete operation begins. So the only solution I've got through with is creating two permanent auxiliary tables, bakcomp and baksong, to make a copy of COMPOSER and SONG with before each delete operation. And my question is, how could temporary tables be performed in this case? Personally, despite my piece of code working correctly for what I want, I would like to improve it or to make it more simple and elegant. Any help would be greatly appreciated. Regards
[ "It seems like doing this on song is doing it the hard way. It's composer that has most of the effects. Delete and insert are easy. Update can be treated as a delete + insert.\n\nComposer\n\non delete: musician.num_awards = musician.num_awards - song.awards\non insert: musician.num_awards = musician.num_awards + song.awards\non update\n\nold.musician.num_awards = old.musician.num_awards - old.song.awards\nnew.musician.num_awards = new.musician.num_awards + new.song.awards\n\n\n\n\n\nWhen a song is inserted, it doesn't matter because it is not associated with a musician. When a song is deleted, it will cascade to delete the associated composers (assuming you've set up cascade deletes). That leaves one trigger, when a song is updated.\n\nSong\n\non update: for all musicians who composed the song, musician.num_awards = musician.num_awards - old.awards + new.awards\n\n\n\nNo temp tables should be necessary.\n" ]
[ 0 ]
[]
[]
[ "postgresql", "sql" ]
stackoverflow_0074679719_postgresql_sql.txt
Q: How to save manytomany in laravel I am trying to save manyto many in laravel. I have been trying for almost 7 hours. But still can't solve this issue. Here is custom migration table: public function up() { Schema::create('customer', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->string("customer_phone", 255); }); } Here is my send_messages migration table: public function up() { Schema::create('send_messages', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->unsignedBigInteger("template_id"); $table->unsignedBigInteger("sender_number_id"); // $table->unsignedBigInteger("cutomer_id"); $table->foreign("template_id")->references("id")->on("messagecontent")->onDelete("cascade"); $table->foreign("sender_number_id")->references("id")->on("sendernumber")->onDelete("cascade"); // $table->foreign("customer_id")->references("id")->on("customer")->onDelete("cascade"); }); } Here is my pivot table: Schema::create('customer_send_message', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->foreignId("send_messages_id")->constrained("send_messages"); $table->foreignId("customer_id")->constrained("customer"); }); Here is CustomerModel class Customer extends Model { use HasFactory; protected $table = "customer"; protected $fillable = [ "customer_phone" ]; public function sendmessage () { return $this->belongsToMany(SendMessage::class, "customer_send_message"); } } Here is my SendMessageModel class SendMessage extends Model { use HasFactory; protected $table = "send_messages"; protected $fillable = [ "customer_id", "template_id", "sender_number_id" ]; public function messageContent() { return $this->belongsTo(MessageContentModel::class); } public function senderNumber() { return $this->belongsTo(SendNumberModel::class); } public function customer() { return $this->belongsToMany(Customer::class, "customer_send_message"); } } Here is my controller I am trying to save: public function send(Request $request) { $sendmessage = new SendMessage(); $sendmessage->template_id = $request->get("template_id"); $sendmessage->sender_number_id = $request->get("sender_number_id"); $customers = Customer::find(1); $sendmessage->customer()->attach($customers); $sendmessage->save(); // $send->save(); return redirect("")->with("message", "Sms sent!"); } I want to get multiple data then I want to save it just like django manytomanyfield. Acutally I was a django developer I recently switched to laravel. I don't know so many things. So Is there any solution for solving this issue? I just want to save. I am getting an error while saving : SQLSTATE[42S22]: Column not found: 1054 Unknown column 'send_message_id' in 'field list' I don't know why I am getting this error!! A: Due to laravel's 'convention over configuration' policy, it tends to make some assumptions regarding your column names. If the column names don't match those assumptions, you run into these kind of issues. IIRC, the problem here is that your class name is SendMessage, from which Laravel will deduce the foreign key on your pivot table is send_message_id, it is however send_messages_id. You should be able to fix this by changing your relation definition in SendMessage: public function customer() { return $this->belongsToMany( Customer::class, 'customer_send_message', 'send_messages_id' ); }
How to save manytomany in laravel
I am trying to save manyto many in laravel. I have been trying for almost 7 hours. But still can't solve this issue. Here is custom migration table: public function up() { Schema::create('customer', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->string("customer_phone", 255); }); } Here is my send_messages migration table: public function up() { Schema::create('send_messages', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->unsignedBigInteger("template_id"); $table->unsignedBigInteger("sender_number_id"); // $table->unsignedBigInteger("cutomer_id"); $table->foreign("template_id")->references("id")->on("messagecontent")->onDelete("cascade"); $table->foreign("sender_number_id")->references("id")->on("sendernumber")->onDelete("cascade"); // $table->foreign("customer_id")->references("id")->on("customer")->onDelete("cascade"); }); } Here is my pivot table: Schema::create('customer_send_message', function (Blueprint $table) { $table->id(); $table->timestamps(); $table->foreignId("send_messages_id")->constrained("send_messages"); $table->foreignId("customer_id")->constrained("customer"); }); Here is CustomerModel class Customer extends Model { use HasFactory; protected $table = "customer"; protected $fillable = [ "customer_phone" ]; public function sendmessage () { return $this->belongsToMany(SendMessage::class, "customer_send_message"); } } Here is my SendMessageModel class SendMessage extends Model { use HasFactory; protected $table = "send_messages"; protected $fillable = [ "customer_id", "template_id", "sender_number_id" ]; public function messageContent() { return $this->belongsTo(MessageContentModel::class); } public function senderNumber() { return $this->belongsTo(SendNumberModel::class); } public function customer() { return $this->belongsToMany(Customer::class, "customer_send_message"); } } Here is my controller I am trying to save: public function send(Request $request) { $sendmessage = new SendMessage(); $sendmessage->template_id = $request->get("template_id"); $sendmessage->sender_number_id = $request->get("sender_number_id"); $customers = Customer::find(1); $sendmessage->customer()->attach($customers); $sendmessage->save(); // $send->save(); return redirect("")->with("message", "Sms sent!"); } I want to get multiple data then I want to save it just like django manytomanyfield. Acutally I was a django developer I recently switched to laravel. I don't know so many things. So Is there any solution for solving this issue? I just want to save. I am getting an error while saving : SQLSTATE[42S22]: Column not found: 1054 Unknown column 'send_message_id' in 'field list' I don't know why I am getting this error!!
[ "Due to laravel's 'convention over configuration' policy, it tends to make some assumptions regarding your column names. If the column names don't match those assumptions, you run into these kind of issues. IIRC, the problem here is that your class name is SendMessage, from which Laravel will deduce the foreign key on your pivot table is send_message_id, it is however send_messages_id.\nYou should be able to fix this by changing your relation definition in SendMessage:\npublic function customer() {\n return $this->belongsToMany(\n Customer::class, \n 'customer_send_message', \n 'send_messages_id'\n );\n}\n\n" ]
[ 1 ]
[]
[]
[ "laravel", "php" ]
stackoverflow_0074679834_laravel_php.txt
Q: Extend date intervals by two different IDs in R I have a big data.frame where I can find a municipality id for each person(id) over time. Sometimes they move and there will be a new municipality_id from the next day on. However, sometimes the municipality_id stays the same. I would like to collapse those date intervals by each id if there is no real change in municipality_id This data id municipality_id from to 1 A 820 2007-01-01 2007-02-28 2 A 200 2007-03-01 2100-01-01 3 B 820 2007-01-01 2007-03-31 4 B 820 2007-04-01 2007-05-31 5 B 830 2007-06-01 2008-01-31 6 B 830 2008-02-01 2100-01-01 7 C 700 2007-01-01 2007-05-31 8 C 500 2007-06-01 2008-12-31 9 C 700 2009-01-01 2100-01-01 should turn into this (two observations for B were extended) id municipality_id from to 1 A 820 2007-01-01 2007-02-28 2 A 200 2007-03-01 2100-01-01 3 B 820 2007-01-01 2007-05-31 4 B 830 2007-06-01 2100-01-01 5 C 700 2007-01-01 2007-05-31 6 C 500 2007-06-01 2008-12-31 7 C 700 2009-01-01 2100-01-01 Here the code to create my two tables: data <- data.frame(id = c('A', 'A', 'B', 'B','B', 'B', 'C', 'C', 'C'), municipality_id = c(820, 200, 820, 820, 830, 830, 700, 500, 700), from = as.Date(c("2007-01-01", "2007-03-01", "2007-01-01", "2007-04-01", "2007-06-01", "2008-02-01", "2007-01-01", "2007-06-01", "2009-01-01")), to = as.Date(c("2007-02-28", "2100-01-01", "2007-03-31", "2007-05-31", "2008-01-31", "2100-01-01", "2007-05-31", "2008-12-31", "2100-01-01"))) Should turn into: data_edit <- data.frame(id = c('A', 'A', 'B', 'B', 'C', 'C', 'C'), municipality_id = c(820, 200, 820, 830, 700, 500, 700), from = as.Date(c("2007-01-01", "2007-03-01", "2007-01-01", "2007-06-01", "2007-01-01", "2007-06-01", "2009-01-01")), to = as.Date(c("2007-02-28", "2100-01-01", "2007-05-31", "2100-01-01", "2007-05-31", "2008-12-31", "2100-01-01"))) Is there an easy solution with R? Thank you for helping me :) A: How about this: data <- data.frame(id = c('A', 'A', 'B', 'B','B', 'B', 'C', 'C', 'C'), municipality_id = c(820, 200, 820, 820, 830, 830, 700, 500, 700), from = as.Date(c("2007-01-01", "2007-03-01", "2007-01-01", "2007-04-01", "2007-06-01", "2008-02-01", "2007-01-01", "2007-06-01", "2009-01-01")), to = as.Date(c("2007-02-28", "2100-01-01", "2007-03-31", "2007-05-31", "2008-01-31", "2100-01-01", "2007-05-31", "2008-12-31", "2100-01-01"))) library(tidyr) library(dplyr) data %>% pivot_longer(from:to, names_to="frto", values_to="vals") %>% group_by(id, municipality_id) %>% summarise(from = min(vals), to=max(vals)) %>% ungroup %>% arrange(id, from) #> `summarise()` has grouped output by 'id'. You can override using the `.groups` #> argument. #> # A tibble: 6 × 4 #> id municipality_id from to #> <chr> <dbl> <date> <date> #> 1 A 820 2007-01-01 2007-02-28 #> 2 A 200 2007-03-01 2100-01-01 #> 3 B 820 2007-01-01 2007-05-31 #> 4 B 830 2007-06-01 2100-01-01 #> 5 C 700 2007-01-01 2100-01-01 #> 6 C 500 2007-06-01 2008-12-31 Created on 2022-12-04 by the reprex package (v2.0.1)
Extend date intervals by two different IDs in R
I have a big data.frame where I can find a municipality id for each person(id) over time. Sometimes they move and there will be a new municipality_id from the next day on. However, sometimes the municipality_id stays the same. I would like to collapse those date intervals by each id if there is no real change in municipality_id This data id municipality_id from to 1 A 820 2007-01-01 2007-02-28 2 A 200 2007-03-01 2100-01-01 3 B 820 2007-01-01 2007-03-31 4 B 820 2007-04-01 2007-05-31 5 B 830 2007-06-01 2008-01-31 6 B 830 2008-02-01 2100-01-01 7 C 700 2007-01-01 2007-05-31 8 C 500 2007-06-01 2008-12-31 9 C 700 2009-01-01 2100-01-01 should turn into this (two observations for B were extended) id municipality_id from to 1 A 820 2007-01-01 2007-02-28 2 A 200 2007-03-01 2100-01-01 3 B 820 2007-01-01 2007-05-31 4 B 830 2007-06-01 2100-01-01 5 C 700 2007-01-01 2007-05-31 6 C 500 2007-06-01 2008-12-31 7 C 700 2009-01-01 2100-01-01 Here the code to create my two tables: data <- data.frame(id = c('A', 'A', 'B', 'B','B', 'B', 'C', 'C', 'C'), municipality_id = c(820, 200, 820, 820, 830, 830, 700, 500, 700), from = as.Date(c("2007-01-01", "2007-03-01", "2007-01-01", "2007-04-01", "2007-06-01", "2008-02-01", "2007-01-01", "2007-06-01", "2009-01-01")), to = as.Date(c("2007-02-28", "2100-01-01", "2007-03-31", "2007-05-31", "2008-01-31", "2100-01-01", "2007-05-31", "2008-12-31", "2100-01-01"))) Should turn into: data_edit <- data.frame(id = c('A', 'A', 'B', 'B', 'C', 'C', 'C'), municipality_id = c(820, 200, 820, 830, 700, 500, 700), from = as.Date(c("2007-01-01", "2007-03-01", "2007-01-01", "2007-06-01", "2007-01-01", "2007-06-01", "2009-01-01")), to = as.Date(c("2007-02-28", "2100-01-01", "2007-05-31", "2100-01-01", "2007-05-31", "2008-12-31", "2100-01-01"))) Is there an easy solution with R? Thank you for helping me :)
[ "How about this:\ndata <- data.frame(id = c('A', 'A', 'B', 'B','B', 'B', 'C', 'C', 'C'),\n municipality_id = c(820, 200, 820, 820, 830, 830, 700, 500, 700),\n from = as.Date(c(\"2007-01-01\", \"2007-03-01\", \"2007-01-01\", \"2007-04-01\", \"2007-06-01\", \"2008-02-01\", \"2007-01-01\", \"2007-06-01\", \"2009-01-01\")),\n to = as.Date(c(\"2007-02-28\", \"2100-01-01\", \"2007-03-31\", \"2007-05-31\", \"2008-01-31\", \"2100-01-01\", \"2007-05-31\", \"2008-12-31\", \"2100-01-01\"))) \n\nlibrary(tidyr)\nlibrary(dplyr)\ndata %>% \n pivot_longer(from:to, names_to=\"frto\", values_to=\"vals\") %>% \n group_by(id, municipality_id) %>% \n summarise(from = min(vals), to=max(vals)) %>% \n ungroup %>% \n arrange(id, from)\n#> `summarise()` has grouped output by 'id'. You can override using the `.groups`\n#> argument.\n#> # A tibble: 6 × 4\n#> id municipality_id from to \n#> <chr> <dbl> <date> <date> \n#> 1 A 820 2007-01-01 2007-02-28\n#> 2 A 200 2007-03-01 2100-01-01\n#> 3 B 820 2007-01-01 2007-05-31\n#> 4 B 830 2007-06-01 2100-01-01\n#> 5 C 700 2007-01-01 2100-01-01\n#> 6 C 500 2007-06-01 2008-12-31\n\nCreated on 2022-12-04 by the reprex package (v2.0.1)\n" ]
[ 0 ]
[]
[]
[ "date", "group_by", "intervals", "lubridate", "r" ]
stackoverflow_0074680226_date_group_by_intervals_lubridate_r.txt
Q: hasOwnProperty always returns false on object with variable properties I'm consuming some k8s objects with typescript and my json looks like this: { "startTime": "2022-12-01T19:15:58Z", "taskRuns": { "task1": { "pipelineTaskName": "task1Ref", "status": { "completionTime": "2022-12-01T19:17:27Z", "conditions": [ { "lastTransitionTime": "2022-12-01T19:17:27Z", "message": "", "reason": "TaskRunImagePullFailed", "status": "False", "type": "Succeeded" } ]}}, "task2":{same fields as task1}, "task3": {same} }} I also have an array with the TaskRun names which looks like the following: ["task1","task2",....] The relevant interface for the object above looks like: export interface PipelineRunStatus { startTime: string; taskRuns: Truns; } export interface Truns { [key: string]: TaskRun; } export interface TaskRUn {<fields from above>} I'm trying to match the array elements to the variable task keys in a taskrun and extract information with the code below: type taskRunKey = keyof typeof currentRun.Status.taskRuns //taskRuns is my string array taskRuns.map((taskRunName: string) => { console.log(taskRunName) if (currentRun?.Status?.taskRuns?.hasOwnProperty(taskRunName as taskRunKey)) console.log(currentRun.Status?.taskRuns[taskRunName as status?.conditions[0]) else { console.log(currentRun?.Status?.taskRuns) console.log(currentRun?.Status) } but this prints task1 undefined Object { TaskRuns: {… task1:{..the object above...}}} ​ task2 undefined Object { TaskRuns: {… pretty much the object above...}} ​ etc In short: the code above always ends up in the "else" branch of the statement despite the fact that there is an object property with the correct name that matches. Can someone please explain what am I missing? A: It looks like you're using the map() method on taskRuns, but taskRuns isn't an array. It's an object, and the map() method only works on arrays. To fix this, you can use a regular for loop to iterate over the keys of taskRuns like this: for (let taskRunName in currentRun?.Status?.taskRuns) { console.log(taskRunName) if (currentRun?.Status?.taskRuns?.hasOwnProperty(taskRunName as taskRunKey)) console.log(currentRun.Status?.taskRuns[taskRunName as status?.conditions[0]) else { console.log(currentRun?.Status?.taskRuns) console.log(currentRun?.Status) } } Alternatively, you could use the Object.keys() method to get an array of keys from currentRun.Status.taskRuns, and then use the map() method on that array. Object.keys(currentRun?.Status?.taskRuns).map((taskRunName: string) => { console.log(taskRunName) if (currentRun?.Status?.taskRuns?.hasOwnProperty(taskRunName as taskRunKey)) console.log(currentRun.Status?.taskRuns[taskRunName as status?.conditions[0]) else { console.log(currentRun?.Status?.taskRuns) console.log(currentRun?.Status) } }) I hope this helps! Let me know if you have any other questions. A: Turns out I had a few things wrong: Typo in "taskRuns" it should be "TaskRuns" and typescript for some reason doesn't deserialise JSON case insensitive (like golang does). I changed my types to be export interface PipelineRunStatus { startTime: string; TaskRuns: Truns; } hasOwnProperty is incorrect, I needed instead : Object.keys(currentRun?.Status?.TaskRuns).includes(taskRunName) Thank you everyone who spent time on this!
hasOwnProperty always returns false on object with variable properties
I'm consuming some k8s objects with typescript and my json looks like this: { "startTime": "2022-12-01T19:15:58Z", "taskRuns": { "task1": { "pipelineTaskName": "task1Ref", "status": { "completionTime": "2022-12-01T19:17:27Z", "conditions": [ { "lastTransitionTime": "2022-12-01T19:17:27Z", "message": "", "reason": "TaskRunImagePullFailed", "status": "False", "type": "Succeeded" } ]}}, "task2":{same fields as task1}, "task3": {same} }} I also have an array with the TaskRun names which looks like the following: ["task1","task2",....] The relevant interface for the object above looks like: export interface PipelineRunStatus { startTime: string; taskRuns: Truns; } export interface Truns { [key: string]: TaskRun; } export interface TaskRUn {<fields from above>} I'm trying to match the array elements to the variable task keys in a taskrun and extract information with the code below: type taskRunKey = keyof typeof currentRun.Status.taskRuns //taskRuns is my string array taskRuns.map((taskRunName: string) => { console.log(taskRunName) if (currentRun?.Status?.taskRuns?.hasOwnProperty(taskRunName as taskRunKey)) console.log(currentRun.Status?.taskRuns[taskRunName as status?.conditions[0]) else { console.log(currentRun?.Status?.taskRuns) console.log(currentRun?.Status) } but this prints task1 undefined Object { TaskRuns: {… task1:{..the object above...}}} ​ task2 undefined Object { TaskRuns: {… pretty much the object above...}} ​ etc In short: the code above always ends up in the "else" branch of the statement despite the fact that there is an object property with the correct name that matches. Can someone please explain what am I missing?
[ "It looks like you're using the map() method on taskRuns, but taskRuns isn't an array. It's an object, and the map() method only works on arrays.\nTo fix this, you can use a regular for loop to iterate over the keys of taskRuns like this:\nfor (let taskRunName in currentRun?.Status?.taskRuns) {\n console.log(taskRunName)\n\n if (currentRun?.Status?.taskRuns?.hasOwnProperty(taskRunName as taskRunKey))\n console.log(currentRun.Status?.taskRuns[taskRunName as status?.conditions[0])\n else {\n console.log(currentRun?.Status?.taskRuns)\n console.log(currentRun?.Status)\n }\n}\n\nAlternatively, you could use the Object.keys() method to get an array of keys from currentRun.Status.taskRuns, and then use the map() method on that array.\nObject.keys(currentRun?.Status?.taskRuns).map((taskRunName: string) => {\n console.log(taskRunName)\n\n if (currentRun?.Status?.taskRuns?.hasOwnProperty(taskRunName as taskRunKey))\n console.log(currentRun.Status?.taskRuns[taskRunName as status?.conditions[0])\n else {\n console.log(currentRun?.Status?.taskRuns)\n console.log(currentRun?.Status)\n }\n})\n\nI hope this helps! Let me know if you have any other questions.\n", "Turns out I had a few things wrong:\n\nTypo in \"taskRuns\" it should be \"TaskRuns\" and typescript for some reason doesn't deserialise JSON case insensitive (like golang does). I changed my types to be\nexport interface PipelineRunStatus { startTime: string; TaskRuns: Truns; }\nhasOwnProperty is incorrect, I needed instead : Object.keys(currentRun?.Status?.TaskRuns).includes(taskRunName)\n\nThank you everyone who spent time on this!\n" ]
[ 1, 0 ]
[]
[]
[ "dictionary", "properties", "typescript" ]
stackoverflow_0074671079_dictionary_properties_typescript.txt
Q: Stop urllib.request from raising exceptions on HTTP errors Python's urllib.request.urlopen() will raise an exception if the HTTP status code of the request is not OK (e.g., 404). This is because the default opener uses the HTTPDefaultErrorHandler class: A class which defines a default handler for HTTP error responses; all responses are turned into HTTPError exceptions. Even if you build your own opener, it (un)helpfully includes the HTTPDefaultErrorHandler for you implicitly. If, however, you don't want Python to raise an exception if you get a non-OK response, it's unclear how to disable this behavior.
Stop urllib.request from raising exceptions on HTTP errors
Python's urllib.request.urlopen() will raise an exception if the HTTP status code of the request is not OK (e.g., 404). This is because the default opener uses the HTTPDefaultErrorHandler class: A class which defines a default handler for HTTP error responses; all responses are turned into HTTPError exceptions. Even if you build your own opener, it (un)helpfully includes the HTTPDefaultErrorHandler for you implicitly. If, however, you don't want Python to raise an exception if you get a non-OK response, it's unclear how to disable this behavior.
[]
[]
[ "I'll be very clear, I'm answering this question to test GPT. That's not my answer, I don't know the anwser. But I asked GPT.\nIf this offends anyone, feel free to delete my message.\n\nTo disable the automatic raising of exceptions for non-OK HTTP status codes, you can create your own HTTPErrorProcessor class that extends the urllib.request.HTTPDefaultErrorHandler class and overrides the http_error_default() method, like this:\nfrom urllib.request import HTTPErrorProcessor, HTTPDefaultErrorHandler\nclass MyHTTPErrorProcessor(HTTPErrorProcessor, HTTPDefaultErrorHandler):\n def http_error_default(self, req, fp, code, msg, headers):\n # do nothing and return the response object\n return fp\n\nThen, when you create an OpenerDirector object and add the handler for HTTP errors, you can use your custom MyHTTPErrorProcessor class instead of the default HTTPDefaultErrorHandler class, like this:\nfrom urllib.request import build_opener, HTTPHandler, OpenerDirector\n\n# create an OpenerDirector object\nopener = build_opener(HTTPHandler)\n\n# add the custom HTTPErrorProcessor to the opener\nopener.add_handler(MyHTTPErrorProcessor())\n\nNow, when you make a request using this opener, Python will not automatically raise an exception for non-OK HTTP status codes. You can check the HTTP status code of the response and handle it as needed, like this:\n# make a request using the opener\nresponse = opener.open(\"https://www.example.com\")\n\n# check the HTTP status code of the response\nif response.code != 200:\n print(\"Received non-OK HTTP status code:\", response.code)\nelse:\n # process the response\n ...\n\nPlease note that this solution only applies to the urllib.request module in Python 2. In Python 3, the urllib.request module has been split into several smaller modules, and the urllib.request.urlopen() function has been moved to the urllib.request.urlopen() function in the urllib.request module. The solution for disabling the automatic raising of exceptions for non-OK HTTP status codes in Python 3 is similar, but the syntax and the classes used are slightly different.\n" ]
[ -2 ]
[ "python", "urllib" ]
stackoverflow_0074680393_python_urllib.txt
Q: Generating URLs when running a discord command I was just wondering how would I go about generating a URL for a user when they run a discord bot command. So once they run the command it will generate a URL for them, then once they click a button on my website they'll be given a role. I know I'll have to use discord.js & express but how would I go about doing this. A: o generate a URL for a user when they run a Discord bot command, you would first need to create a bot for your Discord server. You can do this by going to the Discord Developer Portal and following the instructions there. Once you have created your bot, you will need to use the Discord.js library to access the Discord API and perform various operations with your bot, such as sending messages and reacting to user input. To generate a URL, you can use the discord.js library to create a unique code for each user and then append that code to a base URL. For example: const Discord = require('discord.js'); const client = new Discord.Client(); client.on('message', message => { if (message.content === '!generate-url') { // Generate a unique code for the user const code = generateCode(message.author.id); // Append the code to the base URL const url = `https://my-website.com/verify?code=${code}`; // Send the URL to the user message.channel.send(`Here is your URL: ${url}`); } }); function generateCode(userId) { // Generate a unique code based on the user's ID return userId + '-' + Date.now(); } Once the user clicks on the URL, you can use the express library to create a server that listens for requests to that URL and then performs the appropriate action, such as giving the user a role on your Discord server. Here is an example of how you might use express to create a server that listens for requests to the /verify endpoint and gives the user a role: const Discord = require('discord.js'); const express = require('express'); const app = express(); const client = new Discord.Client(); // Listen for requests to the /verify endpoint app.get('/verify', (req, res) => { // Get the code from the query string const code = req.query.code; // Look up the user associated with the code const user = lookupUserByCode(code); // Give the user the "Verified" role user.addRole('Verified') .then(() => { // Send a success message to the user res.send('You have been verified. Welcome to the server!'); }) .catch(err => { // Handle any errors that may occur res.send('An error occurred while verifying your account.'); }); }); function lookupUserByCode(code) { // Look up the user associated with the code // (implementation details omitted for brevity) } client.login('your-bot-token-here'); app.listen(3000); This is obviously just an example, but I hope it helps as general guidance on how to approach this task.
Generating URLs when running a discord command
I was just wondering how would I go about generating a URL for a user when they run a discord bot command. So once they run the command it will generate a URL for them, then once they click a button on my website they'll be given a role. I know I'll have to use discord.js & express but how would I go about doing this.
[ "o generate a URL for a user when they run a Discord bot command, you would first need to create a bot for your Discord server. You can do this by going to the Discord Developer Portal and following the instructions there.\nOnce you have created your bot, you will need to use the Discord.js library to access the Discord API and perform various operations with your bot, such as sending messages and reacting to user input.\nTo generate a URL, you can use the discord.js library to create a unique code for each user and then append that code to a base URL. For example:\nconst Discord = require('discord.js');\nconst client = new Discord.Client();\n\nclient.on('message', message => {\n if (message.content === '!generate-url') {\n // Generate a unique code for the user\n const code = generateCode(message.author.id);\n // Append the code to the base URL\n const url = `https://my-website.com/verify?code=${code}`;\n // Send the URL to the user\n message.channel.send(`Here is your URL: ${url}`);\n }\n});\n\nfunction generateCode(userId) {\n // Generate a unique code based on the user's ID\n return userId + '-' + Date.now();\n}\n\nOnce the user clicks on the URL, you can use the express library to create a server that listens for requests to that URL and then performs the appropriate action, such as giving the user a role on your Discord server.\nHere is an example of how you might use express to create a server that listens for requests to the /verify endpoint and gives the user a role:\nconst Discord = require('discord.js');\nconst express = require('express');\n\nconst app = express();\nconst client = new Discord.Client();\n\n// Listen for requests to the /verify endpoint\napp.get('/verify', (req, res) => {\n // Get the code from the query string\n const code = req.query.code;\n\n // Look up the user associated with the code\n const user = lookupUserByCode(code);\n\n // Give the user the \"Verified\" role\n user.addRole('Verified')\n .then(() => {\n // Send a success message to the user\n res.send('You have been verified. Welcome to the server!');\n })\n .catch(err => {\n // Handle any errors that may occur\n res.send('An error occurred while verifying your account.');\n });\n});\n\nfunction lookupUserByCode(code) {\n // Look up the user associated with the code\n // (implementation details omitted for brevity)\n}\n\nclient.login('your-bot-token-here');\napp.listen(3000);\n\nThis is obviously just an example, but I hope it helps as general guidance on how to approach this task.\n" ]
[ 1 ]
[]
[]
[ "express", "node.js" ]
stackoverflow_0074680429_express_node.js.txt
Q: ArgumentCountError. Too few arguments to function App\Controllers\Kamar::hapus(), 0 passed CodeIgniter4 I've made this public function hapus to delete at my controller (hapus transalated means delete) to delete data from table public function hapus($id) { $model = new M_Kamar(); $id = $this->request->getPost('idKamar'); $model->hapus($id); session()->setFlashdata('message', 'Dihapus!'); return redirect()->to('/kamar'); } But it returns this error ArgumentCountError. Too few arguments to function App\Controllers\Kamar::hapus(), 0 passed This is the code from my index.php <button type="button" data-toggle="modal" data-target="#modalHapus" id="btn-hapus" class="btn btn-sm btn-danger" data-id="<?= $row['id']; ?>"> <i class="fa fa-trash-alt"></i> </button> <div class="modal fade" id="modalHapus"> <div class="modal-dialog" role="document"> <div class="modal-content"> <form action="/kamar/hapus" method="post"> <div class="modal-body"> Apakah anda yakin ingin menghapus data ini? <input type="hidden" id="idKamar" name="idKamar"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Yakin</button> </div> </div> </form> </div> </div> And last but not least, my method public function hapus($id) { return $this->db->table('kamar')->delete(['id' => $id]); } } How to resolve this problem? I'm wondering also if it might have something to do with my routes? A: the error message explains it actually: 0 arguments are passed to the function hapus() in your Controller: Too few arguments to function App\Controllers\Kamar::hapus(), 0 passed This is an obvious result of the form action in your view: form action="/kamar/hapus", which doesn't send any ID as argument. You are using actually a hidden input field and send/receive ID as a $_POST variable. there are 2 problems to resolve: change your controller function to just: public function hapus() The other problem is that this hidden input field has no value, so you need to populate it with the value you want: <input type="hidden" id="idKamar" name="idKamar" value="the_id_you_want_to_delete">
ArgumentCountError. Too few arguments to function App\Controllers\Kamar::hapus(), 0 passed CodeIgniter4
I've made this public function hapus to delete at my controller (hapus transalated means delete) to delete data from table public function hapus($id) { $model = new M_Kamar(); $id = $this->request->getPost('idKamar'); $model->hapus($id); session()->setFlashdata('message', 'Dihapus!'); return redirect()->to('/kamar'); } But it returns this error ArgumentCountError. Too few arguments to function App\Controllers\Kamar::hapus(), 0 passed This is the code from my index.php <button type="button" data-toggle="modal" data-target="#modalHapus" id="btn-hapus" class="btn btn-sm btn-danger" data-id="<?= $row['id']; ?>"> <i class="fa fa-trash-alt"></i> </button> <div class="modal fade" id="modalHapus"> <div class="modal-dialog" role="document"> <div class="modal-content"> <form action="/kamar/hapus" method="post"> <div class="modal-body"> Apakah anda yakin ingin menghapus data ini? <input type="hidden" id="idKamar" name="idKamar"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Yakin</button> </div> </div> </form> </div> </div> And last but not least, my method public function hapus($id) { return $this->db->table('kamar')->delete(['id' => $id]); } } How to resolve this problem? I'm wondering also if it might have something to do with my routes?
[ "the error message explains it actually: 0 arguments are passed to the function hapus() in your Controller:\n\nToo few arguments to function App\\Controllers\\Kamar::hapus(), 0 passed\n\nThis is an obvious result of the form action in your view: form action=\"/kamar/hapus\", which doesn't send any ID as argument. You are using actually a hidden input field and send/receive ID as a $_POST variable.\nthere are 2 problems to resolve:\n\nchange your controller function to just:\n\n public function hapus()\n\n\nThe other problem is that this hidden input field has no value, so you need to populate it with the value you want:\n\n<input type=\"hidden\" id=\"idKamar\" name=\"idKamar\" value=\"the_id_you_want_to_delete\">\n\n" ]
[ 0 ]
[]
[]
[ "codeigniter", "php" ]
stackoverflow_0074679013_codeigniter_php.txt
Q: Mocking Axios Reject Rest Call I have a utility class: utils.ts import axios, { AxiosResponse } from 'axios'; import { throwError } from 'rxjs'; axios.defaults.withCredentials = true; axios.defaults.responseType = 'json'; export class UserUtils { public updateUserData(data) { return axios.post('http://mock.rest.server.com:1234/rest/update/user/', data, { withCredentials: true, responseType: 'json' as 'json }) .then(resp => { return resp; }) .catch(error => { return throwError('error updating user data'); }); } } And my component classes call the above as per: userComponent.ts export class UserComponent { import { UserUtils } from './utils'; public userUtils: UserUtils = new UserUtils(); // Btn click method public update(content) { this.userUtils.updateUserData(content) // <-- call made here .then((data) => { this.showSuccessModal(); // <- trying to test this }, (err) => { this.showErrorModal(error); // <- trying to test this }); } } I am trying to test the positive (showSuccessModal) / negative (showErrorModal) scenarios on userComponent.ts userComponent.spec.ts import { UserComponent } from '../../../user/userComponent'; import { UserUtils } from '../../../user/utils'; describe('User Comp test', () => { beforeAll(done => (async () => { Testbed.configureTestingModule({ declarations: [ UserComponent ] }); await TestBed.compileComponents(); })().then(done).catch(done.fail); describe('User Comp (with beforeEach)', () => { let component: UserComponent; let fixture: ComponentFixture<UserComponent>; beforeEach(() => { fixture = await TestBed.createComponent(UserComponent); component = fixture.componentInstance; }); it('should show error modal', () => { let errorModal = spyOn(component, 'showErrorModal'); spyOn(component.userUtils, 'updateUserData').and.returnValue(Promise.reject('error updating')); component.update({test: 'test'); expect(errorModal).toHaveBeenCalled(); }); }); } However when running tests, i see: Error: Expected spy showErrorModal to have been called at <Jasmine> It looks like in the test, the 'successful' route it always called. A: I think .catch(error => { return throwError('error updating user data'); }); resolve is Observable, You try: .catch(error => { throw 'error updating user data'; }); A: Figured out the solution - its to callFake and then reject the Promise: import { UserComponent } from '../../../user/userComponent'; import { UserUtils } from '../../../user/utils'; describe('User Comp test', () => { beforeAll(done => (async () => { Testbed.configureTestingModule({ declarations: [ UserComponent ] }); await TestBed.compileComponents(); })().then(done).catch(done.fail); describe('User Comp (with beforeEach)', () => { let component: UserComponent; let fixture: ComponentFixture<UserComponent>; beforeEach(() => { fixture = await TestBed.createComponent(UserComponent); component = fixture.componentInstance; }); it('should show error modal', () => { let errorModal = spyOn(component, 'showErrorModal'); let spyPromise = spyOn(component.userUtils, 'updateUserData').and.returnValue(Promise.resolve({status: 200....})); component.update({test: 'test'); expect(errorModal).not.toHaveBeenCalled(); errorModal.mockClear(); spyPromise.mockClear(); spyPromise.and.callFake(() => Promise.reject()); component.update({test: 'test'); expect(errorModal).toHaveBeenCalled(); }); }); }
Mocking Axios Reject Rest Call
I have a utility class: utils.ts import axios, { AxiosResponse } from 'axios'; import { throwError } from 'rxjs'; axios.defaults.withCredentials = true; axios.defaults.responseType = 'json'; export class UserUtils { public updateUserData(data) { return axios.post('http://mock.rest.server.com:1234/rest/update/user/', data, { withCredentials: true, responseType: 'json' as 'json }) .then(resp => { return resp; }) .catch(error => { return throwError('error updating user data'); }); } } And my component classes call the above as per: userComponent.ts export class UserComponent { import { UserUtils } from './utils'; public userUtils: UserUtils = new UserUtils(); // Btn click method public update(content) { this.userUtils.updateUserData(content) // <-- call made here .then((data) => { this.showSuccessModal(); // <- trying to test this }, (err) => { this.showErrorModal(error); // <- trying to test this }); } } I am trying to test the positive (showSuccessModal) / negative (showErrorModal) scenarios on userComponent.ts userComponent.spec.ts import { UserComponent } from '../../../user/userComponent'; import { UserUtils } from '../../../user/utils'; describe('User Comp test', () => { beforeAll(done => (async () => { Testbed.configureTestingModule({ declarations: [ UserComponent ] }); await TestBed.compileComponents(); })().then(done).catch(done.fail); describe('User Comp (with beforeEach)', () => { let component: UserComponent; let fixture: ComponentFixture<UserComponent>; beforeEach(() => { fixture = await TestBed.createComponent(UserComponent); component = fixture.componentInstance; }); it('should show error modal', () => { let errorModal = spyOn(component, 'showErrorModal'); spyOn(component.userUtils, 'updateUserData').and.returnValue(Promise.reject('error updating')); component.update({test: 'test'); expect(errorModal).toHaveBeenCalled(); }); }); } However when running tests, i see: Error: Expected spy showErrorModal to have been called at <Jasmine> It looks like in the test, the 'successful' route it always called.
[ "I think\n.catch(error => {\n return throwError('error updating user data');\n});\n\nresolve is Observable, You try:\n.catch(error => {\n throw 'error updating user data';\n});\n\n", "Figured out the solution - its to callFake and then reject the Promise:\nimport { UserComponent } from '../../../user/userComponent';\nimport { UserUtils } from '../../../user/utils';\n\n\n describe('User Comp test', () => {\n\n beforeAll(done => (async () => {\n\n Testbed.configureTestingModule({\n declarations: [\n UserComponent\n ]\n });\n await TestBed.compileComponents();\n })().then(done).catch(done.fail);\n\n describe('User Comp (with beforeEach)', () => {\n let component: UserComponent;\n let fixture: ComponentFixture<UserComponent>;\n\n beforeEach(() => { \n fixture = await TestBed.createComponent(UserComponent);\n component = fixture.componentInstance;\n });\n\n it('should show error modal', () => {\n let errorModal = spyOn(component, 'showErrorModal');\n let spyPromise = spyOn(component.userUtils, 'updateUserData').and.returnValue(Promise.resolve({status: 200....}));\n\n component.update({test: 'test');\n expect(errorModal).not.toHaveBeenCalled();\n\n errorModal.mockClear();\n spyPromise.mockClear();\n spyPromise.and.callFake(() => Promise.reject());\n\n component.update({test: 'test');\n expect(errorModal).toHaveBeenCalled();\n });\n });\n }\n\n" ]
[ 1, 1 ]
[]
[]
[ "angular", "axios", "javascript", "promise" ]
stackoverflow_0074546866_angular_axios_javascript_promise.txt
Q: Is it possible to require npm modules in a chrome extension ? I tried so but I have a 'require is not defined' error. I can't find information about that, can someone enlighten the noob in me please? A: It's possible, but you have to be careful. Trying to require() a package means that node will try to locate its files in your file system. A chrome extension only has access to the files you declare in the manifest, not your filesystem. To get around this, use a module bundler like Webpack, which will generate a single javascript file containing all code for all packages included through require(). You will have to generate a separate module for each component of your chrome extension (e.g. one for the background page, one for content scripts, one for the popup) and declare each generated module in your manifest. To avoid trying to setup your build system to make using require() possible, I suggest starting with a boilerplate project. You can check out my extension to see how I do it. A: An updated answer for 2022 Short answer: yes, you can require/import packages. Rather than going through the tedious work of setting up & configuring a bundler like Webpack on your own (especially if you have no experience with them), there are now build tools you can use to create the boilerplate "scaffolding" for a Chrome extension: Extension CLI -- this one is well-documented and you can also reference the source code of some Chrome extensions that have used this tool (READ: learn how others have set up their code). Chrome Extension CLI Benefits of using them: New projects are initiated with a default project file structure. Super helpful. They support modern Javascript (ES6, ES2021), so modules work fine. They already have bundlers integrated and pre-configured (Webpack in both above cases I think). You therefore don't need to install and configure any on your own. You can use npm as normal to install any packages/dependencies you need. Then of course, let the official documentation for Chrome Extensions guide you through the rest. A: It's not possible to require node modules directly within a chrome extension. However, it is possible to bundle node applications and packages into the browser for use with your extensions. See here for more: Is it possible to develop Google Chrome extensions using node.js? A: Yes, It is possible with esm npm packages. require is commonjs module loader. Browser doesn't support commonjs modules system so that this error showed. Method 1: Run npm init -y and add "type" :"module" in your package.json. create path.js file add this line in path.js const fullPath = await import.meta.resolve("npm-pkg-name"); const path = fullPath?.match(/(/node_modules.*)/)[0]; console.log(path); add this line inside package.json "path": "node --experimental-import-meta-resolve path.js", Copy console output text. Replace package name with this copied path. Method 2: Install other npm package to find and replace npm packages' virtual path to real path so that chrome browser will find it. Install Path-fixxer Add this line in path.js import setAllPkgPath from "path-fixxer"; setAllPkgPath(); then run command : npm run path. Now open browser to test it.
Is it possible to require npm modules in a chrome extension ?
I tried so but I have a 'require is not defined' error. I can't find information about that, can someone enlighten the noob in me please?
[ "It's possible, but you have to be careful. Trying to require() a package means that node will try to locate its files in your file system. A chrome extension only has access to the files you declare in the manifest, not your filesystem.\nTo get around this, use a module bundler like Webpack, which will generate a single javascript file containing all code for all packages included through require(). You will have to generate a separate module for each component of your chrome extension (e.g. one for the background page, one for content scripts, one for the popup) and declare each generated module in your manifest.\nTo avoid trying to setup your build system to make using require() possible, I suggest starting with a boilerplate project. You can check out my extension to see how I do it.\n", "An updated answer for 2022\nShort answer: yes, you can require/import packages. Rather than going through the tedious work of setting up & configuring a bundler like Webpack on your own (especially if you have no experience with them), there are now build tools you can use to create the boilerplate \"scaffolding\" for a Chrome extension:\n\nExtension CLI -- this one is well-documented and you can also reference the source code of some Chrome extensions that have used this tool (READ: learn how others have set up their code).\nChrome Extension CLI\n\nBenefits of using them:\n\nNew projects are initiated with a default project file structure. Super helpful.\nThey support modern Javascript (ES6, ES2021), so modules work fine.\nThey already have bundlers integrated and pre-configured (Webpack in both above cases I think). You therefore don't need to install and configure any on your own.\nYou can use npm as normal to install any packages/dependencies you need.\n\nThen of course, let the official documentation for Chrome Extensions guide you through the rest.\n", "It's not possible to require node modules directly within a chrome extension. However, it is possible to bundle node applications and packages into the browser for use with your extensions. See here for more: Is it possible to develop Google Chrome extensions using node.js?\n", "Yes, It is possible with esm npm packages.\nrequire is commonjs module loader.\nBrowser doesn't support commonjs modules system \nso that this error showed.\nMethod 1:\n\nRun npm init -y and add \"type\" :\"module\" in your package.json.\n\ncreate path.js file\n\nadd this line in path.js\nconst fullPath = await import.meta.resolve(\"npm-pkg-name\");\nconst path = fullPath?.match(/(/node_modules.*)/)[0];\nconsole.log(path);\n\nadd this line inside package.json\n\"path\": \"node --experimental-import-meta-resolve path.js\",\n\nCopy console output text. Replace package name with this copied path.\n\n\nMethod 2:\nInstall other npm package to find and replace \nnpm packages' virtual path to real path so that chrome browser will find it.\nInstall Path-fixxer\nAdd this line in path.js\nimport setAllPkgPath from \"path-fixxer\";\nsetAllPkgPath();\n\nthen run command : npm run path.\nNow open browser to test it.\n" ]
[ 63, 15, 8, 0 ]
[]
[]
[ "google_chrome_extension", "npm" ]
stackoverflow_0043684452_google_chrome_extension_npm.txt
Q: Rules for int[] array initialization from initializer list I would appreciate pointers to the int array initialization list in the C++ standard, I found an inconsistency between clang and gcc (c++ 17), see below and in compiler explorer. https://godbolt.org/z/3vMfTv8Ts Questions: Why can v1 be initialized with a initializer list, but we can't initialize a temporary to pass it to Test2? Why clang and gcc have different behavior when the function param is a reference to the int array? Note: clang C++20 compiles the Test1 call. I would appreciate the pointer to the C++ standard where these rules are described. #include <iostream> int Test1(const int (&a)[]) { return a[0]; } int Test2(const int a[]) { return a[0]; } int main() { const int v1[] = { 1,2,3 }; std::cout << Test2(v1) << std::endl; std::cout << Test2({ 1,2,3 }) << std::endl; // Does not compile in clang/gcc std::cout << Test1({ 1,2,3 }) << std::endl; // Does not compile in clang return 0; } A: The difference in behavior between clang and gcc in this case is due to a difference in their implementation of the C++ standard. In particular, clang follows the rules for array decay more strictly than gcc does. In C++, when an array is passed to a function as an argument, it decays into a pointer to its first element. This means that the function receives a pointer to the array, rather than the array itself. In the case of the Test1 and Test2 functions, the parameter a is a pointer to the array, not the array itself. In C++17 and earlier, there is an exception to the array decay rule for arrays that are declared with a size. In this case, the array does not decay into a pointer, and the function receives the array itself as a parameter. This is why the call to Test1 with an initializer list compiles in C++20, but not in C++17. In C++20, the array decay rules have been changed, and an array with a size will always decay into a pointer, regardless of whether it is passed as a parameter to a function. This is why the call to Test1 with an initializer list does not compile in C++20. In the case of the call to Test2 with an initializer list, the initializer list creates a temporary array, which decays into a pointer. This pointer is then passed as an argument to the Test2 function. Since the Test2 function takes a pointer as a parameter, this is allowed, and the code compiles in both clang and gcc. You can find more information about array decay in the C++ standard in section 8.3.4 of the C++17 standard, and section 8.3.4 of the C++20 standard.
Rules for int[] array initialization from initializer list
I would appreciate pointers to the int array initialization list in the C++ standard, I found an inconsistency between clang and gcc (c++ 17), see below and in compiler explorer. https://godbolt.org/z/3vMfTv8Ts Questions: Why can v1 be initialized with a initializer list, but we can't initialize a temporary to pass it to Test2? Why clang and gcc have different behavior when the function param is a reference to the int array? Note: clang C++20 compiles the Test1 call. I would appreciate the pointer to the C++ standard where these rules are described. #include <iostream> int Test1(const int (&a)[]) { return a[0]; } int Test2(const int a[]) { return a[0]; } int main() { const int v1[] = { 1,2,3 }; std::cout << Test2(v1) << std::endl; std::cout << Test2({ 1,2,3 }) << std::endl; // Does not compile in clang/gcc std::cout << Test1({ 1,2,3 }) << std::endl; // Does not compile in clang return 0; }
[ "The difference in behavior between clang and gcc in this case is due to a difference in their implementation of the C++ standard. In particular, clang follows the rules for array decay more strictly than gcc does.\nIn C++, when an array is passed to a function as an argument, it decays into a pointer to its first element. This means that the function receives a pointer to the array, rather than the array itself. In the case of the Test1 and Test2 functions, the parameter a is a pointer to the array, not the array itself.\nIn C++17 and earlier, there is an exception to the array decay rule for arrays that are declared with a size. In this case, the array does not decay into a pointer, and the function receives the array itself as a parameter. This is why the call to Test1 with an initializer list compiles in C++20, but not in C++17.\nIn C++20, the array decay rules have been changed, and an array with a size will always decay into a pointer, regardless of whether it is passed as a parameter to a function. This is why the call to Test1 with an initializer list does not compile in C++20.\nIn the case of the call to Test2 with an initializer list, the initializer list creates a temporary array, which decays into a pointer. This pointer is then passed as an argument to the Test2 function. Since the Test2 function takes a pointer as a parameter, this is allowed, and the code compiles in both clang and gcc.\nYou can find more information about array decay in the C++ standard in section 8.3.4 of the C++17 standard, and section 8.3.4 of the C++20 standard.\n" ]
[ 0 ]
[]
[]
[ "c++", "c++17" ]
stackoverflow_0074679592_c++_c++17.txt
Q: How to redirect url in Primefaces I am new to Primefaces. I made a simple spring boot pages using Primefaces in webapp folder like: webapp\ myapp\ api\ dashboard.xhtml auth\ login.xhtml register.xthml When I run the sever and I always enter the url http://localhost:8080/myapp/auth/login.xhtml to begin. I found this very annoying and want to redirect to login page when I enter just http://localhost:8080. I searched for answers, but there weren't any content like this. Perhaps am I missing the answer available somewhere or can anybody solve this problem? A: Oh, I finally found it! The answer was here: https://codenotfound.com/jsf-primefaces-welcome-page-redirect-example.html
How to redirect url in Primefaces
I am new to Primefaces. I made a simple spring boot pages using Primefaces in webapp folder like: webapp\ myapp\ api\ dashboard.xhtml auth\ login.xhtml register.xthml When I run the sever and I always enter the url http://localhost:8080/myapp/auth/login.xhtml to begin. I found this very annoying and want to redirect to login page when I enter just http://localhost:8080. I searched for answers, but there weren't any content like this. Perhaps am I missing the answer available somewhere or can anybody solve this problem?
[ "Oh, I finally found it!\nThe answer was here: https://codenotfound.com/jsf-primefaces-welcome-page-redirect-example.html\n" ]
[ 0 ]
[]
[]
[ "java", "primefaces", "spring" ]
stackoverflow_0074679940_java_primefaces_spring.txt
Q: proxy not working for react and node I'm having issues with the proxy I set up. This is my root package.json file: "scripts": { "client": "cd client && yarn dev-server", "server": "nodemon server.js", "dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\"" } My client package.json file: "scripts": { "serve": "live-server public/", "build": "webpack", "dev-server": "webpack-dev-server" }, "proxy": "http://localhost:5000/" I've set up express on my server side to run on port 5000. Whenever I make a request to the server, ie : callApi = async () => { const response = await fetch('/api/hello'); const body = await response.json(); // ... more stuff } The request always goes to Can someone point out what i have to do to fix this issue so that the request actually goes to port 5000? A: I experienced this issue quite a few times, and I figured it's because of the cache. To solve the issue, do the following Edit: @mkoe said that he was able to solve this issue simply by deleting the package-lock.json file, and restarting the app, so give that a try first. If that doesn't resolve it, then do the following. Stop your React app Delete package-lock.json file and the node_modules directory by doing rm -r package-lock.json node_modules in the app directory. Then do npm install in the app directory. Hopefully this fixed your proxy issue. A: The reason the react application is still pointing at localhost:8080 is because of cache. To clear it , follow the steps below. Delete package-lock.json and node_modules in React app Turn off React Terminal and npm install all dependencies again on React App Turn back on React App and the proxy should now be working This problem has been haunting me for a long time; but if you follow the steps above it should get your React application pointing at the server correctly. A: This is how I achieved the proxy calls. Do not rely on the browser's network tab. Put consoles in your server controllers to really check whether the call is being made or not. For me I was able to see logs at the server-side. My node server is running on 5000 and client is running on 3000. Network tab - Server logs - Check if your server is really running on the same path /api/hello through postman or browser. For me it was /api/user/register and I was trying to hit /api/user Use cors package to disable cross-origin access issues. A: Is your client being loaded from http://localhost:8080? By default the fetch api, when used without an absolute URL, will mirror the host of the client page (that is, the hostname and port). So calling fetch('/api/hello'); from a page running at http://localhost:8080 will cause the fetch api to infer that you want the request to be made to the absolute url of http://localhost:8080/api/hello. You will need to specify an absolute URL if you want to change the port like that. In your case that would be fetch('http://localhost:5000/api/hello');, although you probably want to dynamically build it since eventually you won't be running on localhost for production. A: For me "proxy" = "http://localhost:5000 did not work because I was listening on 0.0.0.0 changing it to "proxy" = "http://0.0.0.0:5000 did work. A: Make sure you put it on package.json in client side (react) instead of on package.json in server-side(node). A: This solution worked for me, specially if you're using webpack. Go to your webpack.config.js > devServer > add the below proxy: {       '/api': 'http://localhost:3000/', }, This should work out. Read more about webpack devSever proxy: https://webpack.js.org/configuration/dev-server/#devserver-proxy A: I have tried to solve this problem by using so many solutions but nothing worked for me. After a lot of research, I have found this solution which is given below that solved my proxy issues and helped me to connect my frontend with my node server. Those steps are, killed all the terminals so that I can stop frontend and backend servers both. Installed Cors on My Node server.js file. npm install cors And added these lines into server.js file var cors = require('cors') app.use(cors()) Into package.json file of frontend or client folder, I added this line, "proxy" : "http://127.0.0.1:my_servers_port_address_" Now everything working fine. A: Yours might not be the case but I was having a problem because my server was running on localhost 5500 while I proxied it to 5000. I changed my package.json file to change that to 5500 and used this script: npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080 I am pretty sure just changing it on the package.json worked but I just wanted to let you know what I did. A: you should set the proxy address to your backend server, not react client address. you should restart the client after changing package.json you should use fetch('/api/...') (instead of fetch('http://localhost:8080/api/')) A: Make sure you check your .env variables too if you use them. It's because of that if I was looking for a solution on that page. A: I tried all the solutions, proposed here, but it didn't work. Then I found out, that I tried to fetch from root directory (i.e. fetch('/')) and it's not correct for some reason. Using fetch('/something') helped me. A: Your backend data or files and react build files should be inside the same server folder. A: you must give proxy after the name.{"name":"Project Name", "proxy":"http://localhost:5000"} port should match with your backend's port. A: If you are seeing your static react app HTML page being served rather than 404 for paths you want to proxy, see this related question and answer: https://stackoverflow.com/a/51051360/345648 (This doesn't answer the original question, but searching Google for that question took me here so maybe this will help others like me.) A: In my specific case, I had a both Node backend, and an inner folder with a React project. I tried @Harshit's answer, which didn't work, until I had two package.json files in my project, one in the outer folder, and one in my client (React) folder. I needed to set up the proxy in the inner package.json, and I needed to clear the cache in the inner folder. A: My problem was actually the "localhost" part in the proxy route. My computer does not recognize "localhost", so I swapped it with http://127.0.0.1:<PORT_HERE> instead of http://localhost:<PORT_HERE>. Something like this: app.use('/', proxy( 'http://localhost:3000', // replace this with 'http://127.0.0.1:3000' { proxyReqPathResolver: (req) => `http://localhost:3000${req.url}` } ));` A: For me, I solved this by just stopping both the servers i.e. frontend and backend, and restarting them back again. A: Here is an opinion Don't use proxies, use fetch directly not working fetch("/signup", { method:"post", headers:{ "Content-Type":"application/json" }, body:JSON.stringify( { name:"", email:"", password:"", } ) Actually worked after wasting 6hours fetch("http://localhost:5000/signup", { // https -> http // fetch("/signup", { method:"post", headers:{ "Content-Type":"application/json" }, body:JSON.stringify( { name:"", email:"", password:"", } ) A: In my case the problem was that the proxy suddenly stopped to work. after investigating I found that I've moved the setupProxy from the src folder and that cause the problem. Moving it back to the src folder have solved the problem. The problematic structure: The solution: A: faced similar issue. my proxy was not connecting restarting the react app fixed my issue A: In my case it was because of typo. I wrote "Content-type": "application/json", (with small t) instead of "Content-Type": "application/json", A: I was having this issue for hours, and I'm sure some of the things above could be the cause in some other cases. However, in my case, I am using Vite and I had been trying to add my proxy to the package.json file, whereas it should be added to the vite.config.js file. You can click here to read about it in Vite's docs. In the end, my code looks like this: export default defineConfig({ server: { proxy: { "/api": { target: "http://localhost:8000", secure: false, }, }, }, plugins: [react()], });
proxy not working for react and node
I'm having issues with the proxy I set up. This is my root package.json file: "scripts": { "client": "cd client && yarn dev-server", "server": "nodemon server.js", "dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\"" } My client package.json file: "scripts": { "serve": "live-server public/", "build": "webpack", "dev-server": "webpack-dev-server" }, "proxy": "http://localhost:5000/" I've set up express on my server side to run on port 5000. Whenever I make a request to the server, ie : callApi = async () => { const response = await fetch('/api/hello'); const body = await response.json(); // ... more stuff } The request always goes to Can someone point out what i have to do to fix this issue so that the request actually goes to port 5000?
[ "I experienced this issue quite a few times, and I figured it's because of the cache. To solve the issue, do the following\n\nEdit: @mkoe said that he was able to solve this issue simply by deleting the package-lock.json file, and restarting the app, so give that a try first. If that doesn't resolve it, then do the following.\n\n\nStop your React app\nDelete package-lock.json file and the node_modules directory by doing rm -r package-lock.json node_modules in the app directory.\nThen do npm install in the app directory.\n\nHopefully this fixed your proxy issue.\n", "The reason the react application is still pointing at localhost:8080 is because of cache. To clear it , follow the steps below. \n\n\nDelete package-lock.json and node_modules in React app\nTurn off React Terminal and npm install all dependencies again on React App\nTurn back on React App and the proxy should now be working\n\n\nThis problem has been haunting me for a long time; but if you follow the steps above it should get your React application pointing at the server correctly. \n", "This is how I achieved the proxy calls.\n\nDo not rely on the browser's network tab. Put consoles in your server controllers to really check whether the call is being made or not. For me I was able to see logs at the server-side. My node server is running on 5000 and client is running on 3000.\n\n\nNetwork tab -\n\n\n\nServer logs -\n\n\n\nCheck if your server is really running on the same path /api/hello through postman or browser. For me it was /api/user/register and I was trying to hit /api/user\nUse cors package to disable cross-origin access issues.\n\n", "Is your client being loaded from http://localhost:8080?\nBy default the fetch api, when used without an absolute URL, will mirror the host of the client page (that is, the hostname and port). So calling fetch('/api/hello'); from a page running at http://localhost:8080 will cause the fetch api to infer that you want the request to be made to the absolute url of http://localhost:8080/api/hello.\nYou will need to specify an absolute URL if you want to change the port like that. In your case that would be fetch('http://localhost:5000/api/hello');, although you probably want to dynamically build it since eventually you won't be running on localhost for production. \n", "For me \"proxy\" = \"http://localhost:5000 did not work because I was listening on 0.0.0.0 changing it to \"proxy\" = \"http://0.0.0.0:5000 did work.\n", "Make sure you put it on package.json in client side (react) instead of on package.json in server-side(node).\n", "This solution worked for me, specially if you're using webpack.\nGo to your webpack.config.js > devServer > add the below\nproxy: {\n      '/api': 'http://localhost:3000/',\n},\nThis should work out.\nRead more about webpack devSever proxy: https://webpack.js.org/configuration/dev-server/#devserver-proxy\n", "I have tried to solve this problem by using so many solutions but nothing worked for me. After a lot of research, I have found this solution which is given below that solved my proxy issues and helped me to connect my frontend with my node server. Those steps are,\n\nkilled all the terminals so that I can stop frontend and backend servers both.\nInstalled Cors on My Node server.js file.\n\nnpm install cors\n\nAnd added these lines into server.js file\nvar cors = require('cors')\n\napp.use(cors())\n\n\n\nInto package.json file of frontend or client folder, I added this line,\n\n\"proxy\" : \"http://127.0.0.1:my_servers_port_address_\"\n\nNow everything working fine.\n", "Yours might not be the case but I was having a problem because my server was running on localhost 5500 while I proxied it to 5000.\nI changed my package.json file to change that to 5500 and used this script:\n\nnpm config set proxy http://proxy.company.com:8080\nnpm config set https-proxy http://proxy.company.com:8080\n\nI am pretty sure just changing it on the package.json worked but I just wanted to let you know what I did.\n", "\nyou should set the proxy address to your backend server, not react client address.\nyou should restart the client after changing package.json\nyou should use fetch('/api/...') (instead of fetch('http://localhost:8080/api/'))\n\n", "Make sure you check your .env variables too if you use them. It's because of that if I was looking for a solution on that page.\n", "I tried all the solutions, proposed here, but it didn't work. Then I found out, that I tried to fetch from root directory (i.e. fetch('/')) and it's not correct for some reason. Using fetch('/something') helped me.\n", "Your backend data or files and react build files should be inside the same server folder.\n", "you must give proxy after the name.{\"name\":\"Project Name\", \"proxy\":\"http://localhost:5000\"}\nport should match with your backend's port.\n", "If you are seeing your static react app HTML page being served rather than 404 for paths you want to proxy, see this related question and answer:\nhttps://stackoverflow.com/a/51051360/345648\n(This doesn't answer the original question, but searching Google for that question took me here so maybe this will help others like me.)\n", "In my specific case, I had a both Node backend, and an inner folder with a React project. I tried @Harshit's answer, which didn't work, until I had two package.json files in my project, one in the outer folder, and one in my client (React) folder. I needed to set up the proxy in the inner package.json, and I needed to clear the cache in the inner folder.\n", "My problem was actually the \"localhost\" part in the proxy route. My computer does not recognize \"localhost\", so I swapped it with http://127.0.0.1:<PORT_HERE> instead of http://localhost:<PORT_HERE>.\nSomething like this:\napp.use('/', proxy(\n 'http://localhost:3000', // replace this with 'http://127.0.0.1:3000'\n { proxyReqPathResolver: (req) => `http://localhost:3000${req.url}` }\n));`\n\n", "For me, I solved this by just stopping both the servers i.e. frontend and backend, and restarting them back again.\n", "Here is an opinion\nDon't use proxies, use fetch directly\nnot working\nfetch(\"/signup\", { \n method:\"post\", \n headers:{\n \"Content-Type\":\"application/json\" \n },\n body:JSON.stringify(\n {\n name:\"\",\n email:\"\",\n password:\"\",\n }\n )\n\nActually worked after wasting 6hours\nfetch(\"http://localhost:5000/signup\", { // https -> http\n // fetch(\"/signup\", { \n method:\"post\", \n headers:{\n \"Content-Type\":\"application/json\" },\n body:JSON.stringify(\n {\n name:\"\",\n email:\"\",\n password:\"\",\n }\n )\n\n", "In my case the problem was that the proxy suddenly stopped to work.\nafter investigating I found that I've moved the setupProxy from the src folder and that cause the problem.\nMoving it back to the src folder have solved the problem.\nThe problematic structure:\n\nThe solution:\n\n", "faced similar issue. my proxy was not connecting restarting the react app fixed my issue\n", "In my case it was because of typo. I wrote \"Content-type\": \"application/json\", (with small t) instead of \"Content-Type\": \"application/json\",\n", "I was having this issue for hours, and I'm sure some of the things above could be the cause in some other cases. However, in my case, I am using Vite and I had been trying to add my proxy to the package.json file, whereas it should be added to the vite.config.js file. You can click here to read about it in Vite's docs.\nIn the end, my code looks like this:\nexport default defineConfig({\n server: {\n proxy: {\n \"/api\": {\n target: \"http://localhost:8000\",\n secure: false,\n },\n },\n },\n plugins: [react()],\n});\n\n" ]
[ 63, 16, 13, 6, 6, 4, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ "Make sure your end point match with the backend.\n" ]
[ -5 ]
[ "node.js", "package.json", "proxy", "reactjs", "webpack" ]
stackoverflow_0048291950_node.js_package.json_proxy_reactjs_webpack.txt
Q: Seaborn countplot per feature value I have a dataset as follows: The 'island' features has three possible values: Torgensen, Biscoe Island and Dream. I'm printing as Seaborn countplot as follows: fig = sns.countplot(data=dataset, x='Island', hue='Species'); I'm getting the above. I would like to have three seperate plots though per island. I tried the following but that does not work: fig = sns.countplot(data=dataset, x='Island['Torgersen', hue='Species'); fig = sns.countplot(data=dataset, x='Island['Biscoe Island', hue='Species'); fig = sns.countplot(data=dataset, x='Island['Dream', hue='Species'); But that does not seem to work. Any idea how I can achieve three plots (one plot per island) instead of 1 plot (having all three islands)? A: You could create a FacetGrid, and then map sns.countplot to each of the subplots. import matplotlib.pyplot as plt import seaborn as sns dataset = sns.load_dataset('penguins') g = sns.FacetGrid(data=dataset, col='island') species = dataset['species'].unique() g.map(sns.countplot, 'species', order=species, palette='turbo') for ax in g.axes.flat: ax.bar_label(ax.containers[0]) plt.show() PS: You can also plot this via one call to sns.displot (this will use the same color for all the bars). g = sns.displot(data=dataset, kind='hist', stat='count', col='island', x='species', shrink=0.8)
Seaborn countplot per feature value
I have a dataset as follows: The 'island' features has three possible values: Torgensen, Biscoe Island and Dream. I'm printing as Seaborn countplot as follows: fig = sns.countplot(data=dataset, x='Island', hue='Species'); I'm getting the above. I would like to have three seperate plots though per island. I tried the following but that does not work: fig = sns.countplot(data=dataset, x='Island['Torgersen', hue='Species'); fig = sns.countplot(data=dataset, x='Island['Biscoe Island', hue='Species'); fig = sns.countplot(data=dataset, x='Island['Dream', hue='Species'); But that does not seem to work. Any idea how I can achieve three plots (one plot per island) instead of 1 plot (having all three islands)?
[ "You could create a FacetGrid, and then map sns.countplot to each of the subplots.\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndataset = sns.load_dataset('penguins')\ng = sns.FacetGrid(data=dataset, col='island')\n\nspecies = dataset['species'].unique()\ng.map(sns.countplot, 'species', order=species, palette='turbo')\nfor ax in g.axes.flat:\n ax.bar_label(ax.containers[0])\nplt.show()\n\n\nPS: You can also plot this via one call to sns.displot (this will use the same color for all the bars).\ng = sns.displot(data=dataset, kind='hist', stat='count', col='island', x='species', shrink=0.8)\n\n" ]
[ 0 ]
[]
[]
[ "seaborn" ]
stackoverflow_0074677119_seaborn.txt
Q: Comparison of texts of a jtextfield with an autocompletion I would like to know if there is a way to have a text validator, not the equals exactly, because I know if I do one by one it would take me a lifetime, but to validate all the autocompletions that I did to the jtextfield, I add text to see if they can help me. ``import com.mxrck.autocompleter.TextAutoCompleter; import java.awt.event.ActionEvent; import java.text.SimpleDateFormat; import javax.swing.JOptionPane; public class Comparativa extends javax.swing.JFrame { public TextAutoCompleter ac; public Comparativa(){ ac = new TextAutoCompleter(jTextfield); ac.addItem("Procesador"); ac.addItem("RAM"); ac.addItem("Disco"); } public void ValidadorComparacion(){ if(jTextfield.getText().equals(ac.getItem)){ System.out.println("GOOD"); }else{ System.out.println("BAD"); } ``` } `` In the final part I want to make it compare if or if the code but I don't want to use "equals" for each item , but for everything. That code gives me an error in the .equals part I hope your help A: Not sure what error you are actually getting but you should check the value of jTextField to be non-null. public void ValidadorComparacion(){ if (jTextField.getText() != null && jTextfield.getText().equals(ac.getItem())){ System.out.println("GOOD"); }else{ System.out.println("BAD"); } } If you get an error during compilation, please provide more of your source code. And the exact error message.
Comparison of texts of a jtextfield with an autocompletion
I would like to know if there is a way to have a text validator, not the equals exactly, because I know if I do one by one it would take me a lifetime, but to validate all the autocompletions that I did to the jtextfield, I add text to see if they can help me. ``import com.mxrck.autocompleter.TextAutoCompleter; import java.awt.event.ActionEvent; import java.text.SimpleDateFormat; import javax.swing.JOptionPane; public class Comparativa extends javax.swing.JFrame { public TextAutoCompleter ac; public Comparativa(){ ac = new TextAutoCompleter(jTextfield); ac.addItem("Procesador"); ac.addItem("RAM"); ac.addItem("Disco"); } public void ValidadorComparacion(){ if(jTextfield.getText().equals(ac.getItem)){ System.out.println("GOOD"); }else{ System.out.println("BAD"); } ``` } `` In the final part I want to make it compare if or if the code but I don't want to use "equals" for each item , but for everything. That code gives me an error in the .equals part I hope your help
[ "Not sure what error you are actually getting but you should check the value of jTextField to be non-null.\npublic void ValidadorComparacion(){\n if (jTextField.getText() != null && jTextfield.getText().equals(ac.getItem())){\n System.out.println(\"GOOD\");\n }else{\n System.out.println(\"BAD\");\n }\n }\n\nIf you get an error during compilation, please provide more of your source code. And the exact error message.\n" ]
[ 0 ]
[]
[]
[ "java", "java_11", "java_8", "jtextfield", "netbeans" ]
stackoverflow_0074680432_java_java_11_java_8_jtextfield_netbeans.txt
Q: Inconsistent REDIM behaviour in QuickBasic 4.5 I was writing a toy QBasic compiler and some tests for it. When I tried to create a vector type, I encountered an inconsistency with REDIM. The following code works in both QBasic and QuickBasic 4.5 interpreters. However, it produces 'Subscript out of range' error for the second REDIM when compiled as EXE. DECLARE SUB RedimIntArray (arr() AS INTEGER) DECLARE SUB RedimLongArray (arr() AS LONG) ' $DYNAMIC DIM xs(2) AS INTEGER PRINT UBOUND(xs) RedimIntArray xs() PRINT UBOUND(xs) ' $DYNAMIC DIM ys(2) AS LONG PRINT UBOUND(ys) RedimLongArray ys() PRINT UBOUND(ys) SUB RedimIntArray (arr() AS INTEGER) REDIM arr(10) AS INTEGER END SUB SUB RedimLongArray (arr() AS LONG) REDIM arr(10) AS LONG END SUB Is it something expected and documented somewhere, and if so, are there any possible fixes for this? UPD: The program above works fine on QBX 7.1 and QB64, so it might be something to do with the QB 4.5 compiler. A: It's indeed a bug in the compiler. This KB article describes the issue: Q50638: "Subscript Out Of Range" If REDIM Long Integer Array in SUB. REDIMing (redimensioning with REDIM) a dynamic long integer array that was passed to a SUBprogram generates a "Subscript Out Of Range" error at run time. Microsoft has confirmed this to be a problem in Microsoft QuickBASIC Versions 4.00, 4.00b, and 4.50 for MS-DOS and in Microsoft BASIC Compiler Versions 6.00 and 6.00b for MS-DOS and MS OS/2 (buglist6.00, buglist6.00b). This problem was corrected in Microsoft BASIC PDS Version 7.00 (fixlist7.00). The "Subscript Out Of Range" occurs whether the SUBprogram is compiled as part of the main program or it is compiled in a separate module. You can work around this problem by using an array type other than long integer, or by passing the array through a COMMON SHARED block.
Inconsistent REDIM behaviour in QuickBasic 4.5
I was writing a toy QBasic compiler and some tests for it. When I tried to create a vector type, I encountered an inconsistency with REDIM. The following code works in both QBasic and QuickBasic 4.5 interpreters. However, it produces 'Subscript out of range' error for the second REDIM when compiled as EXE. DECLARE SUB RedimIntArray (arr() AS INTEGER) DECLARE SUB RedimLongArray (arr() AS LONG) ' $DYNAMIC DIM xs(2) AS INTEGER PRINT UBOUND(xs) RedimIntArray xs() PRINT UBOUND(xs) ' $DYNAMIC DIM ys(2) AS LONG PRINT UBOUND(ys) RedimLongArray ys() PRINT UBOUND(ys) SUB RedimIntArray (arr() AS INTEGER) REDIM arr(10) AS INTEGER END SUB SUB RedimLongArray (arr() AS LONG) REDIM arr(10) AS LONG END SUB Is it something expected and documented somewhere, and if so, are there any possible fixes for this? UPD: The program above works fine on QBX 7.1 and QB64, so it might be something to do with the QB 4.5 compiler.
[ "It's indeed a bug in the compiler.\nThis KB article describes the issue: Q50638: \"Subscript Out Of Range\" If REDIM Long Integer Array in SUB.\nREDIMing (redimensioning with REDIM) a dynamic long integer array that\nwas passed to a SUBprogram generates a \"Subscript Out Of Range\" error\nat run time.\n\nMicrosoft has confirmed this to be a problem in Microsoft QuickBASIC\nVersions 4.00, 4.00b, and 4.50 for MS-DOS and in Microsoft BASIC\nCompiler Versions 6.00 and 6.00b for MS-DOS and MS OS/2 (buglist6.00,\nbuglist6.00b). This problem was corrected in Microsoft BASIC PDS\nVersion 7.00 (fixlist7.00).\n\nThe \"Subscript Out Of Range\" occurs whether the SUBprogram is compiled\nas part of the main program or it is compiled in a separate module.\n\nYou can work around this problem by using an array type other than\nlong integer, or by passing the array through a COMMON SHARED block.\n\n" ]
[ 0 ]
[]
[]
[ "qbasic", "quickbasic" ]
stackoverflow_0074675645_qbasic_quickbasic.txt
Q: python keyboard - how to deal with multiple keys? Im trying to do a simple bot with using python keyboard lib. i can send key presses with keyobard.send however if player presses and holds w for movement keyboard.send is not working. What should i do? A: If you want to simulate a key press and hold using the keyboard library in Python, you can use the keyboard.press_and_release method instead of the keyboard.send method. This method simulates a press and release of a key, so if you want to simulate holding down a key, you can use a loop to repeatedly call this method. Here's an example of how you can use the keyboard.press_and_release method to simulate holding down the "W" key: import keyboard # simulate holding down the "W" key while True: keyboard.press_and_release('w') This code will simulate pressing and releasing the "W" key repeatedly, which should have the same effect as holding down the key. You can modify this code to suit your specific use case.
python keyboard - how to deal with multiple keys?
Im trying to do a simple bot with using python keyboard lib. i can send key presses with keyobard.send however if player presses and holds w for movement keyboard.send is not working. What should i do?
[ "If you want to simulate a key press and hold using the keyboard library in Python, you can use the keyboard.press_and_release method instead of the keyboard.send method. This method simulates a press and release of a key, so if you want to simulate holding down a key, you can use a loop to repeatedly call this method.\nHere's an example of how you can use the keyboard.press_and_release method to simulate holding down the \"W\" key:\nimport keyboard\n\n# simulate holding down the \"W\" key\nwhile True:\n keyboard.press_and_release('w')\n\nThis code will simulate pressing and releasing the \"W\" key repeatedly, which should have the same effect as holding down the key. You can modify this code to suit your specific use case.\n" ]
[ 0 ]
[]
[]
[ "keyboard", "python" ]
stackoverflow_0074680454_keyboard_python.txt
Q: Select specific fields in Prisma not working I would like to select specific fields return this.prisma.user.findFirst({ where: { password_hash: createHash('md5') .update(`${userId.id}test`) .digest('hex'), }, select: { name: true, email: true, }, }); But I'm getting this Typing error Type '{ name: string; email: string; }' is missing the following properties from type 'User': id, password_hash Here's the type definition of the user export type User = { id: number name: string email: string password_hash: string } A: You are returning the wrong type in the function from which you are calling it. If you add a select clause, the returned result is thinned out to the properties of your select, while you pretend to return a full User from the wrapping function: // The full user: type User = { id: number name: string email: string password_hash: string } // Here you pretend to return a full user: function getUser(userId): Promise<User | null> { return this.prisma.user.findFirst({ where: { password_hash: createHash('md5') .update(`${userId.id}test`) .digest('hex'), }, select: { // Here you remove some properties from the user: name: true, email: true, }, }); } You can fix it by changing the return type: function getUser(userId): Promise<{ name: string, email: string } | null> { ... }
Select specific fields in Prisma not working
I would like to select specific fields return this.prisma.user.findFirst({ where: { password_hash: createHash('md5') .update(`${userId.id}test`) .digest('hex'), }, select: { name: true, email: true, }, }); But I'm getting this Typing error Type '{ name: string; email: string; }' is missing the following properties from type 'User': id, password_hash Here's the type definition of the user export type User = { id: number name: string email: string password_hash: string }
[ "You are returning the wrong type in the function from which you are calling it. If you add a select clause, the returned result is thinned out to the properties of your select, while you pretend to return a full User from the wrapping function:\n// The full user:\ntype User = {\n id: number\n name: string\n email: string\n password_hash: string\n}\n\n// Here you pretend to return a full user:\nfunction getUser(userId): Promise<User | null> {\n return this.prisma.user.findFirst({\n where: {\n password_hash: createHash('md5')\n .update(`${userId.id}test`)\n .digest('hex'),\n },\n select: { // Here you remove some properties from the user:\n name: true,\n email: true,\n },\n });\n}\n\nYou can fix it by changing the return type:\nfunction getUser(userId): Promise<{ name: string, email: string } | null> {\n ...\n}\n\n" ]
[ 0 ]
[]
[]
[ "nestjs", "node.js", "prisma", "typescript" ]
stackoverflow_0071825905_nestjs_node.js_prisma_typescript.txt
Q: Why .NET Core 7 WebApi Action Filter adds extra quote marks to string? I have this IActionFilter and the message I add to it is "Validation Error", without the quote marks. When I check the result I get: "Validation Error" with quote marks, basically it is ""Validation Error"". Is there a way to prevent that an additional pair of quote mark is added? I already have NewtonSoft added, see the configuration below. I haven't found any configuration option for NewtonSoft related to adding/not adding this extra set of quote marks. public class ValidationExceptionsFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { } public void OnActionExecuted(ActionExecutedContext context) { if (context.Exception is ArgumentNullException or ValidationException or DbUpdateException or GuardsServiceValueShouldNotBeEqualToException) { context.Result = new ObjectResult(SourceFormatsServiceResultStatuses.ValidationError) { StatusCode = (int)HttpStatusCode.BadRequest }; context.ExceptionHandled = true; } } } services.AddControllers(o => { o.Filters.Add<InternalServerErrorExceptionsFilter>(); o.Filters.Add<NoSuchEntityExceptionsFilter>(); o.Filters.Add<ValidationExceptionsFilter>(); }) .AddNewtonsoftJson() .AddApplicationPart(typeof(SourceFormatNodeController).Assembly); A: The ObjectResult class has a Value property that you can set to the value you want to return. In your case, you can set this property to "Validation Error" (without the quote marks) like this: context.Result = new ObjectResult("Validation Error") { StatusCode = (int)HttpStatusCode.BadRequest }; This should prevent the additional pair of quote marks from being added to the message. Note that when using the ObjectResult class, the Value property will be serialized to JSON by the JSON serializer that you are using (in your case, NewtonSoft). So if you want to control how the value is serialized, you may need to adjust the configuration of your JSON serializer. Without more information about how you are using NewtonSoft and what options you have set, it is not possible to provide specific advice on how to do this.
Why .NET Core 7 WebApi Action Filter adds extra quote marks to string?
I have this IActionFilter and the message I add to it is "Validation Error", without the quote marks. When I check the result I get: "Validation Error" with quote marks, basically it is ""Validation Error"". Is there a way to prevent that an additional pair of quote mark is added? I already have NewtonSoft added, see the configuration below. I haven't found any configuration option for NewtonSoft related to adding/not adding this extra set of quote marks. public class ValidationExceptionsFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { } public void OnActionExecuted(ActionExecutedContext context) { if (context.Exception is ArgumentNullException or ValidationException or DbUpdateException or GuardsServiceValueShouldNotBeEqualToException) { context.Result = new ObjectResult(SourceFormatsServiceResultStatuses.ValidationError) { StatusCode = (int)HttpStatusCode.BadRequest }; context.ExceptionHandled = true; } } } services.AddControllers(o => { o.Filters.Add<InternalServerErrorExceptionsFilter>(); o.Filters.Add<NoSuchEntityExceptionsFilter>(); o.Filters.Add<ValidationExceptionsFilter>(); }) .AddNewtonsoftJson() .AddApplicationPart(typeof(SourceFormatNodeController).Assembly);
[ "The ObjectResult class has a Value property that you can set to the value you want to return. In your case, you can set this property to \"Validation Error\" (without the quote marks) like this:\ncontext.Result = new ObjectResult(\"Validation Error\")\n{\n StatusCode = (int)HttpStatusCode.BadRequest\n};\n\n\nThis should prevent the additional pair of quote marks from being added to the message.\nNote that when using the ObjectResult class, the Value property will be serialized to JSON by the JSON serializer that you are using (in your case, NewtonSoft). So if you want to control how the value is serialized, you may need to adjust the configuration of your JSON serializer. Without more information about how you are using NewtonSoft and what options you have set, it is not possible to provide specific advice on how to do this.\n" ]
[ 0 ]
[]
[]
[ ".net_core", "asp.net_core_webapi", "json.net", "json_deserialization" ]
stackoverflow_0074679914_.net_core_asp.net_core_webapi_json.net_json_deserialization.txt
Q: Hi,I tried to install but failed MongoDB, BUT something went worng, i was try to fix it, but it didn't work Linux MInt 21, I try to instal MongoDB for like 3 days but apparently I'm not doing something right. I would greatly appreciate it if you could tell me what I am doing wrong :)) I post what i did in the terminal, I removed it and install it again but and that went wrong too Lenovo-Y520-15IKBM:~$ sudo apt install mongodb Reading package lists... Done Building dependency tree... Done Reading state information... Done Package mongodb is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source E: Package 'mongodb' has no installation candidate Lenovo-Y520-15IKBM:~$ ^C Lenovo-Y520-15IKBM:~$ sudo apt-get purge mongo* Reading package lists... Done Building dependency tree... Done Reading state information... Done Note, selecting 'mongodb-server' for glob 'mongo*' Note, selecting 'mongodb-dev' for glob 'mongo*' Note, selecting 'mongodb' for glob 'mongo*' Note, selecting 'mongoose' for glob 'mongo*' Package 'mongodb-dev' is not installed, so not removed Package 'mongodb' is not installed, so not removed Package 'mongodb-server' is not installed, so not removed Package 'mongoose' is not installed, so not removed 0 upgraded, 0 newly installed, 0 to remove and 63 not upgraded. Lenovo-Y520-15IKBM:~$ sudo apt install mongodb Reading package lists... Done Building dependency tree... Done Reading state information... Done Package mongodb is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source E: Package 'mongodb' has no installation candidate Lenovo-Y520-15IKBM:~$ ^C Lenovo-Y520-15IKBM:~$ sudo apt remove --autoremove mongodb-org Reading package lists... Done Building dependency tree... Done Reading state information... Done E: Unable to locate package mongodb-org Lenovo-Y520-15IKBM:~$ ^C Lenovo-Y520-15IKBM:~$ sudo apt install mongodb Reading package lists... Done Building dependency tree... Done Reading state information... Done Package mongodb is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source E: Package 'mongodb' has no installation candi A: A Linux Mint release is always based on a specific Ubuntu version. When you add the MongoDB repositories, you must make sure to reference the correct Ubuntu version. The corresponding variant of Ubuntu is specified in /etc/os-release. Here is an example for installing MongoDB-6 in Mint curl -sS https://pgp.mongodb.com/server-6.0.asc | sudo gpg --dearmor --output /etc/apt/trusted.gpg.d/mongodb-org-6.0-keyring.gpg echo "deb [arch=amd64,arm64] https://repo.mongodb.org/apt/ubuntu $(. /etc/os-release; echo "$UBUNTU_CODENAME")/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list sudo apt-get update sudo apt-get install mongodb-org
Hi,I tried to install but failed MongoDB, BUT something went worng, i was try to fix it, but it didn't work
Linux MInt 21, I try to instal MongoDB for like 3 days but apparently I'm not doing something right. I would greatly appreciate it if you could tell me what I am doing wrong :)) I post what i did in the terminal, I removed it and install it again but and that went wrong too Lenovo-Y520-15IKBM:~$ sudo apt install mongodb Reading package lists... Done Building dependency tree... Done Reading state information... Done Package mongodb is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source E: Package 'mongodb' has no installation candidate Lenovo-Y520-15IKBM:~$ ^C Lenovo-Y520-15IKBM:~$ sudo apt-get purge mongo* Reading package lists... Done Building dependency tree... Done Reading state information... Done Note, selecting 'mongodb-server' for glob 'mongo*' Note, selecting 'mongodb-dev' for glob 'mongo*' Note, selecting 'mongodb' for glob 'mongo*' Note, selecting 'mongoose' for glob 'mongo*' Package 'mongodb-dev' is not installed, so not removed Package 'mongodb' is not installed, so not removed Package 'mongodb-server' is not installed, so not removed Package 'mongoose' is not installed, so not removed 0 upgraded, 0 newly installed, 0 to remove and 63 not upgraded. Lenovo-Y520-15IKBM:~$ sudo apt install mongodb Reading package lists... Done Building dependency tree... Done Reading state information... Done Package mongodb is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source E: Package 'mongodb' has no installation candidate Lenovo-Y520-15IKBM:~$ ^C Lenovo-Y520-15IKBM:~$ sudo apt remove --autoremove mongodb-org Reading package lists... Done Building dependency tree... Done Reading state information... Done E: Unable to locate package mongodb-org Lenovo-Y520-15IKBM:~$ ^C Lenovo-Y520-15IKBM:~$ sudo apt install mongodb Reading package lists... Done Building dependency tree... Done Reading state information... Done Package mongodb is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source E: Package 'mongodb' has no installation candi
[ "A Linux Mint release is always based on a specific Ubuntu version. When you add the MongoDB repositories, you must make sure to reference the correct Ubuntu version. The corresponding variant of Ubuntu is specified in /etc/os-release.\nHere is an example for installing MongoDB-6 in Mint\ncurl -sS https://pgp.mongodb.com/server-6.0.asc | sudo gpg --dearmor --output /etc/apt/trusted.gpg.d/mongodb-org-6.0-keyring.gpg\necho \"deb [arch=amd64,arm64] https://repo.mongodb.org/apt/ubuntu $(. /etc/os-release; echo \"$UBUNTU_CODENAME\")/mongodb-org/6.0 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list\nsudo apt-get update\nsudo apt-get install mongodb-org\n\n" ]
[ 0 ]
[ "wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -\n\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list\n\nsudo apt-get update\n\n\nsudo apt-get install -y mongodb-org\n\ntry these commands and you will have mongodb installed on mint\ndo not forget to start mongodb sudo systemctl start mongod\n" ]
[ -1 ]
[ "linux", "linux_mint", "mongodb" ]
stackoverflow_0074153635_linux_linux_mint_mongodb.txt
Q: SharePoint page using address with the 365 connected domain I have a 365 tenant on domain {somename}.onmicrosoft.com and a connected domain {othername}.com I was able to create users as {username}@{othername}.com I wonder how I can have pages show with https://{othername}.com ? Is there an admin action to take or should I add a CNAME? Thank you A: If you have added domain as your tenant domain you can manage DNS via your office 365 admin portal https://admin.microsoft.com/Adminportal/Home?source=applauncher#/Domains You can simply add an A record to your web server.
SharePoint page using address with the 365 connected domain
I have a 365 tenant on domain {somename}.onmicrosoft.com and a connected domain {othername}.com I was able to create users as {username}@{othername}.com I wonder how I can have pages show with https://{othername}.com ? Is there an admin action to take or should I add a CNAME? Thank you
[ "If you have added domain as your tenant domain you can manage DNS via your office 365 admin portal https://admin.microsoft.com/Adminportal/Home?source=applauncher#/Domains\nYou can simply add an A record to your web server.\n" ]
[ 0 ]
[]
[]
[ "dns", "microsoft365" ]
stackoverflow_0074678116_dns_microsoft365.txt
Q: Navigate in JSON with nultiple keys I'm trying to get a key from a JSON from a website using the following code: import json import requests from bs4 import BeautifulSoup url = input('Enter url:') html = requests.get(url) soup = BeautifulSoup(html.text,'html.parser') data = json.loads(soup.find('script', type='application/json').text) print(data) print("####################################") And here is the JSON: {"props": { "XYZ": { "ABC": [ { "current": "sold", "location": "FD", "type": "d", "uid": "01020633" } ], "searchTerm": "asd" } }} I'm able to load the page, find the JSON, and print all data. The question is, how can I print only the information from the current key? Will something like the following work? print(data['props']['XYZ']['ABC']['current'] A: You can access it like this: data["props"]["XYZ"]["ABC"][0]["current"] Why? Key current is inside a list of dictionaries. ABC is of type list, and we access the elements using their location in the list (0 in your example). A: As the other answers have already explained, you need to add [0] between ['ABC'] and ['current'] because the value that corresponds to the "ABC" key is a list containing a dictionary with the "current" key, so you can access it with data["props"]["XYZ"]["ABC"][0]["current"] Also, if you have a very complex and nested data structure and you want to quickly you can use this set of functions getNestedVal(data, 'current') prints sold, and getNestedVal(data, 'current', 'just_expr', 'data') prints data["props"]["XYZ"]["ABC"][0]["current"] so that you can copy it from the terminal and use in your code. (It's not the best idea to use it other than for just figuring out data structure since it can use up quite a bit of time and memory.) A: You can access current like below: data["props"]["XYZ"]["ABC"][0]["current"] you can get a list of dictionaries by accessing "ABC" key's value. So whenever you get curly {} bracket it shows that it is a dictionary and you can access value of particular keys using dict[key] or dict.get(key,default_value) and whenever you get square [] bracket it shows that it is list and you can access its element by index list[0],list[1]. So, accessing list element and dictionary's key's value is two different things. I hope you understood my point.
Navigate in JSON with nultiple keys
I'm trying to get a key from a JSON from a website using the following code: import json import requests from bs4 import BeautifulSoup url = input('Enter url:') html = requests.get(url) soup = BeautifulSoup(html.text,'html.parser') data = json.loads(soup.find('script', type='application/json').text) print(data) print("####################################") And here is the JSON: {"props": { "XYZ": { "ABC": [ { "current": "sold", "location": "FD", "type": "d", "uid": "01020633" } ], "searchTerm": "asd" } }} I'm able to load the page, find the JSON, and print all data. The question is, how can I print only the information from the current key? Will something like the following work? print(data['props']['XYZ']['ABC']['current']
[ "You can access it like this:\ndata[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]\n\nWhy? Key current is inside a list of dictionaries. ABC is of type list, and we access the elements using their location in the list (0 in your example).\n", "As the other answers have already explained, you need to add [0] between ['ABC'] and ['current'] because the value that corresponds to the \"ABC\" key is a list containing a dictionary with the \"current\" key, so you can access it with\ndata[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]\n\n\nAlso, if you have a very complex and nested data structure and you want to quickly you can use this set of functions\ngetNestedVal(data, 'current')\n\nprints sold, and\ngetNestedVal(data, 'current', 'just_expr', 'data')\n\nprints data[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"] so that you can copy it from the terminal and use in your code. (It's not the best idea to use it other than for just figuring out data structure since it can use up quite a bit of time and memory.)\n", "You can access current like below:\ndata[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]\n\nyou can get a list of dictionaries by accessing \"ABC\" key's value.\nSo whenever you get curly {} bracket it shows that it is a dictionary and you can access value of particular keys using\ndict[key] or dict.get(key,default_value)\nand whenever you get square [] bracket it shows that it is list and you can access its element by index list[0],list[1].\nSo, accessing list element and dictionary's key's value is two different things. I hope you understood my point.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "beautifulsoup", "json", "python", "python_3.x", "python_requests" ]
stackoverflow_0074678361_beautifulsoup_json_python_python_3.x_python_requests.txt
Q: Conflicts with relationship between tables I've been constantly getting a warning on the console and I'm going crazy from how much I've been reading but I haven't been able to resolve this: SAWarning: relationship 'Book.users' will copy column user.uid to column user_book.uid, which conflicts with relationship(s): 'User.books' (copies user.uid to user_book.uid). If this is not intention, consider if these relationships should be linked with back_populates, or if viewonly=True should be applied to one or more if they are read-only. For the less common case that foreign key constraints are partially overlapping, the orm.foreign() annotation can be used to isolate the columns that should be written towards. The 'overlaps' parameter may be used to remove this warning. The tables the console cites in this notice are as follows: user_book = db.Table('user_book', db.Column('uid', db.Integer, db.ForeignKey('user.uid'), primary_key=True), db.Column('bid', db.Text, db.ForeignKey('book.bid'), primary_key=True), db.Column('date_added', db.DateTime(timezone=True), server_default=db.func.now()) ) class User(db.Model): __tablename__ = 'user' uid = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(25), nullable=False) hash = db.Column(db.String(), nullable=False) first_name = db.Column(db.String(30), nullable=True) last_name = db.Column(db.String(80), nullable=True) books = db.relationship('Book', secondary=user_book) class Book(db.Model): __tablename__ = 'book' bid = db.Column(db.Text, primary_key=True) title = db.Column(db.Text, nullable=False) authors = db.Column(db.Text, nullable=False) thumbnail = db.Column(db.Text, nullable=True) users = db.relationship('User', secondary=user_book) I use the user_book table to show the user the books he has added. What am I missing? I take this opportunity to ask, semantically the relationship between tables and foreign keys is being done correctly? A: As the warning message suggests, you are missing the back_populates= attributes in your relationships: class User(db.Model): # … books = db.relationship('Book', secondary=user_book, back_populates="users") # … class Book(db.Model): # … users = db.relationship('User', secondary=user_book, back_populates="books") # … A: I kind of figure this out. As the code in official tutorial. from sqlalchemy import Column, ForeignKey, Integer, String, Table from sqlalchemy.orm import declarative_base, relationship Base = declarative_base() class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True) name = Column(String(64)) kw = relationship("Keyword", secondary=lambda: user_keyword_table) def __init__(self, name): self.name = name class Keyword(Base): __tablename__ = "keyword" id = Column(Integer, primary_key=True) keyword = Column("keyword", String(64)) def __init__(self, keyword): self.keyword = keyword user_keyword_table = Table( "user_keyword", Base.metadata, Column("user_id", Integer, ForeignKey("user.id"), primary_key=True), Column("keyword_id", Integer, ForeignKey("keyword.id"), primary_key=True), ) Doesn't it make you wander why the relationship only exists in User class rather than both class ? The thing is, it automatically creates the reverse relationship in Keyword class (a "backref='users' liked parameter is required I supposed ?)
Conflicts with relationship between tables
I've been constantly getting a warning on the console and I'm going crazy from how much I've been reading but I haven't been able to resolve this: SAWarning: relationship 'Book.users' will copy column user.uid to column user_book.uid, which conflicts with relationship(s): 'User.books' (copies user.uid to user_book.uid). If this is not intention, consider if these relationships should be linked with back_populates, or if viewonly=True should be applied to one or more if they are read-only. For the less common case that foreign key constraints are partially overlapping, the orm.foreign() annotation can be used to isolate the columns that should be written towards. The 'overlaps' parameter may be used to remove this warning. The tables the console cites in this notice are as follows: user_book = db.Table('user_book', db.Column('uid', db.Integer, db.ForeignKey('user.uid'), primary_key=True), db.Column('bid', db.Text, db.ForeignKey('book.bid'), primary_key=True), db.Column('date_added', db.DateTime(timezone=True), server_default=db.func.now()) ) class User(db.Model): __tablename__ = 'user' uid = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(25), nullable=False) hash = db.Column(db.String(), nullable=False) first_name = db.Column(db.String(30), nullable=True) last_name = db.Column(db.String(80), nullable=True) books = db.relationship('Book', secondary=user_book) class Book(db.Model): __tablename__ = 'book' bid = db.Column(db.Text, primary_key=True) title = db.Column(db.Text, nullable=False) authors = db.Column(db.Text, nullable=False) thumbnail = db.Column(db.Text, nullable=True) users = db.relationship('User', secondary=user_book) I use the user_book table to show the user the books he has added. What am I missing? I take this opportunity to ask, semantically the relationship between tables and foreign keys is being done correctly?
[ "As the warning message suggests, you are missing the back_populates= attributes in your relationships:\nclass User(db.Model):\n# …\n books = db.relationship('Book', secondary=user_book, back_populates=\"users\")\n# …\n \nclass Book(db.Model):\n# …\n users = db.relationship('User', secondary=user_book, back_populates=\"books\")\n# …\n\n", "I kind of figure this out.\nAs the code in official tutorial.\nfrom sqlalchemy import Column, ForeignKey, Integer, String, Table\nfrom sqlalchemy.orm import declarative_base, relationship\n\nBase = declarative_base()\n\n\nclass User(Base):\n __tablename__ = \"user\"\n id = Column(Integer, primary_key=True)\n name = Column(String(64))\n kw = relationship(\"Keyword\", secondary=lambda: user_keyword_table)\n\n def __init__(self, name):\n self.name = name\n\n\nclass Keyword(Base):\n __tablename__ = \"keyword\"\n id = Column(Integer, primary_key=True)\n keyword = Column(\"keyword\", String(64))\n\n def __init__(self, keyword):\n self.keyword = keyword\n\n\nuser_keyword_table = Table(\n \"user_keyword\",\n Base.metadata,\n Column(\"user_id\", Integer, ForeignKey(\"user.id\"), primary_key=True),\n Column(\"keyword_id\", Integer, ForeignKey(\"keyword.id\"), primary_key=True),\n)\n\nDoesn't it make you wander why the relationship only exists in User class rather than both class ?\nThe thing is, it automatically creates the reverse relationship in Keyword class (a \"backref='users' liked parameter is required I supposed ?)\n" ]
[ 6, 1 ]
[]
[]
[ "postgresql", "python", "sqlalchemy" ]
stackoverflow_0068322485_postgresql_python_sqlalchemy.txt
Q: Split columns that are dictionaries I have a data frame that has about 200,000 rows with columns like: ID dictionary column 1 dictionary column 2 1 {""1720100"":4,""1720101"":3} {""1720100"":5,""1720101"":1,""1720102"":2} 2 {""1720100"":4} {""1720100"":4,""1720101"":2} ... ... ... The output table I would like to get is: ID col_a col_b col_c col_d 1 1720100 4 1720101 5 1 1720101 3 1720102 1 1 NA NA 1720103 2 2 1720100 4 1720101 4 2 NA NA 1720102 2 ... ... ... ... ... And, I feel like it would be even better if the data frame is divided into several chunks before splitting the columns above to reduce the time needed for the calculation. Could anyone help me with this? A: Looks like you may want to extract json from the column, using jsonlite package. You can put data into longer form, since you have json in two columns. Then with more pivoting to get desired final format. The final select just reorders columns values on the number contained in the column name. library(tidyverse) library(jsonlite) df %>% pivot_longer(cols = -ID) %>% mutate(json_parsed = map(value, ~fromJSON(sprintf("[%s]", .), flatten = T))) %>% unnest(json_parsed) %>% pivot_longer(cols = -c(ID, name, value), names_to = "n", values_to = "v") %>% pivot_wider(id_cols = ID, values_from = c(n, v), values_fn = list) %>% unnest(cols = -ID) %>% select(ID, order(parse_number(names(.)[-1])) + 1) Output ID n_dictionary_column_1 v_dictionary_column_1 n_dictionary_column_2 v_dictionary_column_2 <dbl> <chr> <int> <chr> <int> 1 1 1720100 4 1720100 5 2 1 1720101 3 1720101 1 3 1 1720102 NA 1720102 2 4 2 1720100 4 1720100 4 5 2 1720101 NA 1720101 2 6 2 1720102 NA 1720102 NA
Split columns that are dictionaries
I have a data frame that has about 200,000 rows with columns like: ID dictionary column 1 dictionary column 2 1 {""1720100"":4,""1720101"":3} {""1720100"":5,""1720101"":1,""1720102"":2} 2 {""1720100"":4} {""1720100"":4,""1720101"":2} ... ... ... The output table I would like to get is: ID col_a col_b col_c col_d 1 1720100 4 1720101 5 1 1720101 3 1720102 1 1 NA NA 1720103 2 2 1720100 4 1720101 4 2 NA NA 1720102 2 ... ... ... ... ... And, I feel like it would be even better if the data frame is divided into several chunks before splitting the columns above to reduce the time needed for the calculation. Could anyone help me with this?
[ "Looks like you may want to extract json from the column, using jsonlite package. You can put data into longer form, since you have json in two columns. Then with more pivoting to get desired final format. The final select just reorders columns values on the number contained in the column name.\nlibrary(tidyverse)\nlibrary(jsonlite)\n\ndf %>%\n pivot_longer(cols = -ID) %>%\n mutate(json_parsed = map(value, ~fromJSON(sprintf(\"[%s]\", .), flatten = T))) %>%\n unnest(json_parsed) %>%\n pivot_longer(cols = -c(ID, name, value), names_to = \"n\", values_to = \"v\") %>%\n pivot_wider(id_cols = ID, values_from = c(n, v), values_fn = list) %>%\n unnest(cols = -ID) %>%\n select(ID, order(parse_number(names(.)[-1])) + 1)\n\nOutput\n ID n_dictionary_column_1 v_dictionary_column_1 n_dictionary_column_2 v_dictionary_column_2\n <dbl> <chr> <int> <chr> <int>\n1 1 1720100 4 1720100 5\n2 1 1720101 3 1720101 1\n3 1 1720102 NA 1720102 2\n4 2 1720100 4 1720100 4\n5 2 1720101 NA 1720101 2\n6 2 1720102 NA 1720102 NA\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "r", "split" ]
stackoverflow_0074674029_dictionary_r_split.txt
Q: Is there a way to re-hydrate the gapi.client access token between page loads? The use-token-model documentation states that In the token based authorization model, there is no need to store per-user refresh tokens on your backend server. It also states that In the Token model, an access token is not stored by the OS or browser, instead a new token is first obtained at page load time, or subsequently by triggering a call to requestAccessToken() through a user gesture such as a button press. The trouble I am having is during development my page is continually reloading and I am having to re-connect each time. I have workaround ideas, but I just wanted to confirm that there is no way to persist the token/session information in local storage to rehydrate gapi.client via gapi.client.setToken. A: Yes, that is correct. In the token-based authorization model, there is no way to persist the access token in the browser's local storage. The access token is only valid for a short period of time and must be refreshed by calling the requestAccessToken() function when it expires. This means that when you are developing your application, you will need to call the requestAccessToken() function each time your page is reloaded in order to obtain a new access token and authenticate your requests to the Google API. One workaround is to create a button that the user can click to trigger the requestAccessToken() function and obtain a new access token. This would allow the user to authenticate their requests to the Google API without having to manually refresh the page. Alternatively, you could use the gapi.auth2.getAuthInstance() function to check if the user is already authenticated when your page is loaded. If the user is already authenticated, you can use the gapi.client.setToken() function to set the existing access token and authenticate your requests to the Google API without having to call the requestAccessToken() function.
Is there a way to re-hydrate the gapi.client access token between page loads?
The use-token-model documentation states that In the token based authorization model, there is no need to store per-user refresh tokens on your backend server. It also states that In the Token model, an access token is not stored by the OS or browser, instead a new token is first obtained at page load time, or subsequently by triggering a call to requestAccessToken() through a user gesture such as a button press. The trouble I am having is during development my page is continually reloading and I am having to re-connect each time. I have workaround ideas, but I just wanted to confirm that there is no way to persist the token/session information in local storage to rehydrate gapi.client via gapi.client.setToken.
[ "Yes, that is correct. In the token-based authorization model, there is no way to persist the access token in the browser's local storage. The access token is only valid for a short period of time and must be refreshed by calling the requestAccessToken() function when it expires.\nThis means that when you are developing your application, you will need to call the requestAccessToken() function each time your page is reloaded in order to obtain a new access token and authenticate your requests to the Google API.\nOne workaround is to create a button that the user can click to trigger the requestAccessToken() function and obtain a new access token. This would allow the user to authenticate their requests to the Google API without having to manually refresh the page.\nAlternatively, you could use the gapi.auth2.getAuthInstance() function to check if the user is already authenticated when your page is loaded. If the user is already authenticated, you can use the gapi.client.setToken() function to set the existing access token and authenticate your requests to the Google API without having to call the requestAccessToken() function.\n" ]
[ 0 ]
[]
[]
[ "google_oauth" ]
stackoverflow_0074680449_google_oauth.txt
Q: Why does SSE/AVX lack loading an immediate value? As far as I know, there is no instruction in SSE/AVX for loading an immediate. One workaround is loading a value to a normal register and movd, but compilers seem to think this is more costly than loading from memory even for a single scalar value. This makes memory access necessary every time doing an operation with common constants such as 1, 0x80000000, 0x7fffffff, 0x3f800000, 0x3f000000, etc. Well, having these values encoded in the machine code will occupy 4 bytes each, but so does a 32-bit absolute or rip-relative address, and I believe an immediate load is cheaper than any sort of memory load. I always thought something like movss xmm, imm32 or broadcastss xmm, imm32 would be nice to have, but there must be a reason for not making such instructions. Why was it designed this way? A: AVX (Advanced Vector Extensions) is an instruction set extension to the x86 architecture that provides support for processing single and double-precision floating-point values using the SIMD (Single Instruction Multiple Data) paradigm. As you noted, AVX does not include an instruction for directly loading an immediate value into a register. This is because immediate values are typically used for small constants that can be encoded directly in the instruction itself, while AVX is designed for handling larger vectors of data. In general, loading a value from memory is more expensive than loading an immediate value because it requires an additional memory access. However, compilers may choose to load a value from memory even for a single scalar value if they believe it will be more efficient in the long run. This can happen if the value is used multiple times and can be stored in a register for reuse, or if the value is already stored in memory and can be loaded with a single instruction. In these cases, the cost of the initial memory access may be outweighed by the savings from avoiding additional instructions or memory accesses. It's also worth noting that AVX is not the only instruction set that provides support for vector operations. Other instruction sets, such as SSE (Streaming SIMD Extensions), also provide support for vector operations and may include instructions for loading immediate values. These instruction sets may be better suited for certain types of operations, and compilers will typically choose the most efficient instruction set based on the specific code being compiled.
Why does SSE/AVX lack loading an immediate value?
As far as I know, there is no instruction in SSE/AVX for loading an immediate. One workaround is loading a value to a normal register and movd, but compilers seem to think this is more costly than loading from memory even for a single scalar value. This makes memory access necessary every time doing an operation with common constants such as 1, 0x80000000, 0x7fffffff, 0x3f800000, 0x3f000000, etc. Well, having these values encoded in the machine code will occupy 4 bytes each, but so does a 32-bit absolute or rip-relative address, and I believe an immediate load is cheaper than any sort of memory load. I always thought something like movss xmm, imm32 or broadcastss xmm, imm32 would be nice to have, but there must be a reason for not making such instructions. Why was it designed this way?
[ "AVX (Advanced Vector Extensions) is an instruction set extension to the x86 architecture that provides support for processing single and double-precision floating-point values using the SIMD (Single Instruction Multiple Data) paradigm. As you noted, AVX does not include an instruction for directly loading an immediate value into a register. This is because immediate values are typically used for small constants that can be encoded directly in the instruction itself, while AVX is designed for handling larger vectors of data.\nIn general, loading a value from memory is more expensive than loading an immediate value because it requires an additional memory access. However, compilers may choose to load a value from memory even for a single scalar value if they believe it will be more efficient in the long run. This can happen if the value is used multiple times and can be stored in a register for reuse, or if the value is already stored in memory and can be loaded with a single instruction. In these cases, the cost of the initial memory access may be outweighed by the savings from avoiding additional instructions or memory accesses.\nIt's also worth noting that AVX is not the only instruction set that provides support for vector operations. Other instruction sets, such as SSE (Streaming SIMD Extensions), also provide support for vector operations and may include instructions for loading immediate values. These instruction sets may be better suited for certain types of operations, and compilers will typically choose the most efficient instruction set based on the specific code being compiled.\n" ]
[ 0 ]
[]
[]
[ "assembly", "immediate_operand", "instruction_set", "sse", "x86" ]
stackoverflow_0072145124_assembly_immediate_operand_instruction_set_sse_x86.txt
Q: Error message "DevTools failed to load SourceMap: Could not load content for chrome-extension://..." I'm trying to display an image selected from the local machine and I need the location of that image for a JavaScript function. But I'm unable to get the location. To get the image location, I tried using console.log, but nothing returns. console.log(document.getElementById("uploadPreview")); Here's the HTML code: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div align="center" style="padding-top: 50px"> <img align="center" id="uploadPreview" style="width: 100px; height: 100px;" /> </div> <div align="center" style="padding-left: 30px"> <input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" /> </div> <script type="text/javascript"> function PreviewImage() { var oFReader = new FileReader(); oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]); oFReader.onload = function (oFREvent) { document.getElementById("uploadPreview").src = oFREvent.target.result; console.log(document.getElementById("uploadPreview").src); }; } </script> </body> </html> Console Output: Here's the warning: DevTools failed to load SourceMap: Could not load content for chrome-extension://alplpnakfeabeiebipdmaenpmbgknjce/include.preload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME A: That's because Chrome added support for source maps. Go to the developer tools (F12 in the browser), then select the three dots in the upper right corner, and go to Settings. Then, look for Sources, and disable the options: "Enable JavaScript source maps" "Enable CSS source maps" If you do that, that would get rid of the warnings. It has nothing to do with your code. Check the developer tools in other pages and you will see the same warning. A: Go to Developer tools → Settings → Console → tick "Selected context only". The warnings will be hidden. You can see them again by unticking the same box. The "Selected context only" means only the top, iframe, worker and extension contexts. Which is all that you'll need, the vast majority of the time. A: Fixing "SourceMap" error messages in the Development Tools Console caused by Chrome extensions: Examples caused by McAfee extensions: DevTools failed to load SourceMap: Could not load content for chrome-extension://klekeajafkkpokaofllcadenjdckhinm/sourceMap/content.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME DevTools failed to load SourceMap: Could not load content for chrome-extension://fheoggkfdfchfphceeifdbepaooicaho/sourceMap/chrome/content.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME DevTools failed to load SourceMap: Could not load content for chrome-extension://fheoggkfdfchfphceeifdbepaooicaho/sourceMap/chrome/iframe_handler.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME If you are developing, then you need "Enable JavaScript source maps" and "Enable CSS source maps" checked to be able see your source code in Chrome Developer Tools. Unchecking those takes away your ability to debug your source code. It is like turning off the fire alarm instead of putting out the fire. You do not want to do that. Instead you want to find the extensions that are causing the messages and turn them off. Here is how you do that: Go to the three dots in the upper right hand corner of Chrome. Go to "More Tools" and click on "Extensions". Do this for one extension at a time until no more "SourceMap" errors are in the console: Turn off the extension by sliding the switch to the left. Reload the page that you were using the Development Tools on. Check if any of the "SourceMap" error messages disappeared. If any did, then that extension was causing those messages. Otherwise, that extension can be turned back on. After determining which extensions caused the issue either: If you need it, then contact the maker to have them fix the issue. Otherwise, remove the extension. A: I stumbled upon this Stack Overflow question after discovering loads of source map errors in the console for the Edge browser. (I think I had disabled the warnings in the Chrome browser long ago.) For me it meant first realising what a source map is; please refer to Macro Mazzon's answer to understand this. Since it's a good idea, it was just a case of finding out how to turn them on. It's as simple as adding this line in your webpack.config.js file - module.exports = { devtool: "source-map", } Now that Edge could detect a source map, the errors disappeared. Apologies if this answer insults anybody's intelligence, but maybe somebody reading this will be as clueless about source maps as I was. A: The include.prepload.js file will have a line like below, probably as the last line: //# sourceMappingURL=include.prepload.js.map Delete it and the error will go away. A: For me, the problem was caused not by the application in development itself, but by the Chrome extension React Developer Tool. I solved it partially by right-clicking the extension icon in the toolbar, clicking "Manage extension" and then enabling "Allow access to files URLs." But this measure fixed just some of the alerts. I found issues in the React repository that suggests the cause is a bug in their extension and is planned to be corrected soon - see issues 20091 and 20075. You can confirm is extension-related by accessing your application in an anonymous tab without any extension enabled. A: Right: it has nothing to do with your code. I've found two valid solutions to this warning (not just disabling it). To better understand what a source map is, I suggest you check out this answer, where it explains how it's something that helps you debug: The .map files are for JavaScript and CSS (and now TypeScript too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best. First solution: apparently, Mr Heelis was the closest one: you should add the .map file and there are some tools that help you with this problem (Grunt, Gulp and Google closure for example, quoting the answer). Otherwise you can download the .map file from official sites like Bootstrap, jQuery, font-awesome, preload and so on... (maybe installing things like popper or swiper by the npm command in a random folder and copying just the .map file in your JavaScript/CSS destination folder) Second solution (the one I used): add the source files using a CDN (content delivery network). (Here are all the advantages of using a CDN). Using content delivery network (CDN) you can simply add the CDN link, instead of the path to your folder. You can find CNDs on official websites (Bootstrap, jquery, popper, etc.) or you can easily search on some websites like Cloudflare, cdnjs, etc. A: Chrome has changed the UI in 2022, so this is a new version of the most upvoted reply. Open the dev tools (hit F12 or Option + Command + J) Select the gear at the top. There are two gears in that area, so be sure to select the one at the top, top. Locate the Sources section Deselect "Enable JavaScript source maps" Check to see if it worked! A: Extensions without enough permissions on Chrome can cause these warnings, for example for React developer tools. Check if the following procedure solves your problem: Right click on the extension icon. Or Go to extensions. Click the three-dot in the row of React developer tool. Then choose "This can read and write site data". You should see three options in the list. Pick one that is strict enough based on how much you trust the extension and also satisfies the extension's needs. A: I appreciate this is part of your extensions, but I see this message in all sorts of places these days, and I hate it: how I fixed it (this fix seems to massively speed up the browser too) was by adding a dead file physically create the file it wants it/where it wants it, as a blank file (for example, "popper.min.js.map") put this in the blank file { "version": 1, "mappings": "", "sources": [], "names": [], "file": "popper.min.js" } make sure that "file": "*******" in the content of the blank file matches the name of your file ******.map (minus the word ".map") (I suspect you could physically add this dead file method to the addon yourself.) A: I do not think the warnings you have received are related. I had the same warnings which turned out to be the Chrome extension React Dev Tools. I removed the extension and the errors were gone. A: You have just missing files. Go to the website https://www.cdnpkg.com/. Download what you need and copy it to the right folder. A: For me, the warnings were caused by the Selenium IDE Chrome extension. These warnings appeared in the Console on every page load: DevTools failed to load source map: Could not load content for chrome-extension://mooikfkahbdckldjjndioackbalphokd/assets/atoms.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME DevTools failed to load source map: Could not load content for chrome-extension://mooikfkahbdckldjjndioackbalphokd/assets/polyfills.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME DevTools failed to load source map: Could not load content for chrome-extension://mooikfkahbdckldjjndioackbalphokd/assets/escape.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME DevTools failed to load source map: Could not load content for chrome-extension://mooikfkahbdckldjjndioackbalphokd/assets/playback.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME DevTools failed to load source map: Could not load content for chrome-extension://mooikfkahbdckldjjndioackbalphokd/assets/record.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME Since Selenium IDE was already set to be able to read site data on all sites, I uninstalled it. (I read in another comment here that you might try enabling more permissions for an extension instead of removing it.) In my case, removing Selenium IDE (Chrome extension) got rid of the warnings. A: It is also possible to add the file that is missing, aside with other .js libraries in the same folder (no need to reference the .map in the .html file, <script> tag). I had the same error, when trying to code in Backbone.js. The problematic file was backbone-min.js, and the line that created the error was sourceMappingURL=backbone-min.map. After downloading the missing file (the link comes from here), the error disappeared. A: Problems with Debugging and Sourcemaps in Web Browsers Hope this clarifies the technicals behind the problem...knowing how things works helps some :) This browser error means it has some compiled version of your JavaScript in a sourcemap intermediate file it or some 3rd party created that is now needed when debugging that same script in "devtools" in your web browser. This can happen if your script fails (or in your case trying to get an image source hidden in the sourcemap code that created the script) but whose script error is tied to some JavaScript that got created from an original sourcemap file that now cannot be found to debug that same error. So it's an error about an error, a missing debugging file creating a new error. (crazy, huh?) This error is likely coming from an extension in the web browser and is reporting it has generated a script error it has recorded in the console.log window of devtools (press F12 in the browser). The error is likely from the extension (not your code) saying it has some code that contains an address to a sourcemap file it cannot access, has a bad URI/URL address, is blocked, or that is missing. The browser only needs this sourcemap file if a developer using devtools will need to debug the original script again. A sourcemap, by the way, is a file that translates or transpiles code from one language to another language. Often this is a file that the browser uses to translate this source code into a child script like JavaScript/ECMAScript, or when it needs to do the opposite and recreate the source file from the child script. In most cases this file is not needed at all as a 3rd party software program has already compiled or transpiled the source code into the child script for the browser. For example, developers who like TypeScript use it to create JavaScript. This source code gets transpiled into JavaScript so the browser script engine can run it. The URI/URL to this sourcemap file is usually at the top of the javaScript or application compiled code file in a format like //#.... When this intermediary transpile file is missing or blocked for security reasons in a web browser, the application will usually not care unless it needs the source file for debugging the child script using this source file. In that case it will complain when it feels it needs this file and cannot find it, as it uses it to recreate the source file for the code running in the browser when debugging the script in order to allow a developer to debug the original source code. When it cannot find it, it means that any developer trying to debug it will not be able to do so, and is stuck with the compiled code only. So it is safe to turn off these errors in the various ways mentioned in this post. It should not affect your own scripts if it is connected to an extension. Even if it is related to your own scripts, it is still unlikely you need it unless you plan to run debugging from devtools. A: I had the same problem. I tried to disable the extensions one by one to check it, and finally realized I had Adblock enabled, which was causing this issue. To remove that error I followed the step below, Three dots (top right corner). Click More tools --> extensions. Disable the Adblock. Reload the page. And it should work now.
Error message "DevTools failed to load SourceMap: Could not load content for chrome-extension://..."
I'm trying to display an image selected from the local machine and I need the location of that image for a JavaScript function. But I'm unable to get the location. To get the image location, I tried using console.log, but nothing returns. console.log(document.getElementById("uploadPreview")); Here's the HTML code: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div align="center" style="padding-top: 50px"> <img align="center" id="uploadPreview" style="width: 100px; height: 100px;" /> </div> <div align="center" style="padding-left: 30px"> <input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" /> </div> <script type="text/javascript"> function PreviewImage() { var oFReader = new FileReader(); oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]); oFReader.onload = function (oFREvent) { document.getElementById("uploadPreview").src = oFREvent.target.result; console.log(document.getElementById("uploadPreview").src); }; } </script> </body> </html> Console Output: Here's the warning: DevTools failed to load SourceMap: Could not load content for chrome-extension://alplpnakfeabeiebipdmaenpmbgknjce/include.preload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME
[ "That's because Chrome added support for source maps.\nGo to the developer tools (F12 in the browser), then select the three dots in the upper right corner, and go to Settings.\nThen, look for Sources, and disable the options:\n\n\"Enable JavaScript source maps\"\n\"Enable CSS source maps\"\n\nIf you do that, that would get rid of the warnings. It has nothing to do with your code. Check the developer tools in other pages and you will see the same warning.\n", "Go to Developer tools → Settings → Console → tick \"Selected context only\". The warnings will be hidden. You can see them again by unticking the same box.\nThe \"Selected context only\" means only the top, iframe, worker and extension contexts. Which is all that you'll need, the vast majority of the time.\n", "Fixing \"SourceMap\" error messages in the Development Tools Console caused by Chrome extensions:\nExamples caused by McAfee extensions:\n\nDevTools failed to load SourceMap: Could not load content for chrome-extension://klekeajafkkpokaofllcadenjdckhinm/sourceMap/content.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME\n\n\nDevTools failed to load SourceMap: Could not load content for chrome-extension://fheoggkfdfchfphceeifdbepaooicaho/sourceMap/chrome/content.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME\n\n\nDevTools failed to load SourceMap: Could not load content for chrome-extension://fheoggkfdfchfphceeifdbepaooicaho/sourceMap/chrome/iframe_handler.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME\n\nIf you are developing, then you need \"Enable JavaScript source maps\" and \"Enable CSS source maps\" checked to be able see your source code in Chrome Developer Tools. Unchecking those takes away your ability to debug your source code. It is like turning off the fire alarm instead of putting out the fire. You do not want to do that.\nInstead you want to find the extensions that are causing the messages and turn them off. Here is how you do that:\n\nGo to the three dots in the upper right hand corner of Chrome.\nGo to \"More Tools\" and click on \"Extensions\".\nDo this for one extension at a time until no more \"SourceMap\" errors are in the console:\n\nTurn off the extension by sliding the switch to the left.\nReload the page that you were using the Development Tools on.\nCheck if any of the \"SourceMap\" error messages disappeared.\n\nIf any did, then that extension was causing those messages.\nOtherwise, that extension can be turned back on.\n\n\n\n\n\nAfter determining which extensions caused the issue either:\n\nIf you need it, then contact the maker to have them fix the issue.\nOtherwise, remove the extension.\n\n", "I stumbled upon this Stack Overflow question after discovering loads of source map errors in the console for the Edge browser. (I think I had disabled the warnings in the Chrome browser long ago.)\nFor me it meant first realising what a source map is; please refer to Macro Mazzon's answer to understand this. Since it's a good idea, it was just a case of finding out how to turn them on.\nIt's as simple as adding this line in your webpack.config.js file -\nmodule.exports = {\n devtool: \"source-map\",\n}\n\nNow that Edge could detect a source map, the errors disappeared.\nApologies if this answer insults anybody's intelligence, but maybe somebody reading this will be as clueless about source maps as I was.\n", "The include.prepload.js file will have a line like below, probably as the last line:\n//# sourceMappingURL=include.prepload.js.map\nDelete it and the error will go away.\n", "For me, the problem was caused not by the application in development itself, but by the Chrome extension React Developer Tool. I solved it partially by right-clicking the extension icon in the toolbar, clicking \"Manage extension\" and then enabling \"Allow access to files URLs.\" But this measure fixed just some of the alerts.\nI found issues in the React repository that suggests the cause is a bug in their extension and is planned to be corrected soon - see issues 20091 and 20075.\nYou can confirm is extension-related by accessing your application in an anonymous tab without any extension enabled.\n", "Right: it has nothing to do with your code. I've found two valid solutions to this warning (not just disabling it). To better understand what a source map is, I suggest you check out this answer, where it explains how it's something that helps you debug:\n\nThe .map files are for JavaScript and CSS (and now TypeScript too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.\n\n\nFirst solution: apparently, Mr Heelis was the closest one: you should add the .map file and there are some tools that help you with this problem (Grunt, Gulp and Google closure for example, quoting the answer). Otherwise you can download the .map file from official sites like Bootstrap, jQuery, font-awesome, preload and so on... (maybe installing things like popper or swiper by the npm command in a random folder and copying just the .map file in your JavaScript/CSS destination folder)\n\nSecond solution (the one I used): add the source files using a CDN (content delivery network). (Here are all the advantages of using a CDN). Using content delivery network (CDN) you can simply add the CDN link, instead of the path to your folder. You can find CNDs on official websites (Bootstrap, jquery, popper, etc.) or you can easily search on some websites like Cloudflare, cdnjs, etc.\n\n\n", "Chrome has changed the UI in 2022, so this is a new version of the most upvoted reply.\n\nOpen the dev tools (hit F12 or Option + Command + J)\nSelect the gear at the top. There are two gears in that area, so be sure to select the one at the top, top.\nLocate the Sources section\nDeselect \"Enable JavaScript source maps\"\n\nCheck to see if it worked!\n", "Extensions without enough permissions on Chrome can cause these warnings, for example for React developer tools. Check if the following procedure solves your problem:\n\nRight click on the extension icon.\n\nOr\n\nGo to extensions.\nClick the three-dot in the row of React developer tool.\n\nThen choose \"This can read and write site data\".\nYou should see three options in the list. Pick one that is strict enough based on how much you trust the extension and also satisfies the extension's needs.\n", "I appreciate this is part of your extensions, but I see this message in all sorts of places these days, and I hate it: how I fixed it (this fix seems to massively speed up the browser too) was by adding a dead file\n\nphysically create the file it wants it/where it wants it, as a blank file (for example, \"popper.min.js.map\")\n\nput this in the blank file\n{\n \"version\": 1,\n \"mappings\": \"\",\n \"sources\": [],\n \"names\": [],\n \"file\": \"popper.min.js\"\n}\n\n\nmake sure that \"file\": \"*******\" in the content of the blank file matches the name of your file ******.map (minus the word \".map\")\n\n\n(I suspect you could physically add this dead file method to the addon yourself.)\n", "I do not think the warnings you have received are related. I had the same warnings which turned out to be the Chrome extension React Dev Tools. I removed the extension and the errors were gone.\n", "You have just missing files.\nGo to the website https://www.cdnpkg.com/.\nDownload what you need and copy it to the right folder.\n", "For me, the warnings were caused by the Selenium IDE Chrome extension. These warnings appeared in the Console on every page load:\nDevTools failed to load source map: Could not load content for chrome-extension://mooikfkahbdckldjjndioackbalphokd/assets/atoms.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME\nDevTools failed to load source map: Could not load content for chrome-extension://mooikfkahbdckldjjndioackbalphokd/assets/polyfills.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME\nDevTools failed to load source map: Could not load content for chrome-extension://mooikfkahbdckldjjndioackbalphokd/assets/escape.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME\nDevTools failed to load source map: Could not load content for chrome-extension://mooikfkahbdckldjjndioackbalphokd/assets/playback.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME\nDevTools failed to load source map: Could not load content for chrome-extension://mooikfkahbdckldjjndioackbalphokd/assets/record.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME\n\nSince Selenium IDE was already set to be able to read site data on all sites, I uninstalled it. (I read in another comment here that you might try enabling more permissions for an extension instead of removing it.) In my case, removing Selenium IDE (Chrome extension) got rid of the warnings.\n", "It is also possible to add the file that is missing, aside with other .js libraries in the same folder (no need to reference the .map in the .html file, <script> tag).\nI had the same error, when trying to code in Backbone.js.\nThe problematic file was backbone-min.js, and the line that created the error was sourceMappingURL=backbone-min.map.\nAfter downloading the missing file (the link comes from here), the error disappeared.\n", "Problems with Debugging and Sourcemaps in Web Browsers\nHope this clarifies the technicals behind the problem...knowing how things works helps some :)\nThis browser error means it has some compiled version of your JavaScript in a sourcemap intermediate file it or some 3rd party created that is now needed when debugging that same script in \"devtools\" in your web browser.\nThis can happen if your script fails (or in your case trying to get an image source hidden in the sourcemap code that created the script) but whose script error is tied to some JavaScript that got created from an original sourcemap file that now cannot be found to debug that same error. So it's an error about an error, a missing debugging file creating a new error. (crazy, huh?)\nThis error is likely coming from an extension in the web browser and is reporting it has generated a script error it has recorded in the console.log window of devtools (press F12 in the browser). The error is likely from the extension (not your code) saying it has some code that contains an address to a sourcemap file it cannot access, has a bad URI/URL address, is blocked, or that is missing.\nThe browser only needs this sourcemap file if a developer using devtools will need to debug the original script again.\nA sourcemap, by the way, is a file that translates or transpiles code from one language to another language. Often this is a file that the browser uses to translate this source code into a child script like JavaScript/ECMAScript, or when it needs to do the opposite and recreate the source file from the child script. In most cases this file is not needed at all as a 3rd party software program has already compiled or transpiled the source code into the child script for the browser. For example, developers who like TypeScript use it to create JavaScript. This source code gets transpiled into JavaScript so the browser script engine can run it. The URI/URL to this sourcemap file is usually at the top of the javaScript or application compiled code file in a format like //#....\nWhen this intermediary transpile file is missing or blocked for security reasons in a web browser, the application will usually not care unless it needs the source file for debugging the child script using this source file. In that case it will complain when it feels it needs this file and cannot find it, as it uses it to recreate the source file for the code running in the browser when debugging the script in order to allow a developer to debug the original source code. When it cannot find it, it means that any developer trying to debug it will not be able to do so, and is stuck with the compiled code only. So it is safe to turn off these errors in the various ways mentioned in this post. It should not affect your own scripts if it is connected to an extension. Even if it is related to your own scripts, it is still unlikely you need it unless you plan to run debugging from devtools.\n", "I had the same problem. I tried to disable the extensions one by one to check it, and finally realized I had Adblock enabled, which was causing this issue. To remove that error I followed the step below,\n\nThree dots (top right corner).\nClick More tools --> extensions.\nDisable the Adblock.\nReload the page.\n\nAnd it should work now.\n" ]
[ 342, 123, 64, 50, 47, 33, 14, 12, 10, 5, 4, 3, 3, 2, 1, 0 ]
[ "You need to open Chrome in developer mode: select More tools, then Extensions and select Developer mode\n" ]
[ -3 ]
[ "html", "javascript" ]
stackoverflow_0061339968_html_javascript.txt
Q: How to select an div element that doesn't have a Class or ID Greeting all, I'm a newbie here and I just started my carrier as junior web developer. Can some help me with below situation, I have a WordPress theme, there's some contents doesn't want to be appear so I'm trying to hide those contents by adding some coding to Additional CSS and the div element that I'm trying to hide don't have any class or id given. Please consider the example code below (I'm not showing entire code here, its just example code exact the same with html elements) <div id="shop"> <ul class="products"> <li class="product" style="list-style: none;"> <div class="product-inner"> <div class="product-thumbnail"></div> <div class="product-summary"> <div class="summary-top"></div> <div class="summary-bottom"> <div>Contents</div> <form action="#">Form</form> <div style="color: red;">Contents needs to be hide</div> <a href="#">Link</a> </div> </div> </div> </li> <li class="product" style="list-style: none;"> <div class="product-inner"> <div class="product-thumbnail"></div> <div class="product-summary"> <div class="summary-top"></div> <div class="summary-bottom"> <div>Contents</div> <form action="#">Form</form> <div style="color: red;">Contents needs to be hide</div> <a href="#">Link</a> </div> </div> </div> </li> </ul> </div> A: This solution only consider the posted code so not sure if it will also work in the actual wordpress theme, as there might be existing styles that overrides it. The element to be hidden seems to be an error or helper text that follows a form, so perhaps this can be selected as: a div directly after a form inside summary-bottom. Example: .summary-bottom > form + div { display: none; } <div id="shop"> <ul class="products"> <li class="product" style="list-style: none;"> <div class="product-inner"> <div class="product-thumbnail"></div> <div class="product-summary"> <div class="summary-top"></div> <div class="summary-bottom"> <div>Contents</div> <form action="#">Form</form> <div style="color: red;">Contents needs to be hide</div> <a href="#">Link</a> </div> </div> </div> </li> <li class="product" style="list-style: none;"> <div class="product-inner"> <div class="product-thumbnail"></div> <div class="product-summary"> <div class="summary-top"></div> <div class="summary-bottom"> <div>Contents</div> <form action="#">Form</form> <div style="color: red;">Contents needs to be hide</div> <a href="#">Link</a> </div> </div> </div> </li> </ul> </div> A: You can select the element with by using the general div tag. We can specify this further by assuming that the div should always be a child of the .summary-bottom element, and then can either always select the third child or target the general div based on its inline style attribute. This would leave you either with: .summary-bottom div:nth-child(2) (starting from 0) or .summary-bottom div[style="color: red;"]. Of course, how you can select such an element heavily varies on the real usage, and they are way more possibilities to do so, but both snippets mentioned should work on the above HTML code. A: You can use the selector property .summary-bottom div:nth-child(2) { display: none; } A: div[style="color: red;"] { display: none; } To hide the contents that you want to hide in the WordPress theme, you can use the CSS display property. This property allows you to control how an element is displayed on the page, and setting it to none will hide the element completely. To apply the display property to the specific div element that you want to hide, you can use a CSS selector to target the element. Since the div element does not have a class or ID attribute, you can use an attribute selector to target the element based on its inline style attribute. Here is an example of how you could use an attribute selector to hide the div element that has the color: red; inline style attribute: To add this CSS code to your WordPress theme, you can use the "Additional CSS" option in the WordPress customizer. This option allows you to add custom CSS code that will be applied to your theme, and it can be accessed by going to the "Appearance" menu in the WordPress admin dashboard and selecting the "Customize" option. Once you are in the customizer, you can navigate to the "Additional CSS" section, where you can add the CSS code shown above. This code will be applied to the theme, and it will hide the div element that has the color: red; inline style attribute. Note that the CSS code shown above is just an example, and you may need to adjust the code based on the specific structure and elements of your WordPress theme. It may also be helpful to use the browser's developer tools to inspect the HTML elements and determine the best way to target the element that you want to hide. To add this CSS code to your WordPress theme, you can use the "Additional CSS" option in the WordPress customizer. This option allows you to add custom CSS code that will be applied to your theme, and it can be accessed by going to the "Appearance" menu in the WordPress admin dashboard and selecting the "Customize" option. Once you are in the customizer, you can navigate to the "Additional CSS" section, where you can add the CSS code shown above. This code will be applied to the theme, and it will hide the div element that has the color: red; inline style attribute. Note that the CSS code shown above is just an example, and you may need to adjust the code based on the specific structure and elements of your WordPress theme. It may also be helpful to use the browser's developer tools to inspect the HTML elements and determine the best way to target the element that you want to hide.
How to select an div element that doesn't have a Class or ID
Greeting all, I'm a newbie here and I just started my carrier as junior web developer. Can some help me with below situation, I have a WordPress theme, there's some contents doesn't want to be appear so I'm trying to hide those contents by adding some coding to Additional CSS and the div element that I'm trying to hide don't have any class or id given. Please consider the example code below (I'm not showing entire code here, its just example code exact the same with html elements) <div id="shop"> <ul class="products"> <li class="product" style="list-style: none;"> <div class="product-inner"> <div class="product-thumbnail"></div> <div class="product-summary"> <div class="summary-top"></div> <div class="summary-bottom"> <div>Contents</div> <form action="#">Form</form> <div style="color: red;">Contents needs to be hide</div> <a href="#">Link</a> </div> </div> </div> </li> <li class="product" style="list-style: none;"> <div class="product-inner"> <div class="product-thumbnail"></div> <div class="product-summary"> <div class="summary-top"></div> <div class="summary-bottom"> <div>Contents</div> <form action="#">Form</form> <div style="color: red;">Contents needs to be hide</div> <a href="#">Link</a> </div> </div> </div> </li> </ul> </div>
[ "This solution only consider the posted code so not sure if it will also work in the actual wordpress theme, as there might be existing styles that overrides it.\nThe element to be hidden seems to be an error or helper text that follows a form, so perhaps this can be selected as: a div directly after a form inside summary-bottom.\nExample:\n\n\n.summary-bottom > form + div {\n display: none;\n}\n<div id=\"shop\">\n <ul class=\"products\">\n <li class=\"product\" style=\"list-style: none;\">\n <div class=\"product-inner\">\n <div class=\"product-thumbnail\"></div>\n <div class=\"product-summary\">\n <div class=\"summary-top\"></div>\n <div class=\"summary-bottom\">\n <div>Contents</div>\n <form action=\"#\">Form</form>\n <div style=\"color: red;\">Contents needs to be hide</div>\n <a href=\"#\">Link</a>\n </div>\n </div>\n </div>\n </li>\n <li class=\"product\" style=\"list-style: none;\">\n <div class=\"product-inner\">\n <div class=\"product-thumbnail\"></div>\n <div class=\"product-summary\">\n <div class=\"summary-top\"></div>\n <div class=\"summary-bottom\">\n <div>Contents</div>\n <form action=\"#\">Form</form>\n <div style=\"color: red;\">Contents needs to be hide</div>\n <a href=\"#\">Link</a>\n </div>\n </div>\n </div>\n </li>\n </ul>\n</div>\n\n\n\n", "You can select the element with by using the general div tag.\nWe can specify this further by assuming that the div should always be a child of the .summary-bottom element, and then can either always select the third child or target the general div based on its inline style attribute.\nThis would leave you either with: .summary-bottom div:nth-child(2) (starting from 0) or .summary-bottom div[style=\"color: red;\"].\nOf course, how you can select such an element heavily varies on the real usage, and they are way more possibilities to do so, but both snippets mentioned should work on the above HTML code.\n", "You can use the selector property\n.summary-bottom div:nth-child(2) {\n display: none;\n}\n\n", "div[style=\"color: red;\"] {\n display: none;\n}\n\nTo hide the contents that you want to hide in the WordPress theme, you can use the CSS display property. This property allows you to control how an element is displayed on the page, and setting it to none will hide the element completely.\nTo apply the display property to the specific div element that you want to hide, you can use a CSS selector to target the element. Since the div element does not have a class or ID attribute, you can use an attribute selector to target the element based on its inline style attribute.\nHere is an example of how you could use an attribute selector to hide the div element that has the color: red; inline style attribute:\nTo add this CSS code to your WordPress theme, you can use the \"Additional CSS\" option in the WordPress customizer. This option allows you to add custom CSS code that will be applied to your theme, and it can be accessed by going to the \"Appearance\" menu in the WordPress admin dashboard and selecting the \"Customize\" option.\nOnce you are in the customizer, you can navigate to the \"Additional CSS\" section, where you can add the CSS code shown above. This code will be applied to the theme, and it will hide the div element that has the color: red; inline style attribute.\nNote that the CSS code shown above is just an example, and you may need to adjust the code based on the specific structure and elements of your WordPress theme. It may also be helpful to use the browser's developer tools to inspect the HTML elements and determine the best way to target the element that you want to hide.\nTo add this CSS code to your WordPress theme, you can use the \"Additional CSS\" option in the WordPress customizer. This option allows you to add custom CSS code that will be applied to your theme, and it can be accessed by going to the \"Appearance\" menu in the WordPress admin dashboard and selecting the \"Customize\" option.\nOnce you are in the customizer, you can navigate to the \"Additional CSS\" section, where you can add the CSS code shown above. This code will be applied to the theme, and it will hide the div element that has the color: red; inline style attribute.\nNote that the CSS code shown above is just an example, and you may need to adjust the code based on the specific structure and elements of your WordPress theme. It may also be helpful to use the browser's developer tools to inspect the HTML elements and determine the best way to target the element that you want to hide.\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "css", "css_selectors", "html" ]
stackoverflow_0074680397_css_css_selectors_html.txt
Q: when I come back between screens my data is lost in kotlin? The data I selected on the 1st screen is gone when I come back to the 1st screen from the 2nd screen. I want this data to still show up. How can I do that. There was a way to do this, but I don't remember exactly, so I have to ask. I'm doing this in Kotlin by the way. for example 1- I enter the values ​​on the first screen 2- I switch to the second screen with the help of a button 3- I go back to the first screen with the help of a button from the second screen and the values ​​I entered are gone. pictures my first screen my second screen and when I come back A: I use this method that I explained bellow. I hope it works well for you. You can use the Android ViewModel class to hold data in a lifecycle-aware way. This will allow you to keep data across fragment transactions, as the ViewModel will survive orientation changes and be cleared when the activity is destroyed. You can also use the onSaveInstanceState() method to save data in a Bundle and restore it when the activity is recreated. Here I give you an example step by step: Create a ViewModel class which extends the Android ViewModel class. This class should contain a method for setting and retrieving data, as well as methods for handling the onSaveInstanceState() and onCreate() lifecycle methods. // MyViewModel.kt class MyViewModel : ViewModel() { private var myData: String? = null // Set data in the ViewModel fun setData(data: String) { myData = data } // Retrieve data from the ViewModel fun getData(): String? { return myData } // Save data in the Bundle when the activity is destroyed fun onSaveInstanceState(outState: Bundle) { outState.putString("myData", myData) } // Restore data from the Bundle when the activity is recreated fun onCreate(savedInstanceState: Bundle?) { if (savedInstanceState != null) { myData = savedInstanceState.getString("myData") } } } Create a ViewModelProvider object to create an instance of your ViewModel class. // Create an instance of the ViewModel class val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java) Set and retrieve data in your Activity or Fragment class. Set data in the ViewModel //set date in the viewModel viewModel.setData(myData) // Retrieve data from the ViewModel val myData = viewModel.getData() // Save data in the Bundle when the activity is destroyed override fun onSaveInstanceState(outState: Bundle) { viewModel.onSaveInstanceState(outState) super.onSaveInstanceState(outState) } // Restore data from the Bundle when the activity is recreated override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.onCreate(savedInstanceState) } A: You can use Shared preference simply but depending on the type of data don't worry I got you with both this is for primitive data types Store in SharedPreference(your first activity) : val preference=getSharedPreferences(preference_name, Context.MODE_PRIVATE) val editor=preference.edit() editor.putBoolean("isLoggedIn",true) editor.putInt("id",1) editor.putString("name","Alex") editor.commit() Retrieve from SharedPreference (also in your first activity but we check if the shared is null or not if it isn't then we get the data we stored before) if(preference != null){ val name = preference.getString("name", "") val id = preference.getInt("id", 0) val isLoggedIn = preference.getBoolean("isLoggedIn", false) } and this is for clearing the values of the shared preference: Context.MODE_PRIVATE).edit().clear().apply(); the second type of data is your custom object in other words your created class and you have to use the Gson library to do so which is going to convert your POJO to a string and then convert the string to JSON, when receiving your object it will reverse the algorithm : this is GSON dependency for the converting: //Gson implementation 'com.google.code.gson:gson:2.8.9' Store in Gson SharedPreference : val sharedPreferencesToJson = getSharedPreferences( "preference_name", Context.MODE_PRIVATE ) val object = Customer() // your object what ever it is object.cMobile = mobile object.cImage = imageUri.toString() val edit = sharedPreferencesToJson.edit() val gsonCustomer = Gson() val json = gsonCustomer.toJson(`object`) edit.putString(/*your object lable*/, json) edit.apply() Retrieve from Gson SharedPreference: val sharedPreferences = getSharedPreferences( "preference_name", MODE_PRIVATE ) val gson = Gson() if (sharedPreferences != null) { val json: String = sharedPreferences.getString(/*your object lable*/, "")!! object = gson.fromJson(json, Customer::class.java) } Clear Gson SharedPreference : this.getSharedPreferences(Constants.MY_SHOP, Context.MODE_PRIVATE).edit().clear().apply();
when I come back between screens my data is lost in kotlin?
The data I selected on the 1st screen is gone when I come back to the 1st screen from the 2nd screen. I want this data to still show up. How can I do that. There was a way to do this, but I don't remember exactly, so I have to ask. I'm doing this in Kotlin by the way. for example 1- I enter the values ​​on the first screen 2- I switch to the second screen with the help of a button 3- I go back to the first screen with the help of a button from the second screen and the values ​​I entered are gone. pictures my first screen my second screen and when I come back
[ "I use this method that I explained bellow. I hope it works well for you.\nYou can use the Android ViewModel class to hold data in a lifecycle-aware way. This will allow you to keep data across fragment transactions, as the ViewModel will survive orientation changes and be cleared when the activity is destroyed. You can also use the onSaveInstanceState() method to save data in a Bundle and restore it when the activity is recreated.\nHere I give you an example step by step:\n\nCreate a ViewModel class which extends the Android ViewModel class. This class should contain a method for setting and retrieving data, as well as methods for handling the onSaveInstanceState() and onCreate() lifecycle methods.\n // MyViewModel.kt\n class MyViewModel : ViewModel() {\n private var myData: String? = null\n\n // Set data in the ViewModel\n fun setData(data: String) {\n myData = data\n }\n\n // Retrieve data from the ViewModel\n fun getData(): String? {\n return myData\n }\n\n // Save data in the Bundle when the activity is destroyed\n fun onSaveInstanceState(outState: Bundle) {\n outState.putString(\"myData\", myData)\n }\n\n // Restore data from the Bundle when the activity is recreated\n fun onCreate(savedInstanceState: Bundle?) {\n if (savedInstanceState != null) {\n myData = savedInstanceState.getString(\"myData\")\n }\n }\n }\n\n\nCreate a ViewModelProvider object to create an instance of your ViewModel class.\n // Create an instance of the ViewModel class\n val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)\n\n\nSet and retrieve data in your Activity or Fragment class.\n\n\nSet data in the ViewModel\n//set date in the viewModel\nviewModel.setData(myData)\n\n// Retrieve data from the ViewModel\nval myData = viewModel.getData()\n\n// Save data in the Bundle when the activity is destroyed\noverride fun onSaveInstanceState(outState: Bundle) {\n viewModel.onSaveInstanceState(outState)\n super.onSaveInstanceState(outState)\n}\n\n// Restore data from the Bundle when the activity is recreated\noverride fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n viewModel.onCreate(savedInstanceState)\n}\n\n", "You can use Shared preference simply but depending on the type of data don't worry I got you with both\nthis is for primitive data types\nStore in SharedPreference(your first activity) :\nval preference=getSharedPreferences(preference_name, Context.MODE_PRIVATE)\n\n val editor=preference.edit()\n editor.putBoolean(\"isLoggedIn\",true)\n editor.putInt(\"id\",1)\n editor.putString(\"name\",\"Alex\")\n editor.commit()\n \n \n \n\nRetrieve from SharedPreference (also in your first activity but we check if the shared is null or not if it isn't then we get the data we stored before)\n if(preference != null){\n val name = preference.getString(\"name\", \"\")\n val id = preference.getInt(\"id\", 0)\n val isLoggedIn = preference.getBoolean(\"isLoggedIn\", false)\n }\n\nand this is for clearing the values of the shared preference:\nContext.MODE_PRIVATE).edit().clear().apply();\n \n\nthe second type of data is your custom object in other words your created class and you have to use the Gson library to do so which is going to convert your POJO to a string and then convert the string to JSON, when receiving your object it will reverse the algorithm :\nthis is GSON dependency for the converting:\n //Gson\nimplementation 'com.google.code.gson:gson:2.8.9'\n\nStore in Gson SharedPreference :\nval sharedPreferencesToJson =\n getSharedPreferences(\n \"preference_name\", Context.MODE_PRIVATE\n )\n\n val object = Customer() // your object what ever it is\n object.cMobile = mobile\n object.cImage = imageUri.toString()\n val edit = sharedPreferencesToJson.edit()\n\n val gsonCustomer = Gson()\n val json = gsonCustomer.toJson(`object`)\n edit.putString(/*your object lable*/, json)\n edit.apply()\n\nRetrieve from Gson SharedPreference:\nval sharedPreferences =\n getSharedPreferences(\n \"preference_name\", MODE_PRIVATE\n )\n val gson = Gson()\n if (sharedPreferences != null)\n {\n val json: String = sharedPreferences.getString(/*your object lable*/, \"\")!!\n object = gson.fromJson(json, Customer::class.java)\n }\n\nClear Gson SharedPreference :\n this.getSharedPreferences(Constants.MY_SHOP, Context.MODE_PRIVATE).edit().clear().apply();\n\n" ]
[ 0, 0 ]
[]
[]
[ "android", "kotlin" ]
stackoverflow_0074680172_android_kotlin.txt
Q: How to explode a dict and keep the relation with a certain column Given a dataframe: id text 1 {'txt': 'en', 'longit': 0, 'latit': 0} 2 {'txt': 'fr', 'longit': 10, 'latit': 101, 'gross': 120.1} I want to get this as output: id txt longit latit gross 1 en 0 0 NaN 2 fr 10 101 120.1 What I did: l=df.text.to_list() c=pd.DataFrame(eval(str(l))) The lines above works to create a dataframe but I am not get the right result as I want the id column together. A: Another possible solution, using pandas.json_normalize: df['id'].to_frame().join(pd.json_normalize(df['text'])) Output: id txt longit latit gross 0 1 en 0 0 NaN 1 2 fr 10 101 120.1 A: You can use pandas.concat on axis=1 to keep the column id : out = pd.concat([df["id"], c], axis=1) Another solution : out = pd.concat((df["id"], pd.DataFrame(df["text"].tolist())), axis=1) # Output : print(out) id txt longit latit gross 0 1 en 0 0 NaN 1 2 fr 10 101 120.1 A: As an alternative using pd.Series: df = df.join(df.pop('text').apply(pd.Series)) ''' id txt longit latit gross 0 1 en 0 0 NaN 1 2 fr 10 101 120.1 '''
How to explode a dict and keep the relation with a certain column
Given a dataframe: id text 1 {'txt': 'en', 'longit': 0, 'latit': 0} 2 {'txt': 'fr', 'longit': 10, 'latit': 101, 'gross': 120.1} I want to get this as output: id txt longit latit gross 1 en 0 0 NaN 2 fr 10 101 120.1 What I did: l=df.text.to_list() c=pd.DataFrame(eval(str(l))) The lines above works to create a dataframe but I am not get the right result as I want the id column together.
[ "Another possible solution, using pandas.json_normalize:\ndf['id'].to_frame().join(pd.json_normalize(df['text']))\n\nOutput:\n id txt longit latit gross\n0 1 en 0 0 NaN\n1 2 fr 10 101 120.1\n\n", "You can use pandas.concat on axis=1 to keep the column id :\nout = pd.concat([df[\"id\"], c], axis=1)\n\nAnother solution :\nout = pd.concat((df[\"id\"], pd.DataFrame(df[\"text\"].tolist())), axis=1)\n\n# Output :\nprint(out)\n id txt longit latit gross\n0 1 en 0 0 NaN\n1 2 fr 10 101 120.1\n\n", "As an alternative using pd.Series:\ndf = df.join(df.pop('text').apply(pd.Series))\n'''\n id txt longit latit gross\n0 1 en 0 0 NaN\n1 2 fr 10 101 120.1\n'''\n\n\n" ]
[ 2, 1, 1 ]
[]
[]
[ "jupyter_notebook", "pandas", "python_3.x" ]
stackoverflow_0074680159_jupyter_notebook_pandas_python_3.x.txt
Q: QT Serialport GUI and worker thread First things first, I'm a newbie in QT so don't blame me. I know that many similar questions have been in the forum, but I couldn't solve my problem. Problem description. I want to have a GUI application that receives and parses data and update some qt widget. Formerly I did them all in the Mainwindow thread, but since it hangs, I tried to make it multi-threaded. But it still hangs when I try to update GUI data as fast as 10 ms. Now, this is what I have tried. int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } class Parser : public QThread , public QRunnable { Q_OBJECT public: explicit Parser(QThread *parent = nullptr); ~Parser(); signals: void data1Available(unsigned char*); void data2Available(unsigned char*); void finished(); // QRunnable interface public: void run(); public slots: void parse(); }; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); connect( &SerialPort, SIGNAL(readyRead()), this, SLOT(ReadData()) ); QThread* thread = new QThread; thread->setObjectName("Parser Thread"); qInfo()<<"Parser Thread"; Parser* parser= new Parser(); parser->moveToThread(thread); QObject::connect(thread,&QThread::started,parser,&Parser::run); QObject::connect(parser,&Parser::finished,parser,&Parser::deleteLater); QObject::connect(parser,&Parser::finished,thread,&QThread::quit); QObject::connect(thread,&QThread::finished,thread,&QThread::deleteLater); QObject::connect(parser,SIGNAL(data1Available(unsigned char *)),this,SLOT(on_data1Available(unsigned char *))); QObject::connect(parser,SIGNAL(data2Available(unsigned char *)),this,SLOT(on_data2Available(unsigned char *))); thread->start(); } void MainWindow::ReadData() { QByteArray Data = SerialPort.readAll(); for (unsigned char i=0;i<Data.length();i++) circBuff.append(Data[i]); } void MainWindow::on_data1Available(unsigned char* tempData) { ui->label1->setNum(tempData[5]); } void MainWindow::on_data2Available(unsigned char* tempData) { ui->label2->setNum(tempData[7]); } void Parser::run() { qInfo()<<this<<Q_FUNC_INFO<<QThread::currentThread(); QScopedPointer<QEventLoop> loop (new QEventLoop); QScopedPointer<QTimer> timer (new QTimer); timer->setInterval(5); connect(timer.data(),&QTimer::timeout,this,&Parser::parse); connect(this,&Parser::finished,loop.data(),&QEventLoop::quit); timer->start(); loop->exec(); qInfo()<<this<<"Finished... "<<QThread::currentThread(); } void Parser::parse() { unsigned char tempData[16]; while (1) { while (circBuff.size()>=16) { if ( ) { if () emit data1Available(tempData); else emit data2Available(tempData); } } } emit finished(); } A: It looks like you are calling the parse() function in a loop in the Parser::run() function, which is running on the Parser thread. This means that the parse() function will be running continuously on the Parser thread, which is not good for GUI performance. Instead, you should use a timer to call the parse() function at regular intervals, so that the Parser thread can do other work in between calls to parse(). Here is how you can modify the Parser::run() function to use a timer: void Parser::run() { qInfo()<<this<<Q_FUNC_INFO<<QThread::currentThread(); // Create a timer and set its interval to 10 ms QScopedPointer<QTimer> timer (new QTimer); timer->setInterval(10); // Connect the timeout signal of the timer to the parse() slot connect(timer.data(), &QTimer::timeout, this, &Parser::parse); // Start the timer timer.start(); // Enter the event loop QEventLoop loop; connect(this, &Parser::finished, &loop, &QEventLoop::quit); loop.exec(); qInfo()<<this<<"Finished... "<<QThread::currentThread(); } Also, you should make sure that the parse() function does not run for too long, as this can also cause GUI performance issues. One way to limit the execution time of the parse() function is to use a QElapsedTimer to keep track of the time spent in the parse() function, and break out of the while loop if the execution time exceeds a certain threshold. Here is how you can do that: void Parser::parse() { // Create a QElapsedTimer to keep track of the time spent in the parse() function QElapsedTimer timer; timer.start(); while (1) { while (circBuff.size() >= 16) { if (/* check data */) { if (/* check data1 */) emit data1Available(tempData); else emit data2Available(tempData); } // Check if the parse() function has been running for more than 5 ms if (timer.elapsed() >= 5) { // Stop the loop and return from the parse() function return; } } } emit finished(); }
QT Serialport GUI and worker thread
First things first, I'm a newbie in QT so don't blame me. I know that many similar questions have been in the forum, but I couldn't solve my problem. Problem description. I want to have a GUI application that receives and parses data and update some qt widget. Formerly I did them all in the Mainwindow thread, but since it hangs, I tried to make it multi-threaded. But it still hangs when I try to update GUI data as fast as 10 ms. Now, this is what I have tried. int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } class Parser : public QThread , public QRunnable { Q_OBJECT public: explicit Parser(QThread *parent = nullptr); ~Parser(); signals: void data1Available(unsigned char*); void data2Available(unsigned char*); void finished(); // QRunnable interface public: void run(); public slots: void parse(); }; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); connect( &SerialPort, SIGNAL(readyRead()), this, SLOT(ReadData()) ); QThread* thread = new QThread; thread->setObjectName("Parser Thread"); qInfo()<<"Parser Thread"; Parser* parser= new Parser(); parser->moveToThread(thread); QObject::connect(thread,&QThread::started,parser,&Parser::run); QObject::connect(parser,&Parser::finished,parser,&Parser::deleteLater); QObject::connect(parser,&Parser::finished,thread,&QThread::quit); QObject::connect(thread,&QThread::finished,thread,&QThread::deleteLater); QObject::connect(parser,SIGNAL(data1Available(unsigned char *)),this,SLOT(on_data1Available(unsigned char *))); QObject::connect(parser,SIGNAL(data2Available(unsigned char *)),this,SLOT(on_data2Available(unsigned char *))); thread->start(); } void MainWindow::ReadData() { QByteArray Data = SerialPort.readAll(); for (unsigned char i=0;i<Data.length();i++) circBuff.append(Data[i]); } void MainWindow::on_data1Available(unsigned char* tempData) { ui->label1->setNum(tempData[5]); } void MainWindow::on_data2Available(unsigned char* tempData) { ui->label2->setNum(tempData[7]); } void Parser::run() { qInfo()<<this<<Q_FUNC_INFO<<QThread::currentThread(); QScopedPointer<QEventLoop> loop (new QEventLoop); QScopedPointer<QTimer> timer (new QTimer); timer->setInterval(5); connect(timer.data(),&QTimer::timeout,this,&Parser::parse); connect(this,&Parser::finished,loop.data(),&QEventLoop::quit); timer->start(); loop->exec(); qInfo()<<this<<"Finished... "<<QThread::currentThread(); } void Parser::parse() { unsigned char tempData[16]; while (1) { while (circBuff.size()>=16) { if ( ) { if () emit data1Available(tempData); else emit data2Available(tempData); } } } emit finished(); }
[ "It looks like you are calling the parse() function in a loop in the Parser::run() function, which is running on the Parser thread. This means that the parse() function will be running continuously on the Parser thread, which is not good for GUI performance. Instead, you should use a timer to call the parse() function at regular intervals, so that the Parser thread can do other work in between calls to parse().\nHere is how you can modify the Parser::run() function to use a timer:\nvoid Parser::run()\n{\nqInfo()<<this<<Q_FUNC_INFO<<QThread::currentThread();\n// Create a timer and set its interval to 10 ms\nQScopedPointer<QTimer> timer (new QTimer);\ntimer->setInterval(10);\n\n// Connect the timeout signal of the timer to the parse() slot\nconnect(timer.data(), &QTimer::timeout, this, &Parser::parse);\n\n// Start the timer\ntimer.start();\n\n// Enter the event loop\nQEventLoop loop;\nconnect(this, &Parser::finished, &loop, &QEventLoop::quit);\nloop.exec();\n\nqInfo()<<this<<\"Finished... \"<<QThread::currentThread();\n}\n\nAlso, you should make sure that the parse() function does not run for too long, as this can also cause GUI performance issues. One way to limit the execution time of the parse() function is to use a QElapsedTimer to keep track of the time spent in the parse() function, and break out of the while loop if the execution time exceeds a certain threshold. Here is how you can do that:\nvoid Parser::parse()\n{\n// Create a QElapsedTimer to keep track of the time spent in the parse() function\nQElapsedTimer timer;\ntimer.start();\n\nwhile (1)\n{\n while (circBuff.size() >= 16)\n {\n if (/* check data */)\n {\n if (/* check data1 */)\n emit data1Available(tempData);\n else\n emit data2Available(tempData);\n }\n\n // Check if the parse() function has been running for more than 5 ms\n if (timer.elapsed() >= 5)\n {\n // Stop the loop and return from the parse() function\n return;\n }\n }\n}\n\nemit finished();\n}\n\n" ]
[ 0 ]
[]
[]
[ "c++", "multithreading", "qt", "serial_port", "user_interface" ]
stackoverflow_0074679023_c++_multithreading_qt_serial_port_user_interface.txt
Q: The background image isn't showing up on my page I'm designing a Neocities site and on one of my pages the background image isn't showing up. I've tried doing it in HTML and CSS but neither will work. [This] (https://maggssszzz.neocities.org/spitbucket.html) is the page in question and this is the image I'm trying to attach. I initially tried placing it in the head of my HTML like this: <style> background-image: "url(https://www.google.com/url?sa=i&url=https%3A%2F%2Fpngtree.com%2Ffree-backgrounds-photos%2Fabstract-lines&psig=AOvVaw0DqRellrv87omUXChv5XUF&ust=1670010209669000&source=images&cd=vfe&ved=0CA8QjRxqFwoTCOia0u2x2fsCFQAAAAAdAAAAABAU)"; </style> But that didn't do anything, so then I thought about putting it in CSS. I tried this 2 different ways and neither worked: .body { text-align: center; background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6); } .square { text-align: center; background-color: #16a868; line-height: 70px; width: 400px; height: 800px; color: #701ba1; margin: 20px auto; } and attempt 2: .body { text-align: center; } .square { text-align: center; background-color: #16a868; background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6); line-height: 70px; width: 400px; height: 800px; color: #701ba1; margin: 20px auto; } But nothing works. What did I do wrong? A: I got it fixed! Here is the working code: <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="spitbucket.css" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?Family=Raleway"> <title>Spitbucket.com</title> <style> h1, p, h2, ul {font-family: "Raleway", sans-serif} body { background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6); } </style>
The background image isn't showing up on my page
I'm designing a Neocities site and on one of my pages the background image isn't showing up. I've tried doing it in HTML and CSS but neither will work. [This] (https://maggssszzz.neocities.org/spitbucket.html) is the page in question and this is the image I'm trying to attach. I initially tried placing it in the head of my HTML like this: <style> background-image: "url(https://www.google.com/url?sa=i&url=https%3A%2F%2Fpngtree.com%2Ffree-backgrounds-photos%2Fabstract-lines&psig=AOvVaw0DqRellrv87omUXChv5XUF&ust=1670010209669000&source=images&cd=vfe&ved=0CA8QjRxqFwoTCOia0u2x2fsCFQAAAAAdAAAAABAU)"; </style> But that didn't do anything, so then I thought about putting it in CSS. I tried this 2 different ways and neither worked: .body { text-align: center; background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6); } .square { text-align: center; background-color: #16a868; line-height: 70px; width: 400px; height: 800px; color: #701ba1; margin: 20px auto; } and attempt 2: .body { text-align: center; } .square { text-align: center; background-color: #16a868; background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6); line-height: 70px; width: 400px; height: 800px; color: #701ba1; margin: 20px auto; } But nothing works. What did I do wrong?
[ "I got it fixed! Here is the working code:\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<link rel=\"stylesheet\" href=\"spitbucket.css\" />\n<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?Family=Raleway\">\n<title>Spitbucket.com</title>\n<style>\n h1, p, h2, ul {font-family: \"Raleway\", sans-serif}\n body {\n background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6);\n }\n</style>\n\n" ]
[ 0 ]
[ "It's working fine. Please check \nUse this code\n.square {\ntext-align: center;\nbackground-color: #16a868;\nline-height: 70px;\nwidth: 400px;\nheight: 800px;\ncolor: #701ba1;\nmargin: 20px auto;\nbackground-image: url(https://www.imgonline.com.ua/examples/two-tone-blurred-background-1-big.jpg);\n\n}\n" ]
[ -1 ]
[ "background_image", "css", "html", "image" ]
stackoverflow_0074662901_background_image_css_html_image.txt
Q: Jolt spec to remove element from array For my input json, I need to write a Jolt spec that can remove the externalId field from the list of externalIds in order to avoid repeating this element in the list. Input: { "id": "id_1", "targetId": "targetId42", "externalId": "1extid", "attributes": { "uniqueInfo": { "externalIds": [ "3extid", "2extid", "4extid", "1extid", "5extid" ] } } } Desired output: { "id": "id_1", "targetId": "targetId42", "externalId": "1extid", "attributes": { "uniqueInfo": { "externalIds": [ "3extid", "2extid", "4extid", "5extid" ] } } } Could someone please help with this query. Thanks. A: You can consecutively use "$":"@(0)" tecnique in order to remove the array which is generated due to coincident values (1extid) of externalId within shift transformation specs such that [ { "operation": "shift", "spec": { "*": "&", "externalId": "attributes.uniqueInfo.externalIds.@(0)", //exchange key-value pair "@(0,externalId)": "externalId", //multiplexing value to keep for later steps "attributes": { "uniqueInfo": { "externalIds": { "*": { "@(4,externalId)": "&4.&3.&2.@(0)" //exchange key-value pairs } } } } } }, { "operation": "shift", "spec": { "*": "&", "attributes": { "uniqueInfo": { "externalIds": { "*": { "$": "&4.&3.&2.@(0)"//exchange key-value pairs again } } } } } }, { "operation": "shift", "spec": { "*": "&", "attributes": { "uniqueInfo": { "externalIds": { "*": { "*": "&4.&3.&2[&]" } } } } } } ]
Jolt spec to remove element from array
For my input json, I need to write a Jolt spec that can remove the externalId field from the list of externalIds in order to avoid repeating this element in the list. Input: { "id": "id_1", "targetId": "targetId42", "externalId": "1extid", "attributes": { "uniqueInfo": { "externalIds": [ "3extid", "2extid", "4extid", "1extid", "5extid" ] } } } Desired output: { "id": "id_1", "targetId": "targetId42", "externalId": "1extid", "attributes": { "uniqueInfo": { "externalIds": [ "3extid", "2extid", "4extid", "5extid" ] } } } Could someone please help with this query. Thanks.
[ "You can consecutively use \"$\":\"@(0)\" tecnique in order to remove the array which is generated due to coincident values (1extid) of externalId within shift transformation specs such that\n[\n {\n \"operation\": \"shift\",\n \"spec\": {\n \"*\": \"&\",\n \"externalId\": \"attributes.uniqueInfo.externalIds.@(0)\", //exchange key-value pair\n \"@(0,externalId)\": \"externalId\", //multiplexing value to keep for later steps\n \"attributes\": {\n \"uniqueInfo\": {\n \"externalIds\": {\n \"*\": {\n \"@(4,externalId)\": \"&4.&3.&2.@(0)\" //exchange key-value pairs\n }\n }\n }\n }\n }\n },\n {\n \"operation\": \"shift\",\n \"spec\": {\n \"*\": \"&\",\n \"attributes\": {\n \"uniqueInfo\": {\n \"externalIds\": {\n \"*\": {\n \"$\": \"&4.&3.&2.@(0)\"//exchange key-value pairs again\n }\n }\n }\n }\n }\n },\n {\n \"operation\": \"shift\",\n \"spec\": {\n \"*\": \"&\",\n \"attributes\": {\n \"uniqueInfo\": {\n \"externalIds\": {\n \"*\": {\n \"*\": \"&4.&3.&2[&]\"\n }\n }\n }\n }\n }\n }\n]\n\n" ]
[ 0 ]
[]
[]
[ "apache_nifi", "jolt", "json", "transformation" ]
stackoverflow_0074679656_apache_nifi_jolt_json_transformation.txt
Q: Flutter ScrollController - how to disable scroll in certain area? Is it possible to disable scroll in certain areas of a scrollable widget? Lets say I want to disable scroll within a square area in the middle of the ListView/CustomScrollView, is that possible? I am thinking it might require me to pass true or false in some touch hitTest or some similar concept but I am not sure where to start. Any ideas? A: You can use the Stack widget to overlay an AbsorbPointer widget on top of your scrollable: return Scaffold( body: Stack( children: [ CustomScrollView( slivers: [ SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return Text('...'); }, childCount: 200, ), ), // Rest of the list ], ), Positioned.fill( child: Center( child: AbsorbPointer( absorbing: true, child: Container( width: 100, height: 100, color: Colors.blue, ), ), ), ), ], ), );
Flutter ScrollController - how to disable scroll in certain area?
Is it possible to disable scroll in certain areas of a scrollable widget? Lets say I want to disable scroll within a square area in the middle of the ListView/CustomScrollView, is that possible? I am thinking it might require me to pass true or false in some touch hitTest or some similar concept but I am not sure where to start. Any ideas?
[ "You can use the Stack widget to overlay an AbsorbPointer widget on top of your scrollable:\n return Scaffold(\n body: Stack(\n children: [\n CustomScrollView(\n slivers: [\n SliverList(\n delegate: SliverChildBuilderDelegate(\n (BuildContext context, int index) {\n return Text('...');\n },\n childCount: 200,\n ),\n ),\n // Rest of the list\n ],\n ),\n Positioned.fill(\n child: Center(\n child: AbsorbPointer(\n absorbing: true,\n child: Container(\n width: 100,\n height: 100,\n color: Colors.blue,\n ),\n ),\n ),\n ),\n ],\n ),\n );\n\n" ]
[ 0 ]
[]
[]
[ "flutter", "flutter_dependencies", "flutter_sliver", "flutter_sliverappbar" ]
stackoverflow_0074679172_flutter_flutter_dependencies_flutter_sliver_flutter_sliverappbar.txt
Q: Insert order details from XML into SQL database table I want to insert this XML file into a database table. It has two different items and orderno (code) should be inserted for both rows. Here is the xml file - it should be like this : row #1 orderno: i6tp-pucp-dsrx-1gg7-ikef itemno: 2304 row #2 orderno: i6tp-pucp-dsrx-1gg7-ikef itemno: 10914 XML: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns1:orders> <ns1:order> <ns1:code>i6tp-pucp-dsrx-1gg7-ikef</ns1:code> <ns1:status>CONFIRMED</ns1:status> <ns1:date>2022-11-30T20:50:36.920</ns1:date> <ns1:deliveryAddress> <ns1:firstName>fname</ns1:firstName> <ns1:lastName>lastname</ns1:lastName> <ns1:streetname>streetname </ns1:streetname> <ns1:streetnumber>stno</ns1:streetnumber> <ns1:town>town</ns1:town> <ns1:postalCode>PLZ</ns1:postalCode> <ns1:gender>FEMALE</ns1:gender> <ns1:deliveryAddressType>address</ns1:deliveryAddressType> </ns1:deliveryAddress> <ns1:paymentAddress> <ns1:firstName>fname</ns1:firstName> <ns1:lastName>lastname</ns1:lastName> <ns1:streetname>streetname </ns1:streetname> <ns1:streetnumber>stno</ns1:streetnumber> <ns1:town>town</ns1:town> <ns1:postalCode>PLZ</ns1:postalCode> <ns1:gender>FEMALE</ns1:gender> </ns1:paymentAddress> <ns1:currency>EUR</ns1:currency> <ns1:entries> <ns1:entry> <ns1:sku>2304</ns1:sku> <ns1:quantity>1</ns1:quantity> <ns1:basePrice>18.49</ns1:basePrice> <ns1:totalBasePrice>18.49</ns1:totalBasePrice> <ns1:merchantSubTotal>18.49</ns1:merchantSubTotal> <ns1:totalPrice>18.49</ns1:totalPrice> <ns1:name>ArtNo1</ns1:name> <ns1:taxClass>at-vat-full</ns1:taxClass> <ns1:warehouse>001-default-warehouse</ns1:warehouse> </ns1:entry> <ns1:entry> <ns1:sku>10914</ns1:sku> <ns1:quantity>1</ns1:quantity> <ns1:basePrice>49.99</ns1:basePrice> <ns1:totalBasePrice>49.99</ns1:totalBasePrice> <ns1:merchantSubTotal>49.99</ns1:merchantSubTotal> <ns1:totalPrice>49.99</ns1:totalPrice> <ns1:name>Artno2</ns1:name> <ns1:taxClass>at-vat-full</ns1:taxClass> <ns1:warehouse>001-default-warehouse</ns1:warehouse> </ns1:entry> </ns1:entries> <ns1:cancelOrders/> <ns1:returnOrders/> <ns1:delayOrders/> <ns1:consignments/> <ns1:totalBasePrice>68.48</ns1:totalBasePrice> <ns1:merchantDiscountTotal>0</ns1:merchantDiscountTotal> <ns1:merchantSubTotal>68.48</ns1:merchantSubTotal> <ns1:marketplaceDiscountTotal>0</ns1:marketplaceDiscountTotal> <ns1:subtotal>68.48</ns1:subtotal> <ns1:deliveryCost>0.0</ns1:deliveryCost> <ns1:paymentCost>0.0</ns1:paymentCost> <ns1:totalPrice>68.48</ns1:totalPrice> <ns1:paymentMode>payment</ns1:paymentMode> <ns1:deliveryMode>E+2</ns1:deliveryMode> <ns1:additionalDeliveryOption>E2_1</ns1:additionalDeliveryOption> <ns1:deliveryConfiguration>Post</ns1:deliveryConfiguration> <ns1:shipmentDate>2022-12-02T07:00:11.680</ns1:shipmentDate> <ns1:estimatedDeliveryDate>2022-12-06T07:00:11.680</ns1:estimatedDeliveryDate> <ns1:avisoData> <ns1:address> <ns1:line>line1</ns1:line> <ns1:line>line2</ns1:line> <ns1:line>line3</ns1:line> </ns1:address> <ns1:phone>0123456789</ns1:phone> <ns1:email>info@gmail.com</ns1:email> </ns1:avisoData> </ns1:order> </ns1:orders> A: Try something like this - obviously, as mentioned - I don't know what your XML namespace declaration looks like, so I've just faked it here - adapt as needed.... DECLARE @Data XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns1:orders xmlns:ns1="urn:somenamespace"> <ns1:order> <ns1:code>i6tp-pucp-dsrx-1gg7-ikef</ns1:code> <ns1:status>CONFIRMED</ns1:status> <ns1:date>2022-11-30T20:50:36.920</ns1:date> <ns1:deliveryAddress> <ns1:firstName>fname</ns1:firstName> <ns1:lastName>lastname</ns1:lastName> <ns1:streetname>streetname </ns1:streetname> <ns1:streetnumber>stno</ns1:streetnumber> <ns1:town>town</ns1:town> <ns1:postalCode>PLZ</ns1:postalCode> <ns1:gender>FEMALE</ns1:gender> <ns1:deliveryAddressType>address</ns1:deliveryAddressType> </ns1:deliveryAddress> <ns1:paymentAddress> <ns1:firstName>fname</ns1:firstName> <ns1:lastName>lastname</ns1:lastName> <ns1:streetname>streetname </ns1:streetname> <ns1:streetnumber>stno</ns1:streetnumber> <ns1:town>town</ns1:town> <ns1:postalCode>PLZ</ns1:postalCode> <ns1:gender>FEMALE</ns1:gender> </ns1:paymentAddress> <ns1:currency>EUR</ns1:currency> <ns1:entries> <ns1:entry> <ns1:sku>2304</ns1:sku> <ns1:quantity>1</ns1:quantity> <ns1:basePrice>18.49</ns1:basePrice> <ns1:totalBasePrice>18.49</ns1:totalBasePrice> <ns1:merchantSubTotal>18.49</ns1:merchantSubTotal> <ns1:totalPrice>18.49</ns1:totalPrice> <ns1:name>ArtNo1</ns1:name> <ns1:taxClass>at-vat-full</ns1:taxClass> <ns1:warehouse>001-default-warehouse</ns1:warehouse> </ns1:entry> <ns1:entry> <ns1:sku>10914</ns1:sku> <ns1:quantity>1</ns1:quantity> <ns1:basePrice>49.99</ns1:basePrice> <ns1:totalBasePrice>49.99</ns1:totalBasePrice> <ns1:merchantSubTotal>49.99</ns1:merchantSubTotal> <ns1:totalPrice>49.99</ns1:totalPrice> <ns1:name>Artno2</ns1:name> <ns1:taxClass>at-vat-full</ns1:taxClass> <ns1:warehouse>001-default-warehouse</ns1:warehouse> </ns1:entry> </ns1:entries> <ns1:cancelOrders/> <ns1:returnOrders/> <ns1:delayOrders/> <ns1:consignments/> <ns1:totalBasePrice>68.48</ns1:totalBasePrice> <ns1:merchantDiscountTotal>0</ns1:merchantDiscountTotal> <ns1:merchantSubTotal>68.48</ns1:merchantSubTotal> <ns1:marketplaceDiscountTotal>0</ns1:marketplaceDiscountTotal> <ns1:subtotal>68.48</ns1:subtotal> <ns1:deliveryCost>0.0</ns1:deliveryCost> <ns1:paymentCost>0.0</ns1:paymentCost> <ns1:totalPrice>68.48</ns1:totalPrice> <ns1:paymentMode>payment</ns1:paymentMode> <ns1:deliveryMode>E+2</ns1:deliveryMode> <ns1:additionalDeliveryOption>E2_1</ns1:additionalDeliveryOption> <ns1:deliveryConfiguration>Post</ns1:deliveryConfiguration> <ns1:shipmentDate>2022-12-02T07:00:11.680</ns1:shipmentDate> <ns1:estimatedDeliveryDate>2022-12-06T07:00:11.680</ns1:estimatedDeliveryDate> <ns1:avisoData> <ns1:address> <ns1:line>line1</ns1:line> <ns1:line>line2</ns1:line> <ns1:line>line3</ns1:line> </ns1:address> <ns1:phone>0123456789</ns1:phone> <ns1:email>info@gmail.com</ns1:email> </ns1:avisoData> </ns1:order> </ns1:orders>'; Use this SQL query using the SQL Server XQuery support to get at your data items: WITH XMLNAMESPACES('urn:somenamespace' AS ns1) SELECT OrderNo = xc.value('(ns1:code)[1]', 'varchar(50)'), ItemNo = xc2.value('(ns1:sku)[1]', 'int') FROM @Data.nodes('/ns1:orders/ns1:order') AS XT(XC) CROSS APPLY XC.nodes('ns1:entries/ns1:entry') AS XT2(XC2) This returns a result of: OrderNo ItemNo ----------------------------------- i6tp-pucp-dsrx-1gg7-ikef 2304 i6tp-pucp-dsrx-1gg7-ikef 10914
Insert order details from XML into SQL database table
I want to insert this XML file into a database table. It has two different items and orderno (code) should be inserted for both rows. Here is the xml file - it should be like this : row #1 orderno: i6tp-pucp-dsrx-1gg7-ikef itemno: 2304 row #2 orderno: i6tp-pucp-dsrx-1gg7-ikef itemno: 10914 XML: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns1:orders> <ns1:order> <ns1:code>i6tp-pucp-dsrx-1gg7-ikef</ns1:code> <ns1:status>CONFIRMED</ns1:status> <ns1:date>2022-11-30T20:50:36.920</ns1:date> <ns1:deliveryAddress> <ns1:firstName>fname</ns1:firstName> <ns1:lastName>lastname</ns1:lastName> <ns1:streetname>streetname </ns1:streetname> <ns1:streetnumber>stno</ns1:streetnumber> <ns1:town>town</ns1:town> <ns1:postalCode>PLZ</ns1:postalCode> <ns1:gender>FEMALE</ns1:gender> <ns1:deliveryAddressType>address</ns1:deliveryAddressType> </ns1:deliveryAddress> <ns1:paymentAddress> <ns1:firstName>fname</ns1:firstName> <ns1:lastName>lastname</ns1:lastName> <ns1:streetname>streetname </ns1:streetname> <ns1:streetnumber>stno</ns1:streetnumber> <ns1:town>town</ns1:town> <ns1:postalCode>PLZ</ns1:postalCode> <ns1:gender>FEMALE</ns1:gender> </ns1:paymentAddress> <ns1:currency>EUR</ns1:currency> <ns1:entries> <ns1:entry> <ns1:sku>2304</ns1:sku> <ns1:quantity>1</ns1:quantity> <ns1:basePrice>18.49</ns1:basePrice> <ns1:totalBasePrice>18.49</ns1:totalBasePrice> <ns1:merchantSubTotal>18.49</ns1:merchantSubTotal> <ns1:totalPrice>18.49</ns1:totalPrice> <ns1:name>ArtNo1</ns1:name> <ns1:taxClass>at-vat-full</ns1:taxClass> <ns1:warehouse>001-default-warehouse</ns1:warehouse> </ns1:entry> <ns1:entry> <ns1:sku>10914</ns1:sku> <ns1:quantity>1</ns1:quantity> <ns1:basePrice>49.99</ns1:basePrice> <ns1:totalBasePrice>49.99</ns1:totalBasePrice> <ns1:merchantSubTotal>49.99</ns1:merchantSubTotal> <ns1:totalPrice>49.99</ns1:totalPrice> <ns1:name>Artno2</ns1:name> <ns1:taxClass>at-vat-full</ns1:taxClass> <ns1:warehouse>001-default-warehouse</ns1:warehouse> </ns1:entry> </ns1:entries> <ns1:cancelOrders/> <ns1:returnOrders/> <ns1:delayOrders/> <ns1:consignments/> <ns1:totalBasePrice>68.48</ns1:totalBasePrice> <ns1:merchantDiscountTotal>0</ns1:merchantDiscountTotal> <ns1:merchantSubTotal>68.48</ns1:merchantSubTotal> <ns1:marketplaceDiscountTotal>0</ns1:marketplaceDiscountTotal> <ns1:subtotal>68.48</ns1:subtotal> <ns1:deliveryCost>0.0</ns1:deliveryCost> <ns1:paymentCost>0.0</ns1:paymentCost> <ns1:totalPrice>68.48</ns1:totalPrice> <ns1:paymentMode>payment</ns1:paymentMode> <ns1:deliveryMode>E+2</ns1:deliveryMode> <ns1:additionalDeliveryOption>E2_1</ns1:additionalDeliveryOption> <ns1:deliveryConfiguration>Post</ns1:deliveryConfiguration> <ns1:shipmentDate>2022-12-02T07:00:11.680</ns1:shipmentDate> <ns1:estimatedDeliveryDate>2022-12-06T07:00:11.680</ns1:estimatedDeliveryDate> <ns1:avisoData> <ns1:address> <ns1:line>line1</ns1:line> <ns1:line>line2</ns1:line> <ns1:line>line3</ns1:line> </ns1:address> <ns1:phone>0123456789</ns1:phone> <ns1:email>info@gmail.com</ns1:email> </ns1:avisoData> </ns1:order> </ns1:orders>
[ "Try something like this - obviously, as mentioned - I don't know what your XML namespace declaration looks like, so I've just faked it here - adapt as needed....\nDECLARE @Data XML = \n'<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<ns1:orders xmlns:ns1=\"urn:somenamespace\">\n <ns1:order>\n <ns1:code>i6tp-pucp-dsrx-1gg7-ikef</ns1:code>\n <ns1:status>CONFIRMED</ns1:status>\n <ns1:date>2022-11-30T20:50:36.920</ns1:date>\n <ns1:deliveryAddress>\n <ns1:firstName>fname</ns1:firstName>\n <ns1:lastName>lastname</ns1:lastName>\n <ns1:streetname>streetname </ns1:streetname>\n <ns1:streetnumber>stno</ns1:streetnumber>\n <ns1:town>town</ns1:town>\n <ns1:postalCode>PLZ</ns1:postalCode>\n <ns1:gender>FEMALE</ns1:gender>\n <ns1:deliveryAddressType>address</ns1:deliveryAddressType>\n </ns1:deliveryAddress>\n <ns1:paymentAddress>\n <ns1:firstName>fname</ns1:firstName>\n <ns1:lastName>lastname</ns1:lastName>\n <ns1:streetname>streetname </ns1:streetname>\n <ns1:streetnumber>stno</ns1:streetnumber>\n <ns1:town>town</ns1:town>\n <ns1:postalCode>PLZ</ns1:postalCode>\n <ns1:gender>FEMALE</ns1:gender>\n </ns1:paymentAddress>\n <ns1:currency>EUR</ns1:currency>\n <ns1:entries>\n <ns1:entry>\n <ns1:sku>2304</ns1:sku>\n <ns1:quantity>1</ns1:quantity>\n <ns1:basePrice>18.49</ns1:basePrice>\n <ns1:totalBasePrice>18.49</ns1:totalBasePrice>\n <ns1:merchantSubTotal>18.49</ns1:merchantSubTotal>\n <ns1:totalPrice>18.49</ns1:totalPrice>\n <ns1:name>ArtNo1</ns1:name>\n <ns1:taxClass>at-vat-full</ns1:taxClass>\n <ns1:warehouse>001-default-warehouse</ns1:warehouse>\n </ns1:entry>\n <ns1:entry>\n <ns1:sku>10914</ns1:sku>\n <ns1:quantity>1</ns1:quantity>\n <ns1:basePrice>49.99</ns1:basePrice>\n <ns1:totalBasePrice>49.99</ns1:totalBasePrice>\n <ns1:merchantSubTotal>49.99</ns1:merchantSubTotal>\n <ns1:totalPrice>49.99</ns1:totalPrice>\n <ns1:name>Artno2</ns1:name>\n <ns1:taxClass>at-vat-full</ns1:taxClass>\n <ns1:warehouse>001-default-warehouse</ns1:warehouse>\n </ns1:entry>\n </ns1:entries>\n <ns1:cancelOrders/>\n <ns1:returnOrders/>\n <ns1:delayOrders/>\n <ns1:consignments/>\n <ns1:totalBasePrice>68.48</ns1:totalBasePrice>\n <ns1:merchantDiscountTotal>0</ns1:merchantDiscountTotal>\n <ns1:merchantSubTotal>68.48</ns1:merchantSubTotal>\n <ns1:marketplaceDiscountTotal>0</ns1:marketplaceDiscountTotal>\n <ns1:subtotal>68.48</ns1:subtotal>\n <ns1:deliveryCost>0.0</ns1:deliveryCost>\n <ns1:paymentCost>0.0</ns1:paymentCost>\n <ns1:totalPrice>68.48</ns1:totalPrice>\n <ns1:paymentMode>payment</ns1:paymentMode>\n <ns1:deliveryMode>E+2</ns1:deliveryMode>\n <ns1:additionalDeliveryOption>E2_1</ns1:additionalDeliveryOption>\n <ns1:deliveryConfiguration>Post</ns1:deliveryConfiguration>\n <ns1:shipmentDate>2022-12-02T07:00:11.680</ns1:shipmentDate>\n <ns1:estimatedDeliveryDate>2022-12-06T07:00:11.680</ns1:estimatedDeliveryDate>\n <ns1:avisoData>\n <ns1:address>\n <ns1:line>line1</ns1:line>\n <ns1:line>line2</ns1:line>\n <ns1:line>line3</ns1:line>\n </ns1:address>\n <ns1:phone>0123456789</ns1:phone>\n <ns1:email>info@gmail.com</ns1:email>\n </ns1:avisoData>\n </ns1:order>\n</ns1:orders>';\n\nUse this SQL query using the SQL Server XQuery support to get at your data items:\nWITH XMLNAMESPACES('urn:somenamespace' AS ns1)\nSELECT\n OrderNo = xc.value('(ns1:code)[1]', 'varchar(50)'),\n ItemNo = xc2.value('(ns1:sku)[1]', 'int')\nFROM\n @Data.nodes('/ns1:orders/ns1:order') AS XT(XC)\nCROSS APPLY\n XC.nodes('ns1:entries/ns1:entry') AS XT2(XC2)\n\nThis returns a result of:\nOrderNo ItemNo\n-----------------------------------\ni6tp-pucp-dsrx-1gg7-ikef 2304\ni6tp-pucp-dsrx-1gg7-ikef 10914\n\n" ]
[ 1 ]
[]
[]
[ "sql_server", "xml", "xquery" ]
stackoverflow_0074679670_sql_server_xml_xquery.txt
Q: Convert a string of characters into a hex variable input I have output as in below Hello I use "list" to separate it to characters MS=list(MS) output: ['H', 'e', 'l', 'l', 'o'] I attempted to make it as input in hex format, as shown below: p = (0x48, 0x65, 0x6c, 0x6c, 0x6f) I tried to use the code below to convert it to hex: p = tuple(hex(x) for x in MS) However, it did not work. Is there anyone who knows how to do this?  The error message TypeError: 'str' object cannot be interpreted as an integer A: The hex() function expects an integer, that's the reason why it complains about the str object. You can use help(hex) to obtain the documentation : "Return the hexadecimal representation of an integer." In the loop you can convert each letter to an integer thanks to the ord() function that "returns the Unicode code point for a one-character string". p = tuple(hex(ord(x)) for x in MS) # ('0x48', '0x65', '0x6c', '0x6c', '0x6f')
Convert a string of characters into a hex variable input
I have output as in below Hello I use "list" to separate it to characters MS=list(MS) output: ['H', 'e', 'l', 'l', 'o'] I attempted to make it as input in hex format, as shown below: p = (0x48, 0x65, 0x6c, 0x6c, 0x6f) I tried to use the code below to convert it to hex: p = tuple(hex(x) for x in MS) However, it did not work. Is there anyone who knows how to do this?  The error message TypeError: 'str' object cannot be interpreted as an integer
[ "The hex() function expects an integer, that's the reason why it complains about the str object.\nYou can use help(hex) to obtain the documentation : \"Return the hexadecimal representation of an integer.\"\nIn the loop you can convert each letter to an integer thanks to the ord() function that \"returns the Unicode code point for a one-character string\".\np = tuple(hex(ord(x)) for x in MS) # ('0x48', '0x65', '0x6c', '0x6c', '0x6f')\n\n" ]
[ 0 ]
[]
[]
[ "hex", "python" ]
stackoverflow_0074679916_hex_python.txt
Q: I'm trying to assign a color to a text in tailwindcss but no color is displaying in the browser The color class refuses to have any effect on my html tags <!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="output.css" rel="stylesheet"> </head> <body> <h1 class="text-yellow-400 font-bold"> Hello world! </h1> </body> </html> This is the outcome of the code A: Try to add Tailwind with the CDN. <!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.tailwindcss.com"></script> </head> <body> <h1 class="text-yellow-400 font-bold"> Hello world! </h1> </body> </html>
I'm trying to assign a color to a text in tailwindcss but no color is displaying in the browser
The color class refuses to have any effect on my html tags <!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="output.css" rel="stylesheet"> </head> <body> <h1 class="text-yellow-400 font-bold"> Hello world! </h1> </body> </html> This is the outcome of the code
[ "Try to add Tailwind with the CDN.\n<!doctype html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <script src=\"https://cdn.tailwindcss.com\"></script>\n </head>\n <body>\n <h1 class=\"text-yellow-400 font-bold\">\n Hello world!\n </h1>\n </body>\n</html>\n\n" ]
[ 0 ]
[]
[]
[ "css", "html", "php", "reactjs", "tailwind_css" ]
stackoverflow_0074680059_css_html_php_reactjs_tailwind_css.txt
Q: How to write numbers and strings to csv file in Python I'm new to coding so this may seem a trifle basic ... I'm trying to write three data elements to each record of a csv file. Two of the elements (flow_temp and return_temp) are floating point numbers while the third (flame) is a string ("on" or "off"). Here is my write statement: f.write(str(flow_temp)+","+str(return_temp)+flame+"\n") and here is the error: TypeError: can only concatenate str (not "bytes") to str If I remove flame from the write statement the error goes. I have also tried csv.write but couldn't get that to work either! Mike EDIT: here is the complete code. It uses a command called ebusctl to read the three data elements from a bus every 10 seconds. from subprocess import check_output from datetime import datetime import threading with open("sandbox.csv","w", encoding="utf-8") as f: f.write("Flow,Return,Flame"+"\n") def read_ebus(): threading.Timer(10.0, read_ebus).start() cmd = ["/usr/bin/ebusctl", "read", "-f"] flow_temp = float(check_output([*cmd, "FlowTemp", "temp"])) return_temp = float(check_output([*cmd, "ReturnTemp", "temp"])) flame = check_output([*cmd, "Flame"]) with open("sandbox.csv","a", encoding="utf8") as f: f.write(datetime.today().strftime('%Y-%m-%d'+"," '%H:%M:%S')+",") f.write(str(flow_temp)+","+str(return_temp)+flame+"\n") read_ebus()
How to write numbers and strings to csv file in Python
I'm new to coding so this may seem a trifle basic ... I'm trying to write three data elements to each record of a csv file. Two of the elements (flow_temp and return_temp) are floating point numbers while the third (flame) is a string ("on" or "off"). Here is my write statement: f.write(str(flow_temp)+","+str(return_temp)+flame+"\n") and here is the error: TypeError: can only concatenate str (not "bytes") to str If I remove flame from the write statement the error goes. I have also tried csv.write but couldn't get that to work either! Mike EDIT: here is the complete code. It uses a command called ebusctl to read the three data elements from a bus every 10 seconds. from subprocess import check_output from datetime import datetime import threading with open("sandbox.csv","w", encoding="utf-8") as f: f.write("Flow,Return,Flame"+"\n") def read_ebus(): threading.Timer(10.0, read_ebus).start() cmd = ["/usr/bin/ebusctl", "read", "-f"] flow_temp = float(check_output([*cmd, "FlowTemp", "temp"])) return_temp = float(check_output([*cmd, "ReturnTemp", "temp"])) flame = check_output([*cmd, "Flame"]) with open("sandbox.csv","a", encoding="utf8") as f: f.write(datetime.today().strftime('%Y-%m-%d'+"," '%H:%M:%S')+",") f.write(str(flow_temp)+","+str(return_temp)+flame+"\n") read_ebus()
[]
[]
[ "Try to add str() to flame as well\nf.write(str(flow_temp)+\",\"+str(return_temp)+str(flame)+\"\\n\")\n\nor you could alternativaly write row using csv lib in python\nimport csv\n\n# create a csv.writer object\nwriter = csv.writer(f)\n\n# write the data to the CSV file\nwriter.writerow([flow_temp, return_temp, flame])\n\n" ]
[ -1 ]
[ "concatenation", "csv", "python" ]
stackoverflow_0074680497_concatenation_csv_python.txt
Q: Cordova - BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 63 Node : 16.13.2 Cordova : 11.0.0 Java JDK : 19.0.1 Gradle : 7.5.1 Android SDK : Level 33 So I have been building apps just fine, but Play Console warned me that I should be targeting API level 33, (I previously built 30) So I opened Android Studio and downloaded API level 31,32,33. Builds have been failing ever since, and I have been upgrading whatever else to get compatible components. I don't remember why I needed to, or if I updated Cordova also, but I did upgrade Node.js or npm. I might have just given after all the colored text saying I'm using an old version, and then I've just been chasing the rabbit ever since. I don't remember if I got Java version failure before or after I upgraded Gradle from Android studio. Anyway I got a message saying Gradle required Java 11 and I had 1.8. I think this is good as the earlier 1.8 seem ancient. I did the Java update, and got a prior bug saying deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0. I upgraded Gradle manually, and after this I got another bug saying: BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 63 One thing I noticed in my package.json is this: "devDependencies": { "cordova-android": "^10.1.2" }, Which is off from version 11 that I have. I guess downgrading something is not an option since I need to target latest API level. But I'd like to know what versions you got working both level 30 and 33. A: Just gonna let you know I upgraded npm and was able to build successfuly. New major version of npm available! 8.19.2 -> 9.1.3
Cordova - BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 63
Node : 16.13.2 Cordova : 11.0.0 Java JDK : 19.0.1 Gradle : 7.5.1 Android SDK : Level 33 So I have been building apps just fine, but Play Console warned me that I should be targeting API level 33, (I previously built 30) So I opened Android Studio and downloaded API level 31,32,33. Builds have been failing ever since, and I have been upgrading whatever else to get compatible components. I don't remember why I needed to, or if I updated Cordova also, but I did upgrade Node.js or npm. I might have just given after all the colored text saying I'm using an old version, and then I've just been chasing the rabbit ever since. I don't remember if I got Java version failure before or after I upgraded Gradle from Android studio. Anyway I got a message saying Gradle required Java 11 and I had 1.8. I think this is good as the earlier 1.8 seem ancient. I did the Java update, and got a prior bug saying deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0. I upgraded Gradle manually, and after this I got another bug saying: BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 63 One thing I noticed in my package.json is this: "devDependencies": { "cordova-android": "^10.1.2" }, Which is off from version 11 that I have. I guess downgrading something is not an option since I need to target latest API level. But I'd like to know what versions you got working both level 30 and 33.
[ "Just gonna let you know I upgraded npm and was able to build successfuly.\nNew major version of npm available! 8.19.2 -> 9.1.3\n\n" ]
[ 0 ]
[]
[]
[ "cordova", "gradle", "java" ]
stackoverflow_0074454737_cordova_gradle_java.txt
Q: SQL: How to query a junction table with compound keys by comparing rows and columns I have a Mysql junction table user_connections which maps the users table with the following columns: user_from and user_to, both are foreign keys in users table. My logic is if id1 sends a request to id2, in this case, that will be a pending request. The request will be considered aprroved only if id2 accepts the request which will give the pattern above of (id1, id2) and (id2, id1) in the table (red box). So my question is how can I query the user_connections table so I can get all the pending requests based on id1 (blue box) I have no idea how I can acheave this. So any help will be appriciated. Thank you in advance. A: If you are looking for all the pending requests defined by your user_connections table, then you need to do a left outer join of the table with itself as follows: Schema (MySQL v5.7) create table user_connections ( user_from int, user_to int, primary key(user_from, user_to) ); insert into user_connections(user_from, user_to) values(1, 2); insert into user_connections(user_from, user_to) values(2, 1); insert into user_connections(user_from, user_to) values(67, 1); insert into user_connections(user_from, user_to) values(68, 1); insert into user_connections(user_from, user_to) values(69, 1); insert into user_connections(user_from, user_to) values(70, 1); Query #1 select uc1.user_from, uc1.user_to from user_connections uc1 left join user_connections uc2 on uc2.user_from = uc1.user_to and uc2.user_to = uc1.user_from where uc2.user_from is null; user_from user_to 67 1 68 1 69 1 70 1 View on DB Fiddle For every (id1, id2) in the table we attempt to match it with a row with values (id2, id1). If there is no match, which is the case for pending requests, then the uc2.user_from and uc2.user_to columns will be null and so we just select from the left outer join those rows where uc2.from_user is null. I created the db-fiddle for you, but this something that you should have done yourself.
SQL: How to query a junction table with compound keys by comparing rows and columns
I have a Mysql junction table user_connections which maps the users table with the following columns: user_from and user_to, both are foreign keys in users table. My logic is if id1 sends a request to id2, in this case, that will be a pending request. The request will be considered aprroved only if id2 accepts the request which will give the pattern above of (id1, id2) and (id2, id1) in the table (red box). So my question is how can I query the user_connections table so I can get all the pending requests based on id1 (blue box) I have no idea how I can acheave this. So any help will be appriciated. Thank you in advance.
[ "If you are looking for all the pending requests defined by your user_connections table, then you need to do a left outer join of the table with itself as follows:\nSchema (MySQL v5.7)\ncreate table user_connections (\n user_from int,\n user_to int,\n primary key(user_from, user_to)\n );\n \n insert into user_connections(user_from, user_to) values(1, 2);\n insert into user_connections(user_from, user_to) values(2, 1);\n insert into user_connections(user_from, user_to) values(67, 1);\n insert into user_connections(user_from, user_to) values(68, 1);\n insert into user_connections(user_from, user_to) values(69, 1);\n insert into user_connections(user_from, user_to) values(70, 1);\n\n\nQuery #1\nselect uc1.user_from, uc1.user_to from\nuser_connections uc1 left join\nuser_connections uc2 on uc2.user_from = uc1.user_to and uc2.user_to = uc1.user_from\nwhere uc2.user_from is null;\n\n\n\n\n\nuser_from\nuser_to\n\n\n\n\n67\n1\n\n\n68\n1\n\n\n69\n1\n\n\n70\n1\n\n\n\n\nView on DB Fiddle\nFor every (id1, id2) in the table we attempt to match it with a row with values (id2, id1). If there is no match, which is the case for pending requests, then the uc2.user_from and uc2.user_to columns will be null and so we just select from the left outer join those rows where uc2.from_user is null.\nI created the db-fiddle for you, but this something that you should have done yourself.\n" ]
[ 1 ]
[]
[]
[ "junction_table", "mysql" ]
stackoverflow_0074680003_junction_table_mysql.txt
Q: How can I show an image with react from an api I created? I need to show an image from an api, But it wont show. Im using this.state but it goes directly to the alt image. I tried with this.state.image it supposed to go to the url_img but it´s not working. the first_name and last_name are working correctly, it´s renedering in the view ok. so the information from the api is running correctly. It´s just the image class LastUserInDb extends Component { constructor(props) { super(props); this.state = { usuario: [], }; } componentDidMount() { fetch("http://localhost:3050/usersRoutes/lastUser") .then((response) => response.json()) .then((usuario) => { console.log(usuario) this.setState({ apellido: usuario.data.last_name, nombre: usuario.data.first_name, image: usuario.data.url_img }); }); console.log(this.state.image) } render() { return ( <div className="col-lg-6 mb-4"> <div className="card shadow mb-4"> <div className="card-header py-3"> <h5 className="m-0 font-weight-bold text-gray-800"> Ultimo usuario creado:<tr></tr> {this.state.apellido}, {this.state.nombre} </h5> </div> <div className="card-body"> <div className="text-center"> <img className="img-fluid px-3 px-sm-4 mt-3 mb-4" style={{ width: "40rem" }} src={"http://localhost:3000" + this.state.image} alt= "foto ultimo usuario" /> </div> <p> </p> </div> </div> </div> ); } } export default LastUserInDb; this is the api { "data": { "url_img": "/images/users/1670121813886dennis buzenitz.jpg", "idUsuario": 29, "first_name": "Dennis", "last_name": "Buzenitz", "email": "dbuzenitz@gmail.com", "password": "$2a$10$rdmiLSvCRpuNVlBdU0daLOyVWAaizxpJAO/9Sd0lArdFP1kjfi666", "image": "1670121813886dennis buzenitz.jpg" } } A: "1670121813886dennis buzenitz.jpg" => There is an espace between "dennis" and "buzenitz", can't this be the problem ? A: you should set the src attribute of the img element directly to the URL that the API is returning, which in this case looks like it's /images/users/1670121813886dennis buzenitz.jpg. change the src attribute in your img element: <img className="img-fluid px-3 px-sm-4 mt-3 mb-4" style={{ width: "40rem" }} src={this.state.image} alt="foto ultimo usuario" />
How can I show an image with react from an api I created?
I need to show an image from an api, But it wont show. Im using this.state but it goes directly to the alt image. I tried with this.state.image it supposed to go to the url_img but it´s not working. the first_name and last_name are working correctly, it´s renedering in the view ok. so the information from the api is running correctly. It´s just the image class LastUserInDb extends Component { constructor(props) { super(props); this.state = { usuario: [], }; } componentDidMount() { fetch("http://localhost:3050/usersRoutes/lastUser") .then((response) => response.json()) .then((usuario) => { console.log(usuario) this.setState({ apellido: usuario.data.last_name, nombre: usuario.data.first_name, image: usuario.data.url_img }); }); console.log(this.state.image) } render() { return ( <div className="col-lg-6 mb-4"> <div className="card shadow mb-4"> <div className="card-header py-3"> <h5 className="m-0 font-weight-bold text-gray-800"> Ultimo usuario creado:<tr></tr> {this.state.apellido}, {this.state.nombre} </h5> </div> <div className="card-body"> <div className="text-center"> <img className="img-fluid px-3 px-sm-4 mt-3 mb-4" style={{ width: "40rem" }} src={"http://localhost:3000" + this.state.image} alt= "foto ultimo usuario" /> </div> <p> </p> </div> </div> </div> ); } } export default LastUserInDb; this is the api { "data": { "url_img": "/images/users/1670121813886dennis buzenitz.jpg", "idUsuario": 29, "first_name": "Dennis", "last_name": "Buzenitz", "email": "dbuzenitz@gmail.com", "password": "$2a$10$rdmiLSvCRpuNVlBdU0daLOyVWAaizxpJAO/9Sd0lArdFP1kjfi666", "image": "1670121813886dennis buzenitz.jpg" } }
[ "\"1670121813886dennis buzenitz.jpg\" => There is an espace between \"dennis\" and \"buzenitz\", can't this be the problem ?\n", "you should set the src attribute of the img element directly to the URL that the API is returning, which in this case looks like it's\n/images/users/1670121813886dennis buzenitz.jpg.\nchange the src attribute in your img element:\n<img\n className=\"img-fluid px-3 px-sm-4 mt-3 mb-4\"\n style={{ width: \"40rem\" }}\n src={this.state.image} \n alt=\"foto ultimo usuario\"\n/>\n\n" ]
[ 0, 0 ]
[]
[]
[ "api", "image", "reactjs", "url" ]
stackoverflow_0074680507_api_image_reactjs_url.txt
Q: PHP format() method of DateTime modifies time I'm trying to display a dateTime with a specific format, but it modifies the time when displayed : $opened_at = \DateTime::createFromFormat('Y-m-d H:i:s', '2022-12-04 19:12:31'); $opened_at->setTimezone(new \DateTimeZone('Europe/Paris')); echo $opened_at->format('d/m/Y h:i'); I'm expecting this : 04/12/2022 19:12 But instead, I'm getting this : 04/12/2022 08:12 Why is that and how to fix this ? A: Using the lower-case h in the format string will cause the time to be displayed in 12-hour format, with a lower-case h for the hour. This means, since 19 is greater than 12, it will be displayed as 07:12 (p.m.) in 12-hour format. This is shifted forward by an hour (to 08:12 pm) due to the timezone change. To fix this and display the time in 24-hour format, you can use the upper-case H in the format string instead of the lower-case h. This will cause the hour to be displayed in 24-hour format, which will not be affected by the time zone. Here is an example of how to do this: $opened_at = \DateTime::createFromFormat('Y-m-d H:i:s', '2022-12-04 19:12:31'); $opened_at->setTimezone(new \DateTimeZone('Europe/Paris')); // Timezone change offsets time to 04/12/2022 20:12:31 echo $opened_at->format('d/m/Y H:i'); // Displays "04/12/2022 20:12" Note that you must use the upper-case H in the format string, not the lower-case h. This will ensure that the time is displayed in 24-hour format but will still be affected by the time zone.
PHP format() method of DateTime modifies time
I'm trying to display a dateTime with a specific format, but it modifies the time when displayed : $opened_at = \DateTime::createFromFormat('Y-m-d H:i:s', '2022-12-04 19:12:31'); $opened_at->setTimezone(new \DateTimeZone('Europe/Paris')); echo $opened_at->format('d/m/Y h:i'); I'm expecting this : 04/12/2022 19:12 But instead, I'm getting this : 04/12/2022 08:12 Why is that and how to fix this ?
[ "Using the lower-case h in the format string will cause the time to be displayed in 12-hour format, with a lower-case h for the hour. This means, since 19 is greater than 12, it will be displayed as 07:12 (p.m.) in 12-hour format. This is shifted forward by an hour (to 08:12 pm) due to the timezone change.\nTo fix this and display the time in 24-hour format, you can use the upper-case H in the format string instead of the lower-case h. This will cause the hour to be displayed in 24-hour format, which will not be affected by the time zone. Here is an example of how to do this:\n$opened_at = \\DateTime::createFromFormat('Y-m-d H:i:s', '2022-12-04 19:12:31');\n$opened_at->setTimezone(new \\DateTimeZone('Europe/Paris')); // Timezone change offsets time to 04/12/2022 20:12:31\necho $opened_at->format('d/m/Y H:i'); // Displays \"04/12/2022 20:12\"\n\nNote that you must use the upper-case H in the format string, not the lower-case h. This will ensure that the time is displayed in 24-hour format but will still be affected by the time zone.\n" ]
[ 1 ]
[]
[]
[ "datetime", "php" ]
stackoverflow_0074680458_datetime_php.txt
Q: fine tuning gpt-3 for faq BOT I am trying to get an understanding of how fine-tuning works with gpt-3 I would like to build a chatbot, based on this data https://www.hamburg.de/contentblob/16038508/680281fe853523c4a66199077247d0ce/data/faq.pdf for that, I put this data in JSON format ( only one item, but you get the idea {"prompt":"Was ist die Grundsteuer ->","completion":" Die Grundsteuer ist eine Objektsteuer, die ohne Berücksichtigung der persönlichen Verhältnisse und der subjektiven Leistungsfähigkeit des Steuerschuldners an den Grundbesitz anknüpft. Das Aufkommen an Grundsteuer steht in voller Höhe Hamburg (als Gemeinde) zu.\n"} In total, I have around 70 question/answer pairs for this test. However, the fine-tuned model performs worse than the default DaVinci. I have 3 questions now: how can I monitor/review or verify the success of fine-tuning? is 70 question-answer pairs too few to see any results? would it make sense to augment the data in a way, that I rephrase the question-answer pairs a couple of times to get more training data? Thanks for any advice! A: Overall, thisquestion is too vague and lacks the necessary details to be considered a good fit for SO - it is more opinion based. But here's my "3" cents :) To monitor the success of fine-tuning, you can evaluate the model on a held-out test set. This test set should consist of examples that the model hasn't seen during training, so that you can see how well the model is able to generalize to new data. To evaluate the model, you can use metrics like accuracy, precision, and recall. 70 question-answer pairs may not be enough to see significant improvements from fine-tuning, especially if the data is not very diverse or representative of the task you want to perform. In general, it's a good idea to use as much high-quality training data as possible when fine-tuning a language model. Augmenting the data by rephrasing the question-answer pairs a few times could potentially help improve the performance of the fine-tuned model. This is because it would increase the amount and diversity of the training data, which could help the model learn more robust representations of the task you are trying to perform. However, it's important to make sure that the augmented data is still high-quality and accurately reflects the task you are trying to perform.
fine tuning gpt-3 for faq BOT
I am trying to get an understanding of how fine-tuning works with gpt-3 I would like to build a chatbot, based on this data https://www.hamburg.de/contentblob/16038508/680281fe853523c4a66199077247d0ce/data/faq.pdf for that, I put this data in JSON format ( only one item, but you get the idea {"prompt":"Was ist die Grundsteuer ->","completion":" Die Grundsteuer ist eine Objektsteuer, die ohne Berücksichtigung der persönlichen Verhältnisse und der subjektiven Leistungsfähigkeit des Steuerschuldners an den Grundbesitz anknüpft. Das Aufkommen an Grundsteuer steht in voller Höhe Hamburg (als Gemeinde) zu.\n"} In total, I have around 70 question/answer pairs for this test. However, the fine-tuned model performs worse than the default DaVinci. I have 3 questions now: how can I monitor/review or verify the success of fine-tuning? is 70 question-answer pairs too few to see any results? would it make sense to augment the data in a way, that I rephrase the question-answer pairs a couple of times to get more training data? Thanks for any advice!
[ "Overall, thisquestion is too vague and lacks the necessary details to be considered a good fit for SO - it is more opinion based.\nBut here's my \"3\" cents :)\n\nTo monitor the success of fine-tuning, you can evaluate the model on a held-out test set. This test set should consist of examples that the model hasn't seen during training, so that you can see how well the model is able to generalize to new data. To evaluate the model, you can use metrics like accuracy, precision, and recall.\n\n70 question-answer pairs may not be enough to see significant improvements from fine-tuning, especially if the data is not very diverse or representative of the task you want to perform. In general, it's a good idea to use as much high-quality training data as possible when fine-tuning a language model.\n\nAugmenting the data by rephrasing the question-answer pairs a few times could potentially help improve the performance of the fine-tuned model. This is because it would increase the amount and diversity of the training data, which could help the model learn more robust representations of the task you are trying to perform. However, it's important to make sure that the augmented data is still high-quality and accurately reflects the task you are trying to perform.\n\n\n" ]
[ 1 ]
[]
[]
[ "fine_tune", "gpt_3", "openai", "training_data" ]
stackoverflow_0074680520_fine_tune_gpt_3_openai_training_data.txt
Q: How to correctly use find() function with qplaintextedit I have this part of the code but it cause an infinity loop during execution, how I can avoid it ? find is a method from qplaintextedit class if (query.useRegex) { auto options = (query.flags & QTextDocument::FindCaseSensitively) ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption; QRegularExpression rx(query.text); // TODO: infinite loop caused by regex search (e.g. \w*) while (find(rx, query.flags)) { //processFind(textCursor()); } qDebug() << "End..."; } I would like to avoid infinity loop when use such patterns as \w*, \s* A: In the code you provided, it looks like the find() method is called within a while loop without any condition to break out of the loop. This will cause an infinite loop as the find() method will keep being called until the program runs out of memory or is terminated by the user. To avoid this, you can add a condition to the while loop to break out of the loop once the find() method returns false, indicating that it was unable to find a match. Here's an example of how you can do this: if (query.useRegex) { auto options = (query.flags & QTextDocument::FindCaseSensitively) ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption; QRegularExpression rx(query.text); while (find(rx, query.flags)) { //processFind(textCursor()); // Check if the find method returned false, indicating that it was unable to find a match if (!find(rx, query.flags)) { break; } } qDebug() << "End..."; } Alternatively, you can use a do-while loop instead of a while loop. This will allow you to call the find() method at least once before checking the condition to break out of the loop. Here's an example of how you can do this: if (query.useRegex) { auto options = (query.flags & QTextDocument::FindCaseSensitively) ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption; QRegularExpression rx(query.text); do { //processFind(textCursor()); } while (find(rx, query.flags)); qDebug() << "End..."; }
How to correctly use find() function with qplaintextedit
I have this part of the code but it cause an infinity loop during execution, how I can avoid it ? find is a method from qplaintextedit class if (query.useRegex) { auto options = (query.flags & QTextDocument::FindCaseSensitively) ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption; QRegularExpression rx(query.text); // TODO: infinite loop caused by regex search (e.g. \w*) while (find(rx, query.flags)) { //processFind(textCursor()); } qDebug() << "End..."; } I would like to avoid infinity loop when use such patterns as \w*, \s*
[ "In the code you provided, it looks like the find() method is called within a while loop without any condition to break out of the loop. This will cause an infinite loop as the find() method will keep being called until the program runs out of memory or is terminated by the user.\nTo avoid this, you can add a condition to the while loop to break out of the loop once the find() method returns false, indicating that it was unable to find a match. Here's an example of how you can do this:\nif (query.useRegex) {\n auto options = (query.flags & QTextDocument::FindCaseSensitively) ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption;\n QRegularExpression rx(query.text);\n\n while (find(rx, query.flags)) {\n //processFind(textCursor());\n\n // Check if the find method returned false, indicating that it was unable to find a match\n if (!find(rx, query.flags)) {\n break;\n }\n }\n\n qDebug() << \"End...\";\n}\n\nAlternatively, you can use a do-while loop instead of a while loop. This will allow you to call the find() method at least once before checking the condition to break out of the loop. Here's an example of how you can do this:\nif (query.useRegex) {\n auto options = (query.flags & QTextDocument::FindCaseSensitively) ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption;\n QRegularExpression rx(query.text);\n\n do {\n //processFind(textCursor());\n } while (find(rx, query.flags));\n\n qDebug() << \"End...\";\n}\n\n" ]
[ 0 ]
[]
[]
[ "c++", "qplaintextedit", "qt", "qtextedit" ]
stackoverflow_0074678738_c++_qplaintextedit_qt_qtextedit.txt
Q: Debugging Java programs with command line arguments from Visual Studio Code I'm using the "Extension Pack for Java" by Microsoft. It works fine, I can add new class files, compile, run and debug them. If I run extension command "Java: Create Java Project" I get a nice setup with subfolders for libraries, "binaries" and source, i.e. ./lib, ./bin, ./src. However, now I need to call a program with command line arguments. I can go to the terminal and run the program with command line arguments: java .\src\HelloWorld.java Argument1 Argument2 or compile it in VSC and run it from terminal using: java .\bin\ HelloWorld Argument1 Argument2 However, how can I add the arguments when starting the application from VSC? (running and/or debugging). I've seen and tried quite a few guides on setting up various .json "settings" files for VSC but none of them seem to match the Java Extension pack setup. What is the simplest possible solution? (simple as in fewest possible text lines in .json file). A: To run a Java program with command line arguments from Visual Studio Code, you can use the "Launch" configuration in the Debug panel. This allows you to specify the arguments that you want to pass to the program when it is launched. Here's an example of how you can set this up: Open the Debug panel in Visual Studio Code by clicking on the Debugging icon in the left sidebar, or by using the CTRL+SHIFT+D keyboard shortcut. Click on the dropdown menu next to the "Start Debugging" button, and select "Add Configuration..." In the launch.json file that opens, add a new configuration for your Java program. For example: { "name": "Hello World", "type": "java", "request": "launch", "mainClass": "src/HelloWorld", "args": "Argument1 Argument2" } Save the file, and start debugging your program by clicking on the "Start Debugging" button. The program will be launched with the specified command line arguments. Note that in the above example, the mainClass property specifies the path to the main class of your program, relative to the project root. This should be the same path that you use when running the program from the terminal.
Debugging Java programs with command line arguments from Visual Studio Code
I'm using the "Extension Pack for Java" by Microsoft. It works fine, I can add new class files, compile, run and debug them. If I run extension command "Java: Create Java Project" I get a nice setup with subfolders for libraries, "binaries" and source, i.e. ./lib, ./bin, ./src. However, now I need to call a program with command line arguments. I can go to the terminal and run the program with command line arguments: java .\src\HelloWorld.java Argument1 Argument2 or compile it in VSC and run it from terminal using: java .\bin\ HelloWorld Argument1 Argument2 However, how can I add the arguments when starting the application from VSC? (running and/or debugging). I've seen and tried quite a few guides on setting up various .json "settings" files for VSC but none of them seem to match the Java Extension pack setup. What is the simplest possible solution? (simple as in fewest possible text lines in .json file).
[ "To run a Java program with command line arguments from Visual Studio Code, you can use the \"Launch\" configuration in the Debug panel. This allows you to specify the arguments that you want to pass to the program when it is launched.\nHere's an example of how you can set this up:\n\nOpen the Debug panel in Visual Studio Code by clicking on the Debugging icon in the left sidebar, or by using the CTRL+SHIFT+D keyboard shortcut.\n\nClick on the dropdown menu next to the \"Start Debugging\" button, and select \"Add Configuration...\"\n\nIn the launch.json file that opens, add a new configuration for your Java program. For example:\n\n\n{\n \"name\": \"Hello World\",\n \"type\": \"java\",\n \"request\": \"launch\",\n \"mainClass\": \"src/HelloWorld\",\n \"args\": \"Argument1 Argument2\"\n}\n\n\nSave the file, and start debugging your program by clicking on the \"Start Debugging\" button. The program will be launched with the specified command line arguments.\n\nNote that in the above example, the mainClass property specifies the path to the main class of your program, relative to the project root. This should be the same path that you use when running the program from the terminal.\n" ]
[ 0 ]
[]
[]
[ "command_line", "ide", "java", "vscode_extensions" ]
stackoverflow_0074680482_command_line_ide_java_vscode_extensions.txt
Q: My function is not running due to VScode deprecation-warning I was doing a React Project. But the Code seems to be an argument in a function. And it is showing as deprecated in VSCode. import React, { useState } from "react"; import "./ExpenseForm.css"; const ExpenseForm = () => { const [enteredTitle, setEnteredTitle] = useState(""); const [enteredAmount, setEnteredAmount] = useState(""); const [enteredDate, setEnteredDate] = useState(""); const titleChangeHandler = (event) => { setEnteredTitle(event.target.value); }; const amountChangeHandler = (event) = { setEnteredAmount(event.target.value); }; const dateChangeHandler = (event) = { setEnteredDate(event.target.value); }; Here is the screenshot. Please Help! A: You forgot to add => (arrow) in your function syntax.
My function is not running due to VScode deprecation-warning
I was doing a React Project. But the Code seems to be an argument in a function. And it is showing as deprecated in VSCode. import React, { useState } from "react"; import "./ExpenseForm.css"; const ExpenseForm = () => { const [enteredTitle, setEnteredTitle] = useState(""); const [enteredAmount, setEnteredAmount] = useState(""); const [enteredDate, setEnteredDate] = useState(""); const titleChangeHandler = (event) => { setEnteredTitle(event.target.value); }; const amountChangeHandler = (event) = { setEnteredAmount(event.target.value); }; const dateChangeHandler = (event) = { setEnteredDate(event.target.value); }; Here is the screenshot. Please Help!
[ "You forgot to add => (arrow) in your function syntax.\n" ]
[ 1 ]
[]
[]
[ "deprecation_warning", "jsx", "reactjs", "visual_studio_code" ]
stackoverflow_0074680477_deprecation_warning_jsx_reactjs_visual_studio_code.txt
Q: Read Outlook inbox with oauth2 authentication - error NO AUTHENTICATE failed I'm trying to connect with node imap library to a Outlook email inbox. Outlook need oauth2 authentication, this is my code that try to connect to IMAP server with oauth2 token retrieved by msal library. I followed this guide: https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth async function getMSToken(){ let msalConfig = { auth: { clientId: "1cf7d7ff-*****************", authority: "https://login.microsoftonline.com/880c05e3-*****************", clientSecret: "azQ8Q~eU.*****************", } }; const cca = new msal.ConfidentialClientApplication(msalConfig); let tokenRequest = { scopes: [ "https://graph.microsoft.com/.default" ], }; let { accessToken } = await cca.acquireTokenByClientCredential(tokenRequest); console.log("accessToken", accessToken); let user = "*****************@*****************"; return btoa('user=' + user + '^Aauth=Bearer ' + accessToken + '^A^A'); } async function connect(){ let token = await getMSToken(); console.log("tokenConverted", token); imap = new Imap({ xoauth2: token, host: 'outlook.office365.com', port: 993, tls: true, debug: console.log }); imap.once("ready", () => { console.log("connected"); }); imap.once("error", function(err) { console.error("Error connecting", err); }); console.log("connecting..."); imap.connect(); } The msal library return me an access token but when i tried to connect to IMAP server, this is the log of connection: <= '* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADUAUABSADAANwAwADEAQwBBADAAMAAyADQALgBlAHUAcgBwAHIAZAAwADcALgBwAHIAbwBkAC4AbwB1AHQAbABvAG8AawAuAGMAbwBtAA==]' => 'A0 CAPABILITY' <= '* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+' <= 'A0 OK CAPABILITY completed.' => 'A1 AUTHENTICATE XOAUTH2 ***********************' <= 'A1 NO AUTHENTICATE failed.' And these are the permissions on tenant: If I try the scope https://outlook.office365.com/IMAP.AccessAsUser.All the response from msal library it's: 1002012 - [2022-10-24 14:46:27Z]: AADSTS1002012: The provided value for scope https://outlook.office365.com/IMAP.AccessAsUser.All is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).\r\n What can I try? Thank you! A: it's little tricky (setting up OAUTH2 authentication on IMAP in our Azure AAD instance), but following https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth very carefully it should work. I guess you can try with scope "https://outlook.office365.com/.default" I don't know much about Node but I can share an example using JAVA running with that scope (https://github.com/victorgv/dev-notes/tree/main/Using%20IMAP%20with%20OAuth%202%20authenticate%20and%20Office%20365).
Read Outlook inbox with oauth2 authentication - error NO AUTHENTICATE failed
I'm trying to connect with node imap library to a Outlook email inbox. Outlook need oauth2 authentication, this is my code that try to connect to IMAP server with oauth2 token retrieved by msal library. I followed this guide: https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth async function getMSToken(){ let msalConfig = { auth: { clientId: "1cf7d7ff-*****************", authority: "https://login.microsoftonline.com/880c05e3-*****************", clientSecret: "azQ8Q~eU.*****************", } }; const cca = new msal.ConfidentialClientApplication(msalConfig); let tokenRequest = { scopes: [ "https://graph.microsoft.com/.default" ], }; let { accessToken } = await cca.acquireTokenByClientCredential(tokenRequest); console.log("accessToken", accessToken); let user = "*****************@*****************"; return btoa('user=' + user + '^Aauth=Bearer ' + accessToken + '^A^A'); } async function connect(){ let token = await getMSToken(); console.log("tokenConverted", token); imap = new Imap({ xoauth2: token, host: 'outlook.office365.com', port: 993, tls: true, debug: console.log }); imap.once("ready", () => { console.log("connected"); }); imap.once("error", function(err) { console.error("Error connecting", err); }); console.log("connecting..."); imap.connect(); } The msal library return me an access token but when i tried to connect to IMAP server, this is the log of connection: <= '* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADUAUABSADAANwAwADEAQwBBADAAMAAyADQALgBlAHUAcgBwAHIAZAAwADcALgBwAHIAbwBkAC4AbwB1AHQAbABvAG8AawAuAGMAbwBtAA==]' => 'A0 CAPABILITY' <= '* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+' <= 'A0 OK CAPABILITY completed.' => 'A1 AUTHENTICATE XOAUTH2 ***********************' <= 'A1 NO AUTHENTICATE failed.' And these are the permissions on tenant: If I try the scope https://outlook.office365.com/IMAP.AccessAsUser.All the response from msal library it's: 1002012 - [2022-10-24 14:46:27Z]: AADSTS1002012: The provided value for scope https://outlook.office365.com/IMAP.AccessAsUser.All is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).\r\n What can I try? Thank you!
[ "it's little tricky (setting up OAUTH2 authentication on IMAP in our Azure AAD instance), but following https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth very carefully it should work.\nI guess you can try with scope \"https://outlook.office365.com/.default\"\nI don't know much about Node but I can share an example using JAVA running with that scope (https://github.com/victorgv/dev-notes/tree/main/Using%20IMAP%20with%20OAuth%202%20authenticate%20and%20Office%20365).\n" ]
[ 0 ]
[]
[]
[ "node.js", "oauth_2.0", "outlook" ]
stackoverflow_0074182663_node.js_oauth_2.0_outlook.txt
Q: lambda function returning a list of None elements does anyone know why the function fill the list with "None"? I can not find the problem, everything looks true. my_lis = [] l = lambda m : [my_lis.append(x) for x in range(m)] l(10) output : [None, None, None, None, None, None, None, None, None, None] if i print the x instead of append, i get 1 to 10 and the None list at the end. anyway I'm trying to get a list of numbers by this way A: A simple list comprehension lst = [i**2 for i in range(3)] is interpreted as: lst = [] for i in range(3): lst.append(i**2) Now back to your example: So your code is currently like this: my_lis = [] def l(m): result = [] for x in range(m): result.append(my_lis.append(x)) return result print(l(10)) # [None, None, None, None, None, None, None, None, None, None] print(my_lis) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] So basically you're filling the my_lis when you call my_lis.append(), but .append() is an in-place method, It just adds item to the list but its return value is None and you're filling result with Nones. Indeed result is the what list comprehension hands you after-all. As per request in comment: You basically don't need extra my_lis list. The list comprehension inside the lambda gives you the final result, so: l = lambda m: [x for x in range(m)] print(l(10)) Now [x for x in range(m)] is pointless and slower here, You can directly call list on range(m): l = lambda m: list(range(m)) print(l(10))
lambda function returning a list of None elements
does anyone know why the function fill the list with "None"? I can not find the problem, everything looks true. my_lis = [] l = lambda m : [my_lis.append(x) for x in range(m)] l(10) output : [None, None, None, None, None, None, None, None, None, None] if i print the x instead of append, i get 1 to 10 and the None list at the end. anyway I'm trying to get a list of numbers by this way
[ "A simple list comprehension\nlst = [i**2 for i in range(3)]\n\nis interpreted as:\nlst = []\nfor i in range(3):\n lst.append(i**2)\n\nNow back to your example: So your code is currently like this:\nmy_lis = []\n\ndef l(m):\n result = []\n for x in range(m):\n result.append(my_lis.append(x))\n return result\n\n\nprint(l(10)) # [None, None, None, None, None, None, None, None, None, None]\nprint(my_lis) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nSo basically you're filling the my_lis when you call my_lis.append(), but .append() is an in-place method, It just adds item to the list but its return value is None and you're filling result with Nones. Indeed result is the what list comprehension hands you after-all.\n\nAs per request in comment:\nYou basically don't need extra my_lis list. The list comprehension inside the lambda gives you the final result, so:\nl = lambda m: [x for x in range(m)]\nprint(l(10))\n\nNow [x for x in range(m)] is pointless and slower here, You can directly call list on range(m):\nl = lambda m: list(range(m))\nprint(l(10))\n\n" ]
[ 2 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0074680509_lambda_python.txt
Q: flutter web : The difference between the local version and the version when uploading to the server My application, when I test the debug version, shows the products and all things coming from the server, while when I upload the version to the server, the products or anything coming from the server that needs the Internet does not appear. I will attach pictures to you while testing a version. Local and when I upload the copy on the site. A: My best guess is that this is a CORS issue. To fix the CORS error on the server so that images can be displayed on Flutter web, you will need to add the appropriate CORS headers to your server. This can typically be done by adding a CORS middleware to your server code. For example, if you are using Express.js as your server framework, you can use the cors package to easily add CORS support. Here is an example of how to do this: const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); // Add your other server code here app.listen(3000, () => { console.log('Server listening on port 3000'); }); Once you have added the CORS middleware to your server, you should be able to load images from your server in your Flutter web app without encountering CORS errors. Note that you will need to configure the CORS middleware to allow requests from the domains that your Flutter web app will be running on. You can use the cors package's origin option to do this, as shown in the following example: app.use(cors({ origin: ['http://localhost:8080', 'https://my-flutter-web-app.com'] })); This will allow requests from the domains http://localhost:8080 and https://my-flutter-web-app.com to access your server. You can add as many domains as you need to the origin option, or use a wildcard (e.g. '*') to allow requests from all domains.
flutter web : The difference between the local version and the version when uploading to the server
My application, when I test the debug version, shows the products and all things coming from the server, while when I upload the version to the server, the products or anything coming from the server that needs the Internet does not appear. I will attach pictures to you while testing a version. Local and when I upload the copy on the site.
[ "My best guess is that this is a CORS issue.\nTo fix the CORS error on the server so that images can be displayed on Flutter web, you will need to add the appropriate CORS headers to your server. This can typically be done by adding a CORS middleware to your server code.\nFor example, if you are using Express.js as your server framework, you can use the cors package to easily add CORS support. Here is an example of how to do this:\nconst express = require('express');\nconst cors = require('cors');\n\nconst app = express();\n\napp.use(cors());\n\n// Add your other server code here\n\napp.listen(3000, () => {\n console.log('Server listening on port 3000');\n});\n\nOnce you have added the CORS middleware to your server, you should be able to load images from your server in your Flutter web app without encountering CORS errors.\nNote that you will need to configure the CORS middleware to allow requests from the domains that your Flutter web app will be running on. You can use the cors package's origin option to do this, as shown in the following example:\napp.use(cors({\n origin: ['http://localhost:8080', 'https://my-flutter-web-app.com']\n}));\n\nThis will allow requests from the domains http://localhost:8080 and https://my-flutter-web-app.com to access your server. You can add as many domains as you need to the origin option, or use a wildcard (e.g. '*') to allow requests from all domains.\n" ]
[ 0 ]
[]
[]
[ "dart", "flutter", "flutter_web" ]
stackoverflow_0074665473_dart_flutter_flutter_web.txt
Q: TypeScript list iteration inside return statement I am new at React-TypeScript and want to make a visual list of Publisher type of objects which should look like this: the screenshot of my javascript code which can list my objects properly inside return statement This is my return statement which is coded using TypeScript but does not working. It does not give any error but gives full white screen. return ( <div> <input type="text" placeholder='Name' className='input_box' onChange={(i) => searchFor(i)} /> <div className="container" > {publishers.map((publisher:Publisher) => <Card border="secondary" style={{ width: '18rem', maxWidth: 'auto', height: 'auto', maxHeight: 'auto', margin: 15, background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)' }}> <Card.Img style={{ width: "auto", maxHeight: "200px", padding: '5px' }} variant="top" src={img}/> <Card.Body> <Card.Title key="{publisher_name}">{publisher.name}</Card.Title> <ListGroup variant="flush" style={{ listStyle: 'none'}}> <ListGroup.Item key="{website}">{publisher.website}</ListGroup.Item> <ListGroup.Item key="{phone}">{publisher.phone}</ListGroup.Item> <ListGroup.Item key="{address}">{publisher.address}</ListGroup.Item> </ListGroup> </Card.Body> </Card> ) } </div> </div> ); I am pretty sure that publishers is not empty because I tried this kind of code in javascript file and took the screenshot above. Can you please help me how can I list my objects inside this return statement? I also tried foreach but it also was not successfull. Note: You may need to see my Publisher class. Here it is: export class Publisher { name: string = ""; website: string = ""; phone: string = ""; address: string = ""; constructor(initializer?: any) { if (!initializer) return; if (initializer.name) this.name = initializer.name; if (initializer.website) this.website = initializer.website; if (initializer.phone) this.phone = initializer.phone; if (initializer.address) this.address = initializer.address; } } A: You are using the key attribute on the ListGroup.Item elements in your code, but you are not providing a unique value for each key. It cause React component to render incorrectly, showing a blank screen. return ( <div> <input type="text" placeholder="Name" className="input_box" onChange={(i) => searchFor(i)} /> <div className="container"> {publishers.map((publisher: Publisher) => ( <Card border="secondary" style={{ width: "18rem", maxWidth: "auto", height: "auto", maxHeight: "auto", margin: 15, background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)", }} > <Card.Img style={{ width: "auto", maxHeight: "200px", padding: "5px" }} variant="top" src={img} /> <Card.Body> <Card.Title key={publisher.name}>{publisher.name}</Card.Title> <ListGroup variant="flush" style={{ listStyle: "none" }}> <ListGroup.Item key={`${publisher.name}-website`}> {publisher.website} </ListGroup.Item> <ListGroup.Item key={`${publisher.name}-phone`}> {publisher.phone} </ListGroup.Item> <ListGroup.Item key={`${publisher.name}-address`}> {publisher.address} </ListGroup.Item> </ListGroup> </Card.Body> </Card> ))} </div> </div> );
TypeScript list iteration inside return statement
I am new at React-TypeScript and want to make a visual list of Publisher type of objects which should look like this: the screenshot of my javascript code which can list my objects properly inside return statement This is my return statement which is coded using TypeScript but does not working. It does not give any error but gives full white screen. return ( <div> <input type="text" placeholder='Name' className='input_box' onChange={(i) => searchFor(i)} /> <div className="container" > {publishers.map((publisher:Publisher) => <Card border="secondary" style={{ width: '18rem', maxWidth: 'auto', height: 'auto', maxHeight: 'auto', margin: 15, background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)' }}> <Card.Img style={{ width: "auto", maxHeight: "200px", padding: '5px' }} variant="top" src={img}/> <Card.Body> <Card.Title key="{publisher_name}">{publisher.name}</Card.Title> <ListGroup variant="flush" style={{ listStyle: 'none'}}> <ListGroup.Item key="{website}">{publisher.website}</ListGroup.Item> <ListGroup.Item key="{phone}">{publisher.phone}</ListGroup.Item> <ListGroup.Item key="{address}">{publisher.address}</ListGroup.Item> </ListGroup> </Card.Body> </Card> ) } </div> </div> ); I am pretty sure that publishers is not empty because I tried this kind of code in javascript file and took the screenshot above. Can you please help me how can I list my objects inside this return statement? I also tried foreach but it also was not successfull. Note: You may need to see my Publisher class. Here it is: export class Publisher { name: string = ""; website: string = ""; phone: string = ""; address: string = ""; constructor(initializer?: any) { if (!initializer) return; if (initializer.name) this.name = initializer.name; if (initializer.website) this.website = initializer.website; if (initializer.phone) this.phone = initializer.phone; if (initializer.address) this.address = initializer.address; } }
[ "You are using the key attribute on the ListGroup.Item elements in your code, but you are not providing a unique value for each key. It cause React component to render incorrectly, showing a blank screen.\nreturn (\n <div>\n <input type=\"text\" placeholder=\"Name\" className=\"input_box\" onChange={(i) => searchFor(i)} />\n <div className=\"container\">\n {publishers.map((publisher: Publisher) => (\n <Card\n border=\"secondary\"\n style={{\n width: \"18rem\",\n maxWidth: \"auto\",\n height: \"auto\",\n maxHeight: \"auto\",\n margin: 15,\n background: \"linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)\",\n }}\n >\n <Card.Img\n style={{ width: \"auto\", maxHeight: \"200px\", padding: \"5px\" }}\n variant=\"top\"\n src={img}\n />\n <Card.Body>\n <Card.Title key={publisher.name}>{publisher.name}</Card.Title>\n <ListGroup variant=\"flush\" style={{ listStyle: \"none\" }}>\n <ListGroup.Item key={`${publisher.name}-website`}>\n {publisher.website}\n </ListGroup.Item>\n <ListGroup.Item key={`${publisher.name}-phone`}>\n {publisher.phone}\n </ListGroup.Item>\n <ListGroup.Item key={`${publisher.name}-address`}>\n {publisher.address}\n </ListGroup.Item>\n </ListGroup>\n </Card.Body>\n </Card>\n ))}\n </div>\n </div>\n);\n\n" ]
[ 1 ]
[]
[]
[ "iteration", "react_typescript", "tsx", "typescript" ]
stackoverflow_0074680508_iteration_react_typescript_tsx_typescript.txt
Q: Python webscraping problem - arrays length I scrape daily courses from the website tatrabanka.sk. They recently updated the website and my script returns the following error. How can I handle that? Do I need to use bs4 and classically download the entire website? Thanks for any advice. import pandas as pd import numpy as np from datetime import datetime tmp_url = "https://www.tatrabanka.sk/rest/tatra/exchange/list/20.11.2022-00:00" pd.read_json(tmp_url) Output: ... ValueError: All arrays must be of the same length Full script: dr = pd.date_range(start = datetime.today().strftime('%m/%d/%Y'), end = datetime.today().strftime('%m/%d/%Y'), freq = '1440min') df_date = pd.to_datetime(dr, format = '%Y-%m-%d').strftime('%d.%m.%Y') df_date = df_date + '-00:00' url_list = 'https://www.tatrabanka.sk/rest/tatra/exchange/list/' + df_date smbl = ["USD", "PLN", "HUF", "CZK", "HRK", "RON"] data = [] tmp_url = "https://www.tatrabanka.sk/rest/tatra/exchange/list/20.11.2022-00:00" pd.read_json(tmp_url) for urls in url_list: print(urls) dft = pd.read_json(urls) dft['DateReal'] = urls[51:61] data.append(dft.loc[dft["feCycd"].isin(smbl)]) out_df = pd.concat(data) A: To load the Json into a dataframe try: import requests import pandas as pd tmp_url = "https://www.tatrabanka.sk/rest/tatra/exchange/list/20.11.2022-00:00" data = requests.get(tmp_url).json() df = pd.DataFrame(data["rates"]) print(df) Prints: id feDate feCntr feCycd feAmnt feDnrt feDprt feDsrt feVnrt feVprt feVsrt feLccy rateListId status formattedDate translatedCountry translatedCode flag 0 198 1668985200000 Austrália AUD 1 1.5868 1.5094 1.5481 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Austrália AUD /templates/tatrabanka/assets/img/flags/au.svg 1 195 1668985200000 Česká republika CZK 1 24.9790 23.7610 24.3700 25.2230 23.5170 24.3700 EUR 10212 1 21.11.2022 00:00 Česká republika CZK /templates/tatrabanka/assets/img/flags/cz.svg 2 192 1668985200000 Chorvátsko HRK 1 7.7152 7.3388 7.5270 7.9034 7.1506 7.5270 EUR 10212 0 21.11.2022 00:00 Chorvátsko HRK /templates/tatrabanka/assets/img/flags/hr.svg 3 194 1668985200000 Dánsko DKK 1 7.6243 7.2523 7.4383 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Dánsko DKK /templates/tatrabanka/assets/img/flags/dk.svg 4 190 1668985200000 Japonsko JPY 1 148.2400 141.0000 144.6200 0.0000 0.0000 0.0000 EUR 10212 0 21.11.2022 00:00 Japonsko JPY /templates/tatrabanka/assets/img/flags/jp.svg 5 181 1668985200000 Južná Afrika ZAR 1 18.3326 17.4384 17.8855 0.0000 0.0000 0.0000 EUR 10212 0 21.11.2022 00:00 Južná Afrika ZAR /templates/tatrabanka/assets/img/flags/za.svg 6 197 1668985200000 Kanada CAD 1 1.4193 1.3501 1.3847 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Kanada CAD /templates/tatrabanka/assets/img/flags/ca.svg 7 191 1668985200000 Maďarsko HUF 1 417.0600 396.7200 406.8900 427.2300 386.5500 406.8900 EUR 10212 0 21.11.2022 00:00 Maďarsko HUF /templates/tatrabanka/assets/img/flags/hu.svg 8 189 1668985200000 Nórsko NOK 1 10.7917 10.2653 10.5285 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Nórsko NOK /templates/tatrabanka/assets/img/flags/no.svg 9 188 1668985200000 Poľsko PLN 1 4.8218 4.5866 4.7042 4.9394 4.4690 4.7042 EUR 10212 1 21.11.2022 00:00 Poľsko PLN /templates/tatrabanka/assets/img/flags/pl.svg 10 187 1668985200000 Rumunsko RON 1 5.0632 4.8162 4.9397 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Rumunsko RON /templates/tatrabanka/assets/img/flags/ro.svg 11 196 1668985200000 Švajčiarsko CHF 1 1.0108 0.9614 0.9861 1.0206 0.9516 0.9861 EUR 10212 1 21.11.2022 00:00 Švajčiarsko CHF /templates/tatrabanka/assets/img/flags/ch.svg 12 185 1668985200000 Švédsko SEK 1 11.2559 10.7069 10.9814 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Švédsko SEK /templates/tatrabanka/assets/img/flags/se.svg 13 184 1668985200000 Turecko TRY 1 20.2097 18.2849 19.2473 0.0000 0.0000 0.0000 EUR 10212 0 21.11.2022 00:00 Turecko TRY /templates/tatrabanka/assets/img/flags/tr.svg 14 182 1668985200000 USA USD 1 1.0593 1.0025 1.0335 1.0697 0.9973 1.0335 EUR 10212 0 21.11.2022 00:00 USA USD /templates/tatrabanka/assets/img/flags/us.svg 15 193 1668985200000 V. Británia GBP 1 0.8910 0.8476 0.8693 0.9084 0.8302 0.8693 EUR 10212 0 21.11.2022 00:00 Veľká Británia GBP /templates/tatrabanka/assets/img/flags/gb.svg To filter the dataframe: smbl = ["USD", "PLN", "HUF", "CZK", "HRK", "RON"] df = df[df["feCycd"].isin(smbl)] print(df) Prints: id feDate feCntr feCycd feAmnt feDnrt feDprt feDsrt feVnrt feVprt feVsrt feLccy rateListId status formattedDate translatedCountry translatedCode flag 1 195 1668985200000 Česká republika CZK 1 24.9790 23.7610 24.3700 25.2230 23.5170 24.3700 EUR 10212 1 21.11.2022 00:00 Česká republika CZK /templates/tatrabanka/assets/img/flags/cz.svg 2 192 1668985200000 Chorvátsko HRK 1 7.7152 7.3388 7.5270 7.9034 7.1506 7.5270 EUR 10212 0 21.11.2022 00:00 Chorvátsko HRK /templates/tatrabanka/assets/img/flags/hr.svg 7 191 1668985200000 Maďarsko HUF 1 417.0600 396.7200 406.8900 427.2300 386.5500 406.8900 EUR 10212 0 21.11.2022 00:00 Maďarsko HUF /templates/tatrabanka/assets/img/flags/hu.svg 9 188 1668985200000 Poľsko PLN 1 4.8218 4.5866 4.7042 4.9394 4.4690 4.7042 EUR 10212 1 21.11.2022 00:00 Poľsko PLN /templates/tatrabanka/assets/img/flags/pl.svg 10 187 1668985200000 Rumunsko RON 1 5.0632 4.8162 4.9397 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Rumunsko RON /templates/tatrabanka/assets/img/flags/ro.svg 14 182 1668985200000 USA USD 1 1.0593 1.0025 1.0335 1.0697 0.9973 1.0335 EUR 10212 0 21.11.2022 00:00 USA USD /templates/tatrabanka/assets/img/flags/us.svg
Python webscraping problem - arrays length
I scrape daily courses from the website tatrabanka.sk. They recently updated the website and my script returns the following error. How can I handle that? Do I need to use bs4 and classically download the entire website? Thanks for any advice. import pandas as pd import numpy as np from datetime import datetime tmp_url = "https://www.tatrabanka.sk/rest/tatra/exchange/list/20.11.2022-00:00" pd.read_json(tmp_url) Output: ... ValueError: All arrays must be of the same length Full script: dr = pd.date_range(start = datetime.today().strftime('%m/%d/%Y'), end = datetime.today().strftime('%m/%d/%Y'), freq = '1440min') df_date = pd.to_datetime(dr, format = '%Y-%m-%d').strftime('%d.%m.%Y') df_date = df_date + '-00:00' url_list = 'https://www.tatrabanka.sk/rest/tatra/exchange/list/' + df_date smbl = ["USD", "PLN", "HUF", "CZK", "HRK", "RON"] data = [] tmp_url = "https://www.tatrabanka.sk/rest/tatra/exchange/list/20.11.2022-00:00" pd.read_json(tmp_url) for urls in url_list: print(urls) dft = pd.read_json(urls) dft['DateReal'] = urls[51:61] data.append(dft.loc[dft["feCycd"].isin(smbl)]) out_df = pd.concat(data)
[ "To load the Json into a dataframe try:\nimport requests\nimport pandas as pd\n\ntmp_url = \"https://www.tatrabanka.sk/rest/tatra/exchange/list/20.11.2022-00:00\"\n\ndata = requests.get(tmp_url).json()\ndf = pd.DataFrame(data[\"rates\"])\nprint(df)\n\nPrints:\n id feDate feCntr feCycd feAmnt feDnrt feDprt feDsrt feVnrt feVprt feVsrt feLccy rateListId status formattedDate translatedCountry translatedCode flag\n0 198 1668985200000 Austrália AUD 1 1.5868 1.5094 1.5481 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Austrália AUD /templates/tatrabanka/assets/img/flags/au.svg\n1 195 1668985200000 Česká republika CZK 1 24.9790 23.7610 24.3700 25.2230 23.5170 24.3700 EUR 10212 1 21.11.2022 00:00 Česká republika CZK /templates/tatrabanka/assets/img/flags/cz.svg\n2 192 1668985200000 Chorvátsko HRK 1 7.7152 7.3388 7.5270 7.9034 7.1506 7.5270 EUR 10212 0 21.11.2022 00:00 Chorvátsko HRK /templates/tatrabanka/assets/img/flags/hr.svg\n3 194 1668985200000 Dánsko DKK 1 7.6243 7.2523 7.4383 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Dánsko DKK /templates/tatrabanka/assets/img/flags/dk.svg\n4 190 1668985200000 Japonsko JPY 1 148.2400 141.0000 144.6200 0.0000 0.0000 0.0000 EUR 10212 0 21.11.2022 00:00 Japonsko JPY /templates/tatrabanka/assets/img/flags/jp.svg\n5 181 1668985200000 Južná Afrika ZAR 1 18.3326 17.4384 17.8855 0.0000 0.0000 0.0000 EUR 10212 0 21.11.2022 00:00 Južná Afrika ZAR /templates/tatrabanka/assets/img/flags/za.svg\n6 197 1668985200000 Kanada CAD 1 1.4193 1.3501 1.3847 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Kanada CAD /templates/tatrabanka/assets/img/flags/ca.svg\n7 191 1668985200000 Maďarsko HUF 1 417.0600 396.7200 406.8900 427.2300 386.5500 406.8900 EUR 10212 0 21.11.2022 00:00 Maďarsko HUF /templates/tatrabanka/assets/img/flags/hu.svg\n8 189 1668985200000 Nórsko NOK 1 10.7917 10.2653 10.5285 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Nórsko NOK /templates/tatrabanka/assets/img/flags/no.svg\n9 188 1668985200000 Poľsko PLN 1 4.8218 4.5866 4.7042 4.9394 4.4690 4.7042 EUR 10212 1 21.11.2022 00:00 Poľsko PLN /templates/tatrabanka/assets/img/flags/pl.svg\n10 187 1668985200000 Rumunsko RON 1 5.0632 4.8162 4.9397 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Rumunsko RON /templates/tatrabanka/assets/img/flags/ro.svg\n11 196 1668985200000 Švajčiarsko CHF 1 1.0108 0.9614 0.9861 1.0206 0.9516 0.9861 EUR 10212 1 21.11.2022 00:00 Švajčiarsko CHF /templates/tatrabanka/assets/img/flags/ch.svg\n12 185 1668985200000 Švédsko SEK 1 11.2559 10.7069 10.9814 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Švédsko SEK /templates/tatrabanka/assets/img/flags/se.svg\n13 184 1668985200000 Turecko TRY 1 20.2097 18.2849 19.2473 0.0000 0.0000 0.0000 EUR 10212 0 21.11.2022 00:00 Turecko TRY /templates/tatrabanka/assets/img/flags/tr.svg\n14 182 1668985200000 USA USD 1 1.0593 1.0025 1.0335 1.0697 0.9973 1.0335 EUR 10212 0 21.11.2022 00:00 USA USD /templates/tatrabanka/assets/img/flags/us.svg\n15 193 1668985200000 V. Británia GBP 1 0.8910 0.8476 0.8693 0.9084 0.8302 0.8693 EUR 10212 0 21.11.2022 00:00 Veľká Británia GBP /templates/tatrabanka/assets/img/flags/gb.svg\n\n\nTo filter the dataframe:\nsmbl = [\"USD\", \"PLN\", \"HUF\", \"CZK\", \"HRK\", \"RON\"]\ndf = df[df[\"feCycd\"].isin(smbl)]\nprint(df)\n\nPrints:\n id feDate feCntr feCycd feAmnt feDnrt feDprt feDsrt feVnrt feVprt feVsrt feLccy rateListId status formattedDate translatedCountry translatedCode flag\n1 195 1668985200000 Česká republika CZK 1 24.9790 23.7610 24.3700 25.2230 23.5170 24.3700 EUR 10212 1 21.11.2022 00:00 Česká republika CZK /templates/tatrabanka/assets/img/flags/cz.svg\n2 192 1668985200000 Chorvátsko HRK 1 7.7152 7.3388 7.5270 7.9034 7.1506 7.5270 EUR 10212 0 21.11.2022 00:00 Chorvátsko HRK /templates/tatrabanka/assets/img/flags/hr.svg\n7 191 1668985200000 Maďarsko HUF 1 417.0600 396.7200 406.8900 427.2300 386.5500 406.8900 EUR 10212 0 21.11.2022 00:00 Maďarsko HUF /templates/tatrabanka/assets/img/flags/hu.svg\n9 188 1668985200000 Poľsko PLN 1 4.8218 4.5866 4.7042 4.9394 4.4690 4.7042 EUR 10212 1 21.11.2022 00:00 Poľsko PLN /templates/tatrabanka/assets/img/flags/pl.svg\n10 187 1668985200000 Rumunsko RON 1 5.0632 4.8162 4.9397 0.0000 0.0000 0.0000 EUR 10212 1 21.11.2022 00:00 Rumunsko RON /templates/tatrabanka/assets/img/flags/ro.svg\n14 182 1668985200000 USA USD 1 1.0593 1.0025 1.0335 1.0697 0.9973 1.0335 EUR 10212 0 21.11.2022 00:00 USA USD /templates/tatrabanka/assets/img/flags/us.svg\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python_3.x", "web_scraping" ]
stackoverflow_0074680506_pandas_python_3.x_web_scraping.txt
Q: robobrowser won't change cookies I have a POST request sent to server from robobrowser, and the server responds with no data. The response headers are as follows (this is the response from Chrome browser and it's the way it supposed to be): Cache-Control:no-cache, no-store, must-revalidate Content-Length:335 Content-Type:application/json; charset=utf-8 Date:Wed, 02 Aug 2017 17:01:17 GMT Expires:-1 lg:2673 Pragma:no-cache Server:Unknown Set-Cookie:BrandingUserLocationGroupID=ic4DUh/NXVp8VOKAtyDgbA==; expires=Fri, 01-Sep-2017 17:01:16 GMT; path=/; secure; HttpOnly Set-Cookie:.AIRWATCHAUTH=A69C1A5EE8A5F3626385F35DA1B104EE7DFF5E5AF549DDB02EE8ED53931A0585C0FBB8299E3FC7B428A982B9826EF68390E659F4A74DCE00E195601F400D6E69F53907DADED4194F32DD08A72BA212DCCD0D23AB7C5BD56171E6C55EF1BE90849E9C81B2DAE23B05CA6E361326F44604; expires=Thu, 03-Aug-2017 17:01:17 GMT; path=/; secure; HttpOnly Strict-Transport-Security:max-age=31536000;includeSubDomains user:5679 X-Content-Type-Options:nosniff x-download-options:noopen x-frame-options:SAMEORIGIN X-XSS-Protection:1; mode=block it looks like server is resetting cookies, but my robobrowser instance does not respond/refresh to new cookies. basically, the website is trying to switch sessions/change cookies I think, but my python robobrowser does not reflect that or does not allow it to change for some reason Here is my POST request and response: browser=RoboBrowser() browser.session.headers['X-Requested-With']='XMLHttpRequest' browser.open('https://example.com/test/Users/set-role?id='+role_id+'&__RequestVerificationToken='+token,method='POST') print browser.response.content This gives me the following error message: {"RedirectUrl":null,"IsSuccess":false,"Message":"Save Failed","CustomMessage":null,"Errors":[{"Key":"","Value":["An error has occurred. This error has automatically been saved for further analysis. Please contact technical support."]}],"Messages":{},"HasView":false,"ViewHtml":null,"ViewUrl":null,"IsValidationException":false,"IsValidationWarning":false,"ReloadPage":false,"IsSessionExpired":false,"Script":null,"NextWizardUrl":null,"PreviousWizardUrl":null,"ShowDialog":false} Does anyone know how to get robobrowser to respond to new cookies? Added screenshot of cookie from Developer Tools in Chrome. The red box highlighted is where the change occurs once the link is clicked. A: You can use the update_state() method and pass in the new cookies that were set in the server response. For example: browser=RoboBrowser() browser.session.headers['X-Requested-With']='XMLHttpRequest' browser.open('https://example.com/test/Users/set-role?id='+role_id+'&__RequestVerificationToken='+token,method='POST') # Update cookies with new values from the server response browser.cookies = browser.response.cookies print browser.response.content Alternatively, you can use the open() method again with the same URL to automatically update the cookies with the new values from the server response. browser=RoboBrowser() browser.session.headers['X-Requested-With']='XMLHttpRequest' browser.open('https://example.com/test/Users/set-role?id='+role_id+'&__RequestVerificationToken='+token,method='POST') # Open the same URL again to update cookies with new values browser.open('https://example.com/test/Users/set-role?id='+role_id+'&__RequestVerificationToken='+token,method='POST') print browser.response.content You can also use the cookies property of the RoboBrowser instance to manually access and update the cookies. browser=RoboBrowser() browser.session.headers['X-Requested-With']='XMLHttpRequest' browser.open('https://example.com/test/Users/set-role?id='+role_id+'&__RequestVerificationToken='+token,method='POST') # Update cookies with new values from the server response browser.cookies = browser.response.cookies print browser.response.content
robobrowser won't change cookies
I have a POST request sent to server from robobrowser, and the server responds with no data. The response headers are as follows (this is the response from Chrome browser and it's the way it supposed to be): Cache-Control:no-cache, no-store, must-revalidate Content-Length:335 Content-Type:application/json; charset=utf-8 Date:Wed, 02 Aug 2017 17:01:17 GMT Expires:-1 lg:2673 Pragma:no-cache Server:Unknown Set-Cookie:BrandingUserLocationGroupID=ic4DUh/NXVp8VOKAtyDgbA==; expires=Fri, 01-Sep-2017 17:01:16 GMT; path=/; secure; HttpOnly Set-Cookie:.AIRWATCHAUTH=A69C1A5EE8A5F3626385F35DA1B104EE7DFF5E5AF549DDB02EE8ED53931A0585C0FBB8299E3FC7B428A982B9826EF68390E659F4A74DCE00E195601F400D6E69F53907DADED4194F32DD08A72BA212DCCD0D23AB7C5BD56171E6C55EF1BE90849E9C81B2DAE23B05CA6E361326F44604; expires=Thu, 03-Aug-2017 17:01:17 GMT; path=/; secure; HttpOnly Strict-Transport-Security:max-age=31536000;includeSubDomains user:5679 X-Content-Type-Options:nosniff x-download-options:noopen x-frame-options:SAMEORIGIN X-XSS-Protection:1; mode=block it looks like server is resetting cookies, but my robobrowser instance does not respond/refresh to new cookies. basically, the website is trying to switch sessions/change cookies I think, but my python robobrowser does not reflect that or does not allow it to change for some reason Here is my POST request and response: browser=RoboBrowser() browser.session.headers['X-Requested-With']='XMLHttpRequest' browser.open('https://example.com/test/Users/set-role?id='+role_id+'&__RequestVerificationToken='+token,method='POST') print browser.response.content This gives me the following error message: {"RedirectUrl":null,"IsSuccess":false,"Message":"Save Failed","CustomMessage":null,"Errors":[{"Key":"","Value":["An error has occurred. This error has automatically been saved for further analysis. Please contact technical support."]}],"Messages":{},"HasView":false,"ViewHtml":null,"ViewUrl":null,"IsValidationException":false,"IsValidationWarning":false,"ReloadPage":false,"IsSessionExpired":false,"Script":null,"NextWizardUrl":null,"PreviousWizardUrl":null,"ShowDialog":false} Does anyone know how to get robobrowser to respond to new cookies? Added screenshot of cookie from Developer Tools in Chrome. The red box highlighted is where the change occurs once the link is clicked.
[ "You can use the update_state() method and pass in the new cookies that were set in the server response. \nFor example:\nbrowser=RoboBrowser()\nbrowser.session.headers['X-Requested-With']='XMLHttpRequest'\nbrowser.open('https://example.com/test/Users/set-role?id='+role_id+'&__RequestVerificationToken='+token,method='POST')\n\n# Update cookies with new values from the server response\nbrowser.cookies = browser.response.cookies\n\nprint browser.response.content\n\nAlternatively, you can use the open() method again with the same URL to automatically update the cookies with the new values from the server response.\nbrowser=RoboBrowser()\nbrowser.session.headers['X-Requested-With']='XMLHttpRequest'\nbrowser.open('https://example.com/test/Users/set-role?id='+role_id+'&__RequestVerificationToken='+token,method='POST')\n\n# Open the same URL again to update cookies with new values\nbrowser.open('https://example.com/test/Users/set-role?id='+role_id+'&__RequestVerificationToken='+token,method='POST')\n\nprint browser.response.content\n\nYou can also use the cookies property of the RoboBrowser instance to manually access and update the cookies.\nbrowser=RoboBrowser()\nbrowser.session.headers['X-Requested-With']='XMLHttpRequest'\nbrowser.open('https://example.com/test/Users/set-role?id='+role_id+'&__RequestVerificationToken='+token,method='POST')\n\n# Update cookies with new values from the server response\nbrowser.cookies = browser.response.cookies\n\nprint browser.response.content\n\n" ]
[ 0 ]
[]
[]
[ "http", "python", "python_2.7", "python_requests", "urllib2" ]
stackoverflow_0045467986_http_python_python_2.7_python_requests_urllib2.txt
Q: ReferenceError: TextEncoder is not defined when importing jsdom library I have these two files: test.js: const jsdom = require("jsdom"); const hello = () => { console.log("hello!"); }; module.exports = { hello }; and server.js: const hello = require('./stuff/test'); hello.hello(); directory structure: myprojectfolder backend src stuff test.js server.js When I run server.js I get the ReferenceError: TextEncoder is not defined error: /home/myusername/projects/myprojectfolder/node_modules/whatwg-url/lib/encoding.js:2 const utf8Encoder = new TextEncoder(); ^ ReferenceError: TextEncoder is not defined If I remove const jsdom = require("jsdom"); line from test.js, server.js runs fine and without any errors (outputs hello). Why does it happen and how do I fix it (while still being able to import and use jsdom inside test.js?). A: Well, it took me all day, but finally I managed to pull it together. My problem was that tests didn't run because of that error. So, in package.json under "scripts" I added the following: "test": "jest --verbose --runInBand --detectOpenHandles --forceExit" And in jest.config.js, I added the following: globals: { "ts-jest": { tsConfigFile: "tsconfig.json" }, TextEncoder: require("util").TextEncoder, TextDecoder: require("util").TextDecoder }
ReferenceError: TextEncoder is not defined when importing jsdom library
I have these two files: test.js: const jsdom = require("jsdom"); const hello = () => { console.log("hello!"); }; module.exports = { hello }; and server.js: const hello = require('./stuff/test'); hello.hello(); directory structure: myprojectfolder backend src stuff test.js server.js When I run server.js I get the ReferenceError: TextEncoder is not defined error: /home/myusername/projects/myprojectfolder/node_modules/whatwg-url/lib/encoding.js:2 const utf8Encoder = new TextEncoder(); ^ ReferenceError: TextEncoder is not defined If I remove const jsdom = require("jsdom"); line from test.js, server.js runs fine and without any errors (outputs hello). Why does it happen and how do I fix it (while still being able to import and use jsdom inside test.js?).
[ "Well, it took me all day, but finally I managed to pull it together.\nMy problem was that tests didn't run because of that error.\nSo, in package.json under \"scripts\" I added the following:\n\"test\": \"jest --verbose --runInBand --detectOpenHandles --forceExit\"\n\nAnd in jest.config.js, I added the following:\n globals: {\n \"ts-jest\": {\n tsConfigFile: \"tsconfig.json\"\n },\n TextEncoder: require(\"util\").TextEncoder,\n TextDecoder: require(\"util\").TextDecoder\n }\n\n" ]
[ 1 ]
[]
[]
[ "javascript", "jsdom", "node.js" ]
stackoverflow_0071163892_javascript_jsdom_node.js.txt
Q: What's the correct approach for having a list/detail view with React Native Navigation Bottom Tab? I have something like: const Tab = createBottomTabNavigator<DefaultTabbedParamList>(); const DefaultTabbedNavigation = () => { return ( <> <Tab.Navigator initialRouteName='Home' screenOptions={{ unmountOnBlur: true, }}> <Tab.Screen name="Home" component={HomeScreen} options={{ ...defaultOptions, tabBarIcon: ({ color, size, focused }) => ( <Icon as={Ionicons} name={`home${focused ? `` : `-outline`}`} size={size} color={color} /> ) }} /> ... </Tab.Navigator> </> ); } When a user clicks to a detail view from Home (or any other tab), I want to load a detail view with the currently selected tab remaining. What's the correct approach to handle this? One idea I had was to have a StackNavigator in HomeScreen that includes a Detail screen. But it seems repetitive to do for every screen, no? A: How about this? return ( <NavigationContainer> <Stack.Navigator screenOptions={{ headerShown: false }}> <Stack.Screen name={"Tabs"} component={Tabs} /> <Stack.Screen name={"Detail"} component={DetailScreen} /> </Stack.Navigator> </NavigationContainer> ); A: Yeah, you'll likely want to define a StackNavigator for each tab. It's a bit repetitive, but that's been a theme of my experience with RN. You can do something like: const HomeStackNavigator = () => { return ( <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} /> <Stack.Screen name="Detail" component={DetailScreen} /> </Stack.Navigator> ); }; const OtherStackNavigator = () => { return ( <Stack.Navigator> <Stack.Screen name="Other" component={OtherScreen} /> <Stack.Screen name="Detail" component={DetailScreen} /> </Stack.Navigator> ); }; const DefaultTabbedNavigation = () => { return ( <Tab.Navigator> <Tab.Screen name="Home" component={HomeStackNavigator} /> <Tab.Screen name="Other" component={OtherStackNavigator} /> </Tab.Navigator> ) }
What's the correct approach for having a list/detail view with React Native Navigation Bottom Tab?
I have something like: const Tab = createBottomTabNavigator<DefaultTabbedParamList>(); const DefaultTabbedNavigation = () => { return ( <> <Tab.Navigator initialRouteName='Home' screenOptions={{ unmountOnBlur: true, }}> <Tab.Screen name="Home" component={HomeScreen} options={{ ...defaultOptions, tabBarIcon: ({ color, size, focused }) => ( <Icon as={Ionicons} name={`home${focused ? `` : `-outline`}`} size={size} color={color} /> ) }} /> ... </Tab.Navigator> </> ); } When a user clicks to a detail view from Home (or any other tab), I want to load a detail view with the currently selected tab remaining. What's the correct approach to handle this? One idea I had was to have a StackNavigator in HomeScreen that includes a Detail screen. But it seems repetitive to do for every screen, no?
[ "How about this?\nreturn (\n <NavigationContainer>\n <Stack.Navigator screenOptions={{ headerShown: false }}>\n <Stack.Screen name={\"Tabs\"} component={Tabs} />\n <Stack.Screen name={\"Detail\"} component={DetailScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n\n", "Yeah, you'll likely want to define a StackNavigator for each tab. It's a bit repetitive, but that's been a theme of my experience with RN.\nYou can do something like:\nconst HomeStackNavigator = () => {\n return (\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Detail\" component={DetailScreen} />\n </Stack.Navigator>\n );\n};\n\nconst OtherStackNavigator = () => {\n return (\n <Stack.Navigator>\n <Stack.Screen name=\"Other\" component={OtherScreen} />\n <Stack.Screen name=\"Detail\" component={DetailScreen} />\n </Stack.Navigator>\n );\n};\n\nconst DefaultTabbedNavigation = () => {\n return (\n <Tab.Navigator>\n <Tab.Screen name=\"Home\" component={HomeStackNavigator} />\n <Tab.Screen name=\"Other\" component={OtherStackNavigator} />\n </Tab.Navigator>\n )\n}\n\n" ]
[ 1, 0 ]
[]
[]
[ "react_native", "react_native_navigation" ]
stackoverflow_0074536276_react_native_react_native_navigation.txt
Q: VueJs get json from file and wait for response I am new to VueJS with limited knowledge of Javascript, trying to do something I thought would be incredibly simple and commonplace. Here is a simplified version of the code that demonstrates the problem: export default { template: ` <br><br> testData: <br> {{ testData }} <br><br> <button @click="getData()">Get Data</button> `, data() { return { testData: [] } }, methods: { getData() { fetch('json.txt', {method: 'GET'}) .then(response => response.json()) .then((data) => { this.testData = data; }); this.doSomethingWithData() }, doSomethingWithData() { alert(this.testData[1]); } } } The json.txt file contains : ["one","two","three"] The problem here is that when you click the button, calling the getData() method, it doesn't do things in the order in the code, instead it gets the json data after doing everything else, causing this.testData[1] in the next method to return 'undefined' instead of 'two'. It is definitely getting the json data eventually because the {{ testData }} is updated successfully. This must be something to do with Javascript await, promise asynchronious somethingorother, which I have yet to learn about, but how do you get the code to wait for the data from the text file before proceeding to the next bit of code. (I have spent hours on StackOverflow and elsewhere trying many variations of the code above without success.) The equivalent in PHP is just this simple line of code: $testData = json_decode(file_get_contents('json.txt'), true); Many thanks in advance ! A: You should be able to just move this.doSomethingWithData() after this.testData = data; and will only be executed after data has been fetched, as JS will continue executing the function after the fetch and only wait for the finished variable for the code inside the .then() callbacks. An alternative way to do this, as you said, to use async and await. Vue allows any method to be an async method, so this is no problem. Your snippet could look like this then: async getData() { const response = await fetch('json.txt', { method: 'GET' }); const data = await response.json(); this.testData = data; this.doSomethingWithData(); } In this example, the getData() function is marked as async, which means it will return a promise. Inside the function, the await keyword is used to wait for the promise returned by fetch() to resolve before assigning the result to the response variable. Similarly, the await keyword is used to wait for the promise returned by response.json() to resolve before assigning the parsed JSON data to the data variable. Once the data has been fetched and parsed, it is assigned to this.testData and the doSomethingWithData() function is called.
VueJs get json from file and wait for response
I am new to VueJS with limited knowledge of Javascript, trying to do something I thought would be incredibly simple and commonplace. Here is a simplified version of the code that demonstrates the problem: export default { template: ` <br><br> testData: <br> {{ testData }} <br><br> <button @click="getData()">Get Data</button> `, data() { return { testData: [] } }, methods: { getData() { fetch('json.txt', {method: 'GET'}) .then(response => response.json()) .then((data) => { this.testData = data; }); this.doSomethingWithData() }, doSomethingWithData() { alert(this.testData[1]); } } } The json.txt file contains : ["one","two","three"] The problem here is that when you click the button, calling the getData() method, it doesn't do things in the order in the code, instead it gets the json data after doing everything else, causing this.testData[1] in the next method to return 'undefined' instead of 'two'. It is definitely getting the json data eventually because the {{ testData }} is updated successfully. This must be something to do with Javascript await, promise asynchronious somethingorother, which I have yet to learn about, but how do you get the code to wait for the data from the text file before proceeding to the next bit of code. (I have spent hours on StackOverflow and elsewhere trying many variations of the code above without success.) The equivalent in PHP is just this simple line of code: $testData = json_decode(file_get_contents('json.txt'), true); Many thanks in advance !
[ "You should be able to just move this.doSomethingWithData() after this.testData = data; and will only be executed after data has been fetched, as JS will continue executing the function after the fetch and only wait for the finished variable for the code inside the .then() callbacks.\nAn alternative way to do this, as you said, to use async and await. Vue allows any method to be an async method, so this is no problem.\nYour snippet could look like this then:\nasync getData() {\n const response = await fetch('json.txt', { method: 'GET' });\n const data = await response.json();\n this.testData = data;\n\n this.doSomethingWithData();\n}\n\nIn this example, the getData() function is marked as async, which means it will return a promise. Inside the function, the await keyword is used to wait for the promise returned by fetch() to resolve before assigning the result to the response variable. Similarly, the await keyword is used to wait for the promise returned by response.json() to resolve before assigning the parsed JSON data to the data variable. Once the data has been fetched and parsed, it is assigned to this.testData and the doSomethingWithData() function is called.\n" ]
[ 1 ]
[]
[]
[ "ajax", "javascript", "json", "vue.js" ]
stackoverflow_0074680392_ajax_javascript_json_vue.js.txt
Q: Inserting picture using macro vba to adopt to a merged cell or single cell I have a problem integrating my InsertPicture code to my FitPicture macro. I'm confused on how to get the shape to resize it automatically after using Insert function. It gives me the error regarding with the object. Here's a link of the idea that I research but still can't make anything happen. Any help is appreciated. Thanks. Here's the macro I'm using to fit the picture into a merged cell or single cell: Sub FitPicture() On Error GoTo NOT_SHAPE Dim r As Range, sel As Shape Set sel = ActiveSheet.Shapes(Selection.Name) sel.LockAspectRatio = msoTrue Set r = Range(sel.TopLeftCell.MergeArea.Address) Select Case (r.Width / r.Height) / (sel.Width / sel.Height) Case Is > 1 sel.Height = r.Height * 0.9 Case Else sel.Width = r.Width * 0.9 End Select sel.Top = r.Top + 0.05 * sel.Height: sel.Left = r.Left + 0.05 * sel.Width Exit Sub NOT_SHAPE: MsgBox "Please select a picture first." End Sub Here's the macro I'm using to insert a picture: Sub InsertPicture() Dim sPicture As String, pic As Picture sPicture = Application.GetOpenFilename _ ("Pictures (*.gif; *.jpg; *.bmp; *.tif), *.gif; *.jpg; *.bmp; *.tif", _ , "Select Picture to Import") If sPicture = "False" Then Exit Sub Set pic = ActiveSheet.Pictures.Insert(sPicture) With pic .ShapeRange.LockAspectRatio = msoFalse .Height = ActiveCell.Height .Width = ActiveCell.Width .Top = ActiveCell.Top .Left = ActiveCell.Left .Placement = xlMoveAndSize End With Set pic = Nothing End Sub How can I integrate my FitPicture code to InsertPicture code? I need to resize it automatically after inserting using my mentioned modification on FitPicture. By the way, I'm using excel 2013. Thanks mates. A: After a day of trying, I finished the macro. Working on single cell, merged cell or selected cell even not merged. Sub Insert() Dim myPicture As String, MyRange As Range myPicture = Application.GetOpenFilename _ ("Pictures (.bmp; .gif; .jpg; .png; .tif),.bmp; .gif; .jpg; .png; .tif", _ , "Select Picture to Import") Set MyRange = Selection InsertAndSizePic MyRange, myPicture End Sub Sub InsertAndSizePic(Target As Range, PicPath As String) Dim p As Picture Application.ScreenUpdating = False On Error GoTo EndOfSubroutine: Set p = ActiveSheet.Pictures.Insert(PicPath) 'resize Select Case (Target.Width / Target.Height) / (p.Width / p.Height) Case Is > 1 p.Height = Target.Height * 0.9 Case Else p.Width = Target.Width * 0.9 End Select 'center picture p.Top = Target.Top + (Target.Height - p.Height) / 2: p.Left = Target.Left + (Target.Width - p.Width) / 2 Exit Sub EndOfSubroutine: End Sub A: Thank you so much for the support. I was able to get it to work when testing in the VBA window, however when I try to use the file it now gives the following error: Cannot run the macro ''Blank Formula Template.xlsm'!InsertPhotoMacro'. The macro may not be available in this workbook or all macros may be disabled.
Inserting picture using macro vba to adopt to a merged cell or single cell
I have a problem integrating my InsertPicture code to my FitPicture macro. I'm confused on how to get the shape to resize it automatically after using Insert function. It gives me the error regarding with the object. Here's a link of the idea that I research but still can't make anything happen. Any help is appreciated. Thanks. Here's the macro I'm using to fit the picture into a merged cell or single cell: Sub FitPicture() On Error GoTo NOT_SHAPE Dim r As Range, sel As Shape Set sel = ActiveSheet.Shapes(Selection.Name) sel.LockAspectRatio = msoTrue Set r = Range(sel.TopLeftCell.MergeArea.Address) Select Case (r.Width / r.Height) / (sel.Width / sel.Height) Case Is > 1 sel.Height = r.Height * 0.9 Case Else sel.Width = r.Width * 0.9 End Select sel.Top = r.Top + 0.05 * sel.Height: sel.Left = r.Left + 0.05 * sel.Width Exit Sub NOT_SHAPE: MsgBox "Please select a picture first." End Sub Here's the macro I'm using to insert a picture: Sub InsertPicture() Dim sPicture As String, pic As Picture sPicture = Application.GetOpenFilename _ ("Pictures (*.gif; *.jpg; *.bmp; *.tif), *.gif; *.jpg; *.bmp; *.tif", _ , "Select Picture to Import") If sPicture = "False" Then Exit Sub Set pic = ActiveSheet.Pictures.Insert(sPicture) With pic .ShapeRange.LockAspectRatio = msoFalse .Height = ActiveCell.Height .Width = ActiveCell.Width .Top = ActiveCell.Top .Left = ActiveCell.Left .Placement = xlMoveAndSize End With Set pic = Nothing End Sub How can I integrate my FitPicture code to InsertPicture code? I need to resize it automatically after inserting using my mentioned modification on FitPicture. By the way, I'm using excel 2013. Thanks mates.
[ "After a day of trying, I finished the macro. Working on single cell, merged cell or selected cell even not merged. \nSub Insert()\n\nDim myPicture As String, MyRange As Range\nmyPicture = Application.GetOpenFilename _\n(\"Pictures (.bmp; .gif; .jpg; .png; .tif),.bmp; .gif; .jpg; .png; .tif\", _\n, \"Select Picture to Import\")\n\nSet MyRange = Selection\nInsertAndSizePic MyRange, myPicture\nEnd Sub\n\n\nSub InsertAndSizePic(Target As Range, PicPath As String)\n\nDim p As Picture\nApplication.ScreenUpdating = False\n\nOn Error GoTo EndOfSubroutine:\nSet p = ActiveSheet.Pictures.Insert(PicPath)\n\n'resize\nSelect Case (Target.Width / Target.Height) / (p.Width / p.Height)\nCase Is > 1\np.Height = Target.Height * 0.9\nCase Else\np.Width = Target.Width * 0.9\nEnd Select\n\n'center picture\np.Top = Target.Top + (Target.Height - p.Height) / 2: p.Left = Target.Left + \n(Target.Width - p.Width) / 2\n\nExit Sub\n\nEndOfSubroutine:\nEnd Sub\n\n", "Thank you so much for the support. I was able to get it to work when testing in the VBA window, however when I try to use the file it now gives the following error:\nCannot run the macro ''Blank Formula Template.xlsm'!InsertPhotoMacro'. The macro may not be available in this workbook or all macros may be disabled.\n" ]
[ 0, 0 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0047069675_excel_vba.txt
Q: how to check if double variable is almost equal to zero in C++? I want to find approximate polynomial roots of a polynomial equation. #include <fstream> #include <cmath> #include <iostream> using namespace std; bool polynomial_algorithm(double a, double b, double c, double d, double e,int& sum, int i1, int i2) { double y = 0; for (double i = i1; i <= i2; i += 0.0000001) { double x = (a * pow(i, 4) + b * pow(i, 3) + c * pow(i, 2) + d * i + e); } return true; } int main() { int i1,i2,sum=0; double a, b, c, d, e; //interval configuration: i1 = -1; i2 = 2; cout << "interval (" << i1 << ";" << i2 << ")" << endl; //configuration of values: a = -1; b = 3; c = static_cast<double>(-4) / 9; d = static_cast<double>(-4) / 3; e = static_cast<double>(32) / 81; cout << a << " " << b << " " << c << " " << d << " " << e << endl; if (i2 < i1) { cout << "invalid interval"; } cout << endl << "compiling" << endl; cout << endl << "compilation success: "<<polynomial_algorithm(a,b,c,d,e,sum,i1,i2) << endl; } This is the code I currently have, how do I got about checking if double x ≈ 0 in bool polynomial_algorithm? I tried reading articles about the std::abs function and other stuff but it just really fried my brain, I appreciate the help if I get any. A: To check if a double value is almost equal to zero, you can use the fabs function from the <cmath> library. This function returns the absolute value of a floating point number. Here is an example of how you can use it: #include <cmath> double value = 0.000001; if (fabs(value) < 0.001) { // value is almost equal to zero } In your code, you can use it like this: bool polynomial_algorithm(double a, double b, double c, double d, double e,int& sum, int i1, int i2) { double y = 0; for (double i = i1; i <= i2; i += 0.0000001) { double x = (a * pow(i, 4) + b * pow(i, 3) + c * pow(i, 2) + d * i + e); if (fabs(x) < 0.001) { // x is almost equal to zero // do something here } } return true; } Note that the threshold value (0.001 in this example) depends on your specific needs. You may need to adjust it to get the desired behavior.
how to check if double variable is almost equal to zero in C++?
I want to find approximate polynomial roots of a polynomial equation. #include <fstream> #include <cmath> #include <iostream> using namespace std; bool polynomial_algorithm(double a, double b, double c, double d, double e,int& sum, int i1, int i2) { double y = 0; for (double i = i1; i <= i2; i += 0.0000001) { double x = (a * pow(i, 4) + b * pow(i, 3) + c * pow(i, 2) + d * i + e); } return true; } int main() { int i1,i2,sum=0; double a, b, c, d, e; //interval configuration: i1 = -1; i2 = 2; cout << "interval (" << i1 << ";" << i2 << ")" << endl; //configuration of values: a = -1; b = 3; c = static_cast<double>(-4) / 9; d = static_cast<double>(-4) / 3; e = static_cast<double>(32) / 81; cout << a << " " << b << " " << c << " " << d << " " << e << endl; if (i2 < i1) { cout << "invalid interval"; } cout << endl << "compiling" << endl; cout << endl << "compilation success: "<<polynomial_algorithm(a,b,c,d,e,sum,i1,i2) << endl; } This is the code I currently have, how do I got about checking if double x ≈ 0 in bool polynomial_algorithm? I tried reading articles about the std::abs function and other stuff but it just really fried my brain, I appreciate the help if I get any.
[ "To check if a double value is almost equal to zero, you can use the fabs function from the <cmath> library. This function returns the absolute value of a floating point number.\nHere is an example of how you can use it:\n#include <cmath>\n\ndouble value = 0.000001;\nif (fabs(value) < 0.001) {\n // value is almost equal to zero\n}\n\nIn your code, you can use it like this:\nbool polynomial_algorithm(double a, double b, double c, double d, double e,int& sum, int i1, int i2)\n{\n double y = 0;\n for (double i = i1; i <= i2; i += 0.0000001)\n {\n double x = (a * pow(i, 4) + b * pow(i, 3) + c * pow(i, 2) + d * i + e);\n if (fabs(x) < 0.001) {\n // x is almost equal to zero\n // do something here\n }\n }\n return true;\n}\n\nNote that the threshold value (0.001 in this example) depends on your specific needs. You may need to adjust it to get the desired behavior.\n" ]
[ 0 ]
[]
[]
[ "algorithm", "c++", "cmath", "function", "math" ]
stackoverflow_0074680498_algorithm_c++_cmath_function_math.txt
Q: ag-grid: How to select the all the rows on click of header checkbox for multiple pages with server side pagination in the ag-grid table I would like to select the ids of all the rows on click of header checkbox for ag-grid table with server-side pagination enabled. Currently i am able to retain only the active page table rows ids but i want to select ids of multiple pages with ag-grid server-side pagination. i tried with getSelectedNodes() and getSelectedRows() apis of rowSelected events of ag-grid but it gives me only the current page data not the multiple page data. Please let me know how can i get the data from multiple pages rows selection with server side pagination. A: use the ag-grid API to programmatically select the rows on each page when the header checkbox is clicked. Just by calling the selectAll method on the grid API and passing it the inRange parameter set to true. const gridApi = gridOptions.api; // Select all rows gridApi.addEventListener('selectionChanged', (event) => { if (event.api.getSelectedRows().length === event.api.paginationGetRowCount()) { gridApi.selectAll({ inRange: true }); } });
ag-grid: How to select the all the rows on click of header checkbox for multiple pages with server side pagination in the ag-grid table
I would like to select the ids of all the rows on click of header checkbox for ag-grid table with server-side pagination enabled. Currently i am able to retain only the active page table rows ids but i want to select ids of multiple pages with ag-grid server-side pagination. i tried with getSelectedNodes() and getSelectedRows() apis of rowSelected events of ag-grid but it gives me only the current page data not the multiple page data. Please let me know how can i get the data from multiple pages rows selection with server side pagination.
[ "use the ag-grid API to programmatically select the rows on each page when the header checkbox is clicked. Just by calling the selectAll method on the grid API and passing it the inRange parameter set to true.\nconst gridApi = gridOptions.api;\n\n// Select all rows \ngridApi.addEventListener('selectionChanged', (event) => {\n if (event.api.getSelectedRows().length === event.api.paginationGetRowCount()) {\n \n gridApi.selectAll({ inRange: true });\n }\n});\n\n" ]
[ 0 ]
[]
[]
[ "ag_grid", "ag_grid_angular", "javascript" ]
stackoverflow_0074680495_ag_grid_ag_grid_angular_javascript.txt
Q: Yahoo Finance - Historical Intraday Download does anybody know why the code below does not bring data after 16:55hr? The market actually closes at 18:00 in Brazil. This happens for all tickers ending in ".SA" in Yahoo Finance. import yfinance as yf data = yf.download("PETR4.SA", group_by="Ticker", period='1mo', interval='5m',prepost = True) data['ticker'] = "PETR4.SA" data Thanks!
Yahoo Finance - Historical Intraday Download
does anybody know why the code below does not bring data after 16:55hr? The market actually closes at 18:00 in Brazil. This happens for all tickers ending in ".SA" in Yahoo Finance. import yfinance as yf data = yf.download("PETR4.SA", group_by="Ticker", period='1mo', interval='5m',prepost = True) data['ticker'] = "PETR4.SA" data Thanks!
[]
[]
[ "did you got to solve this issue? I am trying to solve this too.\n" ]
[ -2 ]
[ "download", "yahoo_finance", "yfinance" ]
stackoverflow_0070947841_download_yahoo_finance_yfinance.txt
Q: Filtering of react native array not working/displaying My current issue is filtering through a array of "lessons" with a search input. When a user first goes to the lessons components all the lessons are loaded if the search input text is nothing. When i type something though(if if it matches it) it will not show up and everything will just not show. my code:(lessonCard is the component of each lesson)**took away the database query because it was too long export default function Learn() { const [lessons,setLessons] = useState([]) const [searchinput,setSearchInput] = useState("") return ( <View style={learnStyle.maincont}> <View style={learnStyle.learncont}> <Text style={learnStyle.even}>EVVENNTI</Text> <Text style={learnStyle.learn}>Learn</Text> </View> <View style={{marginTop:20,flexDirection:"row", width:"100%",alignItems:"center",backgroundColor:"#F3F5F9",borderRadius:20,paddingLeft:15}}> <Feather name="search" size={24} color="#FF802C"style={{flex:0.1}} /> <TextInput style={{padding:20,borderRadius:20,flex:0.9}} placeholder="type lesson keyword" placeholderTextColor="grey" color="#000" value={searchinput} onChangeText={(val) => setSearchInput(val)}/> </View> {li ? <View style={{width:"100%",flexDirection:"row",marginTop:30,borderRadius:20,backgroundColor:"#CFECFE"}}> <View style={{flex:0.5,padding:20}}> <Text style={{fontSize:20,fontWeight:"700",marginBottom:20}}>What do you want to learn Today?</Text> <View style={{backgroundColor:"#FF7F2D",padding:8,borderRadius:20}}> <Button title='Get Started' color="#fff"/> </View> </View> <View style={{flex:0.5,marginLeft:10}}> <Image source={{uri:"https://cdn.discordapp.com/attachments/783336191529320498/1048439876741251072/Screen_Shot_2022-12-02_at_10.25.38_PM.png"}} style={{width:"100%",height:200,borderRadius:20}}/> </View> </View> : null} <View> <Text style={{fontSize:28,marginTop:20}}>Courses</Text> <ScrollView style={{paddingBottom:200}}> {searchinput === "" ? lessons.map((doc,key) => <> <LessonCard key={key} setModalVisible={setModalVisible} title={doc.title} desc={doc.desc} img1={doc.imgURL} modalVisible={modalVisible} /> </>): lessons.filter((lessons) => { if(searchinput.toLocaleLowerCase().includes(lessons.title)) { <LessonCard key={key} setModalVisible={setModalVisible} title={doc.title} desc={doc.desc} img1={doc.imgURL} modalVisible={modalVisible} /> } else {null} })} <View style={{height:600,width:"100%"}}></View> </ScrollView> </View> </View> ) } so basically im trying to see weather or not my search input includes the lesson title and if it does to show it like in this code below {searchinput === "" ? lessons.map((doc,key) => <> <LessonCard key={key} setModalVisible={setModalVisible} title={doc.title} desc={doc.desc} img1={doc.imgURL} modalVisible={modalVisible} /> </>): lessons.filter((lessons) => { if(searchinput.toLocaleLowerCase().includes(lessons.title)) { <LessonCard key={key} setModalVisible={setModalVisible} title={doc.title} desc={doc.desc} img1={doc.imgURL} modalVisible={modalVisible} /> } else {null} })} what would be the correct javascript/react syntax to fully show the lessons that match the search input? A: .filter returns an array based on the condition (which is .includes in your case). So you should write your filter logic and then calling .map on the filtered array to return your components. <div> <InfoBlock data={DATASET} /> <InfoBlock data={RAW_MEDIA} /> { searchinput === "" ? lessons.map((lesson, key) => <LessonCard key={key} setModalVisible={setModalVisible} title={lesson.title} desc={lesson.desc} img1={lesson.imgURL} modalVisible={modalVisible} /> ) : lessons.filter((lesson) => searchinput.toLocaleLowerCase().includes(lesson.title) ? 1 : -1).map((lesson) => { if(searchinput.toLocaleLowerCase().includes(lesson.title)) { return <LessonCard key={key} setModalVisible={setModalVisible} title={lesson.title} desc={lesson.desc} img1={lesson.imgURL} modalVisible={modalVisible} />; } else { return null; } }) } </div> A: Expanding on my comment (demo): import React, { useEffect, useState } from 'react'; import { Text, View, StyleSheet, ScrollView,Image } from 'react-native'; import Constants from 'expo-constants'; import { TextInput } from 'react-native-paper'; export default function App() { const [lessons, setLessons] = useState([]); const [filteredLessons, setFilteredLessons] = useState([]); const [searchinput, setSearchInput] = useState(''); useEffect(() => { // fetch data on mount const getData = async () => { const results = await fetch('https://dummyjson.com/products'); const json = await results.json(); setLessons(json.products); console.log(json.products[0]) }; getData(); }, []); useEffect(() => { // when lessons or searchinput changes update filteredLessons const newLessons = lessons.filter((lesson) => lesson.title.toLowerCase().includes(searchinput.toLowerCase()) ); setFilteredLessons(searchinput.length < 1 ? lessons : newLessons); }, [lessons, searchinput]); return ( <View style={styles.container}> <TextInput value={searchinput} onChangeText={setSearchInput} label="Search" dense mode="outlined" /> <View style={{ flex: 1 }}> <ScrollView style={{ flex: 1 }} > {filteredLessons.map((item,i)=>{ return ( <View style={styles.item}> <Text>{item.title}</Text> <Image source={{uri:item.images[0]}} style={styles.image} /> </View> ); })} </ScrollView> </View> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', padding: 8, }, image:{ width:150, height:100 }, item: { padding: 5, margin: 5, justifyContent:'center', alignItems:'center' }, });
Filtering of react native array not working/displaying
My current issue is filtering through a array of "lessons" with a search input. When a user first goes to the lessons components all the lessons are loaded if the search input text is nothing. When i type something though(if if it matches it) it will not show up and everything will just not show. my code:(lessonCard is the component of each lesson)**took away the database query because it was too long export default function Learn() { const [lessons,setLessons] = useState([]) const [searchinput,setSearchInput] = useState("") return ( <View style={learnStyle.maincont}> <View style={learnStyle.learncont}> <Text style={learnStyle.even}>EVVENNTI</Text> <Text style={learnStyle.learn}>Learn</Text> </View> <View style={{marginTop:20,flexDirection:"row", width:"100%",alignItems:"center",backgroundColor:"#F3F5F9",borderRadius:20,paddingLeft:15}}> <Feather name="search" size={24} color="#FF802C"style={{flex:0.1}} /> <TextInput style={{padding:20,borderRadius:20,flex:0.9}} placeholder="type lesson keyword" placeholderTextColor="grey" color="#000" value={searchinput} onChangeText={(val) => setSearchInput(val)}/> </View> {li ? <View style={{width:"100%",flexDirection:"row",marginTop:30,borderRadius:20,backgroundColor:"#CFECFE"}}> <View style={{flex:0.5,padding:20}}> <Text style={{fontSize:20,fontWeight:"700",marginBottom:20}}>What do you want to learn Today?</Text> <View style={{backgroundColor:"#FF7F2D",padding:8,borderRadius:20}}> <Button title='Get Started' color="#fff"/> </View> </View> <View style={{flex:0.5,marginLeft:10}}> <Image source={{uri:"https://cdn.discordapp.com/attachments/783336191529320498/1048439876741251072/Screen_Shot_2022-12-02_at_10.25.38_PM.png"}} style={{width:"100%",height:200,borderRadius:20}}/> </View> </View> : null} <View> <Text style={{fontSize:28,marginTop:20}}>Courses</Text> <ScrollView style={{paddingBottom:200}}> {searchinput === "" ? lessons.map((doc,key) => <> <LessonCard key={key} setModalVisible={setModalVisible} title={doc.title} desc={doc.desc} img1={doc.imgURL} modalVisible={modalVisible} /> </>): lessons.filter((lessons) => { if(searchinput.toLocaleLowerCase().includes(lessons.title)) { <LessonCard key={key} setModalVisible={setModalVisible} title={doc.title} desc={doc.desc} img1={doc.imgURL} modalVisible={modalVisible} /> } else {null} })} <View style={{height:600,width:"100%"}}></View> </ScrollView> </View> </View> ) } so basically im trying to see weather or not my search input includes the lesson title and if it does to show it like in this code below {searchinput === "" ? lessons.map((doc,key) => <> <LessonCard key={key} setModalVisible={setModalVisible} title={doc.title} desc={doc.desc} img1={doc.imgURL} modalVisible={modalVisible} /> </>): lessons.filter((lessons) => { if(searchinput.toLocaleLowerCase().includes(lessons.title)) { <LessonCard key={key} setModalVisible={setModalVisible} title={doc.title} desc={doc.desc} img1={doc.imgURL} modalVisible={modalVisible} /> } else {null} })} what would be the correct javascript/react syntax to fully show the lessons that match the search input?
[ ".filter returns an array based on the condition (which is .includes in your case). So you should write your filter logic and then calling .map on the filtered array to return your components.\n<div>\n <InfoBlock data={DATASET} />\n <InfoBlock data={RAW_MEDIA} />\n{\n searchinput === \"\" ? \n lessons.map((lesson, key) => \n <LessonCard key={key} setModalVisible={setModalVisible} title={lesson.title} desc={lesson.desc} img1={lesson.imgURL} modalVisible={modalVisible} />\n )\n : \n lessons.filter((lesson) => searchinput.toLocaleLowerCase().includes(lesson.title) ? 1 : -1).map((lesson) => {\n if(searchinput.toLocaleLowerCase().includes(lesson.title)) {\n return <LessonCard key={key} setModalVisible={setModalVisible} title={lesson.title} desc={lesson.desc} img1={lesson.imgURL} modalVisible={modalVisible} />;\n } else {\n return null;\n }\n })\n}\n</div>\n\n", "Expanding on my comment (demo):\nimport React, { useEffect, useState } from 'react';\nimport { Text, View, StyleSheet, ScrollView,Image } from 'react-native';\nimport Constants from 'expo-constants';\nimport { TextInput } from 'react-native-paper';\n\nexport default function App() {\n const [lessons, setLessons] = useState([]);\n const [filteredLessons, setFilteredLessons] = useState([]);\n const [searchinput, setSearchInput] = useState('');\n\n useEffect(() => {\n // fetch data on mount\n const getData = async () => {\n const results = await fetch('https://dummyjson.com/products');\n const json = await results.json();\n setLessons(json.products);\n console.log(json.products[0])\n };\n getData();\n }, []);\n useEffect(() => {\n // when lessons or searchinput changes update filteredLessons\n const newLessons = lessons.filter((lesson) =>\n lesson.title.toLowerCase().includes(searchinput.toLowerCase())\n );\n setFilteredLessons(searchinput.length < 1 ? lessons : newLessons);\n }, [lessons, searchinput]);\n return (\n <View style={styles.container}>\n <TextInput\n value={searchinput}\n onChangeText={setSearchInput}\n label=\"Search\"\n dense\n mode=\"outlined\"\n />\n <View style={{ flex: 1 }}>\n <ScrollView\n style={{ flex: 1 }}\n \n >\n {filteredLessons.map((item,i)=>{\n return (\n <View style={styles.item}>\n <Text>{item.title}</Text>\n <Image\n source={{uri:item.images[0]}}\n style={styles.image}\n />\n </View>\n );\n })}\n </ScrollView>\n </View>\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n justifyContent: 'center',\n paddingTop: Constants.statusBarHeight,\n backgroundColor: '#ecf0f1',\n padding: 8,\n },\n image:{\n width:150,\n height:100\n },\n item: {\n padding: 5,\n margin: 5,\n justifyContent:'center',\n alignItems:'center'\n },\n});\n\n" ]
[ 1, 1 ]
[]
[]
[ "frontend", "javascript", "react_native", "reactjs" ]
stackoverflow_0074680201_frontend_javascript_react_native_reactjs.txt
Q: button is not working when i click on button arrow it is not taking me to the next image <section id="carouselExampleControls"> <div id="carouselExampleControls" class="carousel slide" data-ride="false"> <div class="carousel-inner"> <div class="carousel-item active"> <h2>You no longer have to carry a portable oxygen meter while at home.</h2> <img class="testimonial-image" src="C:\Users\adharsh.mamidi\Desktop\webdevelopment\oxyhome\TinDog-Start-master\images\second image.jpg" alt="Portable-oxygen"> </div> <div class="carousel-item"> <h2 class="testimonial-text">OxyHome provides the same amount of concentration as of the portable machine. Breathe.</h2> <img class="testimonial-image" src="C:\Users\adharsh.mamidi\Desktop\webdevelopment\oxyhome\TinDog-Start-master\images\lady-img.jpg" alt="lady-profile"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a class="carousel-control-next" role="button" href="#carouselExampleControls" data-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> </section> IThe buttons are created but when i click on the next button im not getting the next image the buttons are not working. A: Try removing the data-ride attribute and replacing it with data-interval="false" or data-ride="carousel"
button is not working when i click on button arrow it is not taking me to the next image
<section id="carouselExampleControls"> <div id="carouselExampleControls" class="carousel slide" data-ride="false"> <div class="carousel-inner"> <div class="carousel-item active"> <h2>You no longer have to carry a portable oxygen meter while at home.</h2> <img class="testimonial-image" src="C:\Users\adharsh.mamidi\Desktop\webdevelopment\oxyhome\TinDog-Start-master\images\second image.jpg" alt="Portable-oxygen"> </div> <div class="carousel-item"> <h2 class="testimonial-text">OxyHome provides the same amount of concentration as of the portable machine. Breathe.</h2> <img class="testimonial-image" src="C:\Users\adharsh.mamidi\Desktop\webdevelopment\oxyhome\TinDog-Start-master\images\lady-img.jpg" alt="lady-profile"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a class="carousel-control-next" role="button" href="#carouselExampleControls" data-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> </section> IThe buttons are created but when i click on the next button im not getting the next image the buttons are not working.
[ "Try removing the data-ride attribute and replacing it with data-interval=\"false\" or data-ride=\"carousel\"\n" ]
[ 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074679933_css_html.txt
Q: Unable to Turn on Loudspeaker while on call in Java I am creating a call functionalituy where I am using third party call service for calling feature in React Native. I want to turn on/off speaker while on call. I have used this package but it also not helped. Further I have tried modifying the AudioManager code and give following permissions also - <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> I have also tried adding some changes to audioManager.setSpeakerphoneOn(enable); but nothing is working for me to set speaker on. I have also tried doing audioManager.setMode(AudioManager.MODE_IN_CALL); & Also tried audioManager.setMode(AudioManager.MODE_RINGTONE; But none of these options helped. I needed this urgently to be done. For now I need in Android so any solutions by which it can work ? that will be helpful. A: One potential solution could be to use the React Native Audio API, which allows you to control audio playback and settings in your app. You can use the following code to set the speakerphone on: const sound = new Audio.Sound(); await sound.setSpeakerphoneOn(true);
Unable to Turn on Loudspeaker while on call in Java
I am creating a call functionalituy where I am using third party call service for calling feature in React Native. I want to turn on/off speaker while on call. I have used this package but it also not helped. Further I have tried modifying the AudioManager code and give following permissions also - <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> I have also tried adding some changes to audioManager.setSpeakerphoneOn(enable); but nothing is working for me to set speaker on. I have also tried doing audioManager.setMode(AudioManager.MODE_IN_CALL); & Also tried audioManager.setMode(AudioManager.MODE_RINGTONE; But none of these options helped. I needed this urgently to be done. For now I need in Android so any solutions by which it can work ? that will be helpful.
[ "One potential solution could be to use the React Native Audio API, which allows you to control audio playback and settings in your app. You can use the following code to set the speakerphone on:\nconst sound = new Audio.Sound();\nawait sound.setSpeakerphoneOn(true);\n\n" ]
[ 0 ]
[]
[]
[ "android", "ios", "java", "phone_call", "react_native" ]
stackoverflow_0074680579_android_ios_java_phone_call_react_native.txt
Q: ggplot2 display duplicate x axis tick labels I have the following tibble: library(tibble) library(ggplot2) df <- tibble( Time = c('J-17', 'J', 'A', 'S', 'O', 'N', 'D', 'J-18', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D', 'J-19', 'F'), Measurement = c(6.8, 6.7, 6.86, 6.63, 6.86, 7.61, 6.99, 7.48, 6.96, 7.22, 7.27, 7.19, 7.58, 7.46, 6.6, 6.97, 7.05, 7.41, 7.91, 6.38, 6.69) ) # Added an index to df df$Index <- 1:nrow(df) I'm plotting like this: ggplot(df, aes( x = df$Index, y = df$Measurement, )) + geom_hline(yintercept = mean(df$Measurement)) + geom_line() + scale_x_discrete(expand = c(0,0), labels = df$Time) + theme_classic() + geom_point() The labels aren't showing on the x axis at all. Am I using labels in scale_x_discrete correctly? Time contains duplicate values and I want to keep those and keep the same order as in the df Any help is appreciated! Thanks! A: You don't need to use $ inside aes, since you already referencing the data.frame. Also it is scale_x_continuous, since the variable for x is Index. ggplot( data = df, aes( x = Index, y = Measurement)) + geom_hline(aes(yintercept = mean(Measurement))) + geom_line() + scale_x_continuous(expand = c(0,0),breaks = df$Index,labels = df$Time ) + theme_classic() + geom_point()
ggplot2 display duplicate x axis tick labels
I have the following tibble: library(tibble) library(ggplot2) df <- tibble( Time = c('J-17', 'J', 'A', 'S', 'O', 'N', 'D', 'J-18', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D', 'J-19', 'F'), Measurement = c(6.8, 6.7, 6.86, 6.63, 6.86, 7.61, 6.99, 7.48, 6.96, 7.22, 7.27, 7.19, 7.58, 7.46, 6.6, 6.97, 7.05, 7.41, 7.91, 6.38, 6.69) ) # Added an index to df df$Index <- 1:nrow(df) I'm plotting like this: ggplot(df, aes( x = df$Index, y = df$Measurement, )) + geom_hline(yintercept = mean(df$Measurement)) + geom_line() + scale_x_discrete(expand = c(0,0), labels = df$Time) + theme_classic() + geom_point() The labels aren't showing on the x axis at all. Am I using labels in scale_x_discrete correctly? Time contains duplicate values and I want to keep those and keep the same order as in the df Any help is appreciated! Thanks!
[ "You don't need to use $ inside aes, since you already referencing the data.frame. Also it is scale_x_continuous, since the variable for x is Index.\nggplot(\n data = df, aes(\n x = Index,\n y = Measurement)) +\n geom_hline(aes(yintercept = mean(Measurement))) +\n geom_line() +\n scale_x_continuous(expand = c(0,0),breaks = df$Index,labels = df$Time ) +\n theme_classic() +\n geom_point()\n\n\n" ]
[ 2 ]
[]
[]
[ "ggplot2", "r" ]
stackoverflow_0074680573_ggplot2_r.txt
Q: How to make Python CUDA atomicAdd to work with long int How can I make Python CUDA atomicAdd works with long int? I tried with the below code, and it does not work as long as I use long *result_count or atomicAdd(&InitianCount,1);, with compilation error such as below. import os _path = r"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\bin\Hostx64\x64" if os.system("cl.exe"): os.environ['PATH'] += ';' + _path if os.system("cl.exe"): raise RuntimeError("cl.exe still not found, path probably incorrect") import pycuda.driver as cuda import pycuda.autoinit from pycuda.compiler import SourceModule import pandas as pd import numpy as np InitianCount = 0 record_result = np.zeros((100000000, 4)).astype(np.float32) record_result_gpu = cuda.mem_alloc(record_result.nbytes) # result_count = np.int64(0) result_count = np.zeros(1, dtype=np.int64) result_count_gpu = cuda.mem_alloc(result_count.nbytes) cuda.memcpy_htod(result_count_gpu, result_count) print('result_count.nbytes is ' + str(result_count.nbytes)) mod = SourceModule(""" #include <cstdlib> __global__ void test_cuda_LongIntArray(long InitianCount, int *result_count, float *record_result) // __global__ void test_cuda_LongIntArray(long InitianCount, long *result_count, float *record_result) { long result_index; result_index = atomicAdd(result_count,1); // result_index = atomicAdd(&InitianCount,1); } """) func = mod.get_function("test_cuda_LongIntArray") func( np.int64(InitianCount), result_count_gpu, record_result_gpu, block=(4,16,16)) record_result = np.empty((100000000, 4), dtype=np.float32) cuda.memcpy_dtoh(record_result, record_result_gpu) print('record_result is with dimension ' + str(len(record_result)) + ' x ' + str(len(record_result[0]))) print(record_result) record_result_gpu.free() 'cl.exe' is not recognized as an internal or external command, operable program or batch file. Microsoft (R) C/C++ Optimizing Compiler Version 19.33.31629 for x64 Copyright (C) Microsoft Corporation. All rights reserved. result_count.nbytes is 8 Traceback (most recent call last): File C:\PythonProjects\TradeAnalysis\Test\TestCUDAUtilisationBrute_Long_a.py:34 in <module> mod = SourceModule(""" File ~\anaconda3\lib\site-packages\pycuda\compiler.py:352 in __init__ cubin = compile( File ~\anaconda3\lib\site-packages\pycuda\compiler.py:301 in compile return compile_plain(source, options, keep, nvcc, cache_dir, target) File ~\anaconda3\lib\site-packages\pycuda\compiler.py:154 in compile_plain raise CompileError( CompileError: nvcc compilation of C:\Users\henry\AppData\Local\Temp\tmpjggfucw2\kernel.cu failed A: First, on windows, long (or long int) is a (signed) 32-bit (integer) type. So when asking for "how to use atomics with long" while at the same time allocating for 64-bit types in your code: result_count = np.zeros(1, dtype=np.int64) begs the question are you really asking about how to use atomics with long, or are you really asking about how to use atomics on a 64-bit integer type? I'll assume you want 64-bit atomics. In CUDA, atomicAdd for 64-bit integer types is only supported for unsigned types. So we will choose to use unsigned long long here, as it is unambiguously 64-bits unsigned on either windows or linux (for all currently supported CUDA activity using 64-bit OS's). Second, to address your attempt in comments, you cannot do atomics on a local variable. When you use this variable: __global__ void test_cuda_LongIntArray(long InitianCount, ^^^^^^^^^^^^ in a thread, that is effectively thread-local. Atomics work on global (or shared) variables. A global variable will generally be passed to a kernel using a pointer, perhaps like so: __global__ void test_cuda_LongIntArray(long *InitianCount, If we aim for that (albeit using the result_count example), we can create something like this: $ cat t36.py import pycuda.driver as cuda import pycuda.autoinit from pycuda.compiler import SourceModule import numpy as np InitianCount = 0 record_result = np.zeros((10000000, 4)).astype(np.float32) record_result_gpu = cuda.mem_alloc(record_result.nbytes) # result_count = np.int64(0) result_count = np.zeros(1, dtype=np.uint64) result_count_gpu = cuda.mem_alloc(result_count.nbytes) cuda.memcpy_htod(result_count_gpu, result_count) print('result_count.nbytes is ' + str(result_count.nbytes)) mod = SourceModule(""" #include <cstdlib> __global__ void test_cuda_LongIntArray(long long InitianCount, unsigned long long *result_count, float *record_result) // __global__ void test_cuda_LongIntArray(long InitianCount, long *result_count, float *record_result) { unsigned long long result_index; result_index = atomicAdd(result_count,1); // result_index = atomicAdd(&InitianCount,1); } """) func = mod.get_function("test_cuda_LongIntArray") func( np.int64(InitianCount), result_count_gpu, record_result_gpu, block=(4,16,16)) cuda.memcpy_dtoh(record_result, record_result_gpu) print('record_result is with dimension ' + str(len(record_result)) + ' x ' + str(len(record_result[0]))) print(record_result) record_result_gpu.free() $ python t36.py result_count.nbytes is 8 record_result is with dimension 10000000 x 4 [[ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.] ..., [ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]] $
How to make Python CUDA atomicAdd to work with long int
How can I make Python CUDA atomicAdd works with long int? I tried with the below code, and it does not work as long as I use long *result_count or atomicAdd(&InitianCount,1);, with compilation error such as below. import os _path = r"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\bin\Hostx64\x64" if os.system("cl.exe"): os.environ['PATH'] += ';' + _path if os.system("cl.exe"): raise RuntimeError("cl.exe still not found, path probably incorrect") import pycuda.driver as cuda import pycuda.autoinit from pycuda.compiler import SourceModule import pandas as pd import numpy as np InitianCount = 0 record_result = np.zeros((100000000, 4)).astype(np.float32) record_result_gpu = cuda.mem_alloc(record_result.nbytes) # result_count = np.int64(0) result_count = np.zeros(1, dtype=np.int64) result_count_gpu = cuda.mem_alloc(result_count.nbytes) cuda.memcpy_htod(result_count_gpu, result_count) print('result_count.nbytes is ' + str(result_count.nbytes)) mod = SourceModule(""" #include <cstdlib> __global__ void test_cuda_LongIntArray(long InitianCount, int *result_count, float *record_result) // __global__ void test_cuda_LongIntArray(long InitianCount, long *result_count, float *record_result) { long result_index; result_index = atomicAdd(result_count,1); // result_index = atomicAdd(&InitianCount,1); } """) func = mod.get_function("test_cuda_LongIntArray") func( np.int64(InitianCount), result_count_gpu, record_result_gpu, block=(4,16,16)) record_result = np.empty((100000000, 4), dtype=np.float32) cuda.memcpy_dtoh(record_result, record_result_gpu) print('record_result is with dimension ' + str(len(record_result)) + ' x ' + str(len(record_result[0]))) print(record_result) record_result_gpu.free() 'cl.exe' is not recognized as an internal or external command, operable program or batch file. Microsoft (R) C/C++ Optimizing Compiler Version 19.33.31629 for x64 Copyright (C) Microsoft Corporation. All rights reserved. result_count.nbytes is 8 Traceback (most recent call last): File C:\PythonProjects\TradeAnalysis\Test\TestCUDAUtilisationBrute_Long_a.py:34 in <module> mod = SourceModule(""" File ~\anaconda3\lib\site-packages\pycuda\compiler.py:352 in __init__ cubin = compile( File ~\anaconda3\lib\site-packages\pycuda\compiler.py:301 in compile return compile_plain(source, options, keep, nvcc, cache_dir, target) File ~\anaconda3\lib\site-packages\pycuda\compiler.py:154 in compile_plain raise CompileError( CompileError: nvcc compilation of C:\Users\henry\AppData\Local\Temp\tmpjggfucw2\kernel.cu failed
[ "First, on windows, long (or long int) is a (signed) 32-bit (integer) type. So when asking for \"how to use atomics with long\" while at the same time allocating for 64-bit types in your code:\nresult_count = np.zeros(1, dtype=np.int64)\n\nbegs the question are you really asking about how to use atomics with long, or are you really asking about how to use atomics on a 64-bit integer type? I'll assume you want 64-bit atomics. In CUDA, atomicAdd for 64-bit integer types is only supported for unsigned types. So we will choose to use unsigned long long here, as it is unambiguously 64-bits unsigned on either windows or linux (for all currently supported CUDA activity using 64-bit OS's).\nSecond, to address your attempt in comments, you cannot do atomics on a local variable. When you use this variable:\n__global__ void test_cuda_LongIntArray(long InitianCount,\n ^^^^^^^^^^^^\n\nin a thread, that is effectively thread-local. Atomics work on global (or shared) variables. A global variable will generally be passed to a kernel using a pointer, perhaps like so:\n__global__ void test_cuda_LongIntArray(long *InitianCount,\n\nIf we aim for that (albeit using the result_count example), we can create something like this:\n$ cat t36.py\nimport pycuda.driver as cuda\nimport pycuda.autoinit\nfrom pycuda.compiler import SourceModule\nimport numpy as np\n\nInitianCount = 0\n\nrecord_result = np.zeros((10000000, 4)).astype(np.float32)\nrecord_result_gpu = cuda.mem_alloc(record_result.nbytes)\n\n# result_count = np.int64(0)\nresult_count = np.zeros(1, dtype=np.uint64)\nresult_count_gpu = cuda.mem_alloc(result_count.nbytes)\ncuda.memcpy_htod(result_count_gpu, result_count)\n\nprint('result_count.nbytes is ' + str(result_count.nbytes))\n\nmod = SourceModule(\"\"\"\n #include <cstdlib>\n\n __global__ void test_cuda_LongIntArray(long long InitianCount, unsigned long long *result_count, float *record_result)\n// __global__ void test_cuda_LongIntArray(long InitianCount, long *result_count, float *record_result)\n {\n unsigned long long result_index;\n result_index = atomicAdd(result_count,1);\n// result_index = atomicAdd(&InitianCount,1);\n }\n \"\"\")\n\nfunc = mod.get_function(\"test_cuda_LongIntArray\")\nfunc( np.int64(InitianCount), result_count_gpu, record_result_gpu, block=(4,16,16))\n\ncuda.memcpy_dtoh(record_result, record_result_gpu)\n\nprint('record_result is with dimension ' + str(len(record_result)) + ' x ' + str(len(record_result[0])))\nprint(record_result)\n\nrecord_result_gpu.free()\n$ python t36.py\nresult_count.nbytes is 8\nrecord_result is with dimension 10000000 x 4\n[[ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]\n ...,\n [ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]]\n$\n\n" ]
[ 1 ]
[]
[]
[ "cuda", "python" ]
stackoverflow_0074678342_cuda_python.txt
Q: How to disable Teacher Forcing RNN model I have the following Teacher forcing RNN model where I'm implicitly passing the entire input sequence (inputs = ids[:, i:i+seq_length] to the model at once. What should I modify to disable teacher forcing training and get the original model. ids = corpus.get_data('data/train.txt', batch_size) model = RNNLM(vocab_size, embed_size, hidden_size, num_layers).to(device) # Loss and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) # Truncated backpropagation def detach(states): return [state.detach() for state in states] # Train the model for epoch in range(num_epochs): # Set initial hidden and cell states states = (torch.zeros(num_layers, batch_size, hidden_size).to(device), torch.zeros(num_layers, batch_size, hidden_size).to(device)) for i in range(0, ids.size(1) - seq_length, seq_length): # Get mini-batch inputs and targets inputs = ids[:, i:i+seq_length].to(device) targets = ids[:, (i+1):(i+1)+seq_length].to(device) # Forward pass states = detach(states) outputs, states = model(inputs, states) loss = criterion(outputs, targets.reshape(-1)) # Backward and optimize optimizer.zero_grad() loss.backward() clip_grad_norm_(model.parameters(), 0.5) optimizer.step() step = (i+1) // seq_length if step % 100 == 0: print ('Epoch [{}/{}], Step[{}/{}], Loss: {:.4f}, Perplexity: {:5.2f}' .format(epoch+1, num_epochs, step, num_batches, loss.item(), np.exp(loss.item()))) I tried to pass input and targets in different way, but nothing works. I'm kinda confused what the input and targets should be for the original model. A: To disable teacher forcing in the model, you need to modify the code that generates the input and target sequences. Currently, the input sequence is constructed by taking a contiguous block of seq_length tokens from the ids tensor, starting at position i and ending at position i + seq_length. The target sequence is constructed by taking a contiguous block of seq_length tokens from the ids tensor, starting at position i + 1 and ending at position (i + 1) + seq_length. To disable teacher forcing, you need to construct the input and target sequences differently. Instead of using a fixed length sequence of tokens, you should use a single token as the input and the corresponding target token. This means that you will need to loop through the ids tensor one token at a time, instead of using a fixed length block of tokens. Here is how you could modify the code to do this: #Train the model for epoch in range(num_epochs): # Set initial hidden and cell states states = (torch.zeros(num_layers, batch_size, hidden_size).to(device), torch.zeros(num_layers, batch_size, hidden_size).to(device)) # Loop through the tokens in the input sequence one at a time for i in range(0, ids.size(1)): # Get the current input and target tokens input = ids[:, i].to(device) target = ids[:, i+1].to(device) # Forward pass states = detach(states) outputs, states = model(input, states) loss = criterion(outputs, target) # Backward and optimize optimizer.zero_grad() loss.backward() clip_grad_norm_(model.parameters(), 0.5) optimizer.step() if i % 100 == 0: `
How to disable Teacher Forcing RNN model
I have the following Teacher forcing RNN model where I'm implicitly passing the entire input sequence (inputs = ids[:, i:i+seq_length] to the model at once. What should I modify to disable teacher forcing training and get the original model. ids = corpus.get_data('data/train.txt', batch_size) model = RNNLM(vocab_size, embed_size, hidden_size, num_layers).to(device) # Loss and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) # Truncated backpropagation def detach(states): return [state.detach() for state in states] # Train the model for epoch in range(num_epochs): # Set initial hidden and cell states states = (torch.zeros(num_layers, batch_size, hidden_size).to(device), torch.zeros(num_layers, batch_size, hidden_size).to(device)) for i in range(0, ids.size(1) - seq_length, seq_length): # Get mini-batch inputs and targets inputs = ids[:, i:i+seq_length].to(device) targets = ids[:, (i+1):(i+1)+seq_length].to(device) # Forward pass states = detach(states) outputs, states = model(inputs, states) loss = criterion(outputs, targets.reshape(-1)) # Backward and optimize optimizer.zero_grad() loss.backward() clip_grad_norm_(model.parameters(), 0.5) optimizer.step() step = (i+1) // seq_length if step % 100 == 0: print ('Epoch [{}/{}], Step[{}/{}], Loss: {:.4f}, Perplexity: {:5.2f}' .format(epoch+1, num_epochs, step, num_batches, loss.item(), np.exp(loss.item()))) I tried to pass input and targets in different way, but nothing works. I'm kinda confused what the input and targets should be for the original model.
[ "To disable teacher forcing in the model, you need to modify the code that generates the input and target sequences. Currently, the input sequence is constructed by taking a contiguous block of seq_length tokens from the ids tensor, starting at position i and ending at position i + seq_length. The target sequence is constructed by taking a contiguous block of seq_length tokens from the ids tensor, starting at position i + 1 and ending at position (i + 1) + seq_length.\nTo disable teacher forcing, you need to construct the input and target sequences differently. Instead of using a fixed length sequence of tokens, you should use a single token as the input and the corresponding target token. This means that you will need to loop through the ids tensor one token at a time, instead of using a fixed length block of tokens. Here is how you could modify the code to do this:\n#Train the model\nfor epoch in range(num_epochs):\n # Set initial hidden and cell states\n states = (torch.zeros(num_layers, batch_size, hidden_size).to(device),\n torch.zeros(num_layers, batch_size, hidden_size).to(device))\n \n # Loop through the tokens in the input sequence one at a time\n for i in range(0, ids.size(1)):\n # Get the current input and target tokens\n input = ids[:, i].to(device)\n target = ids[:, i+1].to(device)\n \n # Forward pass\n states = detach(states)\n outputs, states = model(input, states)\n loss = criterion(outputs, target)\n \n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n clip_grad_norm_(model.parameters(), 0.5)\n optimizer.step()\n\n if i % 100 == 0:\n\n`\n" ]
[ 0 ]
[]
[]
[ "python", "recurrent_neural_network" ]
stackoverflow_0074680569_python_recurrent_neural_network.txt
Q: how can I found flutter text to speech and speech to text amharic language accenet how can I set the assistant accent to native amharic speaker in flutter text-to-speech and speech to text? Future _Speak() async { await _flutterTts.setLanguage('en-US'); await _flutterTts.setVoice({"name": "Karen", "locale": "en-US"}); await _flutterTts.setPitch(1.0); await _flutterTts.setVolume(1); await _flutterTts.setSpeechRate(0.5); // await _flutterTts.speak(_textController.text); if (_tts != null) { if (_tts!.isNotEmpty) { await _flutterTts.speak(_tts!); } } } it really works with English accent (it can read Amharic alphabets but the accent is not good to listen for native Amharic speakers ), so what should I do? I am trying to develop Amharic text to speech and speech to text converter A: To set the accent to native Amharic, you will need to set the language and voice parameters of the _flutterTts object to the appropriate values. For the language parameter, you can use am-ET as the value to specify Amharic as the language. For the voice parameter, you will need to find the specific voice that sounds like a native Amharic speaker. You can try using different values for the name and locale keys within the voice parameter to see which one produces the desired result.
how can I found flutter text to speech and speech to text amharic language accenet
how can I set the assistant accent to native amharic speaker in flutter text-to-speech and speech to text? Future _Speak() async { await _flutterTts.setLanguage('en-US'); await _flutterTts.setVoice({"name": "Karen", "locale": "en-US"}); await _flutterTts.setPitch(1.0); await _flutterTts.setVolume(1); await _flutterTts.setSpeechRate(0.5); // await _flutterTts.speak(_textController.text); if (_tts != null) { if (_tts!.isNotEmpty) { await _flutterTts.speak(_tts!); } } } it really works with English accent (it can read Amharic alphabets but the accent is not good to listen for native Amharic speakers ), so what should I do? I am trying to develop Amharic text to speech and speech to text converter
[ "To set the accent to native Amharic, you will need to set the language and voice parameters of the _flutterTts object to the appropriate values.\nFor the language parameter, you can use am-ET as the value to specify Amharic as the language.\nFor the voice parameter, you will need to find the specific voice that sounds like a native Amharic speaker. You can try using different values for the name and locale keys within the voice parameter to see which one produces the desired result.\n" ]
[ 0 ]
[]
[]
[ "flutter", "speech_to_text", "text_to_speech" ]
stackoverflow_0074680577_flutter_speech_to_text_text_to_speech.txt
Q: Microsoft outlook authentication oAuth2.0 We have a daemon application that makes IMAP connection to access mailbox of user. Earlier we were using plain authentication method of using email ID and password to establish IMAP connection. Now as Microsoft has blocked this type authentication process and introduced oAuth2.0. My question here I was able to establish IMAP connection with the user that falls inside my tenant. But I am unable to figure out that how it can be done if I need to access the mailbox of user that doesn't fall inside my tenant or need to access the mailbox of any personal outlook account. A: I tried to reproduce the same in my environment and got the below results: Note that, if you want to access the mailbox of user that doesn't fall inside your tenant or need to access the mailbox of any personal outlook account then you have to register a Multi-Tenant Azure AD Application like below: I created an Azure AD Multi-Tenant Application and granted the API Permissions: Now, I registered service principals in Exchange by using below commands:** Connect-ExchangeOnline -Organization TenantID New-ServicePrincipal -AppId AppID -ServiceId ObjectID [-Organization OrganizationID] Get-ServicePrincipal | fl I granted service principal access to one mailbox : Add-MailboxPermission -Identity "USER@XXX.com" -User ServicePrincipal_ID> -AccessRights FullAccess Test-ApplicationAccessPolicy -Identity "USER@XXX.com" -AppId AppID I generated the access token via Postman for Multi-Tenant Application by using the parameters like below: https://login.microsoftonline.com/common/oauth2/v2.0/token client_id:5f3068f5-a920-4d6d-9742-XXXXXX client_secret:ESJ8Q~ShJVdlY2MhKicyTEApGdtZh******* scope:https://outlook.office365.com/.default grant_type:client_credentials To do the same in JAVA, you can refer the below sample code by user3206771 in this SO Thread : public String getAccessTokenByClientCredentialGrant() { String accessToken = null; String clientId = "CLIENTID"; String secret = "CLIENTSECRET"; String authority = "https://login.microsoftonline.com/common/oauth2/v2.0/token"; String scope = "https://outlook.office365.com/.default"; log.info("Client ID : "+clientId); log.info("Client Secret : "+secret); log.info("Auth Server: "+authority); log.info("Scope: "+scope); try { ConfidentialClientApplication app = ConfidentialClientApplication.builder( clientId, ClientCredentialFactory.createFromSecret(secret)) .authority(authority) .build(); ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder( Collections.singleton(scope)) .build(); CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam); IAuthenticationResult result = future.get(); accessToken = result.accessToken(); } catch(Exception e) { log.error("Exception in acquiring token: "+e.getMessage()); e.printStackTrace(); } log.info("Access Token : "+accessToken); return accessToken; } public Store connect(String userEmailId, String oauth2AccessToken) throws Exception { String host = "outlook.office365.com"; String port = "993"; Store store = null; String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props= new Properties(); props.put("mail.imaps.ssl.enable", "true"); props.put("mail.imaps.sasl.enable", "true"); props.put("mail.imaps.port", port); props.put("mail.imaps.auth.mechanisms", "XOAUTH2"); props.put("mail.imaps.sasl.mechanisms", "XOAUTH2"); props.put("mail.imaps.auth.login.disable", "true"); props.put("mail.imaps.auth.plain.disable", "true"); props.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY); props.setProperty("mail.imaps.socketFactory.fallback", "false"); props.setProperty("mail.imaps.socketFactory.port", port); props.setProperty("mail.imaps.starttls.enable", "true"); props.put("mail.debug", "true"); props.put("mail.debug.auth", "true"); Session session = Session.getInstance(props); session.setDebug(true); store = session.getStore("imaps"); log.info("OAUTH2 IMAP trying to connect with system properties to Host:" + host + ", Port: "+ port + ", userEmailId: " + userEmailId+ ", AccessToken: " + oauth2AccessToken); try { store.connect(host, userEmailId, oauth2AccessToken); log.info("IMAP connected with system properties to Host:" + host + ", Port: "+ port + ", userEmailId: " + userEmailId+ ", AccessToken: " + oauth2AccessToken); if(store.isConnected()){ log.info("Connection Established using imap protocol successfully !"); } } catch (Exception e) { log.error("Store.Connect failed with the errror: "+e.getMessage()); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String exceptionAsString = sw.toString(); log.error(exceptionAsString); } return store; } public void getEmailContents() throws Exception { Store store = null; String accessToken = getAccessTokenByClientCredentialGrant(); String emailId = "<email which needs to be read>"; try { store = connect(emailId, accessToken ); } catch (Exception ex) { log.error("Exception in connecting to email " + ex.getMessage()); ex.printStackTrace(); } } A: it's little tricky (setting up OAUTH2 authentication on IMAP in our Azure AAD instance), but following https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth very carefully it should work. I can share an example using JAVA it works perfectly (https://github.com/victorgv/dev-notes/tree/main/Using%20IMAP%20with%20OAuth%202%20authenticate%20and%20Office%20365).
Microsoft outlook authentication oAuth2.0
We have a daemon application that makes IMAP connection to access mailbox of user. Earlier we were using plain authentication method of using email ID and password to establish IMAP connection. Now as Microsoft has blocked this type authentication process and introduced oAuth2.0. My question here I was able to establish IMAP connection with the user that falls inside my tenant. But I am unable to figure out that how it can be done if I need to access the mailbox of user that doesn't fall inside my tenant or need to access the mailbox of any personal outlook account.
[ "I tried to reproduce the same in my environment and got the below results:\nNote that, if you want to access the mailbox of user that doesn't fall inside your tenant or need to access the mailbox of any personal outlook account then you have to register a Multi-Tenant Azure AD Application like below:\n\nI created an Azure AD Multi-Tenant Application and granted the API Permissions:\n\nNow, I registered service principals in Exchange by using below commands:**\nConnect-ExchangeOnline -Organization TenantID\n\nNew-ServicePrincipal -AppId AppID -ServiceId ObjectID [-Organization OrganizationID]\nGet-ServicePrincipal | fl\n\n\nI granted service principal access to one mailbox :\nAdd-MailboxPermission -Identity \"USER@XXX.com\" -User \nServicePrincipal_ID> -AccessRights FullAccess\n\nTest-ApplicationAccessPolicy -Identity \"USER@XXX.com\" -AppId AppID\n\n\nI generated the access token via Postman for Multi-Tenant Application by using the parameters like below:\nhttps://login.microsoftonline.com/common/oauth2/v2.0/token\n\nclient_id:5f3068f5-a920-4d6d-9742-XXXXXX\nclient_secret:ESJ8Q~ShJVdlY2MhKicyTEApGdtZh*******\nscope:https://outlook.office365.com/.default\ngrant_type:client_credentials\n\n\nTo do the same in JAVA, you can refer the below sample code by user3206771 in this SO Thread :\npublic String getAccessTokenByClientCredentialGrant() { \n String accessToken = null;\n String clientId = \"CLIENTID\";\n String secret = \"CLIENTSECRET\";\n String authority = \"https://login.microsoftonline.com/common/oauth2/v2.0/token\";\n String scope = \"https://outlook.office365.com/.default\";\n log.info(\"Client ID : \"+clientId);\n log.info(\"Client Secret : \"+secret);\n log.info(\"Auth Server: \"+authority);\n log.info(\"Scope: \"+scope);\n try {\n ConfidentialClientApplication app = ConfidentialClientApplication.builder(\n clientId,\n ClientCredentialFactory.createFromSecret(secret))\n .authority(authority)\n .build(); \n \n ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(\n Collections.singleton(scope))\n .build();\n \n CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);\n IAuthenticationResult result = future.get();\n accessToken = result.accessToken();\n \n } catch(Exception e) {\n log.error(\"Exception in acquiring token: \"+e.getMessage());\n e.printStackTrace();\n }\n log.info(\"Access Token : \"+accessToken);\n return accessToken;\n}\npublic Store connect(String userEmailId, String oauth2AccessToken) throws Exception {\n String host = \"outlook.office365.com\";\n String port = \"993\";\n Store store = null;\n \n String SSL_FACTORY = \"javax.net.ssl.SSLSocketFactory\";\n Properties props= new Properties();\n props.put(\"mail.imaps.ssl.enable\", \"true\");\n props.put(\"mail.imaps.sasl.enable\", \"true\");\n props.put(\"mail.imaps.port\", port);\n props.put(\"mail.imaps.auth.mechanisms\", \"XOAUTH2\");\n props.put(\"mail.imaps.sasl.mechanisms\", \"XOAUTH2\");\n props.put(\"mail.imaps.auth.login.disable\", \"true\");\n props.put(\"mail.imaps.auth.plain.disable\", \"true\");\n props.setProperty(\"mail.imaps.socketFactory.class\", SSL_FACTORY);\n props.setProperty(\"mail.imaps.socketFactory.fallback\", \"false\");\n props.setProperty(\"mail.imaps.socketFactory.port\", port);\n props.setProperty(\"mail.imaps.starttls.enable\", \"true\");\n props.put(\"mail.debug\", \"true\");\n props.put(\"mail.debug.auth\", \"true\");\n Session session = Session.getInstance(props);\n session.setDebug(true);\n store = session.getStore(\"imaps\");\n log.info(\"OAUTH2 IMAP trying to connect with system properties to Host:\" + host + \", Port: \"+ port\n + \", userEmailId: \" + userEmailId+ \", AccessToken: \" + oauth2AccessToken);\n try {\n \n store.connect(host, userEmailId, oauth2AccessToken);\n log.info(\"IMAP connected with system properties to Host:\" + host + \", Port: \"+ port\n + \", userEmailId: \" + userEmailId+ \", AccessToken: \" + oauth2AccessToken);\n if(store.isConnected()){\n log.info(\"Connection Established using imap protocol successfully !\"); \n }\n } catch (Exception e) {\n log.error(\"Store.Connect failed with the errror: \"+e.getMessage());\n StringWriter sw = new StringWriter();\n e.printStackTrace(new PrintWriter(sw));\n String exceptionAsString = sw.toString();\n log.error(exceptionAsString);\n \n }\n return store;\n}\npublic void getEmailContents() throws Exception {\n Store store = null;\n String accessToken = getAccessTokenByClientCredentialGrant();\n String emailId = \"<email which needs to be read>\";\n try {\n store = connect(emailId, accessToken );\n } catch (Exception ex) {\n log.error(\"Exception in connecting to email \" + ex.getMessage());\n ex.printStackTrace();\n }\n }\n\n", "it's little tricky (setting up OAUTH2 authentication on IMAP in our Azure AAD instance), but following https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth very carefully it should work.\nI can share an example using JAVA it works perfectly (https://github.com/victorgv/dev-notes/tree/main/Using%20IMAP%20with%20OAuth%202%20authenticate%20and%20Office%20365).\n" ]
[ 0, 0 ]
[]
[]
[ "azure", "java", "microsoft_oauth", "oauth_2.0", "office365" ]
stackoverflow_0074431893_azure_java_microsoft_oauth_oauth_2.0_office365.txt
Q: Are Python coroutines stackless or stackful? I've seen conflicting views on whether Python coroutines (I primarily mean async/await) are stackless or stackful. Some sources say they're stackful: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2074r0.pdf 'Python coroutines are stackful.' How do coroutines in Python compare to those in Lua? Yes, Python coroutines are stackful, first-class and asymmetric. While others seem to imply they're stackless, e.g. https://gamelisp.rs/reference/coroutines.html GameLisp's coroutines follow the model set by Rust, Python, C# and C++. Our coroutines are "stackless" In general my understanding always was that any meaningful async/await implementation implies stackless coroutines, while stackful ones are basically fibers (userspace threads, often switched more or less cooperatively), like goroutines, Boost.Coroutine, apparently those in Lua etc. Is my understanding correct? Or do Python coroutines somehow fundamentally differ from those in say C++, and are stackful? Or do the authors of the source above mean different things? A: It seems that the sources are using different terminology and definitions for "stackful" and "stackless" coroutines. In the first source, "stackful" means that the coroutine has its own stack, which is separate from the calling function's stack. This allows the coroutine to have its own local variables and execution state, and to return to the calling function at a later time. In the second source, "stackless" means that the coroutine does not have its own stack, and instead shares the stack with the calling function. This means that the coroutine cannot return to the calling function at a later time, and must instead be resumed from the same point in the calling function's stack. So, both sources are correct, but they are talking about different aspects of coroutines. Python coroutines are stackful in the sense that they have their own stack, but they may also be considered stackless in the sense that they share the stack with the calling function.
Are Python coroutines stackless or stackful?
I've seen conflicting views on whether Python coroutines (I primarily mean async/await) are stackless or stackful. Some sources say they're stackful: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2074r0.pdf 'Python coroutines are stackful.' How do coroutines in Python compare to those in Lua? Yes, Python coroutines are stackful, first-class and asymmetric. While others seem to imply they're stackless, e.g. https://gamelisp.rs/reference/coroutines.html GameLisp's coroutines follow the model set by Rust, Python, C# and C++. Our coroutines are "stackless" In general my understanding always was that any meaningful async/await implementation implies stackless coroutines, while stackful ones are basically fibers (userspace threads, often switched more or less cooperatively), like goroutines, Boost.Coroutine, apparently those in Lua etc. Is my understanding correct? Or do Python coroutines somehow fundamentally differ from those in say C++, and are stackful? Or do the authors of the source above mean different things?
[ "It seems that the sources are using different terminology and definitions for \"stackful\" and \"stackless\" coroutines.\nIn the first source, \"stackful\" means that the coroutine has its own stack, which is separate from the calling function's stack. This allows the coroutine to have its own local variables and execution state, and to return to the calling function at a later time.\nIn the second source, \"stackless\" means that the coroutine does not have its own stack, and instead shares the stack with the calling function. This means that the coroutine cannot return to the calling function at a later time, and must instead be resumed from the same point in the calling function's stack.\nSo, both sources are correct, but they are talking about different aspects of coroutines. Python coroutines are stackful in the sense that they have their own stack, but they may also be considered stackless in the sense that they share the stack with the calling function.\n" ]
[ 0 ]
[]
[]
[ "coroutine", "python", "python_asyncio" ]
stackoverflow_0070339355_coroutine_python_python_asyncio.txt
Q: Why Riverpod provider goes into the loading state when there's already value? Minimum reproducible code: class FooPage extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final asyncValue = ref.watch(provider1); print('loading: ${asyncValue.isLoading}, value: ${asyncValue.valueOrNull}'); return Container(); } } final provider1 = StreamProvider<int>((ref) { final stream = ref.watch(provider2); return stream.maybeWhen( orElse: () => Stream.value(0), data: (x) { print('data = $x'); return Stream.value(x); }, ); }); final provider2 = StreamProvider<int>((ref) async* { await Future.delayed(Duration(seconds: 3)); yield 1; }); Output: flutter: loading: true, value: null // Why value != 0 flutter: loading: false, value: 0 // After 3 seconds... flutter: data = 1 flutter: loading: true, value: 0 // Why value != 1 flutter: loading: false, value: 1 There are two questions. When I have already provided a default value in orElse callback, then why the first line doesn't print that value instead of going in the loading state and printing null. Once I get the data after 3s, why does the provider print loading: true, value: 0? A: When a StreamProvider is first created, it will not have received any data from the stream yet, so its isLoading property will be true and its valueOrNull property will be null. This is why the first line of the output prints loading: loading: true, value: null. Once the stream emits data, the StreamProvider will update its valueOrNull property with the latest value from the stream. However, it is possible that the ConsumerWidget has not yet rebuilt to reflect this change. When the ConsumerWidget rebuilds, it will receive the latest value from the stream and print it. This is why the fourth line of the output prints loading: false, value: 1. The orElse callback is used to provide a default value for the StreamProvider when the stream has not emitted any data yet. It does not affect the StreamProvider after it has received data from the stream. This is why the second and fifth lines of the output print loading: false, value: 0. In summary, the StreamProvider will initially be in the loading state and have a null value until it receives data from the stream. Once it has received data, it will update its value to reflect the latest value from the stream, but this update may not be reflected in the ConsumerWidget until it rebuilds. The orElse callback only provides a default value for the StreamProvider when the stream has not emitted any data.
Why Riverpod provider goes into the loading state when there's already value?
Minimum reproducible code: class FooPage extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final asyncValue = ref.watch(provider1); print('loading: ${asyncValue.isLoading}, value: ${asyncValue.valueOrNull}'); return Container(); } } final provider1 = StreamProvider<int>((ref) { final stream = ref.watch(provider2); return stream.maybeWhen( orElse: () => Stream.value(0), data: (x) { print('data = $x'); return Stream.value(x); }, ); }); final provider2 = StreamProvider<int>((ref) async* { await Future.delayed(Duration(seconds: 3)); yield 1; }); Output: flutter: loading: true, value: null // Why value != 0 flutter: loading: false, value: 0 // After 3 seconds... flutter: data = 1 flutter: loading: true, value: 0 // Why value != 1 flutter: loading: false, value: 1 There are two questions. When I have already provided a default value in orElse callback, then why the first line doesn't print that value instead of going in the loading state and printing null. Once I get the data after 3s, why does the provider print loading: true, value: 0?
[ "When a StreamProvider is first created, it will not have received any data from the stream yet, so its isLoading property will be true and its valueOrNull property will be null. This is why the first line of the output prints loading: loading: true, value: null.\nOnce the stream emits data, the StreamProvider will update its valueOrNull property with the latest value from the stream. However, it is possible that the ConsumerWidget has not yet rebuilt to reflect this change. When the ConsumerWidget rebuilds, it will receive the latest value from the stream and print it. This is why the fourth line of the output prints loading: false, value: 1.\nThe orElse callback is used to provide a default value for the StreamProvider when the stream has not emitted any data yet. It does not affect the StreamProvider after it has received data from the stream. This is why the second and fifth lines of the output print loading: false, value: 0.\nIn summary, the StreamProvider will initially be in the loading state and have a null value until it receives data from the stream. Once it has received data, it will update its value to reflect the latest value from the stream, but this update may not be reflected in the ConsumerWidget until it rebuilds. The orElse callback only provides a default value for the StreamProvider when the stream has not emitted any data.\n" ]
[ 1 ]
[]
[]
[ "flutter", "flutter_riverpod", "riverpod" ]
stackoverflow_0074678470_flutter_flutter_riverpod_riverpod.txt
Q: Character too large for enclosing character literal type c++ I have a problem with my code. I see these errors in the following lines of code. for (int i = 0; i < strlen(string); i++) { encrypt_string[current_element] = string[i]; current_element++; if (string[i] == 'а' || string[i] == 'е' || string[i] == 'и' || string[i] == 'о' || string[i] == 'у' || string[i] == 'я' || string[i] == 'Я' || string[i] == 'ы' || string[i] == 'ё' || string[i] == 'ю' || string[i] == 'я' || string[i] == 'э' || string[i] == 'a' || string[i] == 'e' || string[i] == 'i' || string[i] == 'o' || string[i] == 'u' || string[i] == 'y') { encrypt_string[current_element] = 'л'; encrypt_string[current_element+1] = 'а'; current_element += 2; } } I tried to google on this topic, but the advice on the Internet does not help (Char_16T, Char_32T, ETC.). Perhaps this does not work with MacOS or Clang ++ compiler. How I can do it on Mac?
Character too large for enclosing character literal type c++
I have a problem with my code. I see these errors in the following lines of code. for (int i = 0; i < strlen(string); i++) { encrypt_string[current_element] = string[i]; current_element++; if (string[i] == 'а' || string[i] == 'е' || string[i] == 'и' || string[i] == 'о' || string[i] == 'у' || string[i] == 'я' || string[i] == 'Я' || string[i] == 'ы' || string[i] == 'ё' || string[i] == 'ю' || string[i] == 'я' || string[i] == 'э' || string[i] == 'a' || string[i] == 'e' || string[i] == 'i' || string[i] == 'o' || string[i] == 'u' || string[i] == 'y') { encrypt_string[current_element] = 'л'; encrypt_string[current_element+1] = 'а'; current_element += 2; } } I tried to google on this topic, but the advice on the Internet does not help (Char_16T, Char_32T, ETC.). Perhaps this does not work with MacOS or Clang ++ compiler. How I can do it on Mac?
[]
[]
[ "It looks like you are trying to use the strlen() function to get the length of a string in your code. The strlen() function is part of the C standard library and is not available in C++. In C++, you can use the std::string type and its .length() method to get the length of a string.\n#include <string>\n#include <iostream>\n\nint main() {\n std::string string = \"Hello, World!\";\n std::string encrypt_string = \"\";\n int current_element = 0;\n\n for (int i = 0; i < string.length(); i++) {\n encrypt_string += string[i];\n if (string[i] == 'а' || string[i] == 'е' || \n string[i] == 'и' || string[i] == 'о' || \n string[i] == 'у' || string[i] == 'я' || string[i] == 'Я' ||\n string[i] == 'ы' || string[i] == 'ё' || \n string[i] == 'ю' || string[i] == 'я' || \n string[i] == 'э' || string[i] == 'a' ||\n string[i] == 'e' || string[i] == 'i' || \n string[i] == 'o' || string[i] == 'u' || \n string[i] == 'y') {\n encrypt_string += \"ла\";\n }\n }\n\n std::cout << encrypt_string << std::endl;\n\n return 0;\n}\n\nIn this example, I used the += operator to concatenate new characters to the encrypt_string variable. This is a more concise and efficient way to add characters to a string in C++.\nI also removed the current_element variable, since it is not needed in this code.\n" ]
[ -3 ]
[ "c++", "macos" ]
stackoverflow_0074680590_c++_macos.txt
Q: Fibonacci series in C++ #include <iostream> using namespace std; int main() { int num1 = 0; int num2 = 1; int num_temp; int num_next = 1; int n; cin >> n; for (int i = 0; i < n; i++){ cout << num_next << " "; num_next = num1 + num2; num1 = num2; num_temp = num2; num2 = num_next - num1; num1 = num_temp; } return 0; } I have to output the first "n" fibonacci numbers however I think there is some problem in logic.. I can't find out what am I doing wrong. The first 3 or 4 elements are correct but then a problem occurs... EXPECTED: For n=9 0, 1, 1, 2, 3, 5, 8, 13, 21 Actual: 1 1 1 1 1 1 1 1 1 A: #include <iostream> using namespace std; int main() { int num1 = 0; int num2 = 1; int num_temp; int num_next = 1; int n; cin >> n; if (n>=1) cout << 0 << " "; if (n>=2) cout << 1 << " "; for (int i = 0; i < n-2; i++){ num_next = num1 + num2; cout << num_next << " "; num1 = num2; num2 = num_next; } cout << endl; return 0; } A: Try this instead. It's a bit of a different take but will get you there just the same. #include <iostream> using namespace std; int main() { int input(0), Alpha(0), Beta(1), Total(1); cout << "Please input a top number: "; cin >> input; for(int i = 0; i <= input; i++) { cout << Total << endl; Total = Alpha + Beta; Alpha = Beta; Beta = Total; } } A: The Fibonacci Sequence is {0, 1, 1, 2, 3, ... N - 1, N, 2N - 1}. In order to implement it, you need to have a N - 2 variable, and an N - 1 variable so that you can calculate N = (N - 2) + (N - 1): unsigned int count = 0; std::cin >> count; // assume count >= 2 unsigned int prev2 = 0; unsigned int prev1 = 1; std::cout << prev2 << " " << prev1 << " "; for (unsigned int i = 2; i < count; ++i) { unsigned int current = prev2 + prev1; prev2 = prev1; std::cout << current << " "; prev1 = current; } std::cout << std::endl; A: This is my version. It's more or less same as previous samples, but I wanted to show the use of ring buffer. // Study for algorithm that counts n:th fibonacci number // Fibonacci[1] == 1 and Fibonacci[2] == 1 (and Fibonacci[0] == 0) // Fibonacci[n] = Fibonacci[n-1] + Fibonacci[n-2] #include <cstdio> #include <iostream> #include <cstdlib> int main(int argc, const char* argv[]) { // not counting trivial Fibonacci[0] if(argc != 2 || atoi(argv[1]) < 1){ std::cout << "You must provide one argument. Integer > 0" << std::endl; return EXIT_SUCCESS; } // ring buffer to store previous two fibonacci numbers, index it with [i%2] // seeded with Fibonacci[1] and Fibonacci[2] // if you want to count really big fibonacci numbers, you have to make your own type for // buffer variable // this type overflows after [93] with my macbook unsigned long long int buffer[2]={ 1, 1 }; // n:th Fibonacci unsigned int fn = atoi(argv[1]); // count loop is used if seeked fibonacci number is gt 2 if(fn > 2){ for(unsigned int i = 2; i < fn; ++i){ buffer[i%2] = buffer[(i-1)%2] + buffer[(i-2)%2]; } } // Result will be send to cout std::cout << "Fibonacci[" << fn << "] is " << buffer[(fn-1)%2] << std::endl; return EXIT_SUCCESS; } A: #include <iostream> using std::cout; using std::cin; int main() { unsigned int a=0u, b=1u, n;//assuming n is a positive number. //otherwise make it int instead of unsigned //and check if it's negative cin >> n; if(n==0) {return 0;} if(n==1) {cout << a; return 0;} cout << a << " " << b << " "; for(unsigned int i=2u ; i<n; i++) { b = a + b; a = b - a; cout << b << " "; } return 0; } It puts the next value in 'b' by adding the last two values together. 'a' then gets the previous b value. assume a = 3 and b = 5. Then the new b will become 8, and 'a' will become 5. This is because it always sums the last two numbers to get the result of the next number. The next operation will sum 5 (current a) and 8(current b) and so on... A: #include<iostream.h> #include<conio.h> void main() { clrscr(); int arr[50],n,i; cout<<"Enter the no. of elements to be printed in fibonacci series : "; cin>>n; arr[0]=0;arr[1]=1; for(i=2;i<n;i++) { arr[i]=arr[i-1]+arr[i-2]; } cout<<"\nThe fibonacii series is : "<<endl; for(i=0;i<n;i++) { cout<<arr[i]<<"\t"; } getch(); } A: Stack overflow is, of course, a limitation of the recursive version. If that is not a problem, you may also wish to consider a templated version of recursive Fibonacci. #include <iostream> template <int N> int Fib(){ return Fib<N-1>() + Fib<N-2>(); } template <> int Fib<1>() { return 1; } template <> int Fib<0>() { return 1; } using namespace std; int main() { // For the 10th Fibbonacci number... cout << Fib<10>() << endl; return 0; } A: Well I have been looking for some recursive solution to do the same task, Mostly what people do is, they write a recursive function for finding nth Fibonacci number, and then in the main program, they run a loop n times, and call this recursive function with values 1 to n to get all the n Fibonacci numbers and print them, which is a big overhead. Here is a solution which does the same task but it calls recursive function only once for getting all up to n Fibonacci numbers, and stores them in an array, and then prints. Which is ((n-1)*(recursive call's overhead)) times faster than the one I mentioned earlier. Thumbs up if you find it helping :) #include<iostream> using namespace std; int *arr; int iter = 0; int len; int returnValue; void exist(int num, int arr[] ) /* this function checks if the Fibonacci number that recursive function have calcuated is already in the array or not, mean if it is already calculated by some other recursive call*/ { bool checkExistance = false; /* if this is true, means this Fibonacci number is already calculated and saved in array, so do not save it again*/ returnValue = num; for (int i = 0; i< len; i++) { if(arr[i]==num) { checkExistance = true; break; } } if(!checkExistance) { arr[iter]=num; iter++; } } int fibonacci(int n) { if (n==1) { exist(1,arr); return 1; } else if (n==2) { exist(1,arr); return 1; } else { exist((fibonacci(n-1)+fibonacci(n-2)),arr); return returnValue; } } int main() { int n; cout<<"Enter the number of Fibonacci you want to print: "; cin>>n; len = n; arr = new int[n]; fibonacci(n); arr[n-1] = 1; cout<<"1:\t"<<arr[n-1]<<endl; for (int i = 0; i< len-1; i++) { cout<<i+2<<":\t"<<arr[i]<<endl; } return 0; } A: #include <iostream> using namespace std; int main() { int num1 = 0, num2 = 1 , num_next = 1, n; cout << "enter a number: \n"; cin >> n; //for when a negative value is given while(n < 0) { cout << "ERROR\n"; cin >> n; } //when any positive number (above 1 is given) if (n > 0) { //to give the value of 0 without ruining the loop cout << num1 << " "; for (int i = 0; i < n; i++) { //the Fibonacci loop cout << num_next << " "; num_next = num1 + num2; num1 = num2; num2 = num_next; } } //for when 0 is the given value else if (n == 0) cout << n << " "; return 0; } A: Here's a solution without a temp variable: #include <iostream> using namespace std; int main() { int n0 = 0; int n1 = 1; int n; cout << "Prints first N in Fibonacci series. Please enter a number for N: "; cin >> n; for(int i = 0; i < n; i++) { cout << n0 << " "; n1 = n0 + n1; n0 = n1 - n0; } } Also a (tail) recursive solution: #include <iostream> using namespace std; void fib(int n, int n0, int n1) { if(n <= 0) { return; } else { cout << n0 << " "; fib(n-1, n1, n0 + n1); } } int main() { int n; cout << "Prints first N in Fibonacci series. Please enter a number for N: "; cin >> n; fib(n, 0, 1); } A: /* Author: Eric Gitangu Date: 07/29/2015 This program spits out the fibionacci sequence for the range of 32-bit numbers Assumption: all values are +ve ; unsigned int works here */ #include <iostream> #include <math.h> #define N pow(2.0,31.0) using namespace std; void fibionacci(unsigned int &fib, unsigned int &prevfib){ int temp = prevfib; prevfib = fib; fib += temp; } void main(){ int count = 0; unsigned int fib = 0u, prev = 1u; while(fib < N){ if( fib ==0 ){ fib = 0; cout<<" "<< fib++ <<" \n "; continue; } if( fib == 1 && count++ < 2 ){ fib = 1; cout<< fib <<" \n "; continue; } fibionacci(fib, prev); cout<< fib <<" \n "; } } A: So... Heres a solution to "If you want a specific sequence of the Fib." #include <iostream> using namespace std; int fibonacciSeq(int k) { int num1=1; int num2=1; int count; for(int i=0; i<k; i++) { if(i==1) count=1; else { count=num1+num2; num1=num2; num2=count; } } return count; } A: How about another look at a recursive solution: void fibonacci(int n1, int n2, int numCount) { --numCount; if (numCount > 0) { cout << n1 << ", "; fibonacci(n2, n1 + n2, numCount); } else cout << n1 << endl; } Then you could call it: enterint fNum; cout << "Enter a non negative number to print output fibonacci sequence: "; cin >> fNum; fibonacci(0, 1, fNum); Example of the output: A: Concise version: int n, a{0}, b{1}; std::cin >> n; while (n-- > 0) { std::cout << a << " "; std::tie(a, b) = std::make_tuple(b, a + b); } A: You can write a code generating a Fibonacci series avoiding the if-else statement that prints zero and one, avoiding printing them outside the loop and avoiding the 'temp' integer. You can do it by initializing the 'first' and 'second' variables with -1 and 1, so the sum between them will give you 0, which is the first organ of the series, and the loop will do the rest of the job. #include <iostream> using namespace std; int main() { int num, a = -1, b = 1; cout << "enter a number:" << endl; cin >> num; for (int i = 0 ; i <= num ; i++ ) { b += a; cout << b << " "; a = b - a; } cout << endl; return 0; } A: Fibonacci with do...while loop. #include <iostream> using namespace std; int main() { int n; cout << "Input fibonacci sequence length: "; cin >> n; int i = 1, fib0, fib1, fib2, sum = 0; fib0 = 0; fib1 = 1; fib2 = 1; do { i++; cout << fib0 << " "; sum = sum + fib0; fib1 = fib2; fib2 = fib0; fib0 = fib1 + fib2; } while (i <= n); cout << endl << endl; cout << "Sum of numbers are: " << sum << endl; return 0; }
Fibonacci series in C++
#include <iostream> using namespace std; int main() { int num1 = 0; int num2 = 1; int num_temp; int num_next = 1; int n; cin >> n; for (int i = 0; i < n; i++){ cout << num_next << " "; num_next = num1 + num2; num1 = num2; num_temp = num2; num2 = num_next - num1; num1 = num_temp; } return 0; } I have to output the first "n" fibonacci numbers however I think there is some problem in logic.. I can't find out what am I doing wrong. The first 3 or 4 elements are correct but then a problem occurs... EXPECTED: For n=9 0, 1, 1, 2, 3, 5, 8, 13, 21 Actual: 1 1 1 1 1 1 1 1 1
[ "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n int num1 = 0;\n int num2 = 1;\n int num_temp;\n int num_next = 1;\n int n;\n cin >> n;\n if (n>=1)\n cout << 0 << \" \";\n if (n>=2)\n cout << 1 << \" \";\n for (int i = 0; i < n-2; i++){\n num_next = num1 + num2;\n cout << num_next << \" \";\n num1 = num2;\n num2 = num_next;\n }\n cout << endl;\n return 0;\n}\n\n", "Try this instead. It's a bit of a different take but will get you there just the same.\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n int input(0), Alpha(0), Beta(1), Total(1); \n cout << \"Please input a top number: \"; \n cin >> input; \n\n for(int i = 0; i <= input; i++)\n {\n cout << Total << endl; \n Total = Alpha + Beta; \n Alpha = Beta;\n Beta = Total; \n }\n} \n\n", "The Fibonacci Sequence is {0, 1, 1, 2, 3, ... N - 1, N, 2N - 1}.\nIn order to implement it, you need to have a N - 2 variable, and an N - 1 variable so that you can calculate N = (N - 2) + (N - 1):\nunsigned int count = 0;\nstd::cin >> count;\n// assume count >= 2\nunsigned int prev2 = 0;\nunsigned int prev1 = 1;\n\nstd::cout << prev2 << \" \" << prev1 << \" \";\nfor (unsigned int i = 2; i < count; ++i)\n{\n unsigned int current = prev2 + prev1;\n prev2 = prev1;\n std::cout << current << \" \";\n prev1 = current; \n}\nstd::cout << std::endl;\n\n", "This is my version.\nIt's more or less same as previous samples, but I wanted to show the use of ring buffer.\n// Study for algorithm that counts n:th fibonacci number\n// Fibonacci[1] == 1 and Fibonacci[2] == 1 (and Fibonacci[0] == 0)\n// Fibonacci[n] = Fibonacci[n-1] + Fibonacci[n-2] \n\n#include <cstdio>\n#include <iostream>\n#include <cstdlib>\n\nint main(int argc, const char* argv[])\n{\n\n // not counting trivial Fibonacci[0]\n if(argc != 2 || atoi(argv[1]) < 1){\n std::cout << \"You must provide one argument. Integer > 0\" << std::endl;\n return EXIT_SUCCESS;\n }\n\n // ring buffer to store previous two fibonacci numbers, index it with [i%2]\n // seeded with Fibonacci[1] and Fibonacci[2]\n // if you want to count really big fibonacci numbers, you have to make your own type for\n // buffer variable\n // this type overflows after [93] with my macbook\n unsigned long long int buffer[2]={ 1, 1 };\n\n // n:th Fibonacci \n unsigned int fn = atoi(argv[1]);\n\n // count loop is used if seeked fibonacci number is gt 2 \n if(fn > 2){\n for(unsigned int i = 2; i < fn; ++i){ \n buffer[i%2] = buffer[(i-1)%2] + buffer[(i-2)%2];\n }\n }\n\n // Result will be send to cout \n std::cout << \"Fibonacci[\" << fn << \"] is \" << buffer[(fn-1)%2] << std::endl;\n return EXIT_SUCCESS;\n}\n\n", "#include <iostream>\nusing std::cout; using std::cin;\n\nint main()\n{\n unsigned int a=0u, b=1u, n;//assuming n is a positive number.\n //otherwise make it int instead of unsigned\n //and check if it's negative\n cin >> n;\n\n if(n==0)\n {return 0;}\n if(n==1)\n {cout << a; return 0;}\n cout << a << \" \" << b << \" \";\n for(unsigned int i=2u ; i<n; i++)\n {\n b = a + b;\n a = b - a;\n cout << b << \" \";\n }\n return 0;\n}\n\nIt puts the next value in 'b' by adding the last two values together. 'a' then gets the previous b value. assume a = 3 and b = 5. Then the new b will become 8, and 'a' will become 5. This is because it always sums the last two numbers to get the result of the next number. The next operation will sum 5 (current a) and 8(current b) and so on...\n", "#include<iostream.h>\n#include<conio.h>\n\nvoid main()\n{ \n clrscr();\n int arr[50],n,i;\n cout<<\"Enter the no. of elements to be printed in fibonacci series : \";\n cin>>n;\n arr[0]=0;arr[1]=1;\n for(i=2;i<n;i++)\n { \n arr[i]=arr[i-1]+arr[i-2]; \n }\n cout<<\"\\nThe fibonacii series is : \"<<endl;\n for(i=0;i<n;i++)\n {\n cout<<arr[i]<<\"\\t\"; \n }\n getch();\n}\n\n", "Stack overflow is, of course, a limitation of the recursive version. If that is not a problem, you may also wish to consider a templated version of recursive Fibonacci.\n#include <iostream>\n\ntemplate <int N> int Fib(){ return Fib<N-1>() + Fib<N-2>(); }\ntemplate <> int Fib<1>() { return 1; }\ntemplate <> int Fib<0>() { return 1; }\n\nusing namespace std;\nint main()\n{\n // For the 10th Fibbonacci number...\n cout << Fib<10>() << endl;\n return 0;\n}\n\n", "Well I have been looking for some recursive solution to do the same task, Mostly what people do is, they write a recursive function for finding nth Fibonacci number, and then in the main program, they run a loop n times, and call this recursive function with values 1 to n to get all the n Fibonacci numbers and print them, which is a big overhead.\nHere is a solution which does the same task but it calls recursive function only once for getting all up to n Fibonacci numbers, and stores them in an array, and then prints. Which is ((n-1)*(recursive call's overhead)) times faster than the one I mentioned earlier. Thumbs up if you find it helping :)\n#include<iostream>\nusing namespace std;\nint *arr;\nint iter = 0;\nint len;\nint returnValue;\nvoid exist(int num, int arr[] ) /* this function checks if the Fibonacci number that recursive function have calcuated is already in the array or not, mean if it is already calculated by some other recursive call*/\n{\n bool checkExistance = false; /* if this is true, means this Fibonacci number is already calculated and saved in array, so do not save it again*/\n returnValue = num;\n for (int i = 0; i< len; i++)\n {\n if(arr[i]==num)\n {\n checkExistance = true;\n break;\n }\n }\n if(!checkExistance)\n {\n arr[iter]=num;\n iter++;\n }\n}\nint fibonacci(int n)\n{ \n if (n==1)\n {\n exist(1,arr);\n return 1;\n } \n else if (n==2)\n {\n exist(1,arr);\n return 1;\n }\n else\n {\n exist((fibonacci(n-1)+fibonacci(n-2)),arr);\n return returnValue;\n }\n}\nint main()\n{\n int n;\n cout<<\"Enter the number of Fibonacci you want to print: \";\n cin>>n;\n len = n;\n arr = new int[n];\n fibonacci(n);\n arr[n-1] = 1;\n cout<<\"1:\\t\"<<arr[n-1]<<endl;\n for (int i = 0; i< len-1; i++)\n {\n cout<<i+2<<\":\\t\"<<arr[i]<<endl;\n }\n return 0;\n}\n\n", "#include <iostream>\n\nusing namespace std;\n\nint main()\n\n{\n\n int num1 = 0, num2 = 1 , num_next = 1, n;\n\n cout << \"enter a number: \\n\";\n cin >> n;\n //for when a negative value is given\n while(n < 0)\n {\n cout << \"ERROR\\n\";\n cin >> n;\n }\n //when any positive number (above 1 is given)\n if (n > 0)\n {\n //to give the value of 0 without ruining the loop\n cout << num1 << \" \";\n for (int i = 0; i < n; i++)\n {\n //the Fibonacci loop\n cout << num_next << \" \";\n num_next = num1 + num2;\n num1 = num2;\n num2 = num_next;\n }\n }\n //for when 0 is the given value\n else if (n == 0)\n cout << n << \" \";\n return 0;\n}\n\n", "Here's a solution without a temp variable:\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n int n0 = 0;\n int n1 = 1;\n int n;\n\n cout << \"Prints first N in Fibonacci series. Please enter a number for N: \";\n cin >> n;\n\n for(int i = 0; i < n; i++) {\n cout << n0 << \" \";\n n1 = n0 + n1;\n n0 = n1 - n0;\n }\n}\n\nAlso a (tail) recursive solution:\n#include <iostream>\nusing namespace std;\n\nvoid fib(int n, int n0, int n1) {\n if(n <= 0) {\n return;\n } else {\n cout << n0 << \" \";\n fib(n-1, n1, n0 + n1);\n }\n}\n\nint main()\n{\n int n;\n\n cout << \"Prints first N in Fibonacci series. Please enter a number for N: \";\n cin >> n;\n\n fib(n, 0, 1);\n}\n\n", "/* Author: Eric Gitangu\n Date: 07/29/2015\n This program spits out the fibionacci sequence for the range of 32-bit numbers\n Assumption: all values are +ve ; unsigned int works here\n*/\n#include <iostream>\n#include <math.h>\n#define N pow(2.0,31.0)\n\nusing namespace std;\n\nvoid fibionacci(unsigned int &fib, unsigned int &prevfib){\n int temp = prevfib;\n prevfib = fib;\n fib += temp;\n}\nvoid main(){\n int count = 0;\n unsigned int fib = 0u, prev = 1u;\n\n while(fib < N){\n if( fib ==0 ){\n fib = 0;\n cout<<\" \"<< fib++ <<\" \\n \";\n continue;\n }\n if( fib == 1 && count++ < 2 ){\n fib = 1;\n cout<< fib <<\" \\n \";\n continue;\n }\n fibionacci(fib, prev);\n cout<< fib <<\" \\n \";\n }\n}\n\n", "So... Heres a solution to \"If you want a specific sequence of the Fib.\"\n#include <iostream>\nusing namespace std;\nint fibonacciSeq(int k)\n{\n int num1=1;\n int num2=1;\n int count;\n for(int i=0; i<k; i++)\n {\n if(i==1)\n count=1;\n else\n {\n count=num1+num2;\n num1=num2;\n num2=count;\n }\n }\n return count;\n}\n\n", "How about another look at a recursive solution:\nvoid fibonacci(int n1, int n2, int numCount)\n{\n --numCount;\n\n if (numCount > 0)\n {\n cout << n1 << \", \";\n fibonacci(n2, n1 + n2, numCount);\n }\n else\n cout << n1 << endl;\n}\n\nThen you could call it:\nenterint fNum;\ncout << \"Enter a non negative number to print output fibonacci sequence: \";\ncin >> fNum;\n\nfibonacci(0, 1, fNum);\n\nExample of the output:\n\n", "Concise version:\nint n, a{0}, b{1};\nstd::cin >> n;\nwhile (n-- > 0) {\n std::cout << a << \" \";\n std::tie(a, b) = std::make_tuple(b, a + b);\n}\n\n", "You can write a code generating a Fibonacci series avoiding the if-else statement that prints zero and one, avoiding printing them outside the loop and avoiding the 'temp' integer. You can do it by initializing the 'first' and 'second' variables with -1 and 1, so the sum between them will give you 0, which is the first organ of the series, and the loop will do the rest of the job.\n#include <iostream>\n\nusing namespace std;\nint main()\n{\n int num, a = -1, b = 1; \n cout << \"enter a number:\" << endl;\n cin >> num;\n for (int i = 0 ; i <= num ; i++ ) \n {\n b += a; \n cout << b << \" \"; \n a = b - a;\n }\n cout << endl;\n return 0;\n}\n\n", "Fibonacci with do...while loop.\n#include <iostream>\nusing namespace std;\n\nint main() {\n\n int n;\n cout << \"Input fibonacci sequence length: \";\n cin >> n;\n\n int i = 1, fib0, fib1, fib2, sum = 0;\n fib0 = 0;\n fib1 = 1;\n fib2 = 1;\n\n do {\n i++;\n cout << fib0 << \" \";\n sum = sum + fib0;\n fib1 = fib2;\n fib2 = fib0;\n fib0 = fib1 + fib2;\n }\n while (i <= n);\n cout << endl << endl;\n cout << \"Sum of numbers are: \" << sum << endl;\n\n return 0;\n}\n\n" ]
[ 7, 3, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "c++", "fibonacci" ]
stackoverflow_0019718677_c++_fibonacci.txt
Q: Python JSON -> CSV different headers I have a json file that is like so: {"16CD7631-0ED0-4DA0-8D3B-8BBB41992EED": {"id": "16CD7631-0ED0-4DA0-8D3B-8BBB41992EED", "longitude": "-122.406417", "reportType": "Other", "latitude": "37.785834"}, "91CA4A9C-9A48-41A2-8453-07CBC8DC723E": {"id": "91CA4A9C-9A48-41A2-8453-07CBC8DC723E", "longitude": "-1.1932383", "reportType": "Street Obstruction", "latitude": "45.8827419"}} The goal is to get this to turn into a csv file like so: id,longitude,reportType,latitude 16CD7631-0ED0-4DA0-8D3B-8BBB41992EED,-122.406417,Other,37.785834 91CA4A9C-9A48-41A2-8453-07CBC8DC723E,-1.1932383,Street Obstruction,45.8827419 I tried just doing with open('sample.json', encoding='utf-8') as inputfile: df = pd.read_json(inputfile) df.to_csv('csvfile.csv', encoding='utf-8', index=False) But because the name of each document was named its id, I get incorrect output. What is the best way to achieve my goal? Thanks A: You can use pandas.json_normalize. Try this : import json import pandas as pd with open('sample.json', encoding='utf-8') as inputfile: data = json.load(inputfile) df = pd.json_normalize(data[k] for k in data.keys()) # Output : print(df.to_string()) id longitude reportType latitude 0 16CD7631-0ED0-4DA0-8D3B-8BBB41992EED -122.406417 Other 37.785834 1 91CA4A9C-9A48-41A2-8453-07CBC8DC723E -1.1932383 Street Obstruction 45.8827419
Python JSON -> CSV different headers
I have a json file that is like so: {"16CD7631-0ED0-4DA0-8D3B-8BBB41992EED": {"id": "16CD7631-0ED0-4DA0-8D3B-8BBB41992EED", "longitude": "-122.406417", "reportType": "Other", "latitude": "37.785834"}, "91CA4A9C-9A48-41A2-8453-07CBC8DC723E": {"id": "91CA4A9C-9A48-41A2-8453-07CBC8DC723E", "longitude": "-1.1932383", "reportType": "Street Obstruction", "latitude": "45.8827419"}} The goal is to get this to turn into a csv file like so: id,longitude,reportType,latitude 16CD7631-0ED0-4DA0-8D3B-8BBB41992EED,-122.406417,Other,37.785834 91CA4A9C-9A48-41A2-8453-07CBC8DC723E,-1.1932383,Street Obstruction,45.8827419 I tried just doing with open('sample.json', encoding='utf-8') as inputfile: df = pd.read_json(inputfile) df.to_csv('csvfile.csv', encoding='utf-8', index=False) But because the name of each document was named its id, I get incorrect output. What is the best way to achieve my goal? Thanks
[ "You can use pandas.json_normalize.\nTry this :\nimport json\nimport pandas as pd\n\nwith open('sample.json', encoding='utf-8') as inputfile:\n data = json.load(inputfile)\n df = pd.json_normalize(data[k] for k in data.keys())\n\n# Output :\nprint(df.to_string())\n\n id longitude reportType latitude\n0 16CD7631-0ED0-4DA0-8D3B-8BBB41992EED -122.406417 Other 37.785834\n1 91CA4A9C-9A48-41A2-8453-07CBC8DC723E -1.1932383 Street Obstruction 45.8827419\n\n" ]
[ 0 ]
[]
[]
[ "csv", "json", "pandas", "python" ]
stackoverflow_0074680602_csv_json_pandas_python.txt
Q: Getting error while building Android app with React Native: The minCompileSdk (31) specified in a dependency's AAR metadata I am trying to build react native project but I got an error when running npm run android > A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction > The minCompileSdk (31) specified in a dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) is greater than this module's compileSdkVersion (android-30). Dependency: androidx.appcompat:appcompat:1.4.1. Already gone through all the solution mentioned on this, this, this, and this but could not solve it. android/build.gradle // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { buildToolsVersion = "30.0.2" minSdkVersion = 21 compileSdkVersion = 30 targetSdkVersion = 30 ndkVersion = "21.4.7075529" } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle:4.2.2") // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath 'com.google.gms:google-services:4.3.10' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1' } } allprojects { repositories { jcenter() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url("$rootDir/../node_modules/react-native/android") } maven { // Android JSC is installed from npm url("$rootDir/../node_modules/jsc-android/dist") } mavenCentral { // We don't want to fetch react-native from Maven Central as there are // older versions over there. content { excludeGroup "com.facebook.react" } } google() maven { url 'https://www.jitpack.io' } } } app/build.gradle dependencies dependencies { implementation 'androidx.multidex:multidex:2.0.1' implementation fileTree(dir: "libs", include: ["*.jar"]) //noinspection GradleDynamicVersion implementation "com.facebook.react:react-native:+" // From node_modules implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") { exclude group:'com.facebook.fbjni' } debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' exclude group:'com.squareup.okhttp3', module:'okhttp' } debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' } if (enableHermes) { def hermesPath = "../../node_modules/hermes-engine/android/"; debugImplementation files(hermesPath + "hermes-debug.aar") releaseImplementation files(hermesPath + "hermes-release.aar") } else { implementation jscFlavor } } Let me know if anyone require any additional information. A: Updated the compileSdkVersion & targetSdkVersion to 31 and added kotlinVersion = "1.7.20" in android/build.gradle kotlinVersion = "1.7.20" buildToolsVersion = "30.0.2" minSdkVersion = 21 compileSdkVersion = 31 targetSdkVersion = 31 ndkVersion = "21.4.7075529" You may have to specify REACT_NATIVE_VERSION so add these changes in android/build.gradle def REACT_NATIVE_VERSION = new File(['node', '--print',"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim()) allprojects { configurations.all { resolutionStrategy { force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION } } Add the android:exported="true" in Androidmanifest.xml in .MainActivity tag like this <activity android:name=".MainActivity" android:label="@string/app_name" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize" android:screenOrientation="portrait" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode" android:exported="true"> Anyone who still faces any issues comment on this answer, I will try my best to help you.
Getting error while building Android app with React Native: The minCompileSdk (31) specified in a dependency's AAR metadata
I am trying to build react native project but I got an error when running npm run android > A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction > The minCompileSdk (31) specified in a dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) is greater than this module's compileSdkVersion (android-30). Dependency: androidx.appcompat:appcompat:1.4.1. Already gone through all the solution mentioned on this, this, this, and this but could not solve it. android/build.gradle // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { buildToolsVersion = "30.0.2" minSdkVersion = 21 compileSdkVersion = 30 targetSdkVersion = 30 ndkVersion = "21.4.7075529" } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle:4.2.2") // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath 'com.google.gms:google-services:4.3.10' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1' } } allprojects { repositories { jcenter() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url("$rootDir/../node_modules/react-native/android") } maven { // Android JSC is installed from npm url("$rootDir/../node_modules/jsc-android/dist") } mavenCentral { // We don't want to fetch react-native from Maven Central as there are // older versions over there. content { excludeGroup "com.facebook.react" } } google() maven { url 'https://www.jitpack.io' } } } app/build.gradle dependencies dependencies { implementation 'androidx.multidex:multidex:2.0.1' implementation fileTree(dir: "libs", include: ["*.jar"]) //noinspection GradleDynamicVersion implementation "com.facebook.react:react-native:+" // From node_modules implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") { exclude group:'com.facebook.fbjni' } debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' exclude group:'com.squareup.okhttp3', module:'okhttp' } debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' } if (enableHermes) { def hermesPath = "../../node_modules/hermes-engine/android/"; debugImplementation files(hermesPath + "hermes-debug.aar") releaseImplementation files(hermesPath + "hermes-release.aar") } else { implementation jscFlavor } } Let me know if anyone require any additional information.
[ "Updated the compileSdkVersion & targetSdkVersion to 31 and added kotlinVersion = \"1.7.20\" in android/build.gradle\nkotlinVersion = \"1.7.20\"\nbuildToolsVersion = \"30.0.2\"\nminSdkVersion = 21\ncompileSdkVersion = 31\ntargetSdkVersion = 31\nndkVersion = \"21.4.7075529\"\n\nYou may have to specify REACT_NATIVE_VERSION so add these changes in android/build.gradle\ndef REACT_NATIVE_VERSION = new File(['node', '--print',\"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version\"].execute(null, rootDir).text.trim())\nallprojects {\n configurations.all {\n resolutionStrategy {\n force \"com.facebook.react:react-native:\" + REACT_NATIVE_VERSION\n }\n }\n\nAdd the android:exported=\"true\" in Androidmanifest.xml in .MainActivity tag like this\n<activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\"\n android:launchMode=\"singleTask\"\n android:windowSoftInputMode=\"adjustResize\"\n android:screenOrientation=\"portrait\"\n android:configChanges=\"keyboard|keyboardHidden|orientation|screenSize|uiMode\"\n android:exported=\"true\">\n\nAnyone who still faces any issues comment on this answer, I will try my best to help you.\n" ]
[ 0 ]
[]
[]
[ "android", "build.gradle", "react_native" ]
stackoverflow_0074620132_android_build.gradle_react_native.txt
Q: Graph BFS Traversal - C++ Given an undirected and disconnected graph G(V, E), print its BFS traversal. Here you need to consider that you need to print BFS path starting from vertex 0 only. V is the number of vertices present in graph G and vertices are numbered from 0 to V-1. E is the number of edges present in graph G. Note : 1. Take graph input in the adjacency matrix. 2. Handle for Disconnected Graphs as well Input Format : Line 1: Two Integers V and E (separated by space) Next 'E' lines, each have two space-separated integers, 'a' and 'b', denoting that there exists an edge between Vertex 'a' and Vertex 'b'. Output Format : BFS Traversal (separated by space) Constraints : 2 <= V <= 1000 1 <= E <= 1000 Sample Input 1: 4 4 0 1 0 3 1 2 2 3 Sample Output 1: 0 1 3 2 Please tell what is wrong in the code. Here is the code: #include <iostream> using namespace std; #include <queue> void print(int** edges, int V, int sv, bool* visited){ queue<int> pq; pq.push(sv); visited[sv] = true; while(!pq.empty()){ int ans = pq.front(); cout << ans << " "; pq.pop(); for(int i = 0; i < V; i++){ if(ans == i){ continue; } if(edges[ans][i] == 1 && !visited[i]){ pq.push(i); visited[i] = true; } } } } void BFS(int** edges, int V){ bool* visited = new bool[V]; for(int i = 0; i < V; i++){ visited[i] = false; } for(int i = 0; i < V; i++){ if(!visited[i]){ print(edges, V, i, visited); } } delete [] visited; } int main() { int V, E; cin >> V >> E; int**edges = new int*[V]; for(int i = 0; i < V; i++){ edges[i] = new int[V]; for(int j = 0; j < V; j++){ edges[i][j] = 0; } } for(int i = 0; i < E; i++){ int f, s; cin >> f >> s; edges[f][s] == 1; edges[s][f] == 1; } BFS(edges, V); for(int i = 0; i < V; i++){ delete [] edges[i]; } delete [] edges; /* Write Your Code Here Complete the Rest of the Program You have to take input and print the output yourself */ } A: I think the only problem is a tiny mistake I see in the part you read params from command line. The algorithm itself looks good. You need to use assignment operator = instead of comparison operator == when read edges: edges[f][s] = 1; edges[s][f] = 1;
Graph BFS Traversal - C++
Given an undirected and disconnected graph G(V, E), print its BFS traversal. Here you need to consider that you need to print BFS path starting from vertex 0 only. V is the number of vertices present in graph G and vertices are numbered from 0 to V-1. E is the number of edges present in graph G. Note : 1. Take graph input in the adjacency matrix. 2. Handle for Disconnected Graphs as well Input Format : Line 1: Two Integers V and E (separated by space) Next 'E' lines, each have two space-separated integers, 'a' and 'b', denoting that there exists an edge between Vertex 'a' and Vertex 'b'. Output Format : BFS Traversal (separated by space) Constraints : 2 <= V <= 1000 1 <= E <= 1000 Sample Input 1: 4 4 0 1 0 3 1 2 2 3 Sample Output 1: 0 1 3 2 Please tell what is wrong in the code. Here is the code: #include <iostream> using namespace std; #include <queue> void print(int** edges, int V, int sv, bool* visited){ queue<int> pq; pq.push(sv); visited[sv] = true; while(!pq.empty()){ int ans = pq.front(); cout << ans << " "; pq.pop(); for(int i = 0; i < V; i++){ if(ans == i){ continue; } if(edges[ans][i] == 1 && !visited[i]){ pq.push(i); visited[i] = true; } } } } void BFS(int** edges, int V){ bool* visited = new bool[V]; for(int i = 0; i < V; i++){ visited[i] = false; } for(int i = 0; i < V; i++){ if(!visited[i]){ print(edges, V, i, visited); } } delete [] visited; } int main() { int V, E; cin >> V >> E; int**edges = new int*[V]; for(int i = 0; i < V; i++){ edges[i] = new int[V]; for(int j = 0; j < V; j++){ edges[i][j] = 0; } } for(int i = 0; i < E; i++){ int f, s; cin >> f >> s; edges[f][s] == 1; edges[s][f] == 1; } BFS(edges, V); for(int i = 0; i < V; i++){ delete [] edges[i]; } delete [] edges; /* Write Your Code Here Complete the Rest of the Program You have to take input and print the output yourself */ }
[ "I think the only problem is a tiny mistake I see in the part you read params from command line. The algorithm itself looks good.\nYou need to use assignment operator = instead of comparison operator == when read edges:\nedges[f][s] = 1;\nedges[s][f] = 1;\n\n" ]
[ 0 ]
[]
[]
[ "breadth_first_search", "c++", "data_structures", "graph" ]
stackoverflow_0061558819_breadth_first_search_c++_data_structures_graph.txt
Q: xcodebuild -create-xcframework - BCSymbolMaps missing - on M1 Xcode 14.0 I use the same bash script for building the XCFramework for at least 2 years and everything worked successfully until the moment I switched my Mac to M1 and my Xcode is 14.0. The script is pretty standard (see below). On MacPro M1, Xcode 14.0 I get the following error (the same script works just fine on Xcode 13.1). error: the path does not point to a valid debug symbols file: /Users/*******/build/Release-iphoneos.xcarchive/BCSymbolMaps/* Indeed when I look at build/Release-iphoneos.xcarchive folder - the BCSymbolMaps is not there. I verified that the Xcode setting "debug information format" is dwarf with dsym file. Can someone please help me understand what is this error? and why it started happening on M1, Xcode 14.0 ? Thank you See my bash build script below. # Build the framework for device and for simulator (using # all needed architectures). xcodebuild archive -scheme "${TARGET_NAME}" -destination="iOS" -sdk iphonesimulator SKIP_INSTALL=NO BUILD_LIBRARIES_FOR_DISTRIBUTION=YES -archivePath "${SRCROOT}/build/Release-iphonesimulator" xcodebuild archive -scheme "${TARGET_NAME}" -destination="iOS" -sdk iphoneos SKIP_INSTALL=NO BUILD_LIBRARIES_FOR_DISTRIBUTION=YES -archivePath "${SRCROOT}/build/Release-iphoneos" ls -l "${SRCROOT}/build/" # https://developer.apple.com/forums/thread/655768 # First, get all the UUID filepaths for BCSymbolMaps, because these are randomly generated and need to be individually added as the `-debug-symbols` parameter. The dSYM path is always the same so that one is manually added echo "XCFramework: Generating IPHONE BCSymbolMap paths..." IPHONE_BCSYMBOLMAP_PATHS=(${SRCROOT}/build/Release-iphoneos.xcarchive/BCSymbolMaps/*) IPHONE_BCSYMBOLMAP_COMMANDS="" for path in "${IPHONE_BCSYMBOLMAP_PATHS[@]}"; do IPHONE_BCSYMBOLMAP_COMMANDS="$IPHONE_BCSYMBOLMAP_COMMANDS -debug-symbols $path " echo $IPHONE_BCSYMBOLMAP_COMMANDS done echo "XCFramework: Generating IPHONE BCSymbolMap paths... --> Done" # XCFramework with debug symbols - see https://pspdfkit.com/blog/2021/advances-in-xcframeworks/#built-in-support-for-bcsymbolmaps-and-dsyms xcodebuild -create-xcframework -allow-internal-distribution \ -framework "${SRCROOT}/build/Release-iphoneos.xcarchive/Products/Library/Frameworks/${FRAMEWORK_NAME}.framework" \ -debug-symbols "${SRCROOT}/build/Release-iphoneos.xcarchive/dSYMs/${FRAMEWORK_NAME}.framework.dSYM" \ $IPHONE_BCSYMBOLMAP_COMMANDS \ -framework "${SRCROOT}/build/Release-iphonesimulator.xcarchive/Products/Library/Frameworks/${FRAMEWORK_NAME}.framework" \ -debug-symbols "${SRCROOT}/build/Release-iphonesimulator.xcarchive/dSYMs/${FRAMEWORK_NAME}.framework.dSYM" \ -output "${SF_RELEASE_DIR}/${FRAMEWORK_NAME}.xcframework" A: It appears that the error you are seeing is caused by a change in the way that Xcode 14 handles debug symbols when creating XCFrameworks. In previous versions of Xcode, the BCSymbolMaps directory containing debug symbol information was included in the generated XCFramework, but in Xcode 14 this information is not included by default. To fix this error, I think you will need to add the -include-bcsymbolmaps flag to the xcodebuild command when creating the XCFramework. This will tell Xcode to include the BCSymbolMaps directory in the generated XCFramework, and the error should no longer occur.
xcodebuild -create-xcframework - BCSymbolMaps missing - on M1 Xcode 14.0
I use the same bash script for building the XCFramework for at least 2 years and everything worked successfully until the moment I switched my Mac to M1 and my Xcode is 14.0. The script is pretty standard (see below). On MacPro M1, Xcode 14.0 I get the following error (the same script works just fine on Xcode 13.1). error: the path does not point to a valid debug symbols file: /Users/*******/build/Release-iphoneos.xcarchive/BCSymbolMaps/* Indeed when I look at build/Release-iphoneos.xcarchive folder - the BCSymbolMaps is not there. I verified that the Xcode setting "debug information format" is dwarf with dsym file. Can someone please help me understand what is this error? and why it started happening on M1, Xcode 14.0 ? Thank you See my bash build script below. # Build the framework for device and for simulator (using # all needed architectures). xcodebuild archive -scheme "${TARGET_NAME}" -destination="iOS" -sdk iphonesimulator SKIP_INSTALL=NO BUILD_LIBRARIES_FOR_DISTRIBUTION=YES -archivePath "${SRCROOT}/build/Release-iphonesimulator" xcodebuild archive -scheme "${TARGET_NAME}" -destination="iOS" -sdk iphoneos SKIP_INSTALL=NO BUILD_LIBRARIES_FOR_DISTRIBUTION=YES -archivePath "${SRCROOT}/build/Release-iphoneos" ls -l "${SRCROOT}/build/" # https://developer.apple.com/forums/thread/655768 # First, get all the UUID filepaths for BCSymbolMaps, because these are randomly generated and need to be individually added as the `-debug-symbols` parameter. The dSYM path is always the same so that one is manually added echo "XCFramework: Generating IPHONE BCSymbolMap paths..." IPHONE_BCSYMBOLMAP_PATHS=(${SRCROOT}/build/Release-iphoneos.xcarchive/BCSymbolMaps/*) IPHONE_BCSYMBOLMAP_COMMANDS="" for path in "${IPHONE_BCSYMBOLMAP_PATHS[@]}"; do IPHONE_BCSYMBOLMAP_COMMANDS="$IPHONE_BCSYMBOLMAP_COMMANDS -debug-symbols $path " echo $IPHONE_BCSYMBOLMAP_COMMANDS done echo "XCFramework: Generating IPHONE BCSymbolMap paths... --> Done" # XCFramework with debug symbols - see https://pspdfkit.com/blog/2021/advances-in-xcframeworks/#built-in-support-for-bcsymbolmaps-and-dsyms xcodebuild -create-xcframework -allow-internal-distribution \ -framework "${SRCROOT}/build/Release-iphoneos.xcarchive/Products/Library/Frameworks/${FRAMEWORK_NAME}.framework" \ -debug-symbols "${SRCROOT}/build/Release-iphoneos.xcarchive/dSYMs/${FRAMEWORK_NAME}.framework.dSYM" \ $IPHONE_BCSYMBOLMAP_COMMANDS \ -framework "${SRCROOT}/build/Release-iphonesimulator.xcarchive/Products/Library/Frameworks/${FRAMEWORK_NAME}.framework" \ -debug-symbols "${SRCROOT}/build/Release-iphonesimulator.xcarchive/dSYMs/${FRAMEWORK_NAME}.framework.dSYM" \ -output "${SF_RELEASE_DIR}/${FRAMEWORK_NAME}.xcframework"
[ "It appears that the error you are seeing is caused by a change in the way that Xcode 14 handles debug symbols when creating XCFrameworks. In previous versions of Xcode, the BCSymbolMaps directory containing debug symbol information was included in the generated XCFramework, but in Xcode 14 this information is not included by default.\nTo fix this error, I think you will need to add the -include-bcsymbolmaps flag to the xcodebuild command when creating the XCFramework. This will tell Xcode to include the BCSymbolMaps directory in the generated XCFramework, and the error should no longer occur.\n" ]
[ 0 ]
[]
[]
[ "ios", "xcframework", "xcode", "xcodebuild" ]
stackoverflow_0074588213_ios_xcframework_xcode_xcodebuild.txt
Q: How can I extract specific text and link from div class using a BeautifulSoup I am trying to extract text and link from this website: https://www.rexelusa.com/s/terminal-block-end-stops?cat=61imhp2p In my code, I was trying to extract first output that is all CAT# numbers. This is my code: import selenium.webdriver from bs4 import BeautifulSoup from selenium.webdriver.firefox.options import Options options = Options() options.binary_location = r"C:\Program Files\Mozilla Firefox\firefox.exe" url = "https://www.rexelusa.com/s/terminal-block-end-stops?cat=61imhp2p" driver = selenium.webdriver.Firefox(options=options, executable_path='C:\webdrivers\geckodriver.exe') driver.get(url) soup = BeautifulSoup(driver.page_source,"html.parser") all_div = soup.find_all("div", class_= 'row no-gutters') #print(all_div) for div in all_div: all_items = div.find_all(class_= 'pr-4 col col-auto') for item in all_items: print(item) driver.quit() And my expected output is: all CAT# numbers(means total 92 will come in output) and category detail as shown in picture CAT #: 1492-EAJ35 Categories Control & Automation Terminal Blocks Terminal Blocks Accessories Terminal Block End Stops enter image description here A: #To extract the CAT# numbers and category details from the website, you can try using the requests and BeautifulSoup libraries. You can use the requests library to send an HTTP GET request to the URL, and then use the BeautifulSoup library to parse the HTML response and extract the data you want. #Here is an example of how you could do this: import requests from bs4 import BeautifulSoup url = "https://www.rexelusa.com/s/terminal-block-end-stops?cat=61imhp2p" # Send an HTTP GET request to the URL and get the response response = requests.get(url) # Parse the response HTML using BeautifulSoup soup = BeautifulSoup(response.text, "html.parser") # Extract the CAT# numbers from the response HTML cat_numbers = [x.text for x in soup.find_all("span", class_="c-black-text f-s-18 f-w-600")] # Print the CAT# numbers for cat_number in cat_numbers: print(cat_number) # Extract the category details from the response HTML category_details = [x.text for x in soup.find_all("div", class_="c-black-text f-s-12")] # Print the category details for category_detail in category_details: print(category_detail) #This code should extract the CAT# numbers and category details from the website and print them to the console. Note that you may need to modify the code to use the correct CSS classes for the elements you want to extract, as these may have changed since the original question was posted.
How can I extract specific text and link from div class using a BeautifulSoup
I am trying to extract text and link from this website: https://www.rexelusa.com/s/terminal-block-end-stops?cat=61imhp2p In my code, I was trying to extract first output that is all CAT# numbers. This is my code: import selenium.webdriver from bs4 import BeautifulSoup from selenium.webdriver.firefox.options import Options options = Options() options.binary_location = r"C:\Program Files\Mozilla Firefox\firefox.exe" url = "https://www.rexelusa.com/s/terminal-block-end-stops?cat=61imhp2p" driver = selenium.webdriver.Firefox(options=options, executable_path='C:\webdrivers\geckodriver.exe') driver.get(url) soup = BeautifulSoup(driver.page_source,"html.parser") all_div = soup.find_all("div", class_= 'row no-gutters') #print(all_div) for div in all_div: all_items = div.find_all(class_= 'pr-4 col col-auto') for item in all_items: print(item) driver.quit() And my expected output is: all CAT# numbers(means total 92 will come in output) and category detail as shown in picture CAT #: 1492-EAJ35 Categories Control & Automation Terminal Blocks Terminal Blocks Accessories Terminal Block End Stops enter image description here
[ "#To extract the CAT# numbers and category details from the website, you can try using the requests and BeautifulSoup libraries. You can use the requests library to send an HTTP GET request to the URL, and then use the BeautifulSoup library to parse the HTML response and extract the data you want.\n\n#Here is an example of how you could do this:\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.rexelusa.com/s/terminal-block-end-stops?cat=61imhp2p\"\n\n# Send an HTTP GET request to the URL and get the response\nresponse = requests.get(url)\n\n# Parse the response HTML using BeautifulSoup\nsoup = BeautifulSoup(response.text, \"html.parser\")\n\n# Extract the CAT# numbers from the response HTML\ncat_numbers = [x.text for x in soup.find_all(\"span\", class_=\"c-black-text f-s-18 f-w-600\")]\n\n# Print the CAT# numbers\nfor cat_number in cat_numbers:\n print(cat_number)\n\n# Extract the category details from the response HTML\ncategory_details = [x.text for x in soup.find_all(\"div\", class_=\"c-black-text f-s-12\")]\n\n# Print the category details\nfor category_detail in category_details:\n print(category_detail)\n\n#This code should extract the CAT# numbers and category details from the website and print them to the console. Note that you may need to modify the code to use the correct CSS classes for the elements you want to extract, as these may have changed since the original question was posted.\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "javascript", "python" ]
stackoverflow_0074680638_beautifulsoup_html_javascript_python.txt
Q: Bicep publish runbook using URI I am using Bicep to create an Automation Account, Blob storage, uploading a file to Blob, and then creating a Runbook inside my Automation Account. This works the first time, but if i update the file that goes into my blob, this isnt reflected in my runbook. Here is a copy of my runbook deployment - is it possible the publish link URI gets cached and it doesn't 'refetch' the script content? resource symbolicname 'Microsoft.Automation/automationAccounts/runbooks@2022-08-08' = { name: 'Schedule Summary Table Rebuild' location: automationAccount.location tags: _tags dependsOn: [deploymentScript] parent: automationAcc properties: { description: 'Automation to recreate summary tables.' logActivityTrace: 0 logProgress: true logVerbose: true runbookType: 'PowerShell7' publishContentLink: { uri:'https://storageacc.blob.core.windows.net/data/ExecuteSQL.txt' version:'1.0.0.0' } } }``` A: When you redeploy the template, nothing has changed so I'm guessing the ARM API doesn't even try to resubmit the deployment to the resource provider. You could add a parameter to try to force the update: param forceUpdate string = newGuid() ... resource symbolicname 'Microsoft.Automation/automationAccounts/runbooks@2022-08-08' = { name: 'Schedule Summary Table Rebuild' location: automationAccount.location tags: _tags dependsOn: [ deploymentScript ] parent: automationAcc properties: { description: 'Automation to recreate summary tables.' logActivityTrace: 0 logProgress: true logVerbose: true runbookType: 'PowerShell7' publishContentLink: { uri: 'https://storageacc.blob.core.windows.net/data/ExecuteSQL.txt?forceUpdate=${forceUpdate}' version: '1.0.0.0' } } } ...
Bicep publish runbook using URI
I am using Bicep to create an Automation Account, Blob storage, uploading a file to Blob, and then creating a Runbook inside my Automation Account. This works the first time, but if i update the file that goes into my blob, this isnt reflected in my runbook. Here is a copy of my runbook deployment - is it possible the publish link URI gets cached and it doesn't 'refetch' the script content? resource symbolicname 'Microsoft.Automation/automationAccounts/runbooks@2022-08-08' = { name: 'Schedule Summary Table Rebuild' location: automationAccount.location tags: _tags dependsOn: [deploymentScript] parent: automationAcc properties: { description: 'Automation to recreate summary tables.' logActivityTrace: 0 logProgress: true logVerbose: true runbookType: 'PowerShell7' publishContentLink: { uri:'https://storageacc.blob.core.windows.net/data/ExecuteSQL.txt' version:'1.0.0.0' } } }```
[ "When you redeploy the template, nothing has changed so I'm guessing the ARM API doesn't even try to resubmit the deployment to the resource provider.\nYou could add a parameter to try to force the update:\nparam forceUpdate string = newGuid()\n...\n\nresource symbolicname 'Microsoft.Automation/automationAccounts/runbooks@2022-08-08' = {\n name: 'Schedule Summary Table Rebuild'\n location: automationAccount.location\n tags: _tags\n dependsOn: [ deploymentScript ]\n parent: automationAcc\n properties: {\n description: 'Automation to recreate summary tables.'\n logActivityTrace: 0\n logProgress: true\n logVerbose: true\n runbookType: 'PowerShell7'\n publishContentLink: {\n uri: 'https://storageacc.blob.core.windows.net/data/ExecuteSQL.txt?forceUpdate=${forceUpdate}'\n version: '1.0.0.0'\n }\n }\n}\n...\n\n" ]
[ 0 ]
[]
[]
[ "azure", "azure_bicep", "azure_blob_storage", "azure_resource_manager", "azure_runbook" ]
stackoverflow_0074671632_azure_azure_bicep_azure_blob_storage_azure_resource_manager_azure_runbook.txt
Q: Office 365 I used oauth2 authentication, failed to get the smtptransport object(java) Microsoft office 365 to close simple authentication,I want to send an email through Microsoft's latest(oauth2) authentication method https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth I have successfully obtained OAuth token,And has relevant authority enter image description here 3. However, I failed to create the smtptransport object,This is my code (imitating Gmail) public SMTPTransport connectToSmtp(String host, int port, String userEmail, final String oauthToken, boolean debug) throws Exception { Properties props = new Properties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.starttls.required", "true"); props.put("mail.smtp.sasl.enable", "true"); // props.put("mail.smtp.auth", "true"); props.put("mail.smtp.sasl.mechanisms", "XOAUTH2"); props.put("mail.smtp.sasl.mechanisms.oauth2.oauthToken", oauthToken); props.put("mail.smtp.ssl.protocols", "TLSv1.2"); session = Session.getInstance(props, null); session.setDebug(debug); final URLName unusedUrlName = null; SMTPTransport transport = new SMTPTransport(session, unusedUrlName); // transport.connect(host, port, userEmail, null); //host:"smtp.partner.outlook.cn" transport.connect(host, 587, userEmail, null); byte[] binLogin = ("user=" + userEmail + "\u0001auth=Bearer " + oauthToken + "\u0001\u0001").getBytes(StandardCharsets.UTF_8); String base64Encoded = Base64.encodeBase64StringUnChunked(binLogin); transport.issueCommand("AUTH XOAUTH2 " + base64Encoded, 235); return transport; } code:transport.issueCommand("AUTH XOAUTH2 " + base64Encoded,235); The following exception information was thrown: Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: 535 5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [BJBPR01CA042.CHNPR01.prod.partner.outlook.cn] at com.norming.authclient.api.MicrosoftOauth.main(MicrosoftOauth.java:58) Caused by: javax.mail.MessagingException: 535 5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [BJBPR01CA042.CHNPR01.prod.partner.outlook.cn] at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:2074) The above information prompts me that auth is not turned on,However, I do not have this option in the administrator configuration,I don't know how to use OAuth to send office 365 mail or get SMTPTransport. this just is C# demo,I have not found any Java related cases package com.norming.authclient.api;using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using MailKit.Net.Smtp; using MailKit.Security; using MimeKit; using MailKit; namespace OAuth2forMail { class Program { static void Main(string[] args) { var p = new Program(); p.Sendmm(); } void Sendmm() { MimeMessage mm = new MimeMessage(); mm.To.Add(new MailboxAddress("My Customer", "customer@abc.com")); mm.From.Add(new MailboxAddress("Boss Wang", "user@abc.com")); var builder = new BodyBuilder(); builder.TextBody = @"This is a test mail."; mm.Subject = "Test to send mail with OAuth2"; mm.Body = builder.ToMessageBody(); SaslMechanismOAuth2 oauth2 = new SaslMechanismOAuth2("user@abc.com", "eyJ0eXAiOiJKV1QiLCJub25jZSI6IjlBOGtWal9hcXpVOWAA" ); using (var client = new SmtpClient(new ProtocolLogger("smtp.log"))) { client.Connect("smtp.partner.outlook.cn", 587, SecureSocketOptions.StartTls); client.Authenticate(oauth2); try { client.Send(mm); Console.WriteLine("send success"); client.Disconnect(true); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } } } } } i need help thanks! A: it's little tricky (setting up OAUTH2 authentication on IMAP in our Azure AAD instance), but following https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth very carefully it should work. I can share an example using JAVA it works perfectly (https://github.com/victorgv/dev-notes/tree/main/Using%20IMAP%20with%20OAuth%202%20authenticate%20and%20Office%20365).
Office 365 I used oauth2 authentication, failed to get the smtptransport object(java)
Microsoft office 365 to close simple authentication,I want to send an email through Microsoft's latest(oauth2) authentication method https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth I have successfully obtained OAuth token,And has relevant authority enter image description here 3. However, I failed to create the smtptransport object,This is my code (imitating Gmail) public SMTPTransport connectToSmtp(String host, int port, String userEmail, final String oauthToken, boolean debug) throws Exception { Properties props = new Properties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.starttls.required", "true"); props.put("mail.smtp.sasl.enable", "true"); // props.put("mail.smtp.auth", "true"); props.put("mail.smtp.sasl.mechanisms", "XOAUTH2"); props.put("mail.smtp.sasl.mechanisms.oauth2.oauthToken", oauthToken); props.put("mail.smtp.ssl.protocols", "TLSv1.2"); session = Session.getInstance(props, null); session.setDebug(debug); final URLName unusedUrlName = null; SMTPTransport transport = new SMTPTransport(session, unusedUrlName); // transport.connect(host, port, userEmail, null); //host:"smtp.partner.outlook.cn" transport.connect(host, 587, userEmail, null); byte[] binLogin = ("user=" + userEmail + "\u0001auth=Bearer " + oauthToken + "\u0001\u0001").getBytes(StandardCharsets.UTF_8); String base64Encoded = Base64.encodeBase64StringUnChunked(binLogin); transport.issueCommand("AUTH XOAUTH2 " + base64Encoded, 235); return transport; } code:transport.issueCommand("AUTH XOAUTH2 " + base64Encoded,235); The following exception information was thrown: Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: 535 5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [BJBPR01CA042.CHNPR01.prod.partner.outlook.cn] at com.norming.authclient.api.MicrosoftOauth.main(MicrosoftOauth.java:58) Caused by: javax.mail.MessagingException: 535 5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [BJBPR01CA042.CHNPR01.prod.partner.outlook.cn] at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:2074) The above information prompts me that auth is not turned on,However, I do not have this option in the administrator configuration,I don't know how to use OAuth to send office 365 mail or get SMTPTransport. this just is C# demo,I have not found any Java related cases package com.norming.authclient.api;using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using MailKit.Net.Smtp; using MailKit.Security; using MimeKit; using MailKit; namespace OAuth2forMail { class Program { static void Main(string[] args) { var p = new Program(); p.Sendmm(); } void Sendmm() { MimeMessage mm = new MimeMessage(); mm.To.Add(new MailboxAddress("My Customer", "customer@abc.com")); mm.From.Add(new MailboxAddress("Boss Wang", "user@abc.com")); var builder = new BodyBuilder(); builder.TextBody = @"This is a test mail."; mm.Subject = "Test to send mail with OAuth2"; mm.Body = builder.ToMessageBody(); SaslMechanismOAuth2 oauth2 = new SaslMechanismOAuth2("user@abc.com", "eyJ0eXAiOiJKV1QiLCJub25jZSI6IjlBOGtWal9hcXpVOWAA" ); using (var client = new SmtpClient(new ProtocolLogger("smtp.log"))) { client.Connect("smtp.partner.outlook.cn", 587, SecureSocketOptions.StartTls); client.Authenticate(oauth2); try { client.Send(mm); Console.WriteLine("send success"); client.Disconnect(true); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } } } } } i need help thanks!
[ "it's little tricky (setting up OAUTH2 authentication on IMAP in our Azure AAD instance), but following https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth very carefully it should work.\nI can share an example using JAVA it works perfectly (https://github.com/victorgv/dev-notes/tree/main/Using%20IMAP%20with%20OAuth%202%20authenticate%20and%20Office%20365).\n" ]
[ 0 ]
[]
[]
[ "email", "java", "office365" ]
stackoverflow_0073577534_email_java_office365.txt
Q: How to connect Vue 3 with Vuetify? I initialized a new, empty Vue application using Vue version 3. I then tried to add the plugin Vuetify with the command vue add vuetify, but received the following error. Any ideas on how to solve it? A: Currently possible with Vuetify 3 Alpha: Installation In order for the installation to proceed correctly, vue-cli 4.0 is required. Further instructions are available at vue-cli. (check with vue -V) Once installed, generate a project with the following command using the vue-cli 4.0: vue create my-app When prompted, choose Vue 3 Preview: ? Please pick a preset: Default ([Vue 2] babel, eslint) > Default (Vue 3 Preview) ([Vue 3] babel, eslint) Manually select features It is recommended to commit or stash your changes at this point, in case you need to rollback the changes. cd my-app vue add vuetify Once prompted, choose v3 (alpha): ? Choose a preset: (Use arrow keys) Default (recommended) Prototype (rapid development) Configure (advanced) > v3 (alpha) Usage With Vue 3.0, the initialization process for Vue apps (and by extension Vuetify) has changed. With the new createVuetify method, the options passed to it have also changed. Please see the pages in the Features section of the documentation for further details. Next, navigate to your project directory and add Vuetify to your project: import { createApp } from "vue"; import vuetify from "./plugins/vuetify"; import App from "./App"; const app = createApp(App); app.use(vuetify); app.mount("#app"); Source: https://next.vuetifyjs.com/en/getting-started/installation/#installation https://next.vuetifyjs.com/en/introduction/roadmap A: As of July 2020 Vue 3 is unsupported by Vuetify 2.x. All components are being refactored for Vue 3 per Vuetify's task task list: https://www.notion.so/d107077314ca4d2896f0eeba49fe8a14?v=5cc7c08e9cc44021a7c86a20f189b0ba A: While there is no Vuetify 3, I'd use Vue 2.x with Vuetify 2.x and install the Composition API as a package/plugin: npm install @vue/composition-api Then importing to your project (in main.js): import Vue from 'vue' import VueCompositionAPI from '@vue/composition-api' Vue.use(VueCompositionAPI) And finally using it in your component: // use the APIs import { ref, reactive } from '@vue/composition-api' Just be aware of the limitations of this method. A: Vuetify is not currently compatible with Vue 3. Given the number of breaking changes and implementation differences in Vue 3, the entire library needs to be rewritten. As of Jan 2021, they are targetting a Quarter 1, 2021 release for an alpha version, but the average user shouldn't expect to see a release version until late in the year, possibly even early 2022. Until then, there are other alternatives that are Vue 3 compatible, such as Prime Vue. I believe they have Material Design themes that can be connected and a decent number of components (albeit slightly lacking in the v-app style feature coordination). EDIT: The Vuetify v3 BETA is now available with a full release likely in Summer/Autumn of '22. A: You can try vue 3 with the alpha of vuetify https://next.vuetifyjs.com/ A: You Must Install Vuetify 3 using the command npm i vuetify@3.0.0-beta.11 and add it using the instruction from https://next.vuetifyjs.com/en/ A: As of today Dec-4-2022 Vue 3 is released for Months, even vuetify@3.0.3 is released but the latest npm is'nt updated it is still in next even its not in beta anymore, also the vue-cli is in Maintenance mode and for a new Vue project they recommend using the Vite base install so the best solution is to install it from npm with the latest release from GitHub like npm i vuetify@^3.0.0 I hope they update it soon so you can install it without the version number
How to connect Vue 3 with Vuetify?
I initialized a new, empty Vue application using Vue version 3. I then tried to add the plugin Vuetify with the command vue add vuetify, but received the following error. Any ideas on how to solve it?
[ "Currently possible with Vuetify 3 Alpha:\nInstallation\nIn order for the installation to proceed correctly, vue-cli 4.0 is required. Further instructions are available at vue-cli. (check with vue -V)\nOnce installed, generate a project with the following command using the vue-cli 4.0:\nvue create my-app\n\nWhen prompted, choose Vue 3 Preview:\n? Please pick a preset:\n Default ([Vue 2] babel, eslint)\n > Default (Vue 3 Preview) ([Vue 3] babel, eslint)\n Manually select features\n\nIt is recommended to commit or stash your changes at this point, in case you need to rollback the changes.\ncd my-app\nvue add vuetify\n\nOnce prompted, choose v3 (alpha):\n? Choose a preset: (Use arrow keys)\n Default (recommended)\n Prototype (rapid development)\n Configure (advanced)\n> v3 (alpha)\n\nUsage\nWith Vue 3.0, the initialization process for Vue apps (and by extension Vuetify) has changed. With the new createVuetify method, the options passed to it have also changed. Please see the pages in the Features section of the documentation for further details.\nNext, navigate to your project directory and add Vuetify to your project:\nimport { createApp } from \"vue\";\nimport vuetify from \"./plugins/vuetify\";\nimport App from \"./App\";\n\nconst app = createApp(App);\n\napp.use(vuetify);\n\napp.mount(\"#app\");\n\nSource:\n\nhttps://next.vuetifyjs.com/en/getting-started/installation/#installation\nhttps://next.vuetifyjs.com/en/introduction/roadmap\n\n", "As of July 2020 Vue 3 is unsupported by Vuetify 2.x. All components are being refactored for Vue 3 per Vuetify's task task list: https://www.notion.so/d107077314ca4d2896f0eeba49fe8a14?v=5cc7c08e9cc44021a7c86a20f189b0ba\n", "While there is no Vuetify 3, I'd use Vue 2.x with Vuetify 2.x and install the Composition API as a package/plugin:\nnpm install @vue/composition-api\n\nThen importing to your project (in main.js):\nimport Vue from 'vue'\nimport VueCompositionAPI from '@vue/composition-api'\n\nVue.use(VueCompositionAPI)\n\nAnd finally using it in your component:\n// use the APIs\nimport { ref, reactive } from '@vue/composition-api'\n\nJust be aware of the limitations of this method.\n", "Vuetify is not currently compatible with Vue 3.\nGiven the number of breaking changes and implementation differences in Vue 3, the entire library needs to be rewritten.\nAs of Jan 2021, they are targetting a Quarter 1, 2021 release for an alpha version, but the average user shouldn't expect to see a release version until late in the year, possibly even early 2022.\nUntil then, there are other alternatives that are Vue 3 compatible, such as Prime Vue. I believe they have Material Design themes that can be connected and a decent number of components (albeit slightly lacking in the v-app style feature coordination).\nEDIT: The Vuetify v3 BETA is now available with a full release likely in Summer/Autumn of '22.\n", "You can try vue 3 with the alpha of vuetify https://next.vuetifyjs.com/\n", "You Must Install Vuetify 3 using the command\nnpm i vuetify@3.0.0-beta.11\n\n\nand add it using the instruction from https://next.vuetifyjs.com/en/\n", "As of today Dec-4-2022 Vue 3 is released for Months,\neven vuetify@3.0.3 is released but the latest npm is'nt updated it is still in next even its not in beta anymore,\nalso the vue-cli is in Maintenance mode and for a new Vue project they recommend using the Vite base install\nso the best solution is to install it from npm with the latest release from GitHub like\nnpm i vuetify@^3.0.0\n\nI hope they update it soon so you can install it without the version number\n" ]
[ 19, 12, 10, 5, 1, 0, 0 ]
[]
[]
[ "vue.js", "vuejs3", "vuetify.js" ]
stackoverflow_0062871984_vue.js_vuejs3_vuetify.js.txt
Q: Hot to create an AWS ECS resource before an image is available in Terraform To Devs, I am using Terraform to spin up resources in AWS, resources are ECS in Fargate mode. On first run, I will not have an image to create the Task with but I would like to set up all the other necessary resources (ECS, Service, Task Group, Task Definition, Autoscaling). GitLab CI CD would build the image, push the image and create the Task. Terraform is complaining that the Task Definition can not be defined without the image. What are my options? Thanks, Marc A: Use placeholder. resource "aws_ecs_task_definition" "my_task" { family = "my_task_family" network_mode = "awsvpc" requires_compatibilities = ["FARGATE"] container_definitions = [ { name = "my_container" image = "amazon/amazon-ecs-sample" // container configuration } ] // task definition configuration } When the actual Docker image for your task is available, you can update the placeholder image in the task definition using the aws_ecs_task_definition resource in Terraform. It will update the task definition to use the actual image so next time the task is run, it will use the correct image.
Hot to create an AWS ECS resource before an image is available in Terraform
To Devs, I am using Terraform to spin up resources in AWS, resources are ECS in Fargate mode. On first run, I will not have an image to create the Task with but I would like to set up all the other necessary resources (ECS, Service, Task Group, Task Definition, Autoscaling). GitLab CI CD would build the image, push the image and create the Task. Terraform is complaining that the Task Definition can not be defined without the image. What are my options? Thanks, Marc
[ "Use placeholder.\nresource \"aws_ecs_task_definition\" \"my_task\" {\n family = \"my_task_family\"\n network_mode = \"awsvpc\"\n requires_compatibilities = [\"FARGATE\"]\n\n container_definitions = [\n {\n name = \"my_container\"\n image = \"amazon/amazon-ecs-sample\"\n // container configuration\n }\n ]\n\n // task definition configuration \n}\n\nWhen the actual Docker image for your task is available, you can update the placeholder image in the task definition using the aws_ecs_task_definition resource in Terraform.\nIt will update the task definition to use the actual image so next time the task is run, it will use the correct image.\n" ]
[ 2 ]
[]
[]
[ "amazon_ecs", "amazon_web_services", "terraform" ]
stackoverflow_0074680630_amazon_ecs_amazon_web_services_terraform.txt
Q: Run child processes in parallel for debugging with NodeJS I'm trying to spawn child processes based on this API example: https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows I simply want to run 3 commands (from NPM, like npm run x-script) in parallel and stream their output to the parent, but I'm getting: node:events:491 throw er; // Unhandled 'error' event Error: spawn npm run debug-js-watch ENOENT at Process.ChildProcess._handle.onexit (node:internal/child_process:283:19) at onErrorNT (node:internal/child_process:478:16) at processTicksAndRejections (node:internal/process/task_queues:83:21) Emitted 'error' event on ChildProcess instance at: at Process.ChildProcess._handle.onexit (node:internal/child_process:289:12) at onErrorNT (node:internal/child_process:478:16) at processTicksAndRejections (node:internal/process/task_queues:83:21) { errno: -4058, code: 'ENOENT', syscall: 'spawn npm run debug-js-watch', path: 'npm run debug-js-watch', spawnargs: [] } Here's the code: const path = require('path'); const { spawn } = require('node:child_process'); function runInParallel(command, argumentsList) { let childProcess = spawn(command, argumentsList); childProcess.stdout.on('data', (data) => { console.log(data.toString()); }); childProcess.stderr.on('data', (data) => { console.error(data.toString()); }); /* childProcess.on('exit', (code) => { console.log(`Child exited with code ${code}`); }); */ } runInParallel('npm run debug-js-watch', []); runInParallel('npm run debug-css-watch', []); runInParallel('npm run debug-serve', []); A: spawn takes a command and an arguments list. You can fix this by splitting your string. function runInParallel(cmd) { const [ command, ...argumentsList ] = cmd.split(' ') let childProcess = spawn(command, argumentsList); // etc runInParallel('npm run debug-js-watch'); // etc A: It looks like spawn doesn't find npm. I had to use exec instead and it worked: const {exec} = require('node:child_process'); function runInParallel(cmd) { let childProcess = exec(cmd); ... }
Run child processes in parallel for debugging with NodeJS
I'm trying to spawn child processes based on this API example: https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows I simply want to run 3 commands (from NPM, like npm run x-script) in parallel and stream their output to the parent, but I'm getting: node:events:491 throw er; // Unhandled 'error' event Error: spawn npm run debug-js-watch ENOENT at Process.ChildProcess._handle.onexit (node:internal/child_process:283:19) at onErrorNT (node:internal/child_process:478:16) at processTicksAndRejections (node:internal/process/task_queues:83:21) Emitted 'error' event on ChildProcess instance at: at Process.ChildProcess._handle.onexit (node:internal/child_process:289:12) at onErrorNT (node:internal/child_process:478:16) at processTicksAndRejections (node:internal/process/task_queues:83:21) { errno: -4058, code: 'ENOENT', syscall: 'spawn npm run debug-js-watch', path: 'npm run debug-js-watch', spawnargs: [] } Here's the code: const path = require('path'); const { spawn } = require('node:child_process'); function runInParallel(command, argumentsList) { let childProcess = spawn(command, argumentsList); childProcess.stdout.on('data', (data) => { console.log(data.toString()); }); childProcess.stderr.on('data', (data) => { console.error(data.toString()); }); /* childProcess.on('exit', (code) => { console.log(`Child exited with code ${code}`); }); */ } runInParallel('npm run debug-js-watch', []); runInParallel('npm run debug-css-watch', []); runInParallel('npm run debug-serve', []);
[ "spawn takes a command and an arguments list. You can fix this by splitting your string.\nfunction runInParallel(cmd) {\n const [ command, ...argumentsList ] = cmd.split(' ')\n let childProcess = spawn(command, argumentsList);\n // etc\n\nrunInParallel('npm run debug-js-watch');\n// etc\n\n", "It looks like spawn doesn't find npm. I had to use exec instead and it worked:\nconst {exec} = require('node:child_process');\n\nfunction runInParallel(cmd) {\n let childProcess = exec(cmd);\n ...\n}\n\n" ]
[ 1, 0 ]
[]
[]
[ "javascript", "node.js", "npm" ]
stackoverflow_0074680491_javascript_node.js_npm.txt
Q: alternative to multiple .forEach() loops for filter in Javascript There is a use case to filter key/value pairs that have a value of zero out of the following dataset. If all the values are zero for the given key then the key/value pair is to be filtered out entirely (as is the case for keys 41521, 41530). const simpleData = { "41511": { "count": 0, "probability": 0.000017 }, "41521": { "count": 0, "probability": 0 }, "41530": { "count": 0, "probability": 0 }, "41540": { "count": 0, "probability": 0.000085 }, "41551": { "count": 1, "probability": 1 } }; acc = {}; Object.entries(simpleData).forEach(([key, value]) => { acc[key] = {}; Object.entries(value).forEach(([k, v]) => { if (v !== 0) acc[key][k] = v; }); if (Object.keys(acc[key]).length === 0) delete acc[key]; }); // console.log('simpleData', simpleData); console.log('acc ', acc); The current approach uses two .forEach() loops. Is there a different way to do this filtering that avoids multiple .forEach() loops? A: Actually multiple loops are not need as you can achieve your goal using the filter method to filter out the items where the count and probability keys equal to 0 or in other words to keep the items that have at least one key from count and probability keys that is not 0. Here's a live demo: const simpleData = { "41511": { "count": 0, "probability": 0.000017 }, "41521": { "count": 0, "probability": 0 }, "41530": { "count": 0, "probability": 0 }, "41540": { "count": 0, "probability": 0.000085 }, "41551": { "count": 1, "probability": 1 } }, /** * filtered array will contain the filtered data. * we'll only keep the items where at least one of the keys ("count" or "probability") is not equal to "0" */ filtered = Object.entries(simpleData).filter(([k, v]) => v['count'] > 0 || v['probability'] > 0); // print the result console.log(filtered); The above method prevents you from having multiple loops but now the filtered array no longer contain object but rather each item will be an array where the key 0 is the key from the original object (like 41511 and the key 1 is the actual data (like {"count": 0, "probability": 0.000017}. A: const simpleData = { "41511": { "count": 0, "probability": 0.000017 }, "41521": { "count": 0, "probability": 0 }, "41530": { "count": 0, "probability": 0 }, "41540": { "count": 0, "probability": 0.000085 }, "41551": { "count": 1, "probability": 1 } }; acc = {}; Object.entries(simpleData).forEach(([key, value]) => { tmp = Object.entries(value).filter(([, v]) => v !== 0); if (tmp.length !== 0) acc[key] = Object.fromEntries(tmp); }); console.log('acc ', acc); A: The strategy here is 1) split the data into individual entries, 2) filter these entries and 3) create a new object from filtered entries: result = Object.fromEntries( Object .entries(simpleData) .filter(pair => Object.values(pair[1]).some(x => x !== 0) ))
alternative to multiple .forEach() loops for filter in Javascript
There is a use case to filter key/value pairs that have a value of zero out of the following dataset. If all the values are zero for the given key then the key/value pair is to be filtered out entirely (as is the case for keys 41521, 41530). const simpleData = { "41511": { "count": 0, "probability": 0.000017 }, "41521": { "count": 0, "probability": 0 }, "41530": { "count": 0, "probability": 0 }, "41540": { "count": 0, "probability": 0.000085 }, "41551": { "count": 1, "probability": 1 } }; acc = {}; Object.entries(simpleData).forEach(([key, value]) => { acc[key] = {}; Object.entries(value).forEach(([k, v]) => { if (v !== 0) acc[key][k] = v; }); if (Object.keys(acc[key]).length === 0) delete acc[key]; }); // console.log('simpleData', simpleData); console.log('acc ', acc); The current approach uses two .forEach() loops. Is there a different way to do this filtering that avoids multiple .forEach() loops?
[ "Actually multiple loops are not need as you can achieve your goal using the filter method to filter out the items where the count and probability keys equal to 0 or in other words to keep the items that have at least one key from count and probability keys that is not 0.\nHere's a live demo:\n\n\nconst simpleData = {\n \"41511\": {\n \"count\": 0,\n \"probability\": 0.000017\n },\n \"41521\": {\n \"count\": 0,\n \"probability\": 0\n },\n \"41530\": {\n \"count\": 0,\n \"probability\": 0\n },\n \"41540\": {\n \"count\": 0,\n \"probability\": 0.000085\n },\n \"41551\": {\n \"count\": 1,\n \"probability\": 1\n }\n },\n /**\n * filtered array will contain the filtered data.\n * we'll only keep the items where at least one of the keys (\"count\" or \"probability\") is not equal to \"0\"\n */\n filtered = Object.entries(simpleData).filter(([k, v]) => v['count'] > 0 || v['probability'] > 0);\n\n// print the result\nconsole.log(filtered);\n\n\n\n\nThe above method prevents you from having multiple loops but now the filtered array no longer contain object but rather each item will be an array where the key 0 is the key from the original object (like 41511 and the key 1 is the actual data (like {\"count\": 0, \"probability\": 0.000017}.\n\n", "\n\nconst simpleData = {\n \"41511\": {\n \"count\": 0,\n \"probability\": 0.000017\n },\n \"41521\": {\n \"count\": 0,\n \"probability\": 0\n },\n \"41530\": {\n \"count\": 0,\n \"probability\": 0\n },\n \"41540\": {\n \"count\": 0,\n \"probability\": 0.000085\n },\n \"41551\": {\n \"count\": 1,\n \"probability\": 1\n }\n};\n\nacc = {};\nObject.entries(simpleData).forEach(([key, value]) => {\n tmp = Object.entries(value).filter(([, v]) => v !== 0);\n if (tmp.length !== 0) acc[key] = Object.fromEntries(tmp);\n});\nconsole.log('acc ', acc);\n\n\n\n", "The strategy here is 1) split the data into individual entries, 2) filter these entries and 3) create a new object from filtered entries:\nresult = Object.fromEntries(\n Object\n .entries(simpleData)\n .filter(pair =>\n Object.values(pair[1]).some(x => x !== 0)\n ))\n\n" ]
[ 0, 0, 0 ]
[ "\n\nconst finalResult = Object.entries(simpleData)\n .filter(([eachKey, eachValue]) => {\n if (!eachValue[\"count\"] && !eachValue[\"probability\"]) return false;\n return true;\n })\n .map(([eachKey, eachValue]) => {\n if (eachValue[\"count\"] && eachValue[\"probability\"]) {\n return {\n [eachKey]: eachValue,\n };\n }\n if (!eachValue[\"count\"]) {\n return {\n [eachKey]: {\n probability: eachValue[\"probability\"],\n },\n };\n }\n\n if (!eachValue[\"probability\"]) {\n return {\n [eachKey]: {\n count: eachValue[\"count\"],\n },\n };\n }\n })\n .reduce((prev, current) => {\n return {\n ...prev,\n ...current,\n };\n });\n\nconsole.log(\"finalResult is\", finalResult);\n\n\n\n" ]
[ -1 ]
[ "javascript" ]
stackoverflow_0074680140_javascript.txt
Q: Hierarchical Index from pd dataframe to Excel, need to forward fill and unmerge I have a pandas dataframe with a three-level hierarchical index, created by the following: df_grouped = df.groupby(['Country','Description', pd.Grouper(freq = 'M')]).sum() Basically, a table where Country is the highest level, and Description is the second level, and followed by the date grouped by month. PICTURE A I'd like to do two unrelated things: Unmerge all the hierarchical indices in this structure within python, then forward fill to create PICTURE B. PICTURE B Be able to transform the datetimes while in the hierarchical structure of PICTURE A into YYYY-MM in python so when I export it I get PICTURE C. (I understand that I can do that from the structure in PICTURE B, I just want to be able to do it while it's still in the hierarchical structure in a pandas dataframe). PICTURE C Any tips? A: After groupby you get MultiIndex DataFrame, so values are repaeting in first and second level, only not displayning. If second DataFrame is not necessary you can convert DatetimeIndex to YYYY-MM format by strftime or to month period by to_period: df_grouped = df.groupby(['Country','Description', df.index.strftime('%Y-%m')]).sum() Or: df_grouped = df.groupby(['Country','Description', df.index.to_period('m')]).sum() If need second DataFrame add reset_index for convert levels to columns and for convert second level MultiIndex.set_levels with get_level_values: df_grouped = df.groupby(['Country','Description', pd.Grouper(freq = 'M')]).sum() df = df_grouped.reset_index() idx = df_grouped.index.get_level_values(2).strftime('%Y-%m') df_grouped.index = df_grouped.index.set_levels(idx, level=2) Sample: rng = pd.date_range('2017-04-03', periods=10, freq='10D') df = pd.DataFrame({'Country': ['Country'] * 10, 'Description':['A'] * 3 + ['B'] * 3 + ['C'] * 4, 'a': range(10)}, index=rng) print (df) Country Description a 2017-04-03 Country A 0 2017-04-13 Country A 1 2017-04-23 Country A 2 2017-05-03 Country B 3 2017-05-13 Country B 4 2017-05-23 Country B 5 2017-06-02 Country C 6 2017-06-12 Country C 7 2017-06-22 Country C 8 2017-07-02 Country C 9 df_grouped = df.groupby(['Country','Description', pd.Grouper(freq = 'M')]).sum() print (df_grouped) a Country Description Country A 2017-04-30 3 B 2017-05-31 12 C 2017-06-30 21 2017-07-31 9 df = df_grouped.reset_index().rename(columns={'level_2':'Date'}) print (df) Country Description Date a 0 Country A 2017-04-30 3 1 Country B 2017-05-31 12 2 Country C 2017-06-30 21 3 Country C 2017-07-31 9 idx = df_grouped.index.get_level_values(2).strftime('%Y-%m') df_grouped.index = df_grouped.index.set_levels(idx, level=2) print (df_grouped) a Country Description Country A 2017-04 3 B 2017-05 12 C 2017-06 21 2017-07 9 A: I realize this is an older post, but if you just want to get the displays to not look sparse, but the export to Excel still ends up merged, check that you have pandas version 1.5.2 then use the following: pd.set_option("display.multi_sparse", False) # for output display I don't know how to get the export to Excel to have all the grouped-by rows be filled with the index, that's my question here.
Hierarchical Index from pd dataframe to Excel, need to forward fill and unmerge
I have a pandas dataframe with a three-level hierarchical index, created by the following: df_grouped = df.groupby(['Country','Description', pd.Grouper(freq = 'M')]).sum() Basically, a table where Country is the highest level, and Description is the second level, and followed by the date grouped by month. PICTURE A I'd like to do two unrelated things: Unmerge all the hierarchical indices in this structure within python, then forward fill to create PICTURE B. PICTURE B Be able to transform the datetimes while in the hierarchical structure of PICTURE A into YYYY-MM in python so when I export it I get PICTURE C. (I understand that I can do that from the structure in PICTURE B, I just want to be able to do it while it's still in the hierarchical structure in a pandas dataframe). PICTURE C Any tips?
[ "After groupby you get MultiIndex DataFrame, so values are repaeting in first and second level, only not displayning.\nIf second DataFrame is not necessary you can convert DatetimeIndex to YYYY-MM format by strftime or to month period by to_period:\ndf_grouped = df.groupby(['Country','Description', df.index.strftime('%Y-%m')]).sum()\n\nOr:\ndf_grouped = df.groupby(['Country','Description', df.index.to_period('m')]).sum()\n\nIf need second DataFrame add reset_index for convert levels to columns and for convert second level MultiIndex.set_levels with get_level_values:\ndf_grouped = df.groupby(['Country','Description', pd.Grouper(freq = 'M')]).sum()\n\ndf = df_grouped.reset_index()\n\nidx = df_grouped.index.get_level_values(2).strftime('%Y-%m')\ndf_grouped.index = df_grouped.index.set_levels(idx, level=2)\n\nSample:\nrng = pd.date_range('2017-04-03', periods=10, freq='10D')\ndf = pd.DataFrame({'Country': ['Country'] * 10,\n 'Description':['A'] * 3 + ['B'] * 3 + ['C'] * 4, \n 'a': range(10)}, index=rng) \nprint (df)\n Country Description a\n2017-04-03 Country A 0\n2017-04-13 Country A 1\n2017-04-23 Country A 2\n2017-05-03 Country B 3\n2017-05-13 Country B 4\n2017-05-23 Country B 5\n2017-06-02 Country C 6\n2017-06-12 Country C 7\n2017-06-22 Country C 8\n2017-07-02 Country C 9\n\ndf_grouped = df.groupby(['Country','Description', pd.Grouper(freq = 'M')]).sum()\nprint (df_grouped)\n a\nCountry Description \nCountry A 2017-04-30 3\n B 2017-05-31 12\n C 2017-06-30 21\n 2017-07-31 9\n\n\ndf = df_grouped.reset_index().rename(columns={'level_2':'Date'})\nprint (df)\n Country Description Date a\n0 Country A 2017-04-30 3\n1 Country B 2017-05-31 12\n2 Country C 2017-06-30 21\n3 Country C 2017-07-31 9\n\nidx = df_grouped.index.get_level_values(2).strftime('%Y-%m')\ndf_grouped.index = df_grouped.index.set_levels(idx, level=2)\nprint (df_grouped)\n a\nCountry Description \nCountry A 2017-04 3\n B 2017-05 12\n C 2017-06 21\n 2017-07 9\n\n", "I realize this is an older post, but if you just want to get the displays to not look sparse, but the export to Excel still ends up merged, check that you have pandas version 1.5.2 then use the following:\npd.set_option(\"display.multi_sparse\", False) # for output display\n\nI don't know how to get the export to Excel to have all the grouped-by rows be filled with the index, that's my question here.\n" ]
[ 1, 0 ]
[]
[]
[ "datetime", "excel", "pandas", "python" ]
stackoverflow_0054019732_datetime_excel_pandas_python.txt
Q: Data scraping from forexfactory.com I am a beginner in python. In this question they extract data from forex factory. In that time the solution was working with their logic, finding table soup.find('table', class_="calendar__table") . But, now the web structure has been changed, the html table is removed and converted to some javascript format. So, this solution is not find anything now. import requests from bs4 import BeautifulSoup r = requests.get('http://www.forexfactory.com/calendar.php?day=nov18.2016') soup = BeautifulSoup(r.text, 'lxml') calendar_table = soup.find('table', class_="calendar__table") print(calendar_table) # for row in calendar_table.find_all('tr', class_=['calendar__row calendar_row','newday']): # row_data = [td.get_text(strip=True) for td in row.find_all('td')] # print(row_data) As I am a begineer I have no idea how to do that. So, how can I scrape the data? If you give me any hints it will be helpful for me. Thanks a lot for reading my post. A: As you've tagged this question with selenium, this answer relies on Selenium. I am using webdriver manager for ease. from selenium import webdriver from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) try: driver.get("http://www.forexfactory.com/calendar.php?day=nov18.2016") # Get the table table = driver.find_element(By.CLASS_NAME, "calendar__table") # Iterate over each table row for row in table.find_elements(By.TAG_NAME, "tr"): # list comprehension to get each cell's data and filter out empty cells row_data = list(filter(None, [td.text for td in row.find_elements(By.TAG_NAME, "td")])) if row_data == []: continue print(row_data) except Exception as e: print(e) finally: driver.quit() This currently prints out: ['Fri\nNov 18', '2:00am', 'EUR', 'German PPI m/m', '0.7%', '0.3%', '-0.2%'] ['3:30am', 'EUR', 'ECB President Draghi Speaks'] ['4:00am', 'EUR', 'Current Account', '25.3B', '31.3B', '29.1B'] ['4:10am', 'GBP', 'MPC Member Broadbent Speaks'] ['5:30am', 'CHF', 'Gov Board Member Maechler Speaks'] ['EUR', 'German Buba President Weidmann Speaks'] ['USD', 'FOMC Member Bullard Speaks'] ['8:30am', 'CAD', 'Core CPI m/m', '0.2%', '0.3%', '0.2%'] ['CAD', 'CPI m/m', '0.2%', '0.2%', '0.1%'] ['9:30am', 'USD', 'FOMC Member Dudley Speaks'] ['USD', 'FOMC Member George Speaks'] ['10:00am', 'USD', 'CB Leading Index m/m', '0.1%', '0.1%', '0.2%'] ['9:45pm', 'USD', 'FOMC Member Powell Speaks'] The data it's printing is just to show that it can extract the data, you will need to change and format it as you see fit. A: Currently they have implemented some cloudfare protection so only beautifulsouop can't collect data. We have to use selenium for that. Example Working Code: import random import selenium from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By def create_driver(): user_agent_list = [ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11.5; rv:90.0) Gecko/20100101 Firefox/90.0', 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_5_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:90.0) Gecko/20100101 Firefox/90.0', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36' ] user_agent = random.choice(user_agent_list) browser_options = webdriver.ChromeOptions() browser_options.add_argument("--no-sandbox") browser_options.add_argument("--headless") browser_options.add_argument("start-maximized") browser_options.add_argument("window-size=1900,1080") browser_options.add_argument("disable-gpu") browser_options.add_argument("--disable-software-rasterizer") browser_options.add_argument("--disable-dev-shm-usage") browser_options.add_argument(f'user-agent={user_agent}') driver = webdriver.Chrome(options=browser_options, service_args=["--verbose", "--log-path=test.log"]) return driver def parse_data(driver, url): driver.get(url) data_table = driver.find_element(By.CLASS_NAME, "calendar__table") value_list = [] for row in data_table.find_elements(By.TAG_NAME, "tr"): row_data = list(filter(None, [td.text for td in row.find_elements(By.TAG_NAME, "td")])) if row_data: value_list.append(row_data) return value_list driver = create_driver() url = 'https://www.forexfactory.com/calendar?day=aug26.2021' value_list = parse_data(driver=driver, url=url) for value in value_list: if '\n' in value[0]: date_str = value.pop(0).replace('\n', ' - ') print(f'Date: {date_str}') print(value) Output: Date: Thu - Aug 26 ['2:00am', 'EUR', 'German GfK Consumer Climate', '-1.2', '-0.5', '-0.4'] ['4:00am', 'EUR', 'M3 Money Supply y/y', '7.6%', '7.6%', '8.3%'] ['EUR', 'Private Loans y/y', '4.2%', '4.1%', '4.0%'] ['7:30am', 'EUR', 'ECB Monetary Policy Meeting Accounts'] ['8:30am', 'USD', 'Prelim GDP q/q', '6.6%', '6.7%', '6.5%'] ['USD', 'Unemployment Claims', '353K', '345K', '349K'] ['USD', 'Prelim GDP Price Index q/q', '6.1%', '6.0%', '6.0%'] ['10:30am', 'USD', 'Natural Gas Storage', '29B', '40B', '46B'] ['Day 1', 'All', 'Jackson Hole Symposium'] ['5:00pm', 'USD', 'President Biden Speaks'] ['7:30pm', 'JPY', 'Tokyo Core CPI y/y', '0.0%', '-0.1%', '0.1%'] ['9:30pm', 'AUD', 'Retail Sales m/m', '-2.7%', '-2.6%', '-1.8%']
Data scraping from forexfactory.com
I am a beginner in python. In this question they extract data from forex factory. In that time the solution was working with their logic, finding table soup.find('table', class_="calendar__table") . But, now the web structure has been changed, the html table is removed and converted to some javascript format. So, this solution is not find anything now. import requests from bs4 import BeautifulSoup r = requests.get('http://www.forexfactory.com/calendar.php?day=nov18.2016') soup = BeautifulSoup(r.text, 'lxml') calendar_table = soup.find('table', class_="calendar__table") print(calendar_table) # for row in calendar_table.find_all('tr', class_=['calendar__row calendar_row','newday']): # row_data = [td.get_text(strip=True) for td in row.find_all('td')] # print(row_data) As I am a begineer I have no idea how to do that. So, how can I scrape the data? If you give me any hints it will be helpful for me. Thanks a lot for reading my post.
[ "As you've tagged this question with selenium, this answer relies on Selenium. I am using webdriver manager for ease.\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\n\ndriver = webdriver.Chrome(ChromeDriverManager().install())\n\ntry:\n driver.get(\"http://www.forexfactory.com/calendar.php?day=nov18.2016\")\n # Get the table\n table = driver.find_element(By.CLASS_NAME, \"calendar__table\")\n # Iterate over each table row\n for row in table.find_elements(By.TAG_NAME, \"tr\"):\n # list comprehension to get each cell's data and filter out empty cells\n row_data = list(filter(None, [td.text for td in row.find_elements(By.TAG_NAME, \"td\")]))\n if row_data == []:\n continue\n print(row_data)\nexcept Exception as e:\n print(e)\nfinally:\n driver.quit()\n\nThis currently prints out:\n['Fri\\nNov 18', '2:00am', 'EUR', 'German PPI m/m', '0.7%', '0.3%', '-0.2%']\n['3:30am', 'EUR', 'ECB President Draghi Speaks']\n['4:00am', 'EUR', 'Current Account', '25.3B', '31.3B', '29.1B']\n['4:10am', 'GBP', 'MPC Member Broadbent Speaks']\n['5:30am', 'CHF', 'Gov Board Member Maechler Speaks']\n['EUR', 'German Buba President Weidmann Speaks']\n['USD', 'FOMC Member Bullard Speaks']\n['8:30am', 'CAD', 'Core CPI m/m', '0.2%', '0.3%', '0.2%']\n['CAD', 'CPI m/m', '0.2%', '0.2%', '0.1%']\n['9:30am', 'USD', 'FOMC Member Dudley Speaks']\n['USD', 'FOMC Member George Speaks']\n['10:00am', 'USD', 'CB Leading Index m/m', '0.1%', '0.1%', '0.2%']\n['9:45pm', 'USD', 'FOMC Member Powell Speaks']\n\nThe data it's printing is just to show that it can extract the data, you will need to change and format it as you see fit.\n", "Currently they have implemented some cloudfare protection so only beautifulsouop can't collect data. We have to use selenium for that.\nExample Working Code:\nimport random\nimport selenium\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\n\ndef create_driver():\n user_agent_list = [\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11.5; rv:90.0) Gecko/20100101 Firefox/90.0',\n 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_5_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36',\n 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:90.0) Gecko/20100101 Firefox/90.0',\n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'\n ]\n user_agent = random.choice(user_agent_list)\n\n browser_options = webdriver.ChromeOptions()\n browser_options.add_argument(\"--no-sandbox\")\n browser_options.add_argument(\"--headless\")\n browser_options.add_argument(\"start-maximized\")\n browser_options.add_argument(\"window-size=1900,1080\")\n browser_options.add_argument(\"disable-gpu\")\n browser_options.add_argument(\"--disable-software-rasterizer\")\n browser_options.add_argument(\"--disable-dev-shm-usage\")\n browser_options.add_argument(f'user-agent={user_agent}')\n\n driver = webdriver.Chrome(options=browser_options, service_args=[\"--verbose\", \"--log-path=test.log\"])\n\n return driver\n\ndef parse_data(driver, url):\n driver.get(url)\n\n data_table = driver.find_element(By.CLASS_NAME, \"calendar__table\")\n value_list = []\n\n for row in data_table.find_elements(By.TAG_NAME, \"tr\"):\n row_data = list(filter(None, [td.text for td in row.find_elements(By.TAG_NAME, \"td\")]))\n if row_data:\n value_list.append(row_data)\n return value_list\n\ndriver = create_driver()\nurl = 'https://www.forexfactory.com/calendar?day=aug26.2021'\n\nvalue_list = parse_data(driver=driver, url=url)\n\nfor value in value_list:\n if '\\n' in value[0]:\n date_str = value.pop(0).replace('\\n', ' - ')\n print(f'Date: {date_str}')\n print(value)\n\n\nOutput:\nDate: Thu - Aug 26\n['2:00am', 'EUR', 'German GfK Consumer Climate', '-1.2', '-0.5', '-0.4']\n['4:00am', 'EUR', 'M3 Money Supply y/y', '7.6%', '7.6%', '8.3%']\n['EUR', 'Private Loans y/y', '4.2%', '4.1%', '4.0%']\n['7:30am', 'EUR', 'ECB Monetary Policy Meeting Accounts']\n['8:30am', 'USD', 'Prelim GDP q/q', '6.6%', '6.7%', '6.5%']\n['USD', 'Unemployment Claims', '353K', '345K', '349K']\n['USD', 'Prelim GDP Price Index q/q', '6.1%', '6.0%', '6.0%']\n['10:30am', 'USD', 'Natural Gas Storage', '29B', '40B', '46B']\n['Day 1', 'All', 'Jackson Hole Symposium']\n['5:00pm', 'USD', 'President Biden Speaks']\n['7:30pm', 'JPY', 'Tokyo Core CPI y/y', '0.0%', '-0.1%', '0.1%']\n['9:30pm', 'AUD', 'Retail Sales m/m', '-2.7%', '-2.6%', '-1.8%']\n\n" ]
[ 4, 3 ]
[ "how to get that into discord ?\n" ]
[ -2 ]
[ "beautifulsoup", "python", "python_3.x", "selenium", "web_scraping" ]
stackoverflow_0067068287_beautifulsoup_python_python_3.x_selenium_web_scraping.txt
Q: How do I define fallback method for Resilience4j 2.0 Circuit Breaker in a plain Java? How do I define fallback method for Resillience4j 2.0 Circuit Breaker in a plain Java? I cannot find the example in the official docs nor in the API. I have a very simple code and I'd like to register a fallback / recover method when the original one fails. WeatherApi weatherApi = new FaultyWeatherService(); CircuitBreakerRegistry registry = CircuitBreakerRegistry.of( CircuitBreakerConfig.custom() .failureRateThreshold(1) .minimumNumberOfCalls(1) .build() ); CircuitBreaker breaker = registry.circuitBreaker("weather-service"); Function<String, String> weatherFunction = CircuitBreaker .decorateFunction(breaker, weatherApi::getWeatherFor); for (int i = 0; i < 10; i++) { try { System.out.println(weatherFunction.apply("krakow")); } catch (Exception ex) { ex.printStackTrace(); } } A: You can use the withFallback method on the CircuitBreaker object. Here's an example of how you could use it in your code: // Define your fallback method Function<String, String> fallback = (city) -> { // Return a default value or do some other recovery logic here return "Unknown"; }; // Use the withFallback method to register the fallback Function<String, String> weatherFunction = CircuitBreaker .decorateFunction(breaker, weatherApi::getWeatherFor) .withFallback(fallback); The withFallback method takes a Function object that will be called whenever the original function (weatherApi::getWeatherFor in this case) throws an exception. This function should return the same type as the original function (in this case, String). You can also specify a different fallback for each exception type by using the withFallback method that takes a Class object as an argument. This allows you to handle different exceptions in different ways. For example: // Define your fallback methods Function<String, String> ioExceptionFallback = (city) -> { // Return a default value or do some other recovery logic here return "Unknown"; }; Function<String, String> runtimeExceptionFallback = (city) -> { // Return a default value or do some other recovery logic here return "Unavailable"; }; // Use the withFallback methods to register the fallbacks Function<String, String> weatherFunction = CircuitBreaker .decorateFunction(breaker, weatherApi::getWeatherFor) .withFallback(IOException.class, ioExceptionFallback) .withFallback(RuntimeException.class, runtimeExceptionFallback); In this example, the ioExceptionFallback function will be called if the weatherApi::getWeatherFor function throws an IOException, and the runtimeExceptionFallback function will be called if it throws any other RuntimeException.
How do I define fallback method for Resilience4j 2.0 Circuit Breaker in a plain Java?
How do I define fallback method for Resillience4j 2.0 Circuit Breaker in a plain Java? I cannot find the example in the official docs nor in the API. I have a very simple code and I'd like to register a fallback / recover method when the original one fails. WeatherApi weatherApi = new FaultyWeatherService(); CircuitBreakerRegistry registry = CircuitBreakerRegistry.of( CircuitBreakerConfig.custom() .failureRateThreshold(1) .minimumNumberOfCalls(1) .build() ); CircuitBreaker breaker = registry.circuitBreaker("weather-service"); Function<String, String> weatherFunction = CircuitBreaker .decorateFunction(breaker, weatherApi::getWeatherFor); for (int i = 0; i < 10; i++) { try { System.out.println(weatherFunction.apply("krakow")); } catch (Exception ex) { ex.printStackTrace(); } }
[ "You can use the withFallback method on the CircuitBreaker object. Here's an example of how you could use it in your code:\n// Define your fallback method\nFunction<String, String> fallback = (city) -> {\n // Return a default value or do some other recovery logic here\n return \"Unknown\";\n};\n\n\n// Use the withFallback method to register the fallback\nFunction<String, String> weatherFunction = CircuitBreaker\n .decorateFunction(breaker, weatherApi::getWeatherFor)\n .withFallback(fallback);\n\nThe withFallback method takes a Function object that will be called whenever the original function (weatherApi::getWeatherFor in this case) throws an exception. This function should return the same type as the original function (in this case, String).\nYou can also specify a different fallback for each exception type by using the withFallback method that takes a Class object as an argument. This allows you to handle different exceptions in different ways. For example:\n// Define your fallback methods\nFunction<String, String> ioExceptionFallback = (city) -> {\n // Return a default value or do some other recovery logic here\n return \"Unknown\";\n};\n\nFunction<String, String> runtimeExceptionFallback = (city) -> {\n // Return a default value or do some other recovery logic here\n return \"Unavailable\";\n};\n\n// Use the withFallback methods to register the fallbacks\nFunction<String, String> weatherFunction = CircuitBreaker\n .decorateFunction(breaker, weatherApi::getWeatherFor)\n .withFallback(IOException.class, ioExceptionFallback)\n .withFallback(RuntimeException.class, runtimeExceptionFallback);\n\nIn this example, the ioExceptionFallback function will be called if the weatherApi::getWeatherFor function throws an IOException, and the runtimeExceptionFallback function will be called if it throws any other RuntimeException.\n" ]
[ 0 ]
[]
[]
[ "circuit_breaker", "java", "resilience4j" ]
stackoverflow_0074680473_circuit_breaker_java_resilience4j.txt
Q: Why 'width: 100vw' CSS rule causes scrollbar? I try to have a top banner that matches the screen size. This banner contains the title + a wave SVG. I have exactly the result I want with these CSS rules, the SVG matches well in responsive, except for a scrollbar that navigates over a few pixels (I tried many other things, including percentage widths). EDIT : I need the width:100vw rule because I want this container to be full-width while the parent elements are not full-width. .shape-divider { /* It is this class which causes the scrollbar */ left: 50%; line-height: 0; margin-left: -50vw; position: relative; width: 100vw; } .shape-divider svg { display: block; height: 62px; margin-top: -1px; width: calc(100% + 1.3px); } <div class="shape-divider"> <div class="shape-divider__top"> <div> <h1>Title</h1> <p class="post__date">11/30/2022</p> </div> </div> <svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 120" preserveAspectRatio="none"> <path d="M321.39,56.44c58-10.79,114.16-30.13,172-41.86,82.39-16.72,168.19-17.73,250.45-.39C823.78,31,906.67,72,985.66,92.83c70.05,18.48,146.53,26.09,214.34,3V0H0V27.35A600.21,600.21,0,0,0,321.39,56.44Z" class="shape-fill"></path> </svg> </div> Rendering : Does anyone have an idea? Thanks! Why 'width: 100vw' CSS rule makes a scrollbar appear ? A: Its because you have a vertical scrollbar. See this for reference : https://sbx.webflow.io/100vw-scrollbars Use width: 100%; instead (works perfectly for me with the html you gived). Here the full edited CSS : .shape-divider { left: 50%; line-height: 0; margin-left: -50%; position: relative; width: 100%; } .shape-divider svg { display: block; height: 62px; margin-top: -1px; width: 100%; } A: Remove the + 1.3px: .shape-divider { /* It is this class which causes the scrollbar */ left: 50%; line-height: 0; margin-left: -50vw; position: relative; width: 100vw; } .shape-divider svg { display: block; height: 62px; margin-top: -1px; width: 100%; } <div class="shape-divider"> <div class="shape-divider__top"> <div> <h1>Title</h1> <p class="post__date">11/30/2022</p> </div> </div> <svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 120" preserveAspectRatio="none"> <path d="M321.39,56.44c58-10.79,114.16-30.13,172-41.86,82.39-16.72,168.19-17.73,250.45-.39C823.78,31,906.67,72,985.66,92.83c70.05,18.48,146.53,26.09,214.34,3V0H0V27.35A600.21,600.21,0,0,0,321.39,56.44Z" class="shape-fill"></path> </svg> </div>
Why 'width: 100vw' CSS rule causes scrollbar?
I try to have a top banner that matches the screen size. This banner contains the title + a wave SVG. I have exactly the result I want with these CSS rules, the SVG matches well in responsive, except for a scrollbar that navigates over a few pixels (I tried many other things, including percentage widths). EDIT : I need the width:100vw rule because I want this container to be full-width while the parent elements are not full-width. .shape-divider { /* It is this class which causes the scrollbar */ left: 50%; line-height: 0; margin-left: -50vw; position: relative; width: 100vw; } .shape-divider svg { display: block; height: 62px; margin-top: -1px; width: calc(100% + 1.3px); } <div class="shape-divider"> <div class="shape-divider__top"> <div> <h1>Title</h1> <p class="post__date">11/30/2022</p> </div> </div> <svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 120" preserveAspectRatio="none"> <path d="M321.39,56.44c58-10.79,114.16-30.13,172-41.86,82.39-16.72,168.19-17.73,250.45-.39C823.78,31,906.67,72,985.66,92.83c70.05,18.48,146.53,26.09,214.34,3V0H0V27.35A600.21,600.21,0,0,0,321.39,56.44Z" class="shape-fill"></path> </svg> </div> Rendering : Does anyone have an idea? Thanks! Why 'width: 100vw' CSS rule makes a scrollbar appear ?
[ "Its because you have a vertical scrollbar.\nSee this for reference : https://sbx.webflow.io/100vw-scrollbars\nUse width: 100%; instead (works perfectly for me with the html you gived).\nHere the full edited CSS :\n.shape-divider {\n left: 50%;\n line-height: 0;\n margin-left: -50%;\n position: relative;\n width: 100%;\n}\n.shape-divider svg {\n display: block;\n height: 62px;\n margin-top: -1px;\n width: 100%;\n}\n\n", "Remove the + 1.3px:\n\n\n.shape-divider {\n /* It is this class which causes the scrollbar */\n left: 50%;\n line-height: 0;\n margin-left: -50vw;\n position: relative;\n width: 100vw;\n}\n\n.shape-divider svg {\n display: block;\n height: 62px;\n margin-top: -1px;\n width: 100%;\n}\n<div class=\"shape-divider\">\n <div class=\"shape-divider__top\">\n <div>\n <h1>Title</h1>\n <p class=\"post__date\">11/30/2022</p>\n </div>\n </div>\n <svg data-name=\"Layer 1\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 120\" preserveAspectRatio=\"none\">\n <path d=\"M321.39,56.44c58-10.79,114.16-30.13,172-41.86,82.39-16.72,168.19-17.73,250.45-.39C823.78,31,906.67,72,985.66,92.83c70.05,18.48,146.53,26.09,214.34,3V0H0V27.35A600.21,600.21,0,0,0,321.39,56.44Z\" class=\"shape-fill\"></path>\n </svg>\n</div>\n\n\n\n" ]
[ 0, 0 ]
[]
[]
[ "css", "html", "responsive_design" ]
stackoverflow_0074679595_css_html_responsive_design.txt
Q: Typescript Convert a Bignumber Array to a normal number TypeError: array.toNumber is not a function I saw this post here which shows how to convert a BigNumber to a normal number in typescript. The Ethers.jsis typically used for ethereum development and provides a BigNumber type and assists with converting values from onchain to offchain like in javascript applications. My issue: I have an array called arr composed of BigNumbers that is returned from a function. If I console.log(arr) it will be formatted like so: { size: BigNumber { value: '2' }, pricePerDay: [ BigNumber { value: '103897429' }, BigNumber { value: '103827546' } ], unixDate: [ BigNumber { value: '1670268628' }, BigNumber { value: '1670268634' } ] } Typically to convert a BigNumber to a number the etherjs util you would use the provided toNumber() function. So I can convert size in the example easily: arr.size = arr.size.toNumber(); But the other numbers within this arr response are pricePerDay and unixDate which are contained within an array. Is there an easy way to convert the entire array to a regular number? // this fails with TypeError: arr.priceperDay.toNumber is not a function arr.pricePerDay = arr.pricePerDay.toNumber() I know I could use map but failed with an overflow error. Heres my attempt to apply the toNumber() function to transform all elements: // note: i must create a new arr here because the original arr response is read-only function arrayBigNumberToNumber(arr: BigNumber[] { const newArr = arr.map((element: BigNumber, index: number) => { return element.toNumber(); }); return newArr; } // then I tried to apply the same let newArr; newArr.pricePerDay = arrayBigNumberToNumber(arr.pricePerDay); newArr.unixDate= arrayBigNumberToNumber(arr.pricePerDay); The above attempt results in the following overflow error: Error: overflow [ See: https://links.ethers.org/v5-errors-NUMERIC_FAULT-overflow ] (fault="overflow", operation="toNumber", value="1000000000000000000", code=NUMERIC_FAULT, version=bignumber/5.7.0) A: The error message that you provided explains the problem: Error: overflow [ See: https://links.ethers.org/v5-errors-NUMERIC_FAULT-overflow ] ( fault="overflow", operation="toNumber", value="1000000000000000000", code=NUMERIC_FAULT, version=bignumber/5.7.0 ) From the linked documentation: Overflow JavaScript uses IEEE 754 double-precision binary floating point numbers to represent numeric values. As a result, there are holes in the integer set after 9,007,199,254,740,991; which is problematic for Ethereum because that is only around 0.009 ether (in wei), which means any value over that will begin to experience rounding errors. As a result, any attempt to use a number which is outside the safe range, which would result in incorrect values, an error is thrown. In general, numbers should be kept as strings, BigNumber instances or using ES2020 bigints, which all can safely be used without loss of precision. In your case, the value 1000000000000000000 exceeds the maximum integer size for a number type in JavaScript, as demonstrated by the following code: console.log('Max number:', Number.MAX_SAFE_INTEGER); console.log('My number:', '1000000000000000000'); console.log( 'Is too large?', 1000000000000000000 > Number.MAX_SAFE_INTEGER, ); and because of that, the value is not representable as a number type in JavaScript. In order to work with values of that magnitude, you'll need to use the existing BigNumber instances or standard BigInt types.
Typescript Convert a Bignumber Array to a normal number TypeError: array.toNumber is not a function
I saw this post here which shows how to convert a BigNumber to a normal number in typescript. The Ethers.jsis typically used for ethereum development and provides a BigNumber type and assists with converting values from onchain to offchain like in javascript applications. My issue: I have an array called arr composed of BigNumbers that is returned from a function. If I console.log(arr) it will be formatted like so: { size: BigNumber { value: '2' }, pricePerDay: [ BigNumber { value: '103897429' }, BigNumber { value: '103827546' } ], unixDate: [ BigNumber { value: '1670268628' }, BigNumber { value: '1670268634' } ] } Typically to convert a BigNumber to a number the etherjs util you would use the provided toNumber() function. So I can convert size in the example easily: arr.size = arr.size.toNumber(); But the other numbers within this arr response are pricePerDay and unixDate which are contained within an array. Is there an easy way to convert the entire array to a regular number? // this fails with TypeError: arr.priceperDay.toNumber is not a function arr.pricePerDay = arr.pricePerDay.toNumber() I know I could use map but failed with an overflow error. Heres my attempt to apply the toNumber() function to transform all elements: // note: i must create a new arr here because the original arr response is read-only function arrayBigNumberToNumber(arr: BigNumber[] { const newArr = arr.map((element: BigNumber, index: number) => { return element.toNumber(); }); return newArr; } // then I tried to apply the same let newArr; newArr.pricePerDay = arrayBigNumberToNumber(arr.pricePerDay); newArr.unixDate= arrayBigNumberToNumber(arr.pricePerDay); The above attempt results in the following overflow error: Error: overflow [ See: https://links.ethers.org/v5-errors-NUMERIC_FAULT-overflow ] (fault="overflow", operation="toNumber", value="1000000000000000000", code=NUMERIC_FAULT, version=bignumber/5.7.0)
[ "The error message that you provided explains the problem:\nError: overflow [\n See: https://links.ethers.org/v5-errors-NUMERIC_FAULT-overflow\n] (\n fault=\"overflow\",\n operation=\"toNumber\",\n value=\"1000000000000000000\",\n code=NUMERIC_FAULT,\n version=bignumber/5.7.0\n)\n\nFrom the linked documentation:\n\nOverflow\nJavaScript uses IEEE 754 double-precision binary floating point numbers to represent numeric values. As a result, there are holes in the integer set after 9,007,199,254,740,991; which is problematic for Ethereum because that is only around 0.009 ether (in wei), which means any value over that will begin to experience rounding errors.\nAs a result, any attempt to use a number which is outside the safe range, which would result in incorrect values, an error is thrown.\nIn general, numbers should be kept as strings, BigNumber instances or using ES2020 bigints, which all can safely be used without loss of precision.\n\nIn your case, the value 1000000000000000000 exceeds the maximum integer size for a number type in JavaScript, as demonstrated by the following code:\n\n\nconsole.log('Max number:', Number.MAX_SAFE_INTEGER);\nconsole.log('My number:', '1000000000000000000');\n\nconsole.log(\n 'Is too large?',\n 1000000000000000000 > Number.MAX_SAFE_INTEGER,\n);\n\n\n\nand because of that, the value is not representable as a number type in JavaScript.\nIn order to work with values of that magnitude, you'll need to use the existing BigNumber instances or standard BigInt types.\n" ]
[ 1 ]
[]
[]
[ "bignumber.js", "ethereum", "type_conversion", "typescript" ]
stackoverflow_0074680436_bignumber.js_ethereum_type_conversion_typescript.txt
Q: node.js how to send multipart form data in post request I am attempting to get data in the form of an image sent from elsewhere using multipartform, however when trying to understand this via the great sanctuary(stack overflow) there are missing elements I don't quite understand. const options = { method: "POST", url: "https://api.LINK.com/file", port: 443, headers: { "Authorization": "Basic " + auth, "Content-Type": "multipart/form-data" }, formData : { "image" : fs.createReadStream("./images/scr1.png") } }; request(options, function (err, res, body) { if(err) console.log(err); console.log(body); }); 2 questions: what is the variable auth, what do I initialize it to/where/how do I declare it what is the url "api.LINK.com", is this just the site url where this code is on After your comments I think I may be doing this wrong. The goal is to send data(an image) from somewhere else(like another website) to this node app, then the nodeapp uses the image and sends something back. So that I would be the one creating the API endpoint A: In this code snippet, the auth variable is likely intended to be a string that represents some kind of authentication information, such as an API key. You would need to initialize it with the appropriate value, which would depend on the API you are trying to use. The url value, "https://api.LINK.com/file", is just an example URL. It would need to be replaced with the actual URL of the API endpoint that you are trying to access. For example, if you were using the imaginary "LINK" API, you would need to use the correct URL for that API's file endpoint. A: The variable auth is likely a string containing an authorization token or credentials, which is used to authenticate the request to the server. It would need to be initialized with the appropriate value, which would typically be provided by the server or service you are trying to access. The value of the url property in the options object appears to be a placeholder, and would need to be replaced with the actual URL of the server or service that you are trying to access. This URL would typically be provided by the server or service you are trying to access. The code you posted makes an HTTP request to this URL using the request function. In general, it is important to understand that the code you posted is incomplete and may not work as-is without additional information or modifications. It is provided as an example of how to make an HTTP request with the request function using the multipart/form-data content type, but would need to be adapted to your specific use case.
node.js how to send multipart form data in post request
I am attempting to get data in the form of an image sent from elsewhere using multipartform, however when trying to understand this via the great sanctuary(stack overflow) there are missing elements I don't quite understand. const options = { method: "POST", url: "https://api.LINK.com/file", port: 443, headers: { "Authorization": "Basic " + auth, "Content-Type": "multipart/form-data" }, formData : { "image" : fs.createReadStream("./images/scr1.png") } }; request(options, function (err, res, body) { if(err) console.log(err); console.log(body); }); 2 questions: what is the variable auth, what do I initialize it to/where/how do I declare it what is the url "api.LINK.com", is this just the site url where this code is on After your comments I think I may be doing this wrong. The goal is to send data(an image) from somewhere else(like another website) to this node app, then the nodeapp uses the image and sends something back. So that I would be the one creating the API endpoint
[ "In this code snippet, the auth variable is likely intended to be a string that represents some kind of authentication information, such as an API key. You would need to initialize it with the appropriate value, which would depend on the API you are trying to use.\nThe url value, \"https://api.LINK.com/file\", is just an example URL. It would need to be replaced with the actual URL of the API endpoint that you are trying to access. For example, if you were using the imaginary \"LINK\" API, you would need to use the correct URL for that API's file endpoint.\n", "The variable auth is likely a string containing an authorization token or credentials, which is used to authenticate the request to the server. It would need to be initialized with the appropriate value, which would typically be provided by the server or service you are trying to access.\nThe value of the url property in the options object appears to be a placeholder, and would need to be replaced with the actual URL of the server or service that you are trying to access. This URL would typically be provided by the server or service you are trying to access. The code you posted makes an HTTP request to this URL using the request function.\nIn general, it is important to understand that the code you posted is incomplete and may not work as-is without additional information or modifications. It is provided as an example of how to make an HTTP request with the request function using the multipart/form-data content type, but would need to be adapted to your specific use case.\n" ]
[ 0, 0 ]
[]
[]
[ "express", "form_data", "multipartform_data", "node.js", "post" ]
stackoverflow_0074680652_express_form_data_multipartform_data_node.js_post.txt