content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
30
130
Q: How to bind two components from different lazy-loaded modules to the same route? I have an Angular application with the structure as on the image: In want to conditionally select one of the themes based on the data retrieved from the server. const routes: Routes = [ { path: '', loadChildren: 'app/presentation/theme1/theme1.module#Theme1Module', canActivate: [Theme1Guard], }, { path: '', loadChildren: 'app/presentation/theme2/theme2.module#Theme2Module', canActivate: [Theme2Guard], } ]; Both theme-1 and theme-2 modules have the same routes to similar component with different layout and styles. UPDATE 1 I tried CanActivate guards one for theme-1 and the second for theme-2. Each guard retrieves current theme name from the themeStore and compares it to the current route: canActivate() { let currentTheme: string = ''; this.themeStore.currentTheme.subscribe((themeName) => { currentTheme = themeName; }); if (currentTheme == 'theme1') { return true; } else { return false; } } However, this won't work because Angular router does not look for the same path after the first one was rejected by CanActivate guard. UPDATE 2 There's an open issue in Angular repository - Load a component in a route depending on an asynchronous condition. It seems to be added to backlog a few months ago. A: Both theme-1 and theme-2 have the same route to similar component with different layout and styles. No lazy-loading Create theme-1 and theme-2 routes: { path: 'theme-1', component: Theme1Component, children: [ { path: 'page', component: PageComponent, } ] }, { path: 'theme-2', component: Theme2Component, children: [ { path: 'page', component: PageComponent, } ] }, With lazy loading If they are lazy loadable, then in main route module: const routes: Routes = [ { path: '', children: [ { path: 'theme-1', loadChildren: 'path/to/theme1#module', }, { path: 'theme-2', loadChildren: 'path/to/theme2#module', } ] }, ... ]; Lazy-loading theme-1, theme-2 module routes: theme1-routing.module: const routes: Routes = [ { path: '', component: Theme1Component, children: [ { path: 'page', component: PageComponent, }, ] } ]; theme2-routing.module: const routes: Routes = [ { path: '', component: Theme2Component, children: [ { path: 'page', component: PageComponent, }, ] } ]; A: i think your route of the second module is overridden, try to put your routing in the first position in your imports for the second module: // in your second module imports: [ routing, ... // then import the others ], A: In Angular 14.1+ you can use CanMatch guards for this. Lazy-loaded or not, if two routes share the same path there needs to be some condition to separate them. CanActivate runs only after the route is decided. With CanMatch this is simple, as it can be asynchronous, uses Angular's dependency injection like other guards, and can skip routes in the matching stage. It'll also add the functionality of CanLoad, as a route that can't be matched won't load its child routes. Without CanMatch, you could replace path with matcher and provide a synchronous function that would return true for the right route. Now the problem is that UrlMatcher is synchronous and has no dependency injection. There's a detailed answer on a different question about this exact problem, and it includes workarounds for pre-CanMatch Angular versions. Briefly, one workaround is adding a state variable that will be used in both of the matchers, updating it in CanActivate, and if the new value is different - redirecting so the routes will be matched again. You'd also need to make sure the routes are matched in the first place, or there will be cases where the current state is not updated and no route will be matched. In the question's case it's already assured, as their child routes have the same path structure, but in other cases you could add a wildcard route that has the same guard that updates the state variable.
How to bind two components from different lazy-loaded modules to the same route?
I have an Angular application with the structure as on the image: In want to conditionally select one of the themes based on the data retrieved from the server. const routes: Routes = [ { path: '', loadChildren: 'app/presentation/theme1/theme1.module#Theme1Module', canActivate: [Theme1Guard], }, { path: '', loadChildren: 'app/presentation/theme2/theme2.module#Theme2Module', canActivate: [Theme2Guard], } ]; Both theme-1 and theme-2 modules have the same routes to similar component with different layout and styles. UPDATE 1 I tried CanActivate guards one for theme-1 and the second for theme-2. Each guard retrieves current theme name from the themeStore and compares it to the current route: canActivate() { let currentTheme: string = ''; this.themeStore.currentTheme.subscribe((themeName) => { currentTheme = themeName; }); if (currentTheme == 'theme1') { return true; } else { return false; } } However, this won't work because Angular router does not look for the same path after the first one was rejected by CanActivate guard. UPDATE 2 There's an open issue in Angular repository - Load a component in a route depending on an asynchronous condition. It seems to be added to backlog a few months ago.
[ "\nBoth theme-1 and theme-2 have the same route to similar component with\ndifferent layout and styles.\n\nNo lazy-loading\nCreate theme-1 and theme-2 routes:\n{\n path: 'theme-1', component: Theme1Component,\n children: [\n {\n path: 'page', \n component: PageComponent,\n }\n\n ]\n},\n{\n path: 'theme-2', component: Theme2Component,\n children: [\n {\n path: 'page', \n component: PageComponent,\n }\n ]\n},\n\nWith lazy loading\nIf they are lazy loadable, then in main route module:\nconst routes: Routes = [\n {\n path: '', \n children: [\n {\n path: 'theme-1', \n loadChildren: 'path/to/theme1#module',\n },\n {\n path: 'theme-2', \n loadChildren: 'path/to/theme2#module',\n }\n\n ]\n },\n ...\n];\n\nLazy-loading theme-1, theme-2 module routes:\ntheme1-routing.module:\nconst routes: Routes = [\n {\n path: '',\n component: Theme1Component,\n\n children: [\n {\n path: 'page', \n component: PageComponent,\n }, \n ]\n }\n];\n\ntheme2-routing.module:\nconst routes: Routes = [\n {\n path: '',\n component: Theme2Component,\n\n children: [\n {\n path: 'page', \n component: PageComponent,\n }, \n ]\n }\n];\n\n", "i think your route of the second module is overridden, try to put your routing in the first position in your imports for the second module:\n // in your second module\n imports: [\n routing, \n ... // then import the others \n],\n\n", "In Angular 14.1+ you can use CanMatch guards for this.\nLazy-loaded or not, if two routes share the same path there needs to be some condition to separate them. CanActivate runs only after the route is decided. With CanMatch this is simple, as it can be asynchronous, uses Angular's dependency injection like other guards, and can skip routes in the matching stage. It'll also add the functionality of CanLoad, as a route that can't be matched won't load its child routes.\nWithout CanMatch, you could replace path with matcher and provide a synchronous function that would return true for the right route.\nNow the problem is that UrlMatcher is synchronous and has no dependency injection. There's a detailed answer on a different question about this exact problem, and it includes workarounds for pre-CanMatch Angular versions.\nBriefly, one workaround is adding a state variable that will be used in both of the matchers, updating it in CanActivate, and if the new value is different - redirecting so the routes will be matched again.\nYou'd also need to make sure the routes are matched in the first place, or there will be cases where the current state is not updated and no route will be matched. In the question's case it's already assured, as their child routes have the same path structure, but in other cases you could add a wildcard route that has the same guard that updates the state variable.\n" ]
[ 2, 0, 0 ]
[]
[]
[ "angular", "angular_routing" ]
stackoverflow_0049814235_angular_angular_routing.txt
Q: Vite preview is working but I can not see it running when opening index.html I dont know if I'm doint it wrong here, but I started a vanilla.js project with vite, I did my code, and everything is working with: npm run dev (which runs vite command). But when I run npm run build and I open /dist/index.html the page is not working. Probably I'm doing something wrong. I know that when I run npm run build && npm run preview it works. But I'm trying to make it work by only opening the index.html file, because AFAIK, that's the only way I could host it on Github pages. A: I added this at vite.config.js and now it works! import { defineConfig } from 'vite'; export default defineConfig({ base: '/roulette-simulation/' }); A: I added this on my vite.config.js. import { defineConfig } from 'vite'; export default defineConfig({ base: './' }); It happens becouse our navigator doesnt recognize the path /heres-the-file-or-paths so i needed to add the ./ at the beginning of our path when are importing .js and .css files. The same for icons and others. This makes that the build process ends with and index.html like this with our imports paths working. href="./the-rest-of-the-path-here" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="./vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React</title> <script type="module" crossorigin src="./assets/index.b3824f6c.js"></script> <link rel="stylesheet" href="./assets/index.3fce1f81.css"> </head> <body> <div id="root"></div> </body> </html> I hope this can help you.
Vite preview is working but I can not see it running when opening index.html
I dont know if I'm doint it wrong here, but I started a vanilla.js project with vite, I did my code, and everything is working with: npm run dev (which runs vite command). But when I run npm run build and I open /dist/index.html the page is not working. Probably I'm doing something wrong. I know that when I run npm run build && npm run preview it works. But I'm trying to make it work by only opening the index.html file, because AFAIK, that's the only way I could host it on Github pages.
[ "I added this at vite.config.js and now it works!\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n base: '/roulette-simulation/'\n});\n\n", "I added this on my vite.config.js.\n\n\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n base: './'\n});\n\n\n\nIt happens becouse our navigator doesnt recognize the path /heres-the-file-or-paths so i needed to add the ./ at the beginning of our path when are importing .js and .css files. The same for icons and others.\nThis makes that the build process ends with and index.html like this with our imports paths working. href=\"./the-rest-of-the-path-here\"\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"./vite.svg\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Vite + React</title>\n <script type=\"module\" crossorigin src=\"./assets/index.b3824f6c.js\"></script>\n <link rel=\"stylesheet\" href=\"./assets/index.3fce1f81.css\">\n </head>\n <body>\n <div id=\"root\"></div>\n \n </body>\n</html>\n\n\n\nI hope this can help you.\n" ]
[ 0, 0 ]
[]
[]
[ "es6_modules", "html", "javascript", "vite" ]
stackoverflow_0072071621_es6_modules_html_javascript_vite.txt
Q: react-router-dom state returns error on page refresh I am new to react-router-dom I was passing data from ParentPage to the ChildPage page using <Link/> and it was a success, but if I'm going to refresh the child page it returns an error TypeError: Cannot read properties of undefined. I have also tried storing the data on the localStorage but it is still returning the same error Here is my code snippet, I hope anyone can help me. And here is the Error A: I think the problem is with the parsing of data not the link it self. It would have helped a lot if you had showed some code and the full error message A: For this kind of usage, the best practice would be using query param in react-router-dom, so that you can pass your value and by refreshing the page will work the same, you can check if there is no query param in the child component you can redirect the user back I think this blog will help to handle it https://denislistiadi.medium.com/react-router-v6-fundamental-url-parameter-query-strings-customizing-link-57b75f7d63dd
react-router-dom state returns error on page refresh
I am new to react-router-dom I was passing data from ParentPage to the ChildPage page using <Link/> and it was a success, but if I'm going to refresh the child page it returns an error TypeError: Cannot read properties of undefined. I have also tried storing the data on the localStorage but it is still returning the same error Here is my code snippet, I hope anyone can help me. And here is the Error
[ "I think the problem is with the parsing of data not the link it self. It would have helped a lot if you had showed some code and the full error message\n", "For this kind of usage, the best practice would be using query param in react-router-dom, so that you can pass your value and by refreshing the page will work the same, you can check if there is no query param in the child component you can redirect the user back\nI think this blog will help to handle it https://denislistiadi.medium.com/react-router-v6-fundamental-url-parameter-query-strings-customizing-link-57b75f7d63dd\n" ]
[ 0, 0 ]
[]
[]
[ "react_router_dom", "reactjs" ]
stackoverflow_0074667366_react_router_dom_reactjs.txt
Q: Backwards typing effect I am trying to get a backwards typing effect with my code. So the <P> will say "Coming Soon" then type backwards. Then type forwards into "SeaDogs.com.eu.as" This is what I have so far, for some reason it type coming soon backwards twice??? Which is my first hurtle I'm trying to overcome. And trying to delay it so it shows the word "Coming soon" for a few seconds. var str = 'Coming Soon'; var remove = false; var i = str.length; var isTag; var text; (function type() { if (!remove) { text = str.slice(0, --i); if (text === str) return; } if (!isTag) { document.getElementById("demo").innerHTML = text; } setTimeout(type, 520); }()); <p id="demo"></p> A: It's much cleaner to code the logic directly with async/await rather than to fiddle with timeouts: function delay(time) { return new Promise(r => setTimeout(r, time)) } async function typeAnimation(div, rtl, text, time) { for (let i = 1; i <= text.length; i++) { div.innerText = text.slice(0, rtl ? -i : +i) await delay(time) } } async function main() { let div = document.querySelector('h1') await typeAnimation(div, true, 'Coming soon...', 100) await typeAnimation(div, false, 'and here it comes!', 100) } main() <h1></h1> A: I would create two functions with a promise const demo = document.querySelector('#demo') const initial = "Coming Soon" const later = "SeaDogs.com.eu.as" remove(initial).then(() => add(later)) function remove(text) { let i = text.length return new Promise(r => { removeCharacter() function removeCharacter() { if (i < 0) { r() return } const copy = text.slice(0, i) demo.textContent = copy setTimeout(removeCharacter, 100) i -= 1 } }) } function add(text) { let i = 0 return new Promise(r => { removeCharacter() function removeCharacter() { if (i > text.length) { r() return } const copy = text.slice(0, i) demo.textContent = copy setTimeout(removeCharacter, 100) i += 1 } }) } <p id="demo"></p> A: Your exit clause is incorrect - you check if substring of str == str - which it never will. You get it twice because of the way .slice works with a negative index .slice(0, 8) -> start to 8th character .slice(0, -2) -> start to 2 characters from the end You can change the exit clause from if (text === str) return to if (text === "") return; or if (i === 0) return; Depending on when you want it to end - as your exit clause is before the output, this will leave the last character, so instead: if (i<0) return; var str = 'Coming Soon'; var remove = false; var i = str.length; var isTag; var text; (function type() { if (!remove) { text = str.slice(0, --i); //console.log(i, text) if (i < 0) return; } if (!isTag) { document.getElementById("demo").innerHTML = text; } setTimeout(type, 150); }()); <p id="demo"></p> However, I expect there's some mix up between remove and !remove as you have not-remove (ie add) with --i. So when adding, you do need to check text==str
Backwards typing effect
I am trying to get a backwards typing effect with my code. So the <P> will say "Coming Soon" then type backwards. Then type forwards into "SeaDogs.com.eu.as" This is what I have so far, for some reason it type coming soon backwards twice??? Which is my first hurtle I'm trying to overcome. And trying to delay it so it shows the word "Coming soon" for a few seconds. var str = 'Coming Soon'; var remove = false; var i = str.length; var isTag; var text; (function type() { if (!remove) { text = str.slice(0, --i); if (text === str) return; } if (!isTag) { document.getElementById("demo").innerHTML = text; } setTimeout(type, 520); }()); <p id="demo"></p>
[ "It's much cleaner to code the logic directly with async/await rather than to fiddle with timeouts:\n\n\nfunction delay(time) {\n return new Promise(r =>\n setTimeout(r, time))\n}\n\nasync function typeAnimation(div, rtl, text, time) {\n for (let i = 1; i <= text.length; i++) {\n div.innerText = text.slice(0, rtl ? -i : +i)\n await delay(time)\n }\n}\n\nasync function main() {\n let div = document.querySelector('h1')\n await typeAnimation(div, true, 'Coming soon...', 100)\n await typeAnimation(div, false, 'and here it comes!', 100)\n}\n\nmain()\n<h1></h1>\n\n\n\n", "I would create two functions with a promise\n\n\nconst demo = document.querySelector('#demo')\n\nconst initial = \"Coming Soon\"\nconst later = \"SeaDogs.com.eu.as\"\n\nremove(initial).then(() => add(later))\n\nfunction remove(text) {\n let i = text.length\n return new Promise(r => {\n removeCharacter()\n\n function removeCharacter() {\n if (i < 0) {\n r()\n return\n }\n const copy = text.slice(0, i)\n demo.textContent = copy\n\n setTimeout(removeCharacter, 100)\n i -= 1\n }\n })\n}\n\nfunction add(text) {\n let i = 0\n return new Promise(r => {\n removeCharacter()\n\n function removeCharacter() {\n if (i > text.length) {\n r()\n return\n }\n const copy = text.slice(0, i)\n demo.textContent = copy\n\n setTimeout(removeCharacter, 100)\n i += 1\n }\n })\n}\n<p id=\"demo\"></p>\n\n\n\n", "Your exit clause is incorrect - you check if substring of str == str - which it never will.\nYou get it twice because of the way .slice works with a negative index\n\n.slice(0, 8) -> start to 8th character\n.slice(0, -2) -> start to 2 characters from the end\n\nYou can change the exit clause from if (text === str) return to\nif (text === \"\") return;\n\nor\nif (i === 0) return;\n\nDepending on when you want it to end - as your exit clause is before the output, this will leave the last character, so instead:\nif (i<0) return;\n\n\n\nvar str = 'Coming Soon';\nvar remove = false;\nvar i = str.length;\nvar isTag;\nvar text;\n\n(function type() {\n if (!remove) {\n text = str.slice(0, --i);\n //console.log(i, text)\n if (i < 0) return;\n }\n\n if (!isTag) {\n document.getElementById(\"demo\").innerHTML = text;\n }\n\n setTimeout(type, 150);\n\n}());\n<p id=\"demo\"></p>\n\n\n\nHowever, I expect there's some mix up between remove and !remove as you have not-remove (ie add) with --i. So when adding, you do need to check text==str\n" ]
[ 2, 1, 1 ]
[]
[]
[ "animation", "html", "javascript" ]
stackoverflow_0074667319_animation_html_javascript.txt
Q: Where do I put code to initialize before custom module initialization in Angular 14? I'm using ngrx/data 14 and Angular 14. I have built a custom module that I load in my app.module.ts file like so @NgModule({ declarations: [ AppComponent ], imports: [ ... AppRoutingModule, MyCustomModule, ... ], providers: [ ... ], bootstrap: [AppComponent] }) export class AppModule { } The custom module is defined this way export function initialize(appService: AppService){ console.log("in initialize"); return () => appService.load(); } ... @NgModule({ declarations: [ ... ], imports: [ ... ], exports: [ ... ], providers: [ { provide: APP_INITIALIZER, useFactory: initialize, deps: [ AppService ], multi: true }, ... ] }) export class MyCustomModule { constructor(entityDataService: EntityDataService, myObjectDataService: MyObjectDataService) { console.log("called from module"); entityDataService.registerService('MyObject', myObjectDataService); } } The problem is, I notice that the module constructor is run before the "initialize" method (I can see the console.log "called from module" is called before the "in initialize" statement within the "initialize" method. My question is, how or where do I put code that will initialize prior to my module getting instantiated? A: I noticed APP_INITIALIZER is not initializing before the module and this is happening after Angular version 14 and 14+. One workaround for this is to get your initial configuration using fetch API. So whatever data you are fetching from the AppService you can get it using fetch API here. Then call your platformBrowserDynamic Settings once you receive response from the fetch API. Try this stackblitz example. import './polyfills'; export interface AppConfig { auth: { auth0_audience: string, auth0_domain: string, auth0_client_id: string, }; } import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { InjectionToken } from '@angular/core'; const APP_CONFIG: InjectionToken < AppConfig > = new InjectionToken < AppConfig > ('Application Configuration'); // Same as App service fetch('./config.json') .then((res) => res.json()) .then((config) => { console.log("Initialize") console.log(config) // Save this config in window object to access it across application. window['config'] = config; platformBrowserDynamic([{ provide: APP_CONFIG, useValue: config }, ]).bootstrapModule(AppModule).then(ref => { // Ensure Angular destroys itself on hot reloads. // Otherwise, log the boot error }).catch(err => console.error(err)); });
Where do I put code to initialize before custom module initialization in Angular 14?
I'm using ngrx/data 14 and Angular 14. I have built a custom module that I load in my app.module.ts file like so @NgModule({ declarations: [ AppComponent ], imports: [ ... AppRoutingModule, MyCustomModule, ... ], providers: [ ... ], bootstrap: [AppComponent] }) export class AppModule { } The custom module is defined this way export function initialize(appService: AppService){ console.log("in initialize"); return () => appService.load(); } ... @NgModule({ declarations: [ ... ], imports: [ ... ], exports: [ ... ], providers: [ { provide: APP_INITIALIZER, useFactory: initialize, deps: [ AppService ], multi: true }, ... ] }) export class MyCustomModule { constructor(entityDataService: EntityDataService, myObjectDataService: MyObjectDataService) { console.log("called from module"); entityDataService.registerService('MyObject', myObjectDataService); } } The problem is, I notice that the module constructor is run before the "initialize" method (I can see the console.log "called from module" is called before the "in initialize" statement within the "initialize" method. My question is, how or where do I put code that will initialize prior to my module getting instantiated?
[ "I noticed APP_INITIALIZER is not initializing before the module and this is happening after Angular version 14 and 14+.\nOne workaround for this is to get your initial configuration using fetch API. So whatever data you are fetching from the AppService you can get it using fetch API here.\nThen call your platformBrowserDynamic Settings once you receive response from the fetch API.\nTry this stackblitz example.\n\n\nimport './polyfills';\nexport interface AppConfig {\n auth: {\n auth0_audience: string,\n auth0_domain: string,\n auth0_client_id: string,\n };\n}\n\nimport {\n platformBrowserDynamic\n} from '@angular/platform-browser-dynamic';\n\n\nimport {\n AppModule\n} from './app/app.module';\nimport {\n InjectionToken\n} from '@angular/core';\n\nconst APP_CONFIG: InjectionToken < AppConfig > = new InjectionToken < AppConfig > ('Application Configuration');\n// Same as App service\nfetch('./config.json')\n .then((res) => res.json())\n .then((config) => {\n console.log(\"Initialize\")\n console.log(config)\n // Save this config in window object to access it across application.\n window['config'] = config;\n platformBrowserDynamic([{\n provide: APP_CONFIG,\n useValue: config\n }, ]).bootstrapModule(AppModule).then(ref => {\n // Ensure Angular destroys itself on hot reloads.\n\n // Otherwise, log the boot error\n }).catch(err => console.error(err));\n });\n\n\n\n" ]
[ 0 ]
[]
[]
[ "angular", "angular14", "angular_module", "angular_ngrx_data", "initialization" ]
stackoverflow_0074661765_angular_angular14_angular_module_angular_ngrx_data_initialization.txt
Q: How to decrease Qt Creator upper left menu options text size? As you can see in the images I provided, the upper left menu options text is huge. I don't know why this is, I think I updated Qt and then suddenly it looked like this the next time I ran it. I have tried to search for solutions for how to get regular size back but I find pretty much only things related to code font size. Does anyone know how I can get back the original, much smaller and easy-on-the eyes text size? A: This is a bug in QtCreator 9.0.0. It will be fixed in version 9.0.1. which will hopefully come out soon. If you do not want to wait, you can download and install some snapshot of QtCreator 9.0.1. here https://download.qt.io/snapshots/qtcreator/9.0/9.0.1/ See also https://bugreports.qt.io/browse/QTCREATORBUG-28499 for some other workarounds.
How to decrease Qt Creator upper left menu options text size?
As you can see in the images I provided, the upper left menu options text is huge. I don't know why this is, I think I updated Qt and then suddenly it looked like this the next time I ran it. I have tried to search for solutions for how to get regular size back but I find pretty much only things related to code font size. Does anyone know how I can get back the original, much smaller and easy-on-the eyes text size?
[ "This is a bug in QtCreator 9.0.0. It will be fixed in version 9.0.1. which will hopefully come out soon. If you do not want to wait, you can download and install some snapshot of QtCreator 9.0.1. here https://download.qt.io/snapshots/qtcreator/9.0/9.0.1/ See also https://bugreports.qt.io/browse/QTCREATORBUG-28499 for some other workarounds.\n" ]
[ 0 ]
[]
[]
[ "ide", "qt", "qt_creator", "text_size" ]
stackoverflow_0074667165_ide_qt_qt_creator_text_size.txt
Q: python issue while importing a module from a file the below is my main_call.py file from flask import Flask, jsonify, request from test_invoke.invoke import end_invoke from config import config app = Flask(__name__) @app.route("/get/posts", methods=["GET"]) def load_data(): res = "True" # setting a Host url host_url = config()["url"] # getting request parameter and validating it generate_schedule= end_invoke(host_url) if generate_schedule == 200: return jsonify({"status_code": 200, "message": "success"}) elif generate_schedule == 400: return jsonify( {"error": "Invalid ", "status_code": 400} ) if __name__ == "__main__": app.run(debug=True) invoke.py import requests import json import urllib from urllib import request, parse from config import config from flask import request def end_invoke(schedule_url): headers = { "Content-Type":"application/json", } schedule_data = requests.get(schedule_url, headers=headers) if not schedule_data.status_code // 100 == 2: error = schedule_data.json()["error"] print(error) return 400 else: success = schedule_data.json() return 200 tree structure test_invoke β”œβ”€β”€ __init__.py β”œβ”€β”€ __pycache__ β”‚Β Β  β”œβ”€β”€ config.cpython-38.pyc β”‚Β Β  └── invoke.cpython-38.pyc β”œβ”€β”€ config.py β”œβ”€β”€ env.yaml β”œβ”€β”€ invoke.py └── main_call.py However when i run, i get the no module found error python3 main_call.py Traceback (most recent call last): File "main_call.py", line 3, in <module> from test_invoke.invoke import end_invoke ModuleNotFoundError: No module named 'test_invoke' A: Python looks for packages and modules in its Python path. It searches (in that order): the current directory (which may not be the path of the current Python module...) the content of the PYTHONPATH environment variable various (implementation and system dependant) system paths As test_invoke is indeed a package, nothing is a priori bad in using it at the root for its modules provided it is accessible from the Python path. But IMHO, it is always a bad idea to directly start a python module that resides inside a package. Better to make the package accessible and then use relative imports inside the package: rename main_call.py to __main__.py replace the offending import line with from .invoke import end_invoke start the package as python -m test_invoke either for the directory containing test_invoke or after adding that directory to the PYTHONPATH environment variable That way, the import will work even if you start your program from a different current directory. A: You are trying to import file available in the current directory. So, please replace line from test_invoke.invoke import end_invoke with from invoke import end_invoke
python issue while importing a module from a file
the below is my main_call.py file from flask import Flask, jsonify, request from test_invoke.invoke import end_invoke from config import config app = Flask(__name__) @app.route("/get/posts", methods=["GET"]) def load_data(): res = "True" # setting a Host url host_url = config()["url"] # getting request parameter and validating it generate_schedule= end_invoke(host_url) if generate_schedule == 200: return jsonify({"status_code": 200, "message": "success"}) elif generate_schedule == 400: return jsonify( {"error": "Invalid ", "status_code": 400} ) if __name__ == "__main__": app.run(debug=True) invoke.py import requests import json import urllib from urllib import request, parse from config import config from flask import request def end_invoke(schedule_url): headers = { "Content-Type":"application/json", } schedule_data = requests.get(schedule_url, headers=headers) if not schedule_data.status_code // 100 == 2: error = schedule_data.json()["error"] print(error) return 400 else: success = schedule_data.json() return 200 tree structure test_invoke β”œβ”€β”€ __init__.py β”œβ”€β”€ __pycache__ β”‚Β Β  β”œβ”€β”€ config.cpython-38.pyc β”‚Β Β  └── invoke.cpython-38.pyc β”œβ”€β”€ config.py β”œβ”€β”€ env.yaml β”œβ”€β”€ invoke.py └── main_call.py However when i run, i get the no module found error python3 main_call.py Traceback (most recent call last): File "main_call.py", line 3, in <module> from test_invoke.invoke import end_invoke ModuleNotFoundError: No module named 'test_invoke'
[ "Python looks for packages and modules in its Python path. It searches (in that order):\n\nthe current directory (which may not be the path of the current Python module...)\nthe content of the PYTHONPATH environment variable\nvarious (implementation and system dependant) system paths\n\nAs test_invoke is indeed a package, nothing is a priori bad in using it at the root for its modules provided it is accessible from the Python path.\nBut IMHO, it is always a bad idea to directly start a python module that resides inside a package. Better to make the package accessible and then use relative imports inside the package:\n\nrename main_call.py to __main__.py\nreplace the offending import line with from .invoke import end_invoke\nstart the package as python -m test_invoke either for the directory containing test_invoke or after adding that directory to the PYTHONPATH environment variable\n\nThat way, the import will work even if you start your program from a different current directory.\n", "You are trying to import file available in the current directory.\nSo, please replace line\nfrom test_invoke.invoke import end_invoke with from invoke import end_invoke\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074667350_python.txt
Q: FPDF Doesn't output accents or simbols i got a huge text in spanish, when i add it to the pdf with Write(5,$text) it outputs well but it doesn't show any accents(Γ©,Γ‘,Γ³) or simbols like $ or &. i've tried using the output in UTF-8 $pdf->Output("I","Contrato",true); but still doesn't show the text like it should. Any other solution? A: You have to decode your utf-8, like so: Write(5, utf8_decode($text)); An alternative is using iconv(), like so: Write(5, iconv('UTF-8', 'iso-8859-1', $text)); A: The code below helped after I spent many hours searching for a hint... setlocale(LC_CTYPE, 'en_US'); $val = iconv('UTF-8', 'iso-8859-1', $variable_containing_special_chars); $pdf->Cell(x_axis,y_axis,$val);
FPDF Doesn't output accents or simbols
i got a huge text in spanish, when i add it to the pdf with Write(5,$text) it outputs well but it doesn't show any accents(Γ©,Γ‘,Γ³) or simbols like $ or &. i've tried using the output in UTF-8 $pdf->Output("I","Contrato",true); but still doesn't show the text like it should. Any other solution?
[ "You have to decode your utf-8, like so:\nWrite(5, utf8_decode($text));\n\nAn alternative is using iconv(), like so:\n Write(5, iconv('UTF-8', 'iso-8859-1', $text));\n\n", "The code below helped after I spent many hours searching for a hint...\n setlocale(LC_CTYPE, 'en_US');\n $val = iconv('UTF-8', 'iso-8859-1', $variable_containing_special_chars);\n $pdf->Cell(x_axis,y_axis,$val);\n\n" ]
[ 3, 0 ]
[]
[]
[ "fpdf", "fpdi", "php", "zend_framework" ]
stackoverflow_0035040464_fpdf_fpdi_php_zend_framework.txt
Q: Fix dates to correct format as days and months interchanged in certain rows I have a dataset that has a date column and it is interchanging days and months in certain rows after importing the dataset. Can someone pls help me find a fix to this? Correct data: First Name Last Name β€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€ŽDateβ€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Ž Start time Duration DetectedArtifactPercentage Average HR (bpm) Average RespR (times/min) Athlete X 02-02-2022 06:59:18 95 9 110 19.48 Athlete X 02-09-2022 06:49:47 143 6 79 13.52 Athlete X 02-09-2022 18:25:23 125 6 114 19.85 Athlete X 03-09-2022 08:31:22 110 5 105 17.57 Athlete X 03-09-2022 18:37:20 152 5 98 15.61 Athlete X 04-09-2022 09:00:34 228 9 132 23.08 Interchanged dates after importing the dataset: First Name Last Name Date Start time Duration ... 0 Athlete X 2022-02-02 06:59:18 95 1 Athlete X 2022-02-09 06:49:47 143 2 Athlete X 2022-02-09 18:25:23 125 3 Athlete X 2022-03-09 08:31:22 110 4 Athlete X 2022-03-09 18:37:20 152 I am not able to fix this. Pls help. A: I assume you're reading data from an excel file, right? And in excel the cells are represented by text, because otherwise it would have been read automatically without a problem. You should have something like this: print(df.Date) Output: 0 02-02-2022 1 02-09-2022 2 02-09-2022 3 03-09-2022 4 03-09-2022 5 04-09-2022 Name: Date, dtype: object Cast it with the formating and you'll be fine: print(pd.to_datetime(df.Date, format='%d-%m-%Y')) Output: 0 2022-02-02 1 2022-09-02 2 2022-09-02 3 2022-09-03 4 2022-09-03 5 2022-09-04 Name: Date, dtype: datetime64[ns] In case it reads as datetime64[ns] in the first place, you may also swap day and month: import datetime df.Date.apply(lambda x: datetime.datetime.strftime(x, '%Y-%d-%m')) Though it should be considered as a duct tape as sooner or later you come across month going beyond 12. Your situation might also happen if you have some exotic date time format on you PC. To make sure that date is converted the right way besides how it is printed, you may try: print(df.Date.dt.day) Output: 0 2 1 2 2 2 3 3 4 3 5 4 Name: Date, dtype: int64
Fix dates to correct format as days and months interchanged in certain rows
I have a dataset that has a date column and it is interchanging days and months in certain rows after importing the dataset. Can someone pls help me find a fix to this? Correct data: First Name Last Name β€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€ŽDateβ€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Žβ€β€β€Ž β€Ž Start time Duration DetectedArtifactPercentage Average HR (bpm) Average RespR (times/min) Athlete X 02-02-2022 06:59:18 95 9 110 19.48 Athlete X 02-09-2022 06:49:47 143 6 79 13.52 Athlete X 02-09-2022 18:25:23 125 6 114 19.85 Athlete X 03-09-2022 08:31:22 110 5 105 17.57 Athlete X 03-09-2022 18:37:20 152 5 98 15.61 Athlete X 04-09-2022 09:00:34 228 9 132 23.08 Interchanged dates after importing the dataset: First Name Last Name Date Start time Duration ... 0 Athlete X 2022-02-02 06:59:18 95 1 Athlete X 2022-02-09 06:49:47 143 2 Athlete X 2022-02-09 18:25:23 125 3 Athlete X 2022-03-09 08:31:22 110 4 Athlete X 2022-03-09 18:37:20 152 I am not able to fix this. Pls help.
[ "I assume you're reading data from an excel file, right? And in excel the cells are represented by text, because otherwise it would have been read automatically without a problem. You should have something like this:\nprint(df.Date)\n\nOutput:\n0 02-02-2022\n1 02-09-2022\n2 02-09-2022\n3 03-09-2022\n4 03-09-2022\n5 04-09-2022\nName: Date, dtype: object\n\nCast it with the formating and you'll be fine:\nprint(pd.to_datetime(df.Date, format='%d-%m-%Y'))\n\nOutput:\n0 2022-02-02\n1 2022-09-02\n2 2022-09-02\n3 2022-09-03\n4 2022-09-03\n5 2022-09-04\nName: Date, dtype: datetime64[ns]\n\nIn case it reads as datetime64[ns] in the first place, you may also swap day and month:\nimport datetime\ndf.Date.apply(lambda x: datetime.datetime.strftime(x, '%Y-%d-%m'))\n\nThough it should be considered as a duct tape as sooner or later you come across month going beyond 12.\nYour situation might also happen if you have some exotic date time format on you PC. To make sure that date is converted the right way besides how it is printed, you may try:\nprint(df.Date.dt.day)\n\nOutput:\n0 2\n1 2\n2 2\n3 3\n4 3\n5 4\nName: Date, dtype: int64\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074667320_dataframe_pandas_python.txt
Q: c curses loop is stuck I'm working on a snake game in c curses and this part of code will be the foundation of the game, but it seems somehow stuck, the box shows up and there is only a single # in it when realistically there should be a lot more since I commented the delay. WINDOW *game_win = newwin(height, width, ym/4 - height/4, xm/4 - width/4); box(game_win, 0, 0); mvwprintw(game_win, height/2, width/2, "#"); wrefresh(game_win); noecho(); nodelay(game_win, TRUE); int position[] = {height / 2, width / 2}; int direction = KEY_RIGHT; //clock_t delay; while(1){ //delay = clock(); //while(clock() < delay + 100000){ direction = wgetch(game_win); //} if(direction == KEY_UP) position[0]++; if(direction == KEY_DOWN) position[0]--; if(direction == KEY_RIGHT) position[1]++; if(direction == KEY_LEFT) position[1]--; mvwprintw(game_win, position[0], position[1], "#"); wrefresh(game_win); } I thought that the wgetch() was pausing the program so I added nodelay, also tried some clearing and redrawing the whole thing but that didn't help either. At this point I really only need this to cycle infinitely with the user having one second to pick a direction until the snake moves (in this case im not erasing the previous position so instead of moving it just get's longer in the given direction). A: Passed your question to ChatGpt, hope this helps :) It looks like the problem is that the wgetch() function is not returning any input, so the direction variable is never being updated and the snake is not moving. One possible reason for this is that you are using the nodelay() function to prevent the wgetch() function from blocking, but you are passing the game_win window as the argument instead of stdscr. The nodelay() function is used to set the stdscr window to be non-blocking, which means that it will not wait for user input before continuing. In your code, you are passing the game_win window to the nodelay() function, but this will not have any effect because the game_win window is not the stdscr window. To fix this problem, you can remove the call to the nodelay() function and instead use the timeout() function to set a timeout for the wgetch() function. This will allow the wgetch() function to return immediately if there is no user input within the specified timeout. Here is an example of how you could modify your code to use the timeout() function: Copy code #include <curses.h> int main(void) { // Set up the screen and create the game window initscr(); int height = 10; int width = 10; int xm, ym; getmaxyx(stdscr, ym, xm); WINDOW *game_win = newwin(height, width, ym/4 - height/4, xm/4 - width/4); box(game_win, 0, 0); mvwprintw(game_win, height/2, width/2, "#"); wrefresh(game_win); noecho(); // Set a timeout for the wgetch() function timeout(1000); // Initialize the snake position and direction int position[] = {height / 2, width / 2}; int direction = KEY_RIGHT; // Run the game loop while(1) { // Get the user input direction = wgetch(game_win); // Update the snake position based on the user input if(direction == KEY_UP) position[0]++; if(direction == KEY_DOWN) position[0]--; if(direction == KEY_RIGHT) position[1]++; if(direction == KEY_LEFT) position[1]--; // Draw the snake at the new position mvwprintw(game_win, position[0], position[1], "#"); wrefresh(game_win); } // Clean up endwin(); return 0; } In this example, the timeout() function is used to set the timeout for the wgetch() function to 1 second. This means that the wgetch() function will return immediately if there is no user input within 1 second. This allows the game to run smoothly and allows the user to control the snake.
c curses loop is stuck
I'm working on a snake game in c curses and this part of code will be the foundation of the game, but it seems somehow stuck, the box shows up and there is only a single # in it when realistically there should be a lot more since I commented the delay. WINDOW *game_win = newwin(height, width, ym/4 - height/4, xm/4 - width/4); box(game_win, 0, 0); mvwprintw(game_win, height/2, width/2, "#"); wrefresh(game_win); noecho(); nodelay(game_win, TRUE); int position[] = {height / 2, width / 2}; int direction = KEY_RIGHT; //clock_t delay; while(1){ //delay = clock(); //while(clock() < delay + 100000){ direction = wgetch(game_win); //} if(direction == KEY_UP) position[0]++; if(direction == KEY_DOWN) position[0]--; if(direction == KEY_RIGHT) position[1]++; if(direction == KEY_LEFT) position[1]--; mvwprintw(game_win, position[0], position[1], "#"); wrefresh(game_win); } I thought that the wgetch() was pausing the program so I added nodelay, also tried some clearing and redrawing the whole thing but that didn't help either. At this point I really only need this to cycle infinitely with the user having one second to pick a direction until the snake moves (in this case im not erasing the previous position so instead of moving it just get's longer in the given direction).
[ "Passed your question to ChatGpt, hope this helps :)\nIt looks like the problem is that the wgetch() function is not returning any input, so the direction variable is never being updated and the snake is not moving. One possible reason for this is that you are using the nodelay() function to prevent the wgetch() function from blocking, but you are passing the game_win window as the argument instead of stdscr.\nThe nodelay() function is used to set the stdscr window to be non-blocking, which means that it will not wait for user input before continuing. In your code, you are passing the game_win window to the nodelay() function, but this will not have any effect because the game_win window is not the stdscr window.\nTo fix this problem, you can remove the call to the nodelay() function and instead use the timeout() function to set a timeout for the wgetch() function. This will allow the wgetch() function to return immediately if there is no user input within the specified timeout.\nHere is an example of how you could modify your code to use the timeout() function:\nCopy code\n#include <curses.h>\n\nint main(void) {\n // Set up the screen and create the game window\n initscr();\n int height = 10;\n int width = 10;\n int xm, ym;\n getmaxyx(stdscr, ym, xm);\n WINDOW *game_win = newwin(height, width, ym/4 - height/4, xm/4 - width/4);\n box(game_win, 0, 0);\n mvwprintw(game_win, height/2, width/2, \"#\");\n wrefresh(game_win);\n noecho();\n\n // Set a timeout for the wgetch() function\n timeout(1000);\n\n // Initialize the snake position and direction\n int position[] = {height / 2, width / 2};\n int direction = KEY_RIGHT;\n\n // Run the game loop\n while(1) {\n // Get the user input\n direction = wgetch(game_win);\n\n // Update the snake position based on the user input\n if(direction == KEY_UP) position[0]++;\n if(direction == KEY_DOWN) position[0]--;\n if(direction == KEY_RIGHT) position[1]++;\n if(direction == KEY_LEFT) position[1]--;\n\n // Draw the snake at the new position\n mvwprintw(game_win, position[0], position[1], \"#\");\n wrefresh(game_win);\n }\n\n // Clean up\n endwin();\n return 0;\n}\n\nIn this example, the timeout() function is used to set the timeout for the wgetch() function to 1 second. This means that the wgetch() function will return immediately if there is no user input within 1 second. This allows the game to run smoothly and allows the user to control the snake.\n" ]
[ 0 ]
[]
[]
[ "c", "curses", "cycle", "infinite_loop" ]
stackoverflow_0074667485_c_curses_cycle_infinite_loop.txt
Q: Create/Update logstash pipelines through rest apis (kibana or logtsash) with pipeline configuration (content of *.conf file) passed as body parameter The most popular way of coding & deploying logstash pipelines is to create a my_pipeline.conf file and run it like bin/logstash -f conf/my_pipeline.conf Elastic offers an alternative consisting of apis: logstash PUT api PUT _logstash/pipeline/my_pipeline { "description": "Sample pipeline for illustration purposes", "last_modified": "2021-01-02T02:50:51.250Z", "pipeline_metadata": { "type": "logstash_pipeline", "version": "1" }, "username": "elastic", "pipeline": "input {}\n filter { grok {} }\n output {}", "pipeline_settings": { "pipeline.workers": 1, "pipeline.batch.size": 125, "pipeline.batch.delay": 50, "queue.type": "memory", "queue.max_bytes.number": 1, "queue.max_bytes.units": "gb", "queue.checkpoint.writes": 1024 } } as well as kibana api that also upsert the logstah pipeline kibana api PUT <kibana host>:<port>/api/logstash/pipeline/<id> $ curl -X PUT api/logstash/pipeline/hello-world { "pipeline": "input { stdin {} } output { stdout {} }", "settings": { "queue.type": "persisted" } } As you can see in both apis, the content of the logstash "pipeline.conf"file is included in the "pipeline" key of the json body of the HTTP call. Basically I have dozens of *.conf pipelines files and I would like to avoid developping complex code to parse them to reformat their content with espace characters for new lines, carriage returns... My question is: do you know an "easy" way to feed this "pipeline" parameter in the body of the HTTP call with as little formatting transformations as possible of the original .conf files? To illustrate how complex this formatting operation might be, I have an example of what a terraform provider does behind the scenes to generate the right expected format from a simple pipeline ".conf" file. Here is the original content of the file logs_alerts_pubsub.conf: input { google_pubsub { project_id => "pj-becfr-monitoring-mgmt" topic => "f7_monitoring_topic_${environment}_alerting_eck" subscription => "f7_monitoring_subscription_${environment}_alerting_eck" json_key_file => "/usr/share/logstash/config/logstash-sa.json" codec => "json" } } filter { mutate { add_field => { "application_code" => "a-alerting-eck" "leanix_id" => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" "workfront_id" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } } } output { elasticsearch { index => "alerts-%%{+yyyy.MM.dd}" hosts => [ "${url}" ] user => "elastic" ssl => true ssl_certificate_verification => false password => "${pwd}" cacert => "/etc/logstash/certificates/ca.crt" } } Here is the terraform code: locals { pipeline_list = fileset(path.root, "./modules/elasticsearch_logstash_pipeline/*.conf") splitpipepath = split("/", var.pipeline) pipename = element(local.splitpipepath, length(local.splitpipepath) - 1) pipename_ex = split(".", local.pipename)[0] category = split("_", local.pipename_ex)[1] } resource "kibana_logstash_pipeline" "newpipeline" { for_each = local.pipeline_list name = "tf-${local.category}-${var.environment}-${local.pipename_ex}" description = "Logstash Pipeline through Kibana from file" pipeline = templatefile(var.pipeline, { environment = var.environment, url = var.elastic_url, pwd = var.elastic_password }) settings = { "queue.type" = "persisted" } } And below you see the content of the tf.state file (focus on the "pipeline" key): { "module": "module.elasticsearch_logstash_pipeline[\"modules/elasticsearch_logstash_pipeline/logs_alerts_pubsub.conf\"]", "mode": "managed", "type": "kibana_logstash_pipeline", "name": "newpipeline", "provider": "provider[\"registry.terraform.io/disaster37/kibana\"]", "instances": [ { "schema_version": 0, "attributes": { "description": "Logstash Pipeline through Kibana from file", "id": "tf-alerts-dev-logs_alerts_pubsub", "name": "tf-alerts-dev-logs_alerts_pubsub", "pipeline": "input {\n google_pubsub {\n project_id =\u003e \"pj-becfr-monitoring-mgmt\"\n topic =\u003e \"f7_monitoring_topic_dev_alerting_eck\"\n subscription =\u003e \"f7_monitoring_subscription_dev_alerting_eck\"\n json_key_file =\u003e \"/usr/share/logstash/config/logstash-sa.json\"\n codec =\u003e \"json\"\n }\n }\nfilter {\n mutate {\n add_field =\u003e { \"application_code\" =\u003e \"a-alerting-eck\"\n \"leanix_id\" =\u003e \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"\n \"workfront_id\" =\u003e \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n }\n }\n}\noutput {\n elasticsearch {\n index =\u003e \"alerts-gcp\"\n hosts =\u003e [ \"https://35.187.29.254:9200\" ]\n user =\u003e \"elastic\"\n ssl =\u003e true\n ssl_certificate_verification =\u003e false\n password =\u003e \"HIDDEN\"\n cacert =\u003e \"/etc/logstash/certificates/ca.crt\"\n }\n}", "settings": { "queue.type": "persisted" }, "username": "elastic" }, "sensitive_attributes": [ [ { "type": "get_attr", "value": "pipeline" } ] ], "private": "bnVsbA==" } ] } If you have any idea of straightforward commands either in bash or in any language where I could do dump/load or encode/decode or any simple regex, as generic as possible, it would be helpful (FYI in this specific context I cannot use terraform) A: I found a way to substitute the variabkes inside the <pipeline>.conf files as well as a way to correctly format the content of that file as json string. To restart from the beginning, here is the content of the logstash pipeline file logs_alerts_pubsub.conf: input { google_pubsub { project_id => "pj-becfr-monitoring-mgmt" topic => "f7_monitoring_topic_${environment}_alerting_eck" subscription => "f7_monitoring_subscription_${environment}_alerting_eck" json_key_file => "/usr/share/logstash/config/logstash-sa.json" codec => "json" } } filter { mutate { add_field => { "application_code" => "a-alerting-eck" "leanix_id" => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" "workfront_id" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } } } output { elasticsearch { index => "alerts-%%{+yyyy.MM.dd}" hosts => [ "${url}" ] user => "elastic" ssl => true ssl_certificate_verification => false password => "${pwd}" cacert => "/etc/logstash/certificates/ca.crt" } } Now the variable substitution with their values: export url=google.com export pwd=HjkTdddddss export environment=dev envsubst < logs_alerts_pubsub.conf input { google_pubsub { project_id => "pj-becfr-monitoring-mgmt" topic => "f7_monitoring_topic_dev_alerting_eck" subscription => "f7_monitoring_subscription_dev_alerting_eck" json_key_file => "/usr/share/logstash/config/logstash-sa.json" codec => "json" } } filter { mutate { add_field => { "application_code" => "a-alerting-eck" "leanix_id" => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" "workfront_id" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } } } output { elasticsearch { index => "alerts-%%{+yyyy.MM.dd}" hosts => [ "google.com" ] user => "elastic" ssl => true ssl_certificate_verification => false password => "HjkTdddddss" cacert => "/etc/logstash/certificates/ca.crt" } } Now the formatting of the pipeline file as json string: jq -c -Rs "." <(envsubst < logs_alerts_pubsub.conf) "input {\n google_pubsub {\n project_id => \"pj-becfr-monitoring-mgmt\"\n topic => \"f7_monitoring_topic_dev_alerting_eck\"\n subscription => \"f7_monitoring_subscription_dev_alerting_eck\"\n json_key_file => \"/usr/share/logstash/config/logstash-sa.json\"\n codec => \"json\"\n }\n }\nfilter {\n mutate {\n add_field => { \"application_code\" => \"a-alerting-eck\"\n \"leanix_id\" => \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"\n \"workfront_id\" => \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n }\n }\n}\noutput {\n elasticsearch {\n index => \"alerts-%%{+yyyy.MM.dd}\"\n hosts => [ \"google.com\" ]\n user => \"elastic\"\n ssl => true\n ssl_certificate_verification => false\n password => \"HjkTdddddss\"\n cacert => \"/etc/logstash/certificates/ca.crt\"\n }\n}"
Create/Update logstash pipelines through rest apis (kibana or logtsash) with pipeline configuration (content of *.conf file) passed as body parameter
The most popular way of coding & deploying logstash pipelines is to create a my_pipeline.conf file and run it like bin/logstash -f conf/my_pipeline.conf Elastic offers an alternative consisting of apis: logstash PUT api PUT _logstash/pipeline/my_pipeline { "description": "Sample pipeline for illustration purposes", "last_modified": "2021-01-02T02:50:51.250Z", "pipeline_metadata": { "type": "logstash_pipeline", "version": "1" }, "username": "elastic", "pipeline": "input {}\n filter { grok {} }\n output {}", "pipeline_settings": { "pipeline.workers": 1, "pipeline.batch.size": 125, "pipeline.batch.delay": 50, "queue.type": "memory", "queue.max_bytes.number": 1, "queue.max_bytes.units": "gb", "queue.checkpoint.writes": 1024 } } as well as kibana api that also upsert the logstah pipeline kibana api PUT <kibana host>:<port>/api/logstash/pipeline/<id> $ curl -X PUT api/logstash/pipeline/hello-world { "pipeline": "input { stdin {} } output { stdout {} }", "settings": { "queue.type": "persisted" } } As you can see in both apis, the content of the logstash "pipeline.conf"file is included in the "pipeline" key of the json body of the HTTP call. Basically I have dozens of *.conf pipelines files and I would like to avoid developping complex code to parse them to reformat their content with espace characters for new lines, carriage returns... My question is: do you know an "easy" way to feed this "pipeline" parameter in the body of the HTTP call with as little formatting transformations as possible of the original .conf files? To illustrate how complex this formatting operation might be, I have an example of what a terraform provider does behind the scenes to generate the right expected format from a simple pipeline ".conf" file. Here is the original content of the file logs_alerts_pubsub.conf: input { google_pubsub { project_id => "pj-becfr-monitoring-mgmt" topic => "f7_monitoring_topic_${environment}_alerting_eck" subscription => "f7_monitoring_subscription_${environment}_alerting_eck" json_key_file => "/usr/share/logstash/config/logstash-sa.json" codec => "json" } } filter { mutate { add_field => { "application_code" => "a-alerting-eck" "leanix_id" => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" "workfront_id" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } } } output { elasticsearch { index => "alerts-%%{+yyyy.MM.dd}" hosts => [ "${url}" ] user => "elastic" ssl => true ssl_certificate_verification => false password => "${pwd}" cacert => "/etc/logstash/certificates/ca.crt" } } Here is the terraform code: locals { pipeline_list = fileset(path.root, "./modules/elasticsearch_logstash_pipeline/*.conf") splitpipepath = split("/", var.pipeline) pipename = element(local.splitpipepath, length(local.splitpipepath) - 1) pipename_ex = split(".", local.pipename)[0] category = split("_", local.pipename_ex)[1] } resource "kibana_logstash_pipeline" "newpipeline" { for_each = local.pipeline_list name = "tf-${local.category}-${var.environment}-${local.pipename_ex}" description = "Logstash Pipeline through Kibana from file" pipeline = templatefile(var.pipeline, { environment = var.environment, url = var.elastic_url, pwd = var.elastic_password }) settings = { "queue.type" = "persisted" } } And below you see the content of the tf.state file (focus on the "pipeline" key): { "module": "module.elasticsearch_logstash_pipeline[\"modules/elasticsearch_logstash_pipeline/logs_alerts_pubsub.conf\"]", "mode": "managed", "type": "kibana_logstash_pipeline", "name": "newpipeline", "provider": "provider[\"registry.terraform.io/disaster37/kibana\"]", "instances": [ { "schema_version": 0, "attributes": { "description": "Logstash Pipeline through Kibana from file", "id": "tf-alerts-dev-logs_alerts_pubsub", "name": "tf-alerts-dev-logs_alerts_pubsub", "pipeline": "input {\n google_pubsub {\n project_id =\u003e \"pj-becfr-monitoring-mgmt\"\n topic =\u003e \"f7_monitoring_topic_dev_alerting_eck\"\n subscription =\u003e \"f7_monitoring_subscription_dev_alerting_eck\"\n json_key_file =\u003e \"/usr/share/logstash/config/logstash-sa.json\"\n codec =\u003e \"json\"\n }\n }\nfilter {\n mutate {\n add_field =\u003e { \"application_code\" =\u003e \"a-alerting-eck\"\n \"leanix_id\" =\u003e \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"\n \"workfront_id\" =\u003e \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n }\n }\n}\noutput {\n elasticsearch {\n index =\u003e \"alerts-gcp\"\n hosts =\u003e [ \"https://35.187.29.254:9200\" ]\n user =\u003e \"elastic\"\n ssl =\u003e true\n ssl_certificate_verification =\u003e false\n password =\u003e \"HIDDEN\"\n cacert =\u003e \"/etc/logstash/certificates/ca.crt\"\n }\n}", "settings": { "queue.type": "persisted" }, "username": "elastic" }, "sensitive_attributes": [ [ { "type": "get_attr", "value": "pipeline" } ] ], "private": "bnVsbA==" } ] } If you have any idea of straightforward commands either in bash or in any language where I could do dump/load or encode/decode or any simple regex, as generic as possible, it would be helpful (FYI in this specific context I cannot use terraform)
[ "I found a way to substitute the variabkes inside the <pipeline>.conf files as well as a way to correctly format the content of that file as json string. To restart from the beginning, here is the content of the logstash pipeline file logs_alerts_pubsub.conf:\ninput {\n google_pubsub {\n project_id => \"pj-becfr-monitoring-mgmt\"\n topic => \"f7_monitoring_topic_${environment}_alerting_eck\"\n subscription => \"f7_monitoring_subscription_${environment}_alerting_eck\"\n json_key_file => \"/usr/share/logstash/config/logstash-sa.json\"\n codec => \"json\"\n }\n }\nfilter {\n mutate {\n add_field => { \"application_code\" => \"a-alerting-eck\"\n \"leanix_id\" => \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"\n \"workfront_id\" => \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n }\n }\n}\noutput {\n elasticsearch {\n index => \"alerts-%%{+yyyy.MM.dd}\"\n hosts => [ \"${url}\" ]\n user => \"elastic\"\n ssl => true\n ssl_certificate_verification => false\n password => \"${pwd}\"\n cacert => \"/etc/logstash/certificates/ca.crt\"\n }\n}\n\nNow the variable substitution with their values:\n\nexport url=google.com\nexport pwd=HjkTdddddss\nexport environment=dev\n\nenvsubst < logs_alerts_pubsub.conf\ninput {\n google_pubsub {\n project_id => \"pj-becfr-monitoring-mgmt\"\n topic => \"f7_monitoring_topic_dev_alerting_eck\"\n subscription => \"f7_monitoring_subscription_dev_alerting_eck\"\n json_key_file => \"/usr/share/logstash/config/logstash-sa.json\"\n codec => \"json\"\n }\n }\nfilter {\n mutate {\n add_field => { \"application_code\" => \"a-alerting-eck\"\n \"leanix_id\" => \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"\n \"workfront_id\" => \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n }\n }\n}\noutput {\n elasticsearch {\n index => \"alerts-%%{+yyyy.MM.dd}\"\n hosts => [ \"google.com\" ]\n user => \"elastic\"\n ssl => true\n ssl_certificate_verification => false\n password => \"HjkTdddddss\"\n cacert => \"/etc/logstash/certificates/ca.crt\"\n }\n}\n\nNow the formatting of the pipeline file as json string:\njq -c -Rs \".\" <(envsubst < logs_alerts_pubsub.conf)\n\"input {\\n google_pubsub {\\n project_id => \\\"pj-becfr-monitoring-mgmt\\\"\\n topic => \\\"f7_monitoring_topic_dev_alerting_eck\\\"\\n subscription => \\\"f7_monitoring_subscription_dev_alerting_eck\\\"\\n json_key_file => \\\"/usr/share/logstash/config/logstash-sa.json\\\"\\n codec => \\\"json\\\"\\n }\\n }\\nfilter {\\n mutate {\\n add_field => { \\\"application_code\\\" => \\\"a-alerting-eck\\\"\\n \\\"leanix_id\\\" => \\\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\\\"\\n \\\"workfront_id\\\" => \\\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\\"\\n }\\n }\\n}\\noutput {\\n elasticsearch {\\n index => \\\"alerts-%%{+yyyy.MM.dd}\\\"\\n hosts => [ \\\"google.com\\\" ]\\n user => \\\"elastic\\\"\\n ssl => true\\n ssl_certificate_verification => false\\n password => \\\"HjkTdddddss\\\"\\n cacert => \\\"/etc/logstash/certificates/ca.crt\\\"\\n }\\n}\"\n\n" ]
[ 0 ]
[]
[]
[ "elk", "kibana", "logstash", "rest" ]
stackoverflow_0074651393_elk_kibana_logstash_rest.txt
Q: How can I change the IP of google cloud functions? **Introduction: ** On Tuesday, 29/11/2022, Binance decided to limit its availability on futures API and trading API. Binance chose to go with geofencing and block multiple locations - including the USA. This caused havoc and problems in multiple services and bots that use binance data. In the fallout after - I reached out to the binance support via multiple channels and received the same response - "not our problem, discuss with google" (example: https://dev.binance.vision/t/google-cloud-and-ip-restriction-451-on-fapi-binance/13820/3) **Problem statement: ** Is there a way to change the IP of my firebase functions for one OUTSIDE of US? I discussed with the support from Binance - they are not changing the limitation. I changed the region to asia-northeast1 still blocked. The IP is in the US (https://ip-geolocation.whoisxmlapi.com/lookup-report/eJ2av1WA5j) - I was hoping this would work and change the IP. A: Answering as Community wiki, As mentioned by John Hanley in above comments. You cannot change the IP address of a function. You can route traffic to a VPC and add a NAT to use a fixed IP address. However, As far as all Google IP addresses map to the address of Google's headquarters in CA.
How can I change the IP of google cloud functions?
**Introduction: ** On Tuesday, 29/11/2022, Binance decided to limit its availability on futures API and trading API. Binance chose to go with geofencing and block multiple locations - including the USA. This caused havoc and problems in multiple services and bots that use binance data. In the fallout after - I reached out to the binance support via multiple channels and received the same response - "not our problem, discuss with google" (example: https://dev.binance.vision/t/google-cloud-and-ip-restriction-451-on-fapi-binance/13820/3) **Problem statement: ** Is there a way to change the IP of my firebase functions for one OUTSIDE of US? I discussed with the support from Binance - they are not changing the limitation. I changed the region to asia-northeast1 still blocked. The IP is in the US (https://ip-geolocation.whoisxmlapi.com/lookup-report/eJ2av1WA5j) - I was hoping this would work and change the IP.
[ "Answering as Community wiki, As mentioned by John Hanley in above comments.\nYou cannot change the IP address of a function. You can route traffic to a VPC and add a NAT to use a fixed IP address. However, As far as all Google IP addresses map to the address of Google's headquarters in CA.\n" ]
[ 1 ]
[]
[]
[ "firebase", "geolocation", "google_cloud_functions", "ip", "typescript" ]
stackoverflow_0074640622_firebase_geolocation_google_cloud_functions_ip_typescript.txt
Q: Why task is not running even when execution is inside the task method? So this is WPF + MVVM + .NET 4.8 + WCT. I have an AsyncRelayCommand in my VM class defined like this: private AsyncRelayCommand _StartSyncCommand; public AsyncRelayCommand StartSyncCommand { get { _StartSyncCommand ??= new AsyncRelayCommand(Pump, () => !_StartSyncCommand.IsRunning); return _StartSyncCommand; } } The actual task method contains an async iterator and looks like this: private async Task Pump(CancellationToken token) { OnPropertyChanged(nameof(IsBusy)); try { await foreach (var item in applicationService.FetchItems()) { token.ThrowIfCancellationRequested(); ... } } catch(Exception ee) { ... } finally { ... } } This method raises property change notification on IsBusy property (to show wait cursor in the UI). However when I check the status of StartSyncCommand in the property, it tells me that it is not running. public bool IsBusy => StartSyncCommand.IsRunning; I can't see why this should be the case. The method is actually running when the property change notification occurs. I can see the method in the call stack. What am I missing here? Update This is getting weirder. StartSyncCommand.ExecutionTask itself is null while I'm inside the task method: A: All asynchronous methods begin executing synchronously, as I explain on my blog. So it's not surprising to me that at the beginning of your async method that its task is null (and thus presumably the busy property is false). I haven't looked at the WCT code, but I expect under the hood it looks something like this: ExecutionTask = execute(); IsRunning = true; (where execute is a delegate pointing to your Pump method) Since Pump hasn't hit its first await yet, it hasn't returned a task yet, so ExecutionTask hasn't been set. You can work around this by doing an await Task.Yield(); at the beginning of Pump, but IMO a cleaner solution would be to move the OnPropertyChanged call outside Pump, or remove it entirely and just forward the property change notifications from IsRunning. A: For anyone facing this problem, here is what I ended up with: private AsyncRelayCommand _StartSyncCommand; public AsyncRelayCommand StartSyncCommand { get { _StartSyncCommand ??= new AsyncRelayCommand(token => { return Task.Run(async () => { OnPropertyChanged(nameof(IsBusy)); await Pump(token); }); }, () => !_StartSyncCommand.IsRunning); return _StartSyncCommand; } } As @Stephen correctly pointed out in his answer, AsyncRelayCommand does not create an run the task it created from the supplied async method till it hits the first await in the method, which means that trying to check IsRunning or ExecutionTask on the command object will not return desired results before that await line is reached. With a Task.Run() call, I'm force-creating and running the task before issuing my property change notifications.
Why task is not running even when execution is inside the task method?
So this is WPF + MVVM + .NET 4.8 + WCT. I have an AsyncRelayCommand in my VM class defined like this: private AsyncRelayCommand _StartSyncCommand; public AsyncRelayCommand StartSyncCommand { get { _StartSyncCommand ??= new AsyncRelayCommand(Pump, () => !_StartSyncCommand.IsRunning); return _StartSyncCommand; } } The actual task method contains an async iterator and looks like this: private async Task Pump(CancellationToken token) { OnPropertyChanged(nameof(IsBusy)); try { await foreach (var item in applicationService.FetchItems()) { token.ThrowIfCancellationRequested(); ... } } catch(Exception ee) { ... } finally { ... } } This method raises property change notification on IsBusy property (to show wait cursor in the UI). However when I check the status of StartSyncCommand in the property, it tells me that it is not running. public bool IsBusy => StartSyncCommand.IsRunning; I can't see why this should be the case. The method is actually running when the property change notification occurs. I can see the method in the call stack. What am I missing here? Update This is getting weirder. StartSyncCommand.ExecutionTask itself is null while I'm inside the task method:
[ "All asynchronous methods begin executing synchronously, as I explain on my blog. So it's not surprising to me that at the beginning of your async method that its task is null (and thus presumably the busy property is false). I haven't looked at the WCT code, but I expect under the hood it looks something like this:\nExecutionTask = execute();\nIsRunning = true;\n\n(where execute is a delegate pointing to your Pump method)\nSince Pump hasn't hit its first await yet, it hasn't returned a task yet, so ExecutionTask hasn't been set.\nYou can work around this by doing an await Task.Yield(); at the beginning of Pump, but IMO a cleaner solution would be to move the OnPropertyChanged call outside Pump, or remove it entirely and just forward the property change notifications from IsRunning.\n", "For anyone facing this problem, here is what I ended up with:\nprivate AsyncRelayCommand _StartSyncCommand;\npublic AsyncRelayCommand StartSyncCommand\n{\n get\n {\n _StartSyncCommand ??= new AsyncRelayCommand(token =>\n {\n return Task.Run(async () =>\n {\n OnPropertyChanged(nameof(IsBusy));\n await Pump(token);\n });\n }, \n () => !_StartSyncCommand.IsRunning);\n return _StartSyncCommand;\n }\n}\n\nAs @Stephen correctly pointed out in his answer, AsyncRelayCommand does not create an run the task it created from the supplied async method till it hits the first await in the method, which means that trying to check IsRunning or ExecutionTask on the command object will not return desired results before that await line is reached. With a Task.Run() call, I'm force-creating and running the task before issuing my property change notifications.\n" ]
[ 1, 0 ]
[]
[]
[ "async_await", "asynchronous", "c#", "mvvm", "task_parallel_library" ]
stackoverflow_0074641148_async_await_asynchronous_c#_mvvm_task_parallel_library.txt
Q: Get python3: can't find '__main__' module even when I have if __name__ == "__main__": in my file I run a py file using a container using sklearn docker image, but I get error python3: can't find '__main__' module my file is something like: def function() if __name__ == "__main__": function() A: are you facing the error with the same piece or code or it's just for reference? From what I can see is you're missing ": "after method declaration. def function(): print("test") if "__main__" == __name__: function()
Get python3: can't find '__main__' module even when I have if __name__ == "__main__": in my file
I run a py file using a container using sklearn docker image, but I get error python3: can't find '__main__' module my file is something like: def function() if __name__ == "__main__": function()
[ "are you facing the error with the same piece or code or it's just for reference?\nFrom what I can see is you're missing \": \"after method declaration.\ndef function():\n print(\"test\")\n\n\nif \"__main__\" == __name__:\n function()\n\n" ]
[ 0 ]
[]
[]
[ "python_3.x", "scikit_learn" ]
stackoverflow_0074664975_python_3.x_scikit_learn.txt
Q: Using inline queries, but doesn't reproduce desired result as comma in not supported in MySQL My database table structure is like below: UID referred referrer 300 302,304 302 303 300 303 305,306,307 302 304 308 300 308 309 304 Now I am trying to count the numbers at the bottom level of the referral chain, which are 305, 306, 307 and 309. here is an image for reference, I want to show this for user 300. I am using these SQL Queries. $sql = "SELECT GROUP_CONCAT(uid) FROM mybb_users WHERE referrer='300'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $abc= $row["uid"]; this produces the uids in comma seperated format. EG: For 300, these are 302 and 304, (it might be more, but right now its these two). lets say these are produced in comma seperated format, i.e. 302,304 Now in next query I want users referred by 302 and 304 in comma seperated format. I used the below query: SELECT uid FROM mybb_users WHERE referrer='$abc' $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $wbc= $row["uid"]; Now this is supposed to fetch the users referred by 302 and 304, which should be 303 and 308. Again, these might be in comma seperated format such as 303,308 and now I want to use this value in the third inline query to get the desired uid numbers for the level C. I am using this query for this: $sql = "SELECT count(*) FROM mybb_users WHERE referrer='$wbc'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row=mysqli_fetch_assoc($result)) { echo $row['count(*)']; } } else { echo "0"; } } And finally this should produce the list of 305, 306, 307 and 309. Instead it's just producing the list of 305, 306 and 307 but not for 309. and count it which would be 4. But it's showing 3. Which means that it's just processing one leg and ignoring the other one. Please let me know how can I achieve the desired result. Thanks. A: You override $wbc in any iteration instead of appending the values. Also note that the order of ids count here (1,2 is not 2,1 but represents the same in your datamodel). If you want all the ids in $wbc as a list then make it an array and implode later: $wbc[] = $row["uid"]; //... implode("," $wbc) // Produces comma separated list You should not use a list of ids in your databse to refer to other records. For many-to-many relationships you should use a join table like user_refferers with 2 columns user_id and refferer_id which links a user to many refferers with one row for each refferrer.
Using inline queries, but doesn't reproduce desired result as comma in not supported in MySQL
My database table structure is like below: UID referred referrer 300 302,304 302 303 300 303 305,306,307 302 304 308 300 308 309 304 Now I am trying to count the numbers at the bottom level of the referral chain, which are 305, 306, 307 and 309. here is an image for reference, I want to show this for user 300. I am using these SQL Queries. $sql = "SELECT GROUP_CONCAT(uid) FROM mybb_users WHERE referrer='300'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $abc= $row["uid"]; this produces the uids in comma seperated format. EG: For 300, these are 302 and 304, (it might be more, but right now its these two). lets say these are produced in comma seperated format, i.e. 302,304 Now in next query I want users referred by 302 and 304 in comma seperated format. I used the below query: SELECT uid FROM mybb_users WHERE referrer='$abc' $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $wbc= $row["uid"]; Now this is supposed to fetch the users referred by 302 and 304, which should be 303 and 308. Again, these might be in comma seperated format such as 303,308 and now I want to use this value in the third inline query to get the desired uid numbers for the level C. I am using this query for this: $sql = "SELECT count(*) FROM mybb_users WHERE referrer='$wbc'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row=mysqli_fetch_assoc($result)) { echo $row['count(*)']; } } else { echo "0"; } } And finally this should produce the list of 305, 306, 307 and 309. Instead it's just producing the list of 305, 306 and 307 but not for 309. and count it which would be 4. But it's showing 3. Which means that it's just processing one leg and ignoring the other one. Please let me know how can I achieve the desired result. Thanks.
[ "You override $wbc in any iteration instead of appending the values.\nAlso note that the order of ids count here (1,2 is not 2,1 but represents the same in your datamodel).\nIf you want all the ids in $wbc as a list then make it an array and implode later:\n$wbc[] = $row[\"uid\"];\n//...\nimplode(\",\" $wbc) // Produces comma separated list\n\nYou should not use a list of ids in your databse to refer to other records.\nFor many-to-many relationships you should use a join table like user_refferers with 2 columns user_id and refferer_id which links a user to many refferers with one row for each refferrer.\n" ]
[ 1 ]
[]
[]
[ "mysql", "php" ]
stackoverflow_0074667474_mysql_php.txt
Q: How to Data bind to deep nested arrays? Angular Forms Background: I am trying to make a three-layered form front-end, the user should be able to fill out the basic details as well as the list object with the title. The list in its entirety needs to be an array the user can add to make a new list in addition to adding individual nested list items: I am using Angular Form Groups and Form Arrays to try and achieve this: Desired Form Inputs / Data Structure: This is the data structure I want to achieve: { "name": "", "email": "", "list": [ { "list_title": "", "list_items": [ { "list_item_1": {}, "list_item_2": {} } ] } ] } Above you can see the desired data to be captured. In the outer form, you can see three fields. I would like to nest list titles and list items within the list field. List items is another array nested within that. The idea is to get to a position where the user can add items and list objects with new items ect.., Code so far I have decided to do this in a two components and have am able to access the outer items but struggling to access my inner array to data bind. Parent-comp.html: <p>form-comp works!</p> <div class="form-container"> <form (ngSubmit)="submit()" [formGroup]="myForm"> <h1>User Registration</h1> <div class="form-group"> <label for="firstname"></label>` <input type="text" placeholder="First Name" formControlName="name" /> <input type="text" placeholder="Surname" formControlName="email" /> <br /> <div formArrayName="list"> <ng-container *ngFor="let myList of listArray.controls; index as i"> <div [formGroupName]="i"> <input type="text" name="firstname" placeholder="List Title" formControlName="name" formControlName="list_title" /> <br /> </div> <!-- // map items here --> <app-products></app-products> </ng-container> <button (click)="addList()">Add List</button> </div> <button type="submit">Submit</button> </div> <br /> <div class="form-check"> {{ myForm.value | json }} <br /> {{ myForm.valid | json }} </div> </form> </div> Parent-comp-tsx export class FormCompComponent implements OnInit { myForm!: FormGroup; constructor (private fb : FormBuilder) { } ngOnInit(): void { this.myForm = new FormGroup({ name: new FormControl('', Validators.required), email: new FormControl('', Validators.required), list: new FormArray([this.initListFormGroup()]), }); } addList() { this.listArray.push(this.initListFormGroup()); } initListFormGroup() { return new FormGroup({ list_title: new FormControl('', Validators.required), list_items: new FormArray([ ProductsComponent.addListItem()]) }); } get listArray() { return this.myForm.get('list') as FormArray; } submit() { console.log(this.myForm.value); } } Thhrough the code above I am able to push new list parent groups to the array and data bind by looping through these fine. I am also calling a static method on the child component to generate a new item with : ProductsComponent.addListItem() Child-comp.html: <form [formGroup]="childForm"> <input type="text" name="list_item" placeholder="List Item" formControlName="name" formControlName="list_item_1" /> </form> export class ProductsComponent { @Input() public childForm!: FormGroup; constructor() {} static addListItem(): FormGroup { return new FormGroup({ list_item_1: new FormGroup(''), list_item_2: new FormGroup(''), }); } } So far I am able to generate my data structure and can see this on screen when I return myForm.value However struggling to map over the child array: <!-- // map items here --> <app-products></app-products> Above is where I believe I need to map over the inner array but not sure what the equivalent function would be to return that Array since its essentially buried. Here is the reference tutorial at the step where my use case begins to depart: https://youtu.be/DEuTcG8DxUI?t=652 Please let me know if this question makes sense I am eager to solve it, thank you! A: This may look complex but the concept is similar that what you work with FormArray in the parent form and you need to ensure that you need to provide the FormGroup index for rendering the nested object in the array. <!-- // map items here --> <ng-container formArrayName="list_items"> <ng-container *ngFor=" let listItem of getListItemArrayFromList(i).controls; index as j " > <app-products [childForm]="asListItemFormGroup(listItem)"></app-products> </ng-container> </ng-container> <button (click)="addListItem(i)">Add List Item</button> getListItemArrayFromList(i: number) { return (this.listArray.get(`${i}`) as FormGroup).get( 'list_items' ) as FormArray; } asListItemFormGroup(listItem: AbstractControl) { return listItem as FormGroup; } addListItem(formGroupIndex: number) { this.getListItemArrayFromList(formGroupIndex).push( ProductsComponent.addListItem() ); } Note that based on your provided data, list_item_1 and list_item_2 are objects, hence you should use formGroupName attribute instead of formControlName attribute, and create a FormGroup template with FormControl(s). <form [formGroup]="childForm"> <input type="text" name="list_item" placeholder="List Item 1" formGroupName="list_item_1" /> <input type="text" name="list_item" placeholder="List Item 2" formGroupName="list_item_2" /> </form> Demo @ StackBlitz
How to Data bind to deep nested arrays? Angular Forms
Background: I am trying to make a three-layered form front-end, the user should be able to fill out the basic details as well as the list object with the title. The list in its entirety needs to be an array the user can add to make a new list in addition to adding individual nested list items: I am using Angular Form Groups and Form Arrays to try and achieve this: Desired Form Inputs / Data Structure: This is the data structure I want to achieve: { "name": "", "email": "", "list": [ { "list_title": "", "list_items": [ { "list_item_1": {}, "list_item_2": {} } ] } ] } Above you can see the desired data to be captured. In the outer form, you can see three fields. I would like to nest list titles and list items within the list field. List items is another array nested within that. The idea is to get to a position where the user can add items and list objects with new items ect.., Code so far I have decided to do this in a two components and have am able to access the outer items but struggling to access my inner array to data bind. Parent-comp.html: <p>form-comp works!</p> <div class="form-container"> <form (ngSubmit)="submit()" [formGroup]="myForm"> <h1>User Registration</h1> <div class="form-group"> <label for="firstname"></label>` <input type="text" placeholder="First Name" formControlName="name" /> <input type="text" placeholder="Surname" formControlName="email" /> <br /> <div formArrayName="list"> <ng-container *ngFor="let myList of listArray.controls; index as i"> <div [formGroupName]="i"> <input type="text" name="firstname" placeholder="List Title" formControlName="name" formControlName="list_title" /> <br /> </div> <!-- // map items here --> <app-products></app-products> </ng-container> <button (click)="addList()">Add List</button> </div> <button type="submit">Submit</button> </div> <br /> <div class="form-check"> {{ myForm.value | json }} <br /> {{ myForm.valid | json }} </div> </form> </div> Parent-comp-tsx export class FormCompComponent implements OnInit { myForm!: FormGroup; constructor (private fb : FormBuilder) { } ngOnInit(): void { this.myForm = new FormGroup({ name: new FormControl('', Validators.required), email: new FormControl('', Validators.required), list: new FormArray([this.initListFormGroup()]), }); } addList() { this.listArray.push(this.initListFormGroup()); } initListFormGroup() { return new FormGroup({ list_title: new FormControl('', Validators.required), list_items: new FormArray([ ProductsComponent.addListItem()]) }); } get listArray() { return this.myForm.get('list') as FormArray; } submit() { console.log(this.myForm.value); } } Thhrough the code above I am able to push new list parent groups to the array and data bind by looping through these fine. I am also calling a static method on the child component to generate a new item with : ProductsComponent.addListItem() Child-comp.html: <form [formGroup]="childForm"> <input type="text" name="list_item" placeholder="List Item" formControlName="name" formControlName="list_item_1" /> </form> export class ProductsComponent { @Input() public childForm!: FormGroup; constructor() {} static addListItem(): FormGroup { return new FormGroup({ list_item_1: new FormGroup(''), list_item_2: new FormGroup(''), }); } } So far I am able to generate my data structure and can see this on screen when I return myForm.value However struggling to map over the child array: <!-- // map items here --> <app-products></app-products> Above is where I believe I need to map over the inner array but not sure what the equivalent function would be to return that Array since its essentially buried. Here is the reference tutorial at the step where my use case begins to depart: https://youtu.be/DEuTcG8DxUI?t=652 Please let me know if this question makes sense I am eager to solve it, thank you!
[ "This may look complex but the concept is similar that what you work with FormArray in the parent form and you need to ensure that you need to provide the FormGroup index for rendering the nested object in the array.\n<!-- // map items here -->\n<ng-container formArrayName=\"list_items\">\n <ng-container\n *ngFor=\"\n let listItem of getListItemArrayFromList(i).controls;\n index as j\n \"\n >\n <app-products [childForm]=\"asListItemFormGroup(listItem)\"></app-products>\n </ng-container>\n</ng-container>\n\n<button (click)=\"addListItem(i)\">Add List Item</button>\n\ngetListItemArrayFromList(i: number) {\n return (this.listArray.get(`${i}`) as FormGroup).get(\n 'list_items'\n ) as FormArray;\n}\n\nasListItemFormGroup(listItem: AbstractControl) {\n return listItem as FormGroup;\n}\n\naddListItem(formGroupIndex: number) {\n this.getListItemArrayFromList(formGroupIndex).push(\n ProductsComponent.addListItem()\n );\n}\n\nNote that based on your provided data, list_item_1 and list_item_2 are objects, hence you should use formGroupName attribute instead of formControlName attribute, and create a FormGroup template with FormControl(s).\n<form [formGroup]=\"childForm\">\n <input\n type=\"text\"\n name=\"list_item\"\n placeholder=\"List Item 1\"\n formGroupName=\"list_item_1\"\n />\n\n <input\n type=\"text\"\n name=\"list_item\"\n placeholder=\"List Item 2\"\n formGroupName=\"list_item_2\"\n />\n</form>\n\nDemo @ StackBlitz\n" ]
[ 0 ]
[]
[]
[ "angular", "angular_forms", "angular_ngmodel", "formarray", "formgroups" ]
stackoverflow_0074667007_angular_angular_forms_angular_ngmodel_formarray_formgroups.txt
Q: Don't understand this ConfigParser.InterpolationSyntaxError So I have tried to write a small config file for my script, which should specify an IP address, a port and a URL which should be created via interpolation using the former two variables. My config.ini looks like this: [Client] recv_url : http://%(recv_host):%(recv_port)/rpm_list/api/ recv_host = 172.28.128.5 recv_port = 5000 column_list = Name,Version,Build_Date,Host,Release,Architecture,Install_Date,Group,Size,License,Signature,Source_RPM,Build_Host,Relocations,Packager,Vendor,URL,Summary In my script I parse this config file as follows: config = SafeConfigParser() config.read('config.ini') column_list = config.get('Client', 'column_list').split(',') URL = config.get('Client', 'recv_url') If I run my script, this results in: Traceback (most recent call last): File "server_side_agent.py", line 56, in <module> URL = config.get('Client', 'recv_url') File "/usr/lib64/python2.7/ConfigParser.py", line 623, in get return self._interpolate(section, option, value, d) File "/usr/lib64/python2.7/ConfigParser.py", line 691, in _interpolate self._interpolate_some(option, L, rawval, section, vars, 1) File "/usr/lib64/python2.7/ConfigParser.py", line 716, in _interpolate_some "bad interpolation variable reference %r" % rest) ConfigParser.InterpolationSyntaxError: bad interpolation variable reference '%(recv_host):%(recv_port)/rpm_list/api/' I have tried debugging, which resulted in giving me one more line of error code: ... ConfigParser.InterpolationSyntaxError: bad interpolation variable reference '%(recv_host):%(recv_port)/rpm_list/api/' Exception AttributeError: "'NoneType' object has no attribute 'path'" in <function _remove at 0x7fc4d32c46e0> ignored Here I am stuck. I don't know where this _remove function is supposed to be... I tried searching for what the message is supposed to tell me, but quite frankly I have no idea. So... Is there something wrong with my code? What does '< function _remove at ... >' mean? A: There was indeed a mistake in my config.ini file. I did not regard the s at the end of %(...)s as a necessary syntax element. I suppose it refers to "string" but I couldn't really confirm this. A: My .ini file for starting the Python Pyramid server had a similar problem. And to use the variable from the .env file, I needed to add the following: %%(VARIEBLE_FOR_EXAMPLE)s But I got other problems, and I solved them with this: How can I use a system environment variable inside a pyramid ini file?
Don't understand this ConfigParser.InterpolationSyntaxError
So I have tried to write a small config file for my script, which should specify an IP address, a port and a URL which should be created via interpolation using the former two variables. My config.ini looks like this: [Client] recv_url : http://%(recv_host):%(recv_port)/rpm_list/api/ recv_host = 172.28.128.5 recv_port = 5000 column_list = Name,Version,Build_Date,Host,Release,Architecture,Install_Date,Group,Size,License,Signature,Source_RPM,Build_Host,Relocations,Packager,Vendor,URL,Summary In my script I parse this config file as follows: config = SafeConfigParser() config.read('config.ini') column_list = config.get('Client', 'column_list').split(',') URL = config.get('Client', 'recv_url') If I run my script, this results in: Traceback (most recent call last): File "server_side_agent.py", line 56, in <module> URL = config.get('Client', 'recv_url') File "/usr/lib64/python2.7/ConfigParser.py", line 623, in get return self._interpolate(section, option, value, d) File "/usr/lib64/python2.7/ConfigParser.py", line 691, in _interpolate self._interpolate_some(option, L, rawval, section, vars, 1) File "/usr/lib64/python2.7/ConfigParser.py", line 716, in _interpolate_some "bad interpolation variable reference %r" % rest) ConfigParser.InterpolationSyntaxError: bad interpolation variable reference '%(recv_host):%(recv_port)/rpm_list/api/' I have tried debugging, which resulted in giving me one more line of error code: ... ConfigParser.InterpolationSyntaxError: bad interpolation variable reference '%(recv_host):%(recv_port)/rpm_list/api/' Exception AttributeError: "'NoneType' object has no attribute 'path'" in <function _remove at 0x7fc4d32c46e0> ignored Here I am stuck. I don't know where this _remove function is supposed to be... I tried searching for what the message is supposed to tell me, but quite frankly I have no idea. So... Is there something wrong with my code? What does '< function _remove at ... >' mean?
[ "There was indeed a mistake in my config.ini file. I did not regard the s at the end of %(...)s as a necessary syntax element. I suppose it refers to \"string\" but I couldn't really confirm this.\n", "My .ini file for starting the Python Pyramid server had a similar problem.\nAnd to use the variable from the .env file, I needed to add the following: %%(VARIEBLE_FOR_EXAMPLE)s\nBut I got other problems, and I solved them with this: How can I use a system environment variable inside a pyramid ini file?\n" ]
[ 16, 0 ]
[]
[]
[ "configparser", "python", "string_interpolation" ]
stackoverflow_0044156665_configparser_python_string_interpolation.txt
Q: "Unexpected token: punc ())" when building for production If I try to test-build my application with ng build --prod --aot I get the following, quite short, error message: $ ng build --prod Date: 2019-01-26T17:26:45.018Z Hash: 979690c7a363996f24b8 Time: 28274ms chunk {0} runtime.ea8176a0aa687d0c7546.js (runtime) 2.23 kB [entry] [rendered] chunk {1} common.78f3e0cd7d0f774768aa.js (common) 583 bytes [rendered] chunk {2} main.5f97cda0f273b510e26a.js (main) 973 kB [initial] [rendered] chunk {3} polyfills.c2a7344c1c84ba3d2a73.js (polyfills) 58.2 kB [initial] [rendered] chunk {4} styles.1094b1dd78a0fa2c8fa7.css (styles) 85 kB [initial] [rendered] chunk {5} 5.92565e561816566c4426.js () 3.74 MB [rendered] chunk {6} 6.a4ec6e690b75a22ddb72.js () 6.3 kB [rendered] ERROR in 5.92565e561816566c4426.js from Terser Unexpected token: punc ()) [5.92565e561816566c4426.js:25865,4] No idea what's causing this. How can I fix this? Last time I checked this worked. I have already tried rm -rf node_modules/. package.json { "name": "mz-admin", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "node server.js", "build": "ng build --prod", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "engines": { "node": "8.12.0", "npm": "6.4.1" }, "private": true, "dependencies": { "@agm/core": "^1.0.0-beta.3", "@angular/animations": "7.1.0", "@angular/cdk": "^7.1.0", "@angular/cli": "7.0.6", "@angular/common": "7.1.0", "@angular/compiler": "7.1.0", "@angular/compiler-cli": "7.1.0", "@angular/core": "7.1.0", "@angular/flex-layout": "^7.0.0-beta.19", "@angular/forms": "7.1.0", "@angular/http": "7.1.0", "@angular/material": "^7.1.0", "@angular/material-moment-adapter": "^7.1.0", "@angular/platform-browser": "7.1.0", "@angular/platform-browser-dynamic": "7.1.0", "@angular/router": "7.1.0", "@fortawesome/angular-fontawesome": "^0.3.0", "@fortawesome/fontawesome-svg-core": "^1.2.4", "@fortawesome/free-brands-svg-icons": "^5.3.1", "@fortawesome/free-solid-svg-icons": "^5.3.1", "@ngx-share/button": "^7.0.0", "@ngx-share/core": "^7.0.0", "@types/braintree-web": "^3.6.4", "angular-mentions": "^0.8.0", "braintree-web": "^3.41.0", "braintree-web-drop-in": "^1.14.1", "chart.js": "^2.7.2", "core-js": "^2.5.7", "express": "^4.16.3", "http-status-codes": "^1.3.0", "ng-pick-datetime": "^7.0.0", "ngx-logger": "^3.1.0", "ngx-moment": "^3.1.0", "ngx-quill": "^4.5.0", "paypal-checkout": "^4.0.239", "quill": "^1.3.6", "quill-mention": "git+https://github.com/silentsnooc/quill-mention.git", "rxjs": "^6.3.2", "typescript": "^3.1.6", "zone.js": "^0.8.26" }, "devDependencies": { "@angular-devkit/build-angular": "^0.10.6", "@angular/language-service": "7.1.0", "@types/googlemaps": "^3.30.16", "@types/jasmine": "^3.3.0", "@types/jasminewd2": "^2.0.6", "@types/node": "~10.12.10", "codelyzer": "^4.5.0", "enhanced-resolve": "^4.1.0", "express-http-proxy": "^1.5.0", "jasmine-core": "~3.3.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~3.1.1", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "^2.0.4", "karma-jasmine": "~2.0.1", "karma-jasmine-html-reporter": "^1.4.0", "protractor": "^5.4.1", "ts-node": "~7.0.1", "tslint": "^5.11.0", "webpack-bundle-analyzer": "^3.0.3" } } Part of the build log [1m[33mWARNING in Terser Plugin: Dropping unused variable template [6.a4ec6e690b75a22ddb72.js:136,12][39m[22m [1m[33mWARNING in Terser Plugin: Dropping unused variable routes [6.a4ec6e690b75a22ddb72.js:148,4][39m[22m [1m[31mERROR in 5.92565e561816566c4426.js from Terser Unexpected token: punc ()) [5.92565e561816566c4426.js:25865,4][39m[22m Child [1mmini-css-extract-plugin node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!node_modules/postcss-loader/src/index.js??extracted!node_modules/sass-loader/lib/loader.js??ref--14-3!src/styles.scss[39m[22m: [1mAsset[39m[22m [1mSize[39m[22m [1mChunks[39m[22m [1m[39m[22m[1m[39m[22m[1mChunk Names[39m[22m [1m[32m3rdpartylicenses.txt[39m[22m 1 bytes [1m[39m[22m [1m[32m[39m[22m Entrypoint [1mmini-css-extract-plugin[39m[22m = [1m[32m*[39m[22m chunk {[1m[33m0[39m[22m} [1m[32m*[39m[22m (mini-css-extract-plugin) 102 KiB[1m[33m [entry][39m[22m[1m[32m [rendered][39m[22m Child [1mmini-css-extract-plugin node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!node_modules/postcss-loader/src/index.js??extracted!node_modules/sass-loader/lib/loader.js??ref--14-3!src/theme.scss[39m[22m: [1mAsset[39m[22m [1mSize[39m[22m [1mChunks[39m[22m [1m[39m[22m[1m[39m[22m[1mChunk Names[39m[22m [1m[32m3rdpartylicenses.txt[39m[22m 1 bytes [1m[39m[22m [1m[32m[39m[22m Entrypoint [1mmini-css-extract-plugin[39m[22m = [1m[32m*[39m[22m chunk {[1m[33m0[39m[22m} [1m[32m*[39m[22m (mini-css-extract-plugin) 55.6 KiB[1m[33m [entry][39m[22m[1m[32m [rendered][39m[22m WARNING in Terser Plugin: global_defs ngDevMode redefined [main.5f97cda0f273b510e26a.js:14309,21] WARNING in Terser Plugin: global_defs ngDevMode redefined [main.5f97cda0f273b510e26a.js:14510,25] WARNING in Terser Plugin: global_defs ngDevMode redefined [main.5f97cda0f273b510e26a.js:15652,21] WARNING in Terser Plugin: global_defs ngDevMode redefined [main.5f97cda0f273b510e26a.js:15658,21] With --source-map $ ng build --prod --aot --source-map Date: 2019-01-26T22:31:44.106Z Hash: 51afc4cc158a10e520c6 Time: 45390ms chunk {0} runtime.b29d49d6f279fff34f57.js, runtime.b29d49d6f279fff34f57.js.map (runtime) 2.29 kB [entry] [rendered] chunk {1} common.70409de1782336a79716.js, common.70409de1782336a79716.js.map (common) 639 bytes [rendered] chunk {2} main.01e8ea6a2dd33c4e19d8.js, main.01e8ea6a2dd33c4e19d8.js.map (main) 970 kB [initial] [rendered] chunk {3} polyfills.22294cd4941de9604b91.js, polyfills.22294cd4941de9604b91.js.map (polyfills) 61.7 kB [initial] [rendered] chunk {4} styles.97ca4c55e9ba593fdf4c.css, styles.97ca4c55e9ba593fdf4c.css.map (styles) 85.5 kB [initial] [rendered] chunk {5} 5.33da963a3dd6decc5efc.js, 5.33da963a3dd6decc5efc.js.map () 1.9 MB [rendered] chunk {6} 6.85bd192b02e86745d878.js, 6.85bd192b02e86745d878.js.map () 6.35 kB [rendered] Without --source-map $ ng build --prod --aot Date: 2019-01-26T22:32:18.173Z Hash: b5bcaa2123bb6718baf2 Time: 28403ms chunk {0} runtime.0935b498984fda7c2e4f.js (runtime) 2.23 kB [entry] [rendered] chunk {1} common.78f3e0cd7d0f774768aa.js (common) 583 bytes [rendered] chunk {2} main.2ae834dcaf8208d7aecd.js (main) 970 kB [initial] [rendered] chunk {3} polyfills.588b345e325a2549098e.js (polyfills) 61.7 kB [initial] [rendered] chunk {4} styles.088d5b7a7a0995d1df55.css (styles) 85.4 kB [initial] [rendered] chunk {5} 5.7e99fa00323b77c4e1c2.js () 3.82 MB [rendered] chunk {6} 6.954a4978d0c6c411bb2f.js () 6.3 kB [rendered] ERROR in 5.7e99fa00323b77c4e1c2.js from Terser Unexpected token: punc ()) [5.7e99fa00323b77c4e1c2.js:27338,4] With --source-map --named-chunks $ ng build --prod --source-map --named-chunks Date: 2019-01-26T23:00:18.699Z Hash: c37b8f2ccfedbbf077fa Time: 61888ms chunk {0} runtime.a670ad696846ba781d64.js, runtime.a670ad696846ba781d64.js.map (runtime) 2.37 kB [entry] [rendered] chunk {1} common.d7fbf062c6d87ac4ade2.js, common.d7fbf062c6d87ac4ade2.js.map (common) 639 bytes [rendered] chunk {2} component-application-application-module-ngfactory.22de247f215039a3cf63.js, component-application-application-module-ngfactory.22de247f215039a3cf63.js.map (component-application-application-module-ngfactory) 1.9 MB [rendered] chunk {3} main.2897da054822ebda9646.js, main.2897da054822ebda9646.js.map (main) 973 kB [initial] [rendered] chunk {4} module-embedding-calendar-calendar-module-ngfactory.5b0025d2f887a5d7b22d.js, module-embedding-calendar-calendar-module-ngfactory.5b0025d2f887a5d7b22d.js.map (module-embedding-calendar-calendar-module-ngfactory) 6.4 kB [rendered] chunk {5} polyfills.04ae14cfab6dbb09ad49.js, polyfills.04ae14cfab6dbb09ad49.js.map (polyfills) 61.7 kB [initial] [rendered] chunk {6} styles.52c1571339895f2464fa.css, styles.52c1571339895f2464fa.css.map (styles) 85.5 kB [initial] [rendered] It seems that ng build --prod --named-chunks --verbose --build-optimizer=false --source-map finally does the trick - with this, I am finally getting the source of the error: ERROR in component-application-application-module-ngfactory.7eb30a010bb7783ce652.js from Terser Unexpected token: punc ()) [./node_modules/quill-mention/src/quill.mention.js:183,0][component-application-application-module-ngfactory.7eb30a010bb7783ce652.js:29528,4] A: It all started with this warning: It was this missing comma, which I put there to silence the warning, which rendered my project uncompileable. I was only able to locate this issue by using --source-map but also setting --build-optimizer=false ng build --prod --named-chunks --verbose --build-optimizer=false --source-map A: After upgrading to angular 8 during production build, I was getting "Error in common-es2015.xxx.js from Terser Unexpected token: Punc(;) [common-es2015.xxx.js] " After setting sourceMap to true in angular.json file - configurations- production section, compiler displayed actual file name with error line number. It was due to an extra semicolon in a variable declaration in the class file. putGamma: any = 0.0;; A: In my case it was a leftover comma at the end of a list of functions inside a custom .js file in \src directory. The tip of by --source-map=true and also setting --build-optimizer=false in angular.json helped me a lot. A: I had the same problem and found out it was caused by https://www.npmjs.com/package/url-parameter-append There was an extra comma after a list of parameters in a function call I removed the comma in my own copy of url-parameter-append.js and then it worked. I reported the bug to the author of that package https://github.com/techinity/url-parameter-append/issues/10 , but really IMO the bug is in the way angular build reports errors in "Terser": an extra comma after a list of parameters is legit in js/ts. A: In my case it was caused by using ES6 in a .js file in a TypeScript Angular project. Refactoring the .js file's code to ES5 fixed the problem. I used ng build --prod --aot to check if the error was gone. A: I downgraded from Angular 15 to Angular 14 and need to re-align ES2022 -> es2020. angular.json "target": "es2020", "module": "es2020", "lib": [ "es2020", "dom" ] A: Try this "configurations": { "production": { "buildOptimizer": false, "optimization": false }, } buildOptimizer and optimization was not present in my package.json for production. So, I guess their default values are true. Adding them and setting them to "false" solved my problem.
"Unexpected token: punc ())" when building for production
If I try to test-build my application with ng build --prod --aot I get the following, quite short, error message: $ ng build --prod Date: 2019-01-26T17:26:45.018Z Hash: 979690c7a363996f24b8 Time: 28274ms chunk {0} runtime.ea8176a0aa687d0c7546.js (runtime) 2.23 kB [entry] [rendered] chunk {1} common.78f3e0cd7d0f774768aa.js (common) 583 bytes [rendered] chunk {2} main.5f97cda0f273b510e26a.js (main) 973 kB [initial] [rendered] chunk {3} polyfills.c2a7344c1c84ba3d2a73.js (polyfills) 58.2 kB [initial] [rendered] chunk {4} styles.1094b1dd78a0fa2c8fa7.css (styles) 85 kB [initial] [rendered] chunk {5} 5.92565e561816566c4426.js () 3.74 MB [rendered] chunk {6} 6.a4ec6e690b75a22ddb72.js () 6.3 kB [rendered] ERROR in 5.92565e561816566c4426.js from Terser Unexpected token: punc ()) [5.92565e561816566c4426.js:25865,4] No idea what's causing this. How can I fix this? Last time I checked this worked. I have already tried rm -rf node_modules/. package.json { "name": "mz-admin", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "node server.js", "build": "ng build --prod", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "engines": { "node": "8.12.0", "npm": "6.4.1" }, "private": true, "dependencies": { "@agm/core": "^1.0.0-beta.3", "@angular/animations": "7.1.0", "@angular/cdk": "^7.1.0", "@angular/cli": "7.0.6", "@angular/common": "7.1.0", "@angular/compiler": "7.1.0", "@angular/compiler-cli": "7.1.0", "@angular/core": "7.1.0", "@angular/flex-layout": "^7.0.0-beta.19", "@angular/forms": "7.1.0", "@angular/http": "7.1.0", "@angular/material": "^7.1.0", "@angular/material-moment-adapter": "^7.1.0", "@angular/platform-browser": "7.1.0", "@angular/platform-browser-dynamic": "7.1.0", "@angular/router": "7.1.0", "@fortawesome/angular-fontawesome": "^0.3.0", "@fortawesome/fontawesome-svg-core": "^1.2.4", "@fortawesome/free-brands-svg-icons": "^5.3.1", "@fortawesome/free-solid-svg-icons": "^5.3.1", "@ngx-share/button": "^7.0.0", "@ngx-share/core": "^7.0.0", "@types/braintree-web": "^3.6.4", "angular-mentions": "^0.8.0", "braintree-web": "^3.41.0", "braintree-web-drop-in": "^1.14.1", "chart.js": "^2.7.2", "core-js": "^2.5.7", "express": "^4.16.3", "http-status-codes": "^1.3.0", "ng-pick-datetime": "^7.0.0", "ngx-logger": "^3.1.0", "ngx-moment": "^3.1.0", "ngx-quill": "^4.5.0", "paypal-checkout": "^4.0.239", "quill": "^1.3.6", "quill-mention": "git+https://github.com/silentsnooc/quill-mention.git", "rxjs": "^6.3.2", "typescript": "^3.1.6", "zone.js": "^0.8.26" }, "devDependencies": { "@angular-devkit/build-angular": "^0.10.6", "@angular/language-service": "7.1.0", "@types/googlemaps": "^3.30.16", "@types/jasmine": "^3.3.0", "@types/jasminewd2": "^2.0.6", "@types/node": "~10.12.10", "codelyzer": "^4.5.0", "enhanced-resolve": "^4.1.0", "express-http-proxy": "^1.5.0", "jasmine-core": "~3.3.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~3.1.1", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "^2.0.4", "karma-jasmine": "~2.0.1", "karma-jasmine-html-reporter": "^1.4.0", "protractor": "^5.4.1", "ts-node": "~7.0.1", "tslint": "^5.11.0", "webpack-bundle-analyzer": "^3.0.3" } } Part of the build log [1m[33mWARNING in Terser Plugin: Dropping unused variable template [6.a4ec6e690b75a22ddb72.js:136,12][39m[22m [1m[33mWARNING in Terser Plugin: Dropping unused variable routes [6.a4ec6e690b75a22ddb72.js:148,4][39m[22m [1m[31mERROR in 5.92565e561816566c4426.js from Terser Unexpected token: punc ()) [5.92565e561816566c4426.js:25865,4][39m[22m Child [1mmini-css-extract-plugin node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!node_modules/postcss-loader/src/index.js??extracted!node_modules/sass-loader/lib/loader.js??ref--14-3!src/styles.scss[39m[22m: [1mAsset[39m[22m [1mSize[39m[22m [1mChunks[39m[22m [1m[39m[22m[1m[39m[22m[1mChunk Names[39m[22m [1m[32m3rdpartylicenses.txt[39m[22m 1 bytes [1m[39m[22m [1m[32m[39m[22m Entrypoint [1mmini-css-extract-plugin[39m[22m = [1m[32m*[39m[22m chunk {[1m[33m0[39m[22m} [1m[32m*[39m[22m (mini-css-extract-plugin) 102 KiB[1m[33m [entry][39m[22m[1m[32m [rendered][39m[22m Child [1mmini-css-extract-plugin node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!node_modules/postcss-loader/src/index.js??extracted!node_modules/sass-loader/lib/loader.js??ref--14-3!src/theme.scss[39m[22m: [1mAsset[39m[22m [1mSize[39m[22m [1mChunks[39m[22m [1m[39m[22m[1m[39m[22m[1mChunk Names[39m[22m [1m[32m3rdpartylicenses.txt[39m[22m 1 bytes [1m[39m[22m [1m[32m[39m[22m Entrypoint [1mmini-css-extract-plugin[39m[22m = [1m[32m*[39m[22m chunk {[1m[33m0[39m[22m} [1m[32m*[39m[22m (mini-css-extract-plugin) 55.6 KiB[1m[33m [entry][39m[22m[1m[32m [rendered][39m[22m WARNING in Terser Plugin: global_defs ngDevMode redefined [main.5f97cda0f273b510e26a.js:14309,21] WARNING in Terser Plugin: global_defs ngDevMode redefined [main.5f97cda0f273b510e26a.js:14510,25] WARNING in Terser Plugin: global_defs ngDevMode redefined [main.5f97cda0f273b510e26a.js:15652,21] WARNING in Terser Plugin: global_defs ngDevMode redefined [main.5f97cda0f273b510e26a.js:15658,21] With --source-map $ ng build --prod --aot --source-map Date: 2019-01-26T22:31:44.106Z Hash: 51afc4cc158a10e520c6 Time: 45390ms chunk {0} runtime.b29d49d6f279fff34f57.js, runtime.b29d49d6f279fff34f57.js.map (runtime) 2.29 kB [entry] [rendered] chunk {1} common.70409de1782336a79716.js, common.70409de1782336a79716.js.map (common) 639 bytes [rendered] chunk {2} main.01e8ea6a2dd33c4e19d8.js, main.01e8ea6a2dd33c4e19d8.js.map (main) 970 kB [initial] [rendered] chunk {3} polyfills.22294cd4941de9604b91.js, polyfills.22294cd4941de9604b91.js.map (polyfills) 61.7 kB [initial] [rendered] chunk {4} styles.97ca4c55e9ba593fdf4c.css, styles.97ca4c55e9ba593fdf4c.css.map (styles) 85.5 kB [initial] [rendered] chunk {5} 5.33da963a3dd6decc5efc.js, 5.33da963a3dd6decc5efc.js.map () 1.9 MB [rendered] chunk {6} 6.85bd192b02e86745d878.js, 6.85bd192b02e86745d878.js.map () 6.35 kB [rendered] Without --source-map $ ng build --prod --aot Date: 2019-01-26T22:32:18.173Z Hash: b5bcaa2123bb6718baf2 Time: 28403ms chunk {0} runtime.0935b498984fda7c2e4f.js (runtime) 2.23 kB [entry] [rendered] chunk {1} common.78f3e0cd7d0f774768aa.js (common) 583 bytes [rendered] chunk {2} main.2ae834dcaf8208d7aecd.js (main) 970 kB [initial] [rendered] chunk {3} polyfills.588b345e325a2549098e.js (polyfills) 61.7 kB [initial] [rendered] chunk {4} styles.088d5b7a7a0995d1df55.css (styles) 85.4 kB [initial] [rendered] chunk {5} 5.7e99fa00323b77c4e1c2.js () 3.82 MB [rendered] chunk {6} 6.954a4978d0c6c411bb2f.js () 6.3 kB [rendered] ERROR in 5.7e99fa00323b77c4e1c2.js from Terser Unexpected token: punc ()) [5.7e99fa00323b77c4e1c2.js:27338,4] With --source-map --named-chunks $ ng build --prod --source-map --named-chunks Date: 2019-01-26T23:00:18.699Z Hash: c37b8f2ccfedbbf077fa Time: 61888ms chunk {0} runtime.a670ad696846ba781d64.js, runtime.a670ad696846ba781d64.js.map (runtime) 2.37 kB [entry] [rendered] chunk {1} common.d7fbf062c6d87ac4ade2.js, common.d7fbf062c6d87ac4ade2.js.map (common) 639 bytes [rendered] chunk {2} component-application-application-module-ngfactory.22de247f215039a3cf63.js, component-application-application-module-ngfactory.22de247f215039a3cf63.js.map (component-application-application-module-ngfactory) 1.9 MB [rendered] chunk {3} main.2897da054822ebda9646.js, main.2897da054822ebda9646.js.map (main) 973 kB [initial] [rendered] chunk {4} module-embedding-calendar-calendar-module-ngfactory.5b0025d2f887a5d7b22d.js, module-embedding-calendar-calendar-module-ngfactory.5b0025d2f887a5d7b22d.js.map (module-embedding-calendar-calendar-module-ngfactory) 6.4 kB [rendered] chunk {5} polyfills.04ae14cfab6dbb09ad49.js, polyfills.04ae14cfab6dbb09ad49.js.map (polyfills) 61.7 kB [initial] [rendered] chunk {6} styles.52c1571339895f2464fa.css, styles.52c1571339895f2464fa.css.map (styles) 85.5 kB [initial] [rendered] It seems that ng build --prod --named-chunks --verbose --build-optimizer=false --source-map finally does the trick - with this, I am finally getting the source of the error: ERROR in component-application-application-module-ngfactory.7eb30a010bb7783ce652.js from Terser Unexpected token: punc ()) [./node_modules/quill-mention/src/quill.mention.js:183,0][component-application-application-module-ngfactory.7eb30a010bb7783ce652.js:29528,4]
[ "It all started with this warning:\n\nIt was this missing comma, which I put there to silence the warning, which rendered my project uncompileable. \nI was only able to locate this issue by using --source-map but also setting --build-optimizer=false\nng build --prod --named-chunks --verbose --build-optimizer=false --source-map\n\n", "After upgrading to angular 8 during production build, I was getting \"Error in common-es2015.xxx.js from Terser Unexpected token: Punc(;) [common-es2015.xxx.js] \" \nAfter setting sourceMap to true in angular.json file - configurations- production section, compiler displayed actual file name with error line number. It was due to an extra semicolon in a variable declaration in the class file.\nputGamma: any = 0.0;; \n\n", "In my case it was a leftover comma at the end of a list of functions inside a custom .js file in \\src directory.\nThe tip of by --source-map=true and also setting --build-optimizer=false in angular.json helped me a lot.\n", "I had the same problem and found out it was caused by https://www.npmjs.com/package/url-parameter-append\nThere was an extra comma after a list of parameters in a function call\nI removed the comma in my own copy of url-parameter-append.js and then it worked.\nI reported the bug to the author of that package https://github.com/techinity/url-parameter-append/issues/10 , but really IMO the bug is\n\nin the way angular build reports errors\nin \"Terser\": an extra comma after a list of parameters is legit in js/ts.\n\n", "In my case it was caused by using ES6 in a .js file in a TypeScript Angular project. Refactoring the .js file's code to ES5 fixed the problem. I used ng build --prod --aot to check if the error was gone.\n", "I downgraded from Angular 15 to Angular 14 and need to re-align ES2022 -> es2020.\nangular.json\n \"target\": \"es2020\",\n \"module\": \"es2020\",\n \"lib\": [\n \"es2020\",\n \"dom\"\n ]\n\n", "Try this\n\"configurations\": {\n \"production\": {\n \"buildOptimizer\": false,\n \"optimization\": false\n },\n }\n\nbuildOptimizer and optimization was not present in my package.json for production. So, I guess their default values are true. Adding them and setting them to \"false\" solved my problem.\n" ]
[ 37, 12, 3, 1, 1, 1, 0 ]
[]
[]
[ "angular", "eslint" ]
stackoverflow_0054380816_angular_eslint.txt
Q: Using `react-oidc-context` ho do we remove the `grant_id` and `code` from the URL post login? I have a SPA, which is protected using the PKCE authentication flow via the JavaScript library react-oidc-context. Once a user successfully authenticates, they are redirected back to the desired URL, except that react-oidc-context is adding two query string parameters, grant_id and code. Below is an example of the URL users are redirected to after successfully authenticating: https://spa.example.com/?grant_id=239020443&code=2930293029r4jiojokfjdfjsdof30940403433 I'm a bit OCD, and so these two additional query string parameters are bothering me. I understand during the PKCE authentication flow these query string parameters are needed. But once the user is successfully authenticated, I would like the user to be sent to the root URL without the OIDC-related query strings appended on the URL. For example: https://spa.example.com How can I configure react-oidc-context to remove the grant_id and code from the URL post-authentication? A: It is already mentioned on the official documentation here https://github.com/authts/react-oidc-context you need to provide onSigninCallback in your oidcConfig. const onSigninCallback = (_user: User | void): void => { window.history.replaceState( {}, document.title, window.location.pathname ) } You can use it to trim the query params returned by identity provider.
Using `react-oidc-context` ho do we remove the `grant_id` and `code` from the URL post login?
I have a SPA, which is protected using the PKCE authentication flow via the JavaScript library react-oidc-context. Once a user successfully authenticates, they are redirected back to the desired URL, except that react-oidc-context is adding two query string parameters, grant_id and code. Below is an example of the URL users are redirected to after successfully authenticating: https://spa.example.com/?grant_id=239020443&code=2930293029r4jiojokfjdfjsdof30940403433 I'm a bit OCD, and so these two additional query string parameters are bothering me. I understand during the PKCE authentication flow these query string parameters are needed. But once the user is successfully authenticated, I would like the user to be sent to the root URL without the OIDC-related query strings appended on the URL. For example: https://spa.example.com How can I configure react-oidc-context to remove the grant_id and code from the URL post-authentication?
[ "It is already mentioned on the official documentation here https://github.com/authts/react-oidc-context\nyou need to provide onSigninCallback in your oidcConfig.\nconst onSigninCallback = (_user: User | void): void => {\n window.history.replaceState(\n {},\n document.title,\n window.location.pathname\n )\n}\n\nYou can use it to trim the query params returned by identity provider.\n" ]
[ 0 ]
[]
[]
[ "openid_connect", "react_oidc" ]
stackoverflow_0074369601_openid_connect_react_oidc.txt
Q: why floatingActionButton ddidn't work with flutter? I have to run an action on FloatingActionButton. For testing if it works or pressed right I juste create a simple print inside the onPressed() but I got nothing in the terminal. this is my code: @override Widget buildView() { return Scaffold( appBar: AppBar( title: const Text('Find Devices'), ), // body: floatingActionButton: FloatingActionButton( onPressed: () => print("Scan Button"), backgroundColor: Colors.blue, child: const Icon(Icons.search), ), ); } A: It looks like you are using the buildView method from a StatefulWidget. In order for the FloatingActionButton to actually show up on the screen, you will need to return it from the build method of your StatefulWidget instead of buildView. Try modifying your code like this: @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Find Devices'), ), floatingActionButton: FloatingActionButton( onPressed: () => print("Scan Button"), backgroundColor: Colors.blue, child: const Icon(Icons.search), ), ); }
why floatingActionButton ddidn't work with flutter?
I have to run an action on FloatingActionButton. For testing if it works or pressed right I juste create a simple print inside the onPressed() but I got nothing in the terminal. this is my code: @override Widget buildView() { return Scaffold( appBar: AppBar( title: const Text('Find Devices'), ), // body: floatingActionButton: FloatingActionButton( onPressed: () => print("Scan Button"), backgroundColor: Colors.blue, child: const Icon(Icons.search), ), ); }
[ "It looks like you are using the buildView method from a StatefulWidget. In order for the FloatingActionButton to actually show up on the screen, you will need to return it from the build method of your StatefulWidget instead of buildView.\nTry modifying your code like this:\n@override\nWidget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: const Text('Find Devices'),\n ),\n floatingActionButton: FloatingActionButton(\n onPressed: () =>\n print(\"Scan Button\"),\n backgroundColor: Colors.blue,\n child: const Icon(Icons.search),\n ),\n );\n}\n\n" ]
[ 2 ]
[]
[]
[ "action", "dart", "floating_action_button", "flutter", "flutter_onpressed" ]
stackoverflow_0074667498_action_dart_floating_action_button_flutter_flutter_onpressed.txt
Q: Why is it possible to index an object that has type never? With strict enabled in tsconfig.json, why does tsc not issue an error when indexing an object of type never? const mystery = ({ foo: 1 } as never) console.log(mystery['foo']) // no error console.log(mystery.foo) // Property 'foo' does not exist on type 'never'. export {} Playground example A: It's bug #41021: 'never' (and probably 'void') shouldn't be silently indexable types DanielRosenwasser commented on Oct 10, 2020 let x = [1, 2, 3, 4].forEach(x => { console.log(x)); x["hello"] = 123; Expected: an error that x is possibly void or something Actual: no errors DanielRosenwasser commented on Oct 10, 2020 Actually, never seems to suffer from the same issue.. The TypeScript team are actively fixing it, but no fix is available yet. Here's a simpler replication: declare let mystery: never; console.log(mystery["foo"]); // No error console.log(mystery.foo); // Property 'foo' does not exist on type 'never'.
Why is it possible to index an object that has type never?
With strict enabled in tsconfig.json, why does tsc not issue an error when indexing an object of type never? const mystery = ({ foo: 1 } as never) console.log(mystery['foo']) // no error console.log(mystery.foo) // Property 'foo' does not exist on type 'never'. export {} Playground example
[ "It's bug #41021:\n\n'never' (and probably 'void') shouldn't be silently indexable types\nDanielRosenwasser commented on Oct 10, 2020\nlet x = [1, 2, 3, 4].forEach(x => { console.log(x));\nx[\"hello\"] = 123;\n\nExpected: an error that x is possibly void or something\nActual: no errors\n\nDanielRosenwasser commented on Oct 10, 2020\nActually, never seems to suffer from the same issue..\n\nThe TypeScript team are actively fixing it, but no fix is available yet.\nHere's a simpler replication:\ndeclare let mystery: never;\n\nconsole.log(mystery[\"foo\"]); // No error\nconsole.log(mystery.foo); // Property 'foo' does not exist on type 'never'.\n\n" ]
[ 1 ]
[ "The never type in TypeScript represents a value that will never occur. In other words, it represents a value that is impossible to obtain. Because of this, it is not possible to access any properties or methods on a value of type never.\nHowever, in the code you provided, the mystery variable is not actually of type never. It is of type { foo: number }. This is because TypeScript type assertions allow you to override the type of a value. In this case, the type assertion as never is telling TypeScript to treat the value of mystery as if it were of type never, even though it is actually of a different type. This is why the first console.log statement does not produce an error.\nThe second console.log statement does produce an error because it is trying to access a property on a value of type never, which is not allowed.\nIn short, the reason the code you provided is able to index an object of type never is because the object is not actually of type never, but rather of a different type that has been temporarily \"overridden\" by a type assertion.\n" ]
[ -1 ]
[ "typescript" ]
stackoverflow_0074667505_typescript.txt
Q: Cannot fetch the latest record from the database I am trying to get the latest record from the Database (Derby database). I have a BILL table in the database that has a column BillId. The data type of BillId is varchar(15) and is in the format as: 3122022-1 The digits before the "-" (i.e., 3122022) are according to the date (3/12/2002). The value after the "-" is the bill counter (i.e., 1). The problem is, when I try to get the latest record from the database using max(BILLID), it considers 3122022-9 as the maximum/latest record even if the billId 3122022-10 or higher exists. In simple words, it ignores the 0 or any value placed at the second place after "-". Why is this issue happening and what is the solution?? Here is the table structure: Bill table I used the following query: select max(billId) as lastBill from Bill where empName='Hassan' and Date=Current Date; empName is important as there are 4-5 employees and each will have their own count of Bill. If I run this query: select billid from bill order by empName desc; I get this result: Bill ids when I sort them by empName column But if I run the max(billId) query, This is what I get: select max(billId) as lastBill from Bill where empName='Hassan' and Date=Current Date; max(billid) results I hope I was able to explain my question well. Will be grateful for your help and support. I tried max(billId) A: i came up with sample dataset and query. //Postgres sql with data as ( select 'A' as emp_name,'03122022-1' as dated_on union select 'A' as emp_name,'03122022-2' as dated_on union select 'A' as emp_name,'03122022-3' as dated_on union select 'A' as emp_name,'03122022-4' as dated_on union select 'A' as emp_name,'03122022-5' as dated_on union select 'A' as emp_name,'03122022-6' as dated_on ) , data_clean as ( select emp_name,dated_on, to_date((regexp_split_to_array (dated_on,'-'))[1],'DDMMYYYY') as bill_dated_on, (regexp_split_to_array (dated_on,'-'))[2] ::int as bill_id from data) select emp_name,max(bill_id) from data_clean where bill_dated_on='20221203' group by emp_name; emp_name|max| --------+---+ A | 6|
Cannot fetch the latest record from the database
I am trying to get the latest record from the Database (Derby database). I have a BILL table in the database that has a column BillId. The data type of BillId is varchar(15) and is in the format as: 3122022-1 The digits before the "-" (i.e., 3122022) are according to the date (3/12/2002). The value after the "-" is the bill counter (i.e., 1). The problem is, when I try to get the latest record from the database using max(BILLID), it considers 3122022-9 as the maximum/latest record even if the billId 3122022-10 or higher exists. In simple words, it ignores the 0 or any value placed at the second place after "-". Why is this issue happening and what is the solution?? Here is the table structure: Bill table I used the following query: select max(billId) as lastBill from Bill where empName='Hassan' and Date=Current Date; empName is important as there are 4-5 employees and each will have their own count of Bill. If I run this query: select billid from bill order by empName desc; I get this result: Bill ids when I sort them by empName column But if I run the max(billId) query, This is what I get: select max(billId) as lastBill from Bill where empName='Hassan' and Date=Current Date; max(billid) results I hope I was able to explain my question well. Will be grateful for your help and support. I tried max(billId)
[ "i came up with sample dataset and query.\n//Postgres sql\nwith data as\n(\nselect 'A' as emp_name,'03122022-1' as dated_on\nunion\nselect 'A' as emp_name,'03122022-2' as dated_on\nunion\nselect 'A' as emp_name,'03122022-3' as dated_on\nunion\nselect 'A' as emp_name,'03122022-4' as dated_on\nunion\nselect 'A' as emp_name,'03122022-5' as dated_on\nunion\nselect 'A' as emp_name,'03122022-6' as dated_on\n\n)\n,\ndata_clean as (\nselect emp_name,dated_on,\nto_date((regexp_split_to_array (dated_on,'-'))[1],'DDMMYYYY') as bill_dated_on,\n(regexp_split_to_array (dated_on,'-'))[2] ::int as bill_id\nfrom data)\n\nselect emp_name,max(bill_id) from data_clean\nwhere bill_dated_on='20221203'\ngroup by emp_name;\n\nemp_name|max|\n--------+---+\nA | 6|\n\n" ]
[ 0 ]
[]
[]
[ "derby", "java", "sql" ]
stackoverflow_0074667385_derby_java_sql.txt
Q: How to place play image in the middle of the teal square? How would this be done? https://jsfiddle.net/mLwcyj9u/ Can you help me? I am trying to place the play image in the middle of the teal square. That is all I am trying to do. Place the play image inside the teal square. Those are all the details. That is everything. I provided a snippet below. .channel-tile { -webkit-box-sizing: border-box; box-sizing: border-box; border-radius: 4px; width: 180px; float: left; display: block; margin-bottom: 18px; background: #2E2E2E; position: relative; } .channel-tile__image-area { width: 180px; height: 0; padding-top: 100%; position: relative; z-index: 0; border-radius: 4px; background: red; border: 1px solid blue; } .channel-tile__artwork { position: absolute; left: 0; top: 0; bottom: 0; right: 0; margin: auto; width: 170px; height: 170px; -webkit-box-sizing: border-box; box-sizing: border-box; z-index: 0; background: teal; } .cover { -webkit-appearance: none; appearance: none; display: flex; justify-content: center; align-items: center; position: relative; width: 72px; height: 72px; border-radius: 50%; cursor: pointer; border: 9px solid blue; background: transparent; filter: drop-shadow(3px 3px 3px rgba(0, 0, 0, 0.7)); } .cover::before { content: ""; width: 0; height: 0; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-left: 27px solid blue; transform: translateX(4px); } <div class="channel-tile"> <div class="channel-tile__image-area"> <span class="channel-tile__artwork"></span> </div> </div> <div class="cover"> </div> A: Simple, place your .cover element inside the -area and in CSS use position absolute (etc) just like you did for __artwork. .channel-tile { -webkit-box-sizing: border-box; box-sizing: border-box; border-radius: 4px; width: 180px; float: left; display: block; margin-bottom: 18px; background: #2E2E2E; position: relative; } .channel-tile__image-area { width: 180px; height: 0; padding-top: 100%; position: relative; z-index: 0; border-radius: 4px; background: red; border: 1px solid blue; } .channel-tile__artwork { position: absolute; left: 0; top: 0; bottom: 0; right: 0; margin: auto; width: 170px; height: 170px; -webkit-box-sizing: border-box; box-sizing: border-box; z-index: 0; background: teal; } .cover { -webkit-appearance: none; appearance: none; display: flex; justify-content: center; align-items: center; position: relative; width: 72px; height: 72px; border-radius: 50%; cursor: pointer; border: 9px solid blue; background: transparent; filter: drop-shadow(3px 3px 3px rgba(0, 0, 0, 0.7)); position: absolute; left: 0; top: 0; bottom: 0; right: 0; margin: auto; } .cover::before { content: ""; width: 0; height: 0; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-left: 27px solid blue; transform: translateX(4px); } <div class="channel-tile"> <div class="channel-tile__image-area"> <span class="channel-tile__artwork"></span> <div class="cover"></div> </div> </div> Avoid using float. Use flex instead.
How to place play image in the middle of the teal square?
How would this be done? https://jsfiddle.net/mLwcyj9u/ Can you help me? I am trying to place the play image in the middle of the teal square. That is all I am trying to do. Place the play image inside the teal square. Those are all the details. That is everything. I provided a snippet below. .channel-tile { -webkit-box-sizing: border-box; box-sizing: border-box; border-radius: 4px; width: 180px; float: left; display: block; margin-bottom: 18px; background: #2E2E2E; position: relative; } .channel-tile__image-area { width: 180px; height: 0; padding-top: 100%; position: relative; z-index: 0; border-radius: 4px; background: red; border: 1px solid blue; } .channel-tile__artwork { position: absolute; left: 0; top: 0; bottom: 0; right: 0; margin: auto; width: 170px; height: 170px; -webkit-box-sizing: border-box; box-sizing: border-box; z-index: 0; background: teal; } .cover { -webkit-appearance: none; appearance: none; display: flex; justify-content: center; align-items: center; position: relative; width: 72px; height: 72px; border-radius: 50%; cursor: pointer; border: 9px solid blue; background: transparent; filter: drop-shadow(3px 3px 3px rgba(0, 0, 0, 0.7)); } .cover::before { content: ""; width: 0; height: 0; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-left: 27px solid blue; transform: translateX(4px); } <div class="channel-tile"> <div class="channel-tile__image-area"> <span class="channel-tile__artwork"></span> </div> </div> <div class="cover"> </div>
[ "Simple, place your .cover element inside the -area and in CSS use position absolute (etc) just like you did for __artwork.\n\n\n.channel-tile {\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n border-radius: 4px;\n width: 180px;\n float: left;\n display: block;\n margin-bottom: 18px;\n background: #2E2E2E;\n position: relative;\n}\n\n.channel-tile__image-area {\n width: 180px;\n height: 0;\n padding-top: 100%;\n position: relative;\n z-index: 0;\n border-radius: 4px;\n background: red;\n border: 1px solid blue;\n}\n\n.channel-tile__artwork {\n position: absolute;\n left: 0;\n top: 0;\n bottom: 0;\n right: 0;\n margin: auto;\n width: 170px;\n height: 170px;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n z-index: 0;\n background: teal;\n}\n\n.cover {\n -webkit-appearance: none;\n appearance: none;\n display: flex;\n justify-content: center;\n align-items: center;\n position: relative;\n width: 72px;\n height: 72px;\n border-radius: 50%;\n cursor: pointer;\n border: 9px solid blue;\n background: transparent;\n filter: drop-shadow(3px 3px 3px rgba(0, 0, 0, 0.7));\n \n position: absolute;\n left: 0;\n top: 0;\n bottom: 0;\n right: 0;\n margin: auto;\n}\n\n.cover::before {\n content: \"\";\n width: 0;\n height: 0;\n border-top: 20px solid transparent;\n border-bottom: 20px solid transparent;\n border-left: 27px solid blue;\n transform: translateX(4px);\n}\n<div class=\"channel-tile\">\n <div class=\"channel-tile__image-area\">\n <span class=\"channel-tile__artwork\"></span>\n <div class=\"cover\"></div>\n </div>\n</div>\n\n\n\nAvoid using float. Use flex instead.\n" ]
[ 1 ]
[]
[]
[ "css", "css_position" ]
stackoverflow_0074667463_css_css_position.txt
Q: error in sdk manager visual studio "cannot find central directory" Hello I am parsa when i want to download anything from sdk manager it will give me error for e.g I'm trying to use android emulator and download it's packages but when i want to download them it will show me this I try to download another packages but it will get me error to and again the error is "cannot find central directory" how should i do to solve it. A: I have the same problem too. I have Instaled Visual Studio Enterprise 2022 Version 17.0.0 Preview 6.0 Visual Studio Enterprise 2019 Version 16.11.4 Preview 1.0 And both of them have Xamarin Installed. I Uninstall Xamarin from both of them, Reinstalled it On VS 2022, and now it's working for me. A: You have to Use VPN or shecan.ir and change DNS Addresses Regards!
error in sdk manager visual studio "cannot find central directory"
Hello I am parsa when i want to download anything from sdk manager it will give me error for e.g I'm trying to use android emulator and download it's packages but when i want to download them it will show me this I try to download another packages but it will get me error to and again the error is "cannot find central directory" how should i do to solve it.
[ "I have the same problem too.\nI have Instaled\n\nVisual Studio Enterprise 2022 Version 17.0.0 Preview 6.0\nVisual Studio Enterprise 2019 Version 16.11.4 Preview 1.0\n\nAnd both of them have Xamarin Installed.\nI Uninstall Xamarin from both of them, Reinstalled it On VS 2022, and now it's working for me.\n", "You have to Use VPN or shecan.ir and change DNS Addresses\nRegards!\n" ]
[ 0, 0 ]
[]
[]
[ "android", "android_sdk_manager", "visual_studio_2019", "xamarin" ]
stackoverflow_0067279152_android_android_sdk_manager_visual_studio_2019_xamarin.txt
Q: filter query mongoldb Golang I am trying to get a list of data that match specific queries but I am getting this error "(AtlasError) merchant is not allowed or the syntax is incorrect, see the Atlas documentation for more information" func ... var result []*model.Package ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() tokenData, err := middleware.CtxValue(ctx) if err != nil { return nil, err } orQuery := []bson.M{} merchant := "abc" completedQuery := bson.M{"status": "completed"} cancelledQuery := bson.M{"status": "cancelled"} orQuery = append( orQuery, cancelledQuery, completedQuery) limit64 := int64(limit) page64 := int64(page) match := bson.M{"$match": bson.M{"$nor": orQuery}} var filterQuery primitive.M if tokenData.Role == "admin" && merchant != nil { filterQuery = bson.M{"merchant": bson.M{"id": merchant}} } else { filterQuery = bson.M{"user": bson.M{"id": tokenData.Id}} } paginatedData, err1 := paginate.New(r.Collection).Context(ctx).Limit(limit64).Page(page64).Aggregate(match, filterQuery) if err1 != nil { return nil, err1 } ... A: filterQuery, which seems to contain { "merchant" : { "id" : "abc" } }, is being passed sepearately to .Aggregate(). But the aggregation framework is expecting to receive something that represents a sequence of pipeline stages. Each of these stages, outlined here in the documentation, are expected to begin with a $ character such as the $match stage. Currently the database is attempting to process merchant as an options for the pipeline (see here and here). But such an option doesn't exist, hence the error message. To resolve this, you should incorporate the filterQuery logic into the existing match variable/stage that you are building and passing. Alternatively you can wrap filterQuery in a different $match and then pass both of them (as a single argument) to .Aggregate(). This example in the documentation shows they build multiple stages and then submit them together to .Aggregate() via mongo.Pipeline{...}: // create the stages matchStage := bson.D{{"$match", bson.D{{"toppings", "milk foam"}}}} unsetStage := bson.D{{"$unset", bson.A{"_id", "category"}}} sortStage := bson.D{{"$sort", bson.D{ {"price", 1}, {"toppings", 1}}, }} limitStage := bson.D{{"$limit", 2}} // pass the stage into a pipeline // pass the pipeline as the second paramter in the Aggregate() method cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, unsetStage, sortStage, limitStage})
filter query mongoldb Golang
I am trying to get a list of data that match specific queries but I am getting this error "(AtlasError) merchant is not allowed or the syntax is incorrect, see the Atlas documentation for more information" func ... var result []*model.Package ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() tokenData, err := middleware.CtxValue(ctx) if err != nil { return nil, err } orQuery := []bson.M{} merchant := "abc" completedQuery := bson.M{"status": "completed"} cancelledQuery := bson.M{"status": "cancelled"} orQuery = append( orQuery, cancelledQuery, completedQuery) limit64 := int64(limit) page64 := int64(page) match := bson.M{"$match": bson.M{"$nor": orQuery}} var filterQuery primitive.M if tokenData.Role == "admin" && merchant != nil { filterQuery = bson.M{"merchant": bson.M{"id": merchant}} } else { filterQuery = bson.M{"user": bson.M{"id": tokenData.Id}} } paginatedData, err1 := paginate.New(r.Collection).Context(ctx).Limit(limit64).Page(page64).Aggregate(match, filterQuery) if err1 != nil { return nil, err1 } ...
[ "filterQuery, which seems to contain { \"merchant\" : { \"id\" : \"abc\" } }, is being passed sepearately to .Aggregate(). But the aggregation framework is expecting to receive something that represents a sequence of pipeline stages. Each of these stages, outlined here in the documentation, are expected to begin with a $ character such as the $match stage.\nCurrently the database is attempting to process merchant as an options for the pipeline (see here and here). But such an option doesn't exist, hence the error message.\nTo resolve this, you should incorporate the filterQuery logic into the existing match variable/stage that you are building and passing. Alternatively you can wrap filterQuery in a different $match and then pass both of them (as a single argument) to .Aggregate().\nThis example in the documentation shows they build multiple stages and then submit them together to .Aggregate() via mongo.Pipeline{...}:\n// create the stages\nmatchStage := bson.D{{\"$match\", bson.D{{\"toppings\", \"milk foam\"}}}}\nunsetStage := bson.D{{\"$unset\", bson.A{\"_id\", \"category\"}}}\nsortStage := bson.D{{\"$sort\", bson.D{\n {\"price\", 1},\n {\"toppings\", 1}},\n}}\nlimitStage := bson.D{{\"$limit\", 2}}\n\n// pass the stage into a pipeline\n// pass the pipeline as the second paramter in the Aggregate() method\ncursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, unsetStage, sortStage, limitStage})\n\n" ]
[ 0 ]
[]
[]
[ "go", "mongodb", "mongodb_atlas" ]
stackoverflow_0074663983_go_mongodb_mongodb_atlas.txt
Q: Adding photo background via VS Code May I ask on how to add photo background on my website using VS Code? I tried checking in yt but its not background, it just add up to my website as photo alone. A: In css:- background-imge:url(""); i think this maybe helpful for everyone. A: using css background-image: url("url") // it is the best practice but you will have to also set some addtional css properties like .div{ background-image: url("../images/demo.png"); background-repeat: no-repeat; background-size: 300px 400px; background-origin: content-box; background-position: center; } try these the url can be a link to some hosted image file or it can be a local image as showed in the example try these Accept the answer if this helps
Adding photo background via VS Code
May I ask on how to add photo background on my website using VS Code? I tried checking in yt but its not background, it just add up to my website as photo alone.
[ "In css:-\nbackground-imge:url(\"\");\ni think this maybe helpful for everyone.\n", "using css background-image: url(\"url\") // it is the best practice\nbut you will have to also set some addtional css properties like\n\n\n.div{\nbackground-image: url(\"../images/demo.png\");\nbackground-repeat: no-repeat;\nbackground-size: 300px 400px;\nbackground-origin: content-box;\nbackground-position: center;\n}\n\n\n\ntry these\nthe url can be a link to some hosted image file or\nit can be a local image as showed in the example try these\nAccept the answer if this helps\n" ]
[ 0, 0 ]
[]
[]
[ "background_image", "css", "html" ]
stackoverflow_0074667069_background_image_css_html.txt
Q: SBT gives java.lang.NullPointerException when trying to run spark I'm trying to compile spark with sbt 1.7.2 on a Linux machine which system is CentOs6. When I try to run clean command: ./build/sbt clean I get the following output: java.lang.NullPointerException at sun.net.util.URLUtil.urlNoFragString(URLUtil.java:50) at sun.misc.URLClassPath.getLoader(URLClassPath.java:526) at sun.misc.URLClassPath.getNextLoader(URLClassPath.java:498) at sun.misc.URLClassPath.getResource(URLClassPath.java:252) at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:363) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:362) at java.lang.ClassLoader.loadClass(ClassLoader.java:419) at java.lang.ClassLoader.loadClass(ClassLoader.java:406) at java.lang.ClassLoader.loadClass(ClassLoader.java:406) at java.lang.ClassLoader.loadClass(ClassLoader.java:406) at java.lang.ClassLoader.loadClass(ClassLoader.java:406) at java.lang.ClassLoader.loadClass(ClassLoader.java:352) at sbt.internal.XMainConfiguration.run(XMainConfiguration.java:51) at sbt.xMain.run(Main.scala:46) at xsbt.boot.Launch$.$anonfun$run$1(Launch.scala:149) at xsbt.boot.Launch$.withContextLoader(Launch.scala:176) at xsbt.boot.Launch$.run(Launch.scala:149) at xsbt.boot.Launch$.$anonfun$apply$1(Launch.scala:44) at xsbt.boot.Launch$.launch(Launch.scala:159) at xsbt.boot.Launch$.apply(Launch.scala:44) at xsbt.boot.Launch$.apply(Launch.scala:21) at xsbt.boot.Boot$.runImpl(Boot.scala:78) at xsbt.boot.Boot$.run(Boot.scala:73) at xsbt.boot.Boot$.main(Boot.scala:21) at xsbt.boot.Boot.main(Boot.scala) [error] [launcher] error during sbt launcher: java.lang.NullPointerException It also happened when I use sbt 1.7.3, But it can success clean and compile spark when I use sbt 1.6.2. What should I check first? I'd really appreciate any advice anyone can offer. A: Several advices how to debug Spark and sbt. How to build Spark in IntelliJ. Clone https://github.com/apache/spark , open it in IntelliJ as sbt project. I had to execute sbt compile and re-open the project before I can run my code in IntelliJ (I had an error object SqlBaseParser is not a member of package org.apache.spark.sql.catalyst.parser before that). For example I can put the following object in sql/core/src/main/scala and run/debug it in IntelliJ // scalastyle:off import org.apache.spark.sql.{Dataset, SparkSession} object MyMain extends App { val spark = SparkSession.builder() .master("local") .appName("SparkTestApp") .getOrCreate() case class Person(id: Long, name: String) import spark.implicits._ val df: Dataset[Person] = spark.range(10).map(i => Person(i, i.toString)) df.show() //+---+----+ //| id|name| //+---+----+ //| 0| 0| //| 1| 1| //| 2| 2| //| 3| 3| //| 4| 4| //| 5| 5| //| 6| 6| //| 7| 7| //| 8| 8| //| 9| 9| //+---+----+ } I also pressed Run npm install, Load Maven project when these pop-up windows appeared but I haven't noticed the difference. Also once I had to keep in Project Structure in sql/catalyst/target/scala-2.12/src_managed only one source root sql/catalyst/target/scala-2.12/src_managed/main (and not sql/catalyst/target/scala-2.12/src_managed/main/antlr4). I had errors like SqlBaseLexer is already defined as class SqlBaseLexer before that. Build Apache Spark Source Code with IntelliJ IDEA: https://yujheli-wordpress-com.translate.goog/2020/03/26/build-apache-spark-source-code-with-intellij-idea/?_x_tr_sl=auto&_x_tr_tl=en&_x_tr_hl=uk&_x_tr_pto=wapp (original in Chinese: https://yujheli.wordpress.com/2020/03/26/build-apache-spark-source-code-with-intellij-idea/ ) Why does building Spark sources give "object sbt is not a member of package com.typesafe"? How to build sbt in IntelliJ. sbt itself is tricky https://www.lihaoyi.com/post/SowhatswrongwithSBT.html and building it is a little tricky too. Clone https://github.com/sbt/sbt , open it in IntelliJ. Let's try to run the previous Spark code using this cloned sbt. sbt seems to be not intended to run in a specified directory. I put the following object in client/src/main/scala object MyClient extends App { System.setProperty("user.dir", "../spark") sbt.client.Client.main(Array("sql/runMain MyMain")) } (Generally, mutating the system property user.dir is not recommended: How to use "cd" command using Java runtime?) I had to execute sbt compile firstly (this includes the command sbt generateContrabands --- sbt uses sbt plugin sbt-contraband (ContrabandPlugin, JsonCodecPlugin), formerly sbt-datatype, for code generation: https://github.com/sbt/contraband https://www.scala-sbt.org/contraband/ https://www.scala-sbt.org/1.x/docs/Datatype.html https://github.com/eed3si9n/gigahorse/tree/develop/core/src/main/contraband). I had error not found: value ScalaKeywords before that. Next error is type ExcludeItem is not a member of package sbt.internal.bsp. You can just remove in protocol/src/main/contraband-scala/sbt/internal/bsp/codec the files ExcludeItemFormats.scala, ExcludesItemFormats.scala, ExcludesParamsFormats.scala, ExcludesResultFormats.scala. They are outdated auto-generated files. You can check that if you remove the content of directory protocol/src/main/contraband-scala (this is a root for auto-generated sources) and execute sbt generateContrabands all the files except these four will be restored. For some reason these files didn't confuse sbt but confuse IntelliJ. Now MyClient produces while running //[info] +---+----+ //[info] | id|name| //[info] +---+----+ //[info] | 0| 0| //[info] | 1| 1| //[info] | 2| 2| //[info] | 3| 3| //[info] | 4| 4| //[info] | 5| 5| //[info] | 6| 6| //[info] | 7| 7| //[info] | 8| 8| //[info] | 9| 9| //[info] +---+----+ sbt.client.Client is called the thin client. Alternatively, you can publish it locally and use as a dependency build.sbt (https://github.com/sbt/sbt/blob/v1.8.0/build.sbt#L1160) lazy val sbtClientProj = (project in file("client")) .enablePlugins(NativeImagePlugin) .dependsOn(commandProj) .settings( commonBaseSettings, scalaVersion := "2.12.11", publish / skip := false, // change true to false name := "sbt-client", ....... sbt publishLocal A new project: build.sbt scalaVersion := "2.12.17" // ~/.ivy2/local/org.scala-sbt/sbt-client/1.8.1-SNAPSHOT/jars/sbt-client.jar libraryDependencies += "org.scala-sbt" % "sbt-client" % "1.8.1-SNAPSHOT" src/main/scala/Main.scala object Main extends App { System.setProperty("user.dir", "../spark") sbt.client.Client.main(Array("sql/runMain MyMain")) //[info] +---+----+ //[info] | id|name| //[info] +---+----+ //[info] | 0| 0| //[info] | 1| 1| //[info] | 2| 2| //[info] | 3| 3| //[info] | 4| 4| //[info] | 5| 5| //[info] | 6| 6| //[info] | 7| 7| //[info] | 8| 8| //[info] | 9| 9| //[info] +---+----+ } But the thin client is not how sbt normally runs. sbt.xMain from your stack trace is from https://github.com/sbt/sbt . It's here: https://github.com/sbt/sbt/blob/1.8.x/main/src/main/scala/sbt/Main.scala#L44 But xsbt.boot.Boot from the stack trace is not from this repo, it's from https://github.com/sbt/launcher , namely https://github.com/sbt/launcher/blob/1.x/launcher-implementation/src/main/scala/xsbt/boot/Boot.scala The thing is that sbt runs in two steps. The sbt executable (usually downloaded from https://www.scala-sbt.org/download.html#universal-packages) is a shell script, firstly it runs sbt-launch.jar (the object xsbt.boot.Boot) https://github.com/sbt/sbt/blob/v1.8.0/sbt#L507-L512 execRunner "$java_cmd" \ "${java_args[@]}" \ "${sbt_options[@]}" \ -jar "$sbt_jar" \ "${sbt_commands[@]}" \ "${residual_args[@]}" and secondly the latter reflectively calls sbt (the class sbt.xMain) https://github.com/sbt/launcher/blob/v1.4.1/launcher-implementation/src/main/scala/xsbt/boot/Launch.scala#L147-L149 val main = appProvider.newMain() try { withContextLoader(appProvider.loader)(main.run(appConfig)) https://github.com/sbt/launcher/blob/v1.4.1/launcher-implementation/src/main/scala/xsbt/boot/Launch.scala#L496 // implementation of the above appProvider.newMain() else if (AppMainClass.isAssignableFrom(entryPoint)) mainClass.newInstance https://github.com/sbt/launcher/blob/v1.4.1/launcher-implementation/src/main/scala/xsbt/boot/PlainApplication.scala#L13 // implementation of the above main.run(appConfig) mainMethod.invoke(null, configuration.arguments).asInstanceOf[xsbti.Exit] Then xMain#run via XMainConfiguration#run reflectively calls xMain.run https://github.com/sbt/sbt/blob/v1.8.0/main/src/main/scala/sbt/Main.scala#L44-L47 class xMain extends xsbti.AppMain { def run(configuration: xsbti.AppConfiguration): xsbti.MainResult = new XMainConfiguration().run("xMain", configuration) } https://github.com/sbt/sbt/blob/v1.8.0/main/src/main/java/sbt/internal/XMainConfiguration.java#L51-L57 Class<?> clazz = loader.loadClass("sbt." + moduleName + "$"); Object instance = clazz.getField("MODULE$").get(null); Method runMethod = clazz.getMethod("run", xsbti.AppConfiguration.class); try { ..... return (xsbti.MainResult) runMethod.invoke(instance, updatedConfiguration); What is the launcher. Let's consider a helloworld for the launcher. The launcher consists of a library (interfaces) https://mvnrepository.com/artifact/org.scala-sbt/launcher-interface https://github.com/sbt/launcher/tree/1.x/launcher-interface and the launcher runnable jar https://mvnrepository.com/artifact/org.scala-sbt/launcher https://github.com/sbt/launcher/tree/1.x/launcher-implementation/src Create a project (depending on launcher interfaces at compile tome) build.sbt lazy val root = (project in file(".")) .settings( name := "scalademo", organization := "com.example", version := "0.1.0-SNAPSHOT", scalaVersion := "2.13.10", libraryDependencies ++= Seq( "org.scala-sbt" % "launcher-interface" % "1.4.1" % Provided, ), ) src/main/scala/mypackage/Main.scala package mypackage import xsbti.{AppConfiguration, AppMain, Exit, MainResult} class Main extends AppMain { def run(configuration: AppConfiguration): MainResult = { val scalaVersion = configuration.provider.scalaProvider.version println(s"Hello, World! Running Scala $scalaVersion") configuration.arguments.foreach(println) new Exit { override val code: Int = 0 } } } Do sbt publishLocal. The project jar will be published at ~/.ivy2/local/com.example/scalademo_2.13/0.1.0-SNAPSHOT/jars/scalademo_2.13.jar Download launcher runnable jar https://repo1.maven.org/maven2/org/scala-sbt/launcher/1.4.1/launcher-1.4.1.jar Create launcher configuration my.app.configuration [scala] version: 2.13.10 [app] org: com.example name: scalademo version: 0.1.0-SNAPSHOT class: mypackage.Main cross-versioned: binary [repositories] local maven-central [boot] directory: ${user.home}/.myapp/boot Then command java -jar launcher-1.4.1.jar @my.app.configuration a b c produces //Hello world! Running Scala 2.13.10 //a //b //c There appeared files ~/.myapp/boot/scala-2.13.10/com.example/scalademo/0.1.0-SNAPSHOT scalademo_2.13.jar scala-library-2.13.10.jar ~/.myapp/boot/scala-2.13.10/lib java-diff-utils-4.12.jar jna-5.9.0.jar jline-3.21.0.jar scala-library.jar scala-compiler.jar scala-reflect.jar So launcher helps to run application in environments with only Java installed (Scala is not necessary), Ivy dependency resolution will be used. There are features to handle return codes, reboot application with a different Scala version, launch servers etc. Alternatively, any of the following commands can be used java -Dsbt.boot.properties=my.app.configuration -jar launcher-1.4.1.jar java -jar launcher-repacked.jar # put my.app.configuration to sbt/sbt.boot.properties/ and repack the jar https://www.scala-sbt.org/1.x/docs/Launcher-Getting-Started.html How to run sbt with the launcher. Sbt https://github.com/sbt/sbt uses sbt plugin SbtLauncherPlugin https://github.com/sbt/sbt/blob/v1.8.0/project/SbtLauncherPlugin.scala so that from the raw launcher launcher https://github.com/sbt/launcher/tree/1.x/launcher-implementation/src https://mvnrepository.com/artifact/org.scala-sbt/launcher it builds sbt-launch https://github.com/sbt/sbt/tree/v1.8.0/launch https://mvnrepository.com/artifact/org.scala-sbt/sbt-launch Basically, sbt-launch is different from launcher in having default config sbt.boot.properties injected. Working directory can be set either 1) in sbt.xMain (sbt) or 2) in xsbt.boot.Boot (sbt-launcher). 1) // make xMain non-final so that it can be extended /*final*/ class xMain extends xsbti.AppMain { ........... https://github.com/sbt/sbt/blob/v1.8.0/main/src/main/scala/sbt/Main.scala#L44 import sbt.xMain import xsbti.{ AppConfiguration, AppProvider, MainResult } import java.io.File class MyXMain extends xMain { override def run(configuration: AppConfiguration): MainResult = { val args = configuration.arguments val (dir, rest) = if (args.length >= 1 && args(0).startsWith("dir=")) { ( Some(args(0).stripPrefix("dir=")), args.drop(1) ) } else { (None, args) } dir.foreach { dir => System.setProperty("user.dir", dir) } // xMain.run(new AppConfiguration { // not ok // new xMain().run(new AppConfiguration { // not ok super[xMain].run(new AppConfiguration { override val arguments: Array[String] = rest override val baseDirectory: File = dir.map(new File(_)).getOrElse(configuration.baseDirectory) override val provider: AppProvider = configuration.provider }) } } sbt publishLocal my.sbt.configuration [scala] version: auto #version: 2.12.17 [app] org: org.scala-sbt name: sbt #name: main # not ok version: 1.8.1-SNAPSHOT class: MyXMain #class: sbt.xMain components: xsbti,extra cross-versioned: false #cross-versioned: binary [repositories] local maven-central [boot] directory: ${user.home}/.mysbt/boot [ivy] ivy-home: ${user.home}/.ivy2 java -jar launcher-1.4.1.jar @my.sbt.configuration dir=/path_to_spark/spark "sql/runMain MyMain" or java -jar sbt-launch.jar @my.sbt.configuration dir=/path_to_spark/spark "sql/runMain MyMain" //[info] +---+----+ //[info] | id|name| //[info] +---+----+ //[info] | 0| 0| //[info] | 1| 1| //[info] | 2| 2| //[info] | 3| 3| //[info] | 4| 4| //[info] | 5| 5| //[info] | 6| 6| //[info] | 7| 7| //[info] | 8| 8| //[info] | 9| 9| //[info] +---+----+ (sbt-launch.jar is taken from ~/.ivy2/local/org.scala-sbt/sbt-launch/1.8.1-SNAPSHOT/jars) I had to copy scalastyle-config.xml from spark, otherwise it wasn't found. Still I have warnings fatal: Not a git repository (or any parent up to mount parent ...) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set). 2) project/Dependencies.scala (https://github.com/sbt/sbt/blob/v1.8.0/project/Dependencies.scala#L25) val launcherVersion = "1.4.2-SNAPSHOT" // modified Clone https://github.com/sbt/launcher and make the following changes build.sbt (https://github.com/sbt/launcher/blob/v1.4.1/build.sbt#L11) ThisBuild / version := { val orig = (ThisBuild / version).value if (orig.endsWith("-SNAPSHOT")) "1.4.2-SNAPSHOT" // modified else orig } launcher-implementation/src/main/scala/xsbt/boot/Launch.scala (https://github.com/sbt/launcher/blob/v1.4.1/launcher-implementation/src/main/scala/xsbt/boot/Launch.scala#L17 #L21) class LauncherArguments( val args: List[String], val isLocate: Boolean, val isExportRt: Boolean, val dir: Option[String] = None // added ) object Launch { def apply(arguments: LauncherArguments): Option[Int] = apply((new File(arguments.dir.getOrElse(""))).getAbsoluteFile, arguments) // modified ............. launcher-implementation/src/main/scala/xsbt/boot/Boot.scala (https://github.com/sbt/launcher/blob/v1.4.1/launcher-implementation/src/main/scala/xsbt/boot/Boot.scala#L41-L67) def parseArgs(args: Array[String]): LauncherArguments = { @annotation.tailrec def parse( args: List[String], isLocate: Boolean, isExportRt: Boolean, remaining: List[String], dir: Option[String] // added ): LauncherArguments = args match { ................... case "--locate" :: rest => parse(rest, true, isExportRt, remaining, dir) // modified case "--export-rt" :: rest => parse(rest, isLocate, true, remaining, dir) // modified // added case "--mydir" :: next :: rest => parse(rest, isLocate, isExportRt, remaining, Some(next)) case next :: rest => parse(rest, isLocate, isExportRt, next :: remaining, dir) // modified case Nil => new LauncherArguments(remaining.reverse, isLocate, isExportRt, dir) // modified } parse(args.toList, false, false, Nil, None) } sbt-launcher: sbt publishLocal sbt: sbt publishLocal my.sbt.configuration [scala] version: auto [app] org: org.scala-sbt name: sbt version: 1.8.1-SNAPSHOT #class: MyXMain class: sbt.xMain components: xsbti,extra cross-versioned: false [repositories] local maven-central [boot] directory: ${user.home}/.mysbt/boot [ivy] ivy-home: ${user.home}/.ivy2 java -jar launcher-1.4.2-SNAPSHOT.jar @my.sbt.configuration --mydir /path_to_spark/spark "sql/runMain MyMain" or java -jar sbt-launch.jar @my.sbt.configuration --mydir /path_to_spark/spark "sql/runMain MyMain" Alternatively, we can specify "program arguments" in "Run configuration" for xsbt.boot.Boot in IntelliJ @/path_to_sbt_config/my.sbt.configuration --mydir /path_to_spark/spark "sql/runMain MyMain" Also it's possible to specify working directory /path_to_spark/spark in "Run configuration" in IntelliJ. Then remaining "program arguments" are @/path_to_sbt_config/my.sbt.configuration "sql/runMain MyMain" I tried to use "org.scala-sbt" % "launcher" % "1.4.2-SNAPSHOT" or "org.scala-sbt" % "sbt-launch" % "1.8.1-SNAPSHOT" as a dependency but got No RuntimeVisibleAnnotations in classfile with ScalaSignature attribute: class Boot. Your setting. So we can run/debug sbt-launcher code in IntelliJ and/or with printlns and run/debug sbt code with printlns (because there is no runnable object). From your stack trace I have suspection that one of classloader urls is null https://github.com/openjdk/jdk/blob/jdk8-b120/jdk/src/share/classes/sun/misc/URLClassPath.java#L82 Maybe you can add to sbt.xMain#run or MyXMain#run something like var cl = getClass.getClassLoader while (cl != null) { println(s"classloader: ${cl.getClass.getName}") cl match { case cl: URLClassLoader => println("classloader urls:") cl.getURLs.foreach(println) case _ => println("not URLClassLoader") } cl = cl.getParent } in order to see what url is null. https://www.scala-sbt.org/1.x/docs/Developers-Guide.html https://github.com/sbt/sbt/blob/1.8.x/DEVELOPING.md
SBT gives java.lang.NullPointerException when trying to run spark
I'm trying to compile spark with sbt 1.7.2 on a Linux machine which system is CentOs6. When I try to run clean command: ./build/sbt clean I get the following output: java.lang.NullPointerException at sun.net.util.URLUtil.urlNoFragString(URLUtil.java:50) at sun.misc.URLClassPath.getLoader(URLClassPath.java:526) at sun.misc.URLClassPath.getNextLoader(URLClassPath.java:498) at sun.misc.URLClassPath.getResource(URLClassPath.java:252) at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:363) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:362) at java.lang.ClassLoader.loadClass(ClassLoader.java:419) at java.lang.ClassLoader.loadClass(ClassLoader.java:406) at java.lang.ClassLoader.loadClass(ClassLoader.java:406) at java.lang.ClassLoader.loadClass(ClassLoader.java:406) at java.lang.ClassLoader.loadClass(ClassLoader.java:406) at java.lang.ClassLoader.loadClass(ClassLoader.java:352) at sbt.internal.XMainConfiguration.run(XMainConfiguration.java:51) at sbt.xMain.run(Main.scala:46) at xsbt.boot.Launch$.$anonfun$run$1(Launch.scala:149) at xsbt.boot.Launch$.withContextLoader(Launch.scala:176) at xsbt.boot.Launch$.run(Launch.scala:149) at xsbt.boot.Launch$.$anonfun$apply$1(Launch.scala:44) at xsbt.boot.Launch$.launch(Launch.scala:159) at xsbt.boot.Launch$.apply(Launch.scala:44) at xsbt.boot.Launch$.apply(Launch.scala:21) at xsbt.boot.Boot$.runImpl(Boot.scala:78) at xsbt.boot.Boot$.run(Boot.scala:73) at xsbt.boot.Boot$.main(Boot.scala:21) at xsbt.boot.Boot.main(Boot.scala) [error] [launcher] error during sbt launcher: java.lang.NullPointerException It also happened when I use sbt 1.7.3, But it can success clean and compile spark when I use sbt 1.6.2. What should I check first? I'd really appreciate any advice anyone can offer.
[ "Several advices how to debug Spark and sbt.\nHow to build Spark in IntelliJ.\nClone https://github.com/apache/spark , open it in IntelliJ as sbt project.\nI had to execute sbt compile and re-open the project before I can run my code in IntelliJ (I had an error object SqlBaseParser is not a member of package org.apache.spark.sql.catalyst.parser before that). For example I can put the following object in sql/core/src/main/scala and run/debug it in IntelliJ\n// scalastyle:off\nimport org.apache.spark.sql.{Dataset, SparkSession}\n\nobject MyMain extends App {\n val spark = SparkSession.builder()\n .master(\"local\")\n .appName(\"SparkTestApp\")\n .getOrCreate()\n\n case class Person(id: Long, name: String)\n\n import spark.implicits._\n\n val df: Dataset[Person] = spark.range(10).map(i => Person(i, i.toString))\n\n df.show()\n\n//+---+----+\n//| id|name|\n//+---+----+\n//| 0| 0|\n//| 1| 1|\n//| 2| 2|\n//| 3| 3|\n//| 4| 4|\n//| 5| 5|\n//| 6| 6|\n//| 7| 7|\n//| 8| 8|\n//| 9| 9|\n//+---+----+\n\n}\n\nI also pressed Run npm install, Load Maven project when these pop-up windows appeared but I haven't noticed the difference.\nAlso once I had to keep in Project Structure in sql/catalyst/target/scala-2.12/src_managed only one source root sql/catalyst/target/scala-2.12/src_managed/main (and not sql/catalyst/target/scala-2.12/src_managed/main/antlr4). I had errors like SqlBaseLexer is already defined as class SqlBaseLexer before that.\nBuild Apache Spark Source Code with IntelliJ IDEA: https://yujheli-wordpress-com.translate.goog/2020/03/26/build-apache-spark-source-code-with-intellij-idea/?_x_tr_sl=auto&_x_tr_tl=en&_x_tr_hl=uk&_x_tr_pto=wapp (original in Chinese: https://yujheli.wordpress.com/2020/03/26/build-apache-spark-source-code-with-intellij-idea/ )\nWhy does building Spark sources give \"object sbt is not a member of package com.typesafe\"?\nHow to build sbt in IntelliJ.\nsbt itself is tricky https://www.lihaoyi.com/post/SowhatswrongwithSBT.html and building it is a little tricky too.\nClone https://github.com/sbt/sbt , open it in IntelliJ. Let's try to run the previous Spark code using this cloned sbt.\nsbt seems to be not intended to run in a specified directory. I put the following object in client/src/main/scala\nobject MyClient extends App {\n System.setProperty(\"user.dir\", \"../spark\")\n sbt.client.Client.main(Array(\"sql/runMain MyMain\"))\n}\n\n(Generally, mutating the system property user.dir is not recommended: How to use \"cd\" command using Java runtime?)\nI had to execute sbt compile firstly (this includes the command sbt generateContrabands --- sbt uses sbt plugin sbt-contraband (ContrabandPlugin, JsonCodecPlugin), formerly sbt-datatype, for code generation: https://github.com/sbt/contraband https://www.scala-sbt.org/contraband/ https://www.scala-sbt.org/1.x/docs/Datatype.html https://github.com/eed3si9n/gigahorse/tree/develop/core/src/main/contraband). I had error not found: value ScalaKeywords before that.\nNext error is type ExcludeItem is not a member of package sbt.internal.bsp. You can just remove in protocol/src/main/contraband-scala/sbt/internal/bsp/codec the files ExcludeItemFormats.scala, ExcludesItemFormats.scala, ExcludesParamsFormats.scala, ExcludesResultFormats.scala. They are outdated auto-generated files. You can check that if you remove the content of directory protocol/src/main/contraband-scala (this is a root for auto-generated sources) and execute sbt generateContrabands all the files except these four will be restored. For some reason these files didn't confuse sbt but confuse IntelliJ.\nNow MyClient produces while running\n//[info] +---+----+\n//[info] | id|name|\n//[info] +---+----+\n//[info] | 0| 0|\n//[info] | 1| 1|\n//[info] | 2| 2|\n//[info] | 3| 3|\n//[info] | 4| 4|\n//[info] | 5| 5|\n//[info] | 6| 6|\n//[info] | 7| 7|\n//[info] | 8| 8|\n//[info] | 9| 9|\n//[info] +---+----+\n\nsbt.client.Client is called the thin client. Alternatively, you can publish it locally and use as a dependency\nbuild.sbt (https://github.com/sbt/sbt/blob/v1.8.0/build.sbt#L1160)\nlazy val sbtClientProj = (project in file(\"client\"))\n .enablePlugins(NativeImagePlugin)\n .dependsOn(commandProj)\n .settings(\n commonBaseSettings,\n scalaVersion := \"2.12.11\",\n publish / skip := false, // change true to false\n name := \"sbt-client\",\n .......\n\nsbt publishLocal\nA new project:\nbuild.sbt\nscalaVersion := \"2.12.17\"\n\n// ~/.ivy2/local/org.scala-sbt/sbt-client/1.8.1-SNAPSHOT/jars/sbt-client.jar\nlibraryDependencies += \"org.scala-sbt\" % \"sbt-client\" % \"1.8.1-SNAPSHOT\"\n\nsrc/main/scala/Main.scala\nobject Main extends App {\n System.setProperty(\"user.dir\", \"../spark\")\n sbt.client.Client.main(Array(\"sql/runMain MyMain\"))\n \n //[info] +---+----+\n //[info] | id|name|\n //[info] +---+----+\n //[info] | 0| 0|\n //[info] | 1| 1|\n //[info] | 2| 2|\n //[info] | 3| 3|\n //[info] | 4| 4|\n //[info] | 5| 5|\n //[info] | 6| 6|\n //[info] | 7| 7|\n //[info] | 8| 8|\n //[info] | 9| 9|\n //[info] +---+----+\n}\n\nBut the thin client is not how sbt normally runs. sbt.xMain from your stack trace is from https://github.com/sbt/sbt . It's here: https://github.com/sbt/sbt/blob/1.8.x/main/src/main/scala/sbt/Main.scala#L44 But xsbt.boot.Boot from the stack trace is not from this repo, it's from https://github.com/sbt/launcher , namely https://github.com/sbt/launcher/blob/1.x/launcher-implementation/src/main/scala/xsbt/boot/Boot.scala\nThe thing is that sbt runs in two steps. The sbt executable (usually downloaded from https://www.scala-sbt.org/download.html#universal-packages) is a shell script, firstly it runs sbt-launch.jar (the object xsbt.boot.Boot)\nhttps://github.com/sbt/sbt/blob/v1.8.0/sbt#L507-L512\nexecRunner \"$java_cmd\" \\\n \"${java_args[@]}\" \\\n \"${sbt_options[@]}\" \\\n -jar \"$sbt_jar\" \\\n \"${sbt_commands[@]}\" \\\n \"${residual_args[@]}\"\n\nand secondly the latter reflectively calls sbt (the class sbt.xMain)\nhttps://github.com/sbt/launcher/blob/v1.4.1/launcher-implementation/src/main/scala/xsbt/boot/Launch.scala#L147-L149\nval main = appProvider.newMain()\ntry {\n withContextLoader(appProvider.loader)(main.run(appConfig))\n\nhttps://github.com/sbt/launcher/blob/v1.4.1/launcher-implementation/src/main/scala/xsbt/boot/Launch.scala#L496\n// implementation of the above appProvider.newMain()\nelse if (AppMainClass.isAssignableFrom(entryPoint)) mainClass.newInstance\n\nhttps://github.com/sbt/launcher/blob/v1.4.1/launcher-implementation/src/main/scala/xsbt/boot/PlainApplication.scala#L13\n// implementation of the above main.run(appConfig)\nmainMethod.invoke(null, configuration.arguments).asInstanceOf[xsbti.Exit]\n\nThen xMain#run via XMainConfiguration#run reflectively calls xMain.run\nhttps://github.com/sbt/sbt/blob/v1.8.0/main/src/main/scala/sbt/Main.scala#L44-L47\nclass xMain extends xsbti.AppMain {\n def run(configuration: xsbti.AppConfiguration): xsbti.MainResult =\n new XMainConfiguration().run(\"xMain\", configuration)\n}\n\nhttps://github.com/sbt/sbt/blob/v1.8.0/main/src/main/java/sbt/internal/XMainConfiguration.java#L51-L57\nClass<?> clazz = loader.loadClass(\"sbt.\" + moduleName + \"$\");\nObject instance = clazz.getField(\"MODULE$\").get(null);\nMethod runMethod = clazz.getMethod(\"run\", xsbti.AppConfiguration.class);\ntry {\n .....\n return (xsbti.MainResult) runMethod.invoke(instance, updatedConfiguration);\n\nWhat is the launcher.\nLet's consider a helloworld for the launcher.\nThe launcher consists of a library (interfaces)\nhttps://mvnrepository.com/artifact/org.scala-sbt/launcher-interface\nhttps://github.com/sbt/launcher/tree/1.x/launcher-interface\nand the launcher runnable jar\nhttps://mvnrepository.com/artifact/org.scala-sbt/launcher\nhttps://github.com/sbt/launcher/tree/1.x/launcher-implementation/src\nCreate a project (depending on launcher interfaces at compile tome)\nbuild.sbt\nlazy val root = (project in file(\".\"))\n .settings(\n name := \"scalademo\",\n organization := \"com.example\",\n version := \"0.1.0-SNAPSHOT\",\n scalaVersion := \"2.13.10\",\n libraryDependencies ++= Seq(\n \"org.scala-sbt\" % \"launcher-interface\" % \"1.4.1\" % Provided,\n ),\n )\n\nsrc/main/scala/mypackage/Main.scala\npackage mypackage\n\nimport xsbti.{AppConfiguration, AppMain, Exit, MainResult}\n\nclass Main extends AppMain {\n def run(configuration: AppConfiguration): MainResult = {\n val scalaVersion = configuration.provider.scalaProvider.version\n\n println(s\"Hello, World! Running Scala $scalaVersion\")\n configuration.arguments.foreach(println)\n\n new Exit {\n override val code: Int = 0\n }\n }\n}\n\nDo sbt publishLocal. The project jar will be published at ~/.ivy2/local/com.example/scalademo_2.13/0.1.0-SNAPSHOT/jars/scalademo_2.13.jar\nDownload launcher runnable jar https://repo1.maven.org/maven2/org/scala-sbt/launcher/1.4.1/launcher-1.4.1.jar\nCreate launcher configuration\nmy.app.configuration\n[scala]\n version: 2.13.10\n[app]\n org: com.example\n name: scalademo\n version: 0.1.0-SNAPSHOT\n class: mypackage.Main\n cross-versioned: binary\n[repositories]\n local\n maven-central\n[boot]\n directory: ${user.home}/.myapp/boot\n\nThen command java -jar launcher-1.4.1.jar @my.app.configuration a b c produces\n//Hello world! Running Scala 2.13.10\n//a\n//b\n//c\n\nThere appeared files\n~/.myapp/boot/scala-2.13.10/com.example/scalademo/0.1.0-SNAPSHOT\n scalademo_2.13.jar\n scala-library-2.13.10.jar\n~/.myapp/boot/scala-2.13.10/lib\n java-diff-utils-4.12.jar\n jna-5.9.0.jar\n jline-3.21.0.jar\n scala-library.jar\n scala-compiler.jar\n scala-reflect.jar\n\nSo launcher helps to run application in environments with only Java installed (Scala is not necessary), Ivy dependency resolution will be used. There are features to handle return codes, reboot application with a different Scala version, launch servers etc.\nAlternatively, any of the following commands can be used\njava -Dsbt.boot.properties=my.app.configuration -jar launcher-1.4.1.jar\njava -jar launcher-repacked.jar # put my.app.configuration to sbt/sbt.boot.properties/ and repack the jar\n\nhttps://www.scala-sbt.org/1.x/docs/Launcher-Getting-Started.html\nHow to run sbt with the launcher.\nSbt https://github.com/sbt/sbt uses sbt plugin SbtLauncherPlugin https://github.com/sbt/sbt/blob/v1.8.0/project/SbtLauncherPlugin.scala so that from the raw launcher launcher\nhttps://github.com/sbt/launcher/tree/1.x/launcher-implementation/src\nhttps://mvnrepository.com/artifact/org.scala-sbt/launcher\nit builds sbt-launch\nhttps://github.com/sbt/sbt/tree/v1.8.0/launch\nhttps://mvnrepository.com/artifact/org.scala-sbt/sbt-launch\nBasically, sbt-launch is different from launcher in having default config sbt.boot.properties injected.\nWorking directory can be set either 1) in sbt.xMain (sbt) or 2) in xsbt.boot.Boot (sbt-launcher).\n1)\n// make xMain non-final so that it can be extended\n/*final*/ class xMain extends xsbti.AppMain { \n...........\n\nhttps://github.com/sbt/sbt/blob/v1.8.0/main/src/main/scala/sbt/Main.scala#L44\nimport sbt.xMain\nimport xsbti.{ AppConfiguration, AppProvider, MainResult }\nimport java.io.File\n\nclass MyXMain extends xMain {\n override def run(configuration: AppConfiguration): MainResult = {\n val args = configuration.arguments\n\n val (dir, rest) =\n if (args.length >= 1 && args(0).startsWith(\"dir=\")) {\n (\n Some(args(0).stripPrefix(\"dir=\")),\n args.drop(1)\n )\n } else {\n (None, args)\n }\n\n dir.foreach { dir =>\n System.setProperty(\"user.dir\", dir)\n }\n\n // xMain.run(new AppConfiguration { // not ok\n // new xMain().run(new AppConfiguration { // not ok\n super[xMain].run(new AppConfiguration {\n override val arguments: Array[String] = rest\n override val baseDirectory: File =\n dir.map(new File(_)).getOrElse(configuration.baseDirectory)\n override val provider: AppProvider = configuration.provider\n })\n }\n}\n\nsbt publishLocal\nmy.sbt.configuration\n[scala]\n version: auto\n #version: 2.12.17\n[app]\n org: org.scala-sbt\n name: sbt\n #name: main # not ok\n version: 1.8.1-SNAPSHOT\n class: MyXMain\n #class: sbt.xMain\n components: xsbti,extra\n cross-versioned: false\n #cross-versioned: binary\n[repositories]\n local\n maven-central\n[boot]\n directory: ${user.home}/.mysbt/boot\n[ivy]\n ivy-home: ${user.home}/.ivy2\n\njava -jar launcher-1.4.1.jar @my.sbt.configuration dir=/path_to_spark/spark \"sql/runMain MyMain\"\nor\njava -jar sbt-launch.jar @my.sbt.configuration dir=/path_to_spark/spark \"sql/runMain MyMain\"\n//[info] +---+----+\n//[info] | id|name|\n//[info] +---+----+\n//[info] | 0| 0|\n//[info] | 1| 1|\n//[info] | 2| 2|\n//[info] | 3| 3|\n//[info] | 4| 4|\n//[info] | 5| 5|\n//[info] | 6| 6|\n//[info] | 7| 7|\n//[info] | 8| 8|\n//[info] | 9| 9|\n//[info] +---+----+\n\n(sbt-launch.jar is taken from ~/.ivy2/local/org.scala-sbt/sbt-launch/1.8.1-SNAPSHOT/jars)\nI had to copy scalastyle-config.xml from spark, otherwise it wasn't found.\nStill I have warnings fatal: Not a git repository (or any parent up to mount parent ...) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).\n2)\nproject/Dependencies.scala (https://github.com/sbt/sbt/blob/v1.8.0/project/Dependencies.scala#L25)\nval launcherVersion = \"1.4.2-SNAPSHOT\" // modified\n\nClone https://github.com/sbt/launcher and make the following changes\nbuild.sbt (https://github.com/sbt/launcher/blob/v1.4.1/build.sbt#L11)\nThisBuild / version := {\n val orig = (ThisBuild / version).value\n if (orig.endsWith(\"-SNAPSHOT\")) \"1.4.2-SNAPSHOT\" // modified\n else orig\n}\n\nlauncher-implementation/src/main/scala/xsbt/boot/Launch.scala\n(https://github.com/sbt/launcher/blob/v1.4.1/launcher-implementation/src/main/scala/xsbt/boot/Launch.scala#L17\n#L21)\nclass LauncherArguments(\n val args: List[String],\n val isLocate: Boolean,\n val isExportRt: Boolean,\n val dir: Option[String] = None // added\n)\n\nobject Launch {\n def apply(arguments: LauncherArguments): Option[Int] =\n apply((new File(arguments.dir.getOrElse(\"\"))).getAbsoluteFile, arguments) // modified\n\n .............\n\nlauncher-implementation/src/main/scala/xsbt/boot/Boot.scala (https://github.com/sbt/launcher/blob/v1.4.1/launcher-implementation/src/main/scala/xsbt/boot/Boot.scala#L41-L67)\n def parseArgs(args: Array[String]): LauncherArguments = {\n @annotation.tailrec\n def parse(\n args: List[String],\n isLocate: Boolean,\n isExportRt: Boolean,\n remaining: List[String],\n dir: Option[String] // added\n ): LauncherArguments =\n args match {\n ...................\n case \"--locate\" :: rest => parse(rest, true, isExportRt, remaining, dir) // modified\n case \"--export-rt\" :: rest => parse(rest, isLocate, true, remaining, dir) // modified\n // added\n case \"--mydir\" :: next :: rest => parse(rest, isLocate, isExportRt, remaining, Some(next))\n case next :: rest => parse(rest, isLocate, isExportRt, next :: remaining, dir) // modified\n case Nil => new LauncherArguments(remaining.reverse, isLocate, isExportRt, dir) // modified\n }\n parse(args.toList, false, false, Nil, None)\n }\n\nsbt-launcher: sbt publishLocal\nsbt: sbt publishLocal\nmy.sbt.configuration\n[scala]\n version: auto\n[app]\n org: org.scala-sbt\n name: sbt\n version: 1.8.1-SNAPSHOT\n #class: MyXMain\n class: sbt.xMain\n components: xsbti,extra\n cross-versioned: false\n[repositories]\n local\n maven-central\n[boot]\n directory: ${user.home}/.mysbt/boot\n[ivy]\n ivy-home: ${user.home}/.ivy2\n\njava -jar launcher-1.4.2-SNAPSHOT.jar @my.sbt.configuration --mydir /path_to_spark/spark \"sql/runMain MyMain\"\nor\njava -jar sbt-launch.jar @my.sbt.configuration --mydir /path_to_spark/spark \"sql/runMain MyMain\"\nAlternatively, we can specify \"program arguments\" in \"Run configuration\" for xsbt.boot.Boot in IntelliJ\n@/path_to_sbt_config/my.sbt.configuration --mydir /path_to_spark/spark \"sql/runMain MyMain\"\nAlso it's possible to specify working directory /path_to_spark/spark in \"Run configuration\" in IntelliJ. Then remaining \"program arguments\" are\n@/path_to_sbt_config/my.sbt.configuration \"sql/runMain MyMain\"\nI tried to use \"org.scala-sbt\" % \"launcher\" % \"1.4.2-SNAPSHOT\" or \"org.scala-sbt\" % \"sbt-launch\" % \"1.8.1-SNAPSHOT\" as a dependency but got No RuntimeVisibleAnnotations in classfile with ScalaSignature attribute: class Boot.\nYour setting.\nSo we can run/debug sbt-launcher code in IntelliJ and/or with printlns and run/debug sbt code with printlns (because there is no runnable object).\nFrom your stack trace I have suspection that one of classloader urls is null\nhttps://github.com/openjdk/jdk/blob/jdk8-b120/jdk/src/share/classes/sun/misc/URLClassPath.java#L82\nMaybe you can add to sbt.xMain#run or MyXMain#run something like\nvar cl = getClass.getClassLoader\nwhile (cl != null) {\n println(s\"classloader: ${cl.getClass.getName}\")\n cl match {\n case cl: URLClassLoader =>\n println(\"classloader urls:\")\n cl.getURLs.foreach(println)\n case _ =>\n println(\"not URLClassLoader\")\n }\n cl = cl.getParent\n}\n\nin order to see what url is null.\nhttps://www.scala-sbt.org/1.x/docs/Developers-Guide.html\nhttps://github.com/sbt/sbt/blob/1.8.x/DEVELOPING.md\n" ]
[ 0 ]
[]
[]
[ "apache_spark", "sbt", "scala" ]
stackoverflow_0074440324_apache_spark_sbt_scala.txt
Q: Python/Plotly: px bar costumize hover Having this dataframe: df_grafico2 = pd.DataFrame(data = { "Usos" : ['Total','BK','BI','CyL','PyA','BC','VA','Resto','Total','BK','BI','CyL','PyA','BC','VA','Resto'], "Periodo" : ['Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*'], "Dolares" : [5247,869,2227,393,991,606,104,57,6074,996,2334,601,1231,676,202,33] }) I've tryied this plot: plot_impo_usos = px.histogram(df_grafico2[df_grafico2.Usos != "Total"], x = "Usos", y = "Dolares",color="Periodo", barmode="group", template="none", hover_data =["Periodo", "Dolares"], ) plot_impo_usos.update_yaxes(tickformat = ",",title_text='En millones de USD') plot_impo_usos.update_layout(separators=",.",font_family='georgia', title_text = "ImportaciΓ³n por usos econΓ³micos. Octubre de 2022 y octubre de 2021", legend=dict( yanchor="top", orientation = "h", y=1.07, xanchor="left", x=0.3)) But the hover changes automaticaly into "sum of Dolares", and it won't be possible to get the "Dolares" name back, even if I try this: labels={"Usos":"Uso","sum of DΓ³lares": "DΓ³lares"} The best outcome would be a hover template with: "Periodo", "Uso" and "Dolares" (with $ before). I've tried this, but it won't work neither: plot_impo_usos.update_traces(hovertemplate='Periodo: %{color} <br>Uso: %{x} <br>Dolares: $%{y}') Help is much appreciated! A: The easiest way to do hover text is to use fig.data (in your case, plot_impo_usos.data). to get the graph configuration data, so it is easy to customize it. So copy the hover template that is set up for the two listograms and edit it. Being able to customize it with the configuration information gives you more freedom of expression. import plotly.express as px plot_impo_usos = px.histogram(df_grafico2[df_grafico2.Usos != "Total"], x = "Usos", y = "Dolares", color="Periodo", barmode="group", template="none", hover_data =["Periodo", "Dolares"], ) plot_impo_usos.data[0].hovertemplate = 'Periodo: Octubre 2021*<br>Usos: %{x}<br>Dolares: $%{y}<extra></extra>' plot_impo_usos.data[1].hovertemplate = 'Periodo: Octubre 2022*<br>Usos: %{x}<br>Dolares: $%{y}<extra></extra>' plot_impo_usos.update_yaxes(tickformat = ",", title_text='En millones de USD') plot_impo_usos.update_layout(separators=",.", font_family='georgia', title_text = "ImportaciΓ³n por usos econΓ³micos. Octubre de 2022 y octubre de 2021", legend=dict( yanchor="top", orientation = "h", y=1.07, xanchor="left", x=0.3 ) ) plot_impo_usos.show() A: You were very close, in hovertemplate you just need to use %{fullData.name} instead of %{color} : plot_impo_usos.update_traces( hovertemplate='Periodo: %{fullData.name}<br>Uso: %{x}<br>Dolares: %{y:$,.2f}<extra></extra>' ) Nb. When using hovertemplate, there is this "secondary box" that appears next to the hover box, which is (quite often) annoying : Anything contained in tag <extra> is displayed in the secondary box, for example "{fullData.name}". To hide the secondary box completely, use an empty tag <extra></extra>. Note also that fullData.name is the name of the (hovered) trace, which, when using px.histogram(), is set automatically according to the value of color.
Python/Plotly: px bar costumize hover
Having this dataframe: df_grafico2 = pd.DataFrame(data = { "Usos" : ['Total','BK','BI','CyL','PyA','BC','VA','Resto','Total','BK','BI','CyL','PyA','BC','VA','Resto'], "Periodo" : ['Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*'], "Dolares" : [5247,869,2227,393,991,606,104,57,6074,996,2334,601,1231,676,202,33] }) I've tryied this plot: plot_impo_usos = px.histogram(df_grafico2[df_grafico2.Usos != "Total"], x = "Usos", y = "Dolares",color="Periodo", barmode="group", template="none", hover_data =["Periodo", "Dolares"], ) plot_impo_usos.update_yaxes(tickformat = ",",title_text='En millones de USD') plot_impo_usos.update_layout(separators=",.",font_family='georgia', title_text = "ImportaciΓ³n por usos econΓ³micos. Octubre de 2022 y octubre de 2021", legend=dict( yanchor="top", orientation = "h", y=1.07, xanchor="left", x=0.3)) But the hover changes automaticaly into "sum of Dolares", and it won't be possible to get the "Dolares" name back, even if I try this: labels={"Usos":"Uso","sum of DΓ³lares": "DΓ³lares"} The best outcome would be a hover template with: "Periodo", "Uso" and "Dolares" (with $ before). I've tried this, but it won't work neither: plot_impo_usos.update_traces(hovertemplate='Periodo: %{color} <br>Uso: %{x} <br>Dolares: $%{y}') Help is much appreciated!
[ "The easiest way to do hover text is to use fig.data (in your case, plot_impo_usos.data). to get the graph configuration data, so it is easy to customize it. So copy the hover template that is set up for the two listograms and edit it. Being able to customize it with the configuration information gives you more freedom of expression.\nimport plotly.express as px\n\nplot_impo_usos = px.histogram(df_grafico2[df_grafico2.Usos != \"Total\"],\n x = \"Usos\",\n y = \"Dolares\",\n color=\"Periodo\",\n barmode=\"group\",\n template=\"none\",\n hover_data =[\"Periodo\", \"Dolares\"],\n )\n\nplot_impo_usos.data[0].hovertemplate = 'Periodo: Octubre 2021*<br>Usos: %{x}<br>Dolares: $%{y}<extra></extra>'\nplot_impo_usos.data[1].hovertemplate = 'Periodo: Octubre 2022*<br>Usos: %{x}<br>Dolares: $%{y}<extra></extra>'\n\nplot_impo_usos.update_yaxes(tickformat = \",\",\n title_text='En millones de USD')\nplot_impo_usos.update_layout(separators=\",.\",\n font_family='georgia',\n title_text = \"ImportaciΓ³n por usos econΓ³micos. Octubre de 2022 y octubre de 2021\",\n legend=dict(\n yanchor=\"top\",\n orientation = \"h\",\n y=1.07,\n xanchor=\"left\",\n x=0.3\n )\n )\n\nplot_impo_usos.show()\n\n\n", "You were very close, in hovertemplate you just need to use %{fullData.name} instead of %{color} :\nplot_impo_usos.update_traces(\n hovertemplate='Periodo: %{fullData.name}<br>Uso: %{x}<br>Dolares: %{y:$,.2f}<extra></extra>'\n)\n\nNb. When using hovertemplate, there is this \"secondary box\" that appears next to the hover box, which is (quite often) annoying :\n\nAnything contained in tag <extra> is displayed in the secondary box,\nfor example \"{fullData.name}\". To hide the secondary\nbox completely, use an empty tag <extra></extra>.\n\nNote also that fullData.name is the name of the (hovered) trace, which, when using px.histogram(), is set automatically according to the value of color.\n" ]
[ 1, 0 ]
[]
[]
[ "plotly", "plotly_express", "python" ]
stackoverflow_0074658732_plotly_plotly_express_python.txt
Q: Assign ctrl+F to search Button in WPF I'm trying to assign ctrl + F to a search button so when I click it it will open the search box on a pdf which I had added to a WPF userControl in a WebBrowser. My code is based on something I have seen here on another post but doesn't work and gives me an error on the webBrowser.Focus method: System.ExecutionEngineException HResult=0x80131506 Message=Exception of type 'System.ExecutionEngineException' was thrown. This is what I have now: XAML: <WebBrowser x:Name="webBrowser" Source="file:C:\myFile.pdf" /> CS: private void BtnSearch_Click(object sender, EventArgs e) { webBrowser.Focus(); SendKeys.SendWait("^(f)"); } Please if you have any ideas or alternatives to do this I would really appreciate it. A: I found interesting thing on github. I tested it, and it works for a desktop application. May be tested for web applications. The main function that interests you is SendKeyboardInput.
Assign ctrl+F to search Button in WPF
I'm trying to assign ctrl + F to a search button so when I click it it will open the search box on a pdf which I had added to a WPF userControl in a WebBrowser. My code is based on something I have seen here on another post but doesn't work and gives me an error on the webBrowser.Focus method: System.ExecutionEngineException HResult=0x80131506 Message=Exception of type 'System.ExecutionEngineException' was thrown. This is what I have now: XAML: <WebBrowser x:Name="webBrowser" Source="file:C:\myFile.pdf" /> CS: private void BtnSearch_Click(object sender, EventArgs e) { webBrowser.Focus(); SendKeys.SendWait("^(f)"); } Please if you have any ideas or alternatives to do this I would really appreciate it.
[ "I found interesting thing on github. I tested it, and it works for a desktop application.\nMay be tested for web applications.\nThe main function that interests you is SendKeyboardInput.\n" ]
[ 0 ]
[]
[]
[ "c#", "wpf" ]
stackoverflow_0074644643_c#_wpf.txt
Q: Python Pandas Converting Dataframe to Tidy Format dt = {'ID': [1, 1, 1, 1, 2, 2, 2, 2], 'Test': [β€˜Math’, 'Math', 'Writing', 'Writing', β€˜Math’, 'Math', 'Writing', 'Writing', β€˜Math’] 'Year': ['2008', '2009', '2008', '2009', '2008', β€˜2009’, β€˜2008’, β€˜2009’], 'Fall': [15, 12, 22, 10, 12, 16, 13, 23] β€˜Spring’: [16, 13, 22, 14, 13, 14, 11, 20] β€˜Winter’: [19, 27, 24, 20, 25, 21, 29, 26]} mydt = pd.DataFrame(dt, columns = ['ID', β€˜Test’, 'Year', 'Fall', β€˜Spring’, β€˜Winter’]) So I have the above dataset. How can I convert the above dataset so that it looks like the following? Please let me know. A: You can try with set_index with stack + unstack out = (df.set_index(['ID','Test','Year']). stack().unstack(level=1). add_suffix('_Score').reset_index()) out Out[271]: Test ID Year level_2 Math_Score Writing_Score 0 1 2008 Fall 15 22 1 1 2008 Spring 16 22 2 1 2008 Winter 19 24 3 1 2009 Fall 12 10 4 1 2009 Spring 13 14 5 1 2009 Winter 27 20 6 2 2008 Fall 12 13 7 2 2008 Spring 13 11 8 2 2008 Winter 25 29 9 2 2009 Fall 16 23 10 2 2009 Spring 14 20 11 2 2009 Winter 21 26 A: Here is another solution: import pandas as pd data = {'ID': [1, 1, 1, 1, 2, 2, 2, 2], 'Test': ['Math', 'Math', 'Writing', 'Writing', 'Math', 'Math', 'Writing', 'Writing'], 'Year': ['2008', '2009', '2008', '2009', '2008', '2009', '2008', '2009'], 'Fall': [15, 12, 22, 10, 12, 16, 13, 23], 'Spring': [16, 13, 22, 14, 13, 14, 11, 20], 'Winter': [19, 27, 24, 20, 25, 21, 29, 26]} df_data = pd.DataFrame(data, columns=['ID', 'Test', 'Year', 'Fall', 'Spring', 'Winter']) df = df_data.melt(id_vars=['ID', 'Year', 'Test'], var_name='Quarter', value_name='Score') df = df.pivot(index=['ID', 'Year', 'Quarter'], columns=['Test'], values=['Score']) df.columns = df.columns.droplevel(level=0) df = df.add_suffix('_Score').reset_index(drop=False) A: This requires two pivoting operations using tidypandas: import pandas as pd from tidypandas.tidy_accessor import tp data = {'ID': [1, 1, 1, 1, 2, 2, 2, 2], 'Test': ['Math', 'Math', 'Writing', 'Writing', 'Math', 'Math', 'Writing', 'Writing'], 'Year': ['2008', '2009', '2008', '2009', '2008', '2009', '2008', '2009'], 'Fall': [15, 12, 22, 10, 12, 16, 13, 23], 'Spring': [16, 13, 22, 14, 13, 14, 11, 20], 'Winter': [19, 27, 24, 20, 25, 21, 29, 26]} df_data = pd.DataFrame(data, columns=['ID', 'Test', 'Year', 'Fall', 'Spring', 'Winter']) >>> (df_data.tp.pivot_longer(cols = ['Fall', 'Spring', 'Winter'], ... names_to='quarter' ... ) ... .tp.pivot_wider(id_cols = ['ID', 'quarter', 'Year'], ... names_from = 'Test', ... values_from = 'value', ... names_prefix = 'score_' ... ) ... ) Year quarter ID score_Math score_Writing 0 2008 Fall 1 15 22 1 2009 Fall 1 12 10 2 2008 Spring 1 16 22 3 2009 Spring 1 13 14 4 2008 Winter 1 19 24 5 2009 Winter 1 27 20 6 2008 Fall 2 12 13 7 2009 Fall 2 16 23 8 2008 Spring 2 13 11 9 2009 Spring 2 14 20 10 2008 Winter 2 25 29 11 2009 Winter 2 21 26
Python Pandas Converting Dataframe to Tidy Format
dt = {'ID': [1, 1, 1, 1, 2, 2, 2, 2], 'Test': [β€˜Math’, 'Math', 'Writing', 'Writing', β€˜Math’, 'Math', 'Writing', 'Writing', β€˜Math’] 'Year': ['2008', '2009', '2008', '2009', '2008', β€˜2009’, β€˜2008’, β€˜2009’], 'Fall': [15, 12, 22, 10, 12, 16, 13, 23] β€˜Spring’: [16, 13, 22, 14, 13, 14, 11, 20] β€˜Winter’: [19, 27, 24, 20, 25, 21, 29, 26]} mydt = pd.DataFrame(dt, columns = ['ID', β€˜Test’, 'Year', 'Fall', β€˜Spring’, β€˜Winter’]) So I have the above dataset. How can I convert the above dataset so that it looks like the following? Please let me know.
[ "You can try with set_index with stack + unstack\nout = (df.set_index(['ID','Test','Year']).\n stack().unstack(level=1).\n add_suffix('_Score').reset_index())\nout\nOut[271]: \nTest ID Year level_2 Math_Score Writing_Score\n0 1 2008 Fall 15 22\n1 1 2008 Spring 16 22\n2 1 2008 Winter 19 24\n3 1 2009 Fall 12 10\n4 1 2009 Spring 13 14\n5 1 2009 Winter 27 20\n6 2 2008 Fall 12 13\n7 2 2008 Spring 13 11\n8 2 2008 Winter 25 29\n9 2 2009 Fall 16 23\n10 2 2009 Spring 14 20\n11 2 2009 Winter 21 26\n\n", "Here is another solution:\nimport pandas as pd\n\ndata = {'ID': [1, 1, 1, 1, 2, 2, 2, 2],\n 'Test': ['Math', 'Math', 'Writing', 'Writing', 'Math', 'Math', 'Writing', 'Writing'],\n 'Year': ['2008', '2009', '2008', '2009', '2008', '2009', '2008', '2009'],\n 'Fall': [15, 12, 22, 10, 12, 16, 13, 23],\n 'Spring': [16, 13, 22, 14, 13, 14, 11, 20],\n 'Winter': [19, 27, 24, 20, 25, 21, 29, 26]}\ndf_data = pd.DataFrame(data, columns=['ID', 'Test', 'Year', 'Fall', 'Spring', 'Winter'])\n\ndf = df_data.melt(id_vars=['ID', 'Year', 'Test'], var_name='Quarter', value_name='Score')\ndf = df.pivot(index=['ID', 'Year', 'Quarter'], columns=['Test'], values=['Score'])\ndf.columns = df.columns.droplevel(level=0)\ndf = df.add_suffix('_Score').reset_index(drop=False)\n\n", "This requires two pivoting operations using tidypandas:\nimport pandas as pd\nfrom tidypandas.tidy_accessor import tp\n\ndata = {'ID': [1, 1, 1, 1, 2, 2, 2, 2],\n 'Test': ['Math', 'Math', 'Writing', 'Writing', 'Math', 'Math', 'Writing', 'Writing'],\n 'Year': ['2008', '2009', '2008', '2009', '2008', '2009', '2008', '2009'],\n 'Fall': [15, 12, 22, 10, 12, 16, 13, 23],\n 'Spring': [16, 13, 22, 14, 13, 14, 11, 20],\n 'Winter': [19, 27, 24, 20, 25, 21, 29, 26]}\ndf_data = pd.DataFrame(data, columns=['ID', 'Test', 'Year', 'Fall', 'Spring', 'Winter'])\n\n>>> (df_data.tp.pivot_longer(cols = ['Fall', 'Spring', 'Winter'],\n... names_to='quarter'\n... )\n... .tp.pivot_wider(id_cols = ['ID', 'quarter', 'Year'],\n... names_from = 'Test',\n... values_from = 'value',\n... names_prefix = 'score_'\n... )\n... )\n Year quarter ID score_Math score_Writing\n0 2008 Fall 1 15 22\n1 2009 Fall 1 12 10\n2 2008 Spring 1 16 22\n3 2009 Spring 1 13 14\n4 2008 Winter 1 19 24\n5 2009 Winter 1 27 20\n6 2008 Fall 2 12 13\n7 2009 Fall 2 16 23\n8 2008 Spring 2 13 11\n9 2009 Spring 2 14 20\n10 2008 Winter 2 25 29\n11 2009 Winter 2 21 26\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0072933196_pandas_python.txt
Q: Updating an SQLite database via an ODBC linked table in Access I am having an issue with an SQLite database. I am using the SQLite ODBC from http://www.ch-werner.de/sqliteodbc/ Installed the 64-bit version and created the ODBC with these settings: I open my Access database and link to the datasource. I can open the table, add records, but cannot delete or edit any records. Is there something I need to fix on the ODBC side to allow this? The error I get when I try to delete a record is: The Microsoft Access database engine stopped the process because you and another user are attempting to change the same data at the same time. When I edit a record I get: The record has been changed by another user since you started editing it. If you save the record, you will overwrite the changed the other user made. Save record is disabled. Only copy to clipboard or drop changes is available. A: My initial attempt to recreate your issue was unsuccessful. I used the following on my 32-bit test VM: Access 2010 SQLite 3.8.2 SQLite ODBC Driver 0.996 I created and populated the test table [tbl1] as documented here. I created an Access linked table and when prompted I chose both columns ([one] and [two]) as the Primary Key. When I opened the linked table in Datasheet View I was able to add, edit, and delete records without incident. The only difference I can see between my setup and yours (apart from the fact that I am on 32-bit and you are on 64-bit) is that in the ODBC DSN settings I left the Sync.Mode setting at its default value of NORMAL, whereas yours appears to be set to OFF. Try setting your Sync.Mode to NORMAL and see if that makes a difference. Edit re: comments The solution in this case was the following: One possible workaround would be to create a new SQLite table with all the same columns plus a new INTEGER PRIMARY KEY column which Access will "see" as AutoNumber. You can create a unique index on (what are currently) the first four columns to ensure that they remain unique, but the new new "identity" (ROWID) column is what Access would use to identify rows for CRUD operations. A: I had this problem too. I have a table with a primary key on a VARCHAR(30) (TEXT) field. Adding an INTEGER PRIMARY KEY column didn't help at all. After lots of testing I found the issue was with a DATETIME field I had in the table. I removed the DATETIME field and I was able to update record values in MS-Access datasheet view. So now any DATETIME fields I need in SQLite, I declare as VARCHAR(19) so they some into Access via ODBC as text. Not perfect but it works. (And of course SQLite doesn't have a real DATETIME field type anyway so TEXT is just fine and will convert OK) I confirmed it's a number conversion issue. With an empty DATETIME field, I can add a time of 01-01-2014 12:01:02 via Access's datasheet view, if I then look at the value in SQLite the seconds have been rounded off: sqlite> SELECT three from TEST where FLoc='1020'; 2014-01-01 12:01:00.000 SYNCMODE should also be NORMAL not OFF. Update: If you have any text fields with a defined length (e.g. foo VARCHAR(10)) and the field contents contains more characters than the field definition (which SQLite allows) MS-Access will also barf when trying to update any of the fields on that row. A: I've searched all similar posts as I had a similar issue with SQLite linked via ODBC to Access. I had three tables, two of them allowed edits, but the third didn't. The third one had a DATETIME field and when I changed the data type to a TEXT field in the original SQLite database and relinked to access, I could edit the table. So for me it was confirmed as an issue with the DATETIME field. A: After running into this problem, not finding a satisfactory answer, and wasting a lot of time trying other solutions, I eventually discovered that what others have mentioned about DATETIME fields is accurate but another solution exists that lets you keep the proper data type. The SQLite ODBC driver can convert Julian day values into the ODBC SQL_TIMESTAMP / SQL_TYPE_TIMESTAMP types by looking for floating point values in the column, if you have that option enabled in the driver. Storing dates in this manner gives the ODBC timestamp value enough precision to avoid the write conflict error, as well as letting Access see the column as a date/time field. Even storing sub-second precision in the date string doesn't work, which is possibly a bug in the driver because the resulting TIMESTAMP_STRUCT contains the same values, but the fractional seconds must be lost elsewhere.
Updating an SQLite database via an ODBC linked table in Access
I am having an issue with an SQLite database. I am using the SQLite ODBC from http://www.ch-werner.de/sqliteodbc/ Installed the 64-bit version and created the ODBC with these settings: I open my Access database and link to the datasource. I can open the table, add records, but cannot delete or edit any records. Is there something I need to fix on the ODBC side to allow this? The error I get when I try to delete a record is: The Microsoft Access database engine stopped the process because you and another user are attempting to change the same data at the same time. When I edit a record I get: The record has been changed by another user since you started editing it. If you save the record, you will overwrite the changed the other user made. Save record is disabled. Only copy to clipboard or drop changes is available.
[ "My initial attempt to recreate your issue was unsuccessful. I used the following on my 32-bit test VM:\n\nAccess 2010\nSQLite 3.8.2\nSQLite ODBC Driver 0.996\n\nI created and populated the test table [tbl1] as documented here. I created an Access linked table and when prompted I chose both columns ([one] and [two]) as the Primary Key. When I opened the linked table in Datasheet View I was able to add, edit, and delete records without incident.\nThe only difference I can see between my setup and yours (apart from the fact that I am on 32-bit and you are on 64-bit) is that in the ODBC DSN settings I left the Sync.Mode setting at its default value of NORMAL, whereas yours appears to be set to OFF.\nTry setting your Sync.Mode to NORMAL and see if that makes a difference.\nEdit re: comments\nThe solution in this case was the following:\n\nOne possible workaround would be to create a new SQLite table with all the same columns plus a new INTEGER PRIMARY KEY column which Access will \"see\" as AutoNumber. You can create a unique index on (what are currently) the first four columns to ensure that they remain unique, but the new new \"identity\" (ROWID) column is what Access would use to identify rows for CRUD operations.\n\n", "I had this problem too. I have a table with a primary key on a VARCHAR(30) (TEXT) field.\nAdding an INTEGER PRIMARY KEY column didn't help at all. After lots of testing I found the issue was with a DATETIME field I had in the table. I removed the DATETIME field and I was able to update record values in MS-Access datasheet view.\nSo now any DATETIME fields I need in SQLite, I declare as VARCHAR(19) so they some into Access via ODBC as text. Not perfect but it works. (And of course SQLite doesn't have a real DATETIME field type anyway so TEXT is just fine and will convert OK)\nI confirmed it's a number conversion issue. With an empty DATETIME field, I can add a time of 01-01-2014 12:01:02 via Access's datasheet view, if I then look at the value in SQLite the seconds have been rounded off: \n sqlite> SELECT three from TEST where FLoc='1020';\n2014-01-01 12:01:00.000\n\nSYNCMODE should also be NORMAL not OFF.\nUpdate:\nIf you have any text fields with a defined length (e.g. foo VARCHAR(10)) and the field contents contains more characters than the field definition (which SQLite allows) MS-Access will also barf when trying to update any of the fields on that row.\n", "I've searched all similar posts as I had a similar issue with SQLite linked via ODBC to Access. I had three tables, two of them allowed edits, but the third didn't. The third one had a DATETIME field and when I changed the data type to a TEXT field in the original SQLite database and relinked to access, I could edit the table. So for me it was confirmed as an issue with the DATETIME field. \n", "After running into this problem, not finding a satisfactory answer, and wasting a lot of time trying other solutions, I eventually discovered that what others have mentioned about DATETIME fields is accurate but another solution exists that lets you keep the proper data type. The SQLite ODBC driver can convert Julian day values into the ODBC SQL_TIMESTAMP / SQL_TYPE_TIMESTAMP types by looking for floating point values in the column, if you have that option enabled in the driver. Storing dates in this manner gives the ODBC timestamp value enough precision to avoid the write conflict error, as well as letting Access see the column as a date/time field.\nEven storing sub-second precision in the date string doesn't work, which is possibly a bug in the driver because the resulting TIMESTAMP_STRUCT contains the same values, but the fractional seconds must be lost elsewhere.\n" ]
[ 10, 4, 0, 0 ]
[]
[]
[ "ms_access", "ms_access_2010", "odbc", "sqlite", "sqlite_odbc" ]
stackoverflow_0019658747_ms_access_ms_access_2010_odbc_sqlite_sqlite_odbc.txt
Q: Why does a constant property may get initialized twice in a Swift class? The project I'm working on is a mix of Swift and Objective-C. Here's the snippet: // ViewController.m @interface ViewController () @property (nonatomic, strong) MyModel *model; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.model = [[MyModel alloc] initWithIntValue:10]; } // MyModel.swift fileprivate class SomeProperty { init() { print("SomeProperty init") } } class MyModel: BaseModel { private let property = SomeProperty() } // BaseModel.h @interface BaseModel : NSObject - (instancetype)initWithIntValue:(int)intValue; - (instancetype)initWithIntValue:(int)intValue doubleValue:(double)doubleValue; @end // BaseModel.m @implementation BaseModel - (instancetype)initWithIntValue:(int)intValue doubleValue:(double)doubleValue { if (self = [super init]) { } return self; } - (instancetype)initWithIntValue:(int)intValue { return [self initWithIntValue:intValue doubleValue:0]; } @end Interestingly, I find when MyModel instance is initialized, SomeProperty init will be printed twice, which means two SomeProperty instances are created. What's worse, Debug Memory Graph shows that there is a SomeProperty object memory leak. So why is this and how can I fix it? A: Rewrite BaseModel.h like this: - (instancetype)initWithIntValue:(int)intValue; - (instancetype)initWithIntValue:(int)intValue doubleValue:(double)doubleValue NS_DESIGNATED_INITIALIZER; Note the NS_DESIGNATED_INITIALIZER marker at the end of the second initializer. (You may have to scroll my code in order to see it.) This marker, aside from what it does within Objective-C (in its role as a macro), tells Swift that both initializers are not designated initializers; rather, Swift concludes, the first one is a convenience initializer. And that is correct; it calls another initializer, namely β€” in this case β€” the designated initializer. Without that NS_DESIGNATED_INITIALIZER markup, Swift interprets the situation incorrectly because of the (already rather complicated) relationship between Swift initializers and Objective-C initializers. It thinks both initializers are designated initializers and you get this curious double initialization from Swift.
Why does a constant property may get initialized twice in a Swift class?
The project I'm working on is a mix of Swift and Objective-C. Here's the snippet: // ViewController.m @interface ViewController () @property (nonatomic, strong) MyModel *model; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.model = [[MyModel alloc] initWithIntValue:10]; } // MyModel.swift fileprivate class SomeProperty { init() { print("SomeProperty init") } } class MyModel: BaseModel { private let property = SomeProperty() } // BaseModel.h @interface BaseModel : NSObject - (instancetype)initWithIntValue:(int)intValue; - (instancetype)initWithIntValue:(int)intValue doubleValue:(double)doubleValue; @end // BaseModel.m @implementation BaseModel - (instancetype)initWithIntValue:(int)intValue doubleValue:(double)doubleValue { if (self = [super init]) { } return self; } - (instancetype)initWithIntValue:(int)intValue { return [self initWithIntValue:intValue doubleValue:0]; } @end Interestingly, I find when MyModel instance is initialized, SomeProperty init will be printed twice, which means two SomeProperty instances are created. What's worse, Debug Memory Graph shows that there is a SomeProperty object memory leak. So why is this and how can I fix it?
[ "Rewrite BaseModel.h like this:\n- (instancetype)initWithIntValue:(int)intValue;\n- (instancetype)initWithIntValue:(int)intValue doubleValue:(double)doubleValue NS_DESIGNATED_INITIALIZER;\n\nNote the NS_DESIGNATED_INITIALIZER marker at the end of the second initializer. (You may have to scroll my code in order to see it.)\nThis marker, aside from what it does within Objective-C (in its role as a macro), tells Swift that both initializers are not designated initializers; rather, Swift concludes, the first one is a convenience initializer. And that is correct; it calls another initializer, namely β€” in this case β€” the designated initializer.\nWithout that NS_DESIGNATED_INITIALIZER markup, Swift interprets the situation incorrectly because of the (already rather complicated) relationship between Swift initializers and Objective-C initializers. It thinks both initializers are designated initializers and you get this curious double initialization from Swift.\n" ]
[ 4 ]
[]
[]
[ "ios", "objective_c", "swift", "xcode" ]
stackoverflow_0074667314_ios_objective_c_swift_xcode.txt
Q: Flutter _CastError (type 'Null' is not a subtype of type 'List?>' in type cast) This is the flutter code that I wrote 2 years ago. But I couldn't make any sense of why it has stopped working now. How do I fix this exception. import './question.dart'; import './answer.dart'; class Quiz extends StatelessWidget { final List<Map<String, dynamic>> questions; final int questionIndex; final Function answerQuestion; const Quiz({ super.key, required this.questions, required this.answerQuestion, required this.questionIndex, }); @override Widget build(BuildContext context) { return Column( children: [ Question( questions[questionIndex]['questionText'] as String, ), ...(questions[questionIndex]['answers'] as List<Map<String, dynamic>?>) .map((answer) { return Answer( () => answerQuestion(answer['score']), answer!['text'] as String); }).toList() ], ); } } A: Change this: ...(questions[questionIndex]['answers'] as List<Map<String, dynamic>?>) to this: ...(questions[questionIndex]['answers'] as List<Map<String, dynamic>?>?) this happened because questions[questionIndex]['answers'] is null and can't cast null to List<Map<String, dynamic>?>.
Flutter _CastError (type 'Null' is not a subtype of type 'List?>' in type cast)
This is the flutter code that I wrote 2 years ago. But I couldn't make any sense of why it has stopped working now. How do I fix this exception. import './question.dart'; import './answer.dart'; class Quiz extends StatelessWidget { final List<Map<String, dynamic>> questions; final int questionIndex; final Function answerQuestion; const Quiz({ super.key, required this.questions, required this.answerQuestion, required this.questionIndex, }); @override Widget build(BuildContext context) { return Column( children: [ Question( questions[questionIndex]['questionText'] as String, ), ...(questions[questionIndex]['answers'] as List<Map<String, dynamic>?>) .map((answer) { return Answer( () => answerQuestion(answer['score']), answer!['text'] as String); }).toList() ], ); } }
[ "Change this:\n...(questions[questionIndex]['answers'] as List<Map<String, dynamic>?>)\n\nto this:\n...(questions[questionIndex]['answers'] as List<Map<String, dynamic>?>?)\n\nthis happened because questions[questionIndex]['answers'] is null and can't cast null to List<Map<String, dynamic>?>.\n" ]
[ 1 ]
[]
[]
[ "dart", "flutter" ]
stackoverflow_0074667323_dart_flutter.txt
Q: Login to GitHub before pushing android studio code I am working on my android studio codes in kotlin and trying to push them into my GitHub repository. I have watched many videos and all of them show the same steps of downloading the Git and adding VCS and then adding the code and finally committing it, here is the video link: https://www.youtube.com/watch?v=GhfJTOu3_SE The issue is, once I click on the push button it asks me to log in to my GitHub Account in order to complete the procedure and once I enter the Github username and password it keeps on loading and never redirects to anything. I try to create accounts in the JetBrains, bitbucket or any other software that can help me to access the authorization for the GitHub and upload the code but nothing works. Is there something I am missing? I am unable to detect the issue here. A: thank you for the suggestion. I just solved the issue by logging into the github account through android studio settings, looking for github and adding my github account. It no longer asks for permission and directly commits the code into the repository. Appreciate it
Login to GitHub before pushing android studio code
I am working on my android studio codes in kotlin and trying to push them into my GitHub repository. I have watched many videos and all of them show the same steps of downloading the Git and adding VCS and then adding the code and finally committing it, here is the video link: https://www.youtube.com/watch?v=GhfJTOu3_SE The issue is, once I click on the push button it asks me to log in to my GitHub Account in order to complete the procedure and once I enter the Github username and password it keeps on loading and never redirects to anything. I try to create accounts in the JetBrains, bitbucket or any other software that can help me to access the authorization for the GitHub and upload the code but nothing works. Is there something I am missing? I am unable to detect the issue here.
[ "thank you for the suggestion. I just solved the issue by logging into the github account through android studio settings, looking for github and adding my github account.\nIt no longer asks for permission and directly commits the code into the repository.\nAppreciate it\n" ]
[ 0 ]
[]
[]
[ "android_studio", "github", "push" ]
stackoverflow_0074655286_android_studio_github_push.txt
Q: How can I wrote in pinescript that a Moving Average is pointing upwards? I'm making my first strategy in pinescript so im learning how to code. Theres a step in my strategy that the moving average need to be pointing upwards. I was thinking that i could put that the value of the third previous ma candle was below the current value. The problem is that I donΒ΄t know how to do it. Can someone help with this? The problem is that I donΒ΄t know how to do it. Can someone help with this? A: You can use the ta.rising() function to check how many bars your moving average has been rising for. ta.rising(source, length) β†’ series bool RETURNS true if current source is greater than any previous source for length bars back, false otherwise. ARGUMENTS source (series int/float) Series of values to process. length (series int) Number of bars (length).
How can I wrote in pinescript that a Moving Average is pointing upwards?
I'm making my first strategy in pinescript so im learning how to code. Theres a step in my strategy that the moving average need to be pointing upwards. I was thinking that i could put that the value of the third previous ma candle was below the current value. The problem is that I donΒ΄t know how to do it. Can someone help with this? The problem is that I donΒ΄t know how to do it. Can someone help with this?
[ "You can use the ta.rising() function to check how many bars your moving average has been rising for.\n\nta.rising(source, length) β†’ series bool\nRETURNS \ntrue if current source is greater than any previous source for length bars back, false otherwise.\nARGUMENTS\nsource (series int/float) Series of values to process. \nlength (series int) Number of bars (length).\n\n" ]
[ 1 ]
[]
[]
[ "pine_script", "pinescript_v5" ]
stackoverflow_0074666706_pine_script_pinescript_v5.txt
Q: Next OG Image not detected by Facebook Debugger I have set up the NextJs OG Image and everything works well. Only the image cannot be inferred by Facebook. The error/warning is The 'og:image' property should be explicitly provided, even if a value can be inferred from other tags. when i supply the url of the page to Facebook the url is not being detected. The code in my Head looks like <meta property="og:url" content={ `${ process.env.NEXT_PUBLIC_VERCEL_URL ? 'https://' + process.env.NEXT_PUBLIC_VERCEL_URL : 'http://localhost:3000' }/${user.Name}` }/> <meta property="og:type" content="website"/> <meta property="og:title" content={`${user.Name}`}/> <meta property="og:description" content="undefined"/> <meta property="og:image" name="og:image" content={ `${ process.env.NEXT_PUBLIC_VERCEL_URL ? 'https://' + process.env.NEXT_PUBLIC_VERCEL_URL : 'http://localhost:3000' }/api/og-image?title=Nameofuser&description=A description` } /> According to a source Facebook only checks for og:image in the first 50Kbs of the page source. If you are using inline CSS, the og:image will not be seen by Facebook does this mean that Facebook will not find the image. Or am I setting this us the wrong way Edit: I have also copy pasted the code in the NextJS documentation onto my page and the image still does not show. The simple code is <Head> <title>Cool Title</title> <meta name="description" content="Checkout our cool page" key="desc" /> <meta property="og:title" content="Social Title for Cool Page" /> <meta property="og:description" content="And a social description for our cool page" /> <meta property="og:image" content="https://example.com/images/cool-page.jpg" /> </Head> from the documentation link . Is this a known bug in NextJS that I am unaware of A: Eventually I was able to fix the issue. My entire app is wrapped with an AuthProvider by firebase. And for some reason, having it present makes facebook debuggers not wait for the authentication state or something. I would lazy load the AuthComponent and my first load size would come to even about 80Kb from around 182Kb but still facebook debuggers would still not load my og image. This is my solution import { useEffect, useState } from "react"; import dynamic from "next/dynamic"; const AuthContextProvider = dynamic(() => import('../auth/AuthProvider'), { ssr: typeof window==="undefined" }) function MyApp({ Component, pageProps }) { // mock state to make sure we are running in browser const [inBrowser, setInBrowser] = useState(false) useEffect(() => setInBrowser(true), []) return ( <> {inBrowser ? ( // running in browser load Auth <AuthContextProvider> <Component {...pageProps} /> </AuthContextProvider> ) : ( // building or running in pipeline <Component {...pageProps} /> )} </> ); } export default MyApp; When build is running the second block of code is executed, which facebook does (not in a browser environment) and when a normal user loads the page the first block of code is run. If there are security tradeoffs to this (I do not think there is) one can point it out. But that's the solution. Also later I still brought back lazy loading the AuthContext Component, in line 3, because why not, honestly
Next OG Image not detected by Facebook Debugger
I have set up the NextJs OG Image and everything works well. Only the image cannot be inferred by Facebook. The error/warning is The 'og:image' property should be explicitly provided, even if a value can be inferred from other tags. when i supply the url of the page to Facebook the url is not being detected. The code in my Head looks like <meta property="og:url" content={ `${ process.env.NEXT_PUBLIC_VERCEL_URL ? 'https://' + process.env.NEXT_PUBLIC_VERCEL_URL : 'http://localhost:3000' }/${user.Name}` }/> <meta property="og:type" content="website"/> <meta property="og:title" content={`${user.Name}`}/> <meta property="og:description" content="undefined"/> <meta property="og:image" name="og:image" content={ `${ process.env.NEXT_PUBLIC_VERCEL_URL ? 'https://' + process.env.NEXT_PUBLIC_VERCEL_URL : 'http://localhost:3000' }/api/og-image?title=Nameofuser&description=A description` } /> According to a source Facebook only checks for og:image in the first 50Kbs of the page source. If you are using inline CSS, the og:image will not be seen by Facebook does this mean that Facebook will not find the image. Or am I setting this us the wrong way Edit: I have also copy pasted the code in the NextJS documentation onto my page and the image still does not show. The simple code is <Head> <title>Cool Title</title> <meta name="description" content="Checkout our cool page" key="desc" /> <meta property="og:title" content="Social Title for Cool Page" /> <meta property="og:description" content="And a social description for our cool page" /> <meta property="og:image" content="https://example.com/images/cool-page.jpg" /> </Head> from the documentation link . Is this a known bug in NextJS that I am unaware of
[ "Eventually I was able to fix the issue. My entire app is wrapped with an AuthProvider by firebase. And for some reason, having it present makes facebook debuggers not wait for the authentication state or something. I would lazy load the AuthComponent and my first load size would come to even about 80Kb from around 182Kb but still facebook debuggers would still not load my og image. This is my solution\nimport { useEffect, useState } from \"react\";\nimport dynamic from \"next/dynamic\";\nconst AuthContextProvider = dynamic(() => import('../auth/AuthProvider'), {\n ssr: typeof window===\"undefined\"\n})\n\nfunction MyApp({ Component, pageProps }) {\n // mock state to make sure we are running in browser\n const [inBrowser, setInBrowser] = useState(false)\n\n useEffect(() => setInBrowser(true), [])\n return (\n <>\n {inBrowser ? (\n // running in browser load Auth\n <AuthContextProvider>\n <Component {...pageProps} />\n </AuthContextProvider>\n ) : (\n // building or running in pipeline\n <Component {...pageProps} />\n )}\n </>\n );\n}\nexport default MyApp;\n\nWhen build is running the second block of code is executed, which facebook does (not in a browser environment) and when a normal user loads the page the first block of code is run.\nIf there are security tradeoffs to this (I do not think there is) one can point it out. But that's the solution.\nAlso later I still brought back lazy loading the AuthContext Component, in line 3, because why not, honestly\n" ]
[ 0 ]
[]
[]
[ "facebook", "next.js" ]
stackoverflow_0074616801_facebook_next.js.txt
Q: `pip install` Gives Error on Some Packages Some packages give errors when I try to install them using pip install. This is the error when I try to install chatterbot, but some other packages give this error as well: pip install chatterbot Collecting chatterbot Using cached ChatterBot-1.0.5-py2.py3-none-any.whl (67 kB) Collecting pint>=0.8.1 Downloading Pint-0.19.2.tar.gz (292 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 292.0/292.0 kB 1.6 MB/s eta 0:00:00 Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Collecting pyyaml<5.2,>=5.1 Using cached PyYAML-5.1.2.tar.gz (265 kB) Preparing metadata (setup.py) ... done Collecting spacy<2.2,>=2.1 Using cached spacy-2.1.9.tar.gz (30.7 MB) Installing build dependencies ... error error: subprocess-exited-with-error Γ— pip subprocess to install build dependencies did not run successfully. β”‚ exit code: 1 ╰─> [35 lines of output] Collecting setuptools Using cached setuptools-65.0.1-py3-none-any.whl (1.2 MB) Collecting wheel<0.33.0,>0.32.0 Using cached wheel-0.32.3-py2.py3-none-any.whl (21 kB) Collecting Cython Using cached Cython-0.29.32-py2.py3-none-any.whl (986 kB) Collecting cymem<2.1.0,>=2.0.2 Using cached cymem-2.0.6-cp310-cp310-win_amd64.whl (36 kB) Collecting preshed<2.1.0,>=2.0.1 Using cached preshed-2.0.1.tar.gz (113 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error python setup.py egg_info did not run successfully. exit code: 1 [6 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\oguls\AppData\Local\Temp\pip-install-qce7tdof\preshed_546a51fe26c74852ab50db073ad57f1f\setup.py", line 9, in <module> from distutils import ccompiler, msvccompiler ImportError: cannot import name 'msvccompiler' from 'distutils' (C:\Users\oguls\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\_distutils\__init__.py) [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed Encountered error while generating package metadata. See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error Γ— pip subprocess to install build dependencies did not run successfully. β”‚ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. I don't specifically know which packages cause this error, a lot of them install without any problems. I have tried updating pip, changing environment variables and other possible solutions I've found on the internet, but nothing seems to work. Edit: The package I am trying to install supports my Python version. A: The real error in your case is: ImportError: cannot import name 'msvccompiler' from 'distutils' It occured because setuptools has broken distutils in versionΒ 65.0.0 (and has already fixed it in versionΒ 65.0.2). According to your log, the error occured in your global setuptools installation (see the path in error message), so you need to update it with the following command: pip install -U setuptools Those packages, however, may still not getΒ installed or not work properly as the module causing this error doesn't support compiler versions needed for currently supported versions of Python. A: Same thing happened with me, it was basically pip's version problem. Try upgrading pip to latest version --22.3.1 and downgrade the python version from latest version --3.10.00 to 3.9.13... pip --version check for pip's version pip install notebook --upgrade -command to update pip to latest version This worked for me
`pip install` Gives Error on Some Packages
Some packages give errors when I try to install them using pip install. This is the error when I try to install chatterbot, but some other packages give this error as well: pip install chatterbot Collecting chatterbot Using cached ChatterBot-1.0.5-py2.py3-none-any.whl (67 kB) Collecting pint>=0.8.1 Downloading Pint-0.19.2.tar.gz (292 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 292.0/292.0 kB 1.6 MB/s eta 0:00:00 Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Collecting pyyaml<5.2,>=5.1 Using cached PyYAML-5.1.2.tar.gz (265 kB) Preparing metadata (setup.py) ... done Collecting spacy<2.2,>=2.1 Using cached spacy-2.1.9.tar.gz (30.7 MB) Installing build dependencies ... error error: subprocess-exited-with-error Γ— pip subprocess to install build dependencies did not run successfully. β”‚ exit code: 1 ╰─> [35 lines of output] Collecting setuptools Using cached setuptools-65.0.1-py3-none-any.whl (1.2 MB) Collecting wheel<0.33.0,>0.32.0 Using cached wheel-0.32.3-py2.py3-none-any.whl (21 kB) Collecting Cython Using cached Cython-0.29.32-py2.py3-none-any.whl (986 kB) Collecting cymem<2.1.0,>=2.0.2 Using cached cymem-2.0.6-cp310-cp310-win_amd64.whl (36 kB) Collecting preshed<2.1.0,>=2.0.1 Using cached preshed-2.0.1.tar.gz (113 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error python setup.py egg_info did not run successfully. exit code: 1 [6 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\oguls\AppData\Local\Temp\pip-install-qce7tdof\preshed_546a51fe26c74852ab50db073ad57f1f\setup.py", line 9, in <module> from distutils import ccompiler, msvccompiler ImportError: cannot import name 'msvccompiler' from 'distutils' (C:\Users\oguls\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\_distutils\__init__.py) [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed Encountered error while generating package metadata. See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error Γ— pip subprocess to install build dependencies did not run successfully. β”‚ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. I don't specifically know which packages cause this error, a lot of them install without any problems. I have tried updating pip, changing environment variables and other possible solutions I've found on the internet, but nothing seems to work. Edit: The package I am trying to install supports my Python version.
[ "The real error in your case is:\nImportError: cannot import name 'msvccompiler' from 'distutils'\n\nIt occured because setuptools has broken distutils in versionΒ 65.0.0 (and has already fixed it in versionΒ 65.0.2). According to your log, the error occured in your global setuptools installation (see the path in error message), so you need to update it with the following command:\npip install -U setuptools\n\nThose packages, however, may still not getΒ installed or not work properly as the module causing this error doesn't support compiler versions needed for currently supported versions of Python.\n", "Same thing happened with me, it was basically pip's version problem.\nTry upgrading pip to latest version --22.3.1 and downgrade the python version from latest version --3.10.00 to 3.9.13...\npip --version check for pip's version\npip install notebook --upgrade -command to update pip to latest version\nThis worked for me\n" ]
[ 1, 0 ]
[]
[]
[ "dependencies", "pip", "python", "setup.py", "setuptools" ]
stackoverflow_0073378545_dependencies_pip_python_setup.py_setuptools.txt
Q: How to avoid / fix ScriptException error in HTMLUnit? I'm trying to access a website on my router so I can automatically control a fish tank. When I try to connect to the website using HTML Unit it gives me an error: Nov 24, 2019 7:46:15 PM com.gargoylesoftware.htmlunit.javascript.DefaultJavaScriptErrorListener scriptException SEVERE: Error during JavaScript execution ======= EXCEPTION START ======== EcmaError: lineNumber=[108] column=[0] lineSource=[null] name=[ReferenceError] sourceName=[script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10)] message=[ReferenceError: "nsys_translator" is not defined. (script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10)#108)] com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "nsys_translator" is not defined. (script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10)#108) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:883) at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:617) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:534) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.callSecured(HtmlUnitContextFactory.java:336) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:812) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:784) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunction(HtmlPage.java:2542) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunction(HtmlPage.java:2535) at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeEventListeners(EventListenersContainer.java:342) at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeAtTargetListeners(EventListenersContainer.java:379) at com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget.fireEvent(EventTarget.java:171) at com.gargoylesoftware.htmlunit.html.HtmlPage.lambda$executeEventHandlersIfNeeded$0(HtmlPage.java:1248) at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:617) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:534) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.callSecured(HtmlUnitContextFactory.java:336) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeEventHandlersIfNeeded(HtmlPage.java:1248) at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:249) at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:541) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:400) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:317) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:469) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:450) at AlkOutput.main(AlkOutput.java:43) Caused by: net.sourceforge.htmlunit.corejs.javascript.EcmaError: ReferenceError: "nsys_translator" is not defined. (script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10)#108) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:4334) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:4312) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.notFoundError(ScriptRuntime.java:4406) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.nameOrFunction(ScriptRuntime.java:2009) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.name(ScriptRuntime.java:1948) at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1752) at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:1010) at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:111) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:424) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:322) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3628) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$3.doRun(JavaScriptEngine.java:805) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:868) ... 22 more Enclosed exception: net.sourceforge.htmlunit.corejs.javascript.EcmaError: ReferenceError: "nsys_translator" is not defined. (script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10)#108) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:4334) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:4312) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.notFoundError(ScriptRuntime.java:4406) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.nameOrFunction(ScriptRuntime.java:2009) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.name(ScriptRuntime.java:1948) at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1752) at script(script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10):108) at script(script in http://24.92.140.58:80/outsetup.sht from (-1, -1) to (-1, -1)) at script(script in http://24.92.140.58:80/outsetup.sht from (-1, -1) to (-1, -1)) at script(script in http://24.92.140.58:80/outsetup.sht from (-1, -1) to (-1, -1)) at script(script in http://24.92.140.58:80/outsetup.sht from (-1, -1) to (-1, -1)) at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:1010) at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:111) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:424) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:322) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3628) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$3.doRun(JavaScriptEngine.java:805) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:868) at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:617) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:534) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.callSecured(HtmlUnitContextFactory.java:336) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:812) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:784) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunction(HtmlPage.java:2542) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunction(HtmlPage.java:2535) at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeEventListeners(EventListenersContainer.java:342) at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeAtTargetListeners(EventListenersContainer.java:379) at com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget.fireEvent(EventTarget.java:171) at com.gargoylesoftware.htmlunit.html.HtmlPage.lambda$executeEventHandlersIfNeeded$0(HtmlPage.java:1248) at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:617) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:534) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.callSecured(HtmlUnitContextFactory.java:336) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeEventHandlersIfNeeded(HtmlPage.java:1248) at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:249) at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:541) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:400) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:317) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:469) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:450) at AlkOutput.main(AlkOutput.java:43) == CALLING JAVASCRIPT == function () { document.removeEventListener("DOMContentLoaded", arguments.callee, false); T.ready(); } ======= EXCEPTION END ======== I don't know how to bypass this error so I can access the website. I have tried using the command WebClient.getOptions().setThrowExceptionOnScriptError(false); to ignore the error but that doesn't seem to fix the issue. I also tried switching the BrowserVersion but that didn't help either. Maybe the issue is something with the website. I don't have access to changing the code on the website. Here is my code. public class AlkOutput { public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException { DefaultCredentialsProvider cred = new DefaultCredentialsProvider(); cred.addCredentials(username, password); //I didn't include real username / password for privacy WebClient web = new WebClient(BrowserVersion.INTERNET_EXPLORER); web.getOptions().setThrowExceptionOnScriptError(false); web.setCredentialsProvider(cred); HtmlPage page = web.getPage("http://24.92.140.58:80/outsetup.sht"); //error is on this line web.close(); } } A: Can you please check if the same error occures with a real browser. Setting WebClient.getOptions().setThrowExceptionOnScriptError(false); still reports the error but continues to process the js in the page (as browsers do). Why do you think it does not work - do you get the expected page? A: In my experience the default behaviour of HtmlUnit with Java Script errors has always been a mess, for the expectation to find a single page in the internet without error when including tons of script libraries, is quite small. Then, treating any error with an exception, essentially decreases the acceptance of HTMLunit. For me the common solution has been: WebClient cl = = new WebClient(BrowserVersion.FIREFOX); // or similair cl.setCssErrorHandler(...); cl.setIncorrectnessListener(...); cl.setJavaScriptErrorListener(...); cl.getOptions().setThrowExceptionOnScriptError(false); where ... is to be replaced with empty implementations of dedicated interfaces.
How to avoid / fix ScriptException error in HTMLUnit?
I'm trying to access a website on my router so I can automatically control a fish tank. When I try to connect to the website using HTML Unit it gives me an error: Nov 24, 2019 7:46:15 PM com.gargoylesoftware.htmlunit.javascript.DefaultJavaScriptErrorListener scriptException SEVERE: Error during JavaScript execution ======= EXCEPTION START ======== EcmaError: lineNumber=[108] column=[0] lineSource=[null] name=[ReferenceError] sourceName=[script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10)] message=[ReferenceError: "nsys_translator" is not defined. (script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10)#108)] com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "nsys_translator" is not defined. (script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10)#108) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:883) at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:617) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:534) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.callSecured(HtmlUnitContextFactory.java:336) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:812) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:784) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunction(HtmlPage.java:2542) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunction(HtmlPage.java:2535) at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeEventListeners(EventListenersContainer.java:342) at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeAtTargetListeners(EventListenersContainer.java:379) at com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget.fireEvent(EventTarget.java:171) at com.gargoylesoftware.htmlunit.html.HtmlPage.lambda$executeEventHandlersIfNeeded$0(HtmlPage.java:1248) at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:617) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:534) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.callSecured(HtmlUnitContextFactory.java:336) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeEventHandlersIfNeeded(HtmlPage.java:1248) at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:249) at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:541) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:400) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:317) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:469) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:450) at AlkOutput.main(AlkOutput.java:43) Caused by: net.sourceforge.htmlunit.corejs.javascript.EcmaError: ReferenceError: "nsys_translator" is not defined. (script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10)#108) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:4334) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:4312) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.notFoundError(ScriptRuntime.java:4406) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.nameOrFunction(ScriptRuntime.java:2009) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.name(ScriptRuntime.java:1948) at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1752) at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:1010) at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:111) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:424) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:322) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3628) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$3.doRun(JavaScriptEngine.java:805) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:868) ... 22 more Enclosed exception: net.sourceforge.htmlunit.corejs.javascript.EcmaError: ReferenceError: "nsys_translator" is not defined. (script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10)#108) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:4334) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:4312) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.notFoundError(ScriptRuntime.java:4406) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.nameOrFunction(ScriptRuntime.java:2009) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.name(ScriptRuntime.java:1948) at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1752) at script(script in http://24.92.140.58:80/outsetup.sht from (76, 32) to (120, 10):108) at script(script in http://24.92.140.58:80/outsetup.sht from (-1, -1) to (-1, -1)) at script(script in http://24.92.140.58:80/outsetup.sht from (-1, -1) to (-1, -1)) at script(script in http://24.92.140.58:80/outsetup.sht from (-1, -1) to (-1, -1)) at script(script in http://24.92.140.58:80/outsetup.sht from (-1, -1) to (-1, -1)) at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:1010) at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:111) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:424) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:322) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3628) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$3.doRun(JavaScriptEngine.java:805) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:868) at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:617) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:534) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.callSecured(HtmlUnitContextFactory.java:336) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:812) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:784) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunction(HtmlPage.java:2542) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunction(HtmlPage.java:2535) at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeEventListeners(EventListenersContainer.java:342) at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeAtTargetListeners(EventListenersContainer.java:379) at com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget.fireEvent(EventTarget.java:171) at com.gargoylesoftware.htmlunit.html.HtmlPage.lambda$executeEventHandlersIfNeeded$0(HtmlPage.java:1248) at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:617) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:534) at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.callSecured(HtmlUnitContextFactory.java:336) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeEventHandlersIfNeeded(HtmlPage.java:1248) at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:249) at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:541) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:400) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:317) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:469) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:450) at AlkOutput.main(AlkOutput.java:43) == CALLING JAVASCRIPT == function () { document.removeEventListener("DOMContentLoaded", arguments.callee, false); T.ready(); } ======= EXCEPTION END ======== I don't know how to bypass this error so I can access the website. I have tried using the command WebClient.getOptions().setThrowExceptionOnScriptError(false); to ignore the error but that doesn't seem to fix the issue. I also tried switching the BrowserVersion but that didn't help either. Maybe the issue is something with the website. I don't have access to changing the code on the website. Here is my code. public class AlkOutput { public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException { DefaultCredentialsProvider cred = new DefaultCredentialsProvider(); cred.addCredentials(username, password); //I didn't include real username / password for privacy WebClient web = new WebClient(BrowserVersion.INTERNET_EXPLORER); web.getOptions().setThrowExceptionOnScriptError(false); web.setCredentialsProvider(cred); HtmlPage page = web.getPage("http://24.92.140.58:80/outsetup.sht"); //error is on this line web.close(); } }
[ "Can you please check if the same error occures with a real browser.\nSetting WebClient.getOptions().setThrowExceptionOnScriptError(false); still reports the error but continues to process the js in the page (as browsers do).\nWhy do you think it does not work - do you get the expected page?\n", "In my experience the default behaviour of HtmlUnit with Java Script errors has always been a mess, for the expectation to find a single page in the internet without error when including tons of script libraries, is quite small. Then, treating any error with an exception, essentially decreases the acceptance of HTMLunit.\nFor me the common solution has been:\nWebClient cl = = new WebClient(BrowserVersion.FIREFOX); // or similair\n\ncl.setCssErrorHandler(...);\ncl.setIncorrectnessListener(...);\ncl.setJavaScriptErrorListener(...);\ncl.getOptions().setThrowExceptionOnScriptError(false);\n\nwhere ... is to be replaced with empty implementations of dedicated interfaces.\n" ]
[ 2, 0 ]
[]
[]
[ "htmlunit", "java", "javascript" ]
stackoverflow_0059024202_htmlunit_java_javascript.txt
Q: How to hide default calendar icon from datepicker in vue I have an input component in vue and I gave the type as a date. So as you see, the black icon is the default for html. And what I am trying to achieve, first I want to click whole input field to select the date, instead of only clicking the black icon. And also, I want to remove the black icon. So here is my input component in vue: <template> <div> <div v-bind:class="{row: rowStyle, 'form-group': !smallSize}"> <label v-if="label" for=inputName v-bind:class="labelClass" :style="labelStyle">{{ label }}</label> <div class="input-group" v-bind:class="inputColumnAmount"> <div v-if="inputPrefix" class="input-group-prepend"> <span v-html="inputPrefix"/> </div> <input v-if="inputType == 'text' || inputType == 'email' || inputType == 'password' || inputType == 'date'" :type="inputType" class="form-control" v-bind:class="inputClasses" v-on:focusout="$emit('value', $event.target.value)" :id="inputName" :placeholder="placeholder" :value="value" :pattern="pattern" :maxlength="maxlength" :disabled="disabled"> <div v-if="inputSuffix" class="input-group-append"> <span v-html="inputSuffix"/> </div> <div v-if="icon" class="input-group-append"> <div class="input-group-text"><i :class="icon"></i></div> </div> </div> </div> </div> </template> <script> import {v4 as uuidv4} from 'uuid'; import GENERAL_COMPONENT_CONSTANTS from "../constants/GeneralComponentConstants"; export default { props: { label: { type: String, default: '' }, error: { type: String, default: '' }, inputType: { type: String, default: 'text' }, componentStyle: { type: String, default: GENERAL_COMPONENT_CONSTANTS.componentStyle.Row }, inputPrefix: { type: String, default: '' }, inputSuffix: { type: String, default: '' }, icon: { type: String, default: '' }, labelColumns: { type: Number | String, default: 3 }, placeholder: { type: String, default: "" }, value: { type: String | Number, default: "" }, pattern: { type: String, default: "" }, maxlength: { type: String, default: "150" }, disabled: { type: Boolean, default: false }, smallSize: { type: Boolean, default: false }, }, data() { return { inputName: "input-" + uuidv4(), } }, computed: { rowStyle: function() { return this.componentStyle == GENERAL_COMPONENT_CONSTANTS.componentStyle.Row; }, labelClass: function() { let labelClass = ""; if (this.rowStyle) { labelClass += 'col-form-label '; labelClass += this.labelColumnAmount; } return labelClass; }, labelColumnAmount: function () { return "col-sm-" + this.labelColumns; }, inputColumnAmount: function () { if (!this.rowStyle) { return ''; } else if (this.label) { return "col-sm-" + (12 - this.labelColumns); } else { return "col-sm-12"; } }, labelStyle() { if (this.disabled) { return "color: #6c757d;"; } else { return ""; } }, inputClasses() { return { 'is-invalid': this.error, 'form-control-sm': this.smallSize, }; } }, } </script> And here, how I am using it: <cc-input-component label="Create from" labelColumns=4 inputType="date" :value="newAvailabilitySetting.from_date" v-on:value="newAvailabilitySetting.from_date = $event" icon="fa fa-calendar"/> Any recommendations will be appreciated. Thanks. A: First you should set a class input-component and then you can hide default icon input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-calendar-picker-indicator { display: none; -webkit-appearance: none; } A: Add icon-calendar slot with an empty <svg></svg> tag inside. <date-picker> <template v-slot:icon-calendar> <svg></svg> </template> </date-picker> https://github.com/mengxiong10/vue2-datepicker/issues/722#issuecomment-1301691106
How to hide default calendar icon from datepicker in vue
I have an input component in vue and I gave the type as a date. So as you see, the black icon is the default for html. And what I am trying to achieve, first I want to click whole input field to select the date, instead of only clicking the black icon. And also, I want to remove the black icon. So here is my input component in vue: <template> <div> <div v-bind:class="{row: rowStyle, 'form-group': !smallSize}"> <label v-if="label" for=inputName v-bind:class="labelClass" :style="labelStyle">{{ label }}</label> <div class="input-group" v-bind:class="inputColumnAmount"> <div v-if="inputPrefix" class="input-group-prepend"> <span v-html="inputPrefix"/> </div> <input v-if="inputType == 'text' || inputType == 'email' || inputType == 'password' || inputType == 'date'" :type="inputType" class="form-control" v-bind:class="inputClasses" v-on:focusout="$emit('value', $event.target.value)" :id="inputName" :placeholder="placeholder" :value="value" :pattern="pattern" :maxlength="maxlength" :disabled="disabled"> <div v-if="inputSuffix" class="input-group-append"> <span v-html="inputSuffix"/> </div> <div v-if="icon" class="input-group-append"> <div class="input-group-text"><i :class="icon"></i></div> </div> </div> </div> </div> </template> <script> import {v4 as uuidv4} from 'uuid'; import GENERAL_COMPONENT_CONSTANTS from "../constants/GeneralComponentConstants"; export default { props: { label: { type: String, default: '' }, error: { type: String, default: '' }, inputType: { type: String, default: 'text' }, componentStyle: { type: String, default: GENERAL_COMPONENT_CONSTANTS.componentStyle.Row }, inputPrefix: { type: String, default: '' }, inputSuffix: { type: String, default: '' }, icon: { type: String, default: '' }, labelColumns: { type: Number | String, default: 3 }, placeholder: { type: String, default: "" }, value: { type: String | Number, default: "" }, pattern: { type: String, default: "" }, maxlength: { type: String, default: "150" }, disabled: { type: Boolean, default: false }, smallSize: { type: Boolean, default: false }, }, data() { return { inputName: "input-" + uuidv4(), } }, computed: { rowStyle: function() { return this.componentStyle == GENERAL_COMPONENT_CONSTANTS.componentStyle.Row; }, labelClass: function() { let labelClass = ""; if (this.rowStyle) { labelClass += 'col-form-label '; labelClass += this.labelColumnAmount; } return labelClass; }, labelColumnAmount: function () { return "col-sm-" + this.labelColumns; }, inputColumnAmount: function () { if (!this.rowStyle) { return ''; } else if (this.label) { return "col-sm-" + (12 - this.labelColumns); } else { return "col-sm-12"; } }, labelStyle() { if (this.disabled) { return "color: #6c757d;"; } else { return ""; } }, inputClasses() { return { 'is-invalid': this.error, 'form-control-sm': this.smallSize, }; } }, } </script> And here, how I am using it: <cc-input-component label="Create from" labelColumns=4 inputType="date" :value="newAvailabilitySetting.from_date" v-on:value="newAvailabilitySetting.from_date = $event" icon="fa fa-calendar"/> Any recommendations will be appreciated. Thanks.
[ "First you should set a class input-component and then you can hide default icon\n input[type=\"date\"]::-webkit-inner-spin-button,\ninput[type=\"date\"]::-webkit-calendar-picker-indicator {\n display: none;\n -webkit-appearance: none;\n}\n\n", "Add icon-calendar slot with an empty <svg></svg> tag inside.\n<date-picker>\n <template v-slot:icon-calendar>\n <svg></svg>\n </template>\n</date-picker>\n\nhttps://github.com/mengxiong10/vue2-datepicker/issues/722#issuecomment-1301691106\n" ]
[ 1, 0 ]
[]
[]
[ "calendar", "datepicker", "javascript", "vue.js", "vue_component" ]
stackoverflow_0070290874_calendar_datepicker_javascript_vue.js_vue_component.txt
Q: i am facing an error while loading snowpipe into snowflake Pipe Notifications bind failure "Cross cloud integration is not supported for pipe creation in AZURE using a stage in AWS." auto_ingest=true; //couldn't compile, facing the above error. i couldn't find any possible solutions to try A: The error message you are seeing indicates that it is not possible to create a pipe for cross-cloud integration between Azure and AWS using a stage in AWS. This is because the pipe creation process does not support this type of configuration. One possible solution to this issue would be to use a different configuration for your pipe, such as using a stage in Azure instead of AWS. Alternatively, you may need to use a different method for integrating the two cloud platforms, such as using an API or other integration tool. It is also worth noting that the error message may be specific to the version of the software you are using, so it may be worth checking for any updates or potential fixes in newer versions.
i am facing an error while loading snowpipe into snowflake
Pipe Notifications bind failure "Cross cloud integration is not supported for pipe creation in AZURE using a stage in AWS." auto_ingest=true; //couldn't compile, facing the above error. i couldn't find any possible solutions to try
[ "The error message you are seeing indicates that it is not possible to create a pipe for cross-cloud integration between Azure and AWS using a stage in AWS. This is because the pipe creation process does not support this type of configuration.\nOne possible solution to this issue would be to use a different configuration for your pipe, such as using a stage in Azure instead of AWS. Alternatively, you may need to use a different method for integrating the two cloud platforms, such as using an API or other integration tool.\nIt is also worth noting that the error message may be specific to the version of the software you are using, so it may be worth checking for any updates or potential fixes in newer versions.\n" ]
[ 0 ]
[]
[]
[ "snowflake_cloud_data_platform", "snowpipe" ]
stackoverflow_0074667556_snowflake_cloud_data_platform_snowpipe.txt
Q: Variable in JSON path I would like to make the path to data contained in JSON variable. The code I have now looks like this: function writeDB(block) { $.getJSON('js/data.js', function(data) { if (block == "path1") { var adr = data.test.path1.db; }; if (block == "path2") { var adr = data.test.path2.db; }; if (block == "path3") { var adr = data.test.path3.db; }; var datastring=""; $.each(adr, function(i, field){ temp = encodeURIComponent($("#writeDB_"+block+" [name="+adr[i].abc+"]").val()); datastring += adr[i].abc+"="+temp+"&"; }); }); } The "if" parts I would like to simplify and make it variable, by using the variable 'block' directly into the "adr" path, something like this var adr = "data.test."+block+".db"; But a string won't work, so its useless. Someone knows how I can fix that? A: You want to use square bracket notation: var adr = data.test[block].db; A: if (typeof(data.test[block]) != "undefined") var adr = data.test[block].db; .... A: Very simple solution. eval("data.test."+block+".db")
Variable in JSON path
I would like to make the path to data contained in JSON variable. The code I have now looks like this: function writeDB(block) { $.getJSON('js/data.js', function(data) { if (block == "path1") { var adr = data.test.path1.db; }; if (block == "path2") { var adr = data.test.path2.db; }; if (block == "path3") { var adr = data.test.path3.db; }; var datastring=""; $.each(adr, function(i, field){ temp = encodeURIComponent($("#writeDB_"+block+" [name="+adr[i].abc+"]").val()); datastring += adr[i].abc+"="+temp+"&"; }); }); } The "if" parts I would like to simplify and make it variable, by using the variable 'block' directly into the "adr" path, something like this var adr = "data.test."+block+".db"; But a string won't work, so its useless. Someone knows how I can fix that?
[ "You want to use square bracket notation:\nvar adr = data.test[block].db;\n\n", "if (typeof(data.test[block]) != \"undefined\")\n var adr = data.test[block].db;\n....\n\n", "Very simple solution.\neval(\"data.test.\"+block+\".db\")\n" ]
[ 15, 3, 0 ]
[]
[]
[ "javascript", "jquery" ]
stackoverflow_0009703117_javascript_jquery.txt
Q: How to resolve flutter payment issue with setting theme.appcompat? I am unable to set up the app theme properly in flutter. This is required by the flutter_stripe plugin. I know the rest of my plugin works fine as it works on iOS. This is the error I am getting on Android: I/flutter (26094): ----------------FIREBASE CRASHLYTICS---------------- I/flutter (26094): PlatformException(flutter_stripe initialization failed, The plugin failed to initialize: I/flutter (26094): Your theme isn't set to use Theme.AppCompat or Theme.MaterialComponents. I/flutter (26094): Please make sure you follow all the steps detailed inside the README: https://github.com/flutter-stripe/flutter_stripe#android I/flutter (26094): If you continue to have trouble, follow this discussion to get some support https://github.com/flutter-stripe/flutter_stripe/discussions/538, null, null) I/flutter (26094): I/flutter (26094): #0 JSONMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:155:7) I/flutter (26094): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:177:18) I/flutter (26094): <asynchronous suspension> I/flutter (26094): #2 MethodChannelStripe.initialise (package:stripe_platform_interface/src/method_channel_stripe.dart:46:5) I/flutter (26094): <asynchronous suspension> I/flutter (26094): #3 Stripe._initialise (package:flutter_stripe/src/stripe.dart:424:5) I/flutter (26094): <asynchronous suspension> I/flutter (26094): #4 Stripe.initPaymentSheet (package:flutter_stripe/src/stripe.dart:317:5) I/flutter (26094): <asynchronous suspension> I/flutter (26094): #5 _SellTicketsState.makePayment (package:eventiks/Screens/sell_tickets.dart:118:6) I/flutter (26094): <asynchronous suspension> I/flutter (26094): ---------------------------------------------------- I followed the steps here for android. My app/src/main/res/values/styles.xml looks like this: <resources> <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off --> <style name="LaunchTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Show a splash screen on the activity. Automatically removed when Flutter draws its first frame --> <item name="android:windowBackground">@drawable/launch_background</item> </style> <!-- Theme applied to the Android Window as soon as the process has started. This theme determines the color of the Android Window while your Flutter UI initializes, as well as behind your Flutter UI while its running. This Theme is only used starting with V2 of Flutter's Android embedding. --> <style name="NormalTheme" parent="Theme.MaterialComponents"> <item name="android:windowBackground">?android:colorBackground</item> </style> </resources> This shows in red by the way: Theme.AppCompat.Light.NoActionBar & Theme.MaterialComponents with the warning: Cannot resolve symbol 'Theme.MaterialComponents' Cannot resolve symbol 'Theme.AppCompat.Light.NoActionBar' I read online and found that I should add the following in gradle file: implementation 'com.google.android.material:material:1.5.0' My build.gradle looks like this: def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new FileNotFoundException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('key.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion flutter.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "uk.co.eelavan.eventiks" minSdkVersion 21 targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'com.google.android.material:material:1.5.0' } apply plugin: 'com.google.gms.google-services' My kotlin plugin version is: ext.kotlin_version = '1.6.10' Which I did but I still get the error above. Need help, please! A: The answer is that you have to change style.xml in both folders values & values-night I changed in both and it works now! A: style.xml <?xml version="1.0" encoding="utf-8"?> <resources> <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off --> <style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar"> <!-- Show a splash screen on the activity. Automatically removed when Flutter draws its first frame --> <item name="android:windowBackground">@drawable/launch_background</item> </style> <!-- Theme applied to the Android Window as soon as the process has started. This theme determines the color of the Android Window while your Flutter UI initializes, as well as behind your Flutter UI while its running. This Theme is only used starting with V2 of Flutter's Android embedding. --> <!-- <style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">--> <style name="NormalTheme" parent="Theme.MaterialComponents"> <item name="android:windowBackground">?android:colorBackground</item> </style> </resources> MainActivity.kt package com.flutter.stripe.example import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterFragmentActivity class MainActivity: FlutterFragmentActivity() { } A: This is the code I used to fix this. values/styles.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off --> <style name="LaunchTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Show a splash screen on the activity. Automatically removed when Flutter draws its first frame --> <item name="android:windowBackground"> @drawable/launch_background </item> </style> <!-- Theme applied to the Android Window as soon as the process has started. This theme determines the color of the Android Window while your Flutter UI initializes, as well as behind your Flutter UI while its running. This Theme is only used starting with V2 of Flutter's Android embedding. --> <style name="NormalTheme" parent="Theme.MaterialComponents"> <item name="android:windowBackground"> ?android:colorBackground </item> </style> </resources> values-night/styles.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on --> <!-- TODO document the necessary change --> <style name="LaunchTheme" parent="Theme.AppCompat.DayNight.NoActionBar"> <!-- Show a splash screen on the activity. Automatically removed when Flutter draws its first frame --> <item name="android:windowBackground"> @drawable/launch_background </item> </style> <!-- Theme applied to the Android Window as soon as the process has started. This theme determines the color of the Android Window while your Flutter UI initializes, as well as behind your Flutter UI while its running. This Theme is only used starting with V2 of Flutter's Android embedding. --> <style name="NormalTheme" parent="Theme.MaterialComponents"> <item name="android:windowBackground"> ?android:colorBackground </item> </style> </resources> Hope that helps!!!
How to resolve flutter payment issue with setting theme.appcompat?
I am unable to set up the app theme properly in flutter. This is required by the flutter_stripe plugin. I know the rest of my plugin works fine as it works on iOS. This is the error I am getting on Android: I/flutter (26094): ----------------FIREBASE CRASHLYTICS---------------- I/flutter (26094): PlatformException(flutter_stripe initialization failed, The plugin failed to initialize: I/flutter (26094): Your theme isn't set to use Theme.AppCompat or Theme.MaterialComponents. I/flutter (26094): Please make sure you follow all the steps detailed inside the README: https://github.com/flutter-stripe/flutter_stripe#android I/flutter (26094): If you continue to have trouble, follow this discussion to get some support https://github.com/flutter-stripe/flutter_stripe/discussions/538, null, null) I/flutter (26094): I/flutter (26094): #0 JSONMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:155:7) I/flutter (26094): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:177:18) I/flutter (26094): <asynchronous suspension> I/flutter (26094): #2 MethodChannelStripe.initialise (package:stripe_platform_interface/src/method_channel_stripe.dart:46:5) I/flutter (26094): <asynchronous suspension> I/flutter (26094): #3 Stripe._initialise (package:flutter_stripe/src/stripe.dart:424:5) I/flutter (26094): <asynchronous suspension> I/flutter (26094): #4 Stripe.initPaymentSheet (package:flutter_stripe/src/stripe.dart:317:5) I/flutter (26094): <asynchronous suspension> I/flutter (26094): #5 _SellTicketsState.makePayment (package:eventiks/Screens/sell_tickets.dart:118:6) I/flutter (26094): <asynchronous suspension> I/flutter (26094): ---------------------------------------------------- I followed the steps here for android. My app/src/main/res/values/styles.xml looks like this: <resources> <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off --> <style name="LaunchTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Show a splash screen on the activity. Automatically removed when Flutter draws its first frame --> <item name="android:windowBackground">@drawable/launch_background</item> </style> <!-- Theme applied to the Android Window as soon as the process has started. This theme determines the color of the Android Window while your Flutter UI initializes, as well as behind your Flutter UI while its running. This Theme is only used starting with V2 of Flutter's Android embedding. --> <style name="NormalTheme" parent="Theme.MaterialComponents"> <item name="android:windowBackground">?android:colorBackground</item> </style> </resources> This shows in red by the way: Theme.AppCompat.Light.NoActionBar & Theme.MaterialComponents with the warning: Cannot resolve symbol 'Theme.MaterialComponents' Cannot resolve symbol 'Theme.AppCompat.Light.NoActionBar' I read online and found that I should add the following in gradle file: implementation 'com.google.android.material:material:1.5.0' My build.gradle looks like this: def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new FileNotFoundException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('key.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion flutter.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "uk.co.eelavan.eventiks" minSdkVersion 21 targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'com.google.android.material:material:1.5.0' } apply plugin: 'com.google.gms.google-services' My kotlin plugin version is: ext.kotlin_version = '1.6.10' Which I did but I still get the error above. Need help, please!
[ "The answer is that you have to change style.xml in both folders\n\nvalues\n&\nvalues-night\n\nI changed in both and it works now!\n", "style.xml\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->\n <style name=\"LaunchTheme\" parent=\"@android:style/Theme.Light.NoTitleBar\">\n <!-- Show a splash screen on the activity. Automatically removed when\n Flutter draws its first frame -->\n <item name=\"android:windowBackground\">@drawable/launch_background</item>\n </style>\n <!-- Theme applied to the Android Window as soon as the process has started.\n This theme determines the color of the Android Window while your\n Flutter UI initializes, as well as behind your Flutter UI while its\n running.\n \n This Theme is only used starting with V2 of Flutter's Android embedding. -->\n<!-- <style name=\"NormalTheme\" parent=\"@android:style/Theme.Light.NoTitleBar\">-->\n <style name=\"NormalTheme\" parent=\"Theme.MaterialComponents\">\n <item name=\"android:windowBackground\">?android:colorBackground</item>\n </style>\n</resources>\n\nMainActivity.kt\npackage com.flutter.stripe.example\n\nimport io.flutter.embedding.android.FlutterActivity\nimport io.flutter.embedding.android.FlutterFragmentActivity\n\nclass MainActivity: FlutterFragmentActivity() {\n}\n\n", "This is the code I used to fix this.\nvalues/styles.xml:\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->\n <style name=\"LaunchTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n <!--\n Show a splash screen on the activity. Automatically removed when\n Flutter draws its first frame\n -->\n <item name=\"android:windowBackground\">\n @drawable/launch_background\n </item>\n </style>\n <!--\n Theme applied to the Android Window as soon as the process has started.\n This theme determines the color of the Android Window while your\n Flutter UI initializes, as well as behind your Flutter UI while its\n running.\n \n This Theme is only used starting with V2 of Flutter's Android embedding.\n -->\n <style name=\"NormalTheme\" parent=\"Theme.MaterialComponents\">\n <item name=\"android:windowBackground\">\n ?android:colorBackground\n </item>\n </style>\n</resources>\n\nvalues-night/styles.xml:\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->\n <!-- TODO document the necessary change -->\n <style name=\"LaunchTheme\" parent=\"Theme.AppCompat.DayNight.NoActionBar\">\n <!--\n Show a splash screen on the activity. Automatically removed when\n Flutter draws its first frame\n -->\n <item name=\"android:windowBackground\">\n @drawable/launch_background\n </item>\n </style>\n <!--\n Theme applied to the Android Window as soon as the process has started.\n This theme determines the color of the Android Window while your\n Flutter UI initializes, as well as behind your Flutter UI while its\n running.\n \n This Theme is only used starting with V2 of Flutter's Android embedding.\n -->\n <style name=\"NormalTheme\" parent=\"Theme.MaterialComponents\">\n <item name=\"android:windowBackground\">\n ?android:colorBackground\n </item>\n </style>\n</resources>\n\nHope that helps!!!\n" ]
[ 1, 0, 0 ]
[]
[]
[ "build.gradle", "flutter", "flutter_dependencies", "gradle" ]
stackoverflow_0071825737_build.gradle_flutter_flutter_dependencies_gradle.txt
Q: Specify parameters for menu functions This is a snippet in the Google Apps Script for adding a menu in Google Docs/Forms/Sheets. As stated in the Menu#addItem method it calls the menuItem2 function, but the snippet didn't include a sample on how to call the addItem when you want to add parameters in function call, or is this not possible? function onOpen() { var ui = SpreadsheetApp.getUi(); // Or DocumentApp or FormApp. ui.createMenu('Custom Menu') .addItem('First item', 'menuItem1') .addSeparator() .addSubMenu(ui.createMenu('Sub-menu') .addItem('Second item', 'menuItem2')) .addToUi(); } function menuItem2() { SpreadsheetApp.getUi() // Or DocumentApp or FormApp. .alert('You clicked the second menu item!'); } function menuItem2(PARAMETER_HERE) { // codes } A: You can't add parameters to functions called by a menu. A simple workaround is to store parameters elsewhere (in scriptProperties for example) and read these parameters if parameter is undefined. function menuItem2(PARAMETER) { // if PARAMETER is undefined then read default parameter in scriptProperties // codes } In this configuration you can call the menuItem2 function from elsewhere in the script using a "normal" parameter and it will be handled as expected. A: You may pass static parameters. Moreover, you can even create a dynamic menu. class DynamicMenu { constructor() { const mySimpleParams = [["one", "1"], ["two", {aa: "objectparam"}], ["three", [["arrayParam"]]]] this.createMenu = (ui) => { const menu = ui.createMenu('My menu') mySimpleParams.forEach(param=>{ //beware to name without strange characters const functionName = `function${param[0]}` const entryName = `option-${param[0]}` menu.addItem(entryName, `menuActions.${functionName}`) }) menu.addToUi(); } this.createActions = () => { const menuActions = {} mySimpleParams.forEach(param=>{ const functionName = `function${param[0]}` menuActions[functionName] = function() {mayParametrizedFunction(param[1])} }) return menuActions; } function mayParametrizedFunction(param) { SpreadsheetApp.getUi() // Or DocumentApp or FormApp. .alert(`Got you folk!: ${param}`); } } } const menu = new DynamicMenu(); const menuActions = menu.createActions() function onOpen() { menu.createMenu(SpreadsheetApp.getUi()) }
Specify parameters for menu functions
This is a snippet in the Google Apps Script for adding a menu in Google Docs/Forms/Sheets. As stated in the Menu#addItem method it calls the menuItem2 function, but the snippet didn't include a sample on how to call the addItem when you want to add parameters in function call, or is this not possible? function onOpen() { var ui = SpreadsheetApp.getUi(); // Or DocumentApp or FormApp. ui.createMenu('Custom Menu') .addItem('First item', 'menuItem1') .addSeparator() .addSubMenu(ui.createMenu('Sub-menu') .addItem('Second item', 'menuItem2')) .addToUi(); } function menuItem2() { SpreadsheetApp.getUi() // Or DocumentApp or FormApp. .alert('You clicked the second menu item!'); } function menuItem2(PARAMETER_HERE) { // codes }
[ "You can't add parameters to functions called by a menu.\nA simple workaround is to store parameters elsewhere (in scriptProperties for example) and read these parameters if parameter is undefined.\nfunction menuItem2(PARAMETER) {\n // if PARAMETER is undefined then read default parameter in scriptProperties\n // codes \n}\n\nIn this configuration you can call the menuItem2 function from elsewhere in the script using a \"normal\" parameter and it will be handled as expected.\n", "You may pass static parameters.\nMoreover, you can even create a dynamic menu.\nclass DynamicMenu {\n constructor() { \n const mySimpleParams = [[\"one\", \"1\"], [\"two\", {aa: \"objectparam\"}], [\"three\", [[\"arrayParam\"]]]]\n\n this.createMenu = (ui) => {\n const menu = ui.createMenu('My menu')\n mySimpleParams.forEach(param=>{\n //beware to name without strange characters\n const functionName = `function${param[0]}`\n const entryName = `option-${param[0]}`\n menu.addItem(entryName, `menuActions.${functionName}`)\n })\n menu.addToUi();\n }\n \n this.createActions = () => {\n const menuActions = {}\n mySimpleParams.forEach(param=>{\n const functionName = `function${param[0]}`\n menuActions[functionName] = function() {mayParametrizedFunction(param[1])}\n })\n return menuActions;\n }\n\n function mayParametrizedFunction(param) {\n SpreadsheetApp.getUi() // Or DocumentApp or FormApp.\n .alert(`Got you folk!: ${param}`);\n }\n }\n}\n\nconst menu = new DynamicMenu();\nconst menuActions = menu.createActions()\n\nfunction onOpen() {\n menu.createMenu(SpreadsheetApp.getUi())\n}\n\n" ]
[ 6, 0 ]
[]
[]
[ "google_apps_script", "menu" ]
stackoverflow_0025758181_google_apps_script_menu.txt
Q: ECDSA ES256 JWKS JWT signature verification in Java (Elliptic Curve Signatures) I have to do signature verification of a token in Java which uses algorithm as ES256 {"typ":"JWT","alg":"ES256","kid":"4"} The public JWKS has below format: { "kty" : "EC", "kid" : "4", "use" : "sig", "x" : "hkjfghkjfdghkjdfsglkdjhg", "y" : "skjgf krhgkre", "crv" : "P-256", "x5c" : [ "uchfgurhnvgrejbhkltjrhbkrknlytknjlkfldfmndfkfvmlkasdfkljflksdanfgklnsdkjfnsadkjnkjdfnglksdfhkljdlkhfklhjdfgklghjkldfjklfjgklnvdfngjksdnfngkjvnsdfjkvsdfjkgndjkhnkjdsnhkltejhk" ], "x5t" : "jcdhsvkjgnrekngk" } What is the way to verify these? I had a look in the RS256 JWT token verification where the public JWKS is very different as below: { "kty" : "RSA", "kid" : "16", "use" : "sig", "n" : "sdghjfhgjhfjdghjkdfhghfdghfdkjhgkjfhgkjfhgkjhfjkffghjkshgjkfhgjkhfjkghjkfhgjkhfgjkhfjkghjkfhgjkafhjghfjkhgkjfhgkjhfjklghlsjkfhgjksfagmfnvmbrgmberkjltgnerkjhgjkerngkjerngjkhsjkghsjklghjkhgjkhjkghjkfahgjkhgjkhfjklghjkfhg", "e" : "AQAB", "x5c" : [ "MIIClkdfgjlkdfjklgjdfkljgkfdjgkljfkgjfklgjkldjgdfjgkldftuioreutiourtoiuriotuieorutiorutioeurtiueriotuioerwutioerutioukgjkldjgkldfjgkljklgjdfklgjorutoireutioerutiueriotuklgjkldjgklsdfjgkldfjgklsdjgkl" ], "x5t" : "jshgjfhgjkhkhghgkdfhgklhdklh" } Is there any library in Java which offers this functionality? I think in RS256 modulus and exponent is used to verify the signature, but what is used for ES256, I am not sure. Please find the code that i am using for RS256. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.security.Key; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.concurrent.TimeUnit; import org.cache2k.Cache; import org.cache2k.Cache2kBuilder; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Header; import io.jsonwebtoken.Jws; import io.jsonwebtoken.JwsHeader; import io.jsonwebtoken.Jwt; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SigningKeyResolver; import io.jsonwebtoken.SigningKeyResolverAdapter; import java.net.HttpURLConnection; public class JWTValidation { //Externalize the hosts as per the environment private static final String USER_AGENT = "Mozilla/5.0"; // Create a cache object final static Cache<String,String> _cache = new Cache2kBuilder<String, String>() {} .expireAfterWrite(30, TimeUnit.MINUTES) // expire/refresh after 30 minutes .build(); static String _jwkVersionCache = _cache.peek("jwk_version"); static String _modulusCache = _cache.peek("modulus"); static String _exponentCache = _cache.peek("exponent"); public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { System.out.println("Sample code to validate JWT"); // Running the code in loop to test multiple scenarios while(true) { // Used only for console app to get the JWS as user input Scanner reader = new Scanner(System.in); // Get the JWT System.out.println("Enter jwt or enter exit to terminate"); String signedJwtToken = reader.next(); if(signedJwtToken.equalsIgnoreCase("Exit")) { break; } try { // Validate the signed JWT (JWS) ValidateJWS(signedJwtToken); } catch (Exception e) { System.out.println("JWS validation failed"); } finally { } } } // Code to validate signed JWT (JWS) private static void ValidateJWS(String signedJwtToken) { StringBuilder sb = null; String jwtWithoutSignature; String jwtVersion; String jwksUri; String jwksUrl; String kid; TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jwks = null; @SuppressWarnings("rawtypes") Jwt<Header, Claims> jwtClaims = null; try { // Extract the base64 encoded JWT from the signed JWT token (JWS) sb = new StringBuilder(); sb.append(signedJwtToken); jwtWithoutSignature = sb.substring(0, sb.toString().lastIndexOf(".") + 1); // Parse claims without validating the signature jwtClaims = Jwts.parser().parseClaimsJwt(jwtWithoutSignature); // Extract the jwk uri 'jku' & the version 'ver' from the JWT jwtVersion = (String) jwtClaims.getBody().get("ver"); jwksUri = (String) jwtClaims.getBody().get("jku"); // Extract the kid from JWT kid = (String) jwtClaims.getHeader().get("kid"); jwksUrl = jwksHost; System.out.println("jwtVersion: " + jwtVersion); System.out.println("jwksUri: " + jwksUri); System.out.println("kid: " + kid); // Cache the jwk version (ver), modulus (n) and exponent (e) for lifetime of the application. // The JWT version will be same as jwk version. The jwt version will change only when the // JWT signing certificate is renewed. // Invoke the JWK url only if the jwt version is different from the JWK version. // check if the JWK version is cached or not if (_cache.get("jwk_version") != null) { // check if jwt version is same as jwk version if (!jwtVersion.equals(_jwkVersionCache)) { // Get the jwk key & add the modulus, exponent & the jwk version to the cache GetJWK(jwksUrl, kid); } } else { // Get the jwk key & add the modulus, exponent & the jwk version to the cache GetJWK(jwksUrl, kid); } // Calling the setSigningKeyResolver as the JWT is parsed before validating the signature SigningKeyResolver resolver = new SigningKeyResolverAdapter() { @SuppressWarnings("rawtypes") public Key resolveSigningKey(JwsHeader jwsHeader, Claims claims) { try { // Build the RSA public key from modulus & exponent in JWK BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(_modulusCache)); BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(_exponentCache)); PublicKey rsaPublicKey = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, exponent)); return rsaPublicKey; } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { System.out.println("Failed to resolve key: " + e); return null; } } }; try { // Parse claims and validate the signature Jws<Claims> jwsClaims = Jwts.parser().setSigningKeyResolver(resolver).parseClaimsJws(signedJwtToken); System.out.println("Signature on this JWT is good and the JWT token has not expired"); // OK, we can trust this JWT // Parse the claims System.out.println("JWS claims: " + jwsClaims.getBody()); // Code below to validate the claims } catch (Exception ex) { System.out.println("Unable to validate JWS"); } } // catch (SignatureException e) catch (Exception e) { // don't trust the JWT! System.out.println("JWT is malformed or expired"); } } // Get the corresponding JWK using key Id from the JWK set @SuppressWarnings("unchecked") static private Map<String, String> GetKeyById(Map<String, Object> jwks, String kid) { List<Map<String, String>> keys = (List<Map<String, String>>)jwks.get("keys"); Map<String, String> ret = null; for (int i = 0; i < keys.size(); i++) { if (keys.get(i).get("kid").equals(kid)) { System.out.println("i-->"+ keys.get(i).get("kid")); System.out.println("i set-->"+ keys.get(i)); return keys.get(i); } } return ret; } // Get the JWK Set from the JWK endpoint private static void GetJWK(String jwkUrl, String kid) throws IOException { URL url = new URL(jwkUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { //URL url = new URL(jwkUrl); System.out.println("url: "+url); //connection = (HttpURLConnection) url.openConnection(); System.out.println("connection: "+connection); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", USER_AGENT); int responseCode = connection.getResponseCode(); System.out.println("GET Response Code :: " + responseCode); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); System.out.println("rd: "+rd); //StringBuilder response = new StringBuilder(); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = rd.readLine()) != null) { response.append(inputLine); } //in.close(); // print result System.out.println(response.toString()); System.out.println("response:--> "+response); String line; //while ((line = rd.readLine()) != null) { // response.append(line); // response.append('\r'); //} rd.close(); // Jackson mapper for parsing the json TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jwks = mapper.readValue(response.toString(), typeRef); // Get the jwk by using the key Id from the jwt Map<String, String> jwk = GetKeyById(jwks, kid); // Get the modulus 'n' & the exponent 'n' from the JWK & add it to cache if (jwk != null) { _cache.put("modulus", jwk.get("x5c")); _modulusCache = _cache.get("modulus"); _cache.put("exponent", jwk.get("e")); _exponentCache = _cache.get("exponent"); _cache.put("jwk_version", jwk.get("ver")); _jwkVersionCache = _cache.get("jwk_version"); } } catch (Exception e) { // Unable to fetch JWKS. Terminate this program System.out.println("Error getting jwks: " + e); } finally { if (connection != null) { connection.disconnect(); } } } } RFC says: https://www.rfc-editor.org/rfc/rfc7518#section-3.1 "alg" Param value = ES256 Digital Signature or MAC value = ECDSA using P-256 and SHA-256 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.security.*; import java.security.spec.*; import java.text.ParseException; import java.util.Base64; import java.util.Base64.Decoder; import java.util.Base64.Encoder; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.concurrent.TimeUnit; import com.nimbusds.jose.JOSEException; import org.cache2k.Cache; import org.cache2k.Cache2kBuilder; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Header; import io.jsonwebtoken.Jws; import io.jsonwebtoken.JwsHeader; import io.jsonwebtoken.Jwt; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SigningKeyResolver; import io.jsonwebtoken.SigningKeyResolverAdapter; import java.net.HttpURLConnection; public class Es256stack { final static String jwksHost = ""; private static final String USER_AGENT = "Mozilla/5.0"; // Create a cache object final static Cache<String,String> _cache = new Cache2kBuilder<String, String>() {} .expireAfterWrite(30, TimeUnit.MINUTES) // expire/refresh after 30 minutes .build(); static String _jwkVersionCache = _cache.peek("jwk_version"); static String _modulusCache = _cache.peek("modulus"); static String _exponentCache = _cache.peek("exponent"); public static void main(String[] args) throws NoSuchAlgorithmException, InvalidParameterSpecException, InvalidKeySpecException { ValidateJWS(signedJwtToken); } //String signedJwtToken=""; // Code to validate signed JWT (JWS) private static void ValidateJWS(String signedJwtToken) { StringBuilder sb = null; String jwtWithoutSignature; String jwtVersion; String jwksUri; String jwksUrl; String kid; TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jwks = null; @SuppressWarnings("rawtypes") Jwt<Header, Claims> jwtClaims = null; try { // Extract the base64 encoded JWT from the signed JWT token (JWS) sb = new StringBuilder(); sb.append(signedJwtToken); jwtWithoutSignature = sb.substring(0, sb.toString().lastIndexOf(".") + 1); // Parse claims without validating the signature jwtClaims = Jwts.parser().parseClaimsJwt(jwtWithoutSignature); // Extract the jwk uri 'jku' & the version 'ver' from the JWT jwtVersion = (String) jwtClaims.getBody().get("ver"); jwksUri = (String) jwtClaims.getBody().get("jku"); // Extract the kid from JWT kid = (String) jwtClaims.getHeader().get("kid"); jwksUrl = ""; System.out.println("jwtVersion: " + jwtVersion); System.out.println("jwksUri: " + jwksUri); System.out.println("kid: " + kid); // Cache the jwk version (ver), modulus (n) and exponent (e) for lifetime of the application. // The JWT version will be same as jwk version. The jwt version will change only when the // JWT signing certificate is renewed. // Invoke the JWK url only if the jwt version is different from the JWK version. // check if the JWK version is cached or not if (_cache.get("jwk_version") != null) { // check if jwt version is same as jwk version if (!jwtVersion.equals(_jwkVersionCache)) { // Get the jwk key & add the modulus, exponent & the jwk version to the cache GetJWK(jwksUrl, kid); } } else { // Get the jwk key & add the modulus, exponent & the jwk version to the cache GetJWK(jwksUrl, kid); } // Calling the setSigningKeyResolver as the JWT is parsed before validating the signature SigningKeyResolver resolver = new SigningKeyResolverAdapter() { @SuppressWarnings("rawtypes") public Key resolveSigningKey(JwsHeader jwsHeader, Claims claims) { try { AlgorithmParameters a = AlgorithmParameters.getInstance("EC"); a.init(new ECGenParameterSpec("secp256r1")); ECParameterSpec p = a.getParameterSpec(ECParameterSpec.class); // Build the RSA public key from modulus & exponent in JWK BigInteger x = new BigInteger(1, Base64.getDecoder().decode(x)); // either direct or cached BigInteger y = new BigInteger(1, Base64.getDecoder().decode(y)); // ditto PublicKey ecPublicKey = KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(x,y), p)); return ecPublicKey; } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { System.out.println("Failed to resolve key: " + e); return null; } catch (InvalidParameterSpecException e) { throw new RuntimeException(e); } } }; try { // Parse claims and validate the signature Jws<Claims> jwsClaims = Jwts.parser().setSigningKeyResolver(resolver).parseClaimsJws(signedJwtToken); System.out.println("Signature on this JWT is good and the JWT token has not expired"); // OK, we can trust this JWT // Parse the claims System.out.println("JWS claims: " + jwsClaims.getBody()); // Code below to validate the claims } catch (Exception ex) { System.out.println("Unable to validate JWS"); } } // catch (SignatureException e) catch (Exception e) { // don't trust the JWT! System.out.println("JWT is malformed or expired"); } } // Get the JWK Set from the JWK endpoint private static void GetJWK(String jwkUrl, String kid) throws IOException { URL url = new URL(jwkUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { //URL url = new URL(jwkUrl); System.out.println("url: "+url); //connection = (HttpURLConnection) url.openConnection(); System.out.println("connection: "+connection); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", USER_AGENT); int responseCode = connection.getResponseCode(); System.out.println("GET Response Code :: " + responseCode); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); System.out.println("rd: "+rd); //StringBuilder response = new StringBuilder(); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = rd.readLine()) != null) { response.append(inputLine); } //in.close(); // print result System.out.println(response.toString()); System.out.println("response:--> "+response); String line; //while ((line = rd.readLine()) != null) { // response.append(line); // response.append('\r'); //} rd.close(); // Jackson mapper for parsing the json TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jwks = mapper.readValue(response.toString(), typeRef); System.out.println("jwks:--> "+jwks); // Get the jwk by using the key Id from the jwt Map<String, String> jwk = GetKeyById(jwks, kid); System.out.println("jwk:--> "+jwk); // Get the modulus 'n' & the exponent 'n' from the JWK & add it to cache if (jwk != null) { } } catch (Exception e) { // Unable to fetch JWKS. Terminate this program System.out.println("Error getting jwks: " + e); } finally { if (connection != null) { connection.disconnect(); } } } static private Map<String, String> GetKeyById(Map<String, Object> jwks, String kid) { List<Map<String, String>> keys = (List<Map<String, String>>)jwks.get("keys"); Map<String, String> ret = null; for (int i = 0; i < keys.size(); i++) { if (keys.get(i).get("kid").equals(kid)) { System.out.println("i-->"+ keys.get(i).get("kid")); System.out.println("i set-->"+ keys.get(i)); return keys.get(i); } } return ret; } } JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted. cert part worked as below: String x5c=""; System.out.println(" x5c ="+x5c); String stripped = x5c.replaceAll("-----BEGIN (.*)-----", ""); stripped = stripped.replaceAll("-----END (.*)----", ""); stripped = stripped.replaceAll("\r\n", ""); stripped = stripped.replaceAll("\n", ""); stripped.trim(); System.out.println(" stripped ="+stripped); byte[] keyBytes = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(stripped); CertificateFactory fact = CertificateFactory.getInstance("X.509"); X509Certificate cer = (X509Certificate) fact.generateCertificate(new ByteArrayInputStream(keyBytes)); System.out.println(cer); return cer.getPublicKey(); A: First, your code has a bug or is miscopied. In GetJWK in the last block (before catch) you have a comment Get the modulus 'n' & the exponent 'n' which is wrong (the public exponent is 'e') but the code shown actually gets 'x5c' not 'n' and uses it as the modulus, which is very wrong, and shouldn't even work because 'x5c' is an array not a scalar. Yes, the library you are using (jjwt) can verify (and generate) ECDSA signatures in JWS/JWT. For any code, the signature is generated using the algorithm-dependent elements in the private key, and verified using the algorithm-dependent elements in the public key: n and e for RSA, x and y for ECDSA on a curve which is both implied by alg and restated in crv -- see part of rfc7518 section 3.4 and rfc7518 section 6.2.1. Note x and y must be valid base64url (yours aren't) and must be exactly the length required by the size of the curve-group defined by alg and crv (yours aren't). You can construct a Java-crypto ECPublicKey (or pedantically a provider's implementation object implementing that) similar to what you do in resolveSigningKey now for RSA, except that EC requires 'parameters' for the curve in addition to x and y: // this part is the same for all keys and could be done at init or memoized AlgorithmParameters a = AlgorithmParameters.getInstance("EC"); a.init(new ECGenParameterSpec("P-256")); ECParameterSpec p = a.getParameterSpec(ECParameterSpec.class); // this part must be redone for each different key // to prevent misuse verify crv_field (either direct or cached) equals("P-256") // and probably alg_field (ditto) equals("ES256") BigInteger x = new BigInteger(1, base64urldecode(x_field)); // either direct or cached BigInteger y = new BigInteger(1, base64urldecode(y_field)); // ditto PublicKey ecPublicKey = KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(x,y), p)); // add exception handling to taste However, if your JWKs (always) have x5c as in your examples, but with a valid value (yours aren't valid base64url-of-DER and are much too small) you can use much simpler code; for all signature algorithms just do: String x5c = // get element 0 of field 'x5c' from JWK (cached if you like) X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate( new ByteArrayInputStream( base64decode(x5c) ) ); // NOT base64url // (with exception handling of course) // then use cert.getPublicKey() as the PublicKey for jjwt
ECDSA ES256 JWKS JWT signature verification in Java (Elliptic Curve Signatures)
I have to do signature verification of a token in Java which uses algorithm as ES256 {"typ":"JWT","alg":"ES256","kid":"4"} The public JWKS has below format: { "kty" : "EC", "kid" : "4", "use" : "sig", "x" : "hkjfghkjfdghkjdfsglkdjhg", "y" : "skjgf krhgkre", "crv" : "P-256", "x5c" : [ "uchfgurhnvgrejbhkltjrhbkrknlytknjlkfldfmndfkfvmlkasdfkljflksdanfgklnsdkjfnsadkjnkjdfnglksdfhkljdlkhfklhjdfgklghjkldfjklfjgklnvdfngjksdnfngkjvnsdfjkvsdfjkgndjkhnkjdsnhkltejhk" ], "x5t" : "jcdhsvkjgnrekngk" } What is the way to verify these? I had a look in the RS256 JWT token verification where the public JWKS is very different as below: { "kty" : "RSA", "kid" : "16", "use" : "sig", "n" : "sdghjfhgjhfjdghjkdfhghfdghfdkjhgkjfhgkjfhgkjhfjkffghjkshgjkfhgjkhfjkghjkfhgjkhfgjkhfjkghjkfhgjkafhjghfjkhgkjfhgkjhfjklghlsjkfhgjksfagmfnvmbrgmberkjltgnerkjhgjkerngkjerngjkhsjkghsjklghjkhgjkhjkghjkfahgjkhgjkhfjklghjkfhg", "e" : "AQAB", "x5c" : [ "MIIClkdfgjlkdfjklgjdfkljgkfdjgkljfkgjfklgjkldjgdfjgkldftuioreutiourtoiuriotuieorutiorutioeurtiueriotuioerwutioerutioukgjkldjgkldfjgkljklgjdfklgjorutoireutioerutiueriotuklgjkldjgklsdfjgkldfjgklsdjgkl" ], "x5t" : "jshgjfhgjkhkhghgkdfhgklhdklh" } Is there any library in Java which offers this functionality? I think in RS256 modulus and exponent is used to verify the signature, but what is used for ES256, I am not sure. Please find the code that i am using for RS256. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.security.Key; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.concurrent.TimeUnit; import org.cache2k.Cache; import org.cache2k.Cache2kBuilder; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Header; import io.jsonwebtoken.Jws; import io.jsonwebtoken.JwsHeader; import io.jsonwebtoken.Jwt; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SigningKeyResolver; import io.jsonwebtoken.SigningKeyResolverAdapter; import java.net.HttpURLConnection; public class JWTValidation { //Externalize the hosts as per the environment private static final String USER_AGENT = "Mozilla/5.0"; // Create a cache object final static Cache<String,String> _cache = new Cache2kBuilder<String, String>() {} .expireAfterWrite(30, TimeUnit.MINUTES) // expire/refresh after 30 minutes .build(); static String _jwkVersionCache = _cache.peek("jwk_version"); static String _modulusCache = _cache.peek("modulus"); static String _exponentCache = _cache.peek("exponent"); public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { System.out.println("Sample code to validate JWT"); // Running the code in loop to test multiple scenarios while(true) { // Used only for console app to get the JWS as user input Scanner reader = new Scanner(System.in); // Get the JWT System.out.println("Enter jwt or enter exit to terminate"); String signedJwtToken = reader.next(); if(signedJwtToken.equalsIgnoreCase("Exit")) { break; } try { // Validate the signed JWT (JWS) ValidateJWS(signedJwtToken); } catch (Exception e) { System.out.println("JWS validation failed"); } finally { } } } // Code to validate signed JWT (JWS) private static void ValidateJWS(String signedJwtToken) { StringBuilder sb = null; String jwtWithoutSignature; String jwtVersion; String jwksUri; String jwksUrl; String kid; TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jwks = null; @SuppressWarnings("rawtypes") Jwt<Header, Claims> jwtClaims = null; try { // Extract the base64 encoded JWT from the signed JWT token (JWS) sb = new StringBuilder(); sb.append(signedJwtToken); jwtWithoutSignature = sb.substring(0, sb.toString().lastIndexOf(".") + 1); // Parse claims without validating the signature jwtClaims = Jwts.parser().parseClaimsJwt(jwtWithoutSignature); // Extract the jwk uri 'jku' & the version 'ver' from the JWT jwtVersion = (String) jwtClaims.getBody().get("ver"); jwksUri = (String) jwtClaims.getBody().get("jku"); // Extract the kid from JWT kid = (String) jwtClaims.getHeader().get("kid"); jwksUrl = jwksHost; System.out.println("jwtVersion: " + jwtVersion); System.out.println("jwksUri: " + jwksUri); System.out.println("kid: " + kid); // Cache the jwk version (ver), modulus (n) and exponent (e) for lifetime of the application. // The JWT version will be same as jwk version. The jwt version will change only when the // JWT signing certificate is renewed. // Invoke the JWK url only if the jwt version is different from the JWK version. // check if the JWK version is cached or not if (_cache.get("jwk_version") != null) { // check if jwt version is same as jwk version if (!jwtVersion.equals(_jwkVersionCache)) { // Get the jwk key & add the modulus, exponent & the jwk version to the cache GetJWK(jwksUrl, kid); } } else { // Get the jwk key & add the modulus, exponent & the jwk version to the cache GetJWK(jwksUrl, kid); } // Calling the setSigningKeyResolver as the JWT is parsed before validating the signature SigningKeyResolver resolver = new SigningKeyResolverAdapter() { @SuppressWarnings("rawtypes") public Key resolveSigningKey(JwsHeader jwsHeader, Claims claims) { try { // Build the RSA public key from modulus & exponent in JWK BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(_modulusCache)); BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(_exponentCache)); PublicKey rsaPublicKey = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, exponent)); return rsaPublicKey; } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { System.out.println("Failed to resolve key: " + e); return null; } } }; try { // Parse claims and validate the signature Jws<Claims> jwsClaims = Jwts.parser().setSigningKeyResolver(resolver).parseClaimsJws(signedJwtToken); System.out.println("Signature on this JWT is good and the JWT token has not expired"); // OK, we can trust this JWT // Parse the claims System.out.println("JWS claims: " + jwsClaims.getBody()); // Code below to validate the claims } catch (Exception ex) { System.out.println("Unable to validate JWS"); } } // catch (SignatureException e) catch (Exception e) { // don't trust the JWT! System.out.println("JWT is malformed or expired"); } } // Get the corresponding JWK using key Id from the JWK set @SuppressWarnings("unchecked") static private Map<String, String> GetKeyById(Map<String, Object> jwks, String kid) { List<Map<String, String>> keys = (List<Map<String, String>>)jwks.get("keys"); Map<String, String> ret = null; for (int i = 0; i < keys.size(); i++) { if (keys.get(i).get("kid").equals(kid)) { System.out.println("i-->"+ keys.get(i).get("kid")); System.out.println("i set-->"+ keys.get(i)); return keys.get(i); } } return ret; } // Get the JWK Set from the JWK endpoint private static void GetJWK(String jwkUrl, String kid) throws IOException { URL url = new URL(jwkUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { //URL url = new URL(jwkUrl); System.out.println("url: "+url); //connection = (HttpURLConnection) url.openConnection(); System.out.println("connection: "+connection); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", USER_AGENT); int responseCode = connection.getResponseCode(); System.out.println("GET Response Code :: " + responseCode); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); System.out.println("rd: "+rd); //StringBuilder response = new StringBuilder(); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = rd.readLine()) != null) { response.append(inputLine); } //in.close(); // print result System.out.println(response.toString()); System.out.println("response:--> "+response); String line; //while ((line = rd.readLine()) != null) { // response.append(line); // response.append('\r'); //} rd.close(); // Jackson mapper for parsing the json TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jwks = mapper.readValue(response.toString(), typeRef); // Get the jwk by using the key Id from the jwt Map<String, String> jwk = GetKeyById(jwks, kid); // Get the modulus 'n' & the exponent 'n' from the JWK & add it to cache if (jwk != null) { _cache.put("modulus", jwk.get("x5c")); _modulusCache = _cache.get("modulus"); _cache.put("exponent", jwk.get("e")); _exponentCache = _cache.get("exponent"); _cache.put("jwk_version", jwk.get("ver")); _jwkVersionCache = _cache.get("jwk_version"); } } catch (Exception e) { // Unable to fetch JWKS. Terminate this program System.out.println("Error getting jwks: " + e); } finally { if (connection != null) { connection.disconnect(); } } } } RFC says: https://www.rfc-editor.org/rfc/rfc7518#section-3.1 "alg" Param value = ES256 Digital Signature or MAC value = ECDSA using P-256 and SHA-256 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.security.*; import java.security.spec.*; import java.text.ParseException; import java.util.Base64; import java.util.Base64.Decoder; import java.util.Base64.Encoder; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.concurrent.TimeUnit; import com.nimbusds.jose.JOSEException; import org.cache2k.Cache; import org.cache2k.Cache2kBuilder; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Header; import io.jsonwebtoken.Jws; import io.jsonwebtoken.JwsHeader; import io.jsonwebtoken.Jwt; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SigningKeyResolver; import io.jsonwebtoken.SigningKeyResolverAdapter; import java.net.HttpURLConnection; public class Es256stack { final static String jwksHost = ""; private static final String USER_AGENT = "Mozilla/5.0"; // Create a cache object final static Cache<String,String> _cache = new Cache2kBuilder<String, String>() {} .expireAfterWrite(30, TimeUnit.MINUTES) // expire/refresh after 30 minutes .build(); static String _jwkVersionCache = _cache.peek("jwk_version"); static String _modulusCache = _cache.peek("modulus"); static String _exponentCache = _cache.peek("exponent"); public static void main(String[] args) throws NoSuchAlgorithmException, InvalidParameterSpecException, InvalidKeySpecException { ValidateJWS(signedJwtToken); } //String signedJwtToken=""; // Code to validate signed JWT (JWS) private static void ValidateJWS(String signedJwtToken) { StringBuilder sb = null; String jwtWithoutSignature; String jwtVersion; String jwksUri; String jwksUrl; String kid; TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jwks = null; @SuppressWarnings("rawtypes") Jwt<Header, Claims> jwtClaims = null; try { // Extract the base64 encoded JWT from the signed JWT token (JWS) sb = new StringBuilder(); sb.append(signedJwtToken); jwtWithoutSignature = sb.substring(0, sb.toString().lastIndexOf(".") + 1); // Parse claims without validating the signature jwtClaims = Jwts.parser().parseClaimsJwt(jwtWithoutSignature); // Extract the jwk uri 'jku' & the version 'ver' from the JWT jwtVersion = (String) jwtClaims.getBody().get("ver"); jwksUri = (String) jwtClaims.getBody().get("jku"); // Extract the kid from JWT kid = (String) jwtClaims.getHeader().get("kid"); jwksUrl = ""; System.out.println("jwtVersion: " + jwtVersion); System.out.println("jwksUri: " + jwksUri); System.out.println("kid: " + kid); // Cache the jwk version (ver), modulus (n) and exponent (e) for lifetime of the application. // The JWT version will be same as jwk version. The jwt version will change only when the // JWT signing certificate is renewed. // Invoke the JWK url only if the jwt version is different from the JWK version. // check if the JWK version is cached or not if (_cache.get("jwk_version") != null) { // check if jwt version is same as jwk version if (!jwtVersion.equals(_jwkVersionCache)) { // Get the jwk key & add the modulus, exponent & the jwk version to the cache GetJWK(jwksUrl, kid); } } else { // Get the jwk key & add the modulus, exponent & the jwk version to the cache GetJWK(jwksUrl, kid); } // Calling the setSigningKeyResolver as the JWT is parsed before validating the signature SigningKeyResolver resolver = new SigningKeyResolverAdapter() { @SuppressWarnings("rawtypes") public Key resolveSigningKey(JwsHeader jwsHeader, Claims claims) { try { AlgorithmParameters a = AlgorithmParameters.getInstance("EC"); a.init(new ECGenParameterSpec("secp256r1")); ECParameterSpec p = a.getParameterSpec(ECParameterSpec.class); // Build the RSA public key from modulus & exponent in JWK BigInteger x = new BigInteger(1, Base64.getDecoder().decode(x)); // either direct or cached BigInteger y = new BigInteger(1, Base64.getDecoder().decode(y)); // ditto PublicKey ecPublicKey = KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(x,y), p)); return ecPublicKey; } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { System.out.println("Failed to resolve key: " + e); return null; } catch (InvalidParameterSpecException e) { throw new RuntimeException(e); } } }; try { // Parse claims and validate the signature Jws<Claims> jwsClaims = Jwts.parser().setSigningKeyResolver(resolver).parseClaimsJws(signedJwtToken); System.out.println("Signature on this JWT is good and the JWT token has not expired"); // OK, we can trust this JWT // Parse the claims System.out.println("JWS claims: " + jwsClaims.getBody()); // Code below to validate the claims } catch (Exception ex) { System.out.println("Unable to validate JWS"); } } // catch (SignatureException e) catch (Exception e) { // don't trust the JWT! System.out.println("JWT is malformed or expired"); } } // Get the JWK Set from the JWK endpoint private static void GetJWK(String jwkUrl, String kid) throws IOException { URL url = new URL(jwkUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { //URL url = new URL(jwkUrl); System.out.println("url: "+url); //connection = (HttpURLConnection) url.openConnection(); System.out.println("connection: "+connection); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", USER_AGENT); int responseCode = connection.getResponseCode(); System.out.println("GET Response Code :: " + responseCode); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); System.out.println("rd: "+rd); //StringBuilder response = new StringBuilder(); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = rd.readLine()) != null) { response.append(inputLine); } //in.close(); // print result System.out.println(response.toString()); System.out.println("response:--> "+response); String line; //while ((line = rd.readLine()) != null) { // response.append(line); // response.append('\r'); //} rd.close(); // Jackson mapper for parsing the json TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jwks = mapper.readValue(response.toString(), typeRef); System.out.println("jwks:--> "+jwks); // Get the jwk by using the key Id from the jwt Map<String, String> jwk = GetKeyById(jwks, kid); System.out.println("jwk:--> "+jwk); // Get the modulus 'n' & the exponent 'n' from the JWK & add it to cache if (jwk != null) { } } catch (Exception e) { // Unable to fetch JWKS. Terminate this program System.out.println("Error getting jwks: " + e); } finally { if (connection != null) { connection.disconnect(); } } } static private Map<String, String> GetKeyById(Map<String, Object> jwks, String kid) { List<Map<String, String>> keys = (List<Map<String, String>>)jwks.get("keys"); Map<String, String> ret = null; for (int i = 0; i < keys.size(); i++) { if (keys.get(i).get("kid").equals(kid)) { System.out.println("i-->"+ keys.get(i).get("kid")); System.out.println("i set-->"+ keys.get(i)); return keys.get(i); } } return ret; } } JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted. cert part worked as below: String x5c=""; System.out.println(" x5c ="+x5c); String stripped = x5c.replaceAll("-----BEGIN (.*)-----", ""); stripped = stripped.replaceAll("-----END (.*)----", ""); stripped = stripped.replaceAll("\r\n", ""); stripped = stripped.replaceAll("\n", ""); stripped.trim(); System.out.println(" stripped ="+stripped); byte[] keyBytes = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(stripped); CertificateFactory fact = CertificateFactory.getInstance("X.509"); X509Certificate cer = (X509Certificate) fact.generateCertificate(new ByteArrayInputStream(keyBytes)); System.out.println(cer); return cer.getPublicKey();
[ "First, your code has a bug or is miscopied. In GetJWK in the last block (before catch) you have a comment Get the modulus 'n' & the exponent 'n' which is wrong (the public exponent is 'e') but the code shown actually gets 'x5c' not 'n' and uses it as the modulus, which is very wrong, and shouldn't even work because 'x5c' is an array not a scalar.\nYes, the library you are using (jjwt) can verify (and generate) ECDSA signatures in JWS/JWT. For any code, the signature is generated using the algorithm-dependent elements in the private key, and verified using the algorithm-dependent elements in the public key: n and e for RSA, x and y for ECDSA on a curve which is both implied by alg and restated in crv -- see part of rfc7518 section 3.4 and rfc7518 section 6.2.1. Note x and y must be valid base64url (yours aren't) and must be exactly the length required by the size of the curve-group defined by alg and crv (yours aren't).\nYou can construct a Java-crypto ECPublicKey (or pedantically a provider's implementation object implementing that) similar to what you do in resolveSigningKey now for RSA, except that EC requires 'parameters' for the curve in addition to x and y:\n// this part is the same for all keys and could be done at init or memoized\nAlgorithmParameters a = AlgorithmParameters.getInstance(\"EC\");\na.init(new ECGenParameterSpec(\"P-256\"));\nECParameterSpec p = a.getParameterSpec(ECParameterSpec.class);\n\n// this part must be redone for each different key\n// to prevent misuse verify crv_field (either direct or cached) equals(\"P-256\")\n// and probably alg_field (ditto) equals(\"ES256\")\nBigInteger x = new BigInteger(1, base64urldecode(x_field)); // either direct or cached\nBigInteger y = new BigInteger(1, base64urldecode(y_field)); // ditto \nPublicKey ecPublicKey = KeyFactory.getInstance(\"EC\").generatePublic(new ECPublicKeySpec(new ECPoint(x,y), p));\n\n// add exception handling to taste\n\nHowever, if your JWKs (always) have x5c as in your examples, but with a valid value (yours aren't valid base64url-of-DER and are much too small) you can use much simpler code; for all signature algorithms just do:\nString x5c = // get element 0 of field 'x5c' from JWK (cached if you like)\nX509Certificate cert = (X509Certificate) CertificateFactory.getInstance(\"X.509\")\n .generateCertificate( new ByteArrayInputStream( base64decode(x5c) ) ); // NOT base64url\n// (with exception handling of course)\n// then use cert.getPublicKey() as the PublicKey for jjwt\n\n" ]
[ 1 ]
[]
[]
[ "java", "jwt" ]
stackoverflow_0074517437_java_jwt.txt
Q: How to add distributionSha256Sum to gradle Android Studio? This is my gradle-wrapper.properties . gradle#Wed Jul 25 11:42:23 IST 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip I need to add line similar to this :- distributionSha256Sum=7a2c66d1a78f811d5f37d14630ad21cec5e77a2a4dc61e787e2257a6341016ce How can we add distributionSha256Sum to gradle-wrapper.properties ? why gradle/wrapper/gradle.properties is missing distributionSha256Sum is considered as a Security Issue ? I am using latest Android Studio on Ubuntu 16.04. A: Just click the 2nd option and you are good to go ;) https://github.com/SecUSo/privacy-friendly-ludo/issues/14
How to add distributionSha256Sum to gradle Android Studio?
This is my gradle-wrapper.properties . gradle#Wed Jul 25 11:42:23 IST 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip I need to add line similar to this :- distributionSha256Sum=7a2c66d1a78f811d5f37d14630ad21cec5e77a2a4dc61e787e2257a6341016ce How can we add distributionSha256Sum to gradle-wrapper.properties ? why gradle/wrapper/gradle.properties is missing distributionSha256Sum is considered as a Security Issue ? I am using latest Android Studio on Ubuntu 16.04.
[ "Just click the 2nd option and you are good to go ;)\n\nhttps://github.com/SecUSo/privacy-friendly-ludo/issues/14\n" ]
[ 0 ]
[]
[]
[ "android", "checksum", "fdroid", "gradle" ]
stackoverflow_0051571407_android_checksum_fdroid_gradle.txt
Q: Debug Azure Function locally with Visual Studio 2019 I want to run a task every day at 5 am to write some data to the database to create some reports. For that I thought I could use Azure Functions (Timer trigger). My goal is to first debug the function locally (using a local database) before publishing it to Azure. For this I have created a new Azure Functions project in Visual Studio 2019 with the following parameters: .NET 5.0 (Isolated). Timer trigger. Storage Account (AzureWebJobsStorage): Storage Emulator. Schedule: 0 0 5 * * * If I try to run the function (pressing F5 in the keyboard) without any changes to the code, it opens a CMD window with the colored Azure Functions logo created with characters and then the following error: Error: unknown argument --port In project properties > Debug tab > Application arguments I have --port 7282. I have a systray icon with this message: "Storage emulator is started". I tried the answer of What is the simplest way to run a timer-triggered Azure Function locally once? question, but I get the same error. What do I have to do to debug the function locally? Do I need to install any specific tool? If it helps, I have the following files: Program.cs public class Program { public static void Main() { var host = new HostBuilder() .ConfigureFunctionsWorkerDefaults() .Build(); host.Run(); } } Function1.cs: public class Function1 { private readonly ILogger _logger; public Function1(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<Function1>(); } [Function("Function1")] public void Run([TimerTrigger("0 0 5 * * *")] MyInfo myTimer) { _logger.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); _logger.LogInformation($"Next timer schedule at: {myTimer.ScheduleStatus.Next}"); } } public class MyInfo { ... } public class MyScheduleStatus { ... } A: Why do is port sat ? What happens if you remove the --port (can't comment due to my low rep. There for I try to give the answer) Then try to add RunOnStartup=true to your Function parameter as such: [Function("Function1")] public void Run([TimerTrigger("0 0 5 * * *") RunOnStartup=true] MyInfo myTimer) { _logger.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); _logger.LogInformation($"Next timer schedule at: {myTimer.ScheduleStatus.Next}"); } That should trigger it to run at start up for your application. Have you looked at the MS Learn docs
Debug Azure Function locally with Visual Studio 2019
I want to run a task every day at 5 am to write some data to the database to create some reports. For that I thought I could use Azure Functions (Timer trigger). My goal is to first debug the function locally (using a local database) before publishing it to Azure. For this I have created a new Azure Functions project in Visual Studio 2019 with the following parameters: .NET 5.0 (Isolated). Timer trigger. Storage Account (AzureWebJobsStorage): Storage Emulator. Schedule: 0 0 5 * * * If I try to run the function (pressing F5 in the keyboard) without any changes to the code, it opens a CMD window with the colored Azure Functions logo created with characters and then the following error: Error: unknown argument --port In project properties > Debug tab > Application arguments I have --port 7282. I have a systray icon with this message: "Storage emulator is started". I tried the answer of What is the simplest way to run a timer-triggered Azure Function locally once? question, but I get the same error. What do I have to do to debug the function locally? Do I need to install any specific tool? If it helps, I have the following files: Program.cs public class Program { public static void Main() { var host = new HostBuilder() .ConfigureFunctionsWorkerDefaults() .Build(); host.Run(); } } Function1.cs: public class Function1 { private readonly ILogger _logger; public Function1(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<Function1>(); } [Function("Function1")] public void Run([TimerTrigger("0 0 5 * * *")] MyInfo myTimer) { _logger.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); _logger.LogInformation($"Next timer schedule at: {myTimer.ScheduleStatus.Next}"); } } public class MyInfo { ... } public class MyScheduleStatus { ... }
[ "Why do is port sat ?\nWhat happens if you remove the --port (can't comment due to my low rep. There for I try to give the answer)\nThen try to add RunOnStartup=true to your Function parameter as such:\n[Function(\"Function1\")]\n public void Run([TimerTrigger(\"0 0 5 * * *\") RunOnStartup=true] MyInfo myTimer)\n {\n _logger.LogInformation($\"C# Timer trigger function executed at: {DateTime.Now}\");\n _logger.LogInformation($\"Next timer schedule at: {myTimer.ScheduleStatus.Next}\");\n }\n\nThat should trigger it to run at start up for your application.\nHave you looked at the MS Learn docs\n" ]
[ 0 ]
[]
[]
[ "azure", "azure_functions", "c#", "debugging", "visual_studio_2019" ]
stackoverflow_0074644600_azure_azure_functions_c#_debugging_visual_studio_2019.txt
Q: Extract rownames from list of data frames in R I want to go through my list of 11 dataframes and extract rownames of each element. I have tried this but it didn't work properly. all.seq <- vector(mode = "character", length = 11) for(i in 11) { all.seq[i] = rownames(my_list[[i]]) } Anybody can help? A: You can put all your dataframes into a list, use lapply to use rownames() on every dataframe in that list, and then use unlist() to turn your list into a vector. data(mtcars); data(iris); data(airquality) my_list <- list(mtcars, iris, airquality) my_rownames <- lapply(my_list, rownames) my_rownames <- unlist(my_rownames) class(my_rownames) #> [1] "character" head(my_rownames) #> [1] "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" #> [4] "Hornet 4 Drive" "Hornet Sportabout" "Valiant"
Extract rownames from list of data frames in R
I want to go through my list of 11 dataframes and extract rownames of each element. I have tried this but it didn't work properly. all.seq <- vector(mode = "character", length = 11) for(i in 11) { all.seq[i] = rownames(my_list[[i]]) } Anybody can help?
[ "You can put all your dataframes into a list, use lapply to use rownames() on every dataframe in that list, and then use unlist() to turn your list into a vector.\ndata(mtcars); data(iris); data(airquality)\nmy_list <- list(mtcars, iris, airquality)\nmy_rownames <- lapply(my_list, rownames)\nmy_rownames <- unlist(my_rownames)\nclass(my_rownames)\n#> [1] \"character\"\nhead(my_rownames)\n#> [1] \"Mazda RX4\" \"Mazda RX4 Wag\" \"Datsun 710\" \n#> [4] \"Hornet 4 Drive\" \"Hornet Sportabout\" \"Valiant\"\n\n" ]
[ 0 ]
[]
[]
[ "extract", "list", "r", "rowname" ]
stackoverflow_0074660979_extract_list_r_rowname.txt
Q: Source and Header file syntax in MPLAB X IDE v5.50 I am developing the code for my PIC32MK1024MCM project. I have already tested the code well and now I am only putting all the code modules into the final project (the code is not complete in this example yet, but the functionality is not the axis of interest here). For the first time in my life, I wanted to make it a little bit more professional and use separate source and header files for all the different module function declaration. However, I am clearly facing some kind of syntax problem, because I am getting errors in almost every line of the source file (I guess I have to include something in that source file, but I am not sure) Like I said, it is my very first time facing header and source files, so could you please help me, or at least hint me, what is it that I am missing so obviously? I want to thank you in advance. main: #include <xc.h> #include <configuration_bits.c> #include <toolchain_specifics.h> #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include "stdio.h" #include <sys/attribs.h> #include <analog_to_digital_conversion.h> void main(void) { while (1){ } return (EXIT_FAILURE); } configurations_bits // DEVCFG3 #pragma config USERID = 0xFFFF // Enter Hexadecimal value (Enter Hexadecimal value) #pragma config PWMLOCK = OFF // PWM IOxCON lock (PWM IOxCON register writes accesses are not locked or protected) #pragma config FUSBIDIO2 = OFF // USB2 USBID Selection (USBID pin is controlled by the port function) #pragma config FVBUSIO2 = OFF // USB2 VBUSON Selection bit (VBUSON pin is controlled by the port function) #pragma config PGL1WAY = OFF // Permission Group Lock One Way Configuration bit (Allow multiple reconfigurations) #pragma config PMDL1WAY = OFF // Peripheral Module Disable Configuration (Allow multiple reconfigurations) #pragma config IOL1WAY = OFF // Peripheral Pin Select Configuration (Allow multiple reconfigurations) #pragma config FUSBIDIO1 = OFF // USB1 USBID Selection (USBID pin is controlled by the port function) #pragma config FVBUSIO1 = OFF // USB2 VBUSON Selection bit (VBUSON pin is controlled by the port function) // DEVCFG2 #pragma config FPLLIDIV = DIV_1 // System PLL Input Divider (1x Divider) #pragma config FPLLRNG = RANGE_BYPASS // System PLL Input Range (Bypass) #pragma config FPLLICLK = PLL_POSC // System PLL Input Clock Selection (POSC is input to the System PLL) #pragma config FPLLMULT = MUL_4 // System PLL Multiplier (PLL Multiply by 4) #pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (2x Divider) #pragma config BORSEL = HIGH // Brown-out trip voltage (BOR trip voltage 2.1v (Non-OPAMP deviced operation)) #pragma config UPLLEN = OFF // USB PLL Enable (USB PLL Disabled) // DEVCFG1 #pragma config FNOSC = POSC // Oscillator Selection Bits (Primary Osc (HS,EC)) #pragma config DMTINTV = WIN_0 // DMT Count Window Interval (Window/Interval value is zero) #pragma config FSOSCEN = OFF // Secondary Oscillator Enable (Disable Secondary Oscillator) #pragma config IESO = ON // Internal/External Switch Over (Enabled) #pragma config POSCMOD = HS // Primary Oscillator Configuration (HS osc mode) #pragma config OSCIOFNC = OFF // CLKO Output Signal Active on the OSCO Pin (Disabled) #pragma config FCKSM = CSDCMD // Clock Switching and Monitor Selection (Clock Switch Disabled, FSCM Disabled) #pragma config WDTPS = PS1 // Watchdog Timer Postscaler (1:1) #pragma config WDTSPGM = STOP // Watchdog Timer Stop During Flash Programming (WDT stops during Flash programming) #pragma config WINDIS = NORMAL // Watchdog Timer Window Mode (Watchdog Timer is in non-Window mode) #pragma config FWDTEN = OFF // Watchdog Timer Enable (WDT Disabled) #pragma config FWDTWINSZ = WINSZ_25 // Watchdog Timer Window Size (Window size is 25%) #pragma config DMTCNT = DMT31 // Deadman Timer Count Selection (2^31 (2147483648)) #pragma config FDMTEN = OFF // Deadman Timer Enable (Deadman Timer is disabled) // DEVCFG0 #pragma config DEBUG = OFF // Background Debugger Enable (Debugger is disabled) #pragma config JTAGEN = OFF // JTAG Enable (JTAG Disabled) #pragma config ICESEL = ICS_PGx1 // ICE/ICD Comm Channel Select (Communicate on PGEC1/PGED1) #pragma config TRCEN = OFF // Trace Enable (Trace features in the CPU are disabled) #pragma config BOOTISA = MIPS32 // Boot ISA Selection (Boot code and Exception code is MIPS32) #pragma config FECCCON = ECC_DECC_DISABLE_ECCON_WRITABLE // Dynamic Flash ECC Configuration Bits (ECC and Dynamic ECC are disabled (ECCCON<1:0> bits are writable)) #pragma config FSLEEP = OFF // Flash Sleep Mode (Flash is powered down when the device is in Sleep mode) #pragma config DBGPER = PG_ALL // Debug Mode CPU Access Permission (Allow CPU access to all permission regions) #pragma config SMCLR = MCLR_NORM // Soft Master Clear Enable (MCLR pin generates a normal system Reset) #pragma config SOSCGAIN = G3 // Secondary Oscillator Gain Control bits (Gain is G3) #pragma config SOSCBOOST = ON // Secondary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator) #pragma config POSCGAIN = G3 // Primary Oscillator Coarse Gain Control bits (Gain Level 3 (highest)) #pragma config POSCBOOST = ON // Primary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator) #pragma config POSCFGAIN = G3 // Primary Oscillator Fine Gain Control bits (Gain is G3) #pragma config POSCAGCDLY = AGCRNG_x_25ms // AGC Gain Search Step Settling Time Control (Settling time = 25ms x AGCRNG) #pragma config POSCAGCRNG = ONE_X // AGC Lock Range bit (Range 1x) #pragma config POSCAGC = Automatic // Primary Oscillator Gain Control bit (Automatic Gain Control for Oscillator) #pragma config EJTAGBEN = NORMAL // EJTAG Boot Enable (Normal EJTAG functionality) // DEVCP #pragma config CP = OFF // Code Protect (Protection Disabled) // SEQ #pragma config TSEQ = 0xFFFF // Boot Flash True Sequence Number (Enter Hexadecimal value) #pragma config CSEQ = 0xFFFF // Boot Flash Complement Sequence Number (Enter Hexadecimal value) analog_to_digital_conversion.h //************************************************************************** // ANALOG TO DIGITAL CONVERSION HEADER FILE //************************************************************************** #include <analog_to_digital_conversion.c> void Anaolog_to_Digital_Conversion_Setup (void); void Anaolog_to_Digital_Conversion_Enable (void); void Anaolog_to_Digital_Conversion_Disable (void); uint16_t Anaolog_to_Digital_Conversion (void); analog_to_digital_conversion.c //************************************************************************** // ANALOG TO DIGITAL CONVERSION SOURCE FILE //************************************************************************** void Anaolog_to_Digital_Conversion_Setup (void){ //All this procedure is taken from the device`s datasheet (no ADC interrupts are desired) ADCANCONbits.ANEN5 = 0b0; //Analog and bias circuitry disabled (to set calibration) //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADC5CFGbits.ADCCFG = DEVADC5; //Copying the factory calibration ADC module bits to the ADC configuration register //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON1bits.ON = 0b0; //Disabling the ADC module //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADC5TIMEbits.SAMC = 0b1111111111; //Sample time is set to 1025 TAD ADC5TIMEbits.ADCDIV = 0b1111111; //254 * TQ = TAD (ADC clock division bits) //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCANCONbits.WKUPCLKCNT = 0xF; //ADC warm up time is set to 32768 ADC clock cycles (maximum warm up time, around 32 us @ 100 MHz SYSCLK) //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON3bits.ADCSEL = 0b0; //Analog-to-Digital Clock Source (TCLK) -> SYSCLK ADCCON3bits.CONCLKDIV = 0b000000; //TCLK = TQ ADCCON3bits.DIGEN5 = 0b0; //All digital bits are disabled (according to the datasheet) ADCCON3bits.VREFSEL = 0b000; //Vref is set to AVdd and AVss //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCIMCON1bits.DIFF11 = 0b0; //AN11 is using Single-ended mode ADCIMCON1bits.SIGN11 = 0b0; //AN11 is using Unsigned Data mode //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCTRGSNSbits.LVL11 = 0b0; //Analog input is sensitive to the positive edge of its trigger (this is the value after a reset) //--------------------------------------------------------------- ADCTRG3bits.TRGSRC11 = 0b00001; //AN11 is software triggered //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCANCONbits.ANEN5 = 0b1; //Analog and bias circuitry enabled //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON1bits.ON = 0b1; //Enabling the ADC module //--------------------------------------------------------------- while(!((ADCCON2bits.BGVRRDY)&&(ADCANCONbits.WKRDY5))); //Wait until device analog environment is ready ADCCON3bits.DIGEN5 = 0b1; //Enable digital circuitry for data processing //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON3bits.ADINSEL = 0b001011; //Select analog channel 11 for conversion //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON1bits.ON = 0b0; //Disabling the ADC module } void Anaolog_to_Digital_Conversion_Enable (void){ ADCCON1bits.ON = 0b1; //Enabling the ADC module } void Anaolog_to_Digital_Conversion_Disable (void){ ADCCON1bits.ON = 0b0; //Disabling the ADC module } uint16_t Anaolog_to_Digital_Conversion (void){ uint16_t ADC_value = 0; ADCCON3bits.RQCNVRT = 1; //Trigger the conversion while(!ADCDSTAT1bits.ARDY11); //Waiting until ADC result is ready to be read (@ 100 MHz SYSCLK ADC conversion should take around 2ms) ADC_value = ADCDATA11 & 0x000FFFF; //Acquiring ADC result, register is 32 bits, but conversion only gives 12 bit ADC value, hence getting rid of higher 16 bits (those are all zeros) return (ADC_value); } A: As per the files in your question the inclusion should be done using header files since this is the common practice. First of all you need to include the xc.h header in each file you use the processor specific definitions like special fuunction register and bit names. Other dependencies for your program, might be anything from the standard C library like printf from the stdio.h header or uint8_t from the stdint.h header; or any library functions that you wrote for the application and so on. Here is a trick for you: If you use MPLAB editor to write code, after typing a few letters of a function for example, you hit the Ctrl + Space then MPLAB editor will popup possible functions. When you select one of them from the popup list end hit the enter, it will add its header file automatically. Now let's get back to your case. Your main file looks ok except stdio.h inclusion. You must change #include "stdio.h" to #include <stdio.h>. Your adc.c file must have some includes as I mentioned above. First of all it must include the xc.h header. And you don't have to include the *.c file in the *.h file. I also recommend you to use header guards to prevent any possible nested inclusion, resulting in redefiniton errors. analog_to_digital_conversion.h // Header guard #ifndef ANALOG_TO_DIGITAL_CONVERSION_H #define ANALOG_TO_DIGITAL_CONVERSION_H //************************************************************************** // ANALOG TO DIGITAL CONVERSION HEADER FILE //************************************************************************** // #include <analog_to_digital_conversion.c> not needed here. void Anaolog_to_Digital_Conversion_Setup (void); void Anaolog_to_Digital_Conversion_Enable (void); void Anaolog_to_Digital_Conversion_Disable (void); uint16_t Anaolog_to_Digital_Conversion (void); #endif /* ANALOG_TO_DIGITAL_CONVERSION_H */ analog_to_digital_conversion.c //************************************************************************** // ANALOG TO DIGITAL CONVERSION SOURCE FILE //************************************************************************** // include xc header for processor register and bit names #include <xc.h> // since you use uint16_t, you must include stdint header #include <stdint.h> // Finally include your own header for any further definitions #include "analog_to_digital_conversion.h" void Anaolog_to_Digital_Conversion_Setup (void){ //All this procedure is taken from the device`s datasheet (no ADC interrupts are desired) ADCANCONbits.ANEN5 = 0b0; //Analog and bias circuitry disabled (to set calibration) //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADC5CFGbits.ADCCFG = DEVADC5; //Copying the factory calibration ADC module bits to the ADC configuration register //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON1bits.ON = 0b0; //Disabling the ADC module //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADC5TIMEbits.SAMC = 0b1111111111; //Sample time is set to 1025 TAD ADC5TIMEbits.ADCDIV = 0b1111111; //254 * TQ = TAD (ADC clock division bits) //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCANCONbits.WKUPCLKCNT = 0xF; //ADC warm up time is set to 32768 ADC clock cycles (maximum warm up time, around 32 us @ 100 MHz SYSCLK) //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON3bits.ADCSEL = 0b0; //Analog-to-Digital Clock Source (TCLK) -> SYSCLK ADCCON3bits.CONCLKDIV = 0b000000; //TCLK = TQ ADCCON3bits.DIGEN5 = 0b0; //All digital bits are disabled (according to the datasheet) ADCCON3bits.VREFSEL = 0b000; //Vref is set to AVdd and AVss //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCIMCON1bits.DIFF11 = 0b0; //AN11 is using Single-ended mode ADCIMCON1bits.SIGN11 = 0b0; //AN11 is using Unsigned Data mode //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCTRGSNSbits.LVL11 = 0b0; //Analog input is sensitive to the positive edge of its trigger (this is the value after a reset) //--------------------------------------------------------------- ADCTRG3bits.TRGSRC11 = 0b00001; //AN11 is software triggered //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCANCONbits.ANEN5 = 0b1; //Analog and bias circuitry enabled //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON1bits.ON = 0b1; //Enabling the ADC module //--------------------------------------------------------------- while(!((ADCCON2bits.BGVRRDY)&&(ADCANCONbits.WKRDY5))); //Wait until device analog environment is ready ADCCON3bits.DIGEN5 = 0b1; //Enable digital circuitry for data processing //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON3bits.ADINSEL = 0b001011; //Select analog channel 11 for conversion //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON1bits.ON = 0b0; //Disabling the ADC module } void Anaolog_to_Digital_Conversion_Enable (void){ ADCCON1bits.ON = 0b1; //Enabling the ADC module } void Anaolog_to_Digital_Conversion_Disable (void){ ADCCON1bits.ON = 0b0; //Disabling the ADC module } uint16_t Anaolog_to_Digital_Conversion (void){ uint16_t ADC_value = 0; ADCCON3bits.RQCNVRT = 1; //Trigger the conversion while(!ADCDSTAT1bits.ARDY11); //Waiting until ADC result is ready to be read (@ 100 MHz SYSCLK ADC conversion should take around 2ms) ADC_value = ADCDATA11 & 0x000FFFF; //Acquiring ADC result, register is 32 bits, but conversion only gives 12 bit ADC value, hence getting rid of higher 16 bits (those are all zeros) return (ADC_value); } You must use the same inclusion logic for each *.c & *.h file pair that you add to your project. A: Separate compilation requires visibility of external symbols. For example in analog_to_digital_conversion.c where ADCANCONbits is referenced, the compiler needs to see at least a declaration of ADCANCONbits so that it knows that the symbol exists and what its type is. The actual linkage and resolution to a definition occurs when the linker pulse the object code from each separately compiled translation unit together. You resolve undeclared identifier errors by providing the declaration. In this case that declaration exists inside a header file that you must #include in every translation unit that references it. I am not familiar with PIC32 development, but would imagine that header is xc.h Yoiu have a number of other issues, for example analog_to_digital_conversion.h referenced uint16_t but does not include <stdint.h> where that type is defined. You may get away with it due to inclusion in other modules, but you should not rely on it. Also all header files require guards to avoid multiple declarations when included more than once in the same translation unit - which can easily happen when you have nested includes for example.
Source and Header file syntax in MPLAB X IDE v5.50
I am developing the code for my PIC32MK1024MCM project. I have already tested the code well and now I am only putting all the code modules into the final project (the code is not complete in this example yet, but the functionality is not the axis of interest here). For the first time in my life, I wanted to make it a little bit more professional and use separate source and header files for all the different module function declaration. However, I am clearly facing some kind of syntax problem, because I am getting errors in almost every line of the source file (I guess I have to include something in that source file, but I am not sure) Like I said, it is my very first time facing header and source files, so could you please help me, or at least hint me, what is it that I am missing so obviously? I want to thank you in advance. main: #include <xc.h> #include <configuration_bits.c> #include <toolchain_specifics.h> #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include "stdio.h" #include <sys/attribs.h> #include <analog_to_digital_conversion.h> void main(void) { while (1){ } return (EXIT_FAILURE); } configurations_bits // DEVCFG3 #pragma config USERID = 0xFFFF // Enter Hexadecimal value (Enter Hexadecimal value) #pragma config PWMLOCK = OFF // PWM IOxCON lock (PWM IOxCON register writes accesses are not locked or protected) #pragma config FUSBIDIO2 = OFF // USB2 USBID Selection (USBID pin is controlled by the port function) #pragma config FVBUSIO2 = OFF // USB2 VBUSON Selection bit (VBUSON pin is controlled by the port function) #pragma config PGL1WAY = OFF // Permission Group Lock One Way Configuration bit (Allow multiple reconfigurations) #pragma config PMDL1WAY = OFF // Peripheral Module Disable Configuration (Allow multiple reconfigurations) #pragma config IOL1WAY = OFF // Peripheral Pin Select Configuration (Allow multiple reconfigurations) #pragma config FUSBIDIO1 = OFF // USB1 USBID Selection (USBID pin is controlled by the port function) #pragma config FVBUSIO1 = OFF // USB2 VBUSON Selection bit (VBUSON pin is controlled by the port function) // DEVCFG2 #pragma config FPLLIDIV = DIV_1 // System PLL Input Divider (1x Divider) #pragma config FPLLRNG = RANGE_BYPASS // System PLL Input Range (Bypass) #pragma config FPLLICLK = PLL_POSC // System PLL Input Clock Selection (POSC is input to the System PLL) #pragma config FPLLMULT = MUL_4 // System PLL Multiplier (PLL Multiply by 4) #pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (2x Divider) #pragma config BORSEL = HIGH // Brown-out trip voltage (BOR trip voltage 2.1v (Non-OPAMP deviced operation)) #pragma config UPLLEN = OFF // USB PLL Enable (USB PLL Disabled) // DEVCFG1 #pragma config FNOSC = POSC // Oscillator Selection Bits (Primary Osc (HS,EC)) #pragma config DMTINTV = WIN_0 // DMT Count Window Interval (Window/Interval value is zero) #pragma config FSOSCEN = OFF // Secondary Oscillator Enable (Disable Secondary Oscillator) #pragma config IESO = ON // Internal/External Switch Over (Enabled) #pragma config POSCMOD = HS // Primary Oscillator Configuration (HS osc mode) #pragma config OSCIOFNC = OFF // CLKO Output Signal Active on the OSCO Pin (Disabled) #pragma config FCKSM = CSDCMD // Clock Switching and Monitor Selection (Clock Switch Disabled, FSCM Disabled) #pragma config WDTPS = PS1 // Watchdog Timer Postscaler (1:1) #pragma config WDTSPGM = STOP // Watchdog Timer Stop During Flash Programming (WDT stops during Flash programming) #pragma config WINDIS = NORMAL // Watchdog Timer Window Mode (Watchdog Timer is in non-Window mode) #pragma config FWDTEN = OFF // Watchdog Timer Enable (WDT Disabled) #pragma config FWDTWINSZ = WINSZ_25 // Watchdog Timer Window Size (Window size is 25%) #pragma config DMTCNT = DMT31 // Deadman Timer Count Selection (2^31 (2147483648)) #pragma config FDMTEN = OFF // Deadman Timer Enable (Deadman Timer is disabled) // DEVCFG0 #pragma config DEBUG = OFF // Background Debugger Enable (Debugger is disabled) #pragma config JTAGEN = OFF // JTAG Enable (JTAG Disabled) #pragma config ICESEL = ICS_PGx1 // ICE/ICD Comm Channel Select (Communicate on PGEC1/PGED1) #pragma config TRCEN = OFF // Trace Enable (Trace features in the CPU are disabled) #pragma config BOOTISA = MIPS32 // Boot ISA Selection (Boot code and Exception code is MIPS32) #pragma config FECCCON = ECC_DECC_DISABLE_ECCON_WRITABLE // Dynamic Flash ECC Configuration Bits (ECC and Dynamic ECC are disabled (ECCCON<1:0> bits are writable)) #pragma config FSLEEP = OFF // Flash Sleep Mode (Flash is powered down when the device is in Sleep mode) #pragma config DBGPER = PG_ALL // Debug Mode CPU Access Permission (Allow CPU access to all permission regions) #pragma config SMCLR = MCLR_NORM // Soft Master Clear Enable (MCLR pin generates a normal system Reset) #pragma config SOSCGAIN = G3 // Secondary Oscillator Gain Control bits (Gain is G3) #pragma config SOSCBOOST = ON // Secondary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator) #pragma config POSCGAIN = G3 // Primary Oscillator Coarse Gain Control bits (Gain Level 3 (highest)) #pragma config POSCBOOST = ON // Primary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator) #pragma config POSCFGAIN = G3 // Primary Oscillator Fine Gain Control bits (Gain is G3) #pragma config POSCAGCDLY = AGCRNG_x_25ms // AGC Gain Search Step Settling Time Control (Settling time = 25ms x AGCRNG) #pragma config POSCAGCRNG = ONE_X // AGC Lock Range bit (Range 1x) #pragma config POSCAGC = Automatic // Primary Oscillator Gain Control bit (Automatic Gain Control for Oscillator) #pragma config EJTAGBEN = NORMAL // EJTAG Boot Enable (Normal EJTAG functionality) // DEVCP #pragma config CP = OFF // Code Protect (Protection Disabled) // SEQ #pragma config TSEQ = 0xFFFF // Boot Flash True Sequence Number (Enter Hexadecimal value) #pragma config CSEQ = 0xFFFF // Boot Flash Complement Sequence Number (Enter Hexadecimal value) analog_to_digital_conversion.h //************************************************************************** // ANALOG TO DIGITAL CONVERSION HEADER FILE //************************************************************************** #include <analog_to_digital_conversion.c> void Anaolog_to_Digital_Conversion_Setup (void); void Anaolog_to_Digital_Conversion_Enable (void); void Anaolog_to_Digital_Conversion_Disable (void); uint16_t Anaolog_to_Digital_Conversion (void); analog_to_digital_conversion.c //************************************************************************** // ANALOG TO DIGITAL CONVERSION SOURCE FILE //************************************************************************** void Anaolog_to_Digital_Conversion_Setup (void){ //All this procedure is taken from the device`s datasheet (no ADC interrupts are desired) ADCANCONbits.ANEN5 = 0b0; //Analog and bias circuitry disabled (to set calibration) //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADC5CFGbits.ADCCFG = DEVADC5; //Copying the factory calibration ADC module bits to the ADC configuration register //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON1bits.ON = 0b0; //Disabling the ADC module //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADC5TIMEbits.SAMC = 0b1111111111; //Sample time is set to 1025 TAD ADC5TIMEbits.ADCDIV = 0b1111111; //254 * TQ = TAD (ADC clock division bits) //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCANCONbits.WKUPCLKCNT = 0xF; //ADC warm up time is set to 32768 ADC clock cycles (maximum warm up time, around 32 us @ 100 MHz SYSCLK) //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON3bits.ADCSEL = 0b0; //Analog-to-Digital Clock Source (TCLK) -> SYSCLK ADCCON3bits.CONCLKDIV = 0b000000; //TCLK = TQ ADCCON3bits.DIGEN5 = 0b0; //All digital bits are disabled (according to the datasheet) ADCCON3bits.VREFSEL = 0b000; //Vref is set to AVdd and AVss //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCIMCON1bits.DIFF11 = 0b0; //AN11 is using Single-ended mode ADCIMCON1bits.SIGN11 = 0b0; //AN11 is using Unsigned Data mode //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCTRGSNSbits.LVL11 = 0b0; //Analog input is sensitive to the positive edge of its trigger (this is the value after a reset) //--------------------------------------------------------------- ADCTRG3bits.TRGSRC11 = 0b00001; //AN11 is software triggered //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCANCONbits.ANEN5 = 0b1; //Analog and bias circuitry enabled //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON1bits.ON = 0b1; //Enabling the ADC module //--------------------------------------------------------------- while(!((ADCCON2bits.BGVRRDY)&&(ADCANCONbits.WKRDY5))); //Wait until device analog environment is ready ADCCON3bits.DIGEN5 = 0b1; //Enable digital circuitry for data processing //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON3bits.ADINSEL = 0b001011; //Select analog channel 11 for conversion //--------------------------------------------------------------------------------------------------------------------------------------------------------------- ADCCON1bits.ON = 0b0; //Disabling the ADC module } void Anaolog_to_Digital_Conversion_Enable (void){ ADCCON1bits.ON = 0b1; //Enabling the ADC module } void Anaolog_to_Digital_Conversion_Disable (void){ ADCCON1bits.ON = 0b0; //Disabling the ADC module } uint16_t Anaolog_to_Digital_Conversion (void){ uint16_t ADC_value = 0; ADCCON3bits.RQCNVRT = 1; //Trigger the conversion while(!ADCDSTAT1bits.ARDY11); //Waiting until ADC result is ready to be read (@ 100 MHz SYSCLK ADC conversion should take around 2ms) ADC_value = ADCDATA11 & 0x000FFFF; //Acquiring ADC result, register is 32 bits, but conversion only gives 12 bit ADC value, hence getting rid of higher 16 bits (those are all zeros) return (ADC_value); }
[ "As per the files in your question the inclusion should be done using header files since this is the common practice.\nFirst of all you need to include the xc.h header in each file you use the processor specific definitions like special fuunction register and bit names.\nOther dependencies for your program, might be anything from the standard C library like printf from the stdio.h header or uint8_t from the stdint.h header; or any library functions that you wrote for the application and so on.\nHere is a trick for you: If you use MPLAB editor to write code, after typing a few letters of a function for example, you hit the Ctrl + Space then MPLAB editor will popup possible functions. When you select one of them from the popup list end hit the enter, it will add its header file automatically.\nNow let's get back to your case. Your main file looks ok except stdio.h inclusion. You must change #include \"stdio.h\" to #include <stdio.h>.\nYour adc.c file must have some includes as I mentioned above. First of all it must include the xc.h header. And you don't have to include the *.c file in the *.h file. I also recommend you to use header guards to prevent any possible nested inclusion, resulting in redefiniton errors.\nanalog_to_digital_conversion.h\n// Header guard\n#ifndef ANALOG_TO_DIGITAL_CONVERSION_H\n#define ANALOG_TO_DIGITAL_CONVERSION_H\n\n//**************************************************************************\n// ANALOG TO DIGITAL CONVERSION HEADER FILE\n//**************************************************************************\n\n// #include <analog_to_digital_conversion.c> not needed here.\n\nvoid Anaolog_to_Digital_Conversion_Setup (void);\n\nvoid Anaolog_to_Digital_Conversion_Enable (void);\n\nvoid Anaolog_to_Digital_Conversion_Disable (void);\n\nuint16_t Anaolog_to_Digital_Conversion (void);\n\n#endif /* ANALOG_TO_DIGITAL_CONVERSION_H */\n\nanalog_to_digital_conversion.c\n//**************************************************************************\n// ANALOG TO DIGITAL CONVERSION SOURCE FILE\n//**************************************************************************\n\n// include xc header for processor register and bit names\n#include <xc.h>\n// since you use uint16_t, you must include stdint header\n#include <stdint.h>\n// Finally include your own header for any further definitions\n#include \"analog_to_digital_conversion.h\"\n\nvoid Anaolog_to_Digital_Conversion_Setup (void){\n \n //All this procedure is taken from the device`s datasheet (no ADC interrupts are desired)\n \n ADCANCONbits.ANEN5 = 0b0; //Analog and bias circuitry disabled (to set calibration)\n //---------------------------------------------------------------------------------------------------------------------------------------------------------------\n ADC5CFGbits.ADCCFG = DEVADC5; //Copying the factory calibration ADC module bits to the ADC configuration register\n //---------------------------------------------------------------------------------------------------------------------------------------------------------------\n ADCCON1bits.ON = 0b0; //Disabling the ADC module\n //---------------------------------------------------------------------------------------------------------------------------------------------------------------\n ADC5TIMEbits.SAMC = 0b1111111111; //Sample time is set to 1025 TAD\n ADC5TIMEbits.ADCDIV = 0b1111111; //254 * TQ = TAD (ADC clock division bits)\n //---------------------------------------------------------------------------------------------------------------------------------------------------------------\n ADCANCONbits.WKUPCLKCNT = 0xF; //ADC warm up time is set to 32768 ADC clock cycles (maximum warm up time, around 32 us @ 100 MHz SYSCLK)\n //---------------------------------------------------------------------------------------------------------------------------------------------------------------\n ADCCON3bits.ADCSEL = 0b0; //Analog-to-Digital Clock Source (TCLK) -> SYSCLK\n ADCCON3bits.CONCLKDIV = 0b000000; //TCLK = TQ\n ADCCON3bits.DIGEN5 = 0b0; //All digital bits are disabled (according to the datasheet)\n ADCCON3bits.VREFSEL = 0b000; //Vref is set to AVdd and AVss\n //---------------------------------------------------------------------------------------------------------------------------------------------------------------\n ADCIMCON1bits.DIFF11 = 0b0; //AN11 is using Single-ended mode\n ADCIMCON1bits.SIGN11 = 0b0; //AN11 is using Unsigned Data mode\n //---------------------------------------------------------------------------------------------------------------------------------------------------------------\n ADCTRGSNSbits.LVL11 = 0b0; //Analog input is sensitive to the positive edge of its trigger (this is the value after a reset)\n //---------------------------------------------------------------\n ADCTRG3bits.TRGSRC11 = 0b00001; //AN11 is software triggered\n //---------------------------------------------------------------------------------------------------------------------------------------------------------------\n ADCANCONbits.ANEN5 = 0b1; //Analog and bias circuitry enabled\n //---------------------------------------------------------------------------------------------------------------------------------------------------------------\n ADCCON1bits.ON = 0b1; //Enabling the ADC module\n //---------------------------------------------------------------\n while(!((ADCCON2bits.BGVRRDY)&&(ADCANCONbits.WKRDY5))); //Wait until device analog environment is ready\n ADCCON3bits.DIGEN5 = 0b1; //Enable digital circuitry for data processing\n //---------------------------------------------------------------------------------------------------------------------------------------------------------------\n ADCCON3bits.ADINSEL = 0b001011; //Select analog channel 11 for conversion\n //---------------------------------------------------------------------------------------------------------------------------------------------------------------\n ADCCON1bits.ON = 0b0; //Disabling the ADC module\n}\n\nvoid Anaolog_to_Digital_Conversion_Enable (void){\n \n ADCCON1bits.ON = 0b1; //Enabling the ADC module\n}\n\nvoid Anaolog_to_Digital_Conversion_Disable (void){\n \n ADCCON1bits.ON = 0b0; //Disabling the ADC module\n}\n\nuint16_t Anaolog_to_Digital_Conversion (void){\n \n uint16_t ADC_value = 0;\n \n ADCCON3bits.RQCNVRT = 1; //Trigger the conversion\n \n while(!ADCDSTAT1bits.ARDY11); //Waiting until ADC result is ready to be read (@ 100 MHz SYSCLK ADC conversion should take around 2ms)\n \n ADC_value = ADCDATA11 & 0x000FFFF; //Acquiring ADC result, register is 32 bits, but conversion only gives 12 bit ADC value, hence getting rid of higher 16 bits (those are all zeros)\n \n return (ADC_value);\n}\n\nYou must use the same inclusion logic for each *.c & *.h file pair that you add to your project.\n", "Separate compilation requires visibility of external symbols. For example in analog_to_digital_conversion.c where ADCANCONbits is referenced, the compiler needs to see at least a declaration of ADCANCONbits so that it knows that the symbol exists and what its type is. The actual linkage and resolution to a definition occurs when the linker pulse the object code from each separately compiled translation unit together.\nYou resolve undeclared identifier errors by providing the declaration. In this case that declaration exists inside a header file that you must #include in every translation unit that references it. I am not familiar with PIC32 development, but would imagine that header is xc.h\nYoiu have a number of other issues, for example analog_to_digital_conversion.h referenced uint16_t but does not include <stdint.h> where that type is defined. You may get away with it due to inclusion in other modules, but you should not rely on it.\nAlso all header files require guards to avoid multiple declarations when included more than once in the same translation unit - which can easily happen when you have nested includes for example.\n" ]
[ 0, 0 ]
[]
[]
[ "c", "embedded", "header_files", "mplab", "syntax" ]
stackoverflow_0074660047_c_embedded_header_files_mplab_syntax.txt
Q: How to send list of integers into PostgreSQL function parameter? I have a function in Repository which calls a function like this: @Query(value="select * from my_postgres_function(?1)",nativeQuery = true) List<Map<String, String>> getScrutinyData(List<Integer> numbers;); In .sql file, I have that function defined as CREATE OR REPLACE FUNCTION public.my_postgres_function(numbers Integer[]); The query in function is something like select * from table t where t.id in numbers; There seems to be an error and it doesn't work. Has anyone faced this before? I have tried to send it as String and convert the value and put it, but it did work. A: This is right: CREATE OR REPLACE FUNCTION public.my_postgres_function(numbers Integer[]); inside the function you can use numbers like as this: select * from table t where t.id in (select unnest(numbers)) In Java back-end side you can send your parameter using integer array.
How to send list of integers into PostgreSQL function parameter?
I have a function in Repository which calls a function like this: @Query(value="select * from my_postgres_function(?1)",nativeQuery = true) List<Map<String, String>> getScrutinyData(List<Integer> numbers;); In .sql file, I have that function defined as CREATE OR REPLACE FUNCTION public.my_postgres_function(numbers Integer[]); The query in function is something like select * from table t where t.id in numbers; There seems to be an error and it doesn't work. Has anyone faced this before? I have tried to send it as String and convert the value and put it, but it did work.
[ "This is right:\nCREATE OR REPLACE FUNCTION public.my_postgres_function(numbers Integer[]);\n\ninside the function you can use numbers like as this:\nselect * from table t where t.id in (select unnest(numbers))\n\nIn Java back-end side you can send your parameter using integer array.\n" ]
[ 0 ]
[]
[]
[ "java", "jpa", "postgresql" ]
stackoverflow_0074612359_java_jpa_postgresql.txt
Q: Are the E/R diagram and conceptual one good HERE are the diagrams I have many to many between all 3 and so I made an associative table CONTRACT with composed PK. I have many to many between all 3 and so I made an associative table CONTRACT with composed PK. Do i miss something? I am new to DB A: Write out the relationships in plain English. Maybe: An employee can have many jobs but each job is for a specific employee; each job is at a hospital and hospitals will have many jobs; or An employee will only one job but each job may have many employees; each job can be for one-or-more hospitals and hospitals will have many jobs; or An employee can have many jobs and there may be many employees doing the same job; each job can be for many hospitals and each hospital will have many jobs. Once you have written your sentences describing the relationships that will tell you what your assumptions are and what the diagram should represent. As for your diagrams: Why have you introduced a contract? Would it not be better to merge contact and job and put the job name into the contact table (and call that one table job)? Then try putting data into your tables and see if it accurately models the English sentence you used to describe the relationship.
Are the E/R diagram and conceptual one good
HERE are the diagrams I have many to many between all 3 and so I made an associative table CONTRACT with composed PK. I have many to many between all 3 and so I made an associative table CONTRACT with composed PK. Do i miss something? I am new to DB
[ "Write out the relationships in plain English.\nMaybe:\n\nAn employee can have many jobs but each job is for a specific employee; each job is at a hospital and hospitals will have many jobs; or\nAn employee will only one job but each job may have many employees; each job can be for one-or-more hospitals and hospitals will have many jobs; or\nAn employee can have many jobs and there may be many employees doing the same job; each job can be for many hospitals and each hospital will have many jobs.\n\nOnce you have written your sentences describing the relationships that will tell you what your assumptions are and what the diagram should represent.\nAs for your diagrams:\n\nWhy have you introduced a contract?\nWould it not be better to merge contact and job and put the job name into the contact table (and call that one table job)?\n\nThen try putting data into your tables and see if it accurately models the English sentence you used to describe the relationship.\n" ]
[ 0 ]
[]
[]
[ "entity_relationship" ]
stackoverflow_0074666523_entity_relationship.txt
Q: Javascript checkbox checked attribute does not render checked I have a form on my page that is filled with checkboxes the user can select. The values are paginated on the server, and because of that whenever the user clicks next or previous, new values are loaded in the form and the previous removed. I have a variable in my script that holds the selected values. let selectedReaders = new Set(); What I am trying to do, is check if a loaded value has been already selected; and if it has, make it checked. In the code where I add the HTML for each loaded value, I check if it is and set the checked attribute of the checkbox input to false/true. But when I open the page, all checkboxes are always unchecked. Here is the code: for(let reader of serverReaders){ readers.innerHTML += ` <div class="form-check form-check-inline"> <input class="form-check-input me-1" type="checkbox" onclick="addReader(this)" value="${reader.userID}" id="reader-${reader.userID}" > <label class="form-check-label" for="reader-${reader.userID}">${reader.username}</label> </div>` document.getElementById(`reader-${reader.userID}`).checked = [...selectedReaders].some( id => id === reader.userID) console.log(document.getElementById(`reader-${reader.userID}`).checked) } For each reader, I first add the label and input a checkbox for them, and then I check the selectedReaders variable if it has an id of the reader(which means it has been selected previously). If it has been selected previously, I check the checked to true otherwise, it is set to false. The console.log outputs true for the value if it has been selected previously. This means that the checked attribute is set to true properly, but on the page, checked=true does not render the input checkbox checked. What am I doing wrong? A: It looks like you are adding the HTML for the checkboxes and setting their checked attribute after they have been added to the page. In this case, the checked attribute is not applied because the elements don't exist yet when you are setting it. One way to fix this would be to set the checked attribute before adding the HTML for each checkbox to the page. You can do this by storing the HTML for each checkbox in a variable and then setting the checked attribute on that variable before appending it to the page. Here's an example of how you could do this: let checkboxHTML = ""; for (let reader of serverReaders) { // Set the checked attribute on the HTML for the checkbox let checked = [...selectedReaders].some(id => id === reader.userID); checkboxHTML += ` <div class="form-check form-check-inline"> <input class="form-check-input me-1" type="checkbox" onclick="addReader(this)" value="${reader.userID}" id="reader-${reader.userID}" ${checked ? "checked" : ""}> <label class="form-check-label" for="reader-${reader.userID}">${reader.username}</label> </div>` } // Add the checkboxes to the page readers.innerHTML += checkboxHTML;
Javascript checkbox checked attribute does not render checked
I have a form on my page that is filled with checkboxes the user can select. The values are paginated on the server, and because of that whenever the user clicks next or previous, new values are loaded in the form and the previous removed. I have a variable in my script that holds the selected values. let selectedReaders = new Set(); What I am trying to do, is check if a loaded value has been already selected; and if it has, make it checked. In the code where I add the HTML for each loaded value, I check if it is and set the checked attribute of the checkbox input to false/true. But when I open the page, all checkboxes are always unchecked. Here is the code: for(let reader of serverReaders){ readers.innerHTML += ` <div class="form-check form-check-inline"> <input class="form-check-input me-1" type="checkbox" onclick="addReader(this)" value="${reader.userID}" id="reader-${reader.userID}" > <label class="form-check-label" for="reader-${reader.userID}">${reader.username}</label> </div>` document.getElementById(`reader-${reader.userID}`).checked = [...selectedReaders].some( id => id === reader.userID) console.log(document.getElementById(`reader-${reader.userID}`).checked) } For each reader, I first add the label and input a checkbox for them, and then I check the selectedReaders variable if it has an id of the reader(which means it has been selected previously). If it has been selected previously, I check the checked to true otherwise, it is set to false. The console.log outputs true for the value if it has been selected previously. This means that the checked attribute is set to true properly, but on the page, checked=true does not render the input checkbox checked. What am I doing wrong?
[ "It looks like you are adding the HTML for the checkboxes and setting their checked attribute after they have been added to the page. In this case, the checked attribute is not applied because the elements don't exist yet when you are setting it.\nOne way to fix this would be to set the checked attribute before adding the HTML for each checkbox to the page. You can do this by storing the HTML for each checkbox in a variable and then setting the checked attribute on that variable before appending it to the page.\nHere's an example of how you could do this:\nlet checkboxHTML = \"\";\n\nfor (let reader of serverReaders) {\n // Set the checked attribute on the HTML for the checkbox\n let checked = [...selectedReaders].some(id => id === reader.userID);\n checkboxHTML += `\n <div class=\"form-check form-check-inline\">\n <input class=\"form-check-input me-1\" type=\"checkbox\" onclick=\"addReader(this)\" value=\"${reader.userID}\" id=\"reader-${reader.userID}\" ${checked ? \"checked\" : \"\"}>\n <label class=\"form-check-label\" for=\"reader-${reader.userID}\">${reader.username}</label>\n </div>`\n}\n\n// Add the checkboxes to the page\nreaders.innerHTML += checkboxHTML;\n\n" ]
[ 0 ]
[]
[]
[ "html", "javascript" ]
stackoverflow_0074667444_html_javascript.txt
Q: Define the Time Complexity for the algorithm (Java) I have the following snippet of code: public static int digPow(int n, int p) { int powCounter = p; int sum = 0; char[] digits = (""+n).toCharArray(); for (char digit : digits) { sum += Math.pow(Character.getNumericValue(digit), powCounter); powCounter++; } if (sum % n == 0) return sum / n; else return -1; } I don't understand how to define the time complexity, because, even though I have a loop, it seems to me that it's not just O(n). Or it is? A: Its O(n), where n is the length of the character array digits. Since the loop will iterate that no of times the next line is a if else clause which will execute only once.
Define the Time Complexity for the algorithm (Java)
I have the following snippet of code: public static int digPow(int n, int p) { int powCounter = p; int sum = 0; char[] digits = (""+n).toCharArray(); for (char digit : digits) { sum += Math.pow(Character.getNumericValue(digit), powCounter); powCounter++; } if (sum % n == 0) return sum / n; else return -1; } I don't understand how to define the time complexity, because, even though I have a loop, it seems to me that it's not just O(n). Or it is?
[ "Its O(n), where n is the length of the character array digits.\nSince the loop will iterate that no of times the next line is a if else clause which will execute only once.\n" ]
[ 1 ]
[]
[]
[ "algorithm", "big_o", "java", "time_complexity" ]
stackoverflow_0074667613_algorithm_big_o_java_time_complexity.txt
Q: Grant users access to a database object after purchase The javascript project I'm working on provides a way for users to purchase a "virtual" item, which allows them to access to the information about it. For example, purchasing a recipe. The way I've structured my database is the following; Database: Reference: Item: Item Information Users: Purchases: Item When the customer purchases something, a function runs that copies the order data into the "Users" string, as a purchase. From here, I need a way for the user to be granted access to the "Item" object in the reference section to see the "Item Information", to see the information about what was just purchased. Is there something similar to a list of authorised users in the security rules that can be dynamically changed to achieve this? A: There is nothing built into Firebase Authentication of Firebase Realtime Database (or its security rules) for this, but you can likely build it on top. If you want to grant the user access to each item that they purchased, you'd have rules that look something like this: { "rules": { "Items": { "$itemId": { ".read": "root.child('Users').child(auth.uid).child('Purchases').child($itemId).exists()" } } } } So the .read rule here checks if the item the user is trying to read also exists under the list or Purchases for that user in the database.
Grant users access to a database object after purchase
The javascript project I'm working on provides a way for users to purchase a "virtual" item, which allows them to access to the information about it. For example, purchasing a recipe. The way I've structured my database is the following; Database: Reference: Item: Item Information Users: Purchases: Item When the customer purchases something, a function runs that copies the order data into the "Users" string, as a purchase. From here, I need a way for the user to be granted access to the "Item" object in the reference section to see the "Item Information", to see the information about what was just purchased. Is there something similar to a list of authorised users in the security rules that can be dynamically changed to achieve this?
[ "There is nothing built into Firebase Authentication of Firebase Realtime Database (or its security rules) for this, but you can likely build it on top.\nIf you want to grant the user access to each item that they purchased, you'd have rules that look something like this:\n{\n \"rules\": {\n \"Items\": {\n \"$itemId\": {\n \".read\": \"root.child('Users').child(auth.uid).child('Purchases').child($itemId).exists()\"\n }\n }\n }\n}\n\nSo the .read rule here checks if the item the user is trying to read also exists under the list or Purchases for that user in the database.\n" ]
[ 1 ]
[]
[]
[ "firebase", "firebase_realtime_database", "javascript" ]
stackoverflow_0074667119_firebase_firebase_realtime_database_javascript.txt
Q: Finding element by the second class in Selenium Using inspect element, I have one element with two states: <span class="c-form-control-feedback c-form-control-feedback-error" title="" data-original-title="that username is already taken"></span> <span class="c-form-control-feedback c-form-control-feedback-error" title=""></span> Sometimes the element has the first form, sometimes the last form. I need to find the element when it's in the first state, so I need a way to driver.find_element by the data-original-title class. Is that possible? A: You can retrieve them by checking whether contains the data-original-title attribute. Selenium: driver.find_elements(by=By.XPATH, value="//*[contains(@data-original-title, '')]") Beautifulsoup: soup.find_all("span", attrs={"data-original-title": True}) Output: [<span class="c-form-control-feedback c-form-control-feedback-error" data-original-title="that username is already taken" title=""></span>]
Finding element by the second class in Selenium
Using inspect element, I have one element with two states: <span class="c-form-control-feedback c-form-control-feedback-error" title="" data-original-title="that username is already taken"></span> <span class="c-form-control-feedback c-form-control-feedback-error" title=""></span> Sometimes the element has the first form, sometimes the last form. I need to find the element when it's in the first state, so I need a way to driver.find_element by the data-original-title class. Is that possible?
[ "You can retrieve them by checking whether contains the data-original-title attribute.\nSelenium:\ndriver.find_elements(by=By.XPATH, value=\"//*[contains(@data-original-title, '')]\")\n\nBeautifulsoup:\nsoup.find_all(\"span\", attrs={\"data-original-title\": True})\n\n\nOutput:\n[<span class=\"c-form-control-feedback c-form-control-feedback-error\" data-original-title=\"that username is already taken\" title=\"\"></span>]\n\n" ]
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074667563_python_selenium.txt
Q: Refactor useHistory state I'm using useHistory to route my website from page A const history = useHistory(); history.push('/this/is/page-b', { object: selectedObject }); and in page B, I have: const history = useHistory(); const objectData = history.location?.state?.object as Object; First question: Is there anything wrong with this code? Trying to pass data using history. Second question: Any suggestion for another solution to pass data instead of via useHistory hook? Just need some keywords. Thank guys. A: In react router 6, use useNavigate const navigate = useNavigate(); navigate('/this/is/page-b', { object: selectedObject }); use useLocation to catch data const {object} = useLocation();
Refactor useHistory state
I'm using useHistory to route my website from page A const history = useHistory(); history.push('/this/is/page-b', { object: selectedObject }); and in page B, I have: const history = useHistory(); const objectData = history.location?.state?.object as Object; First question: Is there anything wrong with this code? Trying to pass data using history. Second question: Any suggestion for another solution to pass data instead of via useHistory hook? Just need some keywords. Thank guys.
[ "In react router 6, use useNavigate\nconst navigate = useNavigate();\nnavigate('/this/is/page-b', { object: selectedObject });\n\nuse useLocation to catch data\nconst {object} = useLocation();\n\n" ]
[ 1 ]
[]
[]
[ "react_hooks", "react_router_v5", "reactjs" ]
stackoverflow_0074667596_react_hooks_react_router_v5_reactjs.txt
Q: Access NSCache across view controllers in a tab view controller I want to access NSCache from more than one place in my APP, as I'm using it to cache images from an API endpoint. For example table view 4 and viewcontroller 6 in the diagram below use the same images, so I do not want to download them twice. Candidate solutions: Singleton class Cache { private static var sharedCache: NSCache<AnyObject, AnyObject>? static public func getCache () -> NSCache<AnyObject, AnyObject> { if sharedCache == nil { self.sharedCache = NSCache() } return sharedCache! } } Seems to work fine, but "Singletons are bad" so... Store the cache in TabViewController This will tightly couple the views to the view controller so... Store in the AppDelegate somehow. But isn't this the same as 1? So... Use dependency injection. But we're in a tab view controller, so isn't this the same as 2? I'm not sure the right strategy here, so am asking whether there is another method that can be used here. What I've done Created an App with an example using a NSCache, and explored a singleton solution. Ive tried to use dependency injection but think that it doesn't make sense. I've looked at Stack overflow and documentation, but for this specific circumstance I have found no potential solutoins. What I've given A minimal example, with a diagram and tested solution that I'm dissatisfied with. What is not helpful are answers that say NSCache is incorrect, or to use libraries. I'm trying to use NSCache for my own learning, this is not homework and I want to solve this specific instance of this problem in this App structure. What the question is How to avoid using a singleton in this instance, view controllers in a tab view controller. A: First up. Singletons are not inherantly bad. They can make your code hard to test and they do act as dependancy magnets. Singletons are good for classes that are tools e.g NSFileManager aka FileManger, i.e something that does not carry state or data around. A good alternative is dependancy injection but with view controllers and storyboards it can be hard and feel very boilerplate. You end up passing everything down the line in prepareForSegue. One possible method is to declare a protocol that describes a cache like interface. protocol CacheProtocol: class { func doCacheThing() } class Cache: CacheProtocol { func doCacheThing() { // } } Then declare a protocol that all things that wish to use this cache can use. protocol CacheConsumer: class { var cache: CacheProtocol? { get set } func injectCache(to object: AnyObject) } extension CacheConsumer { func injectCache(to object: AnyObject) { if let consumer = object as? CacheConsumer { consumer.cache = cache } } } Finally create a concrete instance of this cache at the top level. /// Top most controller class RootLevelViewController: UIViewController, CacheConsumer { var cache: CacheProtocol? = Cache() override func prepare(for segue: UIStoryboardSegue, sender: Any?) { injectCache(to: segue.destination) } } You could pass the cache down the line in prepareForSegue. Or you can use subtle sub-classing to create conformance. class MyTabBarController: UITabBarController, CacheConsumer { var cache: CacheProtocol? } Or you can use delegate methods to get the cache object broadcast downhill. extension RootLevelViewController: UITabBarControllerDelegate { func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { injectCache(to: viewController) } } You now have a system where any CacheConsumer can use the cache and pass it downhill to any other object. A: If you use the coordinator pattern you can save the cache in the coordinator for your navigation flow and access it from there/init with the cache. It also works nicely since when the navigation flow is removed the cache is also removed. final class SomeCoordinator: NSObject, Coordinator { var rootViewController: UINavigationController var myCache = NSCache<AnyObject, AnyObject>() override init() { self.rootViewController = UINavigationController() super.init() } func start() { let vc = VC1(cache: myCache) vc.coordinator = self rootViewController.setViewControllers([vc], animated: false) parentCoordinator?.rootViewController.present(rootViewController, animated: true) } func goToVC2() { let vc = VC2(cache: myCache) vc.coordinator = self rootViewController.pushViewController(vc, animated: true) } func goToVC3() { let vc = VC3(cache: myCache) vc.coordinator = self rootViewController.present(vc, animated: true) } func goToVC4() { let vc = VC4(cache: myCache) vc.coordinator = self rootViewController.present(vc, animated: true) } deinit { print("βœ… Deinit SomeCoordinator") } }
Access NSCache across view controllers in a tab view controller
I want to access NSCache from more than one place in my APP, as I'm using it to cache images from an API endpoint. For example table view 4 and viewcontroller 6 in the diagram below use the same images, so I do not want to download them twice. Candidate solutions: Singleton class Cache { private static var sharedCache: NSCache<AnyObject, AnyObject>? static public func getCache () -> NSCache<AnyObject, AnyObject> { if sharedCache == nil { self.sharedCache = NSCache() } return sharedCache! } } Seems to work fine, but "Singletons are bad" so... Store the cache in TabViewController This will tightly couple the views to the view controller so... Store in the AppDelegate somehow. But isn't this the same as 1? So... Use dependency injection. But we're in a tab view controller, so isn't this the same as 2? I'm not sure the right strategy here, so am asking whether there is another method that can be used here. What I've done Created an App with an example using a NSCache, and explored a singleton solution. Ive tried to use dependency injection but think that it doesn't make sense. I've looked at Stack overflow and documentation, but for this specific circumstance I have found no potential solutoins. What I've given A minimal example, with a diagram and tested solution that I'm dissatisfied with. What is not helpful are answers that say NSCache is incorrect, or to use libraries. I'm trying to use NSCache for my own learning, this is not homework and I want to solve this specific instance of this problem in this App structure. What the question is How to avoid using a singleton in this instance, view controllers in a tab view controller.
[ "First up. Singletons are not inherantly bad. They can make your code hard to test and they do act as dependancy magnets. \nSingletons are good for classes that are tools e.g NSFileManager aka FileManger, i.e something that does not carry state or data around. \nA good alternative is dependancy injection but with view controllers and storyboards it can be hard and feel very boilerplate. You end up passing everything down the line in prepareForSegue. \nOne possible method is to declare a protocol that describes a cache like interface. \nprotocol CacheProtocol: class {\n func doCacheThing()\n}\n\nclass Cache: CacheProtocol {\n func doCacheThing() {\n //\n }\n}\n\nThen declare a protocol that all things that wish to use this cache can use. \nprotocol CacheConsumer: class {\n var cache: CacheProtocol? { get set }\n func injectCache(to object: AnyObject)\n}\n\nextension CacheConsumer {\n func injectCache(to object: AnyObject) {\n if let consumer = object as? CacheConsumer {\n consumer.cache = cache\n }\n }\n}\n\nFinally create a concrete instance of this cache at the top level. \n/// Top most controller\nclass RootLevelViewController: UIViewController, CacheConsumer {\n var cache: CacheProtocol? = Cache()\n\n override func prepare(for segue: UIStoryboardSegue, sender: Any?) {\n injectCache(to: segue.destination)\n }\n\n}\n\nYou could pass the cache down the line in prepareForSegue. \nOr you can use subtle sub-classing to create conformance.\nclass MyTabBarController: UITabBarController, CacheConsumer {\n var cache: CacheProtocol?\n}\n\nOr you can use delegate methods to get the cache object broadcast downhill. \nextension RootLevelViewController: UITabBarControllerDelegate {\n func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {\n injectCache(to: viewController)\n }\n}\n\nYou now have a system where any CacheConsumer can use the cache and pass it downhill to any other object. \n", "If you use the coordinator pattern you can save the cache in the coordinator for your navigation flow and access it from there/init with the cache. It also works nicely since when the navigation flow is removed the cache is also removed.\nfinal class SomeCoordinator: NSObject, Coordinator {\n var rootViewController: UINavigationController\n var myCache = NSCache<AnyObject, AnyObject>()\n \n override init() {\n self.rootViewController = UINavigationController()\n super.init()\n }\n \n func start() {\n let vc = VC1(cache: myCache)\n vc.coordinator = self\n rootViewController.setViewControllers([vc], animated: false)\n parentCoordinator?.rootViewController.present(rootViewController, animated: true)\n }\n \n func goToVC2() {\n let vc = VC2(cache: myCache)\n vc.coordinator = self\n rootViewController.pushViewController(vc, animated: true)\n }\n \n func goToVC3() {\n let vc = VC3(cache: myCache)\n vc.coordinator = self\n rootViewController.present(vc, animated: true)\n }\n \n func goToVC4() {\n let vc = VC4(cache: myCache)\n vc.coordinator = self\n rootViewController.present(vc, animated: true)\n }\n \n deinit {\n print(\"βœ… Deinit SomeCoordinator\")\n }\n \n}\n\n\n" ]
[ 2, 0 ]
[]
[]
[ "swift" ]
stackoverflow_0055470792_swift.txt
Q: Jest test fails when using a pipe, but succeeds when using a subscription In the application, there is a service, which is used in an action that then updates the state. When running the application everything works fine using a piped observable. However, when creating the test, I am not able to update the state without adding a subscription for it to work. ./MyApiService.ts @Injectable({ providedIn: 'root' }) export class MyApiService { constructor(private http: HttpClient) {} getSomeData(): Observable<any> { return this.http.get('https://some-url.com/') } } ./MyState.ts @State<StateModel>({}) @Injectable() export class MyState { constructor() { private myApiService: MyApiService, } @Action(SomeAction.UpdateData) updateData(ctx: StateContext<StateModel>) { return this.myApiService.getSomeData().pipe( tap(data => { if (data) { ctx.patchState({ data }); } } ) } } Now for the test: ./MyState.spec.ts desribe('some test', () => { beforeEach(() => { stub.MyApiService = { getSomeData: jest.fn().mockReturnValue(of({ foo: 'bar' }]); } stub.ctx = { patchState: jest.fn(), } state = new MyState(stub.MyApiService); }); it('should update data', () => { state.updateData(stub.ctx); expect(stub.MyApiService.getSomeData).toHaveBeenCalledTimes(1); // works expect(stub.ctx.patchState).toHaveBeenCalledTimes(1); // fails! }); }); That does not work. However, if I change the action to have a subscription... ./MyState.ts @State<StateModel>() @Injectable() export class MyState { constructor() { private myApiService: MyApiService, } @Action(SomeAction.UpdateData) updateData(ctx: StateContext<StateModel>) { return this.myApiService.getSomeData().pipe( tap(data => { if (data) { ctx.patchState({ data }); } } ).subscribe(); // added here and now the test succeeds } } ...it works. But it feels a bit off to have to subscribe and also have to unsubscribe when that is not necessary with just the pipe. A: what Matthieu explained is correct. If you dont subscribe to an async-call nothing will ever happend. the pipe() operator is only there to cut into the stream and change the data before it reaches the component/services. But without the Subscription the pipe() will never trigger. Which means in your Tests, that you have to subscribe to get the data, just like in a normal component.
Jest test fails when using a pipe, but succeeds when using a subscription
In the application, there is a service, which is used in an action that then updates the state. When running the application everything works fine using a piped observable. However, when creating the test, I am not able to update the state without adding a subscription for it to work. ./MyApiService.ts @Injectable({ providedIn: 'root' }) export class MyApiService { constructor(private http: HttpClient) {} getSomeData(): Observable<any> { return this.http.get('https://some-url.com/') } } ./MyState.ts @State<StateModel>({}) @Injectable() export class MyState { constructor() { private myApiService: MyApiService, } @Action(SomeAction.UpdateData) updateData(ctx: StateContext<StateModel>) { return this.myApiService.getSomeData().pipe( tap(data => { if (data) { ctx.patchState({ data }); } } ) } } Now for the test: ./MyState.spec.ts desribe('some test', () => { beforeEach(() => { stub.MyApiService = { getSomeData: jest.fn().mockReturnValue(of({ foo: 'bar' }]); } stub.ctx = { patchState: jest.fn(), } state = new MyState(stub.MyApiService); }); it('should update data', () => { state.updateData(stub.ctx); expect(stub.MyApiService.getSomeData).toHaveBeenCalledTimes(1); // works expect(stub.ctx.patchState).toHaveBeenCalledTimes(1); // fails! }); }); That does not work. However, if I change the action to have a subscription... ./MyState.ts @State<StateModel>() @Injectable() export class MyState { constructor() { private myApiService: MyApiService, } @Action(SomeAction.UpdateData) updateData(ctx: StateContext<StateModel>) { return this.myApiService.getSomeData().pipe( tap(data => { if (data) { ctx.patchState({ data }); } } ).subscribe(); // added here and now the test succeeds } } ...it works. But it feels a bit off to have to subscribe and also have to unsubscribe when that is not necessary with just the pipe.
[ "what Matthieu explained is correct.\nIf you dont subscribe to an async-call nothing will ever happend. the pipe() operator is only there to cut into the stream and change the data before it reaches the component/services. But without the Subscription the pipe() will never trigger.\nWhich means in your Tests, that you have to subscribe to get the data, just like in a normal component.\n" ]
[ 1 ]
[]
[]
[ "angular", "jestjs", "rxjs" ]
stackoverflow_0074667376_angular_jestjs_rxjs.txt
Q: Ansible loop with hash values as one of conditions I have two playbooks - outer.yml and inner.yml and below is the code which is not working. outer.yml: - name: outer hosts: localhost vars: volume_names: ["abcd", "efgh"] tasks: - name: create hash values and call inner.yml set_fact: hash: "{{ 60000 | random(seed=item_name) }}" include_tasks: inner.yml loop: "{{ volume_names }}" loop_control: loop_var: item_name inner.yml: - name: inner collection.snapshot: gateway_host: "{{IP}}" username: admin password: pass snapshot_name: "{{ hash }}" vol_name: "{{ item_name }}" What I need is to create volume snapshots but each with unique snapshot name (that is why I used hashes) and do that for all volumes in the variable "volume_names". Code above is not working, but I'm not sure why. Any idea? Thanks! A: There is no need for the include, set_fact, and loop_control. For example, - hosts: localhost vars: volume_names: ["abcd", "efgh"] tasks: - debug: msg: | gateway_host: ip username: admin password: pass snapshot_name: "{{ 60000|random(seed=item) }}" vol_name: "{{ item }}" loop: "{{ volume_names }}" gives PLAY [localhost] ****************************************************************************** TASK [debug] ********************************************************************************** ok: [localhost] => (item=abcd) => msg: |- gateway_host: ip username: admin password: pass snapshot_name: "20203" vol_name: "abcd" ok: [localhost] => (item=efgh) => msg: |- gateway_host: ip username: admin password: pass snapshot_name: "39290" vol_name: "efgh" PLAY RECAP ************************************************************************************ localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 Try - collection.snapshot: gateway_host: "{{ IP }}" username: admin password: pass snapshot_name: "{{ 60000|random(seed=item) }}" vol_name: "{{ item }}" loop: "{{ volume_names }}"
Ansible loop with hash values as one of conditions
I have two playbooks - outer.yml and inner.yml and below is the code which is not working. outer.yml: - name: outer hosts: localhost vars: volume_names: ["abcd", "efgh"] tasks: - name: create hash values and call inner.yml set_fact: hash: "{{ 60000 | random(seed=item_name) }}" include_tasks: inner.yml loop: "{{ volume_names }}" loop_control: loop_var: item_name inner.yml: - name: inner collection.snapshot: gateway_host: "{{IP}}" username: admin password: pass snapshot_name: "{{ hash }}" vol_name: "{{ item_name }}" What I need is to create volume snapshots but each with unique snapshot name (that is why I used hashes) and do that for all volumes in the variable "volume_names". Code above is not working, but I'm not sure why. Any idea? Thanks!
[ "There is no need for the include, set_fact, and loop_control. For example,\n - hosts: localhost\n \n vars:\n volume_names: [\"abcd\", \"efgh\"]\n\n tasks:\n\n - debug:\n msg: |\n gateway_host: ip\n username: admin\n password: pass\n snapshot_name: \"{{ 60000|random(seed=item) }}\"\n vol_name: \"{{ item }}\"\n loop: \"{{ volume_names }}\"\n\ngives\nPLAY [localhost] ******************************************************************************\n\nTASK [debug] **********************************************************************************\nok: [localhost] => (item=abcd) => \n msg: |-\n gateway_host: ip\n username: admin\n password: pass\n snapshot_name: \"20203\"\n vol_name: \"abcd\"\nok: [localhost] => (item=efgh) => \n msg: |-\n gateway_host: ip\n username: admin\n password: pass\n snapshot_name: \"39290\"\n vol_name: \"efgh\"\n\nPLAY RECAP ************************************************************************************\nlocalhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0\n\nTry\n - collection.snapshot:\n gateway_host: \"{{ IP }}\"\n username: admin\n password: pass\n snapshot_name: \"{{ 60000|random(seed=item) }}\"\n vol_name: \"{{ item }}\"\n loop: \"{{ volume_names }}\"\n\n" ]
[ 3 ]
[]
[]
[ "ansible", "hash", "loops" ]
stackoverflow_0074667491_ansible_hash_loops.txt
Q: My dataframe is not changed when I run for loop(comparing two dataframes) I have two dataset, one with over 100,000 rows and 300 columns and the other with 200 rows and 6 columns. I'm comparing these two datasets and updating df1 from df2 using for loop. Here is the sample dataset df1: KEY MAIN_METHOD DRUG_ETCDTL 0 100944 1 unknown 1 67488 20 unknown 2 101476 20 unknown 3 102549 1 sleepingpill_plunitrazeparm 4 103227 1 some drug df2: 5. 방법/μˆ˜λ‹¨ Unnamed: 4 0 100944 sleepingpill_unknown 1 100984 others_green material 2 101476 others_anorexia 3 102549 sleepingpill_plunitrazeparm 4 103227 sleepingpill_pentobarbytal and here is the code that I tried: for i in range(0,4): index_key = df2['5. 방법/μˆ˜λ‹¨'][i] index_rawdata = df1.loc[df1['KEY']==index_key,'DRUG_ETCDTL'].index[0] method1 = df1['DRUG_ETCDTL'][index_rawdata] method2 = df1['METHOD_ETCDTL'][index_rawdata] # split df2 mainmethod = df2['Unnamed: 4'].str.split('_',expland=False) mainmethod[i][0] = mainmethod[i][0].replace('sleepingpill','1').replace('others','20') # change the type so we can compare it with df1 mainmethod[i][0] = int(mainmethod[i][0]) if (mainmethod[i][1] == 1) & (df1['MAIN_METHOD'][index_rawdata] ==1 ): method1 = mainmethod[i][1] elif (mainmethod[i][1] == 20) & df1['MAIN_METHOD'][index_rawdata] == 20): method2 = mainmethodp[i][1] so the df1 should be changed but when it use print df1 it is not changed. The desired output is: KEY MAIN_METHOD DRUG_ETCDTL 0 100944 1 unknown 1 67488. 20 unknown 2 101476 20 anorexia 3 102549 1 plunitrazeparm 4 103227 1 pentobarbytal NOTE: I approached this for loop method since I didn't want to manipulate df2 A: This solution avoids for loops and instead uses a temporary data frame to perform the task. The strings in the Unnamed: 4 column are split using the str.split() function provided by Pandas. The MAIN_METHOD information is transformed using a mapping. The df1 data frame is conditionally updated using numpy.where() before the temporay data frame is deleted. EDIT: The code has been modified to convert the temporary data frame column series to a numpy array using .values to avoid the error: ValueError: Can only compare identically-labeled Series objects Modified np.where() conditions: df1['DRUG_ETCDTL'] = np.where(((df1['KEY']==tmp_df['KEY'].values) & (df1['MAIN_METHOD']==tmp_df['MAIN_METHOD'].values)), tmp_df['DRUG_ETCDTL'], df1['DRUG_ETCDTL']) An alternative solution to avoiding the error would be to use .equals() instead of == when performing the comparison. df1['DRUG_ETCDTL'] = np.where(((df1['KEY'].equals(tmp_df['KEY'])) & (df1['MAIN_METHOD'].equals(tmp_df['MAIN_METHOD']))), tmp_df['DRUG_ETCDTL'], df1['DRUG_ETCDTL']) Complete solution: import pandas as pd import numpy as np df1 = pd.DataFrame({ 'KEY': [100944, 67488, 101476, 102549, 103227], 'MAIN_METHOD': [1, 20, 20, 1, 1], 'DRUG_ETCDTL': ['unknown', 'unknown', 'unknown', 'sleepingpill_plunitrazeparm', 'some drug'] }, index=np.arange(11,16)) df2 = pd.DataFrame({ '5. 방법/μˆ˜λ‹¨': [100944, 100984, 101476, 102549, 103227], 'Unnamed: 4': ['sleepingpill_unknown', 'others_green material', 'others_anorexia', 'sleepingpill_plunitrazeparm', 'sleepingpill_pentobarbytal'] }) # make a temporary copy of 'df2' tmp_df = df2[['5. 방법/μˆ˜λ‹¨', 'Unnamed: 4']].copy() # rename columns tmp_df.columns = ['KEY', 'METHOD_DRUG'] # split the string to get 'METHOD' and 'DRUG_ETCDTL' information tmp_df[['METHOD', 'DRUG_ETCDTL']] = tmp_df['METHOD_DRUG'].str.split('_', expand=True) # use a mapping to create 'MAIN_METHOD' column method_map = { 'sleepingpill': 1, 'others': 20 } tmp_df['MAIN_METHOD'] = tmp_df['METHOD'].map(method_map) # drop unwanted columns (This step is optional) tmp_df.drop(['METHOD_DRUG', 'METHOD'], inplace=True, axis=1) # update 'df1' df1['DRUG_ETCDTL'] = np.where(((df1['KEY']==tmp_df['KEY'].values) & (df1['MAIN_METHOD']==tmp_df['MAIN_METHOD'].values)), tmp_df['DRUG_ETCDTL'], df1['DRUG_ETCDTL']) # delete temporary copy of 'df2' del tmp_df
My dataframe is not changed when I run for loop(comparing two dataframes)
I have two dataset, one with over 100,000 rows and 300 columns and the other with 200 rows and 6 columns. I'm comparing these two datasets and updating df1 from df2 using for loop. Here is the sample dataset df1: KEY MAIN_METHOD DRUG_ETCDTL 0 100944 1 unknown 1 67488 20 unknown 2 101476 20 unknown 3 102549 1 sleepingpill_plunitrazeparm 4 103227 1 some drug df2: 5. 방법/μˆ˜λ‹¨ Unnamed: 4 0 100944 sleepingpill_unknown 1 100984 others_green material 2 101476 others_anorexia 3 102549 sleepingpill_plunitrazeparm 4 103227 sleepingpill_pentobarbytal and here is the code that I tried: for i in range(0,4): index_key = df2['5. 방법/μˆ˜λ‹¨'][i] index_rawdata = df1.loc[df1['KEY']==index_key,'DRUG_ETCDTL'].index[0] method1 = df1['DRUG_ETCDTL'][index_rawdata] method2 = df1['METHOD_ETCDTL'][index_rawdata] # split df2 mainmethod = df2['Unnamed: 4'].str.split('_',expland=False) mainmethod[i][0] = mainmethod[i][0].replace('sleepingpill','1').replace('others','20') # change the type so we can compare it with df1 mainmethod[i][0] = int(mainmethod[i][0]) if (mainmethod[i][1] == 1) & (df1['MAIN_METHOD'][index_rawdata] ==1 ): method1 = mainmethod[i][1] elif (mainmethod[i][1] == 20) & df1['MAIN_METHOD'][index_rawdata] == 20): method2 = mainmethodp[i][1] so the df1 should be changed but when it use print df1 it is not changed. The desired output is: KEY MAIN_METHOD DRUG_ETCDTL 0 100944 1 unknown 1 67488. 20 unknown 2 101476 20 anorexia 3 102549 1 plunitrazeparm 4 103227 1 pentobarbytal NOTE: I approached this for loop method since I didn't want to manipulate df2
[ "This solution avoids for loops and instead uses a temporary data frame to perform the task. The strings in the Unnamed: 4 column are split using the str.split() function provided by Pandas. The MAIN_METHOD information is transformed using a mapping. The df1 data frame is conditionally updated using numpy.where() before the temporay data frame is deleted.\nEDIT: The code has been modified to convert the temporary data frame column series to a numpy array using .values to avoid the error:\nValueError: Can only compare identically-labeled Series objects\n\nModified np.where() conditions:\ndf1['DRUG_ETCDTL'] = np.where(((df1['KEY']==tmp_df['KEY'].values) & \n (df1['MAIN_METHOD']==tmp_df['MAIN_METHOD'].values)),\n tmp_df['DRUG_ETCDTL'],\n df1['DRUG_ETCDTL'])\n\nAn alternative solution to avoiding the error would be to use .equals() instead of == when performing the comparison.\ndf1['DRUG_ETCDTL'] = np.where(((df1['KEY'].equals(tmp_df['KEY'])) & \n (df1['MAIN_METHOD'].equals(tmp_df['MAIN_METHOD']))),\n tmp_df['DRUG_ETCDTL'],\n df1['DRUG_ETCDTL'])\n\nComplete solution:\nimport pandas as pd\nimport numpy as np\n\ndf1 = pd.DataFrame({ \n 'KEY': [100944, 67488, 101476, 102549, 103227],\n 'MAIN_METHOD': [1, 20, 20, 1, 1],\n 'DRUG_ETCDTL': ['unknown', 'unknown', 'unknown', 'sleepingpill_plunitrazeparm', 'some drug']\n}, index=np.arange(11,16))\n\ndf2 = pd.DataFrame({\n '5. 방법/μˆ˜λ‹¨': [100944, 100984, 101476, 102549, 103227],\n 'Unnamed: 4': ['sleepingpill_unknown', 'others_green material', 'others_anorexia', 'sleepingpill_plunitrazeparm', 'sleepingpill_pentobarbytal']\n})\n\n# make a temporary copy of 'df2'\ntmp_df = df2[['5. 방법/μˆ˜λ‹¨', 'Unnamed: 4']].copy()\n# rename columns\ntmp_df.columns = ['KEY', 'METHOD_DRUG']\n# split the string to get 'METHOD' and 'DRUG_ETCDTL' information\ntmp_df[['METHOD', 'DRUG_ETCDTL']] = tmp_df['METHOD_DRUG'].str.split('_', expand=True)\n# use a mapping to create 'MAIN_METHOD' column\nmethod_map = { 'sleepingpill': 1, 'others': 20 }\ntmp_df['MAIN_METHOD'] = tmp_df['METHOD'].map(method_map)\n# drop unwanted columns (This step is optional)\ntmp_df.drop(['METHOD_DRUG', 'METHOD'], inplace=True, axis=1)\n# update 'df1'\ndf1['DRUG_ETCDTL'] = np.where(((df1['KEY']==tmp_df['KEY'].values) & \n (df1['MAIN_METHOD']==tmp_df['MAIN_METHOD'].values)),\n tmp_df['DRUG_ETCDTL'],\n df1['DRUG_ETCDTL'])\n# delete temporary copy of 'df2'\ndel tmp_df\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074666370_dataframe_pandas_python.txt
Q: Socket.io reprocesses first client when using dynamic namespaces with middleware For some reason, if I register a dynamic namespace, the middleware fires, but fires with previously processed sockets that have already been put through the middleware. Below, I set up a server, register a listener that automatically sets up middleware on new namespaces, register a dynamic namespace that uses a regex, then set up two other clients: const { io } = require('socket.io-client'); const { Server } = require('socket.io'); const server = new Server(4321, {}); function middleware(socket, next) { console.log(socket.nsp.name, socket.handshake.headers.cookie); } server.on('new_namespace', (namespace) => { namespace.use(middleware); }) const nsps = server.of(/^\/\w+$/); const clientOne = io.connect('http://localhost:4321/firstNamespace', { extraHeaders: { Cookie: "client=one" } }); const clientTwo = io.connect('http://localhost:4321/secondNamespace', { extraHeaders: { Cookie: "client=two" } }); const clientThree = io.connect('http://localhost:4321/thirdNamespace', { extraHeaders: { Cookie: "client=three" } }); The bizarre thing is, this prints out: /firstNamespace client=one /secondNamespace client=one /thirdNamespace client=one Note the client=one cookies. Instead of firing the middleware for each of the clients on different namespaces, the middleware three times on the first client, and not at all for the other two. If I remove the latter two calls to io.connect and only leave the first, only this prints: /firstNamespace client=one So it is tied to the creation of the latter clients, but only the first client is used? I would love an explanation for this. The actual scenario that lead to this was setting up a test to ensure that the auth middleware is automatically associated with new namespaces. That can be remedied by re-creating the server on every test, but I'd like to know why the above code behaves as it does. Socket.io server and client are version 4.5.4, running on Node v16.15.0. A: In order to get more insights about what's happening under the hood we can rely on the fact that socket.io packages use the https://www.npmjs.com/package/debug package to expose useful info. Therefore if we want to focus about what's going on from the client perspective, we can execute the following command (assuming that your snippet above is in index.js): DEBUG='socket.io-client*' node index.js socket.io-client:url parse http://localhost:4321/firstNamespace +0ms socket.io-client new io instance for http://localhost:4321/firstNamespace +0ms socket.io-client:manager readyState closed +0ms socket.io-client:manager opening http://localhost:4321/firstNamespace +0ms socket.io-client:manager connect attempt will timeout after 20000 +10ms socket.io-client:manager readyState opening +1ms socket.io-client:url parse http://localhost:4321/secondNamespace +14ms socket.io-client:manager readyState opening +0ms socket.io-client:url parse http://localhost:4321/thirdNamespace +0ms socket.io-client:manager readyState opening +0ms socket.io-client:manager open +18ms socket.io-client:manager cleanup +0ms socket.io-client:socket transport is open - connecting +0ms socket.io-client:manager writing packet {"type":0,"nsp":"/firstNamespace"} +1ms socket.io-client:socket transport is open - connecting +1ms socket.io-client:manager writing packet {"type":0,"nsp":"/secondNamespace"} +1ms socket.io-client:socket transport is open - connecting +0ms socket.io-client:manager writing packet {"type":0,"nsp":"/thirdNamespace"} +0ms NIua-1FB4AVjGHAgAAAB /firstNamespace client=one jz9NAF39kOH8FZH5AAAC /secondNamespace client=one BgHBTapkuNAGn_tMAAAD /thirdNamespace client=one The final 3 lines of this input are from this part: function middleware(socket, next) { console.log(socket.id, socket.nsp.name, socket.handshake.headers.cookie); } As you can observe I took the liberty to add the socket.id to confirm the the 3 sockets are indeed different which was not so obvious by looking only at the cookie part. What's happening related to Cookie is that they are transmitted once in the HTTP headers of the HTTP connection on which the WebSocket protocol is then upgraded. Look for 101 HTTP status code on the MDN documentation for more details about this part. The 3 consecutive calls to io.connect(…) reuse the same cached Manager as can be seen from the source code : https://github.com/socketio/socket.io-client/blob/main/lib/index.ts#L34-L72 Here's the relevant extract: const newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace; let io: Manager; if (newConnection) { debug("ignoring socket cache for %s", source); io = new Manager(source, opts); } else { if (!cache[id]) { debug("new io instance for %s", source); cache[id] = new Manager(source, opts); } io = cache[id]; } if (parsed.query && !opts.query) { opts.query = parsed.queryKey; } return io.socket(parsed.path, opts); In conclusion, to obtain 3 distinct client, offering 3 distinct Cookie value, you have to disable this cache by forcing a new underlying connection, with the forceNew option: const clientOne = io.connect('http://localhost:4321/firstNamespace', { forceNew: true, extraHeaders: { Cookie: "client=one" } }); const clientTwo = io.connect('http://localhost:4321/secondNamespace', { forceNew: true, extraHeaders: { Cookie: "client=two" } }); const clientThree = io.connect('http://localhost:4321/thirdNamespace', { forceNew: true, extraHeaders: { Cookie: "client=three" } });
Socket.io reprocesses first client when using dynamic namespaces with middleware
For some reason, if I register a dynamic namespace, the middleware fires, but fires with previously processed sockets that have already been put through the middleware. Below, I set up a server, register a listener that automatically sets up middleware on new namespaces, register a dynamic namespace that uses a regex, then set up two other clients: const { io } = require('socket.io-client'); const { Server } = require('socket.io'); const server = new Server(4321, {}); function middleware(socket, next) { console.log(socket.nsp.name, socket.handshake.headers.cookie); } server.on('new_namespace', (namespace) => { namespace.use(middleware); }) const nsps = server.of(/^\/\w+$/); const clientOne = io.connect('http://localhost:4321/firstNamespace', { extraHeaders: { Cookie: "client=one" } }); const clientTwo = io.connect('http://localhost:4321/secondNamespace', { extraHeaders: { Cookie: "client=two" } }); const clientThree = io.connect('http://localhost:4321/thirdNamespace', { extraHeaders: { Cookie: "client=three" } }); The bizarre thing is, this prints out: /firstNamespace client=one /secondNamespace client=one /thirdNamespace client=one Note the client=one cookies. Instead of firing the middleware for each of the clients on different namespaces, the middleware three times on the first client, and not at all for the other two. If I remove the latter two calls to io.connect and only leave the first, only this prints: /firstNamespace client=one So it is tied to the creation of the latter clients, but only the first client is used? I would love an explanation for this. The actual scenario that lead to this was setting up a test to ensure that the auth middleware is automatically associated with new namespaces. That can be remedied by re-creating the server on every test, but I'd like to know why the above code behaves as it does. Socket.io server and client are version 4.5.4, running on Node v16.15.0.
[ "In order to get more insights about what's happening under the hood we can rely on the fact that socket.io packages use the https://www.npmjs.com/package/debug package to expose useful info.\nTherefore if we want to focus about what's going on from the client perspective, we can execute the following command (assuming that your snippet above is in index.js):\nDEBUG='socket.io-client*' node index.js\n socket.io-client:url parse http://localhost:4321/firstNamespace +0ms\n socket.io-client new io instance for http://localhost:4321/firstNamespace +0ms\n socket.io-client:manager readyState closed +0ms\n socket.io-client:manager opening http://localhost:4321/firstNamespace +0ms\n socket.io-client:manager connect attempt will timeout after 20000 +10ms\n socket.io-client:manager readyState opening +1ms\n socket.io-client:url parse http://localhost:4321/secondNamespace +14ms\n socket.io-client:manager readyState opening +0ms\n socket.io-client:url parse http://localhost:4321/thirdNamespace +0ms\n socket.io-client:manager readyState opening +0ms\n socket.io-client:manager open +18ms\n socket.io-client:manager cleanup +0ms\n socket.io-client:socket transport is open - connecting +0ms\n socket.io-client:manager writing packet {\"type\":0,\"nsp\":\"/firstNamespace\"} +1ms\n socket.io-client:socket transport is open - connecting +1ms\n socket.io-client:manager writing packet {\"type\":0,\"nsp\":\"/secondNamespace\"} +1ms\n socket.io-client:socket transport is open - connecting +0ms\n socket.io-client:manager writing packet {\"type\":0,\"nsp\":\"/thirdNamespace\"} +0ms\nNIua-1FB4AVjGHAgAAAB /firstNamespace client=one\njz9NAF39kOH8FZH5AAAC /secondNamespace client=one\nBgHBTapkuNAGn_tMAAAD /thirdNamespace client=one\n\nThe final 3 lines of this input are from this part:\nfunction middleware(socket, next) {\n console.log(socket.id, socket.nsp.name, socket.handshake.headers.cookie);\n}\n\nAs you can observe I took the liberty to add the socket.id to confirm the the 3 sockets are indeed different which was not so obvious by looking only at the cookie part.\nWhat's happening related to Cookie is that they are transmitted once in the HTTP headers of the HTTP connection on which the WebSocket protocol is then upgraded. Look for 101 HTTP status code on the MDN documentation for more details about this part.\nThe 3 consecutive calls to io.connect(…) reuse the same cached Manager as can be seen from the source code : https://github.com/socketio/socket.io-client/blob/main/lib/index.ts#L34-L72\nHere's the relevant extract:\n const newConnection =\n opts.forceNew ||\n opts[\"force new connection\"] ||\n false === opts.multiplex ||\n sameNamespace;\n\n let io: Manager;\n\n if (newConnection) {\n debug(\"ignoring socket cache for %s\", source);\n io = new Manager(source, opts);\n } else {\n if (!cache[id]) {\n debug(\"new io instance for %s\", source);\n cache[id] = new Manager(source, opts);\n }\n io = cache[id];\n }\n if (parsed.query && !opts.query) {\n opts.query = parsed.queryKey;\n }\n return io.socket(parsed.path, opts);\n\nIn conclusion, to obtain 3 distinct client, offering 3 distinct Cookie value, you have to disable this cache by forcing a new underlying connection, with the forceNew option:\nconst clientOne = io.connect('http://localhost:4321/firstNamespace', {\n forceNew: true,\n extraHeaders: {\n Cookie: \"client=one\"\n }\n});\n\nconst clientTwo = io.connect('http://localhost:4321/secondNamespace', {\n forceNew: true,\n extraHeaders: {\n Cookie: \"client=two\"\n }\n});\n\nconst clientThree = io.connect('http://localhost:4321/thirdNamespace', {\n forceNew: true,\n extraHeaders: {\n Cookie: \"client=three\"\n }\n});\n\n" ]
[ 1 ]
[]
[]
[ "javascript", "node.js", "socket.io" ]
stackoverflow_0074648787_javascript_node.js_socket.io.txt
Q: Free alternative to HEROKU? I have a simple script that is a code that fetches the tweets of a specific account on Twitter and publishes them on Facebook using Python , facebook-sdk and BeautifulSoup library. I used to host script on HEROKU, but now everything in HEROKU needs money. I want a host that I can hosting for my script, thank you I tried Pythonanywhere, but in the free version I can't use Request library A: Have you ever considered using "GitHub-Actions", or "Google Firebase-Cloud Functions" ? Those sound like good candidates for your demand.
Free alternative to HEROKU?
I have a simple script that is a code that fetches the tweets of a specific account on Twitter and publishes them on Facebook using Python , facebook-sdk and BeautifulSoup library. I used to host script on HEROKU, but now everything in HEROKU needs money. I want a host that I can hosting for my script, thank you I tried Pythonanywhere, but in the free version I can't use Request library
[ "Have you ever considered using \"GitHub-Actions\", or \"Google Firebase-Cloud Functions\" ? Those sound like good candidates for your demand.\n" ]
[ 0 ]
[]
[]
[ "heroku", "python", "pythonanywhere" ]
stackoverflow_0074667292_heroku_python_pythonanywhere.txt
Q: BBB How to fix error Error: Could not connect to the configured hostname/IP address my BigBlueButton installation worked but now i get the following error: Potential problems described below Not running: tomcat9 or grails ................................................................................ Error: Could not connect to the configured hostname/IP address #http:/myserver.com/ #If your BigBlueButton server is behind a firewall, see FAQ. Trying to open this URL with my Browser works perfect. Output of the #sudo bbb-conf --check: BigBlueButton Server 2.5.8 (3139) Kernel version: 5.4.0-132-generic Distribution: Ubuntu 20.04.5 LTS (64-bit) Memory: 8148 MB CPU cores: 4 /etc/bigbluebutton/bbb-web.properties (override for bbb-web) /usr/share/bbb-web/WEB-INF/classes/bigbluebutton.properties (bbb-web) bigbluebutton.web.serverURL: http://myserver.com defaultGuestPolicy: ALWAYS_ACCEPT svgImagesRequired: true defaultMeetingLayout: CUSTOM_LAYOUT /etc/nginx/sites-available/bigbluebutton (nginx) server_name: localhost port: 80, \[::\]:80 /opt/freeswitch/etc/freeswitch/vars.xml (FreeSWITCH) local_ip_v4: xxx.xxx.xxx.xxx external_rtp_ip: xxx.xxx.xxx.xxx external_sip_ip: xxx.xxx.xxx.xxx /opt/freeswitch/etc/freeswitch/sip_profiles/external.xml (FreeSWITCH) ext-rtp-ip: $${local_ip_v4} ext-sip-ip: $${local_ip_v4} ws-binding: :5066 wss-binding: :7443 /usr/local/bigbluebutton/core/scripts/bigbluebutton.yml (record and playback) playback_host: myserver.com playback_protocol: http ffmpeg: 4.2.7-0ubuntu0.1 /usr/share/bigbluebutton/nginx/sip.nginx (sip.nginx) proxy_pass: xxx.xxx.xxx.xxx protocol: http /usr/local/bigbluebutton/bbb-webrtc-sfu/config/default.yml (Kurento SFU) /etc/bigbluebutton/bbb-webrtc-sfu/production.yml (Kurento SFU - override) kurento.ip: xxx.xxx.xxx.xxx kurento.url: ws://127.0.0.1:8888/kurento kurento.sip_ip: xxx.xxx.xxx.xxx recordScreenSharing: true recordWebcams: true codec_video_main: VP8 codec_video_content: VP8 /usr/share/meteor/bundle/programs/server/assets/app/config/settings.yml (HTML5 client) /etc/bigbluebutton/bbb-html5.yml (HTML5 client config override) build: 2870 kurentoUrl: wss://myserver.com/bbb-webrtc-sfu enableListenOnly: true sipjsHackViaWs: false /usr/share/bbb-web/WEB-INF/classes/spring/turn-stun-servers.xml (STUN Server) stun: stun.l.google.com:19302 Output of #sudo bbb-conf --status: nginx β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] freeswitch β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] redis-server β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-apps-akka β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-fsesl-akka β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] mongod β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-html5 β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-webrtc-sfu β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] kurento-media-server β€”β€”β–Ί [βœ” - active] bbb-html5-backend@1 β€”β€”β€”β–Ί [βœ” - active] bbb-html5-backend@2 β€”β€”β€”β–Ί [βœ” - active] bbb-html5-frontend@1 β€”β€”β–Ί [βœ” - active] bbb-html5-frontend@2 β€”β€”β–Ί [βœ” - active] etherpad β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-web β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-pads β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-rap-caption-inbox β€”β–Ί [βœ” - active] bbb-rap-resque-worker β€”β–Ί [βœ” - active] bbb-rap-starter β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] Considering the /var/log/nginx folder: The bigbluebutton.access.log is empty, but the error.log (after trying to create a session one time): 2022/11/29 12:44:41 [error] 756#756: *84 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught RuntimeException: Unhandled curl error: Could not resolve host: api in /home/yoshi/bbb/vendo> Stack trace: #0 /home/yoshi/bbb/vendor/bigbluebutton/bigbluebutton-api-php/src/BigBlueButton.php(115): BigBlueButton\BigBlueButton->processXmlResponse() #1 /var/www/bigbluebutton-default/test/join-bbb.php(28): BigBlueButton\BigBlueButton->createMeeting() #2 {main} thrown in /home/yoshi/bbb/vendor/bigbluebutton/bigbluebutton-api-php/src/BigBlueButton.php on line 487" while reading response header from upstream, client: 95.222.25.68, server: bbb.v220221118737> Firewall: Firewall Configuration Would be glad if you can help me with my problem. Regards Yoshi A: great you are using BBB. Did you check for this page? The solution had been to fix a typo: There was a syntax-error in /usr/share/bbb-web/WEB-INF/classes/spring/turn-stun-servers.xml Please have a look - might help you out. If not please give closer information to the following key-words. Did you already check the links - how is your issue different from those? Looking forward to dive deeper in this interesting topic :)
BBB How to fix error Error: Could not connect to the configured hostname/IP address
my BigBlueButton installation worked but now i get the following error: Potential problems described below Not running: tomcat9 or grails ................................................................................ Error: Could not connect to the configured hostname/IP address #http:/myserver.com/ #If your BigBlueButton server is behind a firewall, see FAQ. Trying to open this URL with my Browser works perfect. Output of the #sudo bbb-conf --check: BigBlueButton Server 2.5.8 (3139) Kernel version: 5.4.0-132-generic Distribution: Ubuntu 20.04.5 LTS (64-bit) Memory: 8148 MB CPU cores: 4 /etc/bigbluebutton/bbb-web.properties (override for bbb-web) /usr/share/bbb-web/WEB-INF/classes/bigbluebutton.properties (bbb-web) bigbluebutton.web.serverURL: http://myserver.com defaultGuestPolicy: ALWAYS_ACCEPT svgImagesRequired: true defaultMeetingLayout: CUSTOM_LAYOUT /etc/nginx/sites-available/bigbluebutton (nginx) server_name: localhost port: 80, \[::\]:80 /opt/freeswitch/etc/freeswitch/vars.xml (FreeSWITCH) local_ip_v4: xxx.xxx.xxx.xxx external_rtp_ip: xxx.xxx.xxx.xxx external_sip_ip: xxx.xxx.xxx.xxx /opt/freeswitch/etc/freeswitch/sip_profiles/external.xml (FreeSWITCH) ext-rtp-ip: $${local_ip_v4} ext-sip-ip: $${local_ip_v4} ws-binding: :5066 wss-binding: :7443 /usr/local/bigbluebutton/core/scripts/bigbluebutton.yml (record and playback) playback_host: myserver.com playback_protocol: http ffmpeg: 4.2.7-0ubuntu0.1 /usr/share/bigbluebutton/nginx/sip.nginx (sip.nginx) proxy_pass: xxx.xxx.xxx.xxx protocol: http /usr/local/bigbluebutton/bbb-webrtc-sfu/config/default.yml (Kurento SFU) /etc/bigbluebutton/bbb-webrtc-sfu/production.yml (Kurento SFU - override) kurento.ip: xxx.xxx.xxx.xxx kurento.url: ws://127.0.0.1:8888/kurento kurento.sip_ip: xxx.xxx.xxx.xxx recordScreenSharing: true recordWebcams: true codec_video_main: VP8 codec_video_content: VP8 /usr/share/meteor/bundle/programs/server/assets/app/config/settings.yml (HTML5 client) /etc/bigbluebutton/bbb-html5.yml (HTML5 client config override) build: 2870 kurentoUrl: wss://myserver.com/bbb-webrtc-sfu enableListenOnly: true sipjsHackViaWs: false /usr/share/bbb-web/WEB-INF/classes/spring/turn-stun-servers.xml (STUN Server) stun: stun.l.google.com:19302 Output of #sudo bbb-conf --status: nginx β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] freeswitch β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] redis-server β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-apps-akka β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-fsesl-akka β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] mongod β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-html5 β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-webrtc-sfu β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] kurento-media-server β€”β€”β–Ί [βœ” - active] bbb-html5-backend@1 β€”β€”β€”β–Ί [βœ” - active] bbb-html5-backend@2 β€”β€”β€”β–Ί [βœ” - active] bbb-html5-frontend@1 β€”β€”β–Ί [βœ” - active] bbb-html5-frontend@2 β€”β€”β–Ί [βœ” - active] etherpad β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-web β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-pads β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] bbb-rap-caption-inbox β€”β–Ί [βœ” - active] bbb-rap-resque-worker β€”β–Ί [βœ” - active] bbb-rap-starter β€”β€”β€”β€”β€”β€”β€”β–Ί [βœ” - active] Considering the /var/log/nginx folder: The bigbluebutton.access.log is empty, but the error.log (after trying to create a session one time): 2022/11/29 12:44:41 [error] 756#756: *84 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught RuntimeException: Unhandled curl error: Could not resolve host: api in /home/yoshi/bbb/vendo> Stack trace: #0 /home/yoshi/bbb/vendor/bigbluebutton/bigbluebutton-api-php/src/BigBlueButton.php(115): BigBlueButton\BigBlueButton->processXmlResponse() #1 /var/www/bigbluebutton-default/test/join-bbb.php(28): BigBlueButton\BigBlueButton->createMeeting() #2 {main} thrown in /home/yoshi/bbb/vendor/bigbluebutton/bigbluebutton-api-php/src/BigBlueButton.php on line 487" while reading response header from upstream, client: 95.222.25.68, server: bbb.v220221118737> Firewall: Firewall Configuration Would be glad if you can help me with my problem. Regards Yoshi
[ "great you are using BBB. Did you check for this page?\nThe solution had been to fix a typo: There was a syntax-error in /usr/share/bbb-web/WEB-INF/classes/spring/turn-stun-servers.xml\nPlease have a look - might help you out.\nIf not please give closer information to the following key-words.\nDid you already check the links - how is your issue different from those?\nLooking forward to dive deeper in this interesting topic :)\n" ]
[ 0 ]
[]
[]
[ "api", "bigbluebutton", "nginx" ]
stackoverflow_0074614037_api_bigbluebutton_nginx.txt
Q: How to save file with a number such as 2 so it isnt the same as first file saved import qrcode import time import tkinter as tk import os import shutil from sys import exit # GUI with tkinter root = tk.Tk() root.title('Window') root.geometry("400x400+50+50") root.iconbitmap('QRCODE-GENERATOR.ico') root.configure(bg="grey") lbl_1 = tk.Label(root, text="Qrcode generator", font="1") entry_1 = tk.Entry(root) lbl_1.pack() entry_1.pack(side=tk.RIGHT) tk.mainloop() # GUI end if not entry_1: exit() data = entry_1 # Qr code setup qr = qrcode.QRCode( version=1, box_size=5, border=5 ) # Adding the data to the system qr.add_data(data) # qr customizing qr.make(fit=True) img = qr.make_image( fill_color= 'black', back_color= 'white' ) time.sleep(2) # saving qr img.save('output.png') # absolute path src_path = r"D:\Python\QRcode generator\output.png" dst_path = r"D:\Users" shutil.move(src_path, dst_path) you see I'm getting the error file already exists, so what I want it to add a number to the QR code every time someone saves it. So it doesn't throw the error, you see python and shutils just gets confused when saving a file with the same name 2 times. If you don't really get what I'm saying then just tell me to make some edits, ill make it simpler. Note: I might not be able to respond when you answer A: Based on what i understand you want to add something at the end of the name file to prevent throwing an error. import time FILE_NAME = f"output-{time.time()}.png" img.save(FILE_NAME) A: Try this: Put all your code into a while true loop. Declare a variable "num" and assign it to the integer 0. MAKE SURE THIS IS OUTSIDE THE WHILE TRUE LOOP! Change your code so that this part: src_path = r"D:\Python\QRcode generator\output.png" dst_path = r"D:\Users" looks like this: src_path = r"D:\Python\QRcode generator\output" + str(num) + ".png" dst_path = r"D:\Users" num += 1 (note) If you close the program it will reset
How to save file with a number such as 2 so it isnt the same as first file saved
import qrcode import time import tkinter as tk import os import shutil from sys import exit # GUI with tkinter root = tk.Tk() root.title('Window') root.geometry("400x400+50+50") root.iconbitmap('QRCODE-GENERATOR.ico') root.configure(bg="grey") lbl_1 = tk.Label(root, text="Qrcode generator", font="1") entry_1 = tk.Entry(root) lbl_1.pack() entry_1.pack(side=tk.RIGHT) tk.mainloop() # GUI end if not entry_1: exit() data = entry_1 # Qr code setup qr = qrcode.QRCode( version=1, box_size=5, border=5 ) # Adding the data to the system qr.add_data(data) # qr customizing qr.make(fit=True) img = qr.make_image( fill_color= 'black', back_color= 'white' ) time.sleep(2) # saving qr img.save('output.png') # absolute path src_path = r"D:\Python\QRcode generator\output.png" dst_path = r"D:\Users" shutil.move(src_path, dst_path) you see I'm getting the error file already exists, so what I want it to add a number to the QR code every time someone saves it. So it doesn't throw the error, you see python and shutils just gets confused when saving a file with the same name 2 times. If you don't really get what I'm saying then just tell me to make some edits, ill make it simpler. Note: I might not be able to respond when you answer
[ "Based on what i understand you want to add something at the end of the name file to prevent throwing an error.\nimport time\nFILE_NAME = f\"output-{time.time()}.png\"\nimg.save(FILE_NAME)\n\n", "Try this:\n\nPut all your code into a while true loop.\n\nDeclare a variable \"num\" and assign it to the integer 0. MAKE SURE THIS IS OUTSIDE THE WHILE TRUE LOOP!\n\nChange your code so that this part:\nsrc_path = r\"D:\\Python\\QRcode generator\\output.png\"\ndst_path = r\"D:\\Users\"\nlooks like this:\nsrc_path = r\"D:\\Python\\QRcode generator\\output\" + str(num) + \".png\"\ndst_path = r\"D:\\Users\"\n\n\nnum += 1\n(note) If you close the program it will reset\n" ]
[ 0, 0 ]
[]
[]
[ "file", "python", "python_3.x", "tkinter" ]
stackoverflow_0074667518_file_python_python_3.x_tkinter.txt
Q: How to remove line break? I'm currently working on a website and I it's putting line breaks where I don't believe it should. For example if I'd do: <p>a</p><p>b</p> it'd put a line break between them. Has it always been this way? A: Before and after each paragraph <p> browsers add margin automatically. You can modify that using css. For example, if you want to remove the margin completely: p { margin: 0 } A: If you check the code search for <br/> or \n or <p></p> inside the text elements and remove the which should fix the problem. If not provide the code snipped use browser devtools to locate the line breaks by inspecting on the browser. <p></p> is a block level element. Block level elements won't share the line with another element. You can style them and turn them into inline elements or inline-block elements. or use <span>a</span><span>b</span> if need anything to separate certain texts to style use <span></span>
How to remove line break?
I'm currently working on a website and I it's putting line breaks where I don't believe it should. For example if I'd do: <p>a</p><p>b</p> it'd put a line break between them. Has it always been this way?
[ "Before and after each paragraph <p> browsers add margin automatically.\nYou can modify that using css. For example, if you want to remove the margin completely:\np {\n margin: 0\n}\n\n", "If you check the code\nsearch for <br/> or \\n or <p></p>\ninside the text elements and remove the which should fix the problem.\nIf not provide the code snipped use browser devtools to locate the line breaks by inspecting on the browser.\n<p></p> is a block level element. Block level elements won't share the line with another element. You can style them and turn them into inline elements or inline-block elements.\nor use <span>a</span><span>b</span>\nif need anything to separate certain texts to style use <span></span>\n" ]
[ 1, 0 ]
[]
[]
[ "html" ]
stackoverflow_0074667598_html.txt
Q: how to trigger whatsapp business API via PHP how to trigger whatsapp business API via PHP like amazon what is the procedure to login for whatsapp business account A: To use the WhatsApp Business API, you will first need to sign up for a WhatsApp Business account. You can do this by visiting the WhatsApp Business website and following the steps to create an account. Once you have a WhatsApp Business account, you will need to obtain an API token. This token is a unique identifier that allows you to access the WhatsApp Business API and use its features. You can obtain an API token by following the instructions on the WhatsApp Business website or by contacting WhatsApp Business support. Once you have an API token, you can use it to trigger the WhatsApp Business API using PHP. To do this, you will need to use the WhatsApp Business API client for PHP, which provides a wrapper for the API that makes it easier to interact with the API using PHP. Here is an example of how you can use the WhatsApp Business API client for PHP to trigger the API: <?php // Import the WhatsApp Business API client for PHP require_once 'whatsapp-business-api-client.php'; // Create a new instance of the WhatsApp Business API client $client = new WhatsAppBusinessAPI(); // Set the API URL and your API token $client->setApiUrl('https://my-whatsapp-business-api.com/api/v1'); $client->setApiToken('MY_API_TOKEN'); // Set the identity of the sender and the recipient $client->setSender('+15555555555'); $client->setRecipient('+16666666666'); // Set the content of the message $client->setMessage('Hello, World!'); // Trigger the API to send the message $response = $client->sendMessage(); // Check the response to see if the message was sent successfully if ($response['success']) { echo 'Message sent successfully.'; } else { echo 'Error sending message: ' . $response['error']; } This example sends a simple text message from the sender to the recipient using the WhatsApp Business API. You can modify the code to include additional features or functionality as needed. Please note that this is just an example, and you will need to replace the placeholders (e.g., MY_API_TOKEN) with the appropriate values for your specific setup. Also, you will need to ensure that you have installed the WhatsApp Business API client for PHP and that you have all the necessary dependencies in place before running this code.
how to trigger whatsapp business API via PHP
how to trigger whatsapp business API via PHP like amazon what is the procedure to login for whatsapp business account
[ "To use the WhatsApp Business API, you will first need to sign up for a WhatsApp Business account. You can do this by visiting the WhatsApp Business website and following the steps to create an account.\nOnce you have a WhatsApp Business account, you will need to obtain an API token. This token is a unique identifier that allows you to access the WhatsApp Business API and use its features. You can obtain an API token by following the instructions on the WhatsApp Business website or by contacting WhatsApp Business support.\nOnce you have an API token, you can use it to trigger the WhatsApp Business API using PHP. To do this, you will need to use the WhatsApp Business API client for PHP, which provides a wrapper for the API that makes it easier to interact with the API using PHP.\nHere is an example of how you can use the WhatsApp Business API client for PHP to trigger the API:\n<?php\n\n// Import the WhatsApp Business API client for PHP\nrequire_once 'whatsapp-business-api-client.php';\n\n// Create a new instance of the WhatsApp Business API client\n$client = new WhatsAppBusinessAPI();\n\n// Set the API URL and your API token\n$client->setApiUrl('https://my-whatsapp-business-api.com/api/v1');\n$client->setApiToken('MY_API_TOKEN');\n\n// Set the identity of the sender and the recipient\n$client->setSender('+15555555555');\n$client->setRecipient('+16666666666');\n\n// Set the content of the message\n$client->setMessage('Hello, World!');\n\n// Trigger the API to send the message\n$response = $client->sendMessage();\n\n// Check the response to see if the message was sent successfully\nif ($response['success']) {\n echo 'Message sent successfully.';\n} else {\n echo 'Error sending message: ' . $response['error'];\n}\n\nThis example sends a simple text message from the sender to the recipient using the WhatsApp Business API. You can modify the code to include additional features or functionality as needed.\nPlease note that this is just an example, and you will need to replace the placeholders (e.g., MY_API_TOKEN) with the appropriate values for your specific setup. Also, you will need to ensure that you have installed the WhatsApp Business API client for PHP and that you have all the necessary dependencies in place before running this code.\n" ]
[ 0 ]
[]
[]
[ "php", "whatsapi" ]
stackoverflow_0074667599_php_whatsapi.txt
Q: 'x86_64-linux-gnu-gcc' failed with exit status 1 when I install pcyuda this error shows up; error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 I am following according to these steps : https://wiki.tiker.net/PyCuda/Installation/Linux/Ubuntu/
'x86_64-linux-gnu-gcc' failed with exit status 1
when I install pcyuda this error shows up; error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 I am following according to these steps : https://wiki.tiker.net/PyCuda/Installation/Linux/Ubuntu/
[]
[]
[ "It looks like you are trying to install a package called pcyuda on your system and you are encountering an error.\nThe error message command 'x86_64-linux-gnu-gcc' failed with exit status 1 suggests that the installation failed because the x86_64-linux-gnu-gcc compiler could not be found or failed to run. This could be because the compiler is not installed on your system or because it is not in your system's PATH environment variable.\nTo fix this issue, you will need to make sure that the x86_64-linux-gnu-gcc compiler is installed on your system and that it is available in your PATH environment variable.\nTo check if the compiler is installed, you can try running the following command:\nx86_64-linux-gnu-gcc --version\n\nIf the compiler is not installed, you will need to install it. The exact steps for installing the compiler will depend on your operating system and package manager.\nOnce the compiler is installed, you will need to make sure that it is available in your PATH environment variable.\nIf the output does not include the directory where the x86_64-linux-gnu-gcc compiler is installed, you will need to add it to your PATH variable. You can do this by modifying your shell's configuration file (e.g. ~/.bashrc or ~/.zshrc) to include the directory where the compiler is installed.\n" ]
[ -1 ]
[ "pycuda" ]
stackoverflow_0074667442_pycuda.txt
Q: How to set a column for checkbox value in MySQL in Python? I'm a beginner of python and mysql. Now I want build a small project, user will enter name and email on the website. And there will be a checkbox to check if the users read policy. So if the box is checked, the database will save "true", if not then save "false". Could someone help me the code? Thanks. users = Table('allUsers', meta, Column('id', Integer, primary_key = True), Column('name', String(225)), Column('email', String(225)), Column('ifReadPolicy', String(225)), ) A: The following code can be used to set a column for checkbox value in MySQL in Python: from mysql.connector import connect db_connection = connect( host='localhost', user='username', password='password', database='my_database' ) # Create a cursor object cursor = db_connection.cursor() # Create a table cursor.execute("CREATE TABLE my_table (id INT, checkbox_value BOOLEAN)") # Insert data into the table sql = "INSERT INTO my_table (id, checkbox_value) VALUES (%s, %s)" values = (1, 0) cursor.execute(sql, values) # Commit the changes to the database db_connection.commit()
How to set a column for checkbox value in MySQL in Python?
I'm a beginner of python and mysql. Now I want build a small project, user will enter name and email on the website. And there will be a checkbox to check if the users read policy. So if the box is checked, the database will save "true", if not then save "false". Could someone help me the code? Thanks. users = Table('allUsers', meta, Column('id', Integer, primary_key = True), Column('name', String(225)), Column('email', String(225)), Column('ifReadPolicy', String(225)), )
[ "The following code can be used to set a column for checkbox value in MySQL in Python:\nfrom mysql.connector import connect\n\ndb_connection = connect(\n host='localhost',\n user='username',\n password='password',\n database='my_database'\n)\n\n# Create a cursor object\ncursor = db_connection.cursor()\n\n# Create a table\ncursor.execute(\"CREATE TABLE my_table (id INT, checkbox_value BOOLEAN)\")\n\n# Insert data into the table\nsql = \"INSERT INTO my_table (id, checkbox_value) VALUES (%s, %s)\"\nvalues = (1, 0)\ncursor.execute(sql, values)\n\n# Commit the changes to the database\ndb_connection.commit()\n\n" ]
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0074665816_mysql_python.txt
Q: how to push a data with key of an array of objects without overwriting existing json data using node js? I have an object that looks like this : { "mark": [ { "id":1, "name": "mark", "age":26 }, { "id":2, "name": "mark", "age":25 } ], "jack": [ { "id":1, "name": "jack", "age":26 }, { "id":2, "name": "jack", "age": 24, } ] } WHAT I GOT AS OUTPUT IF A NEW USER IS ADDED IT IS NOT APPENDED, BUT IT IS OVERWRITTEN OR CREATED AS A NEW OBJECT { "mark": [ { "id":1, "name": "mark", "age":26 }, { "id":2, "name": "mark", "age":25 } ], "jack": [ { "id":1, "name": "jack", "age":26 }, { "id":2, "name": "jack", "age": 24, } ], } "Josh": [ { "id":1, "name": "Josh", "age":26 }, { "id":2, "name": "Josh", "age": 24, } ] Expected if new person data arrives in my JSON File, that should be appended to the next array with key values of array of Objects, like { "mark": [ { "id":1, "name": "mark", "age":26 }, { "id":2, "name": "mark", "age":25 } ], "jack": [ { "id":1, "name": "jack", "age":26 }, { "id":2, "name": "jack", "age": 24, } ], "Josh": [ { "id":1, "name": "Josh", "age":26 }, { "id":2, "name": "Josh", "age": 24, } ] } I've tried this method after reading the JSON file var newObject = array.reduce(function (obj, value) { var key = `${value.name}`; if (obj[key] == null) obj[key] = []; obj[key].push(value); return obj; }, {}); console.log(newObject); fs.appendFile("users.json", newObject, (err) => { res.send(JSON.stringify(newObject)); }); A: Like the advice already given, but using async fs i/o. import { promises as fs } from 'fs'; // or require('fs').promises // inside the OP's route const filename = 'users.json'; try { const array = await fs.readFile(filename); // OP's code here // const newObject = array.reduce(... await fs.writeFile(filename, newObject); return res.send(JSON.stringify(newObject)); } catch (error) { return res.status(500).send({ message: 'error' }); } Also note that all this is what a database does. A: You have to first read the data from the JSON and append the new object to the JSON data and then write it back to the file. const data = fs.readFileSync('users.json'); . . fs.writeFileSync('users.json', {...data, ...newObject});
how to push a data with key of an array of objects without overwriting existing json data using node js?
I have an object that looks like this : { "mark": [ { "id":1, "name": "mark", "age":26 }, { "id":2, "name": "mark", "age":25 } ], "jack": [ { "id":1, "name": "jack", "age":26 }, { "id":2, "name": "jack", "age": 24, } ] } WHAT I GOT AS OUTPUT IF A NEW USER IS ADDED IT IS NOT APPENDED, BUT IT IS OVERWRITTEN OR CREATED AS A NEW OBJECT { "mark": [ { "id":1, "name": "mark", "age":26 }, { "id":2, "name": "mark", "age":25 } ], "jack": [ { "id":1, "name": "jack", "age":26 }, { "id":2, "name": "jack", "age": 24, } ], } "Josh": [ { "id":1, "name": "Josh", "age":26 }, { "id":2, "name": "Josh", "age": 24, } ] Expected if new person data arrives in my JSON File, that should be appended to the next array with key values of array of Objects, like { "mark": [ { "id":1, "name": "mark", "age":26 }, { "id":2, "name": "mark", "age":25 } ], "jack": [ { "id":1, "name": "jack", "age":26 }, { "id":2, "name": "jack", "age": 24, } ], "Josh": [ { "id":1, "name": "Josh", "age":26 }, { "id":2, "name": "Josh", "age": 24, } ] } I've tried this method after reading the JSON file var newObject = array.reduce(function (obj, value) { var key = `${value.name}`; if (obj[key] == null) obj[key] = []; obj[key].push(value); return obj; }, {}); console.log(newObject); fs.appendFile("users.json", newObject, (err) => { res.send(JSON.stringify(newObject)); });
[ "Like the advice already given, but using async fs i/o.\nimport { promises as fs } from 'fs'; // or require('fs').promises\n\n// inside the OP's route\n const filename = 'users.json';\n try {\n const array = await fs.readFile(filename);\n\n // OP's code here\n // const newObject = array.reduce(...\n\n await fs.writeFile(filename, newObject);\n return res.send(JSON.stringify(newObject));\n\n } catch (error) {\n return res.status(500).send({ message: 'error' });\n }\n\nAlso note that all this is what a database does.\n", "You have to first read the data from the JSON and append the new object to the JSON data and then write it back to the file.\nconst data = fs.readFileSync('users.json');\n.\n.\nfs.writeFileSync('users.json', {...data, ...newObject});\n\n" ]
[ 2, 0 ]
[]
[]
[ "javascript", "json", "node.js" ]
stackoverflow_0074667141_javascript_json_node.js.txt
Q: (class) does not name a type error in c++ Please note that I have looked at other questions on stack overflow before posting this question. I have not found any solutions that worked. (This is simplified) I have five files: assets.h #pragma once #include "SDL2/SDL.h" #include <map> #include <string> // Asset Manager class class AssetManager { private: std::map<std::string, SDL_Texture*> textures; public: AssetManager(); ~AssetManager(); void addTexture(std::string id, const char *path); SDL_Texture *getTexture(std::string id); }; assets.cpp #include "assets.h" // Constructor AssetManager::AssetManager() {} // Destructor AssetManager::~AssetManager() { // Destructor code } // Adds texture to "textures" void AssetManager::addTexture(std::string id, const char *path) { // Code for adding texture } // Gets texture from "textures" SDL_Texture *AssetManager::getTexture(std::string id) { // Code for getting texture } game.h #pragma once class AssetManager; // assets.h include in game.cpp (see below) class Game { private: // Code here public: static AssetManager *assets; // More code here }; game.cpp #include "assets.h" #include "game.h" AssetManager *Game::assets = new AssetManager(); // Code for game here other_file.cpp #include "game.h" Game::assets->getTexture[<id>] // <-- This is where the error comes from Even though I used a forward decleration of class "AssetsManager" in game.h, and then included assets.h in game.cpp, when included from other files it gives this error: error: invalid use of incomplete type 'class AssetManager' Why does it say "AssetManager" is an incomplete type? A: Turns out I was missing a #include statement in other_file.cpp.
(class) does not name a type error in c++
Please note that I have looked at other questions on stack overflow before posting this question. I have not found any solutions that worked. (This is simplified) I have five files: assets.h #pragma once #include "SDL2/SDL.h" #include <map> #include <string> // Asset Manager class class AssetManager { private: std::map<std::string, SDL_Texture*> textures; public: AssetManager(); ~AssetManager(); void addTexture(std::string id, const char *path); SDL_Texture *getTexture(std::string id); }; assets.cpp #include "assets.h" // Constructor AssetManager::AssetManager() {} // Destructor AssetManager::~AssetManager() { // Destructor code } // Adds texture to "textures" void AssetManager::addTexture(std::string id, const char *path) { // Code for adding texture } // Gets texture from "textures" SDL_Texture *AssetManager::getTexture(std::string id) { // Code for getting texture } game.h #pragma once class AssetManager; // assets.h include in game.cpp (see below) class Game { private: // Code here public: static AssetManager *assets; // More code here }; game.cpp #include "assets.h" #include "game.h" AssetManager *Game::assets = new AssetManager(); // Code for game here other_file.cpp #include "game.h" Game::assets->getTexture[<id>] // <-- This is where the error comes from Even though I used a forward decleration of class "AssetsManager" in game.h, and then included assets.h in game.cpp, when included from other files it gives this error: error: invalid use of incomplete type 'class AssetManager' Why does it say "AssetManager" is an incomplete type?
[ "Turns out I was missing a #include statement in other_file.cpp.\n" ]
[ 0 ]
[]
[]
[ "c++", "compiler_errors", "include", "oop" ]
stackoverflow_0074651210_c++_compiler_errors_include_oop.txt
Q: Correct way of passing array parameter in ethers This is my function in solidity: function mint(uint256[] memory tokenIds) I am using ethers library to interact with contract so I am trying to use this function by using: contract.mint([1,2,3]) but it doesn't work at all. What is the correct way to pass array of elements to a method in ethers? I tried to pass string like "[1,2,3]" or [1,2,3] or even ["1","2","3"] but none of those worked. On etherscan manually I can just pass 1,2,3 and it works fine A: In some cases (as happened in my contract too), the input must be parsed before sending it to the contract. Example of smart contract function: function setServiceFees(uint256[] memory prices) public onlyOwner { require(prices.length == 4); serviceFees = prices; } using the ethers.js, I did this and it worked. Example of javascript code myContract.setServiceFees([ ethers.utils.parseEther(batchFee.toString()), ethers.utils.parseEther(easyFee.toString()), ethers.utils.parseEther(sellFee.toString()), ethers.utils.parseEther(forthFee.toString()), ])
Correct way of passing array parameter in ethers
This is my function in solidity: function mint(uint256[] memory tokenIds) I am using ethers library to interact with contract so I am trying to use this function by using: contract.mint([1,2,3]) but it doesn't work at all. What is the correct way to pass array of elements to a method in ethers? I tried to pass string like "[1,2,3]" or [1,2,3] or even ["1","2","3"] but none of those worked. On etherscan manually I can just pass 1,2,3 and it works fine
[ "In some cases (as happened in my contract too), the input must be parsed before sending it to the contract.\nExample of smart contract function:\n function setServiceFees(uint256[] memory prices) public onlyOwner {\n require(prices.length == 4);\n serviceFees = prices;\n }\n\nusing the ethers.js, I did this and it worked.\nExample of javascript code\nmyContract.setServiceFees([\n ethers.utils.parseEther(batchFee.toString()),\n ethers.utils.parseEther(easyFee.toString()),\n ethers.utils.parseEther(sellFee.toString()),\n ethers.utils.parseEther(forthFee.toString()),\n ])\n\n" ]
[ 0 ]
[]
[]
[ "ethers.js", "javascript", "solidity" ]
stackoverflow_0073179287_ethers.js_javascript_solidity.txt
Q: Checking internet connection in 2nd thread in kivymd app so, I have app in kivy/kivymd- it contains 2 windows, 1st window runs in infinity loop looking for input, but I want it to check form time to time whether or not it has internet connection - probably in 2nd thread. KV settings: KV = """ WindowManager: MainWindow: SecondWindow: <MainWindow>: name: "MainWindow" canvas: Color: rgba: self.background Rectangle: pos: self.pos size: self.size BoxLayout: id: layout orientation: "vertical" pos: self.pos size: self.size Label: text: '' font_size: 1 Image: source: 'logo.jpg' allow_stretch: True size_hint_y: None width: 80 Label: id: info text_size: self.size text: 'scan here' font_size: 26 size_hint_y: None text_size: self.width, None height: self.texture_size[1] halign: 'center' Label: id: clock text: '' font_size: 60 TextInput: id: kod text: '' multiline: False size_hint: (0, .5) font_size: 15 #opacity: 0 focus: True password: True text_validate_unfocus: False on_text_validate: root.update_label(kod.text) MDRaisedButton: text: 'button1' icon_color: 1, 1, 1, 1 size_hint: 0.3, 0.5 pos_hint: {"x":0.35, "top":1} on_release: app.root.current = "SecondWindow" Label: id: wifi text: '' font_size: 5 Label: text: 'gui apk' <SecondWindow> name: "SecondWindow" MDBoxLayout: id: layout orientation: "vertical" pos: self.pos size: self.size md_bg_color: 0.3, 0.3, 0.3, 1.0 Label: text: 'log in' font_size: 22 MDRaisedButton: text: 'button1' size_hint: 0.3, 0.5 pos_hint: {"x":0.35, "top":1} on_release: app.show_date_picker() MDRaisedButton: text: 'exit' size_hint: 0.3, 0.5 pos_hint: {"x":0.35, "top":1} on_release: root.manager.current = "MainWindow" root.manager.get_screen("MainWindow").ids["kod"].focus = True Label: text: 'gui apk' """ Code: import fdb import configparser import threading import time import socket from kivymd.app import MDApp from kivy.properties import ListProperty from kivy.lang import Builder from kivy.clock import Clock from kivy.uix.screenmanager import Screen, ScreenManager from kivy.properties import StringProperty from kivy.clock import mainthread from kivymd.uix.pickers import MDDatePicker config = configparser.ConfigParser() config.read(r'C:\\Users\\Przemek\\Desktop\\RCP\\config.txt') RED_BACKGROUND = [.75, 0, 0, 1.0] BLACK_BACKGROUND = [0.3, 0.3, 0.3, 1.0] GREEN_BACKGROUND = [0.2, 0.3, 0.1, 1] BLUE_BACKGROUND = [0, 0, 1, 1] class MainWindow(Screen): background = ListProperty() def __init__(self, **kwargs): super(MainWindow, self).__init__(**kwargs) self.background = BLACK_BACKGROUND Clock.schedule_interval( self.UpdateClock, 1 ) threading.Thread().start() @mainthread def update_label(self, val): con = fdb.connect( port = int(config.get('global', 'port')), database = str(config.get('global', 'database')), host = str(config.get('global', 'host')), user = str(config.get('global', 'user')), password = str(config.get('global', 'password')), charset = str(config.get('global', 'charset')) ) cur = con.cursor() cur.execute("select KOD, FK_KRT_PRC, ID FROM TABLE") if len(val) > 0: print('main loop here') con.commit() con.close() self.ids.kod.text = '' def SetStartScreen( self, dt ): self.ids.info.text = 'scan' self.background = BLACK_BACKGROUND def UpdateClock( self, dt ): self.ids.clock.text = time.strftime("%H:%M:%S") class SecondWindow(Screen): pass class WindowManager(ScreenManager): pass class MyMainApp(MDApp): def build(self): self.title = "gui apk" return Builder.load_string(KV) def on_save(self, instance, value, date_range): print(instance, value, date_range) pass def on_cancel(self, instance, value): pass def show_date_picker(self): date_dialog = MDDatePicker(mode="range") date_dialog.bind(on_save=self.on_save, on_cancel=self.on_cancel) date_dialog.open() if __name__ == "__main__": MyMainApp().run() My function to test internet connection def check_connection(): try: host = socket.gethostbyname('www.google.com') s = socket.create_connection((host, 80), 2) #print(True) return True except: return False res = check_connection() print(res) I try to put check_connection and call it in various places but w/o success A: I tested the code below. One thing I noticed in your question is the line threading.Thread().start(); this will not do anything because no function was submitted as the target of the thread. import socket import time from threading import Thread, Event def check_connection(internet_on: Event, interval: float = 60.0) -> None: print("starting function intended to be in a new thread") internet_on.clear() # one could also import Queue from queue and return specific error # messages by putting them in the queue in this thread and checking # for them in the main thread. while True: try: _host = socket.gethostbyname('www.google.com') s = socket.create_connection((_host, 80), 2) except socket.gaierror: internet_on.clear() except Exception as e: internet_on.clear() else: internet_on.set() time.sleep(interval) _internet = Event() # set daemon to True so the thread automatically closes when your main program ends new_thread = Thread(target=check_connection, args=(_internet, 5.0), daemon=True) new_thread.start() # below is just an example so this code will execute if __name__ == '__main__': while True: time.sleep(0.5) print(f"internet on = {_internet.is_set()}")
Checking internet connection in 2nd thread in kivymd app
so, I have app in kivy/kivymd- it contains 2 windows, 1st window runs in infinity loop looking for input, but I want it to check form time to time whether or not it has internet connection - probably in 2nd thread. KV settings: KV = """ WindowManager: MainWindow: SecondWindow: <MainWindow>: name: "MainWindow" canvas: Color: rgba: self.background Rectangle: pos: self.pos size: self.size BoxLayout: id: layout orientation: "vertical" pos: self.pos size: self.size Label: text: '' font_size: 1 Image: source: 'logo.jpg' allow_stretch: True size_hint_y: None width: 80 Label: id: info text_size: self.size text: 'scan here' font_size: 26 size_hint_y: None text_size: self.width, None height: self.texture_size[1] halign: 'center' Label: id: clock text: '' font_size: 60 TextInput: id: kod text: '' multiline: False size_hint: (0, .5) font_size: 15 #opacity: 0 focus: True password: True text_validate_unfocus: False on_text_validate: root.update_label(kod.text) MDRaisedButton: text: 'button1' icon_color: 1, 1, 1, 1 size_hint: 0.3, 0.5 pos_hint: {"x":0.35, "top":1} on_release: app.root.current = "SecondWindow" Label: id: wifi text: '' font_size: 5 Label: text: 'gui apk' <SecondWindow> name: "SecondWindow" MDBoxLayout: id: layout orientation: "vertical" pos: self.pos size: self.size md_bg_color: 0.3, 0.3, 0.3, 1.0 Label: text: 'log in' font_size: 22 MDRaisedButton: text: 'button1' size_hint: 0.3, 0.5 pos_hint: {"x":0.35, "top":1} on_release: app.show_date_picker() MDRaisedButton: text: 'exit' size_hint: 0.3, 0.5 pos_hint: {"x":0.35, "top":1} on_release: root.manager.current = "MainWindow" root.manager.get_screen("MainWindow").ids["kod"].focus = True Label: text: 'gui apk' """ Code: import fdb import configparser import threading import time import socket from kivymd.app import MDApp from kivy.properties import ListProperty from kivy.lang import Builder from kivy.clock import Clock from kivy.uix.screenmanager import Screen, ScreenManager from kivy.properties import StringProperty from kivy.clock import mainthread from kivymd.uix.pickers import MDDatePicker config = configparser.ConfigParser() config.read(r'C:\\Users\\Przemek\\Desktop\\RCP\\config.txt') RED_BACKGROUND = [.75, 0, 0, 1.0] BLACK_BACKGROUND = [0.3, 0.3, 0.3, 1.0] GREEN_BACKGROUND = [0.2, 0.3, 0.1, 1] BLUE_BACKGROUND = [0, 0, 1, 1] class MainWindow(Screen): background = ListProperty() def __init__(self, **kwargs): super(MainWindow, self).__init__(**kwargs) self.background = BLACK_BACKGROUND Clock.schedule_interval( self.UpdateClock, 1 ) threading.Thread().start() @mainthread def update_label(self, val): con = fdb.connect( port = int(config.get('global', 'port')), database = str(config.get('global', 'database')), host = str(config.get('global', 'host')), user = str(config.get('global', 'user')), password = str(config.get('global', 'password')), charset = str(config.get('global', 'charset')) ) cur = con.cursor() cur.execute("select KOD, FK_KRT_PRC, ID FROM TABLE") if len(val) > 0: print('main loop here') con.commit() con.close() self.ids.kod.text = '' def SetStartScreen( self, dt ): self.ids.info.text = 'scan' self.background = BLACK_BACKGROUND def UpdateClock( self, dt ): self.ids.clock.text = time.strftime("%H:%M:%S") class SecondWindow(Screen): pass class WindowManager(ScreenManager): pass class MyMainApp(MDApp): def build(self): self.title = "gui apk" return Builder.load_string(KV) def on_save(self, instance, value, date_range): print(instance, value, date_range) pass def on_cancel(self, instance, value): pass def show_date_picker(self): date_dialog = MDDatePicker(mode="range") date_dialog.bind(on_save=self.on_save, on_cancel=self.on_cancel) date_dialog.open() if __name__ == "__main__": MyMainApp().run() My function to test internet connection def check_connection(): try: host = socket.gethostbyname('www.google.com') s = socket.create_connection((host, 80), 2) #print(True) return True except: return False res = check_connection() print(res) I try to put check_connection and call it in various places but w/o success
[ "I tested the code below. One thing I noticed in your question is the line threading.Thread().start(); this will not do anything because no function was submitted as the target of the thread.\nimport socket\nimport time\nfrom threading import Thread, Event\n\n\ndef check_connection(internet_on: Event, interval: float = 60.0) -> None:\n print(\"starting function intended to be in a new thread\")\n internet_on.clear()\n # one could also import Queue from queue and return specific error\n # messages by putting them in the queue in this thread and checking\n # for them in the main thread.\n while True:\n try:\n _host = socket.gethostbyname('www.google.com')\n s = socket.create_connection((_host, 80), 2)\n except socket.gaierror:\n internet_on.clear()\n except Exception as e:\n internet_on.clear()\n else:\n internet_on.set()\n time.sleep(interval)\n\n\n_internet = Event()\n\n# set daemon to True so the thread automatically closes when your main program ends\nnew_thread = Thread(target=check_connection, args=(_internet, 5.0), daemon=True)\nnew_thread.start()\n\n# below is just an example so this code will execute\nif __name__ == '__main__':\n while True:\n time.sleep(0.5)\n print(f\"internet on = {_internet.is_set()}\")\n\n" ]
[ 0 ]
[]
[]
[ "kivy", "kivymd", "python_3.x" ]
stackoverflow_0074656253_kivy_kivymd_python_3.x.txt
Q: How to skip a ggplot2 code if it fails/errors - Need help writing extensible, fault-tolerant code Sample Data: dat <- structure(list(n_speed = c(7, 6, 5, 4, 7, 6, 4, 9), id = c("subj_1", "subj_1", "subj_1", "subj_1", "subj_2", "subj_2", "subj_2", "subj_2" ), timepoint = c("t1", "t1", "t2", "t2", "t1", "t1", "t2", "t2" ), direction = c("long", "lat", "long", "lat", "long", "lat", "long", "lat")), class = "data.frame", row.names = c(NA, -8L)) speed_measures <- structure(list(n_speed = c(7, 6, 5, 4, 7, 6, 4, 9), id = c("subj_1", "subj_1", "subj_1", "subj_1", "subj_2", "subj_2", "subj_2", "subj_2" ), timepoint = c("t1", "t1", "t2", "t2", "t1", "t1", "t2", "t2" ), direction = c("long", "lat", "long", "lat", "long", "lat", "long", "lat")), class = "data.frame", row.names = c(NA, -8L)) dat_combined <- speed_measures |> left_join(dat) I have code that looks like this: ggplot(data = dat_combined, aes(x = n_speed)) + geom_histogram() + facet_wrap(~direction) and am getting the following error: Error in `combine_vars()`: ! Faceting variables must have at least one value Backtrace: 1. base (local) `<fn>`(x) 2. ggplot2:::print.ggplot(x) 4. ggplot2:::ggplot_build.ggplot(x) 5. layout$setup(data, plot$data, plot$plot_env) 6. ggplot2 (local) setup(..., self = self) 7. self$facet$compute_layout(data, self$facet_params) 8. ggplot2 (local) compute_layout(..., self = self) 9. ggplot2::combine_vars(data, params$plot_env, vars, drop = params$drop) This is because the data I'm currently running does not contain the "factor" that facet_wrap is looking for. I am trying to make this code extensible so that I can run data where subjects may or may not have that "factor" available, and don't want to rewrite a seperate pipeline for this situation. I have attempted and failed with: try(ggplot(data = dat_combined, aes(x = n_speed)) + geom_histogram() + facet_wrap(~direction)) Edit: Final code used after all the input: if(is.na(dat_combined$n_speed[1])) { print("No Data") } else { ggplot(data = dat_combined, aes(x = n_speed)) + geom_histogram() + facet_wrap(~direction) } A: Because "Factor" DOES exist in the DF but is empty, we cannot use the "if("region" in names(dat_combined))" method. Instead, we can make sure that the column has no data by checking the first row. This could be a bit more elegant by checking that the entire column in empty, but for the structure I'm working with that's not necessary. Final Answer: if(is.na(dat_combined$n_speed[1])) { print("No Data") } else { ggplot(data = dat_combined, aes(x = n_speed)) + geom_histogram() + facet_wrap(~direction) }
How to skip a ggplot2 code if it fails/errors - Need help writing extensible, fault-tolerant code
Sample Data: dat <- structure(list(n_speed = c(7, 6, 5, 4, 7, 6, 4, 9), id = c("subj_1", "subj_1", "subj_1", "subj_1", "subj_2", "subj_2", "subj_2", "subj_2" ), timepoint = c("t1", "t1", "t2", "t2", "t1", "t1", "t2", "t2" ), direction = c("long", "lat", "long", "lat", "long", "lat", "long", "lat")), class = "data.frame", row.names = c(NA, -8L)) speed_measures <- structure(list(n_speed = c(7, 6, 5, 4, 7, 6, 4, 9), id = c("subj_1", "subj_1", "subj_1", "subj_1", "subj_2", "subj_2", "subj_2", "subj_2" ), timepoint = c("t1", "t1", "t2", "t2", "t1", "t1", "t2", "t2" ), direction = c("long", "lat", "long", "lat", "long", "lat", "long", "lat")), class = "data.frame", row.names = c(NA, -8L)) dat_combined <- speed_measures |> left_join(dat) I have code that looks like this: ggplot(data = dat_combined, aes(x = n_speed)) + geom_histogram() + facet_wrap(~direction) and am getting the following error: Error in `combine_vars()`: ! Faceting variables must have at least one value Backtrace: 1. base (local) `<fn>`(x) 2. ggplot2:::print.ggplot(x) 4. ggplot2:::ggplot_build.ggplot(x) 5. layout$setup(data, plot$data, plot$plot_env) 6. ggplot2 (local) setup(..., self = self) 7. self$facet$compute_layout(data, self$facet_params) 8. ggplot2 (local) compute_layout(..., self = self) 9. ggplot2::combine_vars(data, params$plot_env, vars, drop = params$drop) This is because the data I'm currently running does not contain the "factor" that facet_wrap is looking for. I am trying to make this code extensible so that I can run data where subjects may or may not have that "factor" available, and don't want to rewrite a seperate pipeline for this situation. I have attempted and failed with: try(ggplot(data = dat_combined, aes(x = n_speed)) + geom_histogram() + facet_wrap(~direction)) Edit: Final code used after all the input: if(is.na(dat_combined$n_speed[1])) { print("No Data") } else { ggplot(data = dat_combined, aes(x = n_speed)) + geom_histogram() + facet_wrap(~direction) }
[ "Because \"Factor\" DOES exist in the DF but is empty, we cannot use the \"if(\"region\" in names(dat_combined))\" method.\nInstead, we can make sure that the column has no data by checking the first row. This could be a bit more elegant by checking that the entire column in empty, but for the structure I'm working with that's not necessary.\nFinal Answer:\nif(is.na(dat_combined$n_speed[1])) { \n print(\"No Data\")\n} else {\n ggplot(data = dat_combined, aes(x = n_speed)) +\n geom_histogram() +\n facet_wrap(~direction)\n}\n\n" ]
[ 0 ]
[]
[]
[ "ggplot2", "r" ]
stackoverflow_0074660681_ggplot2_r.txt
Q: PHPMailer does NOT work on one of my GoDaddy servers - SMTP connect() failed On one of of my GoDaddy servers, the PHPMailer does NOT work. While the same script does work pretty fine on local as well as on another GoDaddy server. I'm using following script: <?php $to = "[email protected]"; $subject = "Test Subject"; $message = "Test email message"; require("PHPMailer/PHPMailerAutoload.php"); $mail = new PHPMailer(); $mail->SMTPDebug = 3; $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->SMTPSecure = "ssl"; $mail->SMTPOptions = array( "ssl" => array( "verify_peer" => false, "verify_peer_name" => false, "allow_self_signed" => false ) ); $mail->IsHTML(true); $mail->CharSet = "UTF-8"; $mail->Host = "smtp.gmail.com"; $mail->Port = 465; $mail->Username = "[email protected]"; $mail->Password = "password"; $mail->SetFrom("[email protected]", "Website Admin"); $mail->AddAddress($to, "Website Admin"); $mail->Subject = $subject; $mail->Body = "<html><body style='font-family:Arial, Helvetica, sans-serif;'>"; $mail->Body .= "<table>"; $mail->Body .= "<tr><th>Email:</th><td>$to</td></tr>"; $mail->Body .= "<tr><th>Message:</th><td>$message</td></tr>"; $mail->Body .= "</table>"; $mail->Body .= "</body></html>"; $mail->AltBody = "This is the body in plain text for non-HTML mail clients."; $mail->WordWrap = 70; if($mail->Send()) { echo "Mail sent"; } else { echo "Mailer Error: " . $mail->ErrorInfo; } ?> It gives me following error on GoDaddy: Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting I'm using PHPMailer version 5.2.27. I'm using app password for gmail account. If the script was buggy then how it could even work in another areas? How to fix it to work on that GoDaddy server too? I have already tried their host and port various combination and some other settings too. A: There are a few potential reasons why the PHPMailer script might not be working on your GoDaddy server. Here are a few things you can try to troubleshoot the issue: Make sure that the PHPMailer library is installed and configured properly on your GoDaddy server. This includes ensuring that the correct paths to the PHPMailer files are specified in your PHP script, and that all required dependencies are installed and configured properly. Check the server logs for any errors or messages related to the PHPMailer script. This can help you identify any specific issues that might be preventing the script from working properly. Try using a different SMTP server to send the email. For example, instead of using Gmail as your SMTP server, you could try using a different server (e.g., Outlook, Yahoo, etc.) to see if that resolves the issue. Make sure that the PHP script has the necessary permissions to access the SMTP server and send emails. This can sometimes be an issue on shared hosting environments, where the server may have strict security settings that prevent certain PHP scripts from accessing certain resources. If you're still having trouble, you may want to try contacting GoDaddy support for further assistance. They may be able to provide more specific guidance on why the PHPMailer script is not working on your server, and help you troubleshoot the issue.
PHPMailer does NOT work on one of my GoDaddy servers - SMTP connect() failed
On one of of my GoDaddy servers, the PHPMailer does NOT work. While the same script does work pretty fine on local as well as on another GoDaddy server. I'm using following script: <?php $to = "[email protected]"; $subject = "Test Subject"; $message = "Test email message"; require("PHPMailer/PHPMailerAutoload.php"); $mail = new PHPMailer(); $mail->SMTPDebug = 3; $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->SMTPSecure = "ssl"; $mail->SMTPOptions = array( "ssl" => array( "verify_peer" => false, "verify_peer_name" => false, "allow_self_signed" => false ) ); $mail->IsHTML(true); $mail->CharSet = "UTF-8"; $mail->Host = "smtp.gmail.com"; $mail->Port = 465; $mail->Username = "[email protected]"; $mail->Password = "password"; $mail->SetFrom("[email protected]", "Website Admin"); $mail->AddAddress($to, "Website Admin"); $mail->Subject = $subject; $mail->Body = "<html><body style='font-family:Arial, Helvetica, sans-serif;'>"; $mail->Body .= "<table>"; $mail->Body .= "<tr><th>Email:</th><td>$to</td></tr>"; $mail->Body .= "<tr><th>Message:</th><td>$message</td></tr>"; $mail->Body .= "</table>"; $mail->Body .= "</body></html>"; $mail->AltBody = "This is the body in plain text for non-HTML mail clients."; $mail->WordWrap = 70; if($mail->Send()) { echo "Mail sent"; } else { echo "Mailer Error: " . $mail->ErrorInfo; } ?> It gives me following error on GoDaddy: Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting I'm using PHPMailer version 5.2.27. I'm using app password for gmail account. If the script was buggy then how it could even work in another areas? How to fix it to work on that GoDaddy server too? I have already tried their host and port various combination and some other settings too.
[ "There are a few potential reasons why the PHPMailer script might not be working on your GoDaddy server. Here are a few things you can try to troubleshoot the issue:\n\nMake sure that the PHPMailer library is installed and configured\nproperly on your GoDaddy server. This includes ensuring that the\ncorrect paths to the PHPMailer files are specified in your PHP\nscript, and that all required dependencies are installed and\nconfigured properly.\n\nCheck the server logs for any errors or messages related to the\nPHPMailer script. This can help you identify any specific issues\nthat might be preventing the script from working properly.\n\nTry using a different SMTP server to send the email. For example,\ninstead of using Gmail as your SMTP server, you could try using a\ndifferent server (e.g., Outlook, Yahoo, etc.) to see if that\nresolves the issue.\n\nMake sure that the PHP script has the necessary permissions to\naccess the SMTP server and send emails. This can sometimes be an\nissue on shared hosting environments, where the server may have\nstrict security settings that prevent certain PHP scripts from\naccessing certain resources.\n\nIf you're still having trouble, you may want to try contacting\nGoDaddy support for further assistance. They may be able to provide\nmore specific guidance on why the PHPMailer script is not working on\nyour server, and help you troubleshoot the issue.\n\n\n" ]
[ 0 ]
[]
[]
[ "email", "php" ]
stackoverflow_0074667547_email_php.txt
Q: How to achieve in the same time properly work of React Routes on gh-pages and localhost? 404 when I go to any route. Well, regarding this thread I should change BrowserRouter to HashRouter. But if I do this my localhost routes stops working at all. Any suggestions how to achieve both? Or just to deploy it when development will be over? Or am I missing something? App.tsx import React from 'react'; import { Routes, Route } from 'react-router-dom'; import './styles/main.scss'; import { Footer } from './components/Footer'; import { Header } from './components/Header'; import { Catalog } from './components/Catalog'; import { Cart } from './components/Cart'; import { Favourites } from './components/Favourites'; const App: React.FC = () => { return ( <> <Header /> <Routes> <Route path='phones' element={<Catalog />} /> <Route path='favourites' element={<Favourites />} /> <Route path='cart' element={<Cart />} /> </Routes> <Footer /> </> ); }; Index.tsx import React from 'react'; import { HashRouter } from 'react-router-dom'; import ReactDOM from 'react-dom/client'; import App from './App'; import './styles/utils/reset.scss'; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement, ); root.render( <React.StrictMode> <HashRouter> <App /> </HashRouter> </React.StrictMode>, ); A: add / in the paths <Route path='/phones' element={<Catalog />} /> <Route path='/favourites' element={<Favourites />} /> <Route path='/cart' element={<Cart />} /> also add a default path for initial route <Route path='/' element={<YOUR_COMPONENT />} />
How to achieve in the same time properly work of React Routes on gh-pages and localhost?
404 when I go to any route. Well, regarding this thread I should change BrowserRouter to HashRouter. But if I do this my localhost routes stops working at all. Any suggestions how to achieve both? Or just to deploy it when development will be over? Or am I missing something? App.tsx import React from 'react'; import { Routes, Route } from 'react-router-dom'; import './styles/main.scss'; import { Footer } from './components/Footer'; import { Header } from './components/Header'; import { Catalog } from './components/Catalog'; import { Cart } from './components/Cart'; import { Favourites } from './components/Favourites'; const App: React.FC = () => { return ( <> <Header /> <Routes> <Route path='phones' element={<Catalog />} /> <Route path='favourites' element={<Favourites />} /> <Route path='cart' element={<Cart />} /> </Routes> <Footer /> </> ); }; Index.tsx import React from 'react'; import { HashRouter } from 'react-router-dom'; import ReactDOM from 'react-dom/client'; import App from './App'; import './styles/utils/reset.scss'; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement, ); root.render( <React.StrictMode> <HashRouter> <App /> </HashRouter> </React.StrictMode>, );
[ "add / in the paths\n <Route path='/phones' element={<Catalog />} />\n <Route path='/favourites' element={<Favourites />} />\n <Route path='/cart' element={<Cart />} />\n\nalso add a default path for initial route\n <Route path='/' element={<YOUR_COMPONENT />} /> \n\n" ]
[ 0 ]
[]
[]
[ "github_pages", "reactjs" ]
stackoverflow_0074667675_github_pages_reactjs.txt
Q: TCLab issues with python 3.10 (and python 3.9) OS: macOS 11.7.1 (Big Sur) A few months ago I purchased a TCLab kit and at the time did some very rudimentary tests where the device worked as expected. Recently I decided that I wanted to work on some of the APMonitor lessons and connected the TCLab to my computer expecting that it would work as it had done in the past. Sadly, that is not the case. I would like help in correcting the issues identified and getting the TCLab to work again. Originally, I had been using python 3.9. Since then python 3.10 came out and I installed it. Using the following script from APMonitor as my test, $ cat show_T1.py import tclab with tclab.TCLab() as lab: print(lab.T1) I got the errors documented below: $ python --version Python 3.10.8 $ python show_T1.py Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/show_T1.py", line 1, in <module> import tclab File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/__init__.py", line 2, in <module> from .historian import Historian, Plotter File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/historian.py", line 6, in <module> from collections import Iterable ImportError: cannot import name 'Iterable' from 'collections' (/usr/local/Cellar/[email protected]/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/collections/__init__.py) I was able to find the cause of this problem here: Stack Overflow It is an issue where Iterable was moved to collections.abc from collections. When I change the script to: $ cat show_T1.py import collections.abc collections.Iterable = collections.abc.Iterable collections.Mapping = collections.abc.Mapping collections.MutableSet = collections.abc.MutableSet collections.MutableMapping = collections.abc.MutableMapping import tclab with tclab.TCLab() as lab: print(lab.T1) the import error goes away. However, I now get new errors: $ python show_T1.py TCLab version 0.4.9 Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/tclab.py", line 64, in __init__ self.connect(baud=115200) File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/tclab.py", line 114, in connect self.sp = serial.Serial(port=self.port, baudrate=baud, timeout=2) AttributeError: module 'serial' has no attribute 'Serial' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/tclab.py", line 70, in __init__ self.sp.close() AttributeError: 'TCLab' object has no attribute 'sp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/show_T1.py", line 7, in <module> with tclab.TCLab() as lab: File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/tclab.py", line 77, in __init__ raise RuntimeError('Failed to Connect.') RuntimeError: Failed to Connect. Sadly, I get almost the same error as above if I revert back to python 3.9: (python 3.9 does not have the Iterable problem, so I reverted back to the original script): $ python --version Python 3.9.15 $ python show_T1.py TCLab version 0.4.9 Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv/lib/python3.9/site-packages/tclab/tclab.py", line 64, in __init__ self.connect(baud=115200) File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv/lib/python3.9/site-packages/tclab/tclab.py", line 114, in connect self.sp = serial.Serial(port=self.port, baudrate=baud, timeout=2) AttributeError: module 'serial' has no attribute 'Serial' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv/lib/python3.9/site-packages/tclab/tclab.py", line 70, in __init__ self.sp.close() AttributeError: 'TCLab' object has no attribute 'sp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/show_T1.py", line 2, in <module> with tclab.TCLab() as lab: File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv/lib/python3.9/site-packages/tclab/tclab.py", line 77, in __init__ raise RuntimeError('Failed to Connect.') RuntimeError: Failed to Connect. I know that at least I have connectivity to the device, because when I unplug the USB cable I get an error message that says, correctly, that no arduino is connected: $ python show_T1.py TCLab version 0.4.9 --- Serial Ports --- /dev/cu.Bluetooth-Incoming-Port n/a n/a Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/show_T1.py", line 2, in <module> with tclab.TCLab() as lab: File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv/lib/python3.9/site-packages/tclab/tclab.py", line 61, in __init__ raise RuntimeError('No Arduino device found.') RuntimeError: No Arduino device found. Below are the python modules I have installed under python 3.10 and 3.9: python 3.10: $ pip list Package Version ------------------ --------- blessed 1.19.1 bpython 0.23 certifi 2022.9.24 charset-normalizer 2.1.1 contourpy 1.0.6 curtsies 0.4.1 cwcwidth 0.1.8 cycler 0.11.0 fonttools 4.38.0 future 0.18.2 greenlet 2.0.1 idna 3.4 iso8601 1.1.0 kiwisolver 1.4.4 matplotlib 3.6.2 numpy 1.23.5 packaging 21.3 Pillow 9.3.0 pip 22.3.1 Pygments 2.13.0 pyparsing 3.0.9 pyserial 3.5 python-dateutil 2.8.2 pyxdg 0.28 PyYAML 6.0 requests 2.28.1 scipy 1.9.3 serial 0.0.97 setuptools 65.4.1 six 1.16.0 tclab 0.4.9 urllib3 1.26.13 wcwidth 0.2.5 python 3.9: $ pip list Package Version ------------------ --------- blessed 1.19.1 bpython 0.23 certifi 2022.9.24 charset-normalizer 2.1.1 contourpy 1.0.6 curtsies 0.4.1 cwcwidth 0.1.8 cycler 0.11.0 docopt 0.6.2 fonttools 4.38.0 future 0.18.2 greenlet 2.0.1 idna 3.4 iso8601 1.1.0 kiwisolver 1.4.4 matplotlib 3.6.2 numpy 1.23.5 packaging 21.3 Pillow 9.3.0 pip 22.3.1 pipreqs 0.4.11 Pygments 2.13.0 pyparsing 3.0.9 pyserial 3.5 python-dateutil 2.8.2 pyxdg 0.28 PyYAML 6.0 requests 2.28.1 scipy 1.9.3 serial 0.0.97 setuptools 65.4.1 six 1.16.0 tclab 0.4.9 urllib3 1.26.13 wcwidth 0.2.5 yarg 0.1.9 NOTE: I have send this issue to [email protected] A: Serial Connection Issue This error AttributeError: module 'serial' has no attribute 'Serial' suggests that the package serial or a local file name serial.py has a conflict with pyserial. Rename your file to something else besides serial.py and/or uninstall the serial package (not needed for TCLab). Your pyserial package is the latest version. pip uninstall serial The error occurs when there is a local file named serial.py and we import from the pyserial module. Additional common TCLab help issues are posted to the TCLab setup and troubleshooting page. Serial Port Permission If the serial uninstall doesn't fix the problem of allowing a serial connection, one other thing to check is the USB port permission. On Linux, discover the USB port name with ls /dev/tty* Set the permission for that USB connection with the correct name. sudo chmod a+rw /dev/ttyACM0 Python 3.10 Compatibility You correctly found the issue with installing the latest version of TCLab for Python 3.10 compatibility. The module developer is still working on the next version of the TCLab package. Until that point, you can either edit the historian.py file (path is in the error message) with a text editor and change from collections import Iterable to from collections.abc import Iterable or install the new package from GitHub: pip install --upgrade https://github.com/jckantor/TCLab/archive/master.zip This will be resolved with the next release of TCLab on PyPI.org. The current version is 0.4.9 that does not include Python 3.10 compatibility because of the Iterable package change.
TCLab issues with python 3.10 (and python 3.9)
OS: macOS 11.7.1 (Big Sur) A few months ago I purchased a TCLab kit and at the time did some very rudimentary tests where the device worked as expected. Recently I decided that I wanted to work on some of the APMonitor lessons and connected the TCLab to my computer expecting that it would work as it had done in the past. Sadly, that is not the case. I would like help in correcting the issues identified and getting the TCLab to work again. Originally, I had been using python 3.9. Since then python 3.10 came out and I installed it. Using the following script from APMonitor as my test, $ cat show_T1.py import tclab with tclab.TCLab() as lab: print(lab.T1) I got the errors documented below: $ python --version Python 3.10.8 $ python show_T1.py Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/show_T1.py", line 1, in <module> import tclab File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/__init__.py", line 2, in <module> from .historian import Historian, Plotter File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/historian.py", line 6, in <module> from collections import Iterable ImportError: cannot import name 'Iterable' from 'collections' (/usr/local/Cellar/[email protected]/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/collections/__init__.py) I was able to find the cause of this problem here: Stack Overflow It is an issue where Iterable was moved to collections.abc from collections. When I change the script to: $ cat show_T1.py import collections.abc collections.Iterable = collections.abc.Iterable collections.Mapping = collections.abc.Mapping collections.MutableSet = collections.abc.MutableSet collections.MutableMapping = collections.abc.MutableMapping import tclab with tclab.TCLab() as lab: print(lab.T1) the import error goes away. However, I now get new errors: $ python show_T1.py TCLab version 0.4.9 Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/tclab.py", line 64, in __init__ self.connect(baud=115200) File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/tclab.py", line 114, in connect self.sp = serial.Serial(port=self.port, baudrate=baud, timeout=2) AttributeError: module 'serial' has no attribute 'Serial' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/tclab.py", line 70, in __init__ self.sp.close() AttributeError: 'TCLab' object has no attribute 'sp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/show_T1.py", line 7, in <module> with tclab.TCLab() as lab: File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv3.10/lib/python3.10/site-packages/tclab/tclab.py", line 77, in __init__ raise RuntimeError('Failed to Connect.') RuntimeError: Failed to Connect. Sadly, I get almost the same error as above if I revert back to python 3.9: (python 3.9 does not have the Iterable problem, so I reverted back to the original script): $ python --version Python 3.9.15 $ python show_T1.py TCLab version 0.4.9 Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv/lib/python3.9/site-packages/tclab/tclab.py", line 64, in __init__ self.connect(baud=115200) File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv/lib/python3.9/site-packages/tclab/tclab.py", line 114, in connect self.sp = serial.Serial(port=self.port, baudrate=baud, timeout=2) AttributeError: module 'serial' has no attribute 'Serial' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv/lib/python3.9/site-packages/tclab/tclab.py", line 70, in __init__ self.sp.close() AttributeError: 'TCLab' object has no attribute 'sp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/show_T1.py", line 2, in <module> with tclab.TCLab() as lab: File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv/lib/python3.9/site-packages/tclab/tclab.py", line 77, in __init__ raise RuntimeError('Failed to Connect.') RuntimeError: Failed to Connect. I know that at least I have connectivity to the device, because when I unplug the USB cable I get an error message that says, correctly, that no arduino is connected: $ python show_T1.py TCLab version 0.4.9 --- Serial Ports --- /dev/cu.Bluetooth-Incoming-Port n/a n/a Traceback (most recent call last): File "/Users/USER/TClab/arduino/0_Test_Device/Python/show_T1.py", line 2, in <module> with tclab.TCLab() as lab: File "/Users/USER/TClab/arduino/0_Test_Device/Python/venv/lib/python3.9/site-packages/tclab/tclab.py", line 61, in __init__ raise RuntimeError('No Arduino device found.') RuntimeError: No Arduino device found. Below are the python modules I have installed under python 3.10 and 3.9: python 3.10: $ pip list Package Version ------------------ --------- blessed 1.19.1 bpython 0.23 certifi 2022.9.24 charset-normalizer 2.1.1 contourpy 1.0.6 curtsies 0.4.1 cwcwidth 0.1.8 cycler 0.11.0 fonttools 4.38.0 future 0.18.2 greenlet 2.0.1 idna 3.4 iso8601 1.1.0 kiwisolver 1.4.4 matplotlib 3.6.2 numpy 1.23.5 packaging 21.3 Pillow 9.3.0 pip 22.3.1 Pygments 2.13.0 pyparsing 3.0.9 pyserial 3.5 python-dateutil 2.8.2 pyxdg 0.28 PyYAML 6.0 requests 2.28.1 scipy 1.9.3 serial 0.0.97 setuptools 65.4.1 six 1.16.0 tclab 0.4.9 urllib3 1.26.13 wcwidth 0.2.5 python 3.9: $ pip list Package Version ------------------ --------- blessed 1.19.1 bpython 0.23 certifi 2022.9.24 charset-normalizer 2.1.1 contourpy 1.0.6 curtsies 0.4.1 cwcwidth 0.1.8 cycler 0.11.0 docopt 0.6.2 fonttools 4.38.0 future 0.18.2 greenlet 2.0.1 idna 3.4 iso8601 1.1.0 kiwisolver 1.4.4 matplotlib 3.6.2 numpy 1.23.5 packaging 21.3 Pillow 9.3.0 pip 22.3.1 pipreqs 0.4.11 Pygments 2.13.0 pyparsing 3.0.9 pyserial 3.5 python-dateutil 2.8.2 pyxdg 0.28 PyYAML 6.0 requests 2.28.1 scipy 1.9.3 serial 0.0.97 setuptools 65.4.1 six 1.16.0 tclab 0.4.9 urllib3 1.26.13 wcwidth 0.2.5 yarg 0.1.9 NOTE: I have send this issue to [email protected]
[ "Serial Connection Issue\nThis error AttributeError: module 'serial' has no attribute 'Serial' suggests that the package serial or a local file name serial.py has a conflict with pyserial. Rename your file to something else besides serial.py and/or uninstall the serial package (not needed for TCLab). Your pyserial package is the latest version.\npip uninstall serial\n\nThe error occurs when there is a local file named serial.py and we import from the pyserial module. Additional common TCLab help issues are posted to the TCLab setup and troubleshooting page.\n\nSerial Port Permission\nIf the serial uninstall doesn't fix the problem of allowing a serial connection, one other thing to check is the USB port permission. On Linux, discover the USB port name with ls /dev/tty* Set the permission for that USB connection with the correct name.\nsudo chmod a+rw /dev/ttyACM0\n\nPython 3.10 Compatibility\nYou correctly found the issue with installing the latest version of TCLab for Python 3.10 compatibility. The module developer is still working on the next version of the TCLab package. Until that point, you can either edit the historian.py file (path is in the error message) with a text editor and change from collections import Iterable to from collections.abc import Iterable or install the new package from GitHub:\npip install --upgrade https://github.com/jckantor/TCLab/archive/master.zip\n\nThis will be resolved with the next release of TCLab on PyPI.org. The current version is 0.4.9 that does not include Python 3.10 compatibility because of the Iterable package change.\n" ]
[ 1 ]
[]
[]
[ "iterable", "python" ]
stackoverflow_0074663465_iterable_python.txt
Q: Why doesn't type() work in if statements in Python? user_input = int(input('Enter input: ')) if type(user_input) == "<class 'int'>": print('This is a integer.') The code above outputs nothing to the console. I am just confused because it is very simple and looks like it should work. I've tried removing the int() in the input line which output nothing, I understand this because user_input turns into a string but I do not understand why it outputs nothing when user_input is defined as an integer. A: Fix That is because type(user_input) returns a type, not a string, don't confuse yourself with what you see printed and the real thing. When you print something you only see a representation of the thing. Only if it's a string you can copy and compare it directly print(type(type(user_input))) # <class 'type'> So you well understand, this is how it would work using type if str(type(user_input)) == "<class 'int'>": print('This is a integer.') if type(user_input) == int: print('This is a integer.') if type(user_input) is int: print('This is a integer.') Improve The prefered way should be if isinstance(user_input, int): print('This is a integer.') A: Its because you're comparing it to the wrong thing. if you did "type(user_input) == int" your program should work as expected. A: You can use the isinstance method as mentioned above or just directly compare to the int like: user_input = int(input('Enter input: ')) if type(user_input) is int: print('This is a integer.')
Why doesn't type() work in if statements in Python?
user_input = int(input('Enter input: ')) if type(user_input) == "<class 'int'>": print('This is a integer.') The code above outputs nothing to the console. I am just confused because it is very simple and looks like it should work. I've tried removing the int() in the input line which output nothing, I understand this because user_input turns into a string but I do not understand why it outputs nothing when user_input is defined as an integer.
[ "Fix\nThat is because type(user_input) returns a type, not a string, don't confuse yourself with what you see printed and the real thing. When you print something you only see a representation of the thing. Only if it's a string you can copy and compare it directly\nprint(type(type(user_input))) # <class 'type'>\n\nSo you well understand, this is how it would work using type\nif str(type(user_input)) == \"<class 'int'>\":\n print('This is a integer.')\n\nif type(user_input) == int:\n print('This is a integer.')\n\nif type(user_input) is int:\n print('This is a integer.')\n\nImprove\nThe prefered way should be\nif isinstance(user_input, int):\n print('This is a integer.')\n\n", "Its because you're comparing it to the wrong thing. if you did \"type(user_input) == int\" your program should work as expected.\n", "You can use the isinstance method as mentioned above or just directly compare to the int like: \nuser_input = int(input('Enter input: '))\n\nif type(user_input) is int:\n print('This is a integer.')\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "conditional_statements", "if_statement", "input", "python", "types" ]
stackoverflow_0074667623_conditional_statements_if_statement_input_python_types.txt
Q: joining two columns sql query world! I'm currently stuck on this problem where i want to join two columns and run the select statement of the two, but i'm getting errors; these are the columns i want to join: SELECT DISTINCT column_name FROM owner_name.table_name ORDER BY column_name; and SELECT DISTINCT * FROM (SELECT count(column_name) OVER (partition by column_name) Amount from owner_name.table_name order by column_name); where in the second, for every row, i count how many equal rows i have for each value. the two columns values: first column second column i dont know how to have both of them next to each other as a normal select statement: SELECT column_1, column_2 FROM table; A: SELECT DISTINCT column_name, COUNT(column_name) OVER (PARTITION BY column_name) Amount FROM owner_name.table_name ORDER BY column_name; A: You do not want to use an analytic function for this as you will find the COUNT for all the rows and then use DISTINCT to discard rows which involves lots of unnecessary calculation. Instead, it is much more efficient GROUP BY the column_name and then aggregate so that you only generate a single row for each group to start with: SELECT column_name, COUNT(column_name) AS amount FROM owner_name.table_name GROUP BY column_name ORDER BY column_name;
joining two columns sql query
world! I'm currently stuck on this problem where i want to join two columns and run the select statement of the two, but i'm getting errors; these are the columns i want to join: SELECT DISTINCT column_name FROM owner_name.table_name ORDER BY column_name; and SELECT DISTINCT * FROM (SELECT count(column_name) OVER (partition by column_name) Amount from owner_name.table_name order by column_name); where in the second, for every row, i count how many equal rows i have for each value. the two columns values: first column second column i dont know how to have both of them next to each other as a normal select statement: SELECT column_1, column_2 FROM table;
[ "SELECT DISTINCT\n column_name,\n COUNT(column_name) OVER (PARTITION BY column_name) Amount \nFROM owner_name.table_name \nORDER BY column_name;\n\n", "You do not want to use an analytic function for this as you will find the COUNT for all the rows and then use DISTINCT to discard rows which involves lots of unnecessary calculation.\nInstead, it is much more efficient GROUP BY the column_name and then aggregate so that you only generate a single row for each group to start with:\nSELECT column_name,\n COUNT(column_name) AS amount\nFROM owner_name.table_name\nGROUP BY column_name\nORDER BY column_name;\n\n" ]
[ 0, 0 ]
[]
[]
[ "oracle", "sql" ]
stackoverflow_0074666210_oracle_sql.txt
Q: How can I set a value in a cell to be range for a formula in vba excel? I have code that extracts the cell.address given the value and the range initially, but then I want it to look for a new value in a new range is only in the cell.address row number. I have added comments in the code to explain it better but in cell j3 I get the cell address for e.g $A$15 and in cell k3 i can get the row number using left, right function "15" and I want the range in second "set cell" function to change depending on either of those cells so if the first output is $A$20, I want the second function row to change to 20 Sub find() Dim a As Double Dim wks As Worksheet Dim b As Double Dim c As Integer Dim cell As Range Set wks = Worksheets("comefri") a = wks.Range("c8").value b = wks.Range("D7").value c = wks.Range("k4").value With comefri Set cell = Range("a:a").find(b, MatchCase:=Fasle, searchformat:=False) Range("j3").value = cell.Address ' I want the range row number to change depending on the value output form cell j3 or k3 Set cell = Range("CX15:GS15").find(a, MatchCase:=Fasle, searchformat:=False) Range("K3").value = cell.Address Range("k3").value = cell.Address End With End Sub Public Function ToColNum(ColN) ToColNum = Range(ColN & 1).Column End Function Function GetValue(row As Integer, col As Integer) GetValue = ActiveSheet.Cells(row, col) End Function A: Finding Cells Using the Find Method Option Explicit Sub FindValue() Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code Dim ws As Worksheet: Set ws = wb.Worksheets("comefri") With ws Dim cellB As Range: Set cellB = .Range("J3") Dim cellA As Range: Set cellA = .Range("K3") Dim B As Double: B = .Range("D7").Value Dim A As Double: A = .Range("C8").Value 'Dim C As Double: C = .Range("K4").Value ' not used at the moment Dim cell As Range With .Range("A:A") ' Reference the search column range. Set cell = .Find(B, .Cells(.Cells.Count), xlValues, xlWhole) End With If cell Is Nothing Then ' 'B' not found cellB.ClearContents cellA.ClearContents Exit Sub End If cellB.Value = cell.Address Dim FoundRow As Long: FoundRow = cell.Row With .Range("CX:GS").Rows(FoundRow) ' Reference the search row range. Set cell = .Find(A, .Cells(.Cells.Count), xlValues, xlWhole) End With If cell Is Nothing Then cellA.ClearContents: Exit Sub ' 'A' not found cellA.Value = cell.Address End With End Sub
How can I set a value in a cell to be range for a formula in vba excel?
I have code that extracts the cell.address given the value and the range initially, but then I want it to look for a new value in a new range is only in the cell.address row number. I have added comments in the code to explain it better but in cell j3 I get the cell address for e.g $A$15 and in cell k3 i can get the row number using left, right function "15" and I want the range in second "set cell" function to change depending on either of those cells so if the first output is $A$20, I want the second function row to change to 20 Sub find() Dim a As Double Dim wks As Worksheet Dim b As Double Dim c As Integer Dim cell As Range Set wks = Worksheets("comefri") a = wks.Range("c8").value b = wks.Range("D7").value c = wks.Range("k4").value With comefri Set cell = Range("a:a").find(b, MatchCase:=Fasle, searchformat:=False) Range("j3").value = cell.Address ' I want the range row number to change depending on the value output form cell j3 or k3 Set cell = Range("CX15:GS15").find(a, MatchCase:=Fasle, searchformat:=False) Range("K3").value = cell.Address Range("k3").value = cell.Address End With End Sub Public Function ToColNum(ColN) ToColNum = Range(ColN & 1).Column End Function Function GetValue(row As Integer, col As Integer) GetValue = ActiveSheet.Cells(row, col) End Function
[ "Finding Cells Using the Find Method\nOption Explicit\n\nSub FindValue()\n \n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n Dim ws As Worksheet: Set ws = wb.Worksheets(\"comefri\")\n \n With ws\n \n Dim cellB As Range: Set cellB = .Range(\"J3\")\n Dim cellA As Range: Set cellA = .Range(\"K3\")\n \n Dim B As Double: B = .Range(\"D7\").Value\n Dim A As Double: A = .Range(\"C8\").Value\n 'Dim C As Double: C = .Range(\"K4\").Value ' not used at the moment\n \n Dim cell As Range\n \n With .Range(\"A:A\") ' Reference the search column range.\n Set cell = .Find(B, .Cells(.Cells.Count), xlValues, xlWhole)\n End With\n \n If cell Is Nothing Then ' 'B' not found\n cellB.ClearContents\n cellA.ClearContents\n Exit Sub\n End If\n \n cellB.Value = cell.Address\n \n Dim FoundRow As Long: FoundRow = cell.Row\n \n With .Range(\"CX:GS\").Rows(FoundRow) ' Reference the search row range.\n Set cell = .Find(A, .Cells(.Cells.Count), xlValues, xlWhole)\n End With\n \n If cell Is Nothing Then cellA.ClearContents: Exit Sub ' 'A' not found\n \n cellA.Value = cell.Address\n \n End With\n \nEnd Sub\n\n" ]
[ 0 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0074659342_excel_vba.txt
Q: why 'set' function doesn't work in Jupyter when I write in cell set('hello') it raises error 'tuple' object is not callable
why 'set' function doesn't work in Jupyter
when I write in cell set('hello') it raises error 'tuple' object is not callable
[]
[]
[ "To set an env variable in a jupyter notebook, just use a % magic commands, either %env or %set_env , e.g., %env VAR = VALUE or %env VAR VALUE .\n" ]
[ -1 ]
[ "jupyter_notebook", "python", "set" ]
stackoverflow_0074667529_jupyter_notebook_python_set.txt
Q: Input 0 of layer "conv2d_5" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 2) I am trying to use CNN on multivariate time series instead the most common usage on images. The number of features is between 90 and 120, depending on which I need to consider and experiment with. This is my code scaler = StandardScaler() X_train_s = scaler.fit_transform(X_train) X_test_s = scaler.transform(X_test) X_train_s = X_train_s.reshape((X_train_s.shape[0], X_train_s.shape[1],1)) X_test_s = X_test_s.reshape((X_test_s.shape[0], X_test_s.shape[1],1)) batch_size = 1024 length = 120 n_features = X_train_s.shape[1] generator = TimeseriesGenerator(X_train_s, pd.DataFrame.to_numpy(Y_train[['TARGET_KEEP_LONG', 'TARGET_KEEP_SHORT']]), length=length, batch_size=batch_size) validation_generator = TimeseriesGenerator(X_test_s, pd.DataFrame.to_numpy(Y_test[['TARGET_KEEP_LONG', 'TARGET_KEEP_SHORT']]), length=length, batch_size=batch_size) early_stop = EarlyStopping(monitor = 'val_accuracy', mode = 'max', verbose = 1, patience = 20) CNN_model = Sequential() model.add( Conv2D( filters=64, kernel_size=(1, 5), strides=1, activation="relu", padding="valid", input_shape=(length, n_features, 1), use_bias=True, ) ) model.add(MaxPooling2D(pool_size=(1, 2))) model.add( Conv2D( filters=64, kernel_size=(1, 5), strides=1, activation="relu", padding="valid", use_bias=True, ) ) [... code continuation ...] In other words, I take the features as one dimension and a certain number of rows as the other dimension. But I get this error "ValueError: Input 0 of layer "conv2d_5" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 2)" that is referred to the first CNN layer. A: Data loading I have made a simple class that demonstrates a reasonable approach to doing so. Mind you, I am not that familiar with TensorFlow, mainly using PyTorch, so the code might not be optimized. You are probably best at defining a custom generator if one can't be used for this. After reading the comments, I noticed that you don't want to compute all ahead of time all the values; this would do so because we are only keeping the underlying data in self.data and creating new tensors based on this. import tensorflow as tf import numpy as np v = np.array([[12055., 11430., 10966., 12055., 11430., 10966.], [11430., 10966., 10725., 11430., 10966., 10725.], [10966., 10725., 10672.,10966., 10725., 10672.]]) q = tf.constant(v) class MyData(): def __init__(self, data, windows_size): self.data = data self.windows_size = windows_size self._dataset = tf.data.Dataset.from_generator(self._generator, output_types=tf.float32, output_shapes=(self.windows_size, self.data.shape[1])) def _generator(self): for i in range(self.data.shape[0] - self.windows_size + 1): yield self.data[i:i+self.windows_size] def __len__(self): return self.data.shape[0] - self.windows_size + 1 def get_dataset(self): return self._dataset # Example usage: test = MyData(q, 2) it = iter(test.get_dataset()) for data in it: print(data.shape) This produces tensors that have a windows_size for the first dimension. The code was made to work with [N, DATA] -> [W, DATA], where N is for the time_series, and W is for the reduced window size; I added part of the example code from the previous link. Model design Multiple design decisions can be made for the model design. Firstly, you can treat it as an embedding problem (Embedding layer). Then you can reshape it to use with your 2D convolutions. The second approach is to reshape the data into something resembling 2D images directly. Note that the second approach will be bad if the sequence length changes between different examples. You cannot batchify the training without modifying the network (adding extra layers to process images depending on the size is not relatively straightforward). Lastly, there already exist tutorials that do such things with features of time series data, shown below: def basic_conv2D(n_filters=10, fsize=5, window_size=5, n_features=2): new_model = keras.Sequential() new_model.add(tf.keras.layers.Conv2D(n_filters, (1,fsize), padding=”same”, activation=”relu”, input_shape=(window_size, n_features, 1))) new_model.add(tf.keras.layers.Flatten()) new_model.add(tf.keras.layers.Dense(1000, activation=’relu’)) new_model.add(tf.keras.layers.Dense(100)) new_model.add(tf.keras.layers.Dense(1)) new_model.compile(optimizer=”adam”, loss=”mean_squared_error”) return new_model m2 = basic_conv2D(n_filters=24, fsize=2, window_size=window_size, n_features=data_train_wide.shape[2]) m2.summary()
Input 0 of layer "conv2d_5" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 2)
I am trying to use CNN on multivariate time series instead the most common usage on images. The number of features is between 90 and 120, depending on which I need to consider and experiment with. This is my code scaler = StandardScaler() X_train_s = scaler.fit_transform(X_train) X_test_s = scaler.transform(X_test) X_train_s = X_train_s.reshape((X_train_s.shape[0], X_train_s.shape[1],1)) X_test_s = X_test_s.reshape((X_test_s.shape[0], X_test_s.shape[1],1)) batch_size = 1024 length = 120 n_features = X_train_s.shape[1] generator = TimeseriesGenerator(X_train_s, pd.DataFrame.to_numpy(Y_train[['TARGET_KEEP_LONG', 'TARGET_KEEP_SHORT']]), length=length, batch_size=batch_size) validation_generator = TimeseriesGenerator(X_test_s, pd.DataFrame.to_numpy(Y_test[['TARGET_KEEP_LONG', 'TARGET_KEEP_SHORT']]), length=length, batch_size=batch_size) early_stop = EarlyStopping(monitor = 'val_accuracy', mode = 'max', verbose = 1, patience = 20) CNN_model = Sequential() model.add( Conv2D( filters=64, kernel_size=(1, 5), strides=1, activation="relu", padding="valid", input_shape=(length, n_features, 1), use_bias=True, ) ) model.add(MaxPooling2D(pool_size=(1, 2))) model.add( Conv2D( filters=64, kernel_size=(1, 5), strides=1, activation="relu", padding="valid", use_bias=True, ) ) [... code continuation ...] In other words, I take the features as one dimension and a certain number of rows as the other dimension. But I get this error "ValueError: Input 0 of layer "conv2d_5" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 2)" that is referred to the first CNN layer.
[ "Data loading\nI have made a simple class that demonstrates a reasonable approach to doing so. Mind you, I am not that familiar with TensorFlow, mainly using PyTorch, so the code might not be optimized.\nYou are probably best at defining a custom generator if one can't be used for this. After reading the comments, I noticed that you don't want to compute all ahead of time all the values; this would do so because we are only keeping the underlying data in self.data and creating new tensors based on this.\nimport tensorflow as tf\nimport numpy as np\nv = np.array([[12055., 11430., 10966., 12055., 11430., 10966.], \n [11430., 10966., 10725., 11430., 10966., 10725.],\n [10966., 10725., 10672.,10966., 10725., 10672.]])\nq = tf.constant(v)\nclass MyData():\n\n def __init__(self, data, windows_size):\n self.data = data\n self.windows_size = windows_size\n self._dataset = tf.data.Dataset.from_generator(self._generator,\n output_types=tf.float32,\n output_shapes=(self.windows_size, self.data.shape[1]))\n\n def _generator(self):\n for i in range(self.data.shape[0] - self.windows_size + 1):\n yield self.data[i:i+self.windows_size]\n \n def __len__(self):\n return self.data.shape[0] - self.windows_size + 1\n\n def get_dataset(self):\n return self._dataset\n# Example usage:\ntest = MyData(q, 2)\nit = iter(test.get_dataset())\n\nfor data in it:\n print(data.shape)\n\nThis produces tensors that have a windows_size for the first dimension. The code was made to work with [N, DATA] -> [W, DATA], where N is for the time_series, and W is for the reduced window size; I added part of the example code from the previous link.\nModel design\nMultiple design decisions can be made for the model design.\nFirstly, you can treat it as an embedding problem (Embedding layer). Then you can reshape it to use with your 2D convolutions.\nThe second approach is to reshape the data into something resembling 2D images directly. Note that the second approach will be bad if the sequence length changes between different examples. You cannot batchify the training without modifying the network (adding extra layers to process images depending on the size is not relatively straightforward).\nLastly, there already exist tutorials that do such things with features of time series data, shown below:\ndef basic_conv2D(n_filters=10, fsize=5, window_size=5, n_features=2):\n new_model = keras.Sequential()\n new_model.add(tf.keras.layers.Conv2D(n_filters, (1,fsize), padding=”same”, activation=”relu”, input_shape=(window_size, n_features, 1)))\n new_model.add(tf.keras.layers.Flatten())\n new_model.add(tf.keras.layers.Dense(1000, activation=’relu’))\n new_model.add(tf.keras.layers.Dense(100))\n new_model.add(tf.keras.layers.Dense(1))\n new_model.compile(optimizer=”adam”, loss=”mean_squared_error”) \n return new_model\nm2 = basic_conv2D(n_filters=24, fsize=2, window_size=window_size, n_features=data_train_wide.shape[2])\nm2.summary()\n\n" ]
[ 0 ]
[]
[]
[ "conv_neural_network", "python" ]
stackoverflow_0074590804_conv_neural_network_python.txt
Q: rust reading lines amount file and iterating over them I am attempting to write a program that shortens a file to n lines. I have difficulties regarding reading the lines of the file, and then enumerating over them after. Expectedly the iterator does not work if count() is called on it and then iterated with due to the nature of count() count(): Consumes the iterator, counting the number of iterations and returning it. However, creating two separate buffers from the file produces similar results? let path = Path::new(&args[1]); let file_result = OpenOptions::new().read(true).open(path); let file = match file_result { Ok(file) => file, Err(error) => { panic!("failed to open file: {}", error.to_string()); } }; let lines_amount = BufReader::new(&file).lines().count(); if lines_amount == 0 { panic!("The file has no lines"); } println!("{}", lines_amount); // this will not iterate, no matter the amount of lines in the file for (i, line_result) in BufReader::new(&file).lines().enumerate() { ... } Opening two files and create a buffer from each seems to produce the same results. Why does this happen, and how do I read the amount of lines of a file as well as iterating over it? A: You have to seek to the beginning in between uses of a File or you'll continue reading where the last read left off. It is a little hidden here because the Read on &File uses interior mutability and is equivalent to the one on File. let path = Path::new(&args[1]); let file_result = OpenOptions::new().read(true).open(path); let mut file = match file_result { Ok(file) => file, Err(error) => { panic!("failed to open file: {}", error.to_string()); } }; let lines_amount = BufReader::new(&file).lines().count(); if lines_amount == 0 { panic!("The file has no lines"); } println!("{}", lines_amount); // reset files position to start file.seek( std::io::SeekFrom::Start(0)); for (i, line_result) in BufReader::new(&file).lines().enumerate() { ... }
rust reading lines amount file and iterating over them
I am attempting to write a program that shortens a file to n lines. I have difficulties regarding reading the lines of the file, and then enumerating over them after. Expectedly the iterator does not work if count() is called on it and then iterated with due to the nature of count() count(): Consumes the iterator, counting the number of iterations and returning it. However, creating two separate buffers from the file produces similar results? let path = Path::new(&args[1]); let file_result = OpenOptions::new().read(true).open(path); let file = match file_result { Ok(file) => file, Err(error) => { panic!("failed to open file: {}", error.to_string()); } }; let lines_amount = BufReader::new(&file).lines().count(); if lines_amount == 0 { panic!("The file has no lines"); } println!("{}", lines_amount); // this will not iterate, no matter the amount of lines in the file for (i, line_result) in BufReader::new(&file).lines().enumerate() { ... } Opening two files and create a buffer from each seems to produce the same results. Why does this happen, and how do I read the amount of lines of a file as well as iterating over it?
[ "You have to seek to the beginning in between uses of a File or you'll continue reading where the last read left off.\nIt is a little hidden here because the Read on &File uses interior mutability and is equivalent to the one on File.\nlet path = Path::new(&args[1]);\n\nlet file_result = OpenOptions::new().read(true).open(path);\n\nlet mut file = match file_result {\n Ok(file) => file,\n Err(error) => {\n panic!(\"failed to open file: {}\", error.to_string());\n }\n};\n\nlet lines_amount = BufReader::new(&file).lines().count();\n\nif lines_amount == 0 {\n panic!(\"The file has no lines\");\n}\n\nprintln!(\"{}\", lines_amount);\n\n// reset files position to start\nfile.seek( std::io::SeekFrom::Start(0));\n\nfor (i, line_result) in BufReader::new(&file).lines().enumerate() {\n ...\n}\n\n" ]
[ 2 ]
[]
[]
[ "file", "line", "rust" ]
stackoverflow_0074667471_file_line_rust.txt
Q: DependencyInjection throw error when compiling with IL2CPP in unity for linux server I am using the following code in a Utils script and calling this variable each time I want to create a HttpClient: public static IHttpClientFactory httpClientFactory = new ServiceCollection().AddHttpClient().BuildServiceProvider().GetService<System.Net.Http.IHttpClientFactory>(); I have included all the dependencies under the plugins folder such the Microsoft.Extensions.DependencyInjection.dll and its respective dependencies dlls. When compiled with mono scripting backend the game server runs fine. the problem when compiling with IL2CPP I get the following error and the program seems to halt: ArgumentNullException: Value cannot be null. Parameter name: obj at System.Threading.Monitor.ReliableEnterTimeout (System.Object obj, System.Int32 timeout, System.Boolean& lockTaken) [0x00000] in <00000000000000000000000000000000>:0 at System.Threading.Monitor.ReliableEnter (System.Object obj, System.Boolean& lockTaken) [0x00000] in <00000000000000000000000000000000>:0 at System.Threading.Monitor.Enter (System.Object obj, System.Boolean& lockTaken) [0x00000] in <00000000000000000000000000000000>:0 at Microsoft.Extensions.DependencyInjection.DependencyInjectionEventSource.ServiceProviderBuilt (Microsoft.Extensions.DependencyInjection.ServiceProvider provider) [0x00000] in <00000000000000000000000000000000>:0 at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor (System.Collections.Generic.ICollection`1[T] serviceDescriptors, Microsoft.Extensions.DependencyInjection.ServiceProviderOptions options) [0x00000] in <00000000000000000000000000000000>:0 at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider (Microsoft.Extensions.DependencyInjection.IServiceCollection services, Microsoft.Extensions.DependencyInjection.ServiceProviderOptions options) [0x00000] in <00000000000000000000000000000000>:0 at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider (Microsoft.Extensions.DependencyInjection.IServiceCollection services) [0x00000] in <00000000000000000000000000000000>:0 at Utils..cctor () [0x00000] in <00000000000000000000000000000000>:0 at Myscript.Awake () [0x00000] in <00000000000000000000000000000000>:0 Rethrow as TypeInitializationException: The type initializer for 'Utils' threw an exception. at Myscript.Awake () [0x00000] in <00000000000000000000000000000000>:0 I tried different methods I included the Link.xml file in my assets folder reading the following but the same error keep popping out: <linker> <assembly fullname="System.Core"> <type fullname="System.Linq.Expressions.Interpreter.LightLambda" preserve="all" /> </assembly> <assembly fullname="Plugins/Microsoft.Extensions.Http" preserve="all" /> <assembly fullname="Plugins/Microsoft.Extensions.Logging.Abstractions" preserve="all" /> //The rest of the dlls included in the plugins folder declared in the same manner... </linker> A: Since the variable is static the when of initialization is complicated and could vary between platforms. My suspicion is that initialization is occurring too soon before all of the IHttpClientFactory dependencies are ready. Could you try delaying initialization to test if this is the culprit? Something like. // don't initialize here ... public static IHttpClientFactory httpClientFactory; // ... put this immediately before the first use of httpClientFactory if (httpClientFactory == null) { httpClientFactory = new ServiceCollection().AddHttpClient().BuildServiceProvider().GetService<System.Net.Http.IHttpClientFactory>(); } // first use of httpClientFactory httpClientFactory.DoSomething();
DependencyInjection throw error when compiling with IL2CPP in unity for linux server
I am using the following code in a Utils script and calling this variable each time I want to create a HttpClient: public static IHttpClientFactory httpClientFactory = new ServiceCollection().AddHttpClient().BuildServiceProvider().GetService<System.Net.Http.IHttpClientFactory>(); I have included all the dependencies under the plugins folder such the Microsoft.Extensions.DependencyInjection.dll and its respective dependencies dlls. When compiled with mono scripting backend the game server runs fine. the problem when compiling with IL2CPP I get the following error and the program seems to halt: ArgumentNullException: Value cannot be null. Parameter name: obj at System.Threading.Monitor.ReliableEnterTimeout (System.Object obj, System.Int32 timeout, System.Boolean& lockTaken) [0x00000] in <00000000000000000000000000000000>:0 at System.Threading.Monitor.ReliableEnter (System.Object obj, System.Boolean& lockTaken) [0x00000] in <00000000000000000000000000000000>:0 at System.Threading.Monitor.Enter (System.Object obj, System.Boolean& lockTaken) [0x00000] in <00000000000000000000000000000000>:0 at Microsoft.Extensions.DependencyInjection.DependencyInjectionEventSource.ServiceProviderBuilt (Microsoft.Extensions.DependencyInjection.ServiceProvider provider) [0x00000] in <00000000000000000000000000000000>:0 at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor (System.Collections.Generic.ICollection`1[T] serviceDescriptors, Microsoft.Extensions.DependencyInjection.ServiceProviderOptions options) [0x00000] in <00000000000000000000000000000000>:0 at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider (Microsoft.Extensions.DependencyInjection.IServiceCollection services, Microsoft.Extensions.DependencyInjection.ServiceProviderOptions options) [0x00000] in <00000000000000000000000000000000>:0 at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider (Microsoft.Extensions.DependencyInjection.IServiceCollection services) [0x00000] in <00000000000000000000000000000000>:0 at Utils..cctor () [0x00000] in <00000000000000000000000000000000>:0 at Myscript.Awake () [0x00000] in <00000000000000000000000000000000>:0 Rethrow as TypeInitializationException: The type initializer for 'Utils' threw an exception. at Myscript.Awake () [0x00000] in <00000000000000000000000000000000>:0 I tried different methods I included the Link.xml file in my assets folder reading the following but the same error keep popping out: <linker> <assembly fullname="System.Core"> <type fullname="System.Linq.Expressions.Interpreter.LightLambda" preserve="all" /> </assembly> <assembly fullname="Plugins/Microsoft.Extensions.Http" preserve="all" /> <assembly fullname="Plugins/Microsoft.Extensions.Logging.Abstractions" preserve="all" /> //The rest of the dlls included in the plugins folder declared in the same manner... </linker>
[ "Since the variable is static the when of initialization is complicated and could vary between platforms. My suspicion is that initialization is occurring too soon before all of the IHttpClientFactory dependencies are ready. Could you try delaying initialization to test if this is the culprit? Something like.\n// don't initialize here ...\npublic static IHttpClientFactory httpClientFactory;\n\n// ... put this immediately before the first use of httpClientFactory\nif (httpClientFactory == null) {\n httpClientFactory = new ServiceCollection().AddHttpClient().BuildServiceProvider().GetService<System.Net.Http.IHttpClientFactory>();\n}\n// first use of httpClientFactory\nhttpClientFactory.DoSomething();\n\n" ]
[ 0 ]
[]
[]
[ "il2cpp", "unity3d" ]
stackoverflow_0073833227_il2cpp_unity3d.txt
Q: How to mock Azure Storage Account in C# using Moq? I have a service IBlobService : publicΒ interfaceΒ IBlobService { publicΒ Task<BlobInfo>Β GetBlobAsync(stringΒ name); Β Β Β Β publicΒ Task<IEnumerable<string>>Β ListBlobsAsync(); Β Β Β Β publicΒ TaskΒ UploadFileBlobAsync(stringΒ filePath,Β stringΒ fileName); Β Β Β Β publicΒ TaskΒ UploadContentBlobAsync(stringΒ content,Β stringΒ fileName); Β Β Β Β publicΒ TaskΒ DeleteBlobAsync(stringΒ blobName); } Here is the implementation of the GetBlobAsync method within my BlobService class: publicΒ asyncΒ Task<BlobInfo>Β GetBlobAsync(stringΒ name) { varΒ clientΒ =Β _blobContainerClient.GetBlobClient(name); Β Β Β Β varΒ blobDownloadInfoΒ =Β awaitΒ client.DownloadContentAsync(); Β Β Β Β returnΒ newΒ BlobInfo(blobDownloadInfo.Value.Content,Β blobDownloadInfo.Value.Details.ContentType); } I am trying to figure out how I can use Moq to implement my test. I am relatively new to Moq. Any ideas or guidance? I have tried to review this blog https://devblogs.microsoft.com/azure-sdk/unit-testing-and-mocking/ but i'm still finding myself stuck. I am trying to figure out the best way to implement my test. A: If you want to make a unit test for testing the blobservice or a class using the IblobService ? If it's a class using your IBlobService then you need to mock the IBlobService like this ... public void Test1() { var blobServiceMocked = new Mock<IBlobService>(); blobServiceMocked.Setup(e => e.GetBlobAsync(It.IsAny<string>()).Returns(new BlobInfo(){ ... }); blobServiceMocked.Object; ... // assert _methodThatTakesIBlobservice(blobServiceMocked.Object); ...
How to mock Azure Storage Account in C# using Moq?
I have a service IBlobService : publicΒ interfaceΒ IBlobService { publicΒ Task<BlobInfo>Β GetBlobAsync(stringΒ name); Β Β Β Β publicΒ Task<IEnumerable<string>>Β ListBlobsAsync(); Β Β Β Β publicΒ TaskΒ UploadFileBlobAsync(stringΒ filePath,Β stringΒ fileName); Β Β Β Β publicΒ TaskΒ UploadContentBlobAsync(stringΒ content,Β stringΒ fileName); Β Β Β Β publicΒ TaskΒ DeleteBlobAsync(stringΒ blobName); } Here is the implementation of the GetBlobAsync method within my BlobService class: publicΒ asyncΒ Task<BlobInfo>Β GetBlobAsync(stringΒ name) { varΒ clientΒ =Β _blobContainerClient.GetBlobClient(name); Β Β Β Β varΒ blobDownloadInfoΒ =Β awaitΒ client.DownloadContentAsync(); Β Β Β Β returnΒ newΒ BlobInfo(blobDownloadInfo.Value.Content,Β blobDownloadInfo.Value.Details.ContentType); } I am trying to figure out how I can use Moq to implement my test. I am relatively new to Moq. Any ideas or guidance? I have tried to review this blog https://devblogs.microsoft.com/azure-sdk/unit-testing-and-mocking/ but i'm still finding myself stuck. I am trying to figure out the best way to implement my test.
[ "If you want to make a unit test for testing the blobservice or a class using the IblobService ?\nIf it's a class using your IBlobService then you need to mock the IBlobService\nlike this\n\n...\npublic void Test1() {\n var blobServiceMocked = new Mock<IBlobService>();\n blobServiceMocked.Setup(e => e.GetBlobAsync(It.IsAny<string>()).Returns(new BlobInfo(){ ... }); \nblobServiceMocked.Object;\n... \n\n// assert\n _methodThatTakesIBlobservice(blobServiceMocked.Object);\n...\n\n\n" ]
[ 0 ]
[]
[]
[ ".net", "azure", "c#", "rest" ]
stackoverflow_0074658579_.net_azure_c#_rest.txt
Q: SqlAlchemy AsyncSession transaction When using async session as context manager, what happens is if an exception raises, I get a warning that I wanna get rid of. here's how I use the session: async with session.begin(): retailer: model.Retailer = (await session.scalars(select(model.Retailer).filter(model.Retailer.name=="default"))).first() await session.execute(insert(model.Contact).values(mock_contact(retailer.uuid))) raise RuntimeError() and the warning that I get is: RuntimeWarning: coroutine 'Transaction.rollback' was never awaited I'm sure what I'm supposed to do and the twist here should be a little tricky because I surfed the net for any possible solution and none worked A: The warning message you are seeing, RuntimeWarning: coroutine 'Transaction.rollback' was never awaited, is indicating that you are using an async context manager (async with session.begin()) but you are not awaiting the rollback of the transaction if an exception is raised. In your code, you are using an async context manager to manage a database transaction. This means that the transaction will be automatically committed when the context manager exits normally, but it will be rolled back if an exception is raised. However, because you are not awaiting the rollback of the transaction, the Transaction.rollback coroutine is never actually executed and the warning message is displayed. To fix this issue, you can simply add an await statement to the Transaction.rollback coroutine. Here's an example of how you could do this: async with session.begin() as txn: retailer: model.Retailer = (await session.scalars(select(model.Retailer).filter(model.Retailer.name=="default"))).first() await session.execute(insert(model.Contact).values(mock_contact(retailer.uuid))) raise RuntimeError() # await the rollback of the transaction await txn.rollback()
SqlAlchemy AsyncSession transaction
When using async session as context manager, what happens is if an exception raises, I get a warning that I wanna get rid of. here's how I use the session: async with session.begin(): retailer: model.Retailer = (await session.scalars(select(model.Retailer).filter(model.Retailer.name=="default"))).first() await session.execute(insert(model.Contact).values(mock_contact(retailer.uuid))) raise RuntimeError() and the warning that I get is: RuntimeWarning: coroutine 'Transaction.rollback' was never awaited I'm sure what I'm supposed to do and the twist here should be a little tricky because I surfed the net for any possible solution and none worked
[ "The warning message you are seeing, RuntimeWarning: coroutine 'Transaction.rollback' was never awaited, is indicating that you are using an async context manager (async with session.begin()) but you are not awaiting the rollback of the transaction if an exception is raised.\nIn your code, you are using an async context manager to manage a database transaction. This means that the transaction will be automatically committed when the context manager exits normally, but it will be rolled back if an exception is raised. However, because you are not awaiting the rollback of the transaction, the Transaction.rollback coroutine is never actually executed and the warning message is displayed.\nTo fix this issue, you can simply add an await statement to the Transaction.rollback coroutine. Here's an example of how you could do this:\nasync with session.begin() as txn:\n retailer: model.Retailer = (await session.scalars(select(model.Retailer).filter(model.Retailer.name==\"default\"))).first()\n await session.execute(insert(model.Contact).values(mock_contact(retailer.uuid)))\n raise RuntimeError()\n # await the rollback of the transaction\n await txn.rollback()\n\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074667608_python_sqlalchemy.txt
Q: MySQL2 returning connection log I am attempting to get data from my MySQL databse but it returns [ [ '_events', [Object: null prototype] {} ], [ '_eventsCount', 0 ], [ '_maxListeners', undefined ], [ 'next', [Function: resultsetHeader] ], [ 'sql', 'SELECT * FROM dutylogs ORDER BY time DESC;' ], [ 'values', undefined ], [ '_queryOptions', { rowsAsArray: false, sql: 'SELECT * FROM dutylogs ORDER BY time DESC;', values: undefined } ], [ 'namedPlaceholders', false ], [ 'onResult', [Function (anonymous)] ], [ 'timeout', undefined ], [ 'queryTimeout', null ], [ '_fieldCount', 0 ], [ '_rowParser', null ], [ '_fields', [] ], [ '_rows', [] ], [ '_receivedFieldsCount', 0 ], [ '_resultIndex', 0 ], [ '_localStream', null ], [ '_unpipeStream', [Function (anonymous)] ], [ '_streamFactory', undefined ], [ '_connection', Connection { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, config: [ConnectionConfig], stream: [Socket], _internalId: 0, _commands: [Denque], _command: [Query], _paused: false, _paused_packets: [Denque], _statements: [LRUCache], serverCapabilityFlags: 2181036030, authorized: true, sequenceId: 1, compressedSequenceId: 0, threadId: 4009, _handshakePacket: [Handshake], _fatalError: null, _protocolError: null, _outOfOrderPackets: [], clientEncoding: 'utf8', packetParser: [PacketParser], serverEncoding: 'utf8', connectTimeout: null, connectionId: 4009, [Symbol(kCapture)]: false } ], [ 'options', { isServer: undefined, stream: undefined, host: 'REDACTED', port: 3306, localAddress: undefined, socketPath: undefined, user: 'REDACTED', password: 'REDACTED', passwordSha1: undefined, database: 'REDACTED', connectTimeout: 10000, insecureAuth: false, supportBigNumbers: false, bigNumberStrings: false, decimalNumbers: false, dateStrings: false, debug: undefined, trace: true, stringifyObjects: false, enableKeepAlive: false, keepAliveInitialDelay: 0, timezone: 'local', queryFormat: undefined, pool: undefined, ssl: false, multipleStatements: false, rowsAsArray: false, namedPlaceholders: false, nestTables: undefined, typeCast: true, maxPacketSize: 0, charsetNumber: 224, compress: false, authPlugins: undefined, authSwitchHandler: undefined, clientFlags: 11203535, connectAttributes: undefined, maxPreparedStatements: 16000, sql: 'SELECT * FROM dutylogs ORDER BY time DESC;', values: undefined } ] ] From just reading that I can tell it is a connection log, but it doesn't help me much as I am really looking for something like below [ { key: 7044, name: '~y~Ten~g~Creator~r~[RIP]', id: '518334475038359555', dept: 'SAHP', time: 33, lastclockin: '2022/11/25 22:30:06' }, { key: 7042, name: '~y~Ten~g~Creator~r~[RIP]', id: '518334475038359555', dept: 'STAFF', time: 2, lastclockin: '2022/11/25 21:49:30' }, { key: 7043, name: '~y~Ten~g~Creator~r~[RIP]', id: '518334475038359555', dept: 'BCSO', time: 1, lastclockin: '2022/11/25 21:52:58' } ] I am using the EJS view engine to render this but I have the code divided into a router, this was mainly to keep my code clean, more jargen to meet stack overflow's requirements! const express = require('express') const config = require('../config.json') const mysql = require('mysql2') const router = express.Router(); let print = console.log const sql = mysql.createConnection({ host: config.sql.host, user: config.sql.user, password: config.sql.pass, database: config.sql.database, port: config.sql.port }) sql.connect() router.get('/:deptName', (req, res) => { let dept = req.params.deptName // print(Object.entries(getUnits(dept))) res.render('index', { siteName : dept, serverName : config.serverName, navEnabled : config.NavEnabled, NavBtns : config.NavBtns, deptList : config.departments, viewDept : true, dept : dept, units : Object.entries(getUnits(dept)) }) }) function getUnits (dept) { let sqlQuery = `SELECT * FROM dutylogs ORDER BY time DESC;` let unitGetter = sql.query(sqlQuery, (err, res, field)=>{ if (err) throw err print(res) return res }) return unitGetter } module.exports = router A: I managed to fix it by putting this on line 5 let units = []; and setting a time-out before I render the index! setTimeout(()=>{ res.render('index', { siteName : dept, serverName : config.serverName, navEnabled : config.NavEnabled, NavBtns : config.NavBtns, deptList : config.departments, viewDept : true, dept : dept, units : units }) }, 10) then afterwards I had changed the function to set the units value to its response function getUnits (dept) { let sqlQuery = `SELECT * FROM dutylogs WHERE dept="${dept}" ORDER BY time DESC;` let unitGetter = sql.query(sqlQuery, (err, res, field)=>{ if (err) throw err units = res }) }
MySQL2 returning connection log
I am attempting to get data from my MySQL databse but it returns [ [ '_events', [Object: null prototype] {} ], [ '_eventsCount', 0 ], [ '_maxListeners', undefined ], [ 'next', [Function: resultsetHeader] ], [ 'sql', 'SELECT * FROM dutylogs ORDER BY time DESC;' ], [ 'values', undefined ], [ '_queryOptions', { rowsAsArray: false, sql: 'SELECT * FROM dutylogs ORDER BY time DESC;', values: undefined } ], [ 'namedPlaceholders', false ], [ 'onResult', [Function (anonymous)] ], [ 'timeout', undefined ], [ 'queryTimeout', null ], [ '_fieldCount', 0 ], [ '_rowParser', null ], [ '_fields', [] ], [ '_rows', [] ], [ '_receivedFieldsCount', 0 ], [ '_resultIndex', 0 ], [ '_localStream', null ], [ '_unpipeStream', [Function (anonymous)] ], [ '_streamFactory', undefined ], [ '_connection', Connection { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, config: [ConnectionConfig], stream: [Socket], _internalId: 0, _commands: [Denque], _command: [Query], _paused: false, _paused_packets: [Denque], _statements: [LRUCache], serverCapabilityFlags: 2181036030, authorized: true, sequenceId: 1, compressedSequenceId: 0, threadId: 4009, _handshakePacket: [Handshake], _fatalError: null, _protocolError: null, _outOfOrderPackets: [], clientEncoding: 'utf8', packetParser: [PacketParser], serverEncoding: 'utf8', connectTimeout: null, connectionId: 4009, [Symbol(kCapture)]: false } ], [ 'options', { isServer: undefined, stream: undefined, host: 'REDACTED', port: 3306, localAddress: undefined, socketPath: undefined, user: 'REDACTED', password: 'REDACTED', passwordSha1: undefined, database: 'REDACTED', connectTimeout: 10000, insecureAuth: false, supportBigNumbers: false, bigNumberStrings: false, decimalNumbers: false, dateStrings: false, debug: undefined, trace: true, stringifyObjects: false, enableKeepAlive: false, keepAliveInitialDelay: 0, timezone: 'local', queryFormat: undefined, pool: undefined, ssl: false, multipleStatements: false, rowsAsArray: false, namedPlaceholders: false, nestTables: undefined, typeCast: true, maxPacketSize: 0, charsetNumber: 224, compress: false, authPlugins: undefined, authSwitchHandler: undefined, clientFlags: 11203535, connectAttributes: undefined, maxPreparedStatements: 16000, sql: 'SELECT * FROM dutylogs ORDER BY time DESC;', values: undefined } ] ] From just reading that I can tell it is a connection log, but it doesn't help me much as I am really looking for something like below [ { key: 7044, name: '~y~Ten~g~Creator~r~[RIP]', id: '518334475038359555', dept: 'SAHP', time: 33, lastclockin: '2022/11/25 22:30:06' }, { key: 7042, name: '~y~Ten~g~Creator~r~[RIP]', id: '518334475038359555', dept: 'STAFF', time: 2, lastclockin: '2022/11/25 21:49:30' }, { key: 7043, name: '~y~Ten~g~Creator~r~[RIP]', id: '518334475038359555', dept: 'BCSO', time: 1, lastclockin: '2022/11/25 21:52:58' } ] I am using the EJS view engine to render this but I have the code divided into a router, this was mainly to keep my code clean, more jargen to meet stack overflow's requirements! const express = require('express') const config = require('../config.json') const mysql = require('mysql2') const router = express.Router(); let print = console.log const sql = mysql.createConnection({ host: config.sql.host, user: config.sql.user, password: config.sql.pass, database: config.sql.database, port: config.sql.port }) sql.connect() router.get('/:deptName', (req, res) => { let dept = req.params.deptName // print(Object.entries(getUnits(dept))) res.render('index', { siteName : dept, serverName : config.serverName, navEnabled : config.NavEnabled, NavBtns : config.NavBtns, deptList : config.departments, viewDept : true, dept : dept, units : Object.entries(getUnits(dept)) }) }) function getUnits (dept) { let sqlQuery = `SELECT * FROM dutylogs ORDER BY time DESC;` let unitGetter = sql.query(sqlQuery, (err, res, field)=>{ if (err) throw err print(res) return res }) return unitGetter } module.exports = router
[ "I managed to fix it by putting this on line 5\nlet units = [];\n\nand setting a time-out before I render the index!\n setTimeout(()=>{\n res.render('index', {\n siteName : dept,\n serverName : config.serverName,\n navEnabled : config.NavEnabled,\n NavBtns : config.NavBtns,\n deptList : config.departments,\n viewDept : true,\n dept : dept,\n units : units\n })\n }, 10)\n\nthen afterwards I had changed the function to set the units value to its response\nfunction getUnits (dept) {\n let sqlQuery = `SELECT * FROM dutylogs WHERE dept=\"${dept}\" ORDER BY time DESC;`\n\n let unitGetter = sql.query(sqlQuery, (err, res, field)=>{\n if (err) throw err\n units = res\n })\n}\n\n" ]
[ 0 ]
[]
[]
[ "express", "javascript", "mysql", "node.js" ]
stackoverflow_0074659570_express_javascript_mysql_node.js.txt
Q: Cast ListView Items to List in C# I need to store the current listview items in a new object list just after I removed an element from listview. This is my schema.cs public class Show { public class Show { public Show() { } public int OrdNum { get; set; } public DateTime DTshow { get; set; } public string values { get; set; } public int practice_Number { get; set; } } } The problem is in Takenshows.cs I don't know how to cast listview items to List< Show> after deleting an element from listview. This is the button where I press and I remove an existing element from listview: //Takenshows.cs... public List<Show> myShows; public TakenShows() { InitializeComponent(); lvwColumnSorter = new ListViewColumnSorter(); this.listView1.ListViewItemSorter = lvwColumnSorter; myShows = new List<Show>(); } private void button1_Click(object sender, EventArgs e) { c = 0; if (listView1.SelectedItems != null) { for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].Selected) { DialogResult dr = MessageBox.Show("Are you sure you want to remove the element?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); switch (dr) { case DialogResult.Yes: listView1.Items[i].Remove(); i--; for (int j = 0; j < listView1.Items.Count; j++) { c = c + 1; listView1.Items[j].SubItems[0].Text = c.ToString(); } f = Int32.Parse(c.ToString()); // HERE's THE PROBLEM I need to cast my selected items from list view to object list ( List<Show>) and store those in myShows typed List<Show> Data myShows = listView1.SelectedItems.Cast<ListViewItem>().Select(x => x.OrdNum, x.DTshow, x.values, x.practice_Number).ToList(); var frm2 = Application.OpenForms.OfType<Main>().First(); if (frm2 != null) { frm2.devCont(); frm2.devcontlist(f); } break; case DialogResult.No: break; } } } } } would have to do something like this: //BUT this code not works myShows = listView1.SelectedItems.Cast<ListViewItem>().Select(x => x.OrdNum,x.DTshow,x.values,x.practice_Number).ToList(); I need when I'm removing an existing element from listview items, update the listview with the elements stayed after I removed one of them without including the element I removed. The listview has to update after I remove an existing element from listview and it has to store in a < Show> list. How Can I do that? I've tried all possible ways but it's almost impossible. A: The ListViewItem Class does not have OrdNum, DTshow, etc. properties of your data model. You could add your model to the Tag property of the item when adding a new ListView item like this ListViewItem item = new ListViewItem(); item.Tag = show; item.Text = show.TheText; //TODO: add subitems listView1.Items.Add(item); Then you can retrieve the data like this: myShows = listView1.SelectedItems.Cast<ListViewItem>() .Select(lvi => (Show)lvi.Tag) .ToList();
Cast ListView Items to List in C#
I need to store the current listview items in a new object list just after I removed an element from listview. This is my schema.cs public class Show { public class Show { public Show() { } public int OrdNum { get; set; } public DateTime DTshow { get; set; } public string values { get; set; } public int practice_Number { get; set; } } } The problem is in Takenshows.cs I don't know how to cast listview items to List< Show> after deleting an element from listview. This is the button where I press and I remove an existing element from listview: //Takenshows.cs... public List<Show> myShows; public TakenShows() { InitializeComponent(); lvwColumnSorter = new ListViewColumnSorter(); this.listView1.ListViewItemSorter = lvwColumnSorter; myShows = new List<Show>(); } private void button1_Click(object sender, EventArgs e) { c = 0; if (listView1.SelectedItems != null) { for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].Selected) { DialogResult dr = MessageBox.Show("Are you sure you want to remove the element?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); switch (dr) { case DialogResult.Yes: listView1.Items[i].Remove(); i--; for (int j = 0; j < listView1.Items.Count; j++) { c = c + 1; listView1.Items[j].SubItems[0].Text = c.ToString(); } f = Int32.Parse(c.ToString()); // HERE's THE PROBLEM I need to cast my selected items from list view to object list ( List<Show>) and store those in myShows typed List<Show> Data myShows = listView1.SelectedItems.Cast<ListViewItem>().Select(x => x.OrdNum, x.DTshow, x.values, x.practice_Number).ToList(); var frm2 = Application.OpenForms.OfType<Main>().First(); if (frm2 != null) { frm2.devCont(); frm2.devcontlist(f); } break; case DialogResult.No: break; } } } } } would have to do something like this: //BUT this code not works myShows = listView1.SelectedItems.Cast<ListViewItem>().Select(x => x.OrdNum,x.DTshow,x.values,x.practice_Number).ToList(); I need when I'm removing an existing element from listview items, update the listview with the elements stayed after I removed one of them without including the element I removed. The listview has to update after I remove an existing element from listview and it has to store in a < Show> list. How Can I do that? I've tried all possible ways but it's almost impossible.
[ "The ListViewItem Class does not have OrdNum, DTshow, etc. properties of your data model. You could add your model to the Tag property of the item when adding a new ListView item like this\nListViewItem item = new ListViewItem();\nitem.Tag = show;\nitem.Text = show.TheText;\n//TODO: add subitems\nlistView1.Items.Add(item);\n\nThen you can retrieve the data like this:\nmyShows = listView1.SelectedItems.Cast<ListViewItem>()\n .Select(lvi => (Show)lvi.Tag)\n .ToList();\n\n" ]
[ 1 ]
[]
[]
[ "c#", "c#_4.0", "listview", "listviewitem" ]
stackoverflow_0074667458_c#_c#_4.0_listview_listviewitem.txt
Q: chart.js PHP to JS string conversion question I am querying wordpress ACF fieldsdata which needs to plot into a chart.js radar type chart. <?php // Query posts $args = array( 'post_type' => 'resultaten', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'cursus', 'field' => 'slug', 'terms' => 'vitaliteitsscan' ), array( 'taxonomy' => 'client', 'field' => 'name', 'terms' => 'Bedrijf b', ), ), 'posts_per_page' => -1, 'orderby' => 'date', 'order' => 'DESC', ); $query = new WP_Query( $args ); $total = $query->found_posts; //echo $total; // Set empty array for dataset $row = array(); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); // Here we have the ACF fields per post (it's a form) results of calculation is a number $autonomie = ((get_field( 'vitaliteit_stelling_1') + get_field( 'vitaliteit_stelling_2') + get_field( 'vitaliteit_stelling_3') + get_field( 'vitaliteit_stelling_4'))/4); $competentie = ((get_field( 'vitaliteit_stelling_5') + get_field( 'vitaliteit_stelling_6') + get_field( 'vitaliteit_stelling_7') + get_field( 'vitaliteit_stelling_8'))/4); $verbondenheid = ((get_field( 'vitaliteit_stelling_9') + get_field( 'vitaliteit_stelling_10') + get_field( 'vitaliteit_stelling_11') + get_field( 'vitaliteit_stelling_12'))/4); $vrijheid = ((get_field( 'vitaliteit_stelling_13') + get_field( 'vitaliteit_stelling_14') + get_field( 'vitaliteit_stelling_15') + get_field( 'vitaliteit_stelling_16'))/4); $welbevinden = ((get_field( 'vitaliteit_stelling_17') + get_field( 'vitaliteit_stelling_18') + get_field( 'vitaliteit_stelling_19') + get_field( 'vitaliteit_stelling_20'))/4); $energie = ((get_field( 'vitaliteit_stelling_21') + get_field( 'vitaliteit_stelling_22') + get_field( 'vitaliteit_stelling_23') + get_field( 'vitaliteit_stelling_24'))/4); // Construct the dataset array $row[] = array( 'label' => "Uitslag", 'backgroundColor' => "rgba(146,196,213,0.2)", 'data' => "$autonomie, $competentie, $verbondenheid, $vrijheid, $welbevinden, $energie", ); } } wp_reset_postdata(); //echo print_r($row); $work = json_encode($row); //echo $work; ?> <script> var marksCanvas = document.getElementById("myChart"); var marksData = { labels: ["Autonomie", "Competentie", "Sociale verbondenheid", "Fysieke vrijheid", "Emotioneel welbevinden", "Energie"], // Now here i want the above array to output the retrieved data in the below format datasets: [{ label: "Uitslag", backgroundColor: "rgba(146,196,213,0.2)", data: [49.75, 51, 23.5, 48.25, 27.5, 61.75], }, { label: "Uitslag", backgroundColor: "rgba(146,196,213,0.2)", data: [69.75, 21, 73.5, 68.25, 37.5, 11.75], }], }; // This plots the chart on the canvas var radarChart = new Chart(marksCanvas, { type: 'radar', data: marksData, options: { scales: { r: { suggestedMin: 0, suggestedMax: 100 } } } }); </script> The array output i get with the above code is: [{"label":"uitslag","backgroundColor":"rgba(146,196,213,0.2)","data":"49.75, 51, 23.5, 48.25, 27.5, 61.75"},{"label":"uitslag","backgroundColor":"rgba(146,196,213,0.2)","data":"50.25, 43.5, 39.25, 55.5, 25.5, 33.5"}] Which needs to become [{label:"uitslag",backgroundColor:"rgba(146,196,213,0.2)",data:[49.75, 51, 23.5, 48.25, 27.5, 61.75]},{label:"uitslag",backgroundColor:"rgba(146,196,213,0.2)",data:[50.25, 43.5, 39.25, 55.5, 25.5, 33.5]}] Pulling my hair out (and i have none :-p) how to get rid of the double quotes in the json_encode. A small donation for a ready to implement solution is possible as these parts take me too much time from completing the total website. Joep A: The issue is, that you are constructing the data property of the $row[] as string and not as an array. See below, how to fix this issue: ... $row[] = array( 'label' => "Uitslag", 'backgroundColor' => "rgba(146,196,213,0.2)", 'data' => array($autonomie, $competentie, $verbondenheid, $vrijheid, $welbevinden, $energie) ); ... Then the json should be constructed correct, and the chart should work. Tipp: Just construct your desired data - structure, in the usual PHP fashion (as needed), and than pass it to the function json_encode. It will do the heavy lifting, of converting it into valid json.
chart.js PHP to JS string conversion question
I am querying wordpress ACF fieldsdata which needs to plot into a chart.js radar type chart. <?php // Query posts $args = array( 'post_type' => 'resultaten', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'cursus', 'field' => 'slug', 'terms' => 'vitaliteitsscan' ), array( 'taxonomy' => 'client', 'field' => 'name', 'terms' => 'Bedrijf b', ), ), 'posts_per_page' => -1, 'orderby' => 'date', 'order' => 'DESC', ); $query = new WP_Query( $args ); $total = $query->found_posts; //echo $total; // Set empty array for dataset $row = array(); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); // Here we have the ACF fields per post (it's a form) results of calculation is a number $autonomie = ((get_field( 'vitaliteit_stelling_1') + get_field( 'vitaliteit_stelling_2') + get_field( 'vitaliteit_stelling_3') + get_field( 'vitaliteit_stelling_4'))/4); $competentie = ((get_field( 'vitaliteit_stelling_5') + get_field( 'vitaliteit_stelling_6') + get_field( 'vitaliteit_stelling_7') + get_field( 'vitaliteit_stelling_8'))/4); $verbondenheid = ((get_field( 'vitaliteit_stelling_9') + get_field( 'vitaliteit_stelling_10') + get_field( 'vitaliteit_stelling_11') + get_field( 'vitaliteit_stelling_12'))/4); $vrijheid = ((get_field( 'vitaliteit_stelling_13') + get_field( 'vitaliteit_stelling_14') + get_field( 'vitaliteit_stelling_15') + get_field( 'vitaliteit_stelling_16'))/4); $welbevinden = ((get_field( 'vitaliteit_stelling_17') + get_field( 'vitaliteit_stelling_18') + get_field( 'vitaliteit_stelling_19') + get_field( 'vitaliteit_stelling_20'))/4); $energie = ((get_field( 'vitaliteit_stelling_21') + get_field( 'vitaliteit_stelling_22') + get_field( 'vitaliteit_stelling_23') + get_field( 'vitaliteit_stelling_24'))/4); // Construct the dataset array $row[] = array( 'label' => "Uitslag", 'backgroundColor' => "rgba(146,196,213,0.2)", 'data' => "$autonomie, $competentie, $verbondenheid, $vrijheid, $welbevinden, $energie", ); } } wp_reset_postdata(); //echo print_r($row); $work = json_encode($row); //echo $work; ?> <script> var marksCanvas = document.getElementById("myChart"); var marksData = { labels: ["Autonomie", "Competentie", "Sociale verbondenheid", "Fysieke vrijheid", "Emotioneel welbevinden", "Energie"], // Now here i want the above array to output the retrieved data in the below format datasets: [{ label: "Uitslag", backgroundColor: "rgba(146,196,213,0.2)", data: [49.75, 51, 23.5, 48.25, 27.5, 61.75], }, { label: "Uitslag", backgroundColor: "rgba(146,196,213,0.2)", data: [69.75, 21, 73.5, 68.25, 37.5, 11.75], }], }; // This plots the chart on the canvas var radarChart = new Chart(marksCanvas, { type: 'radar', data: marksData, options: { scales: { r: { suggestedMin: 0, suggestedMax: 100 } } } }); </script> The array output i get with the above code is: [{"label":"uitslag","backgroundColor":"rgba(146,196,213,0.2)","data":"49.75, 51, 23.5, 48.25, 27.5, 61.75"},{"label":"uitslag","backgroundColor":"rgba(146,196,213,0.2)","data":"50.25, 43.5, 39.25, 55.5, 25.5, 33.5"}] Which needs to become [{label:"uitslag",backgroundColor:"rgba(146,196,213,0.2)",data:[49.75, 51, 23.5, 48.25, 27.5, 61.75]},{label:"uitslag",backgroundColor:"rgba(146,196,213,0.2)",data:[50.25, 43.5, 39.25, 55.5, 25.5, 33.5]}] Pulling my hair out (and i have none :-p) how to get rid of the double quotes in the json_encode. A small donation for a ready to implement solution is possible as these parts take me too much time from completing the total website. Joep
[ "The issue is, that you are constructing the data property of the $row[] as string and not as an array. See below, how to fix this issue:\n...\n$row[] = \n array(\n 'label' => \"Uitslag\",\n 'backgroundColor' => \"rgba(146,196,213,0.2)\",\n 'data' => array($autonomie, $competentie, $verbondenheid, $vrijheid, $welbevinden, $energie)\n );\n ...\n\nThen the json should be constructed correct, and the chart should work.\n\nTipp: Just construct your desired data - structure, in the usual PHP fashion (as needed), and than pass it to the function json_encode. It will do the heavy lifting, of converting it into valid json.\n\n" ]
[ 1 ]
[]
[]
[ "arrays", "chart.js", "javascript", "json", "php" ]
stackoverflow_0074667106_arrays_chart.js_javascript_json_php.txt
Q: How do I get PHP errors to display? I have checked my PHP ini file (php.ini) and display_errors is set and also error reporting is E_ALL. I have restarted my Apache webserver. I have even put these lines at the top of my script, and it doesn't even catch simple parse errors. For example, I declare variables with a "$" and I don't close statements";". But all my scripts show a blank page on these errors, but I want to actually see the errors in my browser output. error_reporting(E_ALL); ini_set('display_errors', 1); What is left to do? A: This always works for me: ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); However, this doesn't make PHP to show parse errors - the only way to show those errors is to modify your php.ini with this line: display_errors = on (if you don't have access to php.ini, then putting this line in .htaccess might work too): php_flag display_errors 1 A: You can't catch parse errors when enabling error output at runtime, because it parses the file before actually executing anything (and since it encounters an error during this, it won't execute anything). You'll need to change the actual server configuration so that display_errors is on and the approriate error_reporting level is used. If you don't have access to php.ini, you may be able to use .htaccess or similar, depending on the server. This question may provide additional info. A: Inside your php.ini: display_errors = on Then restart your web server. A: To display all errors you need to: 1. Have these lines in the PHP script you're calling from the browser (typically index.php): error_reporting(E_ALL); ini_set('display_errors', '1'); 2.(a) Make sure that this script has no syntax errors β€”orβ€” 2.(b) Set display_errors = On in your php.ini Otherwise, it can't even run those 2 lines! You can check for syntax errors in your script by running (at the command line): php -l index.php If you include the script from another PHP script then it will display syntax errors in the included script. For example: index.php error_reporting(E_ALL); ini_set('display_errors', '1'); // Any syntax errors here will result in a blank screen in the browser include 'my_script.php'; my_script.php adjfkj // This syntax error will be displayed in the browser A: Some web hosting providers allow you to change PHP parameters in the .htaccess file. You can add the following line: php_value display_errors 1 I had the same issue as yours and this solution fixed it. A: You might find all of the settings for "error reporting" or "display errors" do not appear to work in PHPΒ 7. That is because error handling has changed. Try this instead: try{ // Your code } catch(Error $e) { $trace = $e->getTrace(); echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line']; } Or, to catch exceptions and errors in one go (this is not backward compatible with PHPΒ 5): try{ // Your code } catch(Throwable $e) { $trace = $e->getTrace(); echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line']; } A: This will work: <?php error_reporting(E_ALL); ini_set('display_errors', 1); ?> A: Use: ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); This is the best way to write it, but a syntax error gives blank output, so use the console to check for syntax errors. The best way to debug PHP code is to use the console; run the following: php -l phpfilename.php A: Set this in your index.php file: ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); A: Create a file called php.ini in the folder where your PHP file resides. Inside php.ini add the following code (I am giving an simple error showing code): display_errors = on display_startup_errors = on A: I would usually go with the following code in my plain PHP projects. if(!defined('ENVIRONMENT')){ define('ENVIRONMENT', 'DEVELOPMENT'); } $base_url = null; if (defined('ENVIRONMENT')) { switch (ENVIRONMENT) { case 'DEVELOPMENT': $base_url = 'http://localhost/product/'; ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL|E_STRICT); break; case 'PRODUCTION': $base_url = 'Production URL'; /* https://google.com */ error_reporting(0); /* Mechanism to log errors */ break; default: exit('The application environment is not set correctly.'); } } A: As we are now running PHP 7, answers given here are not correct any more. The only one still OK is the one from Frank Forte, as he talks about PHPΒ 7. On the other side, rather than trying to catch errors with a try/catch you can use a trick: use include. Here three pieces of code: File: tst1.php <?php error_reporting(E_ALL); ini_set('display_errors', 'On'); // Missing " and ; echo "Testing ?> Running this in PHPΒ 7 will show nothing. Now, try this: File: tst2.php <?php error_reporting(E_ALL); ini_set('display_errors', 'On'); include ("tst3.php"); ?> File: tst3.php <?php // Missing " and ; echo "Testing ?> Now run tst2 which sets the error reporting, and then include tst3. You will see: Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in tst3.php on line 4 A: If, despite following all of the above answers (or you can't edit your php.ini file), you still can't get an error message, try making a new PHP file that enables error reporting and then include the problem file. eg: error_reporting(E_ALL); ini_set('display_errors', 1); require_once('problem_file.php'); Despite having everything set properly in my php.ini file, this was the only way I could catch a namespace error. My exact scenario was: //file1.php namespace a\b; class x { ... } //file2.php namespace c\d; use c\d\x; //Dies because it's not sure which 'x' class to use class x { ... } A: If you somehow find yourself in a situation where you can't modifiy the setting via php.ini or .htaccess you're out of luck for displaying errors when your PHP scripts contain parse errors. You'd then have to resolve to linting the files on the command line like this: find . -name '*.php' -type f -print0 | xargs -0 -n1 -P8 php -l | grep -v "No syntax errors" If your host is so locked down that it does not allow changing the value via php.ini or .htaccess, it may also disallow changing the value via ini_set. You can check that with the following PHP script: <?php if( !ini_set( 'display_errors', 1 ) ) { echo "display_errors cannot be set."; } else { echo "changing display_errors via script is possible."; } A: You can do something like below: Set the below parameters in your main index file: ini_set('display_errors', 1); ini_set('display_startup_errors', 1); Then based on your requirement you can choose which you want to show: For all errors, warnings and notices: error_reporting(E_ALL); OR error_reporting(-1); For all errors: error_reporting(E_ERROR); For all warnings: error_reporting(E_WARNING); For all notices: error_reporting(E_NOTICE); For more information, check here. A: You can add your own custom error handler, which can provide extra debug information. Furthermore, you can set it up to send you the information via email. function ERR_HANDLER($errno, $errstr, $errfile, $errline){ $msg = "<b>Something bad happened.</b> [$errno] $errstr <br><br> <b>File:</b> $errfile <br> <b>Line:</b> $errline <br> <pre>".json_encode(debug_backtrace(), JSON_PRETTY_PRINT)."</pre> <br>"; echo $msg; return false; } function EXC_HANDLER($exception){ ERR_HANDLER(0, $exception->getMessage(), $exception->getFile(), $exception->getLine()); } function shutDownFunction() { $error = error_get_last(); if ($error["type"] == 1) { ERR_HANDLER($error["type"], $error["message"], $error["file"], $error["line"]); } } set_error_handler ("ERR_HANDLER", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED); register_shutdown_function("shutdownFunction"); set_exception_handler("EXC_HANDLER"); A: Accepted asnwer including extra options. In PHP files for in my DEVELOPMENT apache vhost (.htaccess if you can ensure it doesn't get into production): ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); However, this doesn't make PHP to show parse errors - the only way to show those errors is to modify your php.ini with this line: display_errors = on (if you don't have access to php.ini, then putting this line in .htaccess might work too): // I've added some extra options that set E_ALL as per https://www.php.net/manual/en/errorfunc.configuration.php. php_flag log_errors on php_flag display_errors on php_flag display_startup_errors on php_value error_reporting 2147483647 php_value error_log /var/www/mywebsite.ext/logs/php.error.log A: This code on top should work: error_reporting(E_ALL); However, try to edit the code on the phone in the file: error_reporting =on A: The best/easy/fast solution that you can use if it's a quick debugging, is to surround your code with catching exceptions. That's what I'm doing when I want to check something fast in production. try { // Page code } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } A: <?php // Turn off error reporting error_reporting(0); // Report runtime errors error_reporting(E_ERROR | E_WARNING | E_PARSE); // Report all errors error_reporting(E_ALL); // Same as error_reporting(E_ALL); ini_set("error_reporting", E_ALL); // Report all errors except E_NOTICE error_reporting(E_ALL & ~E_NOTICE); ?> While your site is live, the php.ini file should have display_errors disabled for security reasons. However, for the development environment, display_errors can be enabled for troubleshooting. A: Just write: error_reporting(-1); A: You can do this by changing the php.ini file and add the following display_errors = on display_startup_errors = on OR you can also use the following code as this always works for me ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); A: If you have Xdebug installed you can override every setting by setting: xdebug.force_display_errors = 1; xdebug.force_error_reporting = -1; force_display_errors Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this setting is set to 1 then errors will always be displayed, no matter what the setting of PHP's display_errors is. force_error_reporting Type: int, Default value: 0, Introduced in Xdebug >= 2.3 This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set(). A: You might want to use this code: ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); A: If it is on the command line, you can run php with -ddisplay_errors=1 to override the setting in php.ini: php -ddisplay_errors=1 script.php A: Report all errors except E_NOTICE error_reporting(E_ALL & ~E_NOTICE); Display all PHP errors error_reporting(E_ALL); or ini_set('error_reporting', E_ALL); Turn off all error reporting error_reporting(0); A: error_reporting(1); ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); Put this at the top of your page. A: Input this on the top of your code ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); And in the php.ini file, insert this: display_errors = on This must work. A: In Unix CLI, it's very practical to redirect only errors to a file: ./script 2> errors.log From your script, either use var_dump() or equivalent as usual (both STDOUT and STDERR will receive the output), but to write only in the log file: fwrite(STDERR, "Debug infos\n"); // Write in errors.log^ Then from another shell, for live changes: tail -f errors.log or simply watch cat errors.log A: You can show Php error in your display via simple ways. Firstly, just put this below code in your php.ini file. display_errors = on; (if you don't have access to php.ini, then putting this line in .htaccess might work too): php_flag display_errors 1 OR you can also use the following code in your index.php file ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); A: If you are on a SharedHosting plan (like on hostgator)... simply adding php_flag display_errors 1 into a .htaccess file and uploading it to the remote folder may not yield the actual warnings/errors that were generated on the server. What you will also need to do is edit the php.ini This is how you do it via cPanel (tested on hostgator shared hosting plan) After logging into your cPanel, search for MultiPHP INI Editor. It is usually found under the SOFTWARE section in your cPanel list of items. On the MultiPHP INI Editor page ...you can stay on the basic mode tab and just check the button on the line that says display_errors. Then click the Apply button to save. IMPORTANT: Just remember to turn it back off when you are done debugging; because this is not recommended for public servers. A: As it is not clear what OS you are on these are my 2 Windows cents. If you are using XAMPP you need to manually create the logs folder under C:\xampp\php. Not your fault, ApacheFriends ommitted this. To read and follow this file do. Get-Content c:\xampp\php\logs\php_error_log -Wait To do this in VSCode create a task in .vscode\tasks.json { β€― // See https://go.microsoft.com/fwlink/?LinkId=733558 β€― // for the documentation about the tasks.json format β€― "version": "2.0.0", β€― "tasks": [ β€― β€― { β€― β€― β€― "label": "Monitor php errors", β€― β€― β€― "type": "shell", β€― β€― β€― "command": "Get-Content -Wait c:\\xampp\\php\\logs\\php_error_log", β€― β€― β€― "runOptions": { β€― β€― β€― β€― "runOn": "folderOpen" β€― β€― β€― } β€― β€― } β€― ] and have it run on folder load.
How do I get PHP errors to display?
I have checked my PHP ini file (php.ini) and display_errors is set and also error reporting is E_ALL. I have restarted my Apache webserver. I have even put these lines at the top of my script, and it doesn't even catch simple parse errors. For example, I declare variables with a "$" and I don't close statements";". But all my scripts show a blank page on these errors, but I want to actually see the errors in my browser output. error_reporting(E_ALL); ini_set('display_errors', 1); What is left to do?
[ "This always works for me:\nini_set('display_errors', '1');\nini_set('display_startup_errors', '1');\nerror_reporting(E_ALL);\n\nHowever, this doesn't make PHP to show parse errors - the only way to show those errors is to modify your php.ini with this line:\ndisplay_errors = on\n\n(if you don't have access to php.ini, then putting this line in .htaccess might work too):\nphp_flag display_errors 1\n\n", "You can't catch parse errors when enabling error output at runtime, because it parses the file before actually executing anything (and since it encounters an error during this, it won't execute anything). You'll need to change the actual server configuration so that display_errors is on and the approriate error_reporting level is used. If you don't have access to php.ini, you may be able to use .htaccess or similar, depending on the server.\nThis question may provide additional info.\n", "Inside your php.ini:\ndisplay_errors = on\n\nThen restart your web server.\n", "To display all errors you need to:\n1. Have these lines in the PHP script you're calling from the browser (typically index.php):\nerror_reporting(E_ALL);\nini_set('display_errors', '1');\n\n2.(a) Make sure that this script has no syntax errors\nβ€”orβ€”\n2.(b) Set display_errors = On in your php.ini\nOtherwise, it can't even run those 2 lines!\nYou can check for syntax errors in your script by running (at the command line):\nphp -l index.php\n\nIf you include the script from another PHP script then it will display syntax errors in the included script. For example:\nindex.php\nerror_reporting(E_ALL);\nini_set('display_errors', '1');\n\n// Any syntax errors here will result in a blank screen in the browser\n\ninclude 'my_script.php';\n\nmy_script.php\nadjfkj // This syntax error will be displayed in the browser\n\n", "Some web hosting providers allow you to change PHP parameters in the .htaccess file.\nYou can add the following line:\nphp_value display_errors 1\n\nI had the same issue as yours and this solution fixed it.\n", "You might find all of the settings for \"error reporting\" or \"display errors\" do not appear to work in PHPΒ 7. That is because error handling has changed. Try this instead:\ntry{\n // Your code\n} \ncatch(Error $e) {\n $trace = $e->getTrace();\n echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];\n}\n\nOr, to catch exceptions and errors in one go (this is not backward compatible with PHPΒ 5):\ntry{\n // Your code\n} \ncatch(Throwable $e) {\n $trace = $e->getTrace();\n echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];\n}\n\n", "This will work:\n<?php\n error_reporting(E_ALL);\n ini_set('display_errors', 1); \n?>\n\n", "Use:\nini_set('display_errors', 1);\nini_set('display_startup_errors', 1);\nerror_reporting(E_ALL);\n\nThis is the best way to write it, but a syntax error gives blank output, so use the console to check for syntax errors. The best way to debug PHP code is to use the console; run the following:\nphp -l phpfilename.php\n\n", "Set this in your index.php file:\nini_set('display_errors', 1);\nini_set('display_startup_errors', 1);\nerror_reporting(E_ALL);\n\n", "Create a file called php.ini in the folder where your PHP file resides.\nInside php.ini add the following code (I am giving an simple error showing code):\ndisplay_errors = on\n\ndisplay_startup_errors = on\n\n", "I would usually go with the following code in my plain PHP projects.\nif(!defined('ENVIRONMENT')){\n define('ENVIRONMENT', 'DEVELOPMENT');\n}\n\n$base_url = null;\n\nif (defined('ENVIRONMENT'))\n{\n switch (ENVIRONMENT)\n {\n case 'DEVELOPMENT':\n $base_url = 'http://localhost/product/';\n ini_set('display_errors', 1);\n ini_set('display_startup_errors', 1);\n error_reporting(E_ALL|E_STRICT);\n break;\n\n case 'PRODUCTION':\n $base_url = 'Production URL'; /* https://google.com */\n error_reporting(0);\n /* Mechanism to log errors */\n break;\n\n default:\n exit('The application environment is not set correctly.');\n }\n}\n\n", "As we are now running PHP 7, answers given here are not correct any more. The only one still OK is the one from Frank Forte, as he talks about PHPΒ 7.\nOn the other side, rather than trying to catch errors with a try/catch you can use a trick: use include.\nHere three pieces of code:\nFile: tst1.php\n<?php\n error_reporting(E_ALL);\n ini_set('display_errors', 'On');\n // Missing \" and ;\n echo \"Testing\n?>\n\nRunning this in PHPΒ 7 will show nothing.\nNow, try this:\nFile: tst2.php\n<?php\n error_reporting(E_ALL);\n ini_set('display_errors', 'On');\n include (\"tst3.php\");\n?>\n\nFile: tst3.php\n<?php\n // Missing \" and ;\n echo \"Testing\n?>\n\nNow run tst2 which sets the error reporting, and then include tst3. You will see:\n\nParse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in tst3.php on line 4\n\n", "If, despite following all of the above answers (or you can't edit your php.ini file), you still can't get an error message, try making a new PHP file that enables error reporting and then include the problem file. eg:\nerror_reporting(E_ALL);\nini_set('display_errors', 1);\nrequire_once('problem_file.php');\n\nDespite having everything set properly in my php.ini file, this was the only way I could catch a namespace error. My exact scenario was:\n//file1.php\nnamespace a\\b;\nclass x {\n ...\n}\n\n//file2.php\nnamespace c\\d;\nuse c\\d\\x; //Dies because it's not sure which 'x' class to use\nclass x {\n ...\n}\n\n", "If you somehow find yourself in a situation where you can't modifiy the setting via php.ini or .htaccess you're out of luck for displaying errors when your PHP scripts contain parse errors. You'd then have to resolve to linting the files on the command line like this:\nfind . -name '*.php' -type f -print0 | xargs -0 -n1 -P8 php -l | grep -v \"No syntax errors\"\n\nIf your host is so locked down that it does not allow changing the value via php.ini or .htaccess, it may also disallow changing the value via ini_set. You can check that with the following PHP script:\n<?php\nif( !ini_set( 'display_errors', 1 ) ) {\n echo \"display_errors cannot be set.\";\n} else {\n echo \"changing display_errors via script is possible.\";\n}\n\n", "You can do something like below:\nSet the below parameters in your main index file:\n ini_set('display_errors', 1);\n ini_set('display_startup_errors', 1);\n\nThen based on your requirement you can choose which you want to show:\nFor all errors, warnings and notices:\n error_reporting(E_ALL); OR error_reporting(-1);\n\nFor all errors:\n error_reporting(E_ERROR);\n\nFor all warnings:\n error_reporting(E_WARNING);\n\nFor all notices:\n error_reporting(E_NOTICE);\n\nFor more information, check here.\n", "You can add your own custom error handler, which can provide extra debug information. Furthermore, you can set it up to send you the information via email.\nfunction ERR_HANDLER($errno, $errstr, $errfile, $errline){\n $msg = \"<b>Something bad happened.</b> [$errno] $errstr <br><br>\n <b>File:</b> $errfile <br>\n <b>Line:</b> $errline <br>\n <pre>\".json_encode(debug_backtrace(), JSON_PRETTY_PRINT).\"</pre> <br>\";\n\n echo $msg;\n\n return false;\n}\n\nfunction EXC_HANDLER($exception){\n ERR_HANDLER(0, $exception->getMessage(), $exception->getFile(), $exception->getLine());\n}\n\nfunction shutDownFunction() {\n $error = error_get_last();\n if ($error[\"type\"] == 1) {\n ERR_HANDLER($error[\"type\"], $error[\"message\"], $error[\"file\"], $error[\"line\"]);\n }\n}\n\nset_error_handler (\"ERR_HANDLER\", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);\nregister_shutdown_function(\"shutdownFunction\");\nset_exception_handler(\"EXC_HANDLER\");\n\n", "Accepted asnwer including extra options. In PHP files for in my DEVELOPMENT apache vhost (.htaccess if you can ensure it doesn't get into production):\nini_set('display_errors', '1');\nini_set('display_startup_errors', '1');\nerror_reporting(E_ALL);\n\nHowever, this doesn't make PHP to show parse errors - the only way to show those errors is to modify your php.ini with this line:\ndisplay_errors = on\n\n(if you don't have access to php.ini, then putting this line in .htaccess might work too):\n// I've added some extra options that set E_ALL as per https://www.php.net/manual/en/errorfunc.configuration.php.\nphp_flag log_errors on\nphp_flag display_errors on\nphp_flag display_startup_errors on\nphp_value error_reporting 2147483647\nphp_value error_log /var/www/mywebsite.ext/logs/php.error.log\n\n", "This code on top should work:\nerror_reporting(E_ALL);\n\nHowever, try to edit the code on the phone in the file:\nerror_reporting =on\n\n", "The best/easy/fast solution that you can use if it's a quick debugging, is to surround your code with catching exceptions. That's what I'm doing when I want to check something fast in production.\ntry {\n // Page code\n}\ncatch (Exception $e) {\n echo 'Caught exception: ', $e->getMessage(), \"\\n\";\n}\n\n", " <?php\n // Turn off error reporting\n error_reporting(0);\n\n // Report runtime errors\n error_reporting(E_ERROR | E_WARNING | E_PARSE);\n\n // Report all errors\n error_reporting(E_ALL);\n\n // Same as error_reporting(E_ALL);\n ini_set(\"error_reporting\", E_ALL);\n\n // Report all errors except E_NOTICE\n error_reporting(E_ALL & ~E_NOTICE);\n ?>\n\nWhile your site is live, the php.ini file should have display_errors disabled for security reasons. However, for the development environment, display_errors can be enabled for troubleshooting. \n", "Just write:\nerror_reporting(-1);\n\n", "You can do this by changing the php.ini file and add the following \ndisplay_errors = on\ndisplay_startup_errors = on\n\nOR you can also use the following code as this always works for me\nini_set('display_errors', 1);\nini_set('display_startup_errors', 1);\nerror_reporting(E_ALL);\n\n", "If you have Xdebug installed you can override every setting by setting:\nxdebug.force_display_errors = 1;\nxdebug.force_error_reporting = -1;\n\n\nforce_display_errors\nType: int, Default value: 0, Introduced in Xdebug >= 2.3 If this\n setting is set to 1 then errors will always be displayed, no matter\n what the setting of PHP's display_errors is.\nforce_error_reporting\nType: int, Default value: 0, Introduced in Xdebug >= 2.3\n This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().\n\n", "You might want to use this code:\nini_set('display_errors', 1);\nini_set('display_startup_errors', 1);\nerror_reporting(E_ALL);\n\n", "If it is on the command line, you can run php with -ddisplay_errors=1 to override the setting in php.ini:\nphp -ddisplay_errors=1 script.php\n\n", "Report all errors except E_NOTICE\nerror_reporting(E_ALL & ~E_NOTICE);\n\nDisplay all PHP errors \nerror_reporting(E_ALL); or ini_set('error_reporting', E_ALL);\n\nTurn off all error reporting\nerror_reporting(0);\n\n", " error_reporting(1);\n ini_set('display_errors', '1');\n ini_set('display_startup_errors', '1');\n error_reporting(E_ALL);\n\nPut this at the top of your page.\n", "Input this on the top of your code\nini_set('display_errors', '1');\nini_set('display_startup_errors', '1');\nerror_reporting(E_ALL);\n\nAnd in the php.ini file, insert this:\ndisplay_errors = on\n\nThis must work.\n", "In Unix CLI, it's very practical to redirect only errors to a file:\n./script 2> errors.log\n\nFrom your script, either use var_dump() or equivalent as usual (both STDOUT and STDERR will receive the output), but to write only in the log file:\nfwrite(STDERR, \"Debug infos\\n\"); // Write in errors.log^\n\n\nThen from another shell, for live changes:\ntail -f errors.log\n\nor simply\nwatch cat errors.log\n\n", "You can show Php error in your display via simple ways.\nFirstly, just put this below code in your php.ini file.\ndisplay_errors = on;\n\n(if you don't have access to php.ini, then putting this line in .htaccess might work too):\nphp_flag display_errors 1\n\nOR you can also use the following code in your index.php file\nini_set('display_errors', 1);\nini_set('display_startup_errors', 1);\nerror_reporting(E_ALL);\n\n", "If you are on a SharedHosting plan (like on hostgator)... simply adding\nphp_flag display_errors 1\n\ninto a .htaccess file and uploading it to the remote folder may not yield the actual warnings/errors that were generated on the server.\nWhat you will also need to do is edit the php.ini\n\nThis is how you do it via cPanel (tested on hostgator shared hosting\nplan)\n\nAfter logging into your cPanel, search for MultiPHP INI Editor.\nIt is usually found under the SOFTWARE section in your cPanel list of items.\nOn the MultiPHP INI Editor page ...you can stay on the basic mode tab and just check the button on the line that says display_errors.\nThen click the Apply button to save.\n\n\nIMPORTANT: Just remember to turn it back off when you are done debugging; because this is not recommended for public servers.\n\n", "As it is not clear what OS you are on these are my 2 Windows cents.\nIf you are using XAMPP you need to manually create the logs folder under C:\\xampp\\php. Not your fault, ApacheFriends ommitted this.\nTo read and follow this file do.\nGet-Content c:\\xampp\\php\\logs\\php_error_log -Wait\n\nTo do this in VSCode create a task in .vscode\\tasks.json\n{ \nβ€― // See https://go.microsoft.com/fwlink/?LinkId=733558 \nβ€― // for the documentation about the tasks.json format \nβ€― \"version\": \"2.0.0\", \nβ€― \"tasks\": [ \nβ€― β€― { \nβ€― β€― β€― \"label\": \"Monitor php errors\", \nβ€― β€― β€― \"type\": \"shell\", \nβ€― β€― β€― \"command\": \"Get-Content -Wait c:\\\\xampp\\\\php\\\\logs\\\\php_error_log\", \nβ€― β€― β€― \"runOptions\": { \nβ€― β€― β€― β€― \"runOn\": \"folderOpen\" \nβ€― β€― β€― } \nβ€― β€― } \nβ€― ] \n\nand have it run on folder load.\n" ]
[ 3480, 161, 153, 107, 54, 44, 35, 34, 24, 20, 16, 16, 15, 14, 14, 12, 10, 7, 6, 5, 4, 4, 3, 3, 2, 2, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "error_handling", "error_reporting", "php", "syntax_error" ]
stackoverflow_0001053424_error_handling_error_reporting_php_syntax_error.txt
Q: @Mock/@InjectMocks for groovy - spock In JUnit / Mockito we have 2 extremly useful annotations: @Mock and @InjectMocks. In my new project i started using groovy with spock for testing, I'm wondering if there is a replacement for mentioned annotations? A: There is no real need for @Mock in Spock, because there is already = Mock(), which can be used everywhere an annotation can be used (and also in other places). There is an open pull request for @InjectMocks, but it hasn't been decided if such a feature will make it into spock-core or spock-guice. (Shipping this feature with spock-guice, or at least requiring Guice on the class path, would allow to delegate injection to Guice, rather than reinventing the wheel.) If not, @InjectMocks could always be shipped as a third-party Spock extension. A: Someone wrote an annotation two months ago: https://github.com/msid256/MockInjector4Spock. The bean you want to test doesn't need to be instantiated manually. All you need to do is to declare it as a field and annotate it with @InjectMocks. @Service class ServiceC { @Autowired public ServiceC(ServiceA a, ServiceB b) {} } class DemoSpec extends Specification { @Autowired ServiceA serviceA; ServiceB serviceB = Mock(ServiceB.class) @InjectMocks // from MockInjector4Spock - de.github.spock.ext.annotation.InjectMocks ServiceC serviceC; } A: https://github.com/marcingrzejszczak/spock-subjects-collaborators-extension you can use @Collaborator and @Subject instead @Mock and @InjectMocks
@Mock/@InjectMocks for groovy - spock
In JUnit / Mockito we have 2 extremly useful annotations: @Mock and @InjectMocks. In my new project i started using groovy with spock for testing, I'm wondering if there is a replacement for mentioned annotations?
[ "There is no real need for @Mock in Spock, because there is already = Mock(), which can be used everywhere an annotation can be used (and also in other places). There is an open pull request for @InjectMocks, but it hasn't been decided if such a feature will make it into spock-core or spock-guice. (Shipping this feature with spock-guice, or at least requiring Guice on the class path, would allow to delegate injection to Guice, rather than reinventing the wheel.) If not, @InjectMocks could always be shipped as a third-party Spock extension.\n", "Someone wrote an annotation two months ago: https://github.com/msid256/MockInjector4Spock.\n\nThe bean you want to test doesn't need to be instantiated manually. All you need to do is to declare it as a field and annotate it with @InjectMocks.\n\n@Service\nclass ServiceC {\n @Autowired\n public ServiceC(ServiceA a, ServiceB b) {}\n}\n\nclass DemoSpec extends Specification {\n @Autowired\n ServiceA serviceA;\n\n ServiceB serviceB = Mock(ServiceB.class)\n\n @InjectMocks // from MockInjector4Spock - de.github.spock.ext.annotation.InjectMocks\n ServiceC serviceC;\n}\n\n", "https://github.com/marcingrzejszczak/spock-subjects-collaborators-extension\nyou can use @Collaborator and @Subject instead @Mock and @InjectMocks\n" ]
[ 12, 0, 0 ]
[]
[]
[ "groovy", "java", "junit", "mockito", "spock" ]
stackoverflow_0020528722_groovy_java_junit_mockito_spock.txt
Q: Substring with patindex for substrings' length not working to extract part of a string I have a table with strings (ItemCode) like: 99XXX123456-789 12ABC221122-987BA1 They are always of a length of 11 characters (upto the - of which they always contain only one), after the - length is variable. I would like to get the part after the first 5 characters upto the - , like this. 123456 221122 I tried with substring and patindex: SELECT SUBSTRING( ItemCode, 6, PATINDEX('%[-]%', ItemCode) - 6 ), PATINDEX('%[-]%', ItemCode), ItemCode FROM TableName WHERE LEFT(ItemCode, 5) = '99XXX' Patindex itself returns the correct value (12) but with PATINDEX('%[-]%', ItemCode) - 6 /sql should understand this as 12 - 6 = 6 / SQL Server 2012 gives an error. I could use 6 as a fix value in the patindex for the length, of course but I want to understand the reason for the error.
Substring with patindex for substrings' length not working to extract part of a string
I have a table with strings (ItemCode) like: 99XXX123456-789 12ABC221122-987BA1 They are always of a length of 11 characters (upto the - of which they always contain only one), after the - length is variable. I would like to get the part after the first 5 characters upto the - , like this. 123456 221122 I tried with substring and patindex: SELECT SUBSTRING( ItemCode, 6, PATINDEX('%[-]%', ItemCode) - 6 ), PATINDEX('%[-]%', ItemCode), ItemCode FROM TableName WHERE LEFT(ItemCode, 5) = '99XXX' Patindex itself returns the correct value (12) but with PATINDEX('%[-]%', ItemCode) - 6 /sql should understand this as 12 - 6 = 6 / SQL Server 2012 gives an error. I could use 6 as a fix value in the patindex for the length, of course but I want to understand the reason for the error.
[]
[]
[ "But when I am using the same query I am not getting the error:\ncreate table #temp\n(\nnum varchar(50)\n)\n\n--insert into #temp values ('99XXX123456-789')\n--insert into #temp values ('12ABC221122-987BA1')\n\nSELECT SUBSTRING( num, 6, PATINDEX('%[-]%', num) - 6 ),\n PATINDEX('%[-]%', num),\n num \nFROM #temp WHERE LEFT(num, 5) = '99XXX'\n\n" ]
[ -1 ]
[ "patindex", "sql_server", "sql_server_2012", "substring" ]
stackoverflow_0074667201_patindex_sql_server_sql_server_2012_substring.txt
Q: Unable to Connect to Rabbit MQ I am using amazon service and created rabbitmq broker now from the DOT NET code i am trying to connect to this broker. var factory = new ConnectionFactory { Uri = new Uri("amqps://it:Password@hostname:5671") }; var connection = factory.CreateConnection(); I am struggle here to get connection getting below error : None of the specified endpoints were reachable at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName) A: It looks like you are having trouble connecting to your RabbitMQ broker. There could be a few reasons for this error. One possible reason is that the URI you are using to connect to the broker is incorrect. It is worth double-checking the hostname, port, and credentials in the URI to make sure they are correct. Another possible reason for this error is that the broker is not running or is not reachable from the network. In this case, you can try checking the status of the broker and making sure it is running, or checking your network connection to make sure it is functioning properly. Additionally, it is worth checking the logs on the broker and on your client to see if there are any other error messages that could provide more information about the issue. A: Update: It seems your client wants to connect using TLS/SSL (your uri specifies the protocol "amqps" and the port 5671). Try enabling TLS/SSL: var factory = new ConnectionFactory { UserName = userName, Password = password, VirtualHost = "/", HostName = hostName, Port = port, Ssl = new SslOption { Enabled = true, // <-------- ServerName = hostName } }; The (JVM based) guide shows how to configure the connection factory. It sets the credentials on the factory, not in the URI: ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(username); // <---------- factory.setPassword(password); // <---------- //Replace the URL with your information factory.setHost("b-c8352341-ec91-4a78-ad9c-a43f23d325bb.mq.us-west-2.amazonaws.com"); factory.setPort(5671); // Allows client to establish a connection over TLS factory.useSslProtocol() // Create a connection Connection conn = factory.newConnection(); (This needs to be translated to the corresponding .NET code)
Unable to Connect to Rabbit MQ
I am using amazon service and created rabbitmq broker now from the DOT NET code i am trying to connect to this broker. var factory = new ConnectionFactory { Uri = new Uri("amqps://it:Password@hostname:5671") }; var connection = factory.CreateConnection(); I am struggle here to get connection getting below error : None of the specified endpoints were reachable at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName)
[ "It looks like you are having trouble connecting to your RabbitMQ broker. There could be a few reasons for this error. One possible reason is that the URI you are using to connect to the broker is incorrect. It is worth double-checking the hostname, port, and credentials in the URI to make sure they are correct.\nAnother possible reason for this error is that the broker is not running or is not reachable from the network. In this case, you can try checking the status of the broker and making sure it is running, or checking your network connection to make sure it is functioning properly.\nAdditionally, it is worth checking the logs on the broker and on your client to see if there are any other error messages that could provide more information about the issue.\n", "Update:\nIt seems your client wants to connect using TLS/SSL (your uri specifies the protocol \"amqps\" and the port 5671).\nTry enabling TLS/SSL:\nvar factory = new ConnectionFactory { \nUserName = userName, \nPassword = password, \nVirtualHost = \"/\", \nHostName = hostName, \nPort = port, \nSsl = new SslOption \n { Enabled = true, // <--------\n ServerName = hostName } \n};\n\n\nThe (JVM based) guide shows how to configure the connection factory. It sets the credentials on the factory, not in the URI:\nConnectionFactory factory = new ConnectionFactory();\n\nfactory.setUsername(username); // <----------\nfactory.setPassword(password); // <----------\n\n//Replace the URL with your information\nfactory.setHost(\"b-c8352341-ec91-4a78-ad9c-a43f23d325bb.mq.us-west-2.amazonaws.com\");\nfactory.setPort(5671);\n\n// Allows client to establish a connection over TLS\nfactory.useSslProtocol()\n\n// Create a connection\nConnection conn = factory.newConnection();\n\n(This needs to be translated to the corresponding .NET code)\n" ]
[ 0, 0 ]
[]
[]
[ ".net_core", "amqp", "rabbitmq" ]
stackoverflow_0074667561_.net_core_amqp_rabbitmq.txt
Q: Send data to specific client from another client with a server in middle[C#] I have searched everywhere but couldn't find as they are all answering to send message to all clients. What I want to achieve is multiple clients request to server to request data from another client and other client sends data to server telling it that data is for requesting client and so. I don't know how to achieve this. I'm new to this. What I want to achieve: I have tried with Data sending client to listen and requesting client to connect to it and transfer data. I have achieved this on local network but to make it work online it needs port forwarding and my user will be a lot of different people so port forwarding is not possible for every user. So I can rent a server which will act as a center of transfer. I programmed a test server in console which will listen to a server IP:port X and accept new clients and their data on port X and forward it to server IP:port Y but what this does is send data to all clients on port Y. I cannot send it to clients public ip address directly for obvious reasons. I understand that all the requesting clients are connected to port Y but I cannot create and assign new ports to all the clients interacting. So I want a way to determine how to request and receive the data without the need of assigning or creating new ports to different clients on same server. What I have tried: Server code using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Test___server { class server { public static string serverIP = "192.168.0.102"; static void Main(string[] args) { Thread listenSendingThread = new Thread(listenSending); listenSendingThread.IsBackground = true; listenSendingThread.Start(); Thread listenReceivingThread = new Thread(listenReceiving); listenReceivingThread.IsBackground = true; listenReceivingThread.Start(); Console.ReadKey(); } public static List<TcpClient> listSending = new List<TcpClient>(); public static List<TcpClient> listReceiving = new List<TcpClient>(); public static TcpClient clientSending = null; private static void listenSending() { TcpListener listenerSending = new TcpListener(IPAddress.Parse(serverIP), 5319); listenerSending.Start(); Console.WriteLine("Server listening to " + serverIP + ":5319"); while(true) { clientSending = listenerSending.AcceptTcpClient(); listSending.Add(clientSending); Console.WriteLine("Sender connection received from " + clientSending.Client.RemoteEndPoint); } } private static void send() { StreamWriter sw = new StreamWriter(clientSending.GetStream()); sw.WriteLine(message); sw.Flush(); Console.WriteLine("Message sent!"); } public static string message = string.Empty; private static void listenReceiving() { TcpListener listener = new TcpListener(IPAddress.Parse(serverIP), 0045); listener.Start(); Console.WriteLine("Server listening to " + serverIP + ":0045"); while (true) { TcpClient client = listener.AcceptTcpClient(); listReceiving.Add(client); Console.WriteLine("Receiver connection received from " + client.Client.RemoteEndPoint); StreamReader sr = new StreamReader(client.GetStream()); message = sr.ReadLine(); send(); } } } } Requesting client code using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test____admin { class admin { static void Main(string[] args) { Console.WriteLine("Begin"); string serverIP = "192.168.0.102"; System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient(); clientSocket.Connect(serverIP, ); Console.WriteLine("Connected"); while (true) { Console.WriteLine("Reading"); StreamReader sr = new StreamReader(clientSocket.GetStream()); Console.WriteLine("Message: " + sr.ReadLine()); } } } } Request satisfying client code using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace Test___client { class client { public static string serverIP = "192.168.0.102"; static void Main(string[] args) { clientConnect(); } private static void clientConnect() { try { TcpClient client = new TcpClient(serverIP, 0045); StreamWriter sw = new StreamWriter(client.GetStream()); sw.WriteLine("Karan!"); sw.Flush(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } } A: You are using a very low-level API, and doing it the right way is challenging. Instead, try YARP as a reverse proxy. The requesting client should notify the reverse proxy about the desired destination client. One option is sending the destination client name in the request header. You will also need to split a single server request into multiple client requests, then merge their responses into a single one. You can achieve it by implementing Transphorms. I'm not sure this approach applies to your situation because clients should implement server API using REST, Grpc or any other supported technology.
Send data to specific client from another client with a server in middle[C#]
I have searched everywhere but couldn't find as they are all answering to send message to all clients. What I want to achieve is multiple clients request to server to request data from another client and other client sends data to server telling it that data is for requesting client and so. I don't know how to achieve this. I'm new to this. What I want to achieve: I have tried with Data sending client to listen and requesting client to connect to it and transfer data. I have achieved this on local network but to make it work online it needs port forwarding and my user will be a lot of different people so port forwarding is not possible for every user. So I can rent a server which will act as a center of transfer. I programmed a test server in console which will listen to a server IP:port X and accept new clients and their data on port X and forward it to server IP:port Y but what this does is send data to all clients on port Y. I cannot send it to clients public ip address directly for obvious reasons. I understand that all the requesting clients are connected to port Y but I cannot create and assign new ports to all the clients interacting. So I want a way to determine how to request and receive the data without the need of assigning or creating new ports to different clients on same server. What I have tried: Server code using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Test___server { class server { public static string serverIP = "192.168.0.102"; static void Main(string[] args) { Thread listenSendingThread = new Thread(listenSending); listenSendingThread.IsBackground = true; listenSendingThread.Start(); Thread listenReceivingThread = new Thread(listenReceiving); listenReceivingThread.IsBackground = true; listenReceivingThread.Start(); Console.ReadKey(); } public static List<TcpClient> listSending = new List<TcpClient>(); public static List<TcpClient> listReceiving = new List<TcpClient>(); public static TcpClient clientSending = null; private static void listenSending() { TcpListener listenerSending = new TcpListener(IPAddress.Parse(serverIP), 5319); listenerSending.Start(); Console.WriteLine("Server listening to " + serverIP + ":5319"); while(true) { clientSending = listenerSending.AcceptTcpClient(); listSending.Add(clientSending); Console.WriteLine("Sender connection received from " + clientSending.Client.RemoteEndPoint); } } private static void send() { StreamWriter sw = new StreamWriter(clientSending.GetStream()); sw.WriteLine(message); sw.Flush(); Console.WriteLine("Message sent!"); } public static string message = string.Empty; private static void listenReceiving() { TcpListener listener = new TcpListener(IPAddress.Parse(serverIP), 0045); listener.Start(); Console.WriteLine("Server listening to " + serverIP + ":0045"); while (true) { TcpClient client = listener.AcceptTcpClient(); listReceiving.Add(client); Console.WriteLine("Receiver connection received from " + client.Client.RemoteEndPoint); StreamReader sr = new StreamReader(client.GetStream()); message = sr.ReadLine(); send(); } } } } Requesting client code using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test____admin { class admin { static void Main(string[] args) { Console.WriteLine("Begin"); string serverIP = "192.168.0.102"; System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient(); clientSocket.Connect(serverIP, ); Console.WriteLine("Connected"); while (true) { Console.WriteLine("Reading"); StreamReader sr = new StreamReader(clientSocket.GetStream()); Console.WriteLine("Message: " + sr.ReadLine()); } } } } Request satisfying client code using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace Test___client { class client { public static string serverIP = "192.168.0.102"; static void Main(string[] args) { clientConnect(); } private static void clientConnect() { try { TcpClient client = new TcpClient(serverIP, 0045); StreamWriter sw = new StreamWriter(client.GetStream()); sw.WriteLine("Karan!"); sw.Flush(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } }
[ "You are using a very low-level API, and doing it the right way is challenging. Instead, try YARP as a reverse proxy. The requesting client should notify the reverse proxy about the desired destination client. One option is sending the destination client name in the request header. You will also need to split a single server request into multiple client requests, then merge their responses into a single one. You can achieve it by implementing Transphorms.\nI'm not sure this approach applies to your situation because clients should implement server API using REST, Grpc or any other supported technology.\n" ]
[ 0 ]
[]
[]
[ "c#", "client", "server", "tcp", "winforms" ]
stackoverflow_0074666871_c#_client_server_tcp_winforms.txt
Q: npm install not working. Says that I need to check permissions? I'm trying to install eslint on my machine right now but it is saying that I need to check permissions because its missing write access to /user/local/lib/node_modules. Does anyone know how to fix this? Thanks! npm install -g eslint npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules npm ERR! path /usr/local/lib/node_modules npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall access npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules' npm ERR! { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules'] npm ERR! stack: npm ERR! "Error: EACCES: permission denied, access '/usr/local/lib/node_modules'", npm ERR! errno: -13, npm ERR! code: 'EACCES', npm ERR! syscall: 'access', npm ERR! path: '/usr/local/lib/node_modules' } npm ERR! npm ERR! The operation was rejected by your operating system. npm ERR! It is likely you do not have the permissions to access this file as the current user npm ERR! npm ERR! If you believe this might be a permissions issue, please double-check the npm ERR! permissions of the file and its containing directories, or try running npm ERR! the command again as root/Administrator (though this is not recommended). npm ERR! A complete log of this run can be found in: npm ERR! /Users/mkaplan/.npm/_logs/2019-03-03T18_05_46_487Z-debug.log A: Try sudo npm install -g eslint A: For Linux use sudo npm install and For Window run powerShell as administrator and got to directory of project and run npm install A: In my case I had this same problem to install angular, so just change the command to : $ sudo npm install -g @angular/cli A: This kind of stuff happens when you run npm commands with sudo to begin with. So don't do it? If this happens, it means that someone has been messing around npm as root. Then root took and created files in global npm cache, denying access to anything different than root. This is why it fires EACCES when running npm install or npm install -g You are not supposed to do anything related to node_modules nor runnpm [anything] with sudo. Do you understand that you are giving the package in question permission to do whatever it wants? Even if you check the package and ensure its security yourself, what about dependencies it downloads? will you check them as well? npm registry gets 30b weekly downloads, their malware control is nowhere near enough You are giving away access to whole sys folder tree to the files of the package in question. Even npm itself gives you feedback that it is not recommended. You do not know what package does in the background. What if you install a package i developed, but i am a villian who likes to make people's life harder... This is a security issue. The above story apart. If you do it with sudo, this will force you to run certain npm commands as sudo from that point on, messing it up even more. The maximum you do as root in this case, is give access for node_modules to whoami The best solution is to either set it up properly so you dont have to use sudo or run app in container, so anything you do is executed inside container, not affecting your local machine at least. Even there it is not recommended to mess around as root, permissions get so messy... it's a hell to debug. A: This can solve the problem: sudo npm install -g npm A: First try sudo npm install -g gatsby-cli then npm start A: I ran into an issue trying to install truffle and got the following errors: npm ERR! The operation was rejected by your operating system. npm ERR! It is likely you do not have the permissions to access this file as the current user I was able to solve this issue with the recommendation to add 'sudo'. solution: sudo npm i -g truffle A: Use the command: sudo npm install -g eslint With the sudo command you will have the permission to install. A: This might happen when you just "sudo" everything in order to make it work or you install a dependency forcefully , you should not mess with the root folder of node modules. For now you can try installing using sudo npm install -g eslint A: I'm fairly new to Node but as a longtime Linux user I'not sure installing node packages as root (via sudo) is a good idea. I imagine eslint is fine but if you're having this issue installing one package then I'm guessing you're having the same problem with every package you're installing globally ('-g'). That means that every time you install a package from npm globally you're downloading who-knows-what install script and running it with root privileges on your computer. Anyway, as I said I'm no Node expert but I had this same problem and my issue was that I'd installed the "nodejs" package using apt. If this is what you did then I suggest: Remove nodejs with sudo apt remove nodejs. (Depending on what Linux distro you're using this may be different. I'm running Ubuntu.) Install nvm or some other node version manager as recommended by the NPM docs. When I did this, I was able to install NPM packages globally without sudo. (Yes, I'm telling you not to install things by running npm as root and then saying you should install things by running apt as root. But you definitely need to run apt as root and I know appropriate precautions are taken by the apt devs and Ubuntu package repo managers. I'm not 100% sure it's wrong to run npm as root but I'm not sure it's right either, and I was able to avoid running it as root using the above steps.)
npm install not working. Says that I need to check permissions?
I'm trying to install eslint on my machine right now but it is saying that I need to check permissions because its missing write access to /user/local/lib/node_modules. Does anyone know how to fix this? Thanks! npm install -g eslint npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules npm ERR! path /usr/local/lib/node_modules npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall access npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules' npm ERR! { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules'] npm ERR! stack: npm ERR! "Error: EACCES: permission denied, access '/usr/local/lib/node_modules'", npm ERR! errno: -13, npm ERR! code: 'EACCES', npm ERR! syscall: 'access', npm ERR! path: '/usr/local/lib/node_modules' } npm ERR! npm ERR! The operation was rejected by your operating system. npm ERR! It is likely you do not have the permissions to access this file as the current user npm ERR! npm ERR! If you believe this might be a permissions issue, please double-check the npm ERR! permissions of the file and its containing directories, or try running npm ERR! the command again as root/Administrator (though this is not recommended). npm ERR! A complete log of this run can be found in: npm ERR! /Users/mkaplan/.npm/_logs/2019-03-03T18_05_46_487Z-debug.log
[ "Try sudo npm install -g eslint\n", "For Linux use sudo npm install and\nFor Window run powerShell as administrator and got to directory of project and run npm install\n", "In my case I had this same problem to install angular, so just change the command to :\n$ sudo npm install -g @angular/cli\n\n", "This kind of stuff happens when you run npm commands with sudo to begin with. So don't do it?\nIf this happens, it means that someone has been messing around npm as root. Then root took and created files in global npm cache, denying access to anything different than root.\nThis is why it fires EACCES when running npm install or npm install -g\nYou are not supposed to do anything related to node_modules nor runnpm [anything] with sudo. Do you understand that you are giving the package in question permission to do whatever it wants? Even if you check the package and ensure its security yourself, what about dependencies it downloads? will you check them as well?\nnpm registry gets 30b weekly downloads, their malware control is nowhere near enough\nYou are giving away access to whole sys folder tree to the files of the package in question. Even npm itself gives you feedback that it is not recommended. You do not know what package does in the background. What if you install a package i developed, but i am a villian who likes to make people's life harder... This is a security issue.\nThe above story apart. If you do it with sudo, this will force you to run certain npm commands as sudo from that point on, messing it up even more.\nThe maximum you do as root in this case, is give access for node_modules to whoami\nThe best solution is to either set it up properly so you dont have to use sudo or run app in container, so anything you do is executed inside container, not affecting your local machine at least. Even there it is not recommended to mess around as root, permissions get so messy... it's a hell to debug.\n", "This can solve the problem:\nsudo npm install -g npm\n\n", "First try sudo npm install -g gatsby-cli\nthen npm start\n", "I ran into an issue trying to install truffle and got the following errors:\nnpm ERR! The operation was rejected by your operating system.\nnpm ERR! It is likely you do not have the permissions to access this file as the current user\nI was able to solve this issue with the recommendation to add 'sudo'.\nsolution:\nsudo npm i -g truffle\n", "Use the command:\nsudo npm install -g eslint\nWith the sudo command you will have the permission to install.\n", "This might happen when you just \"sudo\" everything in order to make it work or you install a dependency forcefully , you should not mess with the root folder of node modules.\nFor now you can try installing using\nsudo npm install -g eslint\n\n", "I'm fairly new to Node but as a longtime Linux user I'not sure installing node packages as root (via sudo) is a good idea.\nI imagine eslint is fine but if you're having this issue installing one package then I'm guessing you're having the same problem with every package you're installing globally ('-g'). That means that every time you install a package from npm globally you're downloading who-knows-what install script and running it with root privileges on your computer.\nAnyway, as I said I'm no Node expert but I had this same problem and my issue was that I'd installed the \"nodejs\" package using apt. If this is what you did then I suggest:\n\nRemove nodejs with sudo apt remove nodejs. (Depending on what Linux distro you're using this may be different. I'm running Ubuntu.)\nInstall nvm or some other node version manager as recommended by the NPM docs.\n\nWhen I did this, I was able to install NPM packages globally without sudo.\n(Yes, I'm telling you not to install things by running npm as root and then saying you should install things by running apt as root. But you definitely need to run apt as root and I know appropriate precautions are taken by the apt devs and Ubuntu package repo managers. I'm not 100% sure it's wrong to run npm as root but I'm not sure it's right either, and I was able to avoid running it as root using the above steps.)\n" ]
[ 40, 3, 2, 1, 0, 0, 0, 0, 0, 0 ]
[ "Use this npm install node-sass --save\n" ]
[ -1 ]
[ "node.js", "npm" ]
stackoverflow_0054972076_node.js_npm.txt
Q: Fastest way to get exact count of rows for a 100GB CSV file stored on S3 What is the fastest way of getting an exact count of rows for a 100GB CSV file stored on Amazon S3 without using Athena nor any Fargate or EC2 VM? I can't use Athena, because the CSV file isn't clean-enough for it. I can't use Fargates or EC2 VMs, because I need a purely serverless solution. I can't use third-party services like Snowflake (native AWS services only). Also, 100GB is too large to fit within a Lambda Function's /tmp (limited to 10GB). I could try to run something like DuckDB (or any other streaming database engine) on a Lambda and scan the entire file with a SELECT COUNT(*) FROM "s3://myBucket/myFile.csv" query, but the Lambda is quite likely to timeout, because its read bandwidth from S3 is 100MB/s at best, and it cannot run for more than 15 minutes (900s). I know the approximate size of the file. Note: I have an inaccurate estimate of the number of rows provided by AWS Glue Data Catalog's crawler, with an error margin of -50%/+100%. This could be used for some kind of iterative or dichotomous process, but I could not figure any out. For example, I tried adding an OFFSET with a value lower than but close to the number of rows to the aforementioned query, but the Lambda running DuckDB timed out. That was disappointing and somewhat surprising, because a query like SELECT * FROM "s3://myBucket/myFile.csv" LIMIT 10 OFFSET 10000000 worked well. A: The fastest solution is probably to use SelectObjectContent with ScanRange to parallelize the request on chunks of 50MB or so.
Fastest way to get exact count of rows for a 100GB CSV file stored on S3
What is the fastest way of getting an exact count of rows for a 100GB CSV file stored on Amazon S3 without using Athena nor any Fargate or EC2 VM? I can't use Athena, because the CSV file isn't clean-enough for it. I can't use Fargates or EC2 VMs, because I need a purely serverless solution. I can't use third-party services like Snowflake (native AWS services only). Also, 100GB is too large to fit within a Lambda Function's /tmp (limited to 10GB). I could try to run something like DuckDB (or any other streaming database engine) on a Lambda and scan the entire file with a SELECT COUNT(*) FROM "s3://myBucket/myFile.csv" query, but the Lambda is quite likely to timeout, because its read bandwidth from S3 is 100MB/s at best, and it cannot run for more than 15 minutes (900s). I know the approximate size of the file. Note: I have an inaccurate estimate of the number of rows provided by AWS Glue Data Catalog's crawler, with an error margin of -50%/+100%. This could be used for some kind of iterative or dichotomous process, but I could not figure any out. For example, I tried adding an OFFSET with a value lower than but close to the number of rows to the aforementioned query, but the Lambda running DuckDB timed out. That was disappointing and somewhat surprising, because a query like SELECT * FROM "s3://myBucket/myFile.csv" LIMIT 10 OFFSET 10000000 worked well.
[ "The fastest solution is probably to use SelectObjectContent with ScanRange to parallelize the request on chunks of 50MB or so.\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_lambda", "csv", "duckdb" ]
stackoverflow_0074667100_amazon_s3_amazon_web_services_aws_lambda_csv_duckdb.txt
Q: Append data after checking a condition I have a yearly table which on a monthly basis will append data from another table. However, I need to check the max date on the monthly table before appending it. If the max date on monthly is same as YTD, then do not append else append. How can I achieve this in SAS. I tried using append but don't know how to check the dates before appending. A: You can use a macro. First, insert the last year/month id on a variable and preper a macro to execute the append operation: proc sql; select max(yourDtcolumn) into : var from yourTable; quit; %macro append; proc sql; insert into yourtable select * from sourcetable; quit; %mend; then, verify if the variable are the same: %macro verify; %if &var > &curMonth %then %do; %append; %end; %mend; finally, you call the macro to execute: %verify; A: I'd skip the check, and simply stack the existing data (excluding the current month, if it exists) and the new data. /* Get period from new data */ proc sql ; select min(period) into :LATEST from new ; quit ; /* Append new to master, and save back master */ data perm.master ; set perm.master (where=(period < &LATEST)) new ; run ;
Append data after checking a condition
I have a yearly table which on a monthly basis will append data from another table. However, I need to check the max date on the monthly table before appending it. If the max date on monthly is same as YTD, then do not append else append. How can I achieve this in SAS. I tried using append but don't know how to check the dates before appending.
[ "You can use a macro.\nFirst, insert the last year/month id on a variable and preper a macro to execute the append operation:\nproc sql;\nselect max(yourDtcolumn) into : var\nfrom yourTable;\nquit;\n\n%macro append;\n proc sql;\n insert into yourtable\n select * from sourcetable;\n quit;\n%mend;\n\nthen, verify if the variable are the same:\n\n%macro verify;\n%if &var > &curMonth %then %do;\n %append;\n%end;\n%mend;\n\nfinally, you call the macro to execute:\n%verify;\n\n", "I'd skip the check, and simply stack the existing data (excluding the current month, if it exists) and the new data.\n/* Get period from new data */\nproc sql ;\n select min(period) into :LATEST\n from new ;\nquit ;\n\n/* Append new to master, and save back master */\ndata perm.master ;\n set perm.master (where=(period < &LATEST))\n new ;\nrun ;\n\n" ]
[ 0, 0 ]
[]
[]
[ "append", "conditional_statements", "if_statement", "sas" ]
stackoverflow_0074661847_append_conditional_statements_if_statement_sas.txt
Q: How to solve selenium webdriver: ElementNotInteractableError: element not interactable in nodejs I started to learn Selenium but i'm stuck trying to upload and download on a element like this: I want to upload a dwg file on this site and convert it into a text file. So I'm using selenium. I encountered a problem while uploading the file This is my error message: We have tried several solutions to this problem. ADD driver.manage().window().maximize(); use click() instead of sendKeys() Check Element is Enabled However, no solution has solved the problem. This is the entire code: const { Builder, Browser, By, Key, until } = require("selenium-webdriver"); const chromeDriver = require("selenium-webdriver/chrome"); const chromeOptions = new chromeDriver.Options(); const chromeExample = async () => { const driver = await new Builder() .forBrowser(Browser.CHROME) .setChromeOptions(chromeOptions.headless()) .build(); driver.manage().window().maximize(); await driver.get("https://products.aspose.app/cad/text-extractor/dwg"); await driver.wait( until.elementLocated(By.className("filedrop-container width-for-mobile")), 10 * 1000 ); await driver.wait( until.elementIsEnabled( driver.findElement(By.className("filedrop-container width-for-mobile")) ), 10 * 1000 ); const tmp = await driver .findElement(By.className("filedrop-container width-for-mobile")) .sendKeys("/home/yeongori/workspace/Engineering-data-search-service/macro/public/images/testfile1.dwg"); console.log(tmp); }; The same error occurs when i change the code as below. await driver .findElement(By.className("filedrop-container width-for-mobile")) .sendKeys(Key.ENTER); One strange thing is that if i change sendKeys to click and check tmp with console.log, it is null. This is Project Directory How can I solve this problem? I'm sorry if it's too basic a question. But I'd be happy if there was any hint. Thank you. WSL2(Ubuntu-20.04), Node.js v18.12.1 A: You need to use sendKeys on the input element which is nested deeper in the element that you are currently trying to send keys to. You can reach the element with this xpath: "//*[contains(@id,'UploadFileInput')]"
How to solve selenium webdriver: ElementNotInteractableError: element not interactable in nodejs
I started to learn Selenium but i'm stuck trying to upload and download on a element like this: I want to upload a dwg file on this site and convert it into a text file. So I'm using selenium. I encountered a problem while uploading the file This is my error message: We have tried several solutions to this problem. ADD driver.manage().window().maximize(); use click() instead of sendKeys() Check Element is Enabled However, no solution has solved the problem. This is the entire code: const { Builder, Browser, By, Key, until } = require("selenium-webdriver"); const chromeDriver = require("selenium-webdriver/chrome"); const chromeOptions = new chromeDriver.Options(); const chromeExample = async () => { const driver = await new Builder() .forBrowser(Browser.CHROME) .setChromeOptions(chromeOptions.headless()) .build(); driver.manage().window().maximize(); await driver.get("https://products.aspose.app/cad/text-extractor/dwg"); await driver.wait( until.elementLocated(By.className("filedrop-container width-for-mobile")), 10 * 1000 ); await driver.wait( until.elementIsEnabled( driver.findElement(By.className("filedrop-container width-for-mobile")) ), 10 * 1000 ); const tmp = await driver .findElement(By.className("filedrop-container width-for-mobile")) .sendKeys("/home/yeongori/workspace/Engineering-data-search-service/macro/public/images/testfile1.dwg"); console.log(tmp); }; The same error occurs when i change the code as below. await driver .findElement(By.className("filedrop-container width-for-mobile")) .sendKeys(Key.ENTER); One strange thing is that if i change sendKeys to click and check tmp with console.log, it is null. This is Project Directory How can I solve this problem? I'm sorry if it's too basic a question. But I'd be happy if there was any hint. Thank you. WSL2(Ubuntu-20.04), Node.js v18.12.1
[ "You need to use sendKeys on the input element which is nested deeper in the element that you are currently trying to send keys to.\nYou can reach the element with this xpath:\n\"//*[contains(@id,'UploadFileInput')]\"\n\n" ]
[ 0 ]
[]
[]
[ "node.js", "selenium", "selenium_webdriver" ]
stackoverflow_0074666397_node.js_selenium_selenium_webdriver.txt
Q: need to run while loop for multiple users in jmeter I am using jmeter to test the performance for the ride booking app.I need to run the while controller which runs the events fetching api continuously until the ride is completed or if driver is not available. This runs correctly for one user .But if i run the plan for multiple users then the while controller enters infinite loop.How can I fix this? A: While Controller is being executed unless its condition (a Function or Variable) resolves to true If it runs into an endless loop - most probably your server responds with something you don't expect, i.e. an error because it gets overloaded. So I would suggest taking 2 actions: Temporarily enable storing of responses into .jtl or a separate file and inspect what does the server return and amend your While Controller's condition accordingly And/or limit maximum number of iterations of the While Controller to some reasonable number, i.e. 10 or 20 or whatever is acceptable value, example __jexl3() function ${__jexl3("${status}" != "running" && ${__jm__While Controller__idx} < 20,)}
need to run while loop for multiple users in jmeter
I am using jmeter to test the performance for the ride booking app.I need to run the while controller which runs the events fetching api continuously until the ride is completed or if driver is not available. This runs correctly for one user .But if i run the plan for multiple users then the while controller enters infinite loop.How can I fix this?
[ "While Controller is being executed unless its condition (a Function or Variable) resolves to true\nIf it runs into an endless loop - most probably your server responds with something you don't expect, i.e. an error because it gets overloaded.\nSo I would suggest taking 2 actions:\n\nTemporarily enable storing of responses into .jtl or a separate file and inspect what does the server return and amend your While Controller's condition accordingly\n\nAnd/or limit maximum number of iterations of the While Controller to some reasonable number, i.e. 10 or 20 or whatever is acceptable value, example __jexl3() function\n${__jexl3(\"${status}\" != \"running\" && ${__jm__While Controller__idx} < 20,)}\n\n\n\n" ]
[ 0 ]
[]
[]
[ "android_multiple_users", "controller", "jmeter", "while_loop" ]
stackoverflow_0074666944_android_multiple_users_controller_jmeter_while_loop.txt
Q: Remove empty strings from a list of strings on each row in a pandas dataframe I have a pandas dataframe and one of the columns contains a list of strings e.g: ['', 'Hello', 'The house is warm', '', 'What time is it'] The strings are different for each row of the dataframe but all lists on each row contain empty strings. How can I remove these? The column is called 'Description'. I have tried the following methods: df['Description'] = df['Description', [i for i in df['Description'] if i]] while("" in df['Description']): df['Description'].remove("") df['Description'] = [list(filter(None, sublist)) for sublist in df['Description']] But none work. Thank you in advance! A: create new list and append only string that is not empty use eval() if they are string representation of list df['Description'] = df['Description'].apply(lambda x: [item for item in eval(x) if item != ''])
Remove empty strings from a list of strings on each row in a pandas dataframe
I have a pandas dataframe and one of the columns contains a list of strings e.g: ['', 'Hello', 'The house is warm', '', 'What time is it'] The strings are different for each row of the dataframe but all lists on each row contain empty strings. How can I remove these? The column is called 'Description'. I have tried the following methods: df['Description'] = df['Description', [i for i in df['Description'] if i]] while("" in df['Description']): df['Description'].remove("") df['Description'] = [list(filter(None, sublist)) for sublist in df['Description']] But none work. Thank you in advance!
[ "create new list and append only string that is not empty\nuse eval() if they are string representation of list\ndf['Description'] = df['Description'].apply(lambda x: [item for item in eval(x) if item != ''])\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "list", "pandas", "python", "string" ]
stackoverflow_0074667700_dataframe_list_pandas_python_string.txt
Q: How Can I Pagination Next and Previous With Firebase Database Without createdAt There is no createdAt column in the database. I'm trying to pagination, but it's not working properly. When I press the previous button endBefore(firstElement) When I press the next button startAfter(lastElement) There is no problem going forward, but the page order is broken when coming back. How can I solve this? const queryConstraints = [] if(onlyMain) queryConstraints.push(where("mainpost","==",true)) if(postType === "previous") queryConstraints.push(endBefore(visibleObject)) if(postType === "next") queryConstraints.push(startAfter(visibleObject)) query(collection(db,"posts"),orderBy("title"),where("title", ">=", "Demo"),limit(count),...queryConstraints) A: If you're browsing backwards, you need to use limitToLast instead of limit. With limitToLast the query returns the documents before the cursor object that you specify, while using limit returns the ones after it.
How Can I Pagination Next and Previous With Firebase Database Without createdAt
There is no createdAt column in the database. I'm trying to pagination, but it's not working properly. When I press the previous button endBefore(firstElement) When I press the next button startAfter(lastElement) There is no problem going forward, but the page order is broken when coming back. How can I solve this? const queryConstraints = [] if(onlyMain) queryConstraints.push(where("mainpost","==",true)) if(postType === "previous") queryConstraints.push(endBefore(visibleObject)) if(postType === "next") queryConstraints.push(startAfter(visibleObject)) query(collection(db,"posts"),orderBy("title"),where("title", ">=", "Demo"),limit(count),...queryConstraints)
[ "If you're browsing backwards, you need to use limitToLast instead of limit. With limitToLast the query returns the documents before the cursor object that you specify, while using limit returns the ones after it.\n" ]
[ 0 ]
[]
[]
[ "firebase", "google_cloud_firestore", "javascript" ]
stackoverflow_0074666755_firebase_google_cloud_firestore_javascript.txt
Q: How to pause/resume video recording using CameraX VideoCapture I couldn't find any resume() or pause() function to pause/resume video recording in my Android app. Any help would be appreciated. There is stopRecording() function only that I used to stop and save the video recording as given below. videoCapture.stopRecording() How to pause video recording, so that users can continue from they left with ? A: If you are using the new androidx.camera.video.VideCapture not the deprecated androidx.camera.VideCapture, the APIs are: pause: https://developer.android.com/reference/androidx/camera/video/Recording#pause() resume: https://developer.android.com/reference/androidx/camera/video/Recording#resume()
How to pause/resume video recording using CameraX VideoCapture
I couldn't find any resume() or pause() function to pause/resume video recording in my Android app. Any help would be appreciated. There is stopRecording() function only that I used to stop and save the video recording as given below. videoCapture.stopRecording() How to pause video recording, so that users can continue from they left with ?
[ "If you are using the new androidx.camera.video.VideCapture not the deprecated androidx.camera.VideCapture, the APIs are:\n\npause: https://developer.android.com/reference/androidx/camera/video/Recording#pause()\nresume: https://developer.android.com/reference/androidx/camera/video/Recording#resume()\n\n" ]
[ 0 ]
[]
[]
[ "android", "android_camerax", "camera", "video_recording" ]
stackoverflow_0074573748_android_android_camerax_camera_video_recording.txt