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: Module not found: Error: Can't resolve 'HtmlWebpackPlugin' in I have a problem using the html-webpack-plugin. I am learning React, and I need to use html-webpack-plugin, but when I run it in developer mode, I have this error: Error: Child compilation failed: Module not found: Error: Can't resolve 'HtmlWebpackPlugin' in '/home/paolo/develop/react-shop' ModuleNotFoundError: Module not found: Error: Can't resolve 'HtmlWebpackPlugin' in '/home/paolo/develop/ react-shop' at /home/paolo/develop/react-shop/node_modules/webpack/lib/Compilation.js:2016:28 at /home/paolo/develop/react-shop/node_modules/webpack/lib/NormalModuleFactory.js:798:13 at eval (eval at create (/home/paolo/develop/react-shop/node_modules/tapable/lib/HookCodeFactory.js: 33:10), :10:1) at /home/paolo/develop/react-shop/node_modules/webpack/lib/NormalModuleFactory.js:270:22 at eval (eval at create (/home/paolo/develop/react-shop/node_modules/tapable/lib/HookCodeFactory.js: 33:10), :9:1) at /home/paolo/develop/react-shop/node_modules/webpack/lib/NormalModuleFactory.js:541:15 at /home/paolo/develop/react-shop/node_modules/webpack/lib/NormalModuleFactory.js:116:11 at /home/paolo/develop/react-shop/node_modules/webpack/lib/NormalModuleFactory.js:612:8 at /home/paolo/develop/react-shop/node_modules/neo-async/async.js:2830:7 at done (/home/paolo/develop/react-shop/node_modules/neo-async/async.js:2925:13) - Compilation.js:2016 [react-shop]/[webpack]/lib/Compilation.js:2016:28 - NormalModuleFactory.js:798 [react-shop]/[webpack]/lib/NormalModuleFactory.js:798:13 - NormalModuleFactory.js:270 [react-shop]/[webpack]/lib/NormalModuleFactory.js:270:22 - NormalModuleFactory.js:541 [react-shop]/[webpack]/lib/NormalModuleFactory.js:541:15 - NormalModuleFactory.js:116 [react-shop]/[webpack]/lib/NormalModuleFactory.js:116:11 - NormalModuleFactory.js:612 [react-shop]/[webpack]/lib/NormalModuleFactory.js:612:8 - async.js:2830 [react-shop]/[neo-async]/async.js:2830:7 - async.js:2925 done [react-shop]/[neo-async]/async.js:2925:13 - child-compiler.js:169 [react-shop]/[html-webpack-plugin]/lib/child-compiler.js:169:18 - Compiler.js:551 finalCallback [react-shop]/[webpack]/lib/Compiler.js:551:5 - Compiler.js:577 [react-shop]/[webpack]/lib/Compiler.js:577:11 - Compiler.js:1196 [react-shop]/[webpack]/lib/Compiler.js:1196:17 - Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync] [react-shop]/[tapable]/lib/Hook.js:18:14 - Compiler.js:1192 [react-shop]/[webpack]/lib/Compiler.js:1192:33 - Compilation.js:2787 finalCallback [react-shop]/[webpack]/lib/Compilation.js:2787:11 - Compilation.js:3092 [react-shop]/[webpack]/lib/Compilation.js:3092:11* ` I have already installed the plugin. This is my webpack config: const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, mode: 'development', resolve: { extensions: [ '.js', '.jsx'] }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader' } }, { test: /\.html$/, use: { loader: 'HtmlWebpackPlugin', } } ] }, plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', filename: './index.html' }) ] } This is my package. { "name": "react-shop", "version": "1.0.0", "description": "react eshop", "main": "src/index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack serve --open", "build": "webpack --mode production" }, "keywords": [ "react", "javascript" ], "author": "Josue Quichca <[email protected]>", "license": "MIT", "dependencies": { "@babel/core": "^7.20.2", "@babel/preset-env": "^7.20.2", "@babel/preset-react": "^7.18.6", "babel-loader": "^9.1.0", "html-loader": "^4.2.0", "html-webpack-plugin": "^5.5.0", "react": "^18.2.0", "react-dom": "^18.2.0", "webpack": "^5.75.0", "webpack-cli": "^5.0.0", "webpack-dev-server": "^4.11.1" } } I am learning. Please help! A: Try this: Remove html-webpack-plugin from your package.json rm -rf node_modules npm cache clean -f npm i html-webpack-plugin --save-dev
Module not found: Error: Can't resolve 'HtmlWebpackPlugin' in
I have a problem using the html-webpack-plugin. I am learning React, and I need to use html-webpack-plugin, but when I run it in developer mode, I have this error: Error: Child compilation failed: Module not found: Error: Can't resolve 'HtmlWebpackPlugin' in '/home/paolo/develop/react-shop' ModuleNotFoundError: Module not found: Error: Can't resolve 'HtmlWebpackPlugin' in '/home/paolo/develop/ react-shop' at /home/paolo/develop/react-shop/node_modules/webpack/lib/Compilation.js:2016:28 at /home/paolo/develop/react-shop/node_modules/webpack/lib/NormalModuleFactory.js:798:13 at eval (eval at create (/home/paolo/develop/react-shop/node_modules/tapable/lib/HookCodeFactory.js: 33:10), :10:1) at /home/paolo/develop/react-shop/node_modules/webpack/lib/NormalModuleFactory.js:270:22 at eval (eval at create (/home/paolo/develop/react-shop/node_modules/tapable/lib/HookCodeFactory.js: 33:10), :9:1) at /home/paolo/develop/react-shop/node_modules/webpack/lib/NormalModuleFactory.js:541:15 at /home/paolo/develop/react-shop/node_modules/webpack/lib/NormalModuleFactory.js:116:11 at /home/paolo/develop/react-shop/node_modules/webpack/lib/NormalModuleFactory.js:612:8 at /home/paolo/develop/react-shop/node_modules/neo-async/async.js:2830:7 at done (/home/paolo/develop/react-shop/node_modules/neo-async/async.js:2925:13) - Compilation.js:2016 [react-shop]/[webpack]/lib/Compilation.js:2016:28 - NormalModuleFactory.js:798 [react-shop]/[webpack]/lib/NormalModuleFactory.js:798:13 - NormalModuleFactory.js:270 [react-shop]/[webpack]/lib/NormalModuleFactory.js:270:22 - NormalModuleFactory.js:541 [react-shop]/[webpack]/lib/NormalModuleFactory.js:541:15 - NormalModuleFactory.js:116 [react-shop]/[webpack]/lib/NormalModuleFactory.js:116:11 - NormalModuleFactory.js:612 [react-shop]/[webpack]/lib/NormalModuleFactory.js:612:8 - async.js:2830 [react-shop]/[neo-async]/async.js:2830:7 - async.js:2925 done [react-shop]/[neo-async]/async.js:2925:13 - child-compiler.js:169 [react-shop]/[html-webpack-plugin]/lib/child-compiler.js:169:18 - Compiler.js:551 finalCallback [react-shop]/[webpack]/lib/Compiler.js:551:5 - Compiler.js:577 [react-shop]/[webpack]/lib/Compiler.js:577:11 - Compiler.js:1196 [react-shop]/[webpack]/lib/Compiler.js:1196:17 - Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync] [react-shop]/[tapable]/lib/Hook.js:18:14 - Compiler.js:1192 [react-shop]/[webpack]/lib/Compiler.js:1192:33 - Compilation.js:2787 finalCallback [react-shop]/[webpack]/lib/Compilation.js:2787:11 - Compilation.js:3092 [react-shop]/[webpack]/lib/Compilation.js:3092:11* ` I have already installed the plugin. This is my webpack config: const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, mode: 'development', resolve: { extensions: [ '.js', '.jsx'] }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader' } }, { test: /\.html$/, use: { loader: 'HtmlWebpackPlugin', } } ] }, plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', filename: './index.html' }) ] } This is my package. { "name": "react-shop", "version": "1.0.0", "description": "react eshop", "main": "src/index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack serve --open", "build": "webpack --mode production" }, "keywords": [ "react", "javascript" ], "author": "Josue Quichca <[email protected]>", "license": "MIT", "dependencies": { "@babel/core": "^7.20.2", "@babel/preset-env": "^7.20.2", "@babel/preset-react": "^7.18.6", "babel-loader": "^9.1.0", "html-loader": "^4.2.0", "html-webpack-plugin": "^5.5.0", "react": "^18.2.0", "react-dom": "^18.2.0", "webpack": "^5.75.0", "webpack-cli": "^5.0.0", "webpack-dev-server": "^4.11.1" } } I am learning. Please help!
[ "Try this:\n\nRemove html-webpack-plugin from your package.json\nrm -rf node_modules\nnpm cache clean -f\nnpm i html-webpack-plugin --save-dev\n\n" ]
[ 0 ]
[]
[]
[ "html", "javascript", "reactjs", "webpack" ]
stackoverflow_0074663979_html_javascript_reactjs_webpack.txt
Q: My html button cannot be clicked, even though I modified only its style The code I have for my button in HTML is this simple What causes the button to not be able to be clicked, even though it is of type button? .menubutton { background-color: orange; color: black; text-align: center; font-size: 20px; padding: 20px 50px; } <button class="menubutton" style="position:absolute;left:10%" type="button"><b>Home</b></button> A: The button is able to be clicked, as demonstrated by the following event listener: document.querySelector(".menubutton").addEventListener("click", (e) => { console.log("button was clicked!"); }) .menubutton { background-color: orange; color: black; text-align: center; font-size: 20px; padding: 20px 50px; } <button class="menubutton" style="position:absolute;left:10%" type="button"><b>Home</b></button> You probably mean that the user can't tell it's a button. To improve this, add a hover effect and pointer cursor to the CSS: document.querySelector(".menubutton").addEventListener("click", (e) => { console.log("button was clicked!"); }) .menubutton { background-color: orange; color: black; text-align: center; font-size: 20px; padding: 20px 50px; /* pointer on hover */ cursor: pointer; /* transition */ transition: 0.2s ease; } /* hover event */ .menubutton:hover { background-color: lightgrey; } <button class="menubutton" style="position:absolute;left:10%" type="button"><b>Home</b></button> Read more about hover effects here and transitions here.
My html button cannot be clicked, even though I modified only its style
The code I have for my button in HTML is this simple What causes the button to not be able to be clicked, even though it is of type button? .menubutton { background-color: orange; color: black; text-align: center; font-size: 20px; padding: 20px 50px; } <button class="menubutton" style="position:absolute;left:10%" type="button"><b>Home</b></button>
[ "The button is able to be clicked, as demonstrated by the following event listener:\n\n\ndocument.querySelector(\".menubutton\").addEventListener(\"click\", (e) => {\n console.log(\"button was clicked!\");\n})\n.menubutton {\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n}\n<button class=\"menubutton\" style=\"position:absolute;left:10%\" type=\"button\"><b>Home</b></button>\n\n\n\nYou probably mean that the user can't tell it's a button. To improve this, add a hover effect and pointer cursor to the CSS:\n\n\ndocument.querySelector(\".menubutton\").addEventListener(\"click\", (e) => {\n console.log(\"button was clicked!\");\n})\n.menubutton {\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n \n /* pointer on hover */\n cursor: pointer;\n /* transition */\n transition: 0.2s ease;\n}\n\n/* hover event */\n.menubutton:hover {\n background-color: lightgrey;\n}\n<button class=\"menubutton\" style=\"position:absolute;left:10%\" type=\"button\"><b>Home</b></button>\n\n\n\nRead more about hover effects here and transitions here.\n" ]
[ 2 ]
[ "\nI don't think you need to add type=button on a button element.\nYou should add all the styles in the element in the <style> tag.\n\nUsing these changes, you should have:\nHTML\n<button class=\"menubutton\">\n <b>Home</b>\n</button>\n\nCSS\n<style>\n .menubutton {\n position: absolute;\n left: 10%;\n background-color: orange;\n color: black;\n text-align: center;\n font-size: 20px;\n padding: 20px 50px;\n }\n</style>\n\n" ]
[ -2 ]
[ "button", "css", "html" ]
stackoverflow_0074670186_button_css_html.txt
Q: Compilation error when creating new project in Unity I'm totally new in Unity and C#, and it's the first time I download Unity. The problem I'm facing is: Evertime I try to create a totally new project or open an official example project should contain no error, the Unity will say that there are compilation errors in my project, just like the screenshot below: Error pop-up This situation will happen in any different version of Unity, I have tried these versions: 2021.3.14, 2020.3.42, 2020.3.25, 2019.4.40. And the error messages in console of each version are different, in 2021.3.14: Error message in console (This kind of disorderly code should be Chinese I think, the reason maybe the Chinese encoded question in Unity. But I don't know why, because the Unity Hub and Unity I installed are all from UK website) In 2020.3.42 and 2020.3.25: Error message in console And in 2019.4.40 the error message is just like the error message in 2020 version, just the "Compiler version 3.5.0-dev" changes to "Compiler version 2.9.1" (I don't have the screenshot cause I have deleted the 2019 version). Here I'll explain the process I download and install Unity: I just have an anaconda preinstalled in my computer(which is related to the Unity), and for the first time, I also have the Visual Studio2019 installed in my computer(But I try to uninstall VS2019 before install Unity later, it doesn't work). And I download and install the Unity Hub from official website, then install the Unity 2021.3.14 in Unity Hub. That's all the process, I didn't change anything else in the system about Unity. (There is actually one another thing I have done, but I don't think it's a reason. I download the ml-agents plugin in github, and created a new anaconda environment for it, with just python3.6 and pytorch and ml-agents installed. Then I try to add ml-agents in Unity's packages even it's in compilation error state.) Here is some info about my computer: UK computer with Windows11, with anaconda, some jdk and SQL installed. And here is the list of things I have tried, all from internet: Change the "Api Compatibility Level*" in Edit->Project Settings->Player->Other Settings->Configuration Download different version of Unity(as mentioned above) Delete some packages that may cause this problem Reimport all the assets of the project Delete the Unity_lic.ulf file in the directory: C:\ProgramData\Unity and let Unity reload it Somebody says this may be caused by some antivirus program, so I removed all the antivirus program on my computer (except virus defense program of win11, cause I don't know how to close it and I think it is better to not close it), and completely remove all the Unity files on my computer (probably, I don't know), the remove steps are: (1) Delete the Unity Editor and Unity Hub files directly (2) Delete temporary file related to Unity: C:\ProgramData\Unity C:\Users\Username\AppData\Local\Unity C:\Users\Username\AppData\Local\unityhub-updater C:\Users\Username\AppData\LocalLow\Unity C:\Users\Username\AppData\Roaming\Unity C:\Users\Username\AppData\Roaming\UnityHub (3) Remove all the Unity related folders in windows registry(to ensure the thing I'm saying, to open this, press win+R, then type"regedit"): HKEY_CURRENT_USER\Software\Unity HKEY_CURRENT_USER\Software\UnityTechnologie And reinstall the whole Unity in a totally different directory, to avoid the Unity influenced by the folder path name(like too long, or contains Chinese character), I create a new folder F:\Unity, and create four folder"Download", "Editor", "Hub", "Project" to hold download tem files, Unity Editor, Unity Hub and project file respectively. Then I download and install Unity Hub, then install Unity Editor in Unity Hub, create new project, and everything don't change... P.S. I also download a Unity use the same process as me on the computer of my roommate. His computer is also win11, with anaconda and Visual Studio preinstalled. And everything went right, it just took me several minutes to successfully create a new project. Can someone tell me what kind of things can influence the download process of Unity (Like other programming environment or IDE)? And how can I fix this problem? A: You tried every possible solution maybe it's time to reinstall a clean windows.
Compilation error when creating new project in Unity
I'm totally new in Unity and C#, and it's the first time I download Unity. The problem I'm facing is: Evertime I try to create a totally new project or open an official example project should contain no error, the Unity will say that there are compilation errors in my project, just like the screenshot below: Error pop-up This situation will happen in any different version of Unity, I have tried these versions: 2021.3.14, 2020.3.42, 2020.3.25, 2019.4.40. And the error messages in console of each version are different, in 2021.3.14: Error message in console (This kind of disorderly code should be Chinese I think, the reason maybe the Chinese encoded question in Unity. But I don't know why, because the Unity Hub and Unity I installed are all from UK website) In 2020.3.42 and 2020.3.25: Error message in console And in 2019.4.40 the error message is just like the error message in 2020 version, just the "Compiler version 3.5.0-dev" changes to "Compiler version 2.9.1" (I don't have the screenshot cause I have deleted the 2019 version). Here I'll explain the process I download and install Unity: I just have an anaconda preinstalled in my computer(which is related to the Unity), and for the first time, I also have the Visual Studio2019 installed in my computer(But I try to uninstall VS2019 before install Unity later, it doesn't work). And I download and install the Unity Hub from official website, then install the Unity 2021.3.14 in Unity Hub. That's all the process, I didn't change anything else in the system about Unity. (There is actually one another thing I have done, but I don't think it's a reason. I download the ml-agents plugin in github, and created a new anaconda environment for it, with just python3.6 and pytorch and ml-agents installed. Then I try to add ml-agents in Unity's packages even it's in compilation error state.) Here is some info about my computer: UK computer with Windows11, with anaconda, some jdk and SQL installed. And here is the list of things I have tried, all from internet: Change the "Api Compatibility Level*" in Edit->Project Settings->Player->Other Settings->Configuration Download different version of Unity(as mentioned above) Delete some packages that may cause this problem Reimport all the assets of the project Delete the Unity_lic.ulf file in the directory: C:\ProgramData\Unity and let Unity reload it Somebody says this may be caused by some antivirus program, so I removed all the antivirus program on my computer (except virus defense program of win11, cause I don't know how to close it and I think it is better to not close it), and completely remove all the Unity files on my computer (probably, I don't know), the remove steps are: (1) Delete the Unity Editor and Unity Hub files directly (2) Delete temporary file related to Unity: C:\ProgramData\Unity C:\Users\Username\AppData\Local\Unity C:\Users\Username\AppData\Local\unityhub-updater C:\Users\Username\AppData\LocalLow\Unity C:\Users\Username\AppData\Roaming\Unity C:\Users\Username\AppData\Roaming\UnityHub (3) Remove all the Unity related folders in windows registry(to ensure the thing I'm saying, to open this, press win+R, then type"regedit"): HKEY_CURRENT_USER\Software\Unity HKEY_CURRENT_USER\Software\UnityTechnologie And reinstall the whole Unity in a totally different directory, to avoid the Unity influenced by the folder path name(like too long, or contains Chinese character), I create a new folder F:\Unity, and create four folder"Download", "Editor", "Hub", "Project" to hold download tem files, Unity Editor, Unity Hub and project file respectively. Then I download and install Unity Hub, then install Unity Editor in Unity Hub, create new project, and everything don't change... P.S. I also download a Unity use the same process as me on the computer of my roommate. His computer is also win11, with anaconda and Visual Studio preinstalled. And everything went right, it just took me several minutes to successfully create a new project. Can someone tell me what kind of things can influence the download process of Unity (Like other programming environment or IDE)? And how can I fix this problem?
[ "You tried every possible solution maybe it's time to reinstall a clean windows.\n" ]
[ 0 ]
[]
[]
[ "c#", "unity3d" ]
stackoverflow_0074646433_c#_unity3d.txt
Q: AxiosError: Network Error in React Native on making api request to local backend Frontend await axios.get("http://localhost:8000/admin/api/getcategories",{ "Content-Type": "application/json", }).then(result=>{ console.log(result); }).catch(err=>{ console.log(err); }) Backend const cors = require('cors'); app.use(cors()); Tried restarting the application, and with other api tried sending without headers, but nothing worked, also added <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> for android and NSAllowsArbitraryLoads for IOS A: Try to use ngrok (https://ngrok.com/) to make your local API public. It is free for developers
AxiosError: Network Error in React Native on making api request to local backend
Frontend await axios.get("http://localhost:8000/admin/api/getcategories",{ "Content-Type": "application/json", }).then(result=>{ console.log(result); }).catch(err=>{ console.log(err); }) Backend const cors = require('cors'); app.use(cors()); Tried restarting the application, and with other api tried sending without headers, but nothing worked, also added <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> for android and NSAllowsArbitraryLoads for IOS
[ "Try to use ngrok (https://ngrok.com/) to make your local API public. It is free for developers\n" ]
[ 0 ]
[]
[]
[ "axios", "node.js", "react_native", "reactjs" ]
stackoverflow_0074669083_axios_node.js_react_native_reactjs.txt
Q: mistake with eslint with command I have this in my package.json: When I'm running "npm run analysis", I've got a problem with eslint How can I solve this ? Thank you for your help A: Close the file with errors (babelrc) run npm run analysis:lint:eslint --fix The errors will be fixed with the eslint. Possible causes: Git made it so You edited the file and it cot converted to crlf by whatever reason
mistake with eslint with command
I have this in my package.json: When I'm running "npm run analysis", I've got a problem with eslint How can I solve this ? Thank you for your help
[ "\nClose the file with errors (babelrc)\nrun npm run analysis:lint:eslint --fix\nThe errors will be fixed with the eslint.\n\nPossible causes:\n\nGit made it so\nYou edited the file and it cot converted to crlf by whatever reason\n\n" ]
[ 1 ]
[]
[]
[ "eslint", "javascript", "typescript" ]
stackoverflow_0074666778_eslint_javascript_typescript.txt
Q: Android Kotlin Click Event for Back Button in Action Bar I try to get action after pressing back button in top toolbar class TagsFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity as AppCompatActivity?)?.supportActionBar?.title = "$selectedItemText Tags" (activity as AppCompatActivity?)?.supportActionBar?.setDisplayHomeAsUpEnabled(true) // This callback will only be called when MyFragment is at least Started. val callback = requireActivity().onBackPressedDispatcher.addCallback(this) { Log.d(InTorry.TAG, "TagsFragment: back BTN Pressed") } } } Unfortunately, it doest log anything I found I should add OnBackPressedCallback but it doesnt work as well : class TagsFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val selectedItemText = arguments?.getString("selectedItemText")//get arguments (activity as AppCompatActivity?)?.supportActionBar?.title = "$selectedItemText Tags" (activity as AppCompatActivity?)?.supportActionBar?.setDisplayHomeAsUpEnabled(true) (activity as AppCompatActivity?)?.onBackPressedDispatcher?.addCallback( this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { Log.d(InTorry.TAG, "Fragment back pressed invoked") // Do custom work here // if you want onBackPressed() to be called as normal afterwards if (isEnabled) { isEnabled = false requireActivity().onBackPressed() } } } ) } Kind regards Jack A: put this in onCreate method getActionBar().setDisplayHomeAsUpEnabled(true); //and then override this method and find id. @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; default: return super.onOptionsItemSelected(item); } } A: I know sometimes it is painful when android just deprecates on of their on Event functions ,Anyways this is your code : toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().onBackPressed(); } }); and you can just remove the onClickListener Interface and shortcut it if you desire like this : toolbar.setNavigationOnClickListener { requireActivity().onBackPressedDispatcher.onBackPressed() } should be working fine A: Thank you all The code I use now: For device back button, in Activity onCreate() class HomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) setSupportActionBar(findViewById(R.id.toolbar)) supportActionBar?.setDisplayHomeAsUpEnabled(true) onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { Log.d(InTorry.TAG,"device back btn click") //finish() } }) Toolbar Back Button arrow - Now I know that it works like one big menu override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> {// this is my back button - simply home Log.d(InTorry.TAG,"Toolbar Back BTN Click") ... } R.id.top_menu_settings -> { Log.d(InTorry.TAG,"top_menu_settings click") true } R.id.top_menu_logout -> { Log.d(InTorry.TAG,"top_menu_logout click") Firebase.auth.signOut() gotoLogin() true } else -> super.onOptionsItemSelected(item) } }
Android Kotlin Click Event for Back Button in Action Bar
I try to get action after pressing back button in top toolbar class TagsFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity as AppCompatActivity?)?.supportActionBar?.title = "$selectedItemText Tags" (activity as AppCompatActivity?)?.supportActionBar?.setDisplayHomeAsUpEnabled(true) // This callback will only be called when MyFragment is at least Started. val callback = requireActivity().onBackPressedDispatcher.addCallback(this) { Log.d(InTorry.TAG, "TagsFragment: back BTN Pressed") } } } Unfortunately, it doest log anything I found I should add OnBackPressedCallback but it doesnt work as well : class TagsFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val selectedItemText = arguments?.getString("selectedItemText")//get arguments (activity as AppCompatActivity?)?.supportActionBar?.title = "$selectedItemText Tags" (activity as AppCompatActivity?)?.supportActionBar?.setDisplayHomeAsUpEnabled(true) (activity as AppCompatActivity?)?.onBackPressedDispatcher?.addCallback( this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { Log.d(InTorry.TAG, "Fragment back pressed invoked") // Do custom work here // if you want onBackPressed() to be called as normal afterwards if (isEnabled) { isEnabled = false requireActivity().onBackPressed() } } } ) } Kind regards Jack
[ "put this in onCreate method\ngetActionBar().setDisplayHomeAsUpEnabled(true);\n//and then override this method and find id.\n @Override\npublic boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n NavUtils.navigateUpFromSameTask(this);\n return true;\n default:\n return super.onOptionsItemSelected(item);\n }\n}\n\n", "I know sometimes it is painful when android just deprecates on of their on Event functions ,Anyways this is your code :\ntoolbar.setNavigationOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n getActivity().onBackPressed();\n }\n});\n\nand you can just remove the onClickListener Interface and shortcut it if you desire like this :\n toolbar.setNavigationOnClickListener {\n requireActivity().onBackPressedDispatcher.onBackPressed()\n }\n\nshould be working fine\n", "Thank you all\nThe code I use now:\n\nFor device back button, in Activity onCreate()\n\nclass HomeActivity : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_home)\n\n setSupportActionBar(findViewById(R.id.toolbar))\n supportActionBar?.setDisplayHomeAsUpEnabled(true)\n\n\n onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {\n override fun handleOnBackPressed() {\n Log.d(InTorry.TAG,\"device back btn click\")\n //finish()\n }\n })\n\n\nToolbar Back Button arrow - Now I know that it works like one big menu\noverride fun onOptionsItemSelected(item: MenuItem): Boolean {\n return when (item.itemId) {\n android.R.id.home -> {// this is my back button - simply home\n\n Log.d(InTorry.TAG,\"Toolbar Back BTN Click\")\n\n ...\n }\n R.id.top_menu_settings -> {\n Log.d(InTorry.TAG,\"top_menu_settings click\")\n true\n }\n R.id.top_menu_logout -> {\n Log.d(InTorry.TAG,\"top_menu_logout click\")\n Firebase.auth.signOut()\n gotoLogin()\n true\n }\n\n\n else -> super.onOptionsItemSelected(item)\n }\n\n}\n\n\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "android", "kotlin" ]
stackoverflow_0074545340_android_kotlin.txt
Q: Translate ninject ISecureDataFormat binding to Autofac I am migrating a large codebase from Ninject to Autofac and am struggling on one of the bindings (that i believe is causing an activation error based on some of my debugging). Ninject: Bind<ISecureDataFormat<AuthenticationTicket>>() .ToMethod(context => { var owinContext = context.Kernel.Get<IOwinContext>(); return owinContext .Get<ISecureDataFormat<AuthenticationTicket>>("SecureDataFormat"); }); Autofac (what i have): builder.Register( context => context.Resolve<IOwinContext>() .Get<ISecureDataFormat<AuthenticationTicket>>("SecureDataFormat")) .As<ISecureDataFormat<AuthenticationTicket>>(); Startup.cs: var container = RegisterIoC(app, config); public IContainer RegisterIoC(IAppBuilder app, HttpConfiguration config) { var builder = new ContainerBuilder(); builder = RegisterDependencies(builder); builder = RegisterFilters(builder, config); /*builder.RegisterModule<DebuggingRequestModule>();*/ var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); app.UseAutofacMiddleware(container); app.UseAutofacMvc(); app.UseAutofacWebApi(config); app.UseWebApi(config); return container; } More: builder.RegisterModule<ApiDependencyModule>().RegisterModule<AutofacWebTypesModule>(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterApiControllers(typeof(AccountController).Assembly); (seemingly) associated constructors: AccountController.cs: public AccountController(ILoginService loginService, IBearerTokenStore tokenStore, IRememberMeCookieService rememberMeCookieService, IInternalSsoChallenge ssoChallenge) { } LoginService.cs: public LoginService(IBearerTokenStore tokenStore, IGrantTypeProvider grantProvider, IRememberMeCookieService rememberMeCookieService) { } BearerTokenCookieStore.cs: public BearerTokenCookieStore(IOwinContext owinContext, ISecureDataFormat<AuthenticationTicket> secureDataFormat, IAppSettingsReader appSettingsReader, ICookieService cookieService) { } I have a logging module that is helping me debug and this is the message list i have Resolving _______.Login.Controllers.AccountController --Resolving _______.ApiGateway.Services.Auth.LoginService ----Resolving _______.ApiGateway.Security.OAuth.BearerTokenCookieStore ------Resolving Microsoft.Owin.Security.DataHandler.SecureDataFormat`1[Microsoft.Owin.Security.AuthenticationTicket] Exception thrown: 'Autofac.Core.DependencyResolutionException' in Autofac.dll Exception thrown: 'Autofac.Core.DependencyResolutionException' in Autofac.dll Exception thrown: 'Autofac.Core.DependencyResolutionException' in Autofac.dll The thread 0x1014 has exited with code 0 (0x0). Edit: The exception I am seeing: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = AccountController (DelegateActivator), Services = [____.Login.Controllers.AccountController], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = AccountController (ReflectionActivator), Services = [____.Login.Controllers.AccountController], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = LoginService (DelegateActivator), Services = [____.ApiGateway.Services.Auth.ILoginService], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = LoginService (ReflectionActivator), Services = [____.ApiGateway.Services.Auth.ILoginService], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = BearerTokenCookieStore (DelegateActivator), Services = [____.ApiGateway.Security.OAuth.IBearerTokenStore], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = BearerTokenCookieStore (ReflectionActivator), Services = [____.ApiGateway.Security.OAuth.IBearerTokenStore], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = Shared, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ISecureDataFormat`1 (DelegateActivator), Services = [Microsoft.Owin.Security.ISecureDataFormat`1[[Microsoft.Owin.Security.AuthenticationTicket, Microsoft.Owin.Security, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ISecureDataFormat`1 (DelegateActivator), Services = [Microsoft.Owin.Security.ISecureDataFormat`1[[Microsoft.Owin.Security.AuthenticationTicket, Microsoft.Owin.Security, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> A delegate registered to create instances of 'Microsoft.Owin.Security.ISecureDataFormat`1[Microsoft.Owin.Security.AuthenticationTicket]' returned null. (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) Inner most: A delegate registered to create instances of 'Microsoft.Owin.Security.ISecureDataFormat`1[Microsoft.Owin.Security.AuthenticationTicket]' returned null. A: We can use autofac with those c# owin inversion-of-control (ninject to autofac) like below, genericly Startup.cs public partial class Startup { public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); WebApiConfig.Register(config); ConfigureIoC(app, config); Components.Config(); Auth.ConfigureForApi(app); app.UseAutofacWebApi(config); app.UseCors(CorsOptions.AllowAll); app.UseWebApi(config); config.EnsureInitialized(); } private void ConfigureIoC(IAppBuilder app, HttpConfiguration config) { IoC.RegisterModules( builder => { builder.Register<IAuthenticationManager>(c => c.Resolve<IOwinContext>().Authentication).InstancePerRequest(); builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest(); builder.RegisterApiControllers(typeof(Startup).Assembly).PropertiesAutowired(); }, container => { config.DependencyResolver = new AutofacWebApiDependencyResolver(container); app.UseAutofacMiddleware(container); }, true ); } } WebApiConfig.cs public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } Component config: public static class Components { public static void Config() { TypeAdapterConfig.GlobalSettings.AllowImplicitDestinationInheritance = true; var registers = new List<IRegister>(); registers.Add(new DtoMapping()); registers.Add(new MappingRegistration()); TypeAdapterConfig.GlobalSettings.Apply(registers); ObjectMapper.Current = new MapsterAdapter(); DbConfiguration.Loaded += DbConfiguration_Loaded; var r = new Registrations(); r.Run(); } private static void DbConfiguration_Loaded(object sender, System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationLoadedEventArgs e) { e.ReplaceService<DbProviderServices>((s, k) => System.Data.Entity.SqlServer.SqlProviderServices.Instance); } } Authentication: public class Auth { public static void ConfigureForMvc(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, UserEntity, int>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie), getUserIdCallback: (Identity) => Identity.GetUserId<int>()) } }); } public static void ConfigureForApi(IAppBuilder app) { var OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/oauth2/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(120), Provider = new CustomOAuthProvider(), AccessTokenFormat = new CustomJwtFormat(ConfigConstants.Issuer) }; app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseJwtBearerAuthentication( new JwtBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, AllowedAudiences = new[] { ConfigConstants.AudienceId }, IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] { new SymmetricKeyIssuerSecurityTokenProvider(ConfigConstants.Issuer, ConfigConstants.AudienceSecurityKey) } }); } } A: The error message indicates that there is a problem with the registration of the AccountController. One possible reason for this error is that the AccountController constructor has dependencies that have not been registered with the container. In Autofac, you must register all of the dependencies that a component needs in order for the component to be resolved successfully. In the case of the AccountController, its constructor has dependencies on ILoginService, IBearerTokenStore, IRememberMeCookieService, and IInternalSsoChallenge. These dependencies must be registered with the container before the AccountController can be resolved. To fix this error, you need to make sure that all of the AccountController's dependencies are registered with the container. You can do this by using the builder.Register() method to register the dependencies with the container. For example: builder.RegisterType<LoginService>().As<ILoginService>(); builder.RegisterType<BearerTokenStore>().As<IBearerTokenStore>(); builder.RegisterType<RememberMeCookieService>().As<IRememberMeCookieService>(); builder.RegisterType<InternalSsoChallenge>().As<IInternalSsoChallenge>(); After registering the dependencies, you should be able to use the AutofacDependencyResolver to resolve instances of IOwinContext and ISecureDataFormat<AuthenticationTicket> from the container. You can do this by calling Resolve on the DependencyResolver class, like this: var resolver = new AutofacDependencyResolver(container); var owinContext = resolver.Resolve<IOwinContext>(); var secureDataFormat = resolver.Resolve<ISecureDataFormat<AuthenticationTicket>>(); Once you have those instances, you can use them to configure the BearerTokenCookieStore and LoginService as needed.
Translate ninject ISecureDataFormat binding to Autofac
I am migrating a large codebase from Ninject to Autofac and am struggling on one of the bindings (that i believe is causing an activation error based on some of my debugging). Ninject: Bind<ISecureDataFormat<AuthenticationTicket>>() .ToMethod(context => { var owinContext = context.Kernel.Get<IOwinContext>(); return owinContext .Get<ISecureDataFormat<AuthenticationTicket>>("SecureDataFormat"); }); Autofac (what i have): builder.Register( context => context.Resolve<IOwinContext>() .Get<ISecureDataFormat<AuthenticationTicket>>("SecureDataFormat")) .As<ISecureDataFormat<AuthenticationTicket>>(); Startup.cs: var container = RegisterIoC(app, config); public IContainer RegisterIoC(IAppBuilder app, HttpConfiguration config) { var builder = new ContainerBuilder(); builder = RegisterDependencies(builder); builder = RegisterFilters(builder, config); /*builder.RegisterModule<DebuggingRequestModule>();*/ var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); app.UseAutofacMiddleware(container); app.UseAutofacMvc(); app.UseAutofacWebApi(config); app.UseWebApi(config); return container; } More: builder.RegisterModule<ApiDependencyModule>().RegisterModule<AutofacWebTypesModule>(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterApiControllers(typeof(AccountController).Assembly); (seemingly) associated constructors: AccountController.cs: public AccountController(ILoginService loginService, IBearerTokenStore tokenStore, IRememberMeCookieService rememberMeCookieService, IInternalSsoChallenge ssoChallenge) { } LoginService.cs: public LoginService(IBearerTokenStore tokenStore, IGrantTypeProvider grantProvider, IRememberMeCookieService rememberMeCookieService) { } BearerTokenCookieStore.cs: public BearerTokenCookieStore(IOwinContext owinContext, ISecureDataFormat<AuthenticationTicket> secureDataFormat, IAppSettingsReader appSettingsReader, ICookieService cookieService) { } I have a logging module that is helping me debug and this is the message list i have Resolving _______.Login.Controllers.AccountController --Resolving _______.ApiGateway.Services.Auth.LoginService ----Resolving _______.ApiGateway.Security.OAuth.BearerTokenCookieStore ------Resolving Microsoft.Owin.Security.DataHandler.SecureDataFormat`1[Microsoft.Owin.Security.AuthenticationTicket] Exception thrown: 'Autofac.Core.DependencyResolutionException' in Autofac.dll Exception thrown: 'Autofac.Core.DependencyResolutionException' in Autofac.dll Exception thrown: 'Autofac.Core.DependencyResolutionException' in Autofac.dll The thread 0x1014 has exited with code 0 (0x0). Edit: The exception I am seeing: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = AccountController (DelegateActivator), Services = [____.Login.Controllers.AccountController], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = AccountController (ReflectionActivator), Services = [____.Login.Controllers.AccountController], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = LoginService (DelegateActivator), Services = [____.ApiGateway.Services.Auth.ILoginService], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = LoginService (ReflectionActivator), Services = [____.ApiGateway.Services.Auth.ILoginService], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = BearerTokenCookieStore (DelegateActivator), Services = [____.ApiGateway.Security.OAuth.IBearerTokenStore], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = BearerTokenCookieStore (ReflectionActivator), Services = [____.ApiGateway.Security.OAuth.IBearerTokenStore], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = Shared, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ISecureDataFormat`1 (DelegateActivator), Services = [Microsoft.Owin.Security.ISecureDataFormat`1[[Microsoft.Owin.Security.AuthenticationTicket, Microsoft.Owin.Security, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ISecureDataFormat`1 (DelegateActivator), Services = [Microsoft.Owin.Security.ISecureDataFormat`1[[Microsoft.Owin.Security.AuthenticationTicket, Microsoft.Owin.Security, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> A delegate registered to create instances of 'Microsoft.Owin.Security.ISecureDataFormat`1[Microsoft.Owin.Security.AuthenticationTicket]' returned null. (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) Inner most: A delegate registered to create instances of 'Microsoft.Owin.Security.ISecureDataFormat`1[Microsoft.Owin.Security.AuthenticationTicket]' returned null.
[ "We can use autofac with those c# owin inversion-of-control (ninject to autofac) like below, genericly\nStartup.cs\npublic partial class Startup\n {\n public void Configuration(IAppBuilder app)\n {\n\n var config = new HttpConfiguration();\n WebApiConfig.Register(config); \n\n ConfigureIoC(app, config);\n Components.Config();\n\n Auth.ConfigureForApi(app);\n\n app.UseAutofacWebApi(config);\n app.UseCors(CorsOptions.AllowAll);\n app.UseWebApi(config);\n config.EnsureInitialized();\n }\n\n private void ConfigureIoC(IAppBuilder app, HttpConfiguration config)\n {\n IoC.RegisterModules(\n builder =>\n {\n builder.Register<IAuthenticationManager>(c => c.Resolve<IOwinContext>().Authentication).InstancePerRequest();\n builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();\n builder.RegisterApiControllers(typeof(Startup).Assembly).PropertiesAutowired();\n },\n container =>\n {\n config.DependencyResolver = new AutofacWebApiDependencyResolver(container);\n app.UseAutofacMiddleware(container);\n\n },\n true\n );\n }\n\n }\n\nWebApiConfig.cs\npublic static class WebApiConfig\n{\n public static void Register(HttpConfiguration config)\n {\n config.MapHttpAttributeRoutes();\n\n config.Routes.MapHttpRoute(\n name: \"DefaultApi\",\n routeTemplate: \"api/{controller}/{id}\",\n defaults: new { id = RouteParameter.Optional }\n );\n\n }\n}\n\nComponent config:\npublic static class Components\n{\n public static void Config() {\n TypeAdapterConfig.GlobalSettings.AllowImplicitDestinationInheritance = true;\n var registers = new List<IRegister>();\n registers.Add(new DtoMapping());\n registers.Add(new MappingRegistration());\n TypeAdapterConfig.GlobalSettings.Apply(registers);\n\n ObjectMapper.Current = new MapsterAdapter();\n DbConfiguration.Loaded += DbConfiguration_Loaded;\n\n var r = new Registrations();\n r.Run();\n }\n\n\n private static void DbConfiguration_Loaded(object sender, System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationLoadedEventArgs e)\n {\n e.ReplaceService<DbProviderServices>((s, k) => System.Data.Entity.SqlServer.SqlProviderServices.Instance);\n }\n\n}\n\nAuthentication:\npublic class Auth\n {\n public static void ConfigureForMvc(IAppBuilder app)\n {\n app.UseCookieAuthentication(new CookieAuthenticationOptions\n {\n AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,\n LoginPath = new PathString(\"/Login\"),\n\n Provider = new CookieAuthenticationProvider\n {\n OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, UserEntity, int>(\n validateInterval: TimeSpan.FromMinutes(30),\n regenerateIdentityCallback: (manager, user) =>\n user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie),\n getUserIdCallback: (Identity) => Identity.GetUserId<int>())\n }\n });\n }\n\n public static void ConfigureForApi(IAppBuilder app)\n {\n var OAuthServerOptions = new OAuthAuthorizationServerOptions()\n {\n AllowInsecureHttp = true,\n TokenEndpointPath = new PathString(\"/oauth2/token\"),\n AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(120),\n Provider = new CustomOAuthProvider(),\n AccessTokenFormat = new CustomJwtFormat(ConfigConstants.Issuer)\n };\n\n app.UseOAuthAuthorizationServer(OAuthServerOptions);\n\n app.UseJwtBearerAuthentication(\n new JwtBearerAuthenticationOptions\n {\n AuthenticationMode = AuthenticationMode.Active,\n AllowedAudiences = new[] { ConfigConstants.AudienceId },\n IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]\n {\n new SymmetricKeyIssuerSecurityTokenProvider(ConfigConstants.Issuer, ConfigConstants.AudienceSecurityKey)\n }\n });\n\n }\n }\n\n", "The error message indicates that there is a problem with the registration of the AccountController. One possible reason for this error is that the AccountController constructor has dependencies that have not been registered with the container. In Autofac, you must register all of the dependencies that a component needs in order for the component to be resolved successfully. In the case of the AccountController, its constructor has dependencies on ILoginService, IBearerTokenStore, IRememberMeCookieService, and IInternalSsoChallenge. These dependencies must be registered with the container before the AccountController can be resolved.\nTo fix this error, you need to make sure that all of the AccountController's dependencies are registered with the container. You can do this by using the builder.Register() method to register the dependencies with the container.\nFor example:\nbuilder.RegisterType<LoginService>().As<ILoginService>();\nbuilder.RegisterType<BearerTokenStore>().As<IBearerTokenStore>();\nbuilder.RegisterType<RememberMeCookieService>().As<IRememberMeCookieService>();\nbuilder.RegisterType<InternalSsoChallenge>().As<IInternalSsoChallenge>();\n\nAfter registering the dependencies, you should be able to use the AutofacDependencyResolver to resolve instances of IOwinContext and ISecureDataFormat<AuthenticationTicket> from the container. You can do this by calling Resolve on the DependencyResolver class, like this:\nvar resolver = new AutofacDependencyResolver(container);\nvar owinContext = resolver.Resolve<IOwinContext>();\nvar secureDataFormat = resolver.Resolve<ISecureDataFormat<AuthenticationTicket>>();\n\nOnce you have those instances, you can use them to configure the BearerTokenCookieStore and LoginService as needed.\n" ]
[ 0, 0 ]
[ "Program.cs\nbuilder.Host.ConfigureContainer<ContainerBuilder>(builder => builder.RegisterModule(new AutofacBusinessModule()));\n\nAutoMapperProfil.cs\nnamespace BusinessKatman.AutoMappers\n{\n public class AutoMapperProfil : Profile\n {\n public AutoMapperProfil()\n {\n CreateMap<PageVM, Page>().ReverseMap();\n }\n }\n}\n\nControllers\nprivate readonly IMapper _mapper;\n public AutoIllerManager(IMapper mapper)\n { \n _mapper = mapper;\n }\n public IActionResult GetPageDetail\n{\nvar p = _mapper.Map<PageVM>(result);\n\n//and\n\nvar p = _mapper.Map<Page>(result);\n\n// list\n\nvar p = _mapper.Map<List<Page>>(result);\n}\n\n" ]
[ -1 ]
[ "autofac", "c#", "inversion_of_control", "ninject", "owin" ]
stackoverflow_0049536492_autofac_c#_inversion_of_control_ninject_owin.txt
Q: Stimulus controller to show/hide toolbox yet allow click I have a content editable block that has a toolbox. When you focus on the content editable block the toolbox will appear (it is a collapse button for the actual toolbar). If you clock on the toolbox, need to add the Bootstrap class "active" to it. If we focus completely out of the content block, that toolbox should disappear (and a new one appear on a different content block). Because of the need to click on the toolbox, I can't get the third event listener to work as expected. The HTML: .border.border-dark.p-4 .position-relative.w-100{data: {controller: "content", content:{block:{value: true}}}} .position-absolute.bg-white{style: "right: 101%"} %button.d-none.btn.btn-outline-dark{type: "button", data: {content_target: "toolbox", bs:{toggle: "collapse", target: "#toolbar1"}}} %i.bi.bi-hammer #toolbar1.collapse.position-absolute.bottom-100.bg-white.btn-toolbar{role: "toolbar", aria:{label: "Toolbar with button groups"}} .btn-group.me-2{role: "group", aria:{label: "First group"}} %button.btn.btn-outline-dark.active{type: "button"} H2 %button.btn.btn-outline-dark{type: "button"} H3 %button.btn.btn-outline-dark{type: "button"} H4 %button.btn.btn-outline-dark{type: "button"} H5 %button.btn.btn-outline-dark{type: "button"} H6 %button.btn.btn-outline-dark{type: "button"} %i.bi.bi-paragraph %p{contenteditable: true, data: {content_target: "contentBlock"}} This is some text and the Stimulus this.contentBlockTarget.addEventListener("focus", (event) => { this.toolboxTarget.classList.remove("d-none") }) this.toolboxTarget.addEventListener("click", (event) => { this.toolboxTarget.classList.add("active") this.toolboxTarget.classList.remove("active") }) this.contentBlockTarget.addEventListener("focusout", (event) => { this.toolboxTarget.classList.add("d-none") }) Here's my requirements: If user focuses on the contentBlock (in this HTML it's a ), toolbox should appear (remove class "d-none"). (first event listener does this fine) If user clicks on the toolbox, add class "active". (if third event listener is commented out, this works fine). If third listener is active, clicking the toolbox makes it disappear, so the toolbar won't actually appear. If user clicks anywhere that is NOT the toolbox, or the cursor is no longer in this area (like maintaining the cursor in there), then need to add "d-none" back. A: One way to solve this issue is to use a combination of event listeners and CSS classes. First, you can add the d-none class to the toolbox by default. Then, you can use the focus event listener on the content editable block to remove the d-none class and make the toolbox appear. To add the active class to the toolbox when it is clicked, you can use the click event listener on the toolbox itself. Inside the event listener, you can add the active class to the toolbox, and then remove it after a brief delay using the setTimeout function. Finally, to hide the toolbox when it is not in focus, you can use the focusout event listener on the content editable block. Inside the event listener, you can check if the user has clicked on the toolbox using the active class. If they haven't clicked on the toolbox, you can add the d-none class to hide it. // Add the "d-none" class to the toolbox by default this.toolboxTarget.classList.add("d-none"); // Show the toolbox when the content editable block is focused this.contentBlockTarget.addEventListener("focus", (event) => { this.toolboxTarget.classList.remove("d-none"); }); // Add the "active" class to the toolbox when it is clicked this.toolboxTarget.addEventListener("click", (event) => { this.toolboxTarget.classList.add("active"); setTimeout(() => { this.toolboxTarget.classList.remove("active"); }, 100); // Remove the "active" class after a brief delay }); // Hide the toolbox when it is not in focus this.contentBlockTarget.addEventListener("focusout", (event) => { if (!this.toolboxTarget.classList.contains("active")) { this.toolboxTarget.classList.add("d-none"); } });
Stimulus controller to show/hide toolbox yet allow click
I have a content editable block that has a toolbox. When you focus on the content editable block the toolbox will appear (it is a collapse button for the actual toolbar). If you clock on the toolbox, need to add the Bootstrap class "active" to it. If we focus completely out of the content block, that toolbox should disappear (and a new one appear on a different content block). Because of the need to click on the toolbox, I can't get the third event listener to work as expected. The HTML: .border.border-dark.p-4 .position-relative.w-100{data: {controller: "content", content:{block:{value: true}}}} .position-absolute.bg-white{style: "right: 101%"} %button.d-none.btn.btn-outline-dark{type: "button", data: {content_target: "toolbox", bs:{toggle: "collapse", target: "#toolbar1"}}} %i.bi.bi-hammer #toolbar1.collapse.position-absolute.bottom-100.bg-white.btn-toolbar{role: "toolbar", aria:{label: "Toolbar with button groups"}} .btn-group.me-2{role: "group", aria:{label: "First group"}} %button.btn.btn-outline-dark.active{type: "button"} H2 %button.btn.btn-outline-dark{type: "button"} H3 %button.btn.btn-outline-dark{type: "button"} H4 %button.btn.btn-outline-dark{type: "button"} H5 %button.btn.btn-outline-dark{type: "button"} H6 %button.btn.btn-outline-dark{type: "button"} %i.bi.bi-paragraph %p{contenteditable: true, data: {content_target: "contentBlock"}} This is some text and the Stimulus this.contentBlockTarget.addEventListener("focus", (event) => { this.toolboxTarget.classList.remove("d-none") }) this.toolboxTarget.addEventListener("click", (event) => { this.toolboxTarget.classList.add("active") this.toolboxTarget.classList.remove("active") }) this.contentBlockTarget.addEventListener("focusout", (event) => { this.toolboxTarget.classList.add("d-none") }) Here's my requirements: If user focuses on the contentBlock (in this HTML it's a ), toolbox should appear (remove class "d-none"). (first event listener does this fine) If user clicks on the toolbox, add class "active". (if third event listener is commented out, this works fine). If third listener is active, clicking the toolbox makes it disappear, so the toolbar won't actually appear. If user clicks anywhere that is NOT the toolbox, or the cursor is no longer in this area (like maintaining the cursor in there), then need to add "d-none" back.
[ "One way to solve this issue is to use a combination of event listeners and CSS classes.\nFirst, you can add the d-none class to the toolbox by default. Then, you can use the focus event listener on the content editable block to remove the d-none class and make the toolbox appear.\nTo add the active class to the toolbox when it is clicked, you can use the click event listener on the toolbox itself. Inside the event listener, you can add the active class to the toolbox, and then remove it after a brief delay using the setTimeout function.\nFinally, to hide the toolbox when it is not in focus, you can use the focusout event listener on the content editable block. Inside the event listener, you can check if the user has clicked on the toolbox using the active class. If they haven't clicked on the toolbox, you can add the d-none class to hide it.\n// Add the \"d-none\" class to the toolbox by default\nthis.toolboxTarget.classList.add(\"d-none\");\n\n// Show the toolbox when the content editable block is focused\nthis.contentBlockTarget.addEventListener(\"focus\", (event) => {\n this.toolboxTarget.classList.remove(\"d-none\");\n});\n\n// Add the \"active\" class to the toolbox when it is clicked\nthis.toolboxTarget.addEventListener(\"click\", (event) => {\n this.toolboxTarget.classList.add(\"active\");\n setTimeout(() => {\n this.toolboxTarget.classList.remove(\"active\");\n }, 100); // Remove the \"active\" class after a brief delay\n});\n\n// Hide the toolbox when it is not in focus\nthis.contentBlockTarget.addEventListener(\"focusout\", (event) => {\n if (!this.toolboxTarget.classList.contains(\"active\")) {\n this.toolboxTarget.classList.add(\"d-none\");\n }\n});\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "stimulus_reflex" ]
stackoverflow_0074664795_javascript_stimulus_reflex.txt
Q: firefox causes visual artifact with "transform:rotate;" Firefox is creating small lines on the triangles I've created and rotated. Chrome FireFox I've looked into what other questions have done and they recommended trying adding transform: translateZ(1px) rotate(-45deg); and background-clip: padding-box; but neither of those worked for me. Also, it is only the rotated triangles that have the line in the firefox browser. The page can be viewed at bingo-caller.herokuapp.com A: I tried on your page and it seems to work, add translateZ(1px) to the transform for the triangles. A: try this hack on the masked element: filter: blur(0.01px); A: Until now desc 2022 that still haven I fix using border with color depending to the background and can not use transparent of border color e.g I use white because my parent background is white border: 1px solid white;
firefox causes visual artifact with "transform:rotate;"
Firefox is creating small lines on the triangles I've created and rotated. Chrome FireFox I've looked into what other questions have done and they recommended trying adding transform: translateZ(1px) rotate(-45deg); and background-clip: padding-box; but neither of those worked for me. Also, it is only the rotated triangles that have the line in the firefox browser. The page can be viewed at bingo-caller.herokuapp.com
[ "I tried on your page and it seems to work, add translateZ(1px) to the transform for the triangles.\n\n", "try this hack on the masked element: filter: blur(0.01px);\n", "Until now desc 2022 that still haven\nI fix using border with color depending to the background and can not use transparent of border color e.g I use white because my parent background is white\nborder: 1px solid white;\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "css", "css_transforms", "firefox", "z_axis" ]
stackoverflow_0054189447_css_css_transforms_firefox_z_axis.txt
Q: How do I pass in a 1d array to sklearn's LabelEncoder? I'm following along an Uber-Lyft price prediction notebook on Kaggle, but I'm trying to use the Polars module. In cell 43 where they use sklearn's LabelEncoder, they have the following loop that appears to loop through each feature, except for price, and encodes it: from sklearn import preprocessing le = preprocessing.LabelEncoder() df_cat_encode= df_cat.copy() for col in df_cat_encode.select_dtypes(include='O').columns: df_cat_encode[col]=le.fit_transform(df_cat_encode[col]) The data being passed through looks like this: source destination cab_type name short_summary icon price Haymarket Square North Station Lyft Shared Mostly Cloudy partly-cloudy-night 5.0 Haymarket Square North Station Lyft Lux Rain rain 11.0 Haymarket Square North Station Lyft Lyft Clear clear-night 7.0 Haymarket Square North Station Lyft Lux Black XL Clear clear-night 26.0 and the label encoded result looks like this: 637975 rows x 7 columns source destination cab_type name short_summary icon price 5 7 0 7 4 5 5.0 5 7 0 2 8 6 11.0 5 7 0 5 0 1 7.0 5 7 0 4 6 1 26.0 ... ... ... ... ... ... ... The problem I'm having is when I try to build the same loop with Polars syntax like for col in df_cat_encode.select(["source","destination","cab_type","name","short_summary","icon"]).columns: df_cat_encode.with_column(le.fit_transform(col)) I get the following error Traceback (most recent call last): File "<stdin>", line 2, in <module> File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/preprocessing/_label.py", line 115, in fit_transform y = column_or_1d(y, warn=True) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/utils/validation.py", line 1038, in column_or_1d raise ValueError( ValueError: y should be a 1d array, got an array of shape () instead. What am I doing wrong, and how can I fix this? A: It looks like this encoding is the equivalent of a "dense" ranking. >>> df_cat_encode source destination cab_type name short_summary icon price 0 0 0 0 3 1 1 5.0 1 0 0 0 0 2 2 11.0 2 0 0 0 2 0 0 7.0 3 0 0 0 1 0 0 26.0 Which you can do in polars using .rank(): >>> df.with_columns(pl.all().exclude("price").rank(method="dense") - 1) shape: (4, 7) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ source | destination | cab_type | name | short_summary | icon | price β”‚ β”‚ --- | --- | --- | --- | --- | --- | --- β”‚ β”‚ u32 | u32 | u32 | u32 | u32 | u32 | f64 β”‚ β•žβ•β•β•β•β•β•β•β•β•ͺ═════════════β•ͺ══════════β•ͺ══════β•ͺ═══════════════β•ͺ══════β•ͺ═══════║ β”‚ 0 | 0 | 0 | 3 | 1 | 1 | 5.0 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 0 | 0 | 0 | 0 | 2 | 2 | 11.0 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 0 | 0 | 0 | 2 | 0 | 0 | 7.0 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 0 | 0 | 0 | 1 | 0 | 0 | 26.0 β”‚ └─//─────┴─//──────────┴─//───────┴─//───┴─//────────────┴─//───┴─//β”€β”€β”€β”€β”˜
How do I pass in a 1d array to sklearn's LabelEncoder?
I'm following along an Uber-Lyft price prediction notebook on Kaggle, but I'm trying to use the Polars module. In cell 43 where they use sklearn's LabelEncoder, they have the following loop that appears to loop through each feature, except for price, and encodes it: from sklearn import preprocessing le = preprocessing.LabelEncoder() df_cat_encode= df_cat.copy() for col in df_cat_encode.select_dtypes(include='O').columns: df_cat_encode[col]=le.fit_transform(df_cat_encode[col]) The data being passed through looks like this: source destination cab_type name short_summary icon price Haymarket Square North Station Lyft Shared Mostly Cloudy partly-cloudy-night 5.0 Haymarket Square North Station Lyft Lux Rain rain 11.0 Haymarket Square North Station Lyft Lyft Clear clear-night 7.0 Haymarket Square North Station Lyft Lux Black XL Clear clear-night 26.0 and the label encoded result looks like this: 637975 rows x 7 columns source destination cab_type name short_summary icon price 5 7 0 7 4 5 5.0 5 7 0 2 8 6 11.0 5 7 0 5 0 1 7.0 5 7 0 4 6 1 26.0 ... ... ... ... ... ... ... The problem I'm having is when I try to build the same loop with Polars syntax like for col in df_cat_encode.select(["source","destination","cab_type","name","short_summary","icon"]).columns: df_cat_encode.with_column(le.fit_transform(col)) I get the following error Traceback (most recent call last): File "<stdin>", line 2, in <module> File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/preprocessing/_label.py", line 115, in fit_transform y = column_or_1d(y, warn=True) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/utils/validation.py", line 1038, in column_or_1d raise ValueError( ValueError: y should be a 1d array, got an array of shape () instead. What am I doing wrong, and how can I fix this?
[ "It looks like this encoding is the equivalent of a \"dense\" ranking.\n>>> df_cat_encode\n source destination cab_type name short_summary icon price\n0 0 0 0 3 1 1 5.0\n1 0 0 0 0 2 2 11.0\n2 0 0 0 2 0 0 7.0\n3 0 0 0 1 0 0 26.0\n\nWhich you can do in polars using .rank():\n>>> df.with_columns(pl.all().exclude(\"price\").rank(method=\"dense\") - 1)\nshape: (4, 7)\nβ”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”\nβ”‚ source | destination | cab_type | name | short_summary | icon | price β”‚\nβ”‚ --- | --- | --- | --- | --- | --- | --- β”‚\nβ”‚ u32 | u32 | u32 | u32 | u32 | u32 | f64 β”‚\nβ•žβ•β•β•β•β•β•β•β•β•ͺ═════════════β•ͺ══════════β•ͺ══════β•ͺ═══════════════β•ͺ══════β•ͺ═══════║\nβ”‚ 0 | 0 | 0 | 3 | 1 | 1 | 5.0 β”‚\nβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€\nβ”‚ 0 | 0 | 0 | 0 | 2 | 2 | 11.0 β”‚\nβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€\nβ”‚ 0 | 0 | 0 | 2 | 0 | 0 | 7.0 β”‚\nβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€\nβ”‚ 0 | 0 | 0 | 1 | 0 | 0 | 26.0 β”‚\n└─//─────┴─//──────────┴─//───────┴─//───┴─//────────────┴─//───┴─//β”€β”€β”€β”€β”˜\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "python", "python_polars", "scikit_learn" ]
stackoverflow_0074669199_arrays_python_python_polars_scikit_learn.txt
Q: Spring Profile Groups in Spring Cloud Config I'm trying to use the Profile Groups added in SpringBoot 2.4 to replace the old spring.profile.include that was changed in the same SB version. To give some context, we are using Spring Cloud Config Server and with a structure similar to shared |_ application.yml |_ application-dev-01.yml |_ application-dev-02.yml |_ application-dev.yml |_ application-prod.yml services |_ myService1 |_ myService1.yml |_ mySerrice1-dev.yml |_ mySerrice1-prod.yml We have many dev environments (dev-01, dev-02) and we specify the right one when we start the service. In each environment-specific profile we specify the database urls, creds, etc. Then we want to activate a global dev if running in any of the dev-XX environment for anything that is shared. This seems like a perfect use case for the profile groups, something like: spring: profiles.group: dev-01: dev dev-02: dev If I put this Profile Groups config in the bundled application.yml of my service, it works as expected. However, if I put it in side the application.yml in Spring Cloud Config, it does not seem to be picked up. Is it expected that we can only put those profile groups in the bundled files? A: There is an open issue about this problem in the Spring Cloud Config Github repository: Profile groups are not honored by client There is another similar open issue: Spring Cloud Config: Bootstrap context not loading profile-specific property files for binding In the later issue, a user is recommending as a workaround to define both spring.profiles.active and spring.cloud.config.profile, but I didn't succeed in reproducing this workaround in my context. There is also an issue about this problem in the Spring Boot Github repository: Using spring cloud config, Profile groups not working but the issue is closed because the problem comes from the Spring Cloud Config project.
Spring Profile Groups in Spring Cloud Config
I'm trying to use the Profile Groups added in SpringBoot 2.4 to replace the old spring.profile.include that was changed in the same SB version. To give some context, we are using Spring Cloud Config Server and with a structure similar to shared |_ application.yml |_ application-dev-01.yml |_ application-dev-02.yml |_ application-dev.yml |_ application-prod.yml services |_ myService1 |_ myService1.yml |_ mySerrice1-dev.yml |_ mySerrice1-prod.yml We have many dev environments (dev-01, dev-02) and we specify the right one when we start the service. In each environment-specific profile we specify the database urls, creds, etc. Then we want to activate a global dev if running in any of the dev-XX environment for anything that is shared. This seems like a perfect use case for the profile groups, something like: spring: profiles.group: dev-01: dev dev-02: dev If I put this Profile Groups config in the bundled application.yml of my service, it works as expected. However, if I put it in side the application.yml in Spring Cloud Config, it does not seem to be picked up. Is it expected that we can only put those profile groups in the bundled files?
[ "There is an open issue about this problem in the Spring Cloud Config Github repository:\nProfile groups are not honored by client\nThere is another similar open issue:\nSpring Cloud Config: Bootstrap context not loading profile-specific property files for binding\nIn the later issue, a user is recommending as a workaround to define both spring.profiles.active and spring.cloud.config.profile, but I didn't succeed in reproducing this workaround in my context.\nThere is also an issue about this problem in the Spring Boot Github repository:\nUsing spring cloud config, Profile groups not working\nbut the issue is closed because the problem comes from the Spring Cloud Config project.\n" ]
[ 0 ]
[]
[]
[ "java", "spring", "spring_boot" ]
stackoverflow_0073854539_java_spring_spring_boot.txt
Q: error flutter _CastError (Null check operator used on a null value) using sqlite database i have trouble with my flutter database , i'm using sqlite for database and when i want to run it i have error said that _CastError (Null check operator used on a null value). i already use (!)in my code but still the same ,can anybody help me my code in dbhelbper Future<List<DistribusiModel>> getAll() async { final data = await _database!.query(namaTabel); List<DistribusiModel> result = data.map((e) => DistribusiModel.fromJson(e)).toList(); return result; } my code from main.dart FutureBuilder<List<DistribusiModel>>( future: databasedistribusi!.getAll(), builder: (context, snapshot) { print('Hasil: ' + snapshot.data!.toString()); return ListTile( title: Text('Algoritma dan Pemrograman I'), trailing: Wrap( children: [ Text( '3', style: TextStyle(color: Colors.black), ), SizedBox( width: 20, ), Text( 'A', style: TextStyle(color: Colors.black), ), SizedBox( width: 20, ), Text('LULUS'), ], ) please help me , i need to finish it immediately sorry for my bad english i hope anyone can help me whit this problem A: Firstly make sure the databasedistribusi is not null. Beware of using ! directly without checking null. and return empty list on null case Future<List<DistribusiModel>> getAll() async { if(_database==null) return []; final data = await _database.query(namaTabel); List<DistribusiModel> result = data.map((e) => DistribusiModel.fromJson(e)).toList(); return result; } And for the FutureBuilder FutureBuilder<List<DistribusiModel>>( future: databasedistribusi?.getAll(), builder: (context, snapshot) { if(snapshot.hasError) return Text("got Error"); else if(snapshot.hasData){ if(snapshot.data.isEmpty) return Text("EmptyData"); else return ListView(....); } return CircularProgressIndicator(); //default } More about using FutureBuilder and understanding-null-safety
error flutter _CastError (Null check operator used on a null value) using sqlite database
i have trouble with my flutter database , i'm using sqlite for database and when i want to run it i have error said that _CastError (Null check operator used on a null value). i already use (!)in my code but still the same ,can anybody help me my code in dbhelbper Future<List<DistribusiModel>> getAll() async { final data = await _database!.query(namaTabel); List<DistribusiModel> result = data.map((e) => DistribusiModel.fromJson(e)).toList(); return result; } my code from main.dart FutureBuilder<List<DistribusiModel>>( future: databasedistribusi!.getAll(), builder: (context, snapshot) { print('Hasil: ' + snapshot.data!.toString()); return ListTile( title: Text('Algoritma dan Pemrograman I'), trailing: Wrap( children: [ Text( '3', style: TextStyle(color: Colors.black), ), SizedBox( width: 20, ), Text( 'A', style: TextStyle(color: Colors.black), ), SizedBox( width: 20, ), Text('LULUS'), ], ) please help me , i need to finish it immediately sorry for my bad english i hope anyone can help me whit this problem
[ "Firstly make sure the databasedistribusi is not null. Beware of using ! directly without checking null.\nand return empty list on null case\nFuture<List<DistribusiModel>> getAll() async {\n if(_database==null) return [];\n final data = await _database.query(namaTabel);\n List<DistribusiModel> result =\n data.map((e) => DistribusiModel.fromJson(e)).toList();\n return result;\n }\n\nAnd for the FutureBuilder\n FutureBuilder<List<DistribusiModel>>(\n future: databasedistribusi?.getAll(),\n builder: (context, snapshot) {\n if(snapshot.hasError) return Text(\"got Error\");\n\n else if(snapshot.hasData){\n if(snapshot.data.isEmpty) return Text(\"EmptyData\");\n else return ListView(....);\n }\n\n return CircularProgressIndicator(); //default\n }\n\n\nMore about using FutureBuilder and understanding-null-safety\n" ]
[ 0 ]
[]
[]
[ "dart", "dart_null_safety", "flutter", "sqlite" ]
stackoverflow_0074670169_dart_dart_null_safety_flutter_sqlite.txt
Q: VBA for listing all files in folder or zip archive including subfolders I'm sharing my code for listing all subdirectories and files contained in a selected folder or ZIP archive. I have been looking for such solution for a few days and only found flawed recursive scripts that stopped at listing the contents of the first subfolder, or missing the files in root folder, or only working for 2 levels of subfolders. This scripts uses listing found items in the worksheet, marking them as directories or files so it can the loop through them and re-initiate the look through function for all newly found subfolder levels as it goes. It uses shell application instead of DIR so it can be used also for searching contents of zip archives (Dir function sees ZIP as file, not directory) I've tried to make it as lean as possible, but I'm more than happy if you can streamline it even further Sub loop_through_files_in_subfolders() Dim wb As Workbook Dim ws As Worksheet Dim start_folder As Variant Dim LastRow As Long Dim CurrRow As Long Set wb = ThisWorkbook Set ws = wb.Worksheets(1) 'set folder of choice or zip archive start_folder = "C:\Makro_test\F1.zip" 'sets the selected path in colum A as initial directory and sets "D"irectory flag in column B ws.Range("A2").Value2 = start_folder ws.Range("B2").Value2 = "D" 'set current row as first under headers CurrRow = 2 'set last row as first empty row LastRow = 3 'continue until current row equals the first empty row (list has ended) Do Until CurrRow = LastRow 'only do for rows containing a "D"irectory path If ws.Range("B" & CurrRow).Value2 = "D" Then start_folder = ws.Range("A" & CurrRow).Value2 'set the folder to look through loop_through_items_in_folder start_folder, wb, ws 'execute the look through function ws.Range("A" & CurrRow).Interior.ColorIndex = 37 'colour mark the cell containing searched folder End If CurrRow = CurrRow + 1 'set current row to next one 'update last row to include contents of the last searched folder LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1 Loop End Sub Function loop_through_items_in_folder(ITM_path As Variant, wb, ws) Dim shell Dim ITM, Sub_ITM Dim LR As Long Set shell = CreateObject("Shell.Application") 'use the provided path to set the folder Set ITM = shell.Namespace(ITM_path) 'loop through all items in folder For Each Sub_ITM In ITM.items 'look for first empty row LR = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1 'store file path in column A ws.Range("A" & LR).Value = Sub_ITM.path 'store flag for "D"irectory or "F"ile in column B If Sub_ITM.isfolder Then ws.Range("B" & LR).Value = "D" Else ws.Range("B" & LR).Value = "F" End If Next Sub_ITM End Function A: You could do it like this (using an Excel file with a zip extension added for testing): Sub Tester() ListZipContents "C:\Temp\tempo.xlsb.zip" End Sub Sub ListZipContents(zipFilePath As Variant) Dim oApp As Object, colFolders As New Collection, itm As Object, fld As Object Set oApp = CreateObject("Shell.Application") colFolders.Add oApp.Namespace(zipFilePath).self Do While colFolders.Count > 0 Set fld = colFolders(1) 'get the first folder colFolders.Remove 1 '...and remove it from the collection For Each itm In oApp.Namespace(fld.Path).Items If itm.isfolder Then colFolders.Add itm 'save folder path for listing Else Debug.Print itm.Path 'list file path End If Next Loop End Sub Ouput: C:\Temp\tempo.xlsb.zip\[Content_Types].xml C:\Temp\tempo.xlsb.zip\_rels\.rels C:\Temp\tempo.xlsb.zip\xl\workbook.bin C:\Temp\tempo.xlsb.zip\xl\styles.bin C:\Temp\tempo.xlsb.zip\xl\sharedStrings.bin C:\Temp\tempo.xlsb.zip\xl\vbaProject.bin C:\Temp\tempo.xlsb.zip\docProps\core.xml C:\Temp\tempo.xlsb.zip\docProps\app.xml C:\Temp\tempo.xlsb.zip\xl\_rels\workbook.bin.rels C:\Temp\tempo.xlsb.zip\xl\worksheets\sheet1.bin C:\Temp\tempo.xlsb.zip\xl\worksheets\binaryIndex1.bin C:\Temp\tempo.xlsb.zip\xl\theme\theme1.xml C:\Temp\tempo.xlsb.zip\xl\printerSettings\printerSettings1.bin C:\Temp\tempo.xlsb.zip\xl\worksheets\_rels\sheet1.bin.rels
VBA for listing all files in folder or zip archive including subfolders
I'm sharing my code for listing all subdirectories and files contained in a selected folder or ZIP archive. I have been looking for such solution for a few days and only found flawed recursive scripts that stopped at listing the contents of the first subfolder, or missing the files in root folder, or only working for 2 levels of subfolders. This scripts uses listing found items in the worksheet, marking them as directories or files so it can the loop through them and re-initiate the look through function for all newly found subfolder levels as it goes. It uses shell application instead of DIR so it can be used also for searching contents of zip archives (Dir function sees ZIP as file, not directory) I've tried to make it as lean as possible, but I'm more than happy if you can streamline it even further Sub loop_through_files_in_subfolders() Dim wb As Workbook Dim ws As Worksheet Dim start_folder As Variant Dim LastRow As Long Dim CurrRow As Long Set wb = ThisWorkbook Set ws = wb.Worksheets(1) 'set folder of choice or zip archive start_folder = "C:\Makro_test\F1.zip" 'sets the selected path in colum A as initial directory and sets "D"irectory flag in column B ws.Range("A2").Value2 = start_folder ws.Range("B2").Value2 = "D" 'set current row as first under headers CurrRow = 2 'set last row as first empty row LastRow = 3 'continue until current row equals the first empty row (list has ended) Do Until CurrRow = LastRow 'only do for rows containing a "D"irectory path If ws.Range("B" & CurrRow).Value2 = "D" Then start_folder = ws.Range("A" & CurrRow).Value2 'set the folder to look through loop_through_items_in_folder start_folder, wb, ws 'execute the look through function ws.Range("A" & CurrRow).Interior.ColorIndex = 37 'colour mark the cell containing searched folder End If CurrRow = CurrRow + 1 'set current row to next one 'update last row to include contents of the last searched folder LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1 Loop End Sub Function loop_through_items_in_folder(ITM_path As Variant, wb, ws) Dim shell Dim ITM, Sub_ITM Dim LR As Long Set shell = CreateObject("Shell.Application") 'use the provided path to set the folder Set ITM = shell.Namespace(ITM_path) 'loop through all items in folder For Each Sub_ITM In ITM.items 'look for first empty row LR = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1 'store file path in column A ws.Range("A" & LR).Value = Sub_ITM.path 'store flag for "D"irectory or "F"ile in column B If Sub_ITM.isfolder Then ws.Range("B" & LR).Value = "D" Else ws.Range("B" & LR).Value = "F" End If Next Sub_ITM End Function
[ "You could do it like this (using an Excel file with a zip extension added for testing):\nSub Tester()\n ListZipContents \"C:\\Temp\\tempo.xlsb.zip\"\nEnd Sub\n\nSub ListZipContents(zipFilePath As Variant)\n\n Dim oApp As Object, colFolders As New Collection, itm As Object, fld As Object\n\n Set oApp = CreateObject(\"Shell.Application\")\n colFolders.Add oApp.Namespace(zipFilePath).self\n \n Do While colFolders.Count > 0\n Set fld = colFolders(1) 'get the first folder\n colFolders.Remove 1 '...and remove it from the collection\n For Each itm In oApp.Namespace(fld.Path).Items\n If itm.isfolder Then\n colFolders.Add itm 'save folder path for listing\n Else\n Debug.Print itm.Path 'list file path\n End If\n Next\n Loop\nEnd Sub\n\nOuput:\nC:\\Temp\\tempo.xlsb.zip\\[Content_Types].xml\nC:\\Temp\\tempo.xlsb.zip\\_rels\\.rels\nC:\\Temp\\tempo.xlsb.zip\\xl\\workbook.bin\nC:\\Temp\\tempo.xlsb.zip\\xl\\styles.bin\nC:\\Temp\\tempo.xlsb.zip\\xl\\sharedStrings.bin\nC:\\Temp\\tempo.xlsb.zip\\xl\\vbaProject.bin\nC:\\Temp\\tempo.xlsb.zip\\docProps\\core.xml\nC:\\Temp\\tempo.xlsb.zip\\docProps\\app.xml\nC:\\Temp\\tempo.xlsb.zip\\xl\\_rels\\workbook.bin.rels\nC:\\Temp\\tempo.xlsb.zip\\xl\\worksheets\\sheet1.bin\nC:\\Temp\\tempo.xlsb.zip\\xl\\worksheets\\binaryIndex1.bin\nC:\\Temp\\tempo.xlsb.zip\\xl\\theme\\theme1.xml\nC:\\Temp\\tempo.xlsb.zip\\xl\\printerSettings\\printerSettings1.bin\nC:\\Temp\\tempo.xlsb.zip\\xl\\worksheets\\_rels\\sheet1.bin.rels\n\n" ]
[ 0 ]
[]
[]
[ "excel", "vba", "zip" ]
stackoverflow_0074668611_excel_vba_zip.txt
Q: getting timers to print values from bubblesort, wont print my last value unless I lower it? import sys import time from random import randint import numpy as np sys.setrecursionlimit(6000) nums = [10, 50, 100, 500, 1000, 5000] def bubble(A, n): for i in range(n - 1): if A[i] > A[i + 1]: A[i], A[i + 1] = A[i + 1], A[i] if n - 1 > 1: bubble(A, n - 1) def time_by_bubble_sort(nums): time_taken_by_bubble_sort = [] for num in nums: A = list(np.random.randint(low=1, high=num, size=num)) st_time = time.time() bubble(A, len(A)) end_time = time.time() time_taken = end_time - st_time time_taken_by_bubble_sort.append(time_taken) return time_taken_by_bubble_sort print(time_by_bubble_sort(nums)) I want to compare time with my values from nums: [10, 50, 100, 500, 1000, 5000] Why dosen't generate a time for the last value (5000), but when I switch it out to 2000 or remove it, it will print? this is the error code: exit code -1073741571 (0xC00000FD) After googling, it might be that my recursive function goes to infinite, but I don't see it. sorry for bad english. A: According to sys.setrecursionlimit, emphasis mine: The highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash. Your limit of 6000 is too high. My system crashes after about 2130 recursive calls to bubble, which explains why using 2000 instead of 5000 works. The crash is due to the Python process's stack running out of space which is platform-dependent.
getting timers to print values from bubblesort, wont print my last value unless I lower it?
import sys import time from random import randint import numpy as np sys.setrecursionlimit(6000) nums = [10, 50, 100, 500, 1000, 5000] def bubble(A, n): for i in range(n - 1): if A[i] > A[i + 1]: A[i], A[i + 1] = A[i + 1], A[i] if n - 1 > 1: bubble(A, n - 1) def time_by_bubble_sort(nums): time_taken_by_bubble_sort = [] for num in nums: A = list(np.random.randint(low=1, high=num, size=num)) st_time = time.time() bubble(A, len(A)) end_time = time.time() time_taken = end_time - st_time time_taken_by_bubble_sort.append(time_taken) return time_taken_by_bubble_sort print(time_by_bubble_sort(nums)) I want to compare time with my values from nums: [10, 50, 100, 500, 1000, 5000] Why dosen't generate a time for the last value (5000), but when I switch it out to 2000 or remove it, it will print? this is the error code: exit code -1073741571 (0xC00000FD) After googling, it might be that my recursive function goes to infinite, but I don't see it. sorry for bad english.
[ "According to sys.setrecursionlimit, emphasis mine:\n\nThe highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.\n\nYour limit of 6000 is too high. My system crashes after about 2130 recursive calls to bubble, which explains why using 2000 instead of 5000 works. The crash is due to the Python process's stack running out of space which is platform-dependent.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074635282_python.txt
Q: General way of filtering by IDs with DRF Is there a generic way that I can filter by an array of IDs when using DRF? For example, if I wanted to return all images with the following IDs, I would do this: /images/?ids=1,2,3,4 My current implementation is to do the following: # filter class ProjectImageFilter(django_filters.FilterSet): """ Filter on existing fields, or defined query_params with associated functions """ ids = django_filters.MethodFilter(action='id_list') def id_list(self, queryset, value): """ Filter by IDs by passing in a query param of this structure `?ids=265,263` """ id_list = value.split(',') return queryset.filter(id__in=id_list) class Meta: model = ProjectImage fields = ['ids',] # viewset class Images(viewsets.ModelViewSet): """ Images associated with a project """ serializer_class = ImageSerializer queryset = ProjectImage.objects.all() filter_class = ProjectImageFilter However, in this case ProjectImageFilter requires a model to be specified ( ProjectImage). Is there a way that I can just generally define this filter so I can use it on multiple ViewSets with different models? A: One solution without django-filters is to just super() override get_queryset. Here is an example: class MyViewSet(view.ViewSet): # your code def get_queryset(self): queryset = super(MyViewSet, self).get_queryset() ids = self.request.query_params.get('ids', None) if ids: ids_list = ids.split(',') queryset = queryset.filter(id__in=ids_list) return queryset A: The library django-filter has support for this using BaseInFilter, in conjunction with DRF. From their docs: class NumberRangeFilter(BaseRangeFilter, NumberFilter): pass class F(FilterSet): id__range = NumberRangeFilter(field_name='id', lookup_expr='range') class Meta: model = User User.objects.create(username='alex') User.objects.create(username='jacob') User.objects.create(username='aaron') User.objects.create(username='carl') # Range: User with IDs between 1 and 3. f = F({'id__range': '1,3'}) assert len(f.qs) == 3
General way of filtering by IDs with DRF
Is there a generic way that I can filter by an array of IDs when using DRF? For example, if I wanted to return all images with the following IDs, I would do this: /images/?ids=1,2,3,4 My current implementation is to do the following: # filter class ProjectImageFilter(django_filters.FilterSet): """ Filter on existing fields, or defined query_params with associated functions """ ids = django_filters.MethodFilter(action='id_list') def id_list(self, queryset, value): """ Filter by IDs by passing in a query param of this structure `?ids=265,263` """ id_list = value.split(',') return queryset.filter(id__in=id_list) class Meta: model = ProjectImage fields = ['ids',] # viewset class Images(viewsets.ModelViewSet): """ Images associated with a project """ serializer_class = ImageSerializer queryset = ProjectImage.objects.all() filter_class = ProjectImageFilter However, in this case ProjectImageFilter requires a model to be specified ( ProjectImage). Is there a way that I can just generally define this filter so I can use it on multiple ViewSets with different models?
[ "One solution without django-filters is to just super() override get_queryset. Here is an example:\nclass MyViewSet(view.ViewSet):\n\n # your code\n\n def get_queryset(self):\n queryset = super(MyViewSet, self).get_queryset()\n\n ids = self.request.query_params.get('ids', None)\n if ids:\n ids_list = ids.split(',')\n queryset = queryset.filter(id__in=ids_list)\n\n return queryset\n\n", "The library django-filter has support for this using BaseInFilter, in conjunction with DRF.\nFrom their docs:\nclass NumberRangeFilter(BaseRangeFilter, NumberFilter):\n pass\n\nclass F(FilterSet):\n id__range = NumberRangeFilter(field_name='id', lookup_expr='range')\n\n class Meta:\n model = User\n\nUser.objects.create(username='alex')\nUser.objects.create(username='jacob')\nUser.objects.create(username='aaron')\nUser.objects.create(username='carl')\n\n# Range: User with IDs between 1 and 3.\nf = F({'id__range': '1,3'})\nassert len(f.qs) == 3\n\n" ]
[ 1, 0 ]
[]
[]
[ "django", "django_rest_framework", "python", "python_2.7" ]
stackoverflow_0036851257_django_django_rest_framework_python_python_2.7.txt
Q: Nightwatch.js - Use the same browser session We would love to adopt Nightwatch.js for testing on browsers, but we're stuck on one major caveat: at the time of this writing, Nightwatchjs does not support running different tests using the same browser session. In short, it means that: Creating the browser session is handled by the Nightwatch module from lib/index.js, in the startSession function; Killing the browser would correspond to the delete command place in the Selenium action queue in the terminate function of that module; A new Nightwatch client is created at every test run, which happens every time we load a different test file; According to this source, it is possible to reuse the current browser session in Selenium, instead of opening a new window. Has anyone managed to fix this problem in Nightwatch? Here's the feature request on Github, which was requested on Mar 31, 2014 and is still open. Another approach would be to circumvent the problem altogether by getting Nightwatch to merge all different files into one Test Suite, but that seems to be harder to solve than the problem with sessions... A: As far as I know, Nightwatch.js still does not support running different tests using the same browser session. However, it is possible to work around this issue by using the before and after hooks in your test suite to start and terminate the browser session manually, rather than relying on Nightwatch to do it for you. Here is an example: // In your test suite before: function(done) { // Start the browser session manually // You can use the `nightwatch` object to access Nightwatch's commands and assertions nightwatch.startSession(function() { done(); }); }, after: function(done) { // Terminate the browser session manually nightwatch.endSession(function() { done(); }); }, // Your tests go here By using the before and after hooks, you can ensure that the browser session is started and terminated only once for the entire test suite, rather than once for each test file. This should allow you to run different tests using the same browser session.
Nightwatch.js - Use the same browser session
We would love to adopt Nightwatch.js for testing on browsers, but we're stuck on one major caveat: at the time of this writing, Nightwatchjs does not support running different tests using the same browser session. In short, it means that: Creating the browser session is handled by the Nightwatch module from lib/index.js, in the startSession function; Killing the browser would correspond to the delete command place in the Selenium action queue in the terminate function of that module; A new Nightwatch client is created at every test run, which happens every time we load a different test file; According to this source, it is possible to reuse the current browser session in Selenium, instead of opening a new window. Has anyone managed to fix this problem in Nightwatch? Here's the feature request on Github, which was requested on Mar 31, 2014 and is still open. Another approach would be to circumvent the problem altogether by getting Nightwatch to merge all different files into one Test Suite, but that seems to be harder to solve than the problem with sessions...
[ "As far as I know, Nightwatch.js still does not support running different tests using the same browser session. However, it is possible to work around this issue by using the before and after hooks in your test suite to start and terminate the browser session manually, rather than relying on Nightwatch to do it for you. Here is an example:\n// In your test suite\nbefore: function(done) {\n // Start the browser session manually\n // You can use the `nightwatch` object to access Nightwatch's commands and assertions\n nightwatch.startSession(function() {\n done();\n });\n},\nafter: function(done) {\n // Terminate the browser session manually\n nightwatch.endSession(function() {\n done();\n });\n},\n\n// Your tests go here\n\nBy using the before and after hooks, you can ensure that the browser session is started and terminated only once for the entire test suite, rather than once for each test file. This should allow you to run different tests using the same browser session.\n" ]
[ 0 ]
[]
[]
[ "nightwatch.js", "selenium" ]
stackoverflow_0031745927_nightwatch.js_selenium.txt
Q: Add opacity and transition to background image and div As demonstrated by the snippet. I created this story part just for mobile devices and will integrate it into the current website. The issue I'm having is that although it functions OK on its own, when I added it to an existing website (between areas of the page), it didn't function as expected. Therefore, I want it to function as a separate area on the website. As you can see in the attached photos. I want to add this story section to existing website and apply opacity to both the background image and the div when the div goes up. The background image changes and flickers as well. I want to fix it. It's a window.onscroll based code and there is lots of other elements in the website so its breaking my code and background image is not showing in within a webiste. As, I'm new to DOM manipulation and animations. So, i need help to fix it. function scrollPictureChange() { var main = document.querySelector(".main"), sections = main.querySelectorAll(".section"), BG = main.querySelector(".BG"), el = document.querySelector(".show"), cords, index = 0, h = window.innerHeight, lastIndex = null, offset = 0; applyBG(0); window.addEventListener("scroll", function () { scrollY = Math.abs(document.body.getClientRects()[0].top); index = Math.floor(scrollY / (h - offset)); if (index != lastIndex) { // on index change if (lastIndex != null) { applyBG(index); } lastIndex = index; } el.innerText = `index : ${index} height : ${h} top : ${scrollY}`; }); function applyBG(index) { BG.classList.remove("anim"); setTimeout(function () { BG.style.backgroundImage = `url(${sections[index + 1].getAttribute( "BGurl" )})`; BG.classList.add("anim"); }, 300); } } window.onload = scrollPictureChange; window.onresize = scrollPictureChange; body { margin: 0; padding: 0; box-sizing: border-box; overflow-x: hidden; } .section { height: 100vh; width: 100%; display: flex; z-index: 1; position: relative; background-size: 100% 100% !important; } .text { margin: auto; } .text p { font-family: 'Lato'; font-style: normal; font-weight: 500; font-size: 18px; line-height: 149%; color: #263244; } .text h1 { margin-bottom: 20px; font-family: 'Lato'; font-style: normal; font-weight: 700; font-size: 50px; line-height: 0px; color: #FFFFFF; margin-bottom: 50px; } .text .story-detail { width: 300px; border-radius: 20px; background: radial-gradient(76.31% 191.89% at 13.43% 22.19%, rgba(226, 228, 231, 0.8) 0%, rgba(228, 228, 229, 0.368) 100%); backdrop-filter: blur(10px); padding: 23px; } .text .story-description { width: 321px; border-radius: 20px; background: radial-gradient(76.31% 191.89% at 13.43% 22.19%, rgba(226, 228, 231, 0.8) 0%, rgba(228, 228, 229, 0.368) 100%); backdrop-filter: blur(10px); padding: 23px; } .BG { position: fixed; z-index: 0; opacity: 1; transition: opacity 10s ease-in-out; height: 100%; } .anim { opacity: 1; } .show { color: orange; } <div class="main"> <div class="section BG"> <div class="show"></div> </div> <div class="section" BGurl="https://i.postimg.cc/9QYL3ytR/mobile-camp.png" > <div class="text"> <div style="margin-inline: 20px"> <h1>Our Story</h1> <div class="story-detail"> <p> We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons. </p> </div> </div> </div> </div> <div class="section" BGurl="https://i.postimg.cc/9QYL3ytR/mobile-camp.png" > <div class="text"> <div style="margin-inline: 20px"> <div class="story-description"> <p> Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on. </p> </div> </div> </div> </div> <div class="section" BGurl="https://i.postimg.cc/cLPLS8xW/mobile-desert.png" > <div class="text"> <div style="margin-inline: 20px"> <div class="story-description"> <p> So since we're passionate about solving problems and bridging gaps, we looked into and identified the challenges and capabilities we'll need to build a bank here in the Kingdom. </p> </div> </div> </div> </div> <div class="section" BGurl="https://i.postimg.cc/mZnqV38T/mobile-birds.png" > <div class="text"> <div style="margin-inline: 20px"> <div class="story-description"> <p> With the best local and international expertise, we began building an innovative digital bank designed by and for the people. We believe that the most effective way to build a bank for people is to do it with them. This is our philosophy. So, we started building it with the help of people like you. </p> </div> </div> </div> </div> <div class="section" BGurl="https://i.postimg.cc/k513m0Fb/mountain.png"> <div class="text"> <div style="margin-inline: 20px"> <div class="story-description"> <p> At D360, innovation starts with someone’s passion for improving financial services. To that person, we say: Never stop offering solutions to your needs. These solutions will not only benefit you, but will significantly impact the lives of millions. </p> </div> </div> </div> </div> </div> A: It is painful to do what you want with the method you follow. Because of that, I suggest the getBoundingClientRect() method. The method is a Web API which returns information about the size of an element and its position in your page. The left, top, right, bottom, x, y, width, and height properties describe the position and size of the overall rectangle in pixels. Properties other than width and height are relative to the top-left of the viewport. Source: Further information and examples Sample (for your question) Create 10 Divs (optional) <div class="div"> <p>Sample sentence is here!</p> </div> Define style to the Divs with CSS .div { /* This must be exist. */ opacity: 0; /* OPTIONAL STYLE */ width: 300px; border:1px solid black; border-radius: 20px; margin:auto; padding: 10px; background-color: white; transition: opacity 1s; margin-bottom: 20px; } Set your background images' path in an array in JS const bgImgs = ['https://picsum.photos/id/237/1920/1080','https://picsum.photos/id/102/1920/1080','https://picsum.photos/id/202/1920/1080','https://picsum.photos/id/99/1920/1080','https://picsum.photos/id/63/1920/1080','https://picsum.photos/id/6/1920/1080','https://picsum.photos/id/10/1920/1080','https://picsum.photos/id/19/1920/1080','https://picsum.photos/id/80/1920/1080','https://picsum.photos/id/111/1920/1080']; Fetch all of your Divs in JS const divs = document.querySelectorAll('.div'); Get each Div's info, and make 3 rule with IF-Statement in JS for (var i = 0; i < divs.length; i++) { const div = divs[i]; const rect = div.getBoundingClientRect(); if (rect.top >= 0 && rect.bottom <= window.innerHeight) { div.style.opacity = 1; document.body.style.backgroundImage = `url('${bgImgs[i]}')`; } else if (rect.top < 0 && rect.bottom > 0) { div.style.opacity = rect.bottom / window.innerHeight; } else if (rect.top > 0 && rect.top < window.innerHeight) { div.style.opacity = 1 - (rect.top / window.innerHeight); } } In the situation, the first condition makes the relevant element's opacity 1 (this means showing us the element), and then change background image. The second condition means the next element, and finally the third condition reduces the previous element's opacity slowly. Test the sample const bgImgs = ['https://picsum.photos/id/237/1920/1080','https://picsum.photos/id/102/1920/1080','https://picsum.photos/id/202/1920/1080','https://picsum.photos/id/99/1920/1080','https://picsum.photos/id/63/1920/1080','https://picsum.photos/id/6/1920/1080','https://picsum.photos/id/10/1920/1080','https://picsum.photos/id/19/1920/1080','https://picsum.photos/id/80/1920/1080','https://picsum.photos/id/111/1920/1080']; function handleScroll(){ const divs = document.querySelectorAll('.div'); for (var i = 0; i < divs.length; i++) { const div = divs[i]; const rect = div.getBoundingClientRect(); if (rect.top >= 0 && rect.bottom <= window.innerHeight) { div.style.opacity = 1; document.body.style.backgroundImage = `url('${bgImgs[i]}')`; } else if (rect.top < 0 && rect.bottom > 0) { div.style.opacity = rect.bottom / window.innerHeight; } else if (rect.top > 0 && rect.top < window.innerHeight) { div.style.opacity = 1 - (rect.top / window.innerHeight); } } }; window.addEventListener('scroll', handleScroll); handleScroll(); html, body { /* OPTIONAL STYLE */ margin: 20px 0 20px 0; padding: 0; transition: background-image 1s; /* The fixed background image */ background-repeat: no-repeat; background-attachment: fixed; } .div { /* This must be exist. */ opacity: 0; /* OPTIONAL STYLE */ width: 300px; border:1px solid black; border-radius: 20px; margin:auto; padding: 10px; background-color: white; transition: opacity 1s; margin-bottom: 20px; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Opacity Divs</title> </head> <body> <div class="div"> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> </div> <div class="div"> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> </div> <div class="div"> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> </div> <div class="div"> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> </div> <div class="div"> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> </div> <div class="div"> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> </div> <div class="div"> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> </div> <div class="div"> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> </div> <div class="div"> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> </div> <div class="div"> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p> <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p> </div> </body> </html> Note: The background images can load a little bit slow because of the size. It is recommended to store up your background images in the local.
Add opacity and transition to background image and div
As demonstrated by the snippet. I created this story part just for mobile devices and will integrate it into the current website. The issue I'm having is that although it functions OK on its own, when I added it to an existing website (between areas of the page), it didn't function as expected. Therefore, I want it to function as a separate area on the website. As you can see in the attached photos. I want to add this story section to existing website and apply opacity to both the background image and the div when the div goes up. The background image changes and flickers as well. I want to fix it. It's a window.onscroll based code and there is lots of other elements in the website so its breaking my code and background image is not showing in within a webiste. As, I'm new to DOM manipulation and animations. So, i need help to fix it. function scrollPictureChange() { var main = document.querySelector(".main"), sections = main.querySelectorAll(".section"), BG = main.querySelector(".BG"), el = document.querySelector(".show"), cords, index = 0, h = window.innerHeight, lastIndex = null, offset = 0; applyBG(0); window.addEventListener("scroll", function () { scrollY = Math.abs(document.body.getClientRects()[0].top); index = Math.floor(scrollY / (h - offset)); if (index != lastIndex) { // on index change if (lastIndex != null) { applyBG(index); } lastIndex = index; } el.innerText = `index : ${index} height : ${h} top : ${scrollY}`; }); function applyBG(index) { BG.classList.remove("anim"); setTimeout(function () { BG.style.backgroundImage = `url(${sections[index + 1].getAttribute( "BGurl" )})`; BG.classList.add("anim"); }, 300); } } window.onload = scrollPictureChange; window.onresize = scrollPictureChange; body { margin: 0; padding: 0; box-sizing: border-box; overflow-x: hidden; } .section { height: 100vh; width: 100%; display: flex; z-index: 1; position: relative; background-size: 100% 100% !important; } .text { margin: auto; } .text p { font-family: 'Lato'; font-style: normal; font-weight: 500; font-size: 18px; line-height: 149%; color: #263244; } .text h1 { margin-bottom: 20px; font-family: 'Lato'; font-style: normal; font-weight: 700; font-size: 50px; line-height: 0px; color: #FFFFFF; margin-bottom: 50px; } .text .story-detail { width: 300px; border-radius: 20px; background: radial-gradient(76.31% 191.89% at 13.43% 22.19%, rgba(226, 228, 231, 0.8) 0%, rgba(228, 228, 229, 0.368) 100%); backdrop-filter: blur(10px); padding: 23px; } .text .story-description { width: 321px; border-radius: 20px; background: radial-gradient(76.31% 191.89% at 13.43% 22.19%, rgba(226, 228, 231, 0.8) 0%, rgba(228, 228, 229, 0.368) 100%); backdrop-filter: blur(10px); padding: 23px; } .BG { position: fixed; z-index: 0; opacity: 1; transition: opacity 10s ease-in-out; height: 100%; } .anim { opacity: 1; } .show { color: orange; } <div class="main"> <div class="section BG"> <div class="show"></div> </div> <div class="section" BGurl="https://i.postimg.cc/9QYL3ytR/mobile-camp.png" > <div class="text"> <div style="margin-inline: 20px"> <h1>Our Story</h1> <div class="story-detail"> <p> We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons. </p> </div> </div> </div> </div> <div class="section" BGurl="https://i.postimg.cc/9QYL3ytR/mobile-camp.png" > <div class="text"> <div style="margin-inline: 20px"> <div class="story-description"> <p> Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on. </p> </div> </div> </div> </div> <div class="section" BGurl="https://i.postimg.cc/cLPLS8xW/mobile-desert.png" > <div class="text"> <div style="margin-inline: 20px"> <div class="story-description"> <p> So since we're passionate about solving problems and bridging gaps, we looked into and identified the challenges and capabilities we'll need to build a bank here in the Kingdom. </p> </div> </div> </div> </div> <div class="section" BGurl="https://i.postimg.cc/mZnqV38T/mobile-birds.png" > <div class="text"> <div style="margin-inline: 20px"> <div class="story-description"> <p> With the best local and international expertise, we began building an innovative digital bank designed by and for the people. We believe that the most effective way to build a bank for people is to do it with them. This is our philosophy. So, we started building it with the help of people like you. </p> </div> </div> </div> </div> <div class="section" BGurl="https://i.postimg.cc/k513m0Fb/mountain.png"> <div class="text"> <div style="margin-inline: 20px"> <div class="story-description"> <p> At D360, innovation starts with someone’s passion for improving financial services. To that person, we say: Never stop offering solutions to your needs. These solutions will not only benefit you, but will significantly impact the lives of millions. </p> </div> </div> </div> </div> </div>
[ "It is painful to do what you want with the method you follow. Because of that, I suggest the getBoundingClientRect() method. The method is a Web API which returns information about the size of an element and its position in your page.\n\nThe left, top, right, bottom, x, y, width, and height properties describe the position and size of the overall rectangle in pixels. Properties other than width and height are relative to the top-left of the viewport.\n\nSource: Further information and examples\n\nSample (for your question)\n\nCreate 10 Divs (optional)\n\n<div class=\"div\">\n <p>Sample sentence is here!</p>\n</div>\n\n\nDefine style to the Divs with CSS\n\n.div {\n /* This must be exist. */\n opacity: 0;\n\n /* OPTIONAL STYLE */\n width: 300px;\n border:1px solid black;\n border-radius: 20px;\n margin:auto;\n padding: 10px;\n background-color: white;\n transition: opacity 1s;\n margin-bottom: 20px;\n}\n\n\nSet your background images' path in an array in JS\n\nconst bgImgs = ['https://picsum.photos/id/237/1920/1080','https://picsum.photos/id/102/1920/1080','https://picsum.photos/id/202/1920/1080','https://picsum.photos/id/99/1920/1080','https://picsum.photos/id/63/1920/1080','https://picsum.photos/id/6/1920/1080','https://picsum.photos/id/10/1920/1080','https://picsum.photos/id/19/1920/1080','https://picsum.photos/id/80/1920/1080','https://picsum.photos/id/111/1920/1080'];\n\n\nFetch all of your Divs in JS\n\nconst divs = document.querySelectorAll('.div');\n\n\nGet each Div's info, and make 3 rule with IF-Statement in JS\n\nfor (var i = 0; i < divs.length; i++) {\n const div = divs[i];\n const rect = div.getBoundingClientRect();\n if (rect.top >= 0 && rect.bottom <= window.innerHeight) {\n div.style.opacity = 1;\n document.body.style.backgroundImage = `url('${bgImgs[i]}')`;\n } else if (rect.top < 0 && rect.bottom > 0) {\n div.style.opacity = rect.bottom / window.innerHeight;\n } else if (rect.top > 0 && rect.top < window.innerHeight) {\n div.style.opacity = 1 - (rect.top / window.innerHeight);\n }\n}\n\nIn the situation, the first condition makes the relevant element's opacity 1 (this means showing us the element), and then change background image. The second condition means the next element, and finally the third condition reduces the previous element's opacity slowly.\nTest the sample\n\n\nconst bgImgs = ['https://picsum.photos/id/237/1920/1080','https://picsum.photos/id/102/1920/1080','https://picsum.photos/id/202/1920/1080','https://picsum.photos/id/99/1920/1080','https://picsum.photos/id/63/1920/1080','https://picsum.photos/id/6/1920/1080','https://picsum.photos/id/10/1920/1080','https://picsum.photos/id/19/1920/1080','https://picsum.photos/id/80/1920/1080','https://picsum.photos/id/111/1920/1080'];\nfunction handleScroll(){\n const divs = document.querySelectorAll('.div');\n for (var i = 0; i < divs.length; i++) {\n const div = divs[i];\n const rect = div.getBoundingClientRect();\n if (rect.top >= 0 && rect.bottom <= window.innerHeight) {\n div.style.opacity = 1;\n document.body.style.backgroundImage = `url('${bgImgs[i]}')`;\n } else if (rect.top < 0 && rect.bottom > 0) {\n div.style.opacity = rect.bottom / window.innerHeight;\n } else if (rect.top > 0 && rect.top < window.innerHeight) {\n div.style.opacity = 1 - (rect.top / window.innerHeight);\n }\n }\n};\nwindow.addEventListener('scroll', handleScroll);\nhandleScroll();\nhtml, body {\n /* OPTIONAL STYLE */\n margin: 20px 0 20px 0;\n padding: 0;\n transition: background-image 1s;\n \n /* The fixed background image */\n background-repeat: no-repeat;\n background-attachment: fixed;\n}\n.div {\n /* This must be exist. */\n opacity: 0;\n\n /* OPTIONAL STYLE */\n width: 300px;\n border:1px solid black;\n border-radius: 20px;\n margin:auto;\n padding: 10px;\n background-color: white;\n transition: opacity 1s;\n margin-bottom: 20px;\n}\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Opacity Divs</title>\n</head>\n<body>\n <div class=\"div\">\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n </div>\n <div class=\"div\">\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n </div>\n <div class=\"div\">\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n </div>\n <div class=\"div\">\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n </div>\n <div class=\"div\">\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n </div>\n <div class=\"div\">\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n </div>\n <div class=\"div\">\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n </div>\n <div class=\"div\">\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n </div>\n <div class=\"div\">\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n </div>\n <div class=\"div\">\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>\n <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>\n </div>\n</body>\n</html>\n\n\n\nNote:\nThe background images can load a little bit slow because of the size. It is recommended to store up your background images in the local.\n" ]
[ 1 ]
[]
[]
[ "css", "css_animations", "dom_manipulation", "html", "javascript" ]
stackoverflow_0074511327_css_css_animations_dom_manipulation_html_javascript.txt
Q: How to set up Phoenix (elixir) with surrealdb? We want to use surrealdb as our database but how would we use it in Phoenix? What configurations are needed? If you have any Experiences with this pls feel free to share :) A: I am working on SurrealDB library for Elixir. You can see how install and configure it on github: https://github.com/ricardombiot/surreal_ex If you wants works with phoenix, you can create a project without ecto (using --no-ecto flags) and after includes library dependence and start your project! For big projects/big-teams, I would recommend creates an umbrella project where you have your application will be divide on independent modules (E.g. A project for Web, other for REST, other for each service as users, mailing, booking.. so on…). The modular architecture improves testeability, reusability, extensibility of each part of your application. Note: I had working on Library only one week (Nov 26, 2022) then consider that maybe some things can change on next versions.
How to set up Phoenix (elixir) with surrealdb?
We want to use surrealdb as our database but how would we use it in Phoenix? What configurations are needed? If you have any Experiences with this pls feel free to share :)
[ "I am working on SurrealDB library for Elixir. You can see how install and configure it on github: https://github.com/ricardombiot/surreal_ex\nIf you wants works with phoenix, you can create a project without ecto (using --no-ecto flags) and after includes library dependence and start your project!\nFor big projects/big-teams, I would recommend creates an umbrella project where you have your application will be divide on independent modules (E.g. A project for Web, other for REST, other for each service as users, mailing, booking.. so on…). The modular architecture improves testeability, reusability, extensibility of each part of your application.\nNote: I had working on Library only one week (Nov 26, 2022) then consider that maybe some things can change on next versions.\n" ]
[ 0 ]
[]
[]
[ "phoenix_framework", "surrealdb" ]
stackoverflow_0074177772_phoenix_framework_surrealdb.txt
Q: My SparkSession initialization takes forever to run on my laptop. Does anybody have any idea why? My SparkSession takes forever to initialize from pyspark.sql import SparkSession spark = (SparkSession .builder .appName('Huy') .getOrCreate()) sc = spark.SparkContext waited for hours without success A: I got the same error. I have resolved it by setting the environment variables. We can set them directly in python code. You need a JDK in the program files. import os os.environ["JAVA_HOME"] = "C:\Program Files\Java\jdk-19" os.environ["SPARK_HOME"] = "C:\Program Files\Spark\spark-3.3.1-bin-hadoop2"
My SparkSession initialization takes forever to run on my laptop. Does anybody have any idea why?
My SparkSession takes forever to initialize from pyspark.sql import SparkSession spark = (SparkSession .builder .appName('Huy') .getOrCreate()) sc = spark.SparkContext waited for hours without success
[ "I got the same error. I have resolved it by setting the environment variables. We can set them directly in python code. You need a JDK in the program files.\n\n\nimport os\nos.environ[\"JAVA_HOME\"] = \"C:\\Program Files\\Java\\jdk-19\"\nos.environ[\"SPARK_HOME\"] = \"C:\\Program Files\\Spark\\spark-3.3.1-bin-hadoop2\"\n\n\n\n" ]
[ 0 ]
[]
[]
[ "apache_spark", "pyspark" ]
stackoverflow_0054185883_apache_spark_pyspark.txt
Q: Plugin [id: 'org.jetbrains.kotlin.jvm', version: '1.2.71'] was not found in any of the following sources I have a fresh install of IntelliJ, I created a new kotlin gradle project using the following settings: This produces the following build.gradle.kts, (the exact same file works on my Windows machine): import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { kotlin("jvm") version "1.2.71" } group = "com.test" version = "1.0-SNAPSHOT" repositories { mavenCentral() } dependencies { compile(kotlin("stdlib-jdk8")) } tasks.withType<KotlinCompile> { kotlinOptions.jvmTarget = "1.8" } Which produces this error, when trying to do a gradle refresh: Plugin [id: 'org.jetbrains.kotlin.jvm', version: '1.2.71'] was not found in any of the following sources: Gradle Core Plugins (plugin is not in 'org.gradle' namespace) Plugin Repositories (could not resolve plugin artifact 'org.jetbrains.kotlin.jvm:org.jetbrains.kotlin.jvm.gradle.plugin:1.2.71') Searched in the following repositories: Gradle Central Plugin Repository A: Check your Internet connection and make sure your Internet is not restricted. I solved this problem by turning on proxy for all tunnels (not just HTTP) with a VPN app. A: (1) in my case (OpenJDK 11 on Ubuntu 18.04) the problem was Gradle not being able to download the POM file from gradle plugin-server. you can test it by entering this line into jshell: new java.net.URL("https://plugins.gradle.org/m2/org/jetbrains/kotlin/jvm/org.jetbrains.kotlin.jvm.gradle.plugin/1.3.11/org.jetbrains.kotlin.jvm.gradle.plugin-1.3.11.pom").openStream() (you can find your url by running gradle with --debug option) So if you received an exception like this: InvalidAlgorithmParameterException: trustAnchors parameter must be non-empty then the trouble is CA-certs cache. which could be easily fixed by writing these lines into bash Ref: sudo su /usr/bin/printf '\xfe\xed\xfe\xed\x00\x00\x00\x02\x00\x00\x00\x00\xe2\x68\x6e\x45\xfb\x43\xdf\xa4\xd9\x92\xdd\x41\xce\xb6\xb2\x1c\x63\x30\xd7\x92' > /etc/ssl/certs/java/cacerts /var/lib/dpkg/info/ca-certificates-java.postinst configure By the way do not forget to restart gradle daemon before trying again. (gradle --stop) (2) another reason could be your internet not having access to bintray.com (the internet of Iran or China) which you can test by putting this line on jshell : new java.net.URL("https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin-api/1.3.11/kotlin-gradle-plugin-api-1.3.11.pom").openStream() If you received a connection timeout, it confirms this theory. In this case you need to buy and have proxy/vpn connected in order to be able to download these dependencies. A: import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { // kotlin("jvm") version "1.2.71" } group = "com.test" version = "1.0-SNAPSHOT" repositories { mavenCentral() } dependencies { compile(kotlin("stdlib-jdk8")) } //tasks.withType<KotlinCompile> { // kotlinOptions.jvmTarget = "1.8" //} gradle sync by commenting the above lines. The gradle will be set up. once the gradle is downloaded, uncomment those line and sync again. if the dependencies are not downloaded properly, run 'gradle build' in the terminal and click on gradle sync. This solved the issue for me. A: Check your gradle and kotlin (or Java) versions. I got the same error and my issue is solved by specifying the kotlin version in build.gradle: Before: plugins { id 'org.jetbrains.kotlin.jvm' } After: plugins { id 'org.jetbrains.kotlin.jvm' version "1.4.10" } A: In my case (Ubuntu 20.04), problem was with gradle 7.2, installed from snap. I have removed gradle 7.2, installed from snap and install gradle 7.2 from sdkman. Works fine for me. A: Ok, so the answer was very simple all along. For some reason I activated gradle's "Offline work" toggle and that was the cause of the problem. To disable it simply go to Settings > Build, Execution, Deployment > Build Tools > Gradle and deselect the "Offline work" checkbox. A: In my case the problem was because Charles Proxy. After closing Charles I could start working again A: If you are using java like me .I got the issue fixed by adding the following: Root gradle dependencies { ext.kotlin_version = '1.4.10' classpath "com.android.tools.build:gradle:7.0.4" classpath "com.google.dagger:hilt-android-gradle-plugin:2.38.1" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" ...... } App gradle file plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-kapt' id 'dagger.hilt.android.plugin' } dependencies { implementation "com.google.dagger:hilt-android:2.38.1" kapt "com.google.dagger:hilt-compiler:2.38.1" ...... } A: I recently had similar issue with an empty project autogenerated by Intellij Idea. Solved this problem by combining Java and Gradle versions. Initially I had Oracle Java 8 with Gradle 6.8.3. After several attempts I found a working combination - AdoptOpenJDK 11 and Gradle 5.6.4 A: In my case I changes the Gradle JVM in Settings > Build, Execution, Deployment > Build Tools > Gradle and it worked. A: Disconnect from your VPN (or make sure you have an open internet connection), then restart Android Studio. If you don't restart it sometimes it continues with invalid proxy properties. A: I updated my Kotlin version to 1.7.20 and fixed this problem. id 'org.jetbrains.kotlin.android' version '1.7.20' apply false
Plugin [id: 'org.jetbrains.kotlin.jvm', version: '1.2.71'] was not found in any of the following sources
I have a fresh install of IntelliJ, I created a new kotlin gradle project using the following settings: This produces the following build.gradle.kts, (the exact same file works on my Windows machine): import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { kotlin("jvm") version "1.2.71" } group = "com.test" version = "1.0-SNAPSHOT" repositories { mavenCentral() } dependencies { compile(kotlin("stdlib-jdk8")) } tasks.withType<KotlinCompile> { kotlinOptions.jvmTarget = "1.8" } Which produces this error, when trying to do a gradle refresh: Plugin [id: 'org.jetbrains.kotlin.jvm', version: '1.2.71'] was not found in any of the following sources: Gradle Core Plugins (plugin is not in 'org.gradle' namespace) Plugin Repositories (could not resolve plugin artifact 'org.jetbrains.kotlin.jvm:org.jetbrains.kotlin.jvm.gradle.plugin:1.2.71') Searched in the following repositories: Gradle Central Plugin Repository
[ "Check your Internet connection and make sure your Internet is not restricted.\nI solved this problem by turning on proxy for all tunnels (not just HTTP) with a VPN app.\n", "(1) in my case (OpenJDK 11 on Ubuntu 18.04) the problem was Gradle not being able to download the POM file from gradle plugin-server. you can test it by entering this line into jshell:\nnew java.net.URL(\"https://plugins.gradle.org/m2/org/jetbrains/kotlin/jvm/org.jetbrains.kotlin.jvm.gradle.plugin/1.3.11/org.jetbrains.kotlin.jvm.gradle.plugin-1.3.11.pom\").openStream()\n\n(you can find your url by running gradle with --debug option)\nSo if you received an exception like this: InvalidAlgorithmParameterException: trustAnchors parameter must be non-empty then the trouble is CA-certs cache. which could be easily fixed by writing these lines into bash Ref:\nsudo su\n/usr/bin/printf '\\xfe\\xed\\xfe\\xed\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\xe2\\x68\\x6e\\x45\\xfb\\x43\\xdf\\xa4\\xd9\\x92\\xdd\\x41\\xce\\xb6\\xb2\\x1c\\x63\\x30\\xd7\\x92' > /etc/ssl/certs/java/cacerts\n/var/lib/dpkg/info/ca-certificates-java.postinst configure\n\nBy the way do not forget to restart gradle daemon before trying again. (gradle --stop)\n(2) another reason could be your internet not having access to bintray.com (the internet of Iran or China) which you can test by putting this line on jshell :\nnew java.net.URL(\"https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin-api/1.3.11/kotlin-gradle-plugin-api-1.3.11.pom\").openStream()\n\nIf you received a connection timeout, it confirms this theory. In this case you need to buy and have proxy/vpn connected in order to be able to download these dependencies.\n", "import org.jetbrains.kotlin.gradle.tasks.KotlinCompile\n\nplugins {\n// kotlin(\"jvm\") version \"1.2.71\"\n}\n\ngroup = \"com.test\"\nversion = \"1.0-SNAPSHOT\"\n\nrepositories {\n mavenCentral()\n}\n\ndependencies {\n compile(kotlin(\"stdlib-jdk8\"))\n}\n\n//tasks.withType<KotlinCompile> {\n// kotlinOptions.jvmTarget = \"1.8\"\n//}\n\n\ngradle sync by commenting the above lines. The gradle will be set up.\nonce the gradle is downloaded, uncomment those line and sync again.\nif the dependencies are not downloaded properly, run 'gradle build' in the terminal and click on gradle sync.\n\nThis solved the issue for me.\n", "Check your gradle and kotlin (or Java) versions.\nI got the same error and my issue is solved by specifying the kotlin version in build.gradle:\nBefore:\nplugins {\n id 'org.jetbrains.kotlin.jvm'\n}\n\nAfter:\nplugins {\n id 'org.jetbrains.kotlin.jvm' version \"1.4.10\"\n}\n\n", "In my case (Ubuntu 20.04), problem was with gradle 7.2, installed from snap.\nI have removed gradle 7.2, installed from snap and install gradle 7.2 from sdkman. Works fine for me.\n", "Ok, so the answer was very simple all along. For some reason I activated gradle's \"Offline work\" toggle and that was the cause of the problem.\nTo disable it simply go to Settings > Build, Execution, Deployment > Build Tools > Gradle and deselect the \"Offline work\" checkbox.\n", "In my case the problem was because Charles Proxy. After closing Charles I could start working again\n", "If you are using java like me .I got the issue fixed by adding the following:\nRoot gradle\ndependencies {\n ext.kotlin_version = '1.4.10'\n\n classpath \"com.android.tools.build:gradle:7.0.4\"\n classpath \"com.google.dagger:hilt-android-gradle-plugin:2.38.1\"\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n\n ......\n }\n\nApp gradle file\nplugins {\n id 'com.android.application'\n id 'kotlin-android'\n id 'kotlin-kapt'\n id 'dagger.hilt.android.plugin'\n}\n\n dependencies {\n implementation \"com.google.dagger:hilt-android:2.38.1\"\n kapt \"com.google.dagger:hilt-compiler:2.38.1\"\n ......\n\n }\n\n", "I recently had similar issue with an empty project autogenerated by Intellij Idea.\nSolved this problem by combining Java and Gradle versions.\nInitially I had Oracle Java 8 with Gradle 6.8.3.\nAfter several attempts I found a working combination - AdoptOpenJDK 11 and Gradle 5.6.4\n", "In my case I changes the Gradle JVM in Settings > Build, Execution, Deployment > Build Tools > Gradle and it worked.\n", "Disconnect from your VPN (or make sure you have an open internet connection), then restart Android Studio.\nIf you don't restart it sometimes it continues with invalid proxy properties.\n", "I updated my Kotlin version to 1.7.20 and fixed this problem.\nid 'org.jetbrains.kotlin.android' version '1.7.20' apply false\n" ]
[ 12, 5, 5, 3, 3, 2, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "gradle", "gradle_kotlin_dsl", "intellij_idea", "kotlin" ]
stackoverflow_0052562735_gradle_gradle_kotlin_dsl_intellij_idea_kotlin.txt
Q: How do I modify Kotlin Flow distinctUntilChanged to add an expiry time How can I use distinctUntilChanged() but also add an expiry to it, which means if the same value is in the flow we still collect it because it was longer than expiry milliseconds after the previous duplicated value was emitted. flow { emit("A") // printed emit("B") // printed emit("A") // printed emit("A") // NOT printed because duplicate delay(5000) emit("A") // printed because 5 seconds elapsed which is more than expiry } .distinctUntilChanged(expiry = 2000) .collect { println(it) } I would like this to print: A B A A Here's the code to test it: @Test fun `distinctUntilChanged works as expected`(): Unit = runBlocking { flow { emit("A") // printed emit("B") // printed emit("A") // printed emit("A") // NOT printed because duplicate delay(5000) emit("A") // printed because 5 seconds elapsed which is more than expiry } .distinctUntilChanged(expiry = 2000) .toList().also { assertEquals("A", it[0]) assertEquals("B", it[1]) assertEquals("A", it[2]) assertEquals("A", it[3]) } } A: I think this will work, but I didn't test very much. I think the logic is self-explanatory. The reason havePreviousValue exists is in case T is nullable and the first emitted value is null. fun <T> Flow<T>.distinctUntilChanged(expiry: Long) = flow { var havePreviousValue = false var previousValue: T? = null var previousTime: Long = 0 collect { if (!havePreviousValue || previousValue != it || previousTime + expiry < System.currentTimeMillis()) { emit(it) havePreviousValue = true previousValue = it previousTime = System.currentTimeMillis() } } } A: Another option: fun <T> Flow<T>.distinctUntilChanged(expiry: Long) = merge( distinctUntilChanged(), channelFlow { val shared = buffer(Channel.CONFLATED).produceIn(this) debounce(expiry).takeWhile { !shared.isClosedForReceive }.collect { val lastVal = shared.receive() shared.receive().let { if(lastVal == it) send(it) } } } ) It basically adds back the non-distinct value to distinctUntilChanged().
How do I modify Kotlin Flow distinctUntilChanged to add an expiry time
How can I use distinctUntilChanged() but also add an expiry to it, which means if the same value is in the flow we still collect it because it was longer than expiry milliseconds after the previous duplicated value was emitted. flow { emit("A") // printed emit("B") // printed emit("A") // printed emit("A") // NOT printed because duplicate delay(5000) emit("A") // printed because 5 seconds elapsed which is more than expiry } .distinctUntilChanged(expiry = 2000) .collect { println(it) } I would like this to print: A B A A Here's the code to test it: @Test fun `distinctUntilChanged works as expected`(): Unit = runBlocking { flow { emit("A") // printed emit("B") // printed emit("A") // printed emit("A") // NOT printed because duplicate delay(5000) emit("A") // printed because 5 seconds elapsed which is more than expiry } .distinctUntilChanged(expiry = 2000) .toList().also { assertEquals("A", it[0]) assertEquals("B", it[1]) assertEquals("A", it[2]) assertEquals("A", it[3]) } }
[ "I think this will work, but I didn't test very much. I think the logic is self-explanatory. The reason havePreviousValue exists is in case T is nullable and the first emitted value is null.\nfun <T> Flow<T>.distinctUntilChanged(expiry: Long) = flow {\n var havePreviousValue = false\n var previousValue: T? = null\n var previousTime: Long = 0\n collect {\n if (!havePreviousValue || previousValue != it || previousTime + expiry < System.currentTimeMillis()) {\n emit(it)\n havePreviousValue = true\n previousValue = it\n previousTime = System.currentTimeMillis()\n }\n }\n}\n\n", "Another option:\nfun <T> Flow<T>.distinctUntilChanged(expiry: Long) = \n merge(\n distinctUntilChanged(), \n channelFlow {\n val shared = buffer(Channel.CONFLATED).produceIn(this)\n debounce(expiry).takeWhile { !shared.isClosedForReceive }.collect { \n val lastVal = shared.receive()\n shared.receive().let { if(lastVal == it) send(it) }\n }\n }\n )\n\nIt basically adds back the non-distinct value to distinctUntilChanged().\n" ]
[ 3, 1 ]
[]
[]
[ "kotlin", "kotlin_coroutines", "kotlin_flow" ]
stackoverflow_0074476929_kotlin_kotlin_coroutines_kotlin_flow.txt
Q: How do I setup JS code completion for a react native project on intellij? React-native organizes its project like : android --build.gradle --settings.gradle ios node_modules index.android.js index.ios.js It's a little messy and requires editing js, java and objective c code, and the android studio does not support any javascript code completion. So I decided to use IntelliJ. The problem is that if I open up at the root level, IntelliJ can't run Gradle, it will say Error running build (1): Module 'ReactLearning' is not backed by gradle However, if I open up at ./android in either android studio or IntelliJ, it works fine and I can see all the external libraries and code completion. But now I can't edit any of the code at the root level. I could have 2 editors open one at the root and one specifically for android, but then the IDEs are constantly overwriting each other's files. Is there something I can do to tell the IDE/ Gradle that the relevant project is one subdirectory down? A: When you create a React Native project, an Android project is created inside its file tree: Now, you can open the Android project using IntelliJ Idea or Android studio, with the path: /path/to/untitled/android And the untitled project which has been created with react-native init using WebStorm, which has JS support, with the path: /path/to/untitled A: You can use tabnine Plugin. It Has Great AI Auto-completion Out of the Box. A: React Native project consists of 3 parts Your JS source Android project which is technically separate android project with a link to your js bundle IOS project, the same as Android but for IOS From my experience, it is better to use Android Studio and XCode if you want to set up and change something within the native parts of your project. A: One possible solution is to create a new project in IntelliJ, and instead of importing the existing code, add the existing code to the new project by right-clicking on the project in the Project pane and selecting New > Directory. Then, navigate to the root directory of your React Native project and select it. This will add the root directory and all its subdirectories to your IntelliJ project, allowing you to edit and run the code from within IntelliJ. Another solution is to create a new build.gradle file at the root of your project and include the necessary configuration for running Gradle in IntelliJ. This will allow you to open the project at the root level in IntelliJ and run Gradle commands from there. To create a new build.gradle file, first create a new file at the root of your project and name it build.gradle. Then, add the following code to the file: apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "com.myapp" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.1.1' } Be sure to update the values for compileSdkVersion, buildToolsVersion, applicationId, minSdkVersion, and targetSdkVersion to match your project's settings. Once you have added this build.gradle file to your project, you should be able to open the project in IntelliJ at the root level and run Gradle commands from within the IDE. This will allow you to use code completion for your React Native project in IntelliJ.
How do I setup JS code completion for a react native project on intellij?
React-native organizes its project like : android --build.gradle --settings.gradle ios node_modules index.android.js index.ios.js It's a little messy and requires editing js, java and objective c code, and the android studio does not support any javascript code completion. So I decided to use IntelliJ. The problem is that if I open up at the root level, IntelliJ can't run Gradle, it will say Error running build (1): Module 'ReactLearning' is not backed by gradle However, if I open up at ./android in either android studio or IntelliJ, it works fine and I can see all the external libraries and code completion. But now I can't edit any of the code at the root level. I could have 2 editors open one at the root and one specifically for android, but then the IDEs are constantly overwriting each other's files. Is there something I can do to tell the IDE/ Gradle that the relevant project is one subdirectory down?
[ "When you create a React Native project, an Android project is created inside its file tree:\n\nNow, you can open the Android project using IntelliJ Idea or Android studio, with the path:\n/path/to/untitled/android\n\nAnd the untitled project which has been created with react-native init using WebStorm, which has JS support, with the path:\n/path/to/untitled\n\n", "You can use tabnine Plugin. It Has Great AI Auto-completion Out of the Box.\n", "React Native project consists of 3 parts\n\nYour JS source\nAndroid project which is technically separate android project with a link to your js bundle\nIOS project, the same as Android but for IOS\n\nFrom my experience, it is better to use Android Studio and XCode if you want to set up and change something within the native parts of your project.\n", "One possible solution is to create a new project in IntelliJ, and instead of importing the existing code, add the existing code to the new project by right-clicking on the project in the Project pane and selecting New > Directory. Then, navigate to the root directory of your React Native project and select it. This will add the root directory and all its subdirectories to your IntelliJ project, allowing you to edit and run the code from within IntelliJ.\nAnother solution is to create a new build.gradle file at the root of your project and include the necessary configuration for running Gradle in IntelliJ. This will allow you to open the project at the root level in IntelliJ and run Gradle commands from there.\nTo create a new build.gradle file, first create a new file at the root of your project and name it build.gradle. Then, add the following code to the file:\napply plugin: 'com.android.application'\n\nandroid {\ncompileSdkVersion 23\nbuildToolsVersion \"23.0.2\"\n\ndefaultConfig {\napplicationId \"com.myapp\"\nminSdkVersion 15\ntargetSdkVersion 23\nversionCode 1\nversionName \"1.0\"\n}\nbuildTypes {\nrelease {\nminifyEnabled false\nproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n}\n}\n}\n\ndependencies {\ncompile fileTree(dir: 'libs', include: ['*.jar'])\ncompile 'com.android.support:appcompat-v7:23.1.1'\n}\n\nBe sure to update the values for compileSdkVersion, buildToolsVersion, applicationId, minSdkVersion, and targetSdkVersion to match your project's settings.\nOnce you have added this build.gradle file to your project, you should be able to open the project in IntelliJ at the root level and run Gradle commands from within the IDE. This will allow you to use code completion for your React Native project in IntelliJ.\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "android", "intellij_idea", "react_native" ]
stackoverflow_0040393680_android_intellij_idea_react_native.txt
Q: python changing a list into a dictionary so i'm taking a python class right now and am struggling with dictionaries at the moment. my assignment is simple, i have to create a fucntion "letter_positions" which will return a dictionary of all positions of a letter in a string. for example positions = letter_positions("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's") positions['e'] should return {4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142} so i'm pretty much done with the assignment but i'm running into the issue that i have all values (positions) assigned to the keys (letters) as a list. here's my code: def letter_positions(n): answer = {} n = n.lower() x = 0 for letter in n: if letter.isalpha(): if letter not in answer: answer[letter] = [] answer[letter].append(x) x += 1 return answer so instead of getting a dictionary of positions i'm getting a list of positions. positions = letter_positions("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's") positions['e'] returns [4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142] is there any way for me to simply change the list into a dictionary or am i approaching this in a completely wrong way? A: If I understand your question correctly, you would like to return a dictionary with the searching key (letter). One way to achieve that in more Pythonic way is to use collections defaultdict factory method to build the indices as list: from collections import defaultdict def letter_index(sentence): answer = defaultdict(list) for idx, ch in enumerate(sentence): answer[ch].append(idx) return answer positions = letter_index("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's") ch = 'e' for k, v in positions.items(): if k == ch: print(k, v) # e [4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142] A: change your code like this def letter_positions(n): answer = {} n = n.lower() x = 0 for letter in n: if letter.isalpha(): answer[letter] = answer.get(letter,[])#if there is not the key letter add it as key with value an empty list answer[letter].append(x) x=x+1 return answer positions = letter_positions("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's") print(positions['e'])
python changing a list into a dictionary
so i'm taking a python class right now and am struggling with dictionaries at the moment. my assignment is simple, i have to create a fucntion "letter_positions" which will return a dictionary of all positions of a letter in a string. for example positions = letter_positions("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's") positions['e'] should return {4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142} so i'm pretty much done with the assignment but i'm running into the issue that i have all values (positions) assigned to the keys (letters) as a list. here's my code: def letter_positions(n): answer = {} n = n.lower() x = 0 for letter in n: if letter.isalpha(): if letter not in answer: answer[letter] = [] answer[letter].append(x) x += 1 return answer so instead of getting a dictionary of positions i'm getting a list of positions. positions = letter_positions("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's") positions['e'] returns [4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142] is there any way for me to simply change the list into a dictionary or am i approaching this in a completely wrong way?
[ "If I understand your question correctly, you would like to return a dictionary with the searching key (letter).\nOne way to achieve that in more Pythonic way is to use collections defaultdict factory method to build the indices as list:\nfrom collections import defaultdict\n\ndef letter_index(sentence):\n answer = defaultdict(list)\n \n for idx, ch in enumerate(sentence):\n answer[ch].append(idx)\n \n return answer\n \npositions = letter_index(\"fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's\")\n\nch = 'e'\n\nfor k, v in positions.items():\n if k == ch:\n print(k, v)\n\n# e [4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142]\n\n", "change your code like this\ndef letter_positions(n):\n answer = {}\n n = n.lower()\n x = 0\n for letter in n:\n if letter.isalpha():\n answer[letter] = answer.get(letter,[])#if there is not the key letter add it as key with value an empty list\n answer[letter].append(x)\n x=x+1\n return answer\npositions = letter_positions(\"fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's\")\nprint(positions['e'])\n\n" ]
[ 1, 0 ]
[]
[]
[ "dictionary", "list", "python_3.x" ]
stackoverflow_0074668891_dictionary_list_python_3.x.txt
Q: Firebase Authentication "auth/invalid-email" and "The email address is badly formatted." I am trying to implement Firebase login/registration into my app using Angular and Ionic 4. I have the registration of my account working and forgetting the password working I can see the accounts in my firebase console. The issue I am having is when I try to log into that account I created. In the developer console I get https://imgur.com/a/WzRiwtn : code: "auth/invalid-email" message: "The email address is badly formatted." Its saying the issue lies in my tab3.page.ts:22 Here is the code from that page import { Component } from '@angular/core'; import { AlertController } from '@ionic/angular'; import { LoadingController, ToastController } from '@ionic/angular'; import { Router } from '@angular/router'; import { AngularFireAuth } from '@angular/fire/auth'; @Component({ selector: 'app-tab3', templateUrl: 'tab3.page.html', styleUrls: ['tab3.page.scss'] }) export class Tab3Page { email: string = ''; password: string = ''; error: string = ''; constructor(private fireauth: AngularFireAuth, private router: Router, private toastController: ToastController, public loadingController: LoadingController, public alertController: AlertController) { } async openLoader() { const loading = await this.loadingController.create({ message: 'Please Wait ...', duration: 2000 }); await loading.present(); } async closeLoading() { return await this.loadingController.dismiss(); } login() { this.fireauth.auth.signInWithEmailAndPassword(this.email, this.password) .then(res => { if (res.user) { console.log(res.user); this.router.navigate(['/home']); } }) .catch(err => { console.log(`login failed ${err}`); this.error = err.message; }); } async presentToast(message, show_button, position, duration) { const toast = await this.toastController.create({ message: message, showCloseButton: show_button, position: position, duration: duration }); toast.present(); } } I have been staring at this since Friday trying multiple different methods and guides online and every method I try I am getting this error any help would be VERY much appreciated. This code came from following this https://enappd.com/blog/email-authentication-with-firebase-in-ionic-4/38/ tutorial and even looking at his github and following it exactly I still come to this issue. A: Here is your error type https://firebase.google.com/docs/auth/admin/errors Hopefully email which you are passing having issue. It should be proper string only. A: From what you're showing here, email has an initial value of an empty string: email: string = ''; And, from what I can see, it never changes value. So you're passing an empty string to signInWithEmailAndPassword, which isn't valid. A: change ' ' to null. better still update to const [email, setEmail] = useState(null); A: Firebase Authentication "auth/invalid-email" and "The email address is badly formatted." Use an email format like: [email protected] [email protected]
Firebase Authentication "auth/invalid-email" and "The email address is badly formatted."
I am trying to implement Firebase login/registration into my app using Angular and Ionic 4. I have the registration of my account working and forgetting the password working I can see the accounts in my firebase console. The issue I am having is when I try to log into that account I created. In the developer console I get https://imgur.com/a/WzRiwtn : code: "auth/invalid-email" message: "The email address is badly formatted." Its saying the issue lies in my tab3.page.ts:22 Here is the code from that page import { Component } from '@angular/core'; import { AlertController } from '@ionic/angular'; import { LoadingController, ToastController } from '@ionic/angular'; import { Router } from '@angular/router'; import { AngularFireAuth } from '@angular/fire/auth'; @Component({ selector: 'app-tab3', templateUrl: 'tab3.page.html', styleUrls: ['tab3.page.scss'] }) export class Tab3Page { email: string = ''; password: string = ''; error: string = ''; constructor(private fireauth: AngularFireAuth, private router: Router, private toastController: ToastController, public loadingController: LoadingController, public alertController: AlertController) { } async openLoader() { const loading = await this.loadingController.create({ message: 'Please Wait ...', duration: 2000 }); await loading.present(); } async closeLoading() { return await this.loadingController.dismiss(); } login() { this.fireauth.auth.signInWithEmailAndPassword(this.email, this.password) .then(res => { if (res.user) { console.log(res.user); this.router.navigate(['/home']); } }) .catch(err => { console.log(`login failed ${err}`); this.error = err.message; }); } async presentToast(message, show_button, position, duration) { const toast = await this.toastController.create({ message: message, showCloseButton: show_button, position: position, duration: duration }); toast.present(); } } I have been staring at this since Friday trying multiple different methods and guides online and every method I try I am getting this error any help would be VERY much appreciated. This code came from following this https://enappd.com/blog/email-authentication-with-firebase-in-ionic-4/38/ tutorial and even looking at his github and following it exactly I still come to this issue.
[ "Here is your error type\nhttps://firebase.google.com/docs/auth/admin/errors\nHopefully email which you are passing having issue. It should be proper string only.\n", "From what you're showing here, email has an initial value of an empty string:\nemail: string = '';\n\nAnd, from what I can see, it never changes value. So you're passing an empty string to signInWithEmailAndPassword, which isn't valid.\n", "change ' ' to null.\nbetter still update to\nconst [email, setEmail] = useState(null);\n", "Firebase Authentication \"auth/invalid-email\" and \"The email address is badly formatted.\"\nUse an email format like:\[email protected]\[email protected]\n\n" ]
[ 4, 2, 0, 0 ]
[]
[]
[ "angular", "firebase", "firebase_authentication", "ionic_framework", "javascript" ]
stackoverflow_0060593166_angular_firebase_firebase_authentication_ionic_framework_javascript.txt
Q: Javascript validtion Error Message is not Showing. Validation is working but if Enter wrong data it should be display Error MSg I have tried to add below code to show the Error message. Form is working fine when I submit all the correct values and also working fine when I entered the wrong values only problem is not showing the Error msg if entered the wrong values. $("input").add("span").addClass("error").value("*"); // adding span with class of error and value of * <h1>Reservation Request</h1> <form action="response.html" method="get" name="reservation_form" id="reservation_form"> <fieldset> <legend>General Information</legend> <label for="arrival_date">Arrival date:</label> <input type="text" name="arrival_date" id="arrival_date" autofocus> <span>*</span><br> <label for="nights">Nights:</label> <input type="text" name="nights" id="nights"> <span>*</span><br> <label>Adults:</label> <select name="adults" id="adults"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select><br> <label>Children:</label> <select name="children" id="children"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select><br> </fieldset> <fieldset> <legend>Preferences</legend> <label>Room type:</label> <input type="radio" name="room" id="standard" class="left" checked>Standard&nbsp;&nbsp;&nbsp; <input type="radio" name="room" id="business" class="left">Business&nbsp;&nbsp;&nbsp; <input type="radio" name="room" id="suite" class="left last">Suite<br> <label>Bed type:</label> <input type="radio" name="bed" id="king" class="left" checked>King&nbsp;&nbsp;&nbsp; <input type="radio" name="bed" id="double" class="left last">Double Double<br> <input type="checkbox" name="smoking" id="smoking">Smoking<br> </fieldset> <fieldset> <legend>Contact Information</legend> <label for="name">Name:</label> <input type="text" name="name" id="name"> <span>*</span><br> <label for="email">Email:</label> <input type="text" name="email" id="email"> <span>*</span><br> <label for="phone">Phone:</label> <input type="text" name="phone" id="phone" placeholder="999-999-9999"> <span>*</span><br> </fieldset> <input type="submit" id="submit" value="Submit Request"><br> </form> ``` I have tried to add below code to show the Error message. ``` $("input").add("span").addClass("error").value("*"); // adding span with class of error and value of * $(document).ready(function () { $("#arrival_date").focus; var $fields = $("#reservation_form").find('input'); $("#reservation_form").submit(function (e) { var $emptyFields = $fields.filter(function () { // remove the $.trim if whitespace is counted as filled return $.trim(this.value) === ""; }); if ($emptyFields.length || !$.isNumeric($("#nights").val()) || !validateEmail($("#email").val())) { e.preventDefault(); } function storeValues(form) { //function to store cookie values from input boxes setCookie("arrival_date", form.arrival_date.value); setCookie("nights", form.nights.value); setCookie("name", form.name.value); setCookie("email", form.email.value); setCookie("phone", form.phone.value); return true; } }); function validateEmail(email) { var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i; return re.test(email); } }); A: It looks like you're trying to add a span with the class error and a value of "*" to each input in your form. However, there are a few problems with your code. First, the add() method in jQuery is used to add elements to a selection, but it doesn't modify the existing elements. So, in your code, $("input").add("span") will create a new selection that contains all of the input elements, followed by all of the span elements, but it won't modify the input elements in any way. Second, the addClass() method is used to add a class to elements in a selection, but it doesn't have a value() method. The value() method is used to get or set the value of an input element, but it doesn't have a class() method. So, in your code, addClass("error").value("*") doesn't make sense because it's trying to use methods that don't exist. $(document).ready(function() { // Add a span with the class "error" and a value of "*" after each input element $("input").after("<span class='error'>*</span>"); // Get all of the input fields in the form var $fields = $("#reservation_form").find('input'); // Attach a submit handler to the form $("#reservation_form").submit(function(e) { // Prevent the form from being submitted e.preventDefault(); // Get all of the empty fields in the form var $emptyFields = $fields.filter(function() { // Remove the $.trim if whitespace is counted as filled return $.trim(this.value) === ""; }); // If there are empty fields, or if the "nights" field doesn't contain a number, show an error message if ($emptyFields.length || !$.isNumeric($("#nights").val())) { alert("Please fill out all of the required fields and make sure the 'Nights' field contains a number."); } else { // If all of the fields are filled out and the "nights" field contains a number, submit the form this.submit(); } }); });
Javascript validtion Error Message is not Showing. Validation is working but if Enter wrong data it should be display Error MSg
I have tried to add below code to show the Error message. Form is working fine when I submit all the correct values and also working fine when I entered the wrong values only problem is not showing the Error msg if entered the wrong values. $("input").add("span").addClass("error").value("*"); // adding span with class of error and value of * <h1>Reservation Request</h1> <form action="response.html" method="get" name="reservation_form" id="reservation_form"> <fieldset> <legend>General Information</legend> <label for="arrival_date">Arrival date:</label> <input type="text" name="arrival_date" id="arrival_date" autofocus> <span>*</span><br> <label for="nights">Nights:</label> <input type="text" name="nights" id="nights"> <span>*</span><br> <label>Adults:</label> <select name="adults" id="adults"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select><br> <label>Children:</label> <select name="children" id="children"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select><br> </fieldset> <fieldset> <legend>Preferences</legend> <label>Room type:</label> <input type="radio" name="room" id="standard" class="left" checked>Standard&nbsp;&nbsp;&nbsp; <input type="radio" name="room" id="business" class="left">Business&nbsp;&nbsp;&nbsp; <input type="radio" name="room" id="suite" class="left last">Suite<br> <label>Bed type:</label> <input type="radio" name="bed" id="king" class="left" checked>King&nbsp;&nbsp;&nbsp; <input type="radio" name="bed" id="double" class="left last">Double Double<br> <input type="checkbox" name="smoking" id="smoking">Smoking<br> </fieldset> <fieldset> <legend>Contact Information</legend> <label for="name">Name:</label> <input type="text" name="name" id="name"> <span>*</span><br> <label for="email">Email:</label> <input type="text" name="email" id="email"> <span>*</span><br> <label for="phone">Phone:</label> <input type="text" name="phone" id="phone" placeholder="999-999-9999"> <span>*</span><br> </fieldset> <input type="submit" id="submit" value="Submit Request"><br> </form> ``` I have tried to add below code to show the Error message. ``` $("input").add("span").addClass("error").value("*"); // adding span with class of error and value of * $(document).ready(function () { $("#arrival_date").focus; var $fields = $("#reservation_form").find('input'); $("#reservation_form").submit(function (e) { var $emptyFields = $fields.filter(function () { // remove the $.trim if whitespace is counted as filled return $.trim(this.value) === ""; }); if ($emptyFields.length || !$.isNumeric($("#nights").val()) || !validateEmail($("#email").val())) { e.preventDefault(); } function storeValues(form) { //function to store cookie values from input boxes setCookie("arrival_date", form.arrival_date.value); setCookie("nights", form.nights.value); setCookie("name", form.name.value); setCookie("email", form.email.value); setCookie("phone", form.phone.value); return true; } }); function validateEmail(email) { var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i; return re.test(email); } });
[ "It looks like you're trying to add a span with the class error and a value of \"*\" to each input in your form. However, there are a few problems with your code.\nFirst, the add() method in jQuery is used to add elements to a selection, but it doesn't modify the existing elements. So, in your code, $(\"input\").add(\"span\") will create a new selection that contains all of the input elements, followed by all of the span elements, but it won't modify the input elements in any way.\nSecond, the addClass() method is used to add a class to elements in a selection, but it doesn't have a value() method. The value() method is used to get or set the value of an input element, but it doesn't have a class() method. So, in your code, addClass(\"error\").value(\"*\") doesn't make sense because it's trying to use methods that don't exist.\n$(document).ready(function() {\n // Add a span with the class \"error\" and a value of \"*\" after each input element\n $(\"input\").after(\"<span class='error'>*</span>\");\n \n // Get all of the input fields in the form\n var $fields = $(\"#reservation_form\").find('input');\n \n // Attach a submit handler to the form\n $(\"#reservation_form\").submit(function(e) {\n // Prevent the form from being submitted\n e.preventDefault();\n \n // Get all of the empty fields in the form\n var $emptyFields = $fields.filter(function() {\n // Remove the $.trim if whitespace is counted as filled\n return $.trim(this.value) === \"\";\n });\n \n // If there are empty fields, or if the \"nights\" field doesn't contain a number, show an error message\n if ($emptyFields.length || !$.isNumeric($(\"#nights\").val())) {\n alert(\"Please fill out all of the required fields and make sure the 'Nights' field contains a number.\");\n } else {\n // If all of the fields are filled out and the \"nights\" field contains a number, submit the form\n this.submit();\n }\n });\n});\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "javascript", "jquery", "validation" ]
stackoverflow_0074664675_arrays_javascript_jquery_validation.txt
Q: CREATE ALGORITHM=UNDEFINED DEFINER I make a backup of some database from distance server, and I had an problem on my local server when I trying to import that backup. I get an error in this line: CREATE ALGORITHM=UNDEFINED DEFINER=root@% SQL SECURITY DEFINER VIEW tematics_field AS select..... Both server have a mysql 5.5.2x. And users are different in that two servers. A: I only try to: CREATE VIEW tematics_field AS select.... And all is work perfectly and import is well done. A: MySql Error: #1227 – Access denied; you need (at least one of) the SUPER privilege(s) for this operation CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY INVOKER VIEW `inventory_stock_1` AS SELECT DISTINCT `legacy_stock_status`.`product_id` AS `product_id`,`legacy_stock_status`.`website_id` AS `website_id`,`legacy_stock_status`.`stock_id` AS `stock_id`,`legacy_stock_status`.`qty` AS `quantity`,`legacy_stock_status`.`stock_status` AS `is_salable`,`product`.`sku` AS `sku` FROM (`cataloginventory_stock_status` `legacy_stock_status` JOIN `decg_catalog_product_entity` `product` ON(`legacy_stock_status`.`product_id` = `product`.`entity_id`)) ; Fixed Solution: The problem is you set definer as root, which is not your current running user, that’s why you need to SUPER privilege. you can create a user called root in RDS, and use root to run the command, or simply CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY INVOKER change to: CREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER read more about CURRENT_USER Final SQL query looks like CREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER VIEW `inventory_stock_1` AS SELECT DISTINCT `legacy_stock_status`.`product_id` AS `product_id`,`legacy_stock_status`.`website_id` AS `website_id`,`legacy_stock_status`.`stock_id` AS `stock_id`,`legacy_stock_status`.`qty` AS `quantity`,`legacy_stock_status`.`stock_status` AS `is_salable`,`product`.`sku` AS `sku` FROM (`cataloginventory_stock_status` `legacy_stock_status` JOIN `decg_catalog_product_entity` `product` ON(`legacy_stock_status`.`product_id` = `product`.`entity_id`)) ; Thank you.From: MazziTorch A: You need to put the hostname (or wildcard in this case) in single-quotes: CREATE ALGORITHM=UNDEFINED DEFINER=root@'%' SQL SECURITY DEFINER VIEW tematics_field AS select..... A: I faced a similar thing. In place of : CREATE ALGORITHM=UNDEFINED DEFINER=`cccts_org`@`%` SQL SECURITY DEFINER VIEW I substituted CURRENT_USER() for the DEFINER and it worked. CREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER() SQL SECURITY DEFINER VIEW If that is used in the next import, it should be portable and not trip over the old credentials. A: CREATE ALGORITHM=UNDEFINED DEFINER=root@% SQL SECURITY DEFINER VIEW tematics_field AS select..... Please remove "ALGORITHM=UNDEFINED DEFINER=root@% SQL SECURITY DEFINER" and keep like "CREATE VIEW tematics_field AS select..... it will work while importing or direct pasting under sql tab A: Error messages: ERROR 1227 (42000) at line XXXX: Access denied; you need (at least one of) the SUPER privilege(s) for this operation Just try this: sed -i.bak 's/`root`@`%`/CURRENT_USER/g' /path/to/your.sql Note: 'root@%' is the user who defined that view. or edit sql file in VIM: :%s/`root`@`%`/CURRENT_USER/g Good luck! A: CREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER
CREATE ALGORITHM=UNDEFINED DEFINER
I make a backup of some database from distance server, and I had an problem on my local server when I trying to import that backup. I get an error in this line: CREATE ALGORITHM=UNDEFINED DEFINER=root@% SQL SECURITY DEFINER VIEW tematics_field AS select..... Both server have a mysql 5.5.2x. And users are different in that two servers.
[ "I only try to:\nCREATE VIEW tematics_field AS select....\n\nAnd all is work perfectly and import is well done.\n", "MySql Error: #1227 – Access denied; you need (at least one of) the SUPER privilege(s) for this operation\nCREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY INVOKER VIEW `inventory_stock_1` AS SELECT DISTINCT `legacy_stock_status`.`product_id` AS `product_id`,`legacy_stock_status`.`website_id` AS `website_id`,`legacy_stock_status`.`stock_id` AS `stock_id`,`legacy_stock_status`.`qty` AS `quantity`,`legacy_stock_status`.`stock_status` AS `is_salable`,`product`.`sku` AS `sku` FROM (`cataloginventory_stock_status` `legacy_stock_status` JOIN `decg_catalog_product_entity` `product` ON(`legacy_stock_status`.`product_id` = `product`.`entity_id`)) ;\n\nFixed Solution:\nThe problem is you set definer as root, which is not your current running user, that’s why you need to SUPER privilege.\nyou can create a user called root in RDS, and use root to run the command, or simply\nCREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY INVOKER\n\nchange to:\nCREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER\n\nread more about CURRENT_USER\nFinal SQL query looks like\nCREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER VIEW `inventory_stock_1` AS SELECT DISTINCT `legacy_stock_status`.`product_id` AS `product_id`,`legacy_stock_status`.`website_id` AS `website_id`,`legacy_stock_status`.`stock_id` AS `stock_id`,`legacy_stock_status`.`qty` AS `quantity`,`legacy_stock_status`.`stock_status` AS `is_salable`,`product`.`sku` AS `sku` FROM (`cataloginventory_stock_status` `legacy_stock_status` JOIN `decg_catalog_product_entity` `product` ON(`legacy_stock_status`.`product_id` = `product`.`entity_id`)) ;\n\nThank you.From: MazziTorch\n", "You need to put the hostname (or wildcard in this case) in single-quotes:\nCREATE ALGORITHM=UNDEFINED DEFINER=root@'%' SQL SECURITY DEFINER VIEW tematics_field AS \nselect.....\n\n", "I faced a similar thing. In place of :\nCREATE ALGORITHM=UNDEFINED DEFINER=`cccts_org`@`%` SQL SECURITY DEFINER VIEW\n\nI substituted CURRENT_USER() for the DEFINER and it worked.\nCREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER() SQL SECURITY DEFINER VIEW\n\nIf that is used in the next import, it should be portable and not trip over the old credentials.\n", " CREATE ALGORITHM=UNDEFINED DEFINER=root@% SQL SECURITY DEFINER VIEW tematics_field AS select.....\nPlease remove \"ALGORITHM=UNDEFINED DEFINER=root@% SQL SECURITY DEFINER\" and keep like \"CREATE VIEW tematics_field AS select.....\nit will work while importing or direct pasting under sql tab\n\n", "Error messages:\nERROR 1227 (42000) at line XXXX: Access denied; you need (at least one of) the SUPER privilege(s) for this operation\n\nJust try this:\nsed -i.bak 's/`root`@`%`/CURRENT_USER/g' /path/to/your.sql\n\n\nNote: 'root@%' is the user who defined that view.\n\nor edit sql file in VIM:\n:%s/`root`@`%`/CURRENT_USER/g\n\nGood luck!\n", "CREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER\n" ]
[ 19, 15, 13, 1, 0, 0, 0 ]
[]
[]
[ "database", "mysql", "phpmyadmin" ]
stackoverflow_0017600564_database_mysql_phpmyadmin.txt
Q: Why is cache.readQuery returning null? I have a project management application built with React and GraphQL for which the Github repo can be found here. One of the functionalities allows for deleting a project. I am trying to update the cache when I delete an individual project. const [deleteProject] = useMutation(DELETE_PROJECT, { variables: { id: projectId }, update(cache, { data: { deleteProject } }) { const { projects } = cache.readQuery({ query: GET_PROJECTS }); cache.writeQuery({ query: GET_PROJECTS, data: { projects: projects.filter( (project) => project.id !== deleteProject.id ), }, }); }, onCompleted: () => navigate("/"), }); However, when I attempt to do so, I am getting the following error: Error: Cannot destructure property 'projects' of 'cache.readQuery(...)' as it is null Can someone help me figure out what's going on? This is what the getProjects query looks like: const GET_PROJECTS = gql` query getProjects { projects { id name description status } } `; Here is the root query: const RootQuery = new GraphQLObjectType({ name: "RootQueryType", fields: { projects: { type: new GraphQLList(ProjectType), resolve(parent, args) { return Project.find(); }, }, project: { type: ProjectType, args: { id: { type: GraphQLID } }, resolve(parent, args) { return Project.findById(args.id); }, }, clients: { type: new GraphQLList(ClientType), resolve(parent, args) { return Client.find(); }, }, client: { type: ClientType, args: { id: { type: GraphQLID } }, resolve(parent, args) { return Client.findById(args.id); }, }, }, }); A: It looks like the issue is with const { projects } = cache.readQuery({ query: GET_PROJECTS });. The error message says that projects is null, which means that cache.readQuery({ query: GET_PROJECTS }) is returning an object with a null value for the projects property. One possible cause of this error is that the GET_PROJECTS query is not being executed before the deleteProject mutation. In order for the cache to have data for the GET_PROJECTS query, that query must be executed and the results must be stored in the cache. You can fix this error by ensuring that the GET_PROJECTS query is executed before the deleteProject mutation. This can be done in a number of ways, depending on how your application is structured. One way to do it is to add the GET_PROJECTS query to the list of queries that are executed when the component that contains the deleteProject mutation is rendered. You can do this by using the useQuery hook in your React component. Here is an example of how you could use the useQuery hook to execute the GET_PROJECTS query when the component is rendered: const { data } = useQuery(GET_PROJECTS); This code will execute the GET_PROJECTS query and store the results in the data variable. The data variable will be an object with a projects property that contains the list of projects. Once the GET_PROJECTS query has been executed and the results are stored in the cache, the deleteProject mutation will be able to read the data from the cache and update it correctly. A: Projects may be null in some cases, so you should check for that before attempting to destructure it. You can do that by adding a null check like this: update(cache, { data: { deleteProject } }) { const queryResult = cache.readQuery({ query: GET_PROJECTS }); if (queryResult && queryResult.projects) { const { projects } = queryResult; cache.writeQuery({ query: GET_PROJECTS, data: { projects: projects.filter( (project) => project.id !== deleteProject.id ), }, }); } }, This will make sure that projects is not null before you try to destructure it.
Why is cache.readQuery returning null?
I have a project management application built with React and GraphQL for which the Github repo can be found here. One of the functionalities allows for deleting a project. I am trying to update the cache when I delete an individual project. const [deleteProject] = useMutation(DELETE_PROJECT, { variables: { id: projectId }, update(cache, { data: { deleteProject } }) { const { projects } = cache.readQuery({ query: GET_PROJECTS }); cache.writeQuery({ query: GET_PROJECTS, data: { projects: projects.filter( (project) => project.id !== deleteProject.id ), }, }); }, onCompleted: () => navigate("/"), }); However, when I attempt to do so, I am getting the following error: Error: Cannot destructure property 'projects' of 'cache.readQuery(...)' as it is null Can someone help me figure out what's going on? This is what the getProjects query looks like: const GET_PROJECTS = gql` query getProjects { projects { id name description status } } `; Here is the root query: const RootQuery = new GraphQLObjectType({ name: "RootQueryType", fields: { projects: { type: new GraphQLList(ProjectType), resolve(parent, args) { return Project.find(); }, }, project: { type: ProjectType, args: { id: { type: GraphQLID } }, resolve(parent, args) { return Project.findById(args.id); }, }, clients: { type: new GraphQLList(ClientType), resolve(parent, args) { return Client.find(); }, }, client: { type: ClientType, args: { id: { type: GraphQLID } }, resolve(parent, args) { return Client.findById(args.id); }, }, }, });
[ "It looks like the issue is with const { projects } = cache.readQuery({ query: GET_PROJECTS });. The error message says that projects is null, which means that cache.readQuery({ query: GET_PROJECTS }) is returning an object with a null value for the projects property.\nOne possible cause of this error is that the GET_PROJECTS query is not being executed before the deleteProject mutation. In order for the cache to have data for the GET_PROJECTS query, that query must be executed and the results must be stored in the cache.\nYou can fix this error by ensuring that the GET_PROJECTS query is executed before the deleteProject mutation. This can be done in a number of ways, depending on how your application is structured. One way to do it is to add the GET_PROJECTS query to the list of queries that are executed when the component that contains the deleteProject mutation is rendered. You can do this by using the useQuery hook in your React component.\nHere is an example of how you could use the useQuery hook to execute the GET_PROJECTS query when the component is rendered:\nconst { data } = useQuery(GET_PROJECTS);\n\nThis code will execute the GET_PROJECTS query and store the results in the data variable. The data variable will be an object with a projects property that contains the list of projects.\nOnce the GET_PROJECTS query has been executed and the results are stored in the cache, the deleteProject mutation will be able to read the data from the cache and update it correctly.\n", "Projects may be null in some cases, so you should check for that before attempting to destructure it.\nYou can do that by adding a null check like this:\nupdate(cache, { data: { deleteProject } }) {\nconst queryResult = cache.readQuery({ query: GET_PROJECTS });\nif (queryResult && queryResult.projects) {\nconst { projects } = queryResult;\ncache.writeQuery({\nquery: GET_PROJECTS,\ndata: {\nprojects: projects.filter(\n(project) => project.id !== deleteProject.id\n),\n},\n});\n}\n},\n\nThis will make sure that projects is not null before you try to destructure it.\n" ]
[ 1, 1 ]
[]
[]
[ "graphql", "javascript", "reactjs" ]
stackoverflow_0074670208_graphql_javascript_reactjs.txt
Q: C# Accessing a class from a "parent project" in a "child project"? Let's say I have multiple projects within a solution. I have the main project parent_project and another project child_project. How can I access classes / namespaces residing in parent_project from child_project ? I have already added a Reference to child_project in parent_project so I can't add a Reference to parent_parent in child_project as it would create a circular dependency. Is this possible? A: If you're sharing logic between projects, you need to isolate that dependency and move it to a shared location (new project for example), restructure your dependencies so that your core logic lives in a core domain-like project or mash your projects together. The latter is not really the cleanest of solutions. I would recommend thinking about your own question and really try to answer "Why do I NEED a circular reference? How can I restructure so that my dependencies make sense?". A: You can inject your dependency using an interface defined in the child project (this can be useful where major refactoring is not possible/too expensive). e.g. In the child project: interface IA { DoLogicInB(); } In the parent project: class ConcreteA : ChildProject.IA { DoLogicInB() { ... } } In the child project, where you need the logic: class ChildB { void DoSomethingWithParent(IA logicEngine) { logicEngine.DoLogicInB(); } } You need to then be able to inject a concrete implementation of the parent object from outside the child project. A: FYI I ended up just copying the logic to a shared location, and "child" projects can access this version. I know from a maintainability point of view this isn't the best solution but it seemed like the best compromise.. A: I didn't require entire namespace, but just reading some data dictionary or calling one particular method from parent project class. Here is how we got it working. using System; using NUnit.Framework; using System.Collections.Concurrent; namespace MyProject.tests { public class ParentChildTest { [Test] public void dataAndMethodTest() { // add the data in parent project Parent.propertyCache["a"] = "b"; // read the data in child project Console.WriteLine("Read from child: " + Child.getProperty("a")); // use Child project to call method of parent project Console.WriteLine("Call from child: Populate method in parent: " + Child.populate("c")); } } class Parent { // data is in Child project. Parent project just has the reference. public static ConcurrentDictionary<string, string> propertyCache = Child.getPropertyCache(); public static string populate(string key) { //calculation string value = key + key; propertyCache[key] = value; return value; } // Pass the parent project method reference to child project public static int dummy = Child.setPopulateMethod(populate); } class Child { // data store static ConcurrentDictionary<string, string> propertyCache = new ConcurrentDictionary<string, string>(); public static ConcurrentDictionary<string, string> getPropertyCache() { return propertyCache; } public static string getProperty(string key) { if (propertyCache.ContainsKey(key)) { return propertyCache[key]; } return null; } // reference to parent project method static Func<string, string> populateMethodReference = null; public static int setPopulateMethod(Func<string, string> methodReference) { populateMethodReference = methodReference; return 0; } public static string populate(string key) { return populateMethodReference(key); } } } Using parent project class data in child Earlier the propertyCache was in parent class. Child needed to access it. So, the propertyCache has been moved to Child. Parent also reads and populates the same. Using parent project class method in child Pass the method reference to the child somehow (by some static method). use the reference to invoke that parent method. Output of the program Read from child: b Call from child: Populate method in parent: cc A: I have to say that Yannicks answer is the way to go there normally. In your special situation (as outlined in your comment to his answer) it sounds like that would be problematic. A different way would be (only possible if the mainclass compiles into a dll): Include the compiled dll of the mainproject in the child project Use the methods you need via reflection This is one possible other route BUT has quite a few pitfalls as reflection has troubles of its own. A: Assembly assembly = this.GetType().Assembly; // DefinedTypes will list all Userdefined class foreach (var typeInfo in assembly.DefinedTypes) { // typeInfo.FullName }
C# Accessing a class from a "parent project" in a "child project"?
Let's say I have multiple projects within a solution. I have the main project parent_project and another project child_project. How can I access classes / namespaces residing in parent_project from child_project ? I have already added a Reference to child_project in parent_project so I can't add a Reference to parent_parent in child_project as it would create a circular dependency. Is this possible?
[ "If you're sharing logic between projects, you need to isolate that dependency and move it to a shared location (new project for example), restructure your dependencies so that your core logic lives in a core domain-like project or mash your projects together.\nThe latter is not really the cleanest of solutions. I would recommend thinking about your own question and really try to answer \"Why do I NEED a circular reference? How can I restructure so that my dependencies make sense?\".\n", "You can inject your dependency using an interface defined in the child project (this can be useful where major refactoring is not possible/too expensive).\ne.g. In the child project:\ninterface IA {\n DoLogicInB();\n}\n\nIn the parent project:\nclass ConcreteA : ChildProject.IA\n{\n DoLogicInB() { ... }\n}\n\nIn the child project, where you need the logic:\nclass ChildB {\n void DoSomethingWithParent(IA logicEngine) {\n logicEngine.DoLogicInB();\n }\n}\n\nYou need to then be able to inject a concrete implementation of the parent object from outside the child project.\n", "FYI\nI ended up just copying the logic to a shared location, and \"child\" projects can access this version. I know from a maintainability point of view this isn't the best solution but it seemed like the best compromise..\n", "I didn't require entire namespace, but just reading some data dictionary or calling one particular method from parent project class. Here is how we got it working.\nusing System;\nusing NUnit.Framework;\nusing System.Collections.Concurrent;\n\nnamespace MyProject.tests\n{\n public class ParentChildTest\n {\n [Test]\n public void dataAndMethodTest()\n {\n // add the data in parent project\n Parent.propertyCache[\"a\"] = \"b\";\n\n // read the data in child project\n Console.WriteLine(\"Read from child: \" + Child.getProperty(\"a\"));\n\n // use Child project to call method of parent project\n Console.WriteLine(\"Call from child: Populate method in parent: \" + Child.populate(\"c\"));\n }\n }\n\n class Parent\n {\n // data is in Child project. Parent project just has the reference.\n public static ConcurrentDictionary<string, string> propertyCache = Child.getPropertyCache();\n\n public static string populate(string key)\n {\n //calculation\n string value = key + key;\n propertyCache[key] = value;\n return value;\n }\n\n // Pass the parent project method reference to child project\n public static int dummy = Child.setPopulateMethod(populate);\n }\n\n class Child\n {\n // data store\n static ConcurrentDictionary<string, string> propertyCache = new ConcurrentDictionary<string, string>();\n\n public static ConcurrentDictionary<string, string> getPropertyCache()\n {\n return propertyCache;\n }\n\n public static string getProperty(string key)\n {\n if (propertyCache.ContainsKey(key))\n {\n return propertyCache[key];\n }\n return null;\n }\n\n // reference to parent project method\n static Func<string, string> populateMethodReference = null;\n\n public static int setPopulateMethod(Func<string, string> methodReference)\n {\n populateMethodReference = methodReference;\n return 0;\n }\n\n public static string populate(string key)\n {\n return populateMethodReference(key);\n }\n }\n}\n\nUsing parent project class data in child\n\nEarlier the propertyCache was in parent class. Child needed to access it.\nSo, the propertyCache has been moved to Child. Parent also reads and populates the same.\n\nUsing parent project class method in child\n\nPass the method reference to the child somehow (by some static method).\nuse the reference to invoke that parent method.\n\nOutput of the program\nRead from child: b\nCall from child: Populate method in parent: cc\n\n", "I have to say that Yannicks answer is the way to go there normally. In your special situation (as outlined in your comment to his answer) it sounds like that would be problematic. A different way would be (only possible if the mainclass compiles into a dll):\n\nInclude the compiled dll of the mainproject in the child project\nUse the methods you need via reflection \n\nThis is one possible other route BUT has quite a few pitfalls as reflection has troubles of its own.\n", "Assembly assembly = this.GetType().Assembly;\n\n// DefinedTypes will list all Userdefined class\nforeach (var typeInfo in assembly.DefinedTypes) \n{\n // typeInfo.FullName\n}\n\n" ]
[ 10, 2, 1, 1, 0, 0 ]
[]
[]
[ "c#", "namespaces" ]
stackoverflow_0028427696_c#_namespaces.txt
Q: code signature in (/xxxxx) not valid for use in process using Library Validation I'm trying to build proxychains with xcode 8. When I run a program I got: /usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib: code signing blocked mmap() of '/usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib' When I signed the program and library: codesign -s "Mac Developer: xxxx" `which proxychains` codesign -s "Mac Developer: xxxx" /usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib No errors, but when I run it again, it says /usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib: code signature in (/usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib) not valid for use in process using Library Validation: mapping process is a platform binary, but mapped file is not What should I do now? Do I need some sort of entitlements? A: I think that you will need to build it with Xcode version 7.x. So, try to uninstall it with brew uninstall proxychains-ng (if using homebrew). Then you will need to select Xcode version 7 with xcode-select and finish by re-installing proxychains with brew install proxychains-ng. I hope this helps! A: It looks like the problem is that you are trying to run a library that is not signed properly. In order to fix this, you will need to sign the library with a valid code signing certificate. To do this, you can use the codesign command-line tool. This tool allows you to sign a binary with a valid code signing certificate. Here is an example of how you can use it to sign the libproxychains4.dylib library: codesign -s "Mac Developer: xxxx" /usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib This command will sign the library with the code signing certificate that is associated with the "Mac Developer: xxxx" identity. You will need to replace "xxxx" with the name of your code signing certificate. Once you have signed the library with a valid code signing certificate, you should be able to run the program without any errors. You may also need to set the DYLD_INSERT_LIBRARIES environment variable to point to the signed library. This will tell the program to use the signed version of the library instead of the unsigned version. export DYLD_INSERT_LIBRARIES=/usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib You can then run the program as usual, and it should use the signed version of the library.
code signature in (/xxxxx) not valid for use in process using Library Validation
I'm trying to build proxychains with xcode 8. When I run a program I got: /usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib: code signing blocked mmap() of '/usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib' When I signed the program and library: codesign -s "Mac Developer: xxxx" `which proxychains` codesign -s "Mac Developer: xxxx" /usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib No errors, but when I run it again, it says /usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib: code signature in (/usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib) not valid for use in process using Library Validation: mapping process is a platform binary, but mapped file is not What should I do now? Do I need some sort of entitlements?
[ "I think that you will need to build it with Xcode version 7.x. So, try to uninstall it with brew uninstall proxychains-ng (if using homebrew). Then you will need to select Xcode version 7 with xcode-select and finish by re-installing proxychains with brew install proxychains-ng. I hope this helps!\n", "It looks like the problem is that you are trying to run a library that is not signed properly. In order to fix this, you will need to sign the library with a valid code signing certificate.\nTo do this, you can use the codesign command-line tool. This tool allows you to sign a binary with a valid code signing certificate.\nHere is an example of how you can use it to sign the libproxychains4.dylib library:\ncodesign -s \"Mac Developer: xxxx\" /usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib\n\nThis command will sign the library with the code signing certificate that is associated with the \"Mac Developer: xxxx\" identity. You will need to replace \"xxxx\" with the name of your code signing certificate.\nOnce you have signed the library with a valid code signing certificate, you should be able to run the program without any errors. You may also need to set the DYLD_INSERT_LIBRARIES environment variable to point to the signed library. This will tell the program to use the signed version of the library instead of the unsigned version.\nexport DYLD_INSERT_LIBRARIES=/usr/local/homebrew/Cellar/proxychains-ng/4.11/lib/libproxychains4.dylib\n\nYou can then run the program as usual, and it should use the signed version of the library.\n" ]
[ 0, 0 ]
[]
[]
[ "codesign", "macos", "validation" ]
stackoverflow_0039682285_codesign_macos_validation.txt
Q: Reactstrap: Prevent closing drop down menu when an item is selected One DropdownItem contains a search Input so when the user clicks on it, I need the drop down menu to remain open so that he types what he needs to search: import React, { Component } from "react"; import { connect } from "react-redux"; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem, } from "reactstrap"; import SearchBar from "./SearchBar"; export class AddToCollectionButton extends Component { constructor(props) { super(props); this.state = { dropdownOpen: false, }; this.toggle = this.toggle.bind(this); } toggle() { this.setState({ dropdownOpen: !this.state.dropdownOpen }); } render() { return ( <Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggle} // color="default" className="div-inline float-right ml-1" direction="left" > <DropdownToggle tag="span" onClick={this.toggle} data-toggle="dropdown" aria-expanded={this.state.dropdownOpen} color="danger" > <span className="badge badge-danger cursor-pointer-no-color"> <i class="fa fa-plus" aria-hidden="true" />{" "} </span> </DropdownToggle> <DropdownMenu className="dropdown-danger scrollable-drop-down-menu"> <DropdownItem onClick={(e) => { // e.preventDefault(); // e.stopPropagation(); // this.setState({ // dropdownOpen: true, // }); }} > <SearchBar /> </DropdownItem> </DropdownMenu> </Dropdown> ); } } const mapStateToProps = (state) => ({}); const mapDispatchToProps = {}; export default connect( mapStateToProps, mapDispatchToProps )(AddToCollectionButton); I tried different things as you can see inside the onClick and other things mentioned on similar questions on SO but nothing worked. A: Not sure if this there's an option in reactstrap, or if you can use React Bootstrap. You can add autoClose={false} in your Dropdown and it will only be closed when clicked again in the Dropdown icon. A: The DropdownItem has a boolean prop "toggle" which defaults to true. If set to false, the menu stays open after selecting an element. <DropdownItem toggle={false} > <SearchBar /> </DropdownItem> Documentation: https://6-4-0--reactstrap.netlify.app/components/dropdowns/ A: You can try adding stopPropagation on the click of <SearchBar /> elements input or div. This should prevent the click event from getting triggered on parent elements on click of the <SearchBar /> elements.
Reactstrap: Prevent closing drop down menu when an item is selected
One DropdownItem contains a search Input so when the user clicks on it, I need the drop down menu to remain open so that he types what he needs to search: import React, { Component } from "react"; import { connect } from "react-redux"; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem, } from "reactstrap"; import SearchBar from "./SearchBar"; export class AddToCollectionButton extends Component { constructor(props) { super(props); this.state = { dropdownOpen: false, }; this.toggle = this.toggle.bind(this); } toggle() { this.setState({ dropdownOpen: !this.state.dropdownOpen }); } render() { return ( <Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggle} // color="default" className="div-inline float-right ml-1" direction="left" > <DropdownToggle tag="span" onClick={this.toggle} data-toggle="dropdown" aria-expanded={this.state.dropdownOpen} color="danger" > <span className="badge badge-danger cursor-pointer-no-color"> <i class="fa fa-plus" aria-hidden="true" />{" "} </span> </DropdownToggle> <DropdownMenu className="dropdown-danger scrollable-drop-down-menu"> <DropdownItem onClick={(e) => { // e.preventDefault(); // e.stopPropagation(); // this.setState({ // dropdownOpen: true, // }); }} > <SearchBar /> </DropdownItem> </DropdownMenu> </Dropdown> ); } } const mapStateToProps = (state) => ({}); const mapDispatchToProps = {}; export default connect( mapStateToProps, mapDispatchToProps )(AddToCollectionButton); I tried different things as you can see inside the onClick and other things mentioned on similar questions on SO but nothing worked.
[ "Not sure if this there's an option in reactstrap, or if you can use React Bootstrap.\nYou can add autoClose={false} in your Dropdown and it will only be closed when clicked again in the Dropdown icon.\n", "The DropdownItem has a boolean prop \"toggle\" which defaults to true. If set to false, the menu stays open after selecting an element.\n<DropdownItem toggle={false} >\n <SearchBar />\n</DropdownItem>\n\nDocumentation: https://6-4-0--reactstrap.netlify.app/components/dropdowns/\n", "You can try adding stopPropagation on the click of <SearchBar /> elements input or div. This should prevent the click event from getting triggered on parent elements on click of the <SearchBar /> elements.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "bootstrap_4", "drop_down_menu", "reactjs", "reactstrap" ]
stackoverflow_0074485968_bootstrap_4_drop_down_menu_reactjs_reactstrap.txt
Q: How to extract all text's link and other properties form html? Note, if it is single element I can extract but I need to extract all of them together. Hi I am trying to extract the text and link from a list of items from a page using Selenium and Java. I am able to extract all link text but facing issue to figure out the link text. The html code looks like below: <div class="col-12"> <a href="/category/agricultural-products-service"> <img src="/assets/images/icon/1.jpg" alt="icon" class="img-fluid category_icon"> <h5 class="category_title">Agricultural </h5> </a> </div> <div class="col-12"> <a href="/category/products-service"> <img src="/assets/images/icon/7.jpg" alt="icon" class="img-fluid category_icon"> <h5 class="category_title">Products</h5> </a> </div> Using h5 I can extract all the elements but I need to extract all href of those elements A: To extract text or link or any other attribute value from several web elements you need to collect all these elements in a list and then to iterate over the list extracting the desired value from each web element object. As following: List<WebElement> elements = driver.findElements(By.tagName("h5")); for(WebElement element : elements){ String value = element.getText(); System.out.println(value); } This will give you all the links there List<WebElement> links = driver.findElements(By.cssSelector(".top_cat a")); for(WebElement link : links){ String value = link.getAttribute("href"); System.out.println(value); } On this specific page the structure is: There are several blocks defined by class="col-12 col-sm-6 col-md-4 border all_cat" elements. Inside each such block several links and titles. Each a is below the class="col-12 col-sm-6 col-md-4 border all_cat" element and the title is below it a element. So, extracting the links and titles here can be done as following: List<WebElement> blocks = driver.findElements(By.cssSelector(".all_cat")); for(WebElement block : blocks){ List<WebElement> links = block.findElements(By.xpath(".//a")); for(WebElement link : links){ String linkValue = link.getAttribute("href"); System.out.println("The link is " + linkValue); WebElement title = block.findElements(By.xpath(".//h5")); String titleValue = title.getText(); System.out.println("The title is " + titleValue); } } A: So, here is my final solution what I was trying to do: List<WebElement> blocks = driver.findElements(By.cssSelector(".all_cat")); for (WebElement block : blocks) { WebElement link = block.findElement(By.xpath(".//a")); String linkValue = link.getAttribute("href"); System.out.println(linkValue); WebElement title = block.findElement(By.xpath(".//h5")); String titleValue = title.getText(); System.out.println(titleValue); }
How to extract all text's link and other properties form html?
Note, if it is single element I can extract but I need to extract all of them together. Hi I am trying to extract the text and link from a list of items from a page using Selenium and Java. I am able to extract all link text but facing issue to figure out the link text. The html code looks like below: <div class="col-12"> <a href="/category/agricultural-products-service"> <img src="/assets/images/icon/1.jpg" alt="icon" class="img-fluid category_icon"> <h5 class="category_title">Agricultural </h5> </a> </div> <div class="col-12"> <a href="/category/products-service"> <img src="/assets/images/icon/7.jpg" alt="icon" class="img-fluid category_icon"> <h5 class="category_title">Products</h5> </a> </div> Using h5 I can extract all the elements but I need to extract all href of those elements
[ "To extract text or link or any other attribute value from several web elements you need to collect all these elements in a list and then to iterate over the list extracting the desired value from each web element object.\nAs following:\nList<WebElement> elements = driver.findElements(By.tagName(\"h5\"));\nfor(WebElement element : elements){\n String value = element.getText();\n System.out.println(value);\n}\n\nThis will give you all the links there\nList<WebElement> links = driver.findElements(By.cssSelector(\".top_cat a\"));\nfor(WebElement link : links){\n String value = link.getAttribute(\"href\");\n System.out.println(value);\n}\n\nOn this specific page the structure is:\nThere are several blocks defined by class=\"col-12 col-sm-6 col-md-4 border all_cat\" elements. Inside each such block several links and titles. Each a is below the class=\"col-12 col-sm-6 col-md-4 border all_cat\" element and the title is below it a element. So, extracting the links and titles here can be done as following:\nList<WebElement> blocks = driver.findElements(By.cssSelector(\".all_cat\"));\nfor(WebElement block : blocks){\n List<WebElement> links = block.findElements(By.xpath(\".//a\"));\n for(WebElement link : links){\n String linkValue = link.getAttribute(\"href\");\n System.out.println(\"The link is \" + linkValue);\n WebElement title = block.findElements(By.xpath(\".//h5\"));\n String titleValue = title.getText();\n System.out.println(\"The title is \" + titleValue);\n }\n}\n\n", "So, here is my final solution what I was trying to do:\nList<WebElement> blocks = driver.findElements(By.cssSelector(\".all_cat\"));\nfor (WebElement block : blocks) {\n WebElement link = block.findElement(By.xpath(\".//a\"));\n String linkValue = link.getAttribute(\"href\");\n System.out.println(linkValue);\n \n WebElement title = block.findElement(By.xpath(\".//h5\"));\n String titleValue = title.getText();\n System.out.println(titleValue);\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "java", "list", "selenium", "selenium_webdriver" ]
stackoverflow_0074668617_java_list_selenium_selenium_webdriver.txt
Q: Cloud SQL Postgres TypeOrm config issue I'm using Nest.js deployed Google cloud app engine and Cloud SQL postgres typeorm Here is my config file { "type":"postgres", "extra":{"socketPath":"/cloudsql/xxx:us-central1:xxx"}, "username":"xxx", "password":"xxx", "database":"xxx", "synchronize":false,"logging":false, "entities":["dist/**/*.entity{ .ts,.js}"], "migrations":["/workspace/dist/src/db/migrations/*.js"], "migrationsTableName":"migrations_typeorm", "migrationsRun":false, "cli":{"migrationsDir":"src/db/migrations"} } But app engine ignores socketPath and automatically use DEFAULT host and port 127.0.0.1:5432 What is wrong with my config options? A: When running the project locally, everything is okay but when deployed to the cloud it's not working. The reason is that locally you don't need "host" property but cloud server needs "host" property which should be the same socketPath ("/cloudsql/xxx:us-central1:xxx"). So when you are on localhost then remove "host" property. When deploying to server attach "host" property.
Cloud SQL Postgres TypeOrm config issue
I'm using Nest.js deployed Google cloud app engine and Cloud SQL postgres typeorm Here is my config file { "type":"postgres", "extra":{"socketPath":"/cloudsql/xxx:us-central1:xxx"}, "username":"xxx", "password":"xxx", "database":"xxx", "synchronize":false,"logging":false, "entities":["dist/**/*.entity{ .ts,.js}"], "migrations":["/workspace/dist/src/db/migrations/*.js"], "migrationsTableName":"migrations_typeorm", "migrationsRun":false, "cli":{"migrationsDir":"src/db/migrations"} } But app engine ignores socketPath and automatically use DEFAULT host and port 127.0.0.1:5432 What is wrong with my config options?
[ "When running the project locally, everything is okay but when deployed to the cloud it's not working. The reason is that locally you don't need \"host\" property but cloud server needs \"host\" property which should be the same socketPath (\"/cloudsql/xxx:us-central1:xxx\").\nSo when you are on localhost then remove \"host\" property.\nWhen deploying to server attach \"host\" property.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "google_cloud_sql", "nestjs", "postgresql", "typeorm" ]
stackoverflow_0074606883_google_app_engine_google_cloud_sql_nestjs_postgresql_typeorm.txt
Q: `CREATE ALGORITHM=UNDEFINED DEFINER` requires super permissions I am trying to import one of my old databases to my new database. To do this I created a user with the same privileges as before: Almost every command seems to work except the following: CREATE ALGORITHM=UNDEFINED DEFINER=`foo`@`localhost` SQL SECURITY DEFINER VIEW `wp_affiliate_wp_campaigns` AS select `wp_affiliate_wp_visits`.`affiliate_id` AS `affiliate_id`,`wp_affiliate_wp_visits`.`campaign` AS `campaign`,count(`wp_affiliate_wp_visits`.`url`) AS `visits`,count(distinct `wp_affiliate_wp_visits`.`url`) AS `unique_visits`,sum(if((`wp_affiliate_wp_visits`.`referral_id` <> 0),1,0)) AS `referrals`,round(((sum(if((`wp_affiliate_wp_visits`.`referral_id` <> 0),1,0)) / count(`wp_affiliate_wp_visits`.`url`)) * 100),2) AS `conversion_rate` from `wp_affiliate_wp_visits` group by `wp_affiliate_wp_visits`.`affiliate_id`,`wp_affiliate_wp_visits`.`campaign`; Which gave me the following error: Error Code: 1227. Access denied; you need (at least one of) the SUPER privilege(s) for this operation This is odd as this table was created with the a user with the same permissions as my old database (i.e. all permissions for table foo). So my question is: What exactly does this command do? Why do I suddenly need super permission to execute it when my old database never did? A: I ran into this identical problem. What worked for me was to take off the: ALGORITHM=UNDEFINED DEFINER=`foo`@`localhost` SQL SECURITY DEFINER You would then just have: CREATE VIEW `wp_affiliate_wp_campaigns'... Worked like a charm. Best of luck! A: Simply try this CREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER
`CREATE ALGORITHM=UNDEFINED DEFINER` requires super permissions
I am trying to import one of my old databases to my new database. To do this I created a user with the same privileges as before: Almost every command seems to work except the following: CREATE ALGORITHM=UNDEFINED DEFINER=`foo`@`localhost` SQL SECURITY DEFINER VIEW `wp_affiliate_wp_campaigns` AS select `wp_affiliate_wp_visits`.`affiliate_id` AS `affiliate_id`,`wp_affiliate_wp_visits`.`campaign` AS `campaign`,count(`wp_affiliate_wp_visits`.`url`) AS `visits`,count(distinct `wp_affiliate_wp_visits`.`url`) AS `unique_visits`,sum(if((`wp_affiliate_wp_visits`.`referral_id` <> 0),1,0)) AS `referrals`,round(((sum(if((`wp_affiliate_wp_visits`.`referral_id` <> 0),1,0)) / count(`wp_affiliate_wp_visits`.`url`)) * 100),2) AS `conversion_rate` from `wp_affiliate_wp_visits` group by `wp_affiliate_wp_visits`.`affiliate_id`,`wp_affiliate_wp_visits`.`campaign`; Which gave me the following error: Error Code: 1227. Access denied; you need (at least one of) the SUPER privilege(s) for this operation This is odd as this table was created with the a user with the same permissions as my old database (i.e. all permissions for table foo). So my question is: What exactly does this command do? Why do I suddenly need super permission to execute it when my old database never did?
[ "I ran into this identical problem. What worked for me was to take off the:\n ALGORITHM=UNDEFINED DEFINER=`foo`@`localhost` SQL SECURITY DEFINER\n\nYou would then just have:\n CREATE VIEW `wp_affiliate_wp_campaigns'...\n\nWorked like a charm. Best of luck!\n", "Simply try this\nCREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER\n\n" ]
[ 8, 0 ]
[]
[]
[ "mysql" ]
stackoverflow_0047617866_mysql.txt
Q: Joblib UserWarning while trying to cache results I get the following UserWarning when trying to cache results using joblib: import numpy from tempfile import mkdtemp cachedir = mkdtemp() from joblib import Memory memory = Memory(cachedir=cachedir, verbose=0) @memory.cache def get_nc_var3d(path_nc, var, year): """ Get value from netcdf for variable var for year :param path_nc: :param var: :param year: :return: """ try: hndl_nc = open_or_die(path_nc) val = hndl_nc.variables[var][int(year), :, :] except: val = numpy.nan logger.info('Error in getting var ' + var + ' for year ' + str(year) + ' from netcdf ') hndl_nc.close() return val I get the following warning when calling this function using parameters: UserWarning: Persisting input arguments took 0.58s to run. If this happens often in your code, it can cause performance problems (results will be correct in all cases). The reason for this is probably some large input arguments for a wrapped function (e.g. large strings). THIS IS A JOBLIB ISSUE. If you can, kindly provide the joblib's team with an example so that they can fix the problem. Input parameters: C:/Users/rit/Documents/PhD/Projects/\GLA/Input/LUWH/\LUWLAN_v1.0h\transit_model.nc range_to_large 1150 How do I get rid of the warning? And why is it happening, since the input parameters are not too long? A: I don't have an answer to the "why doesn't this work?" portion of the question. However to simply ignore the warning you can use warnings.catch_warnings with warnings.simplefilter as seen here. import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") your_code() Obviously, I don't recommend ignoring the warning unless you're sure its harmless, but if you're going to do it this way will only suppress warnings inside the context manager and is straight out of the python docs A: UserWarning: Persisting input arguments took 0.58s to run. If this happens often in your code, it can cause performance problems (results will be correct in all cases). The reason for this is probably some large input arguments for a wrapped function (e.g. large strings). THIS IS A JOBLIB ISSUE. If you can, kindly provide the joblib's team with an example so that they can fix the problem. the warning itself is self explanatory in my humble opinion. it might be in your code issue you can try to decrease the input size,or you can share your report with joblib team so that they can either help to improve joblib or suggest your better approach of usage to avoid this type of performance warnings. A: This warning is generated by joblib when it takes a long time to store the input arguments of a function in its cache. In some cases, this can cause performance issues and should be avoided if possible. To avoid this warning, you can try to minimize the size of the input arguments to the function by passing only the necessary information. For example, instead of passing the entire path to the netcdf file as a string, you could pass only the filename and use that to construct the full path inside the function. Alternatively, you can disable the warning by setting the verbose argument of the Memory object to 0: memory = Memory(cachedir=cachedir, verbose=0) This will prevent joblib from printing the warning, but it will not fix the underlying performance issue. It's generally a good idea to try to minimize the size of the input arguments to avoid this warning.
Joblib UserWarning while trying to cache results
I get the following UserWarning when trying to cache results using joblib: import numpy from tempfile import mkdtemp cachedir = mkdtemp() from joblib import Memory memory = Memory(cachedir=cachedir, verbose=0) @memory.cache def get_nc_var3d(path_nc, var, year): """ Get value from netcdf for variable var for year :param path_nc: :param var: :param year: :return: """ try: hndl_nc = open_or_die(path_nc) val = hndl_nc.variables[var][int(year), :, :] except: val = numpy.nan logger.info('Error in getting var ' + var + ' for year ' + str(year) + ' from netcdf ') hndl_nc.close() return val I get the following warning when calling this function using parameters: UserWarning: Persisting input arguments took 0.58s to run. If this happens often in your code, it can cause performance problems (results will be correct in all cases). The reason for this is probably some large input arguments for a wrapped function (e.g. large strings). THIS IS A JOBLIB ISSUE. If you can, kindly provide the joblib's team with an example so that they can fix the problem. Input parameters: C:/Users/rit/Documents/PhD/Projects/\GLA/Input/LUWH/\LUWLAN_v1.0h\transit_model.nc range_to_large 1150 How do I get rid of the warning? And why is it happening, since the input parameters are not too long?
[ "I don't have an answer to the \"why doesn't this work?\" portion of the question. However to simply ignore the warning you can use warnings.catch_warnings with warnings.simplefilter as seen here.\nimport warnings\n\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n your_code()\n\n\nObviously, I don't recommend ignoring the warning unless you're sure its harmless, but if you're going to do it this way will only suppress warnings inside the context manager and is straight out of the python docs\n", "UserWarning: Persisting input arguments took 0.58s to run.\nIf this happens often in your code, it can cause performance problems\n(results will be correct in all cases).\nThe reason for this is probably some large input arguments for a wrapped function (e.g. large strings).\nTHIS IS A JOBLIB ISSUE. If you can, kindly provide the joblib's team with an example so that they can fix the problem.\nthe warning itself is self explanatory in my humble opinion. it might be in your code issue you can try to decrease the input size,or you can share your report with joblib team so that they can either help to improve joblib or suggest your better approach of usage to avoid this type of performance warnings.\n", "This warning is generated by joblib when it takes a long time to store the input arguments of a function in its cache. In some cases, this can cause performance issues and should be avoided if possible.\nTo avoid this warning, you can try to minimize the size of the input arguments to the function by passing only the necessary information.\nFor example, instead of passing the entire path to the netcdf file as a string, you could pass only the filename and use that to construct the full path inside the function.\nAlternatively, you can disable the warning by setting the verbose argument of the Memory object to 0:\nmemory = Memory(cachedir=cachedir, verbose=0)\n\nThis will prevent joblib from printing the warning, but it will not fix the underlying performance issue. It's generally a good idea to try to minimize the size of the input arguments to avoid this warning.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "joblib", "netcdf", "numpy", "python" ]
stackoverflow_0037129754_joblib_netcdf_numpy_python.txt
Q: How to make a correct POST request with Retrofit in Kotlin? I would like to post this json: { "user": { "name": "Mike", "age": "26", } } but when I use this method @Headers("Content-Type: application/json") @POST("users") suspend fun postUser(@Body user: User) I send this json to the server: { "name": "Mike", "age": "26", } How to include the key user in the body of my request? A: //1. Create an interface with the appropriate annotations: interface ApiService { @POST("path/to/endpoint") fun postRequest(@Body body: Map<String, Any>): Call<ResponseBody> } //2. Create an instance of Retrofit: val retrofit = Retrofit.Builder() .baseUrl("base_url") .addConverterFactory(GsonConverterFactory.create()) .build() //3. Create an instance of the interface: val apiService = retrofit.create(ApiService::class.java) //4. Create the request body: val body = mapOf( "key1" to "value1", "key2" to "value2" ) //5. Make the request: apiService.postRequest(body).enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { // handle the response } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { // handle the failure } })
How to make a correct POST request with Retrofit in Kotlin?
I would like to post this json: { "user": { "name": "Mike", "age": "26", } } but when I use this method @Headers("Content-Type: application/json") @POST("users") suspend fun postUser(@Body user: User) I send this json to the server: { "name": "Mike", "age": "26", } How to include the key user in the body of my request?
[ "//1. Create an interface with the appropriate annotations:\n\ninterface ApiService {\n @POST(\"path/to/endpoint\")\n fun postRequest(@Body body: Map<String, Any>): Call<ResponseBody>\n}\n\n//2. Create an instance of Retrofit:\n\nval retrofit = Retrofit.Builder()\n .baseUrl(\"base_url\")\n .addConverterFactory(GsonConverterFactory.create())\n .build()\n\n//3. Create an instance of the interface:\n\nval apiService = retrofit.create(ApiService::class.java)\n\n//4. Create the request body:\n\nval body = mapOf(\n \"key1\" to \"value1\",\n \"key2\" to \"value2\"\n)\n\n//5. Make the request:\n\napiService.postRequest(body).enqueue(object : Callback<ResponseBody> {\n override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {\n // handle the response\n }\n\n override fun onFailure(call: Call<ResponseBody>, t: Throwable) {\n // handle the failure\n }\n})\n\n" ]
[ 1 ]
[]
[]
[ "android", "kotlin", "rest", "retrofit" ]
stackoverflow_0074670362_android_kotlin_rest_retrofit.txt
Q: In there a markdown syntax similar to Β­? I'm looking for a similar markdown syntax to &shy; in HTML. I know there are hard breaks in markdown, but I'm looking for something that acts like &shy; or similar. A: In HTML, the &shy; character is used to create a soft hyphen, which is a character that is not visible unless it is at the end of a line and the word is too long to fit on the line. In markdown, there is no equivalent character or syntax for creating a soft hyphen. However, you can achieve a similar effect in markdown by using the &nbsp; character, which stands for "non-breaking space." This character will insert a space in your text that will not break onto a new line, even if the line is too long to fit on the page. To use the &nbsp; character in markdown, you simply need to include it in your text where you want the non-breaking space to appear. For example, if you want to insert a non-breaking space between the words "hello" and "world," you would write the following: hello&nbsp;world This will prevent the line from breaking between the two words, even if it would otherwise be too long to fit on the page. A: Most Markdown processors can process any HTML entity, including &shy;. So you can use that. Demo using babelmark3 An alternative is to insert the SOFT HYPHEN (U+00AD) Unicode character directly. However, the feasibility of this depends on how easy your OS and/or editor makes entering arbitrary Unicode characters.
In there a markdown syntax similar to Β­?
I'm looking for a similar markdown syntax to &shy; in HTML. I know there are hard breaks in markdown, but I'm looking for something that acts like &shy; or similar.
[ "In HTML, the &shy; character is used to create a soft hyphen, which is a character that is not visible unless it is at the end of a line and the word is too long to fit on the line. In markdown, there is no equivalent character or syntax for creating a soft hyphen.\nHowever, you can achieve a similar effect in markdown by using the &nbsp; character, which stands for \"non-breaking space.\" This character will insert a space in your text that will not break onto a new line, even if the line is too long to fit on the page.\nTo use the &nbsp; character in markdown, you simply need to include it in your text where you want the non-breaking space to appear. For example, if you want to insert a non-breaking space between the words \"hello\" and \"world,\" you would write the following:\nhello&nbsp;world\n\nThis will prevent the line from breaking between the two words, even if it would otherwise be too long to fit on the page.\n", "Most Markdown processors can process any HTML entity, including &shy;. So you can use that.\nDemo using babelmark3\nAn alternative is to insert the SOFT HYPHEN (U+00AD) Unicode character directly. However, the feasibility of this depends on how easy your OS and/or editor makes entering arbitrary Unicode characters.\n" ]
[ 1, 0 ]
[]
[]
[ "html", "markdown", "syntax" ]
stackoverflow_0074663202_html_markdown_syntax.txt
Q: How to remove images and just place colors in place of the images Instead of images, I want to place colors in those spots. https://jsfiddle.net/rza8v51x/ The images are set in a grid layout, and I want to remove them and add colors. In place of the images I want to add colors in those spots. That is all I am trying to do in the code. Replace the images with colors. How would this be done? .channel-browser__channels { border-top: 1px solid rgba(86,95,115,0.5); padding-top: 14px; margin-top: 24px; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item{ padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; background-color:red; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } .channel-browser__channels { border-top: 1px solid rgba(86,95,115,0.5); padding-top: 14px; margin-top: 24px; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item{ padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; background-color:red; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } <div class="channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> </div> A: This might get you on the right track, but your grid is a mess .channel-browser__channels { border-top: 1px solid rgba(86, 95, 115, 0.5); padding-top: 14px; margin-top: 24px; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .horizontal-content-browser__content-item { padding-top: 100%; } .content-item--channel { height: 280px; } .responsive-image-component { position: relative; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; background-color: red; } .content-item--channel::after { content: ''; display: block; position: absolute; bottom: 20px; width: 100%; aspect-ratio: 1; background-color: black; } <div class="channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> </div> A: Delete the entire img tag in between the div tags, and either add a class as I did in the div tags "box-color-red" or what ever you desire to call the class, and style the background: toWhateverColorYouWant; || OR you can delete the text inside the div class and just create your own if you do not need all of those classes that are declared inside of your div classes. Otherwise, keep them, and appropriately name a new class that will style the color of the div, and make sure the spacing inside the class name is space correctly as well. .channel-browser__channels { border-top: 1px solid rgba(86,95,115,0.5); padding-top: 14px; margin-top: 24px; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item{ padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; background-color:red; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } .box-color-red { background: red; } .box-color-blue { background: blue; } .box-color-yellow { background: yellow; } .box-color-green { background: green; } <div class="channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-red"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-blue"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-yellow"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-green"> </div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> </div> A: Perhaps a quick solution to add a overlay color for the images without changing the HTML code would be adding a ::after to the grid item. /* Added this */ .channel-browser__channel-grid-item::after { content: ""; position: absolute; inset: 0; /* Edit color here */ background-color: pink; } Further control can be added with this implement to perhaps toggle display between the overlay color and image, depending on the use case. Example: /* Added this */ .channel-browser__channel-grid-item::after { content: ""; position: absolute; inset: 0; /* Edit color here */ background-color: pink; } .channel-browser__channels { border-top: 1px solid rgba(86,95,115,0.5); padding-top: 14px; margin-top: 24px; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item{ padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; background-color:red; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } <div class="channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> </div>
How to remove images and just place colors in place of the images
Instead of images, I want to place colors in those spots. https://jsfiddle.net/rza8v51x/ The images are set in a grid layout, and I want to remove them and add colors. In place of the images I want to add colors in those spots. That is all I am trying to do in the code. Replace the images with colors. How would this be done? .channel-browser__channels { border-top: 1px solid rgba(86,95,115,0.5); padding-top: 14px; margin-top: 24px; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item{ padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; background-color:red; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } .channel-browser__channels { border-top: 1px solid rgba(86,95,115,0.5); padding-top: 14px; margin-top: 24px; } .channel-browser__channel-grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } .channel-browser__channel-grid-item { position: relative; } .content-item-container--aspect-square .horizontal-content-browser__content-item{ padding-top: 100%; } .horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component { position: absolute; top: 0; left: 0; width: 100%; height: auto; border-radius: 4px; background-color: #1a1a1a; background-color:red; -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%); } <div class="channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square"> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> <div class="horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible"> <img width="280" height="280" src="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100" srcset="//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x" class="responsive-image-component"></div> </div>
[ "This might get you on the right track, but your grid is a mess\n\n\n.channel-browser__channels {\n border-top: 1px solid rgba(86, 95, 115, 0.5);\n padding-top: 14px;\n margin-top: 24px;\n}\n\n.channel-browser__channel-grid {\n display: grid;\n gap: 16px;\n grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));\n margin: 0;\n padding: 0;\n border: 0;\n font-size: 100%;\n font: inherit;\n vertical-align: baseline;\n}\n\n.channel-browser__channel-grid-item {\n position: relative;\n}\n\n.horizontal-content-browser__content-item {\n padding-top: 100%;\n}\n\n.content-item--channel {\n height: 280px;\n}\n\n.responsive-image-component {\n position: relative;\n top: 0;\n left: 0;\n width: 100%;\n height: auto;\n border-radius: 4px;\n background-color: #1a1a1a;\n background-color: red;\n}\n\n.content-item--channel::after {\n content: '';\n display: block;\n position: absolute;\n bottom: 20px;\n width: 100%;\n aspect-ratio: 1;\n background-color: black;\n}\n<div class=\"channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square\">\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\"\n class=\"responsive-image-component\"></div>\n\n</div>\n\n\n\n", "Delete the entire img tag in between the div tags, and either add a class as I did in the div tags \"box-color-red\" or what ever you desire to call the class, and style the background: toWhateverColorYouWant; || OR you can delete the text inside the div class and just create your own if you do not need all of those classes that are declared inside of your div classes. Otherwise, keep them, and appropriately name a new class that will style the color of the div, and make sure the spacing inside the class name is space correctly as well.\n\n\n.channel-browser__channels {\n border-top: 1px solid rgba(86,95,115,0.5);\n padding-top: 14px;\n margin-top: 24px;\n}\n\n.channel-browser__channel-grid {\n display: grid;\n gap: 16px;\n grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));\n margin: 0;\n padding: 0;\n border: 0;\n font-size: 100%;\n font: inherit;\n vertical-align: baseline;\n}\n.channel-browser__channel-grid-item {\n position: relative;\n}\n\n.content-item-container--aspect-square .horizontal-content-browser__content-item{\n padding-top: 100%;\n}\n\n.horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: auto;\n border-radius: 4px;\n background-color: #1a1a1a;\n background-color:red;\n -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n\n}\n\n.box-color-red {\n background: red;\n }\n \n.box-color-blue {\n background: blue;\n }\n .box-color-yellow {\n background: yellow;\n }\n .box-color-green {\n background: green;\n }\n<div class=\"channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square\">\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-red\">\n </div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-blue\">\n\n </div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-yellow\">\n\n </div>\n\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible box-color-green\">\n\n </div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n</div>\n\n\n\n", "Perhaps a quick solution to add a overlay color for the images without changing the HTML code would be adding a ::after to the grid item.\n/* Added this */\n.channel-browser__channel-grid-item::after {\n content: \"\";\n position: absolute;\n inset: 0;\n /* Edit color here */\n background-color: pink;\n}\n\nFurther control can be added with this implement to perhaps toggle display between the overlay color and image, depending on the use case.\nExample:\n\n\n /* Added this */\n .channel-browser__channel-grid-item::after {\n content: \"\"; \n position: absolute;\n inset: 0;\n /* Edit color here */\n background-color: pink;\n}\n\n.channel-browser__channels {\n border-top: 1px solid rgba(86,95,115,0.5);\n padding-top: 14px;\n margin-top: 24px;\n}\n\n.channel-browser__channel-grid {\n display: grid;\n gap: 16px;\n grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));\n margin: 0;\n padding: 0;\n border: 0;\n font-size: 100%;\n font: inherit;\n vertical-align: baseline;\n}\n.channel-browser__channel-grid-item {\n position: relative;\n}\n\n.content-item-container--aspect-square .horizontal-content-browser__content-item{\n padding-top: 100%;\n}\n\n.horizontal-content-browser__content-item .horizontal-content-browser__fallback-image, .horizontal-content-browser__content-item .responsive-image-component {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: auto;\n border-radius: 4px;\n background-color: #1a1a1a;\n background-color:red;\n -webkit-box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n box-shadow: 0 2px 3px 0 rgb(0 0 0 / 20%);\n\n}\n<div class=\"channel-browser__channels channel-browser__channel-grid content-item-container content-item-container--aspect-square\">\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n <div class=\"horizontal-content-browser__content-item content-item channel-browser__channel-grid-item content-item--channel visible\">\n\n <img width=\"280\" height=\"280\" src=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=280x280&amp;quality=100\" srcset=\"//cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=560x560&amp;quality=100 2x, //cdn-images.audioaddict.com/8/6/d/e/2/b/86de2baad6357243d57e77e71494624f.jpg?size=840x840&amp;quality=100 3x\" class=\"responsive-image-component\"></div>\n\n</div>\n\n\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074670252_css_html.txt
Q: Realloc a table of structures that has table in it I am trying to write a programe that will store data in a table of structures. My problem is that i can't figure out why my realloc isn't working. I am trying to realloc a table that is in a table of structures (sounds confusing, i know), but it won't work. Here is the part of my program i have a problem with: typedef struct { int *node; int l; }przejscie_t; void czytaj(przejscie_t **graf, int vp, int vk){ *graf=realloc(*graf,(vp+1)*sizeof(przejscie_t)); (*graf)[vp].l=1; (*graf)[vp].node=realloc((*graf)[vp].node,(*graf)[vp].l*sizeof(int)); //it crashes here (*graf)[vp].node[(*graf)[vp].l]=vk; } A: (*graf)[vp].node=realloc((*graf)[vp].node,(*graf)[vp].l*sizeof(int)); //it crashes here realloc needs a valid initialized pointer as first parameter (or NULL, in this case it stands as if malloc was called), since (*graf)[vp].node is not initialized you are passing garbage.
Realloc a table of structures that has table in it
I am trying to write a programe that will store data in a table of structures. My problem is that i can't figure out why my realloc isn't working. I am trying to realloc a table that is in a table of structures (sounds confusing, i know), but it won't work. Here is the part of my program i have a problem with: typedef struct { int *node; int l; }przejscie_t; void czytaj(przejscie_t **graf, int vp, int vk){ *graf=realloc(*graf,(vp+1)*sizeof(przejscie_t)); (*graf)[vp].l=1; (*graf)[vp].node=realloc((*graf)[vp].node,(*graf)[vp].l*sizeof(int)); //it crashes here (*graf)[vp].node[(*graf)[vp].l]=vk; }
[ "(*graf)[vp].node=realloc((*graf)[vp].node,(*graf)[vp].l*sizeof(int)); //it crashes here\n\nrealloc needs a valid initialized pointer as first parameter (or NULL, in this case it stands as if malloc was called), since (*graf)[vp].node is not initialized you are passing garbage.\n" ]
[ 3 ]
[]
[]
[ "c", "realloc", "structure" ]
stackoverflow_0074670364_c_realloc_structure.txt
Q: Laravel: Uploaded image not showing i keep getting 404 image not found when viewing the uploaded image on my project but the image is there. im using laravel's asset() helper to retrieve the image. the url in chrome shows http://127.0.0.1:8000/images/dU8oaVTAwQyTor86jvDtdGKvE7H3MYkHZuUG60gH.png and ive already done php artisan storage:link. any help is greatly appreciated. A: You shouldn't use the asset helper for this, the url generated is wrong. As you use the public storage, the url is supposed to be like this : http://127.0.0.1:8000/storage/images/dU8oaVTAwQyTor86jvDtdGKvE7H3MYkHZuUG60gH.png A: but aren't you supposed to access the image through the public folder if you do php artisan storage:link
Laravel: Uploaded image not showing
i keep getting 404 image not found when viewing the uploaded image on my project but the image is there. im using laravel's asset() helper to retrieve the image. the url in chrome shows http://127.0.0.1:8000/images/dU8oaVTAwQyTor86jvDtdGKvE7H3MYkHZuUG60gH.png and ive already done php artisan storage:link. any help is greatly appreciated.
[ "You shouldn't use the asset helper for this, the url generated is wrong.\nAs you use the public storage, the url is supposed to be like this :\nhttp://127.0.0.1:8000/storage/images/dU8oaVTAwQyTor86jvDtdGKvE7H3MYkHZuUG60gH.png\n\n", "but aren't you supposed to access the image through the public folder if you do php artisan storage:link\n" ]
[ 0, 0 ]
[]
[]
[ "file_upload", "laravel", "laravel_filesystem" ]
stackoverflow_0074669005_file_upload_laravel_laravel_filesystem.txt
Q: escape CREATE DEFINER=`root`@`localhost` when backup from phpmyadmin When I export any database from phpmyadmin usually mysql following definer for VIEWS and FUNCTIONS . CREATE DEFINER=`root`@`localhost` FUNCTION CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW ` Is there anything that can be done to avoid that?? A: Better try this CREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER
escape CREATE DEFINER=`root`@`localhost` when backup from phpmyadmin
When I export any database from phpmyadmin usually mysql following definer for VIEWS and FUNCTIONS . CREATE DEFINER=`root`@`localhost` FUNCTION CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW ` Is there anything that can be done to avoid that??
[ "Better try this\nCREATE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER\n\n" ]
[ 0 ]
[]
[]
[ "mysql" ]
stackoverflow_0064251897_mysql.txt
Q: Rust functions behave weirdly I have an implementation like given below: use crate::queue::{Task, WorkQueue}; use digest::consts::U32; use digest::generic_array::typenum::Pow; use sha2::digest::generic_array::GenericArray; use sha2::{Digest, Sha256}; use std::fmt::Write; use std::ops::Add; use std::sync; pub type Hash = GenericArray<u8, U32>; #[derive(Debug, Clone)] pub struct Block { pub prev_hash: Hash, pub generation: u64, pub difficulty: u8, pub data: String, pub proof: Option<u64>, } impl Block { pub fn mine_range(self: &Block, workers: usize, start: u64, end: u64, chunks: u64) -> u64 { // TODO: with `workers` threads, check proof values in the given range, breaking up // into `chunks` tasks in a work queue. Return the first valid proof found. // HINTS: // - Create and use a queue::WorkQueue. // - Use sync::Arc to wrap a clone of self for sharing. unimplemented!() } pub fn mine_for_proof(self: &Block, workers: usize) -> u64 { let range_start: u64 = 0; let range_end: u64 = 8 * (1 << self.difficulty); // 8 * 2^(bits that must be zero) let chunks: u64 = 2345; self.mine_range(workers, range_start, range_end, chunks) } pub fn mine(self: &mut Block, workers: usize) { self.proof = Some(self.mine_for_proof(workers)); } } struct MiningTask { block: sync::Arc<Block>, // TODO: more fields as needed workers: usize } impl Task for MiningTask { type Output = u64; fn run(&self) -> Option<u64> { // TODO: what does it mean to .run? self.block.mine(self.workers); let result = self.block.proof; return result; } } Now if I take out the return state from run like so: impl Task for MiningTask { type Output = u64; fn run(&self) -> Option<u64> { // TODO: what does it mean to .run? self.block.mine(self.workers); let result = self.block.proof; //return result; } } There is no borrowing error however like this: impl Task for MiningTask { type Output = u64; fn run(&self) -> Option<u64> { // TODO: what does it mean to .run? self.block.mine(self.workers); let result = self.block.proof; return result; } } It gives me: cannot borrow data in an Arc as mutable trait DerefMut is required to modify through a dereference, but it is not implemented for Arc<Block> I do not understand why returning something causes a borrow and how would I fix this? Preferably without a Mutex library or without a borrow? Even if I try cloning the self it still performs a borrow, I am very confused. A: In the MiningTask::run method, you are trying to return the proof field of the Block struct. This field is stored within an Option type, which means that it is either a Some value containing the proof or a None value if it has not yet been found. When you try to return this value, the compiler is unable to infer whether you want to return a reference to the proof field or a copy of the proof value. In order to return a reference to the proof field, you would need to use the Option::as_ref method to convert the Option type into an Option of references. For example: fn run(&self) -> Option<&u64> { self.block.mine(self.workers); let result = self.block.proof.as_ref(); return result; } Alternatively, you could return a copy of the proof value by using the Option::copied method to convert the Option type into an Option of the underlying type (u64 in this case). For example: fn run(&self) -> Option<u64> { self.block.mine(self.workers); let result = self.block.proof.copied(); return result; } In the code you provided, you have removed the return statement altogether. This means that the MiningTask::run method will always return None, since the return type is Option and there is no return statement in the body of the method. This will not cause a borrow error, since the Block struct is wrapped in an Arc which allows for multiple references to the same data. However, removing the return statement in this way means that the run method will not return the proof value that was found by mine method. This may not be the behavior you want, depending on what you are trying to do with the MiningTask struct. Update: In the code you provided, the run method has the type signature fn run(&self) -> Option, which means that it returns an Option value. An Option is not an iterator, so it cannot be used with the for loop syntax. If you want to use a for loop to iterate over the possible proof values in a range, you will need to change the run method to return an iterator instead of an Option. Here is an example of how you could do this: impl Task for MiningTask { type Output = u64; fn run(&self) -> impl Iterator<Item = u64> { let range_start: u64 = 0; let range_end: u64 = 8 * (1 << self.block.difficulty); let chunk_size: u64 = 2345; (range_start..range_end).step_by(chunk_size as usize) } } In this example, the run method returns an iterator that yields the proof values in the specified range, stepping by the given chunk size. You can then use this iterator in a for loop to iterate over the proof values and check each one for validity. Here is an example of how this would look: impl Block { pub fn mine_range(self: &Block, workers: usize, start: u64, end: u64, chunks: u64) -> u64 { let task = MiningTask { block: sync::Arc::new(self), workers: workers, }; let queue = WorkQueue::new(task, workers); // Iterate over the proof values in the given range for proof in queue.run() { let mut hasher = Sha256::new(); let mut hash_input = String::new(); write!(hash_input, "{}{}{}{}{}", self.prev_hash, self.generation, self.difficulty, self.data, proof).unwrap(); hasher.update(hash_input); let hash = hasher.finalize(); // Check if the hash is valid if hash[0] == 0 && hash[1] == 0 && hash[2] == 0 { return proof; } } // If no valid proof was found, return 0 0 } }
Rust functions behave weirdly
I have an implementation like given below: use crate::queue::{Task, WorkQueue}; use digest::consts::U32; use digest::generic_array::typenum::Pow; use sha2::digest::generic_array::GenericArray; use sha2::{Digest, Sha256}; use std::fmt::Write; use std::ops::Add; use std::sync; pub type Hash = GenericArray<u8, U32>; #[derive(Debug, Clone)] pub struct Block { pub prev_hash: Hash, pub generation: u64, pub difficulty: u8, pub data: String, pub proof: Option<u64>, } impl Block { pub fn mine_range(self: &Block, workers: usize, start: u64, end: u64, chunks: u64) -> u64 { // TODO: with `workers` threads, check proof values in the given range, breaking up // into `chunks` tasks in a work queue. Return the first valid proof found. // HINTS: // - Create and use a queue::WorkQueue. // - Use sync::Arc to wrap a clone of self for sharing. unimplemented!() } pub fn mine_for_proof(self: &Block, workers: usize) -> u64 { let range_start: u64 = 0; let range_end: u64 = 8 * (1 << self.difficulty); // 8 * 2^(bits that must be zero) let chunks: u64 = 2345; self.mine_range(workers, range_start, range_end, chunks) } pub fn mine(self: &mut Block, workers: usize) { self.proof = Some(self.mine_for_proof(workers)); } } struct MiningTask { block: sync::Arc<Block>, // TODO: more fields as needed workers: usize } impl Task for MiningTask { type Output = u64; fn run(&self) -> Option<u64> { // TODO: what does it mean to .run? self.block.mine(self.workers); let result = self.block.proof; return result; } } Now if I take out the return state from run like so: impl Task for MiningTask { type Output = u64; fn run(&self) -> Option<u64> { // TODO: what does it mean to .run? self.block.mine(self.workers); let result = self.block.proof; //return result; } } There is no borrowing error however like this: impl Task for MiningTask { type Output = u64; fn run(&self) -> Option<u64> { // TODO: what does it mean to .run? self.block.mine(self.workers); let result = self.block.proof; return result; } } It gives me: cannot borrow data in an Arc as mutable trait DerefMut is required to modify through a dereference, but it is not implemented for Arc<Block> I do not understand why returning something causes a borrow and how would I fix this? Preferably without a Mutex library or without a borrow? Even if I try cloning the self it still performs a borrow, I am very confused.
[ "In the MiningTask::run method, you are trying to return the proof field of the Block struct. This field is stored within an Option type, which means that it is either a Some value containing the proof or a None value if it has not yet been found.\nWhen you try to return this value, the compiler is unable to infer whether you want to return a reference to the proof field or a copy of the proof value. In order to return a reference to the proof field, you would need to use the Option::as_ref method to convert the Option type into an Option of references. For example:\nfn run(&self) -> Option<&u64> {\n self.block.mine(self.workers);\n let result = self.block.proof.as_ref();\n return result;\n}\n\nAlternatively, you could return a copy of the proof value by using the Option::copied method to convert the Option type into an Option of the underlying type (u64 in this case). For example:\nfn run(&self) -> Option<u64> {\n self.block.mine(self.workers);\n let result = self.block.proof.copied();\n return result;\n}\n\nIn the code you provided, you have removed the return statement altogether. This means that the MiningTask::run method will always return None, since the return type is Option and there is no return statement in the body of the method. This will not cause a borrow error, since the Block struct is wrapped in an Arc which allows for multiple references to the same data.\nHowever, removing the return statement in this way means that the run method will not return the proof value that was found by mine method. This may not be the behavior you want, depending on what you are trying to do with the MiningTask struct.\nUpdate:\nIn the code you provided, the run method has the type signature fn run(&self) -> Option, which means that it returns an Option value. An Option is not an iterator, so it cannot be used with the for loop syntax.\nIf you want to use a for loop to iterate over the possible proof values in a range, you will need to change the run method to return an iterator instead of an Option. Here is an example of how you could do this:\nimpl Task for MiningTask {\n type Output = u64;\n\n fn run(&self) -> impl Iterator<Item = u64> {\n let range_start: u64 = 0;\n let range_end: u64 = 8 * (1 << self.block.difficulty);\n let chunk_size: u64 = 2345;\n\n (range_start..range_end).step_by(chunk_size as usize)\n }\n}\n\n\nIn this example, the run method returns an iterator that yields the proof values in the specified range, stepping by the given chunk size. You can then use this iterator in a for loop to iterate over the proof values and check each one for validity. Here is an example of how this would look:\nimpl Block {\n pub fn mine_range(self: &Block, workers: usize, start: u64, end: u64, chunks: u64) -> u64 {\n let task = MiningTask {\n block: sync::Arc::new(self),\n workers: workers,\n };\n\n let queue = WorkQueue::new(task, workers);\n\n // Iterate over the proof values in the given range\n for proof in queue.run() {\n let mut hasher = Sha256::new();\n let mut hash_input = String::new();\n write!(hash_input, \"{}{}{}{}{}\", self.prev_hash, self.generation, self.difficulty, self.data, proof).unwrap();\n hasher.update(hash_input);\n let hash = hasher.finalize();\n\n // Check if the hash is valid\n if hash[0] == 0 && hash[1] == 0 && hash[2] == 0 {\n return proof;\n }\n }\n\n // If no valid proof was found, return 0\n 0\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "rust" ]
stackoverflow_0074670387_rust.txt
Q: Does it have an equivalent query in cql/cassandra for "alter table add column if column not exists"? I need to add the column for table that if the column is not existed. I ran the Alter Table <table> add <column_name> <type>; however, it will have this error message if the column already exists. InvalidRequest: Error from server: code=2200 [Invalid query] message="Invalid column name <column_name> because it conflicts with an existing column" Does it have a way to do a similar check on whether the column exists or not? Thank A: According to the official documentation of Cassandra 4.1 you can use the IF NOT EXISTS clause, i.e.: ALTER TABLE addamsFamily ADD IF NOT EXISTS gravesite varchar; I quote (emphasis mine): The ALTER TABLE statement can: ADD a new column to a table. The primary key of a table cannot ever be altered. A new column, thus, cannot be part of the primary key. Adding a column is a constant-time operation based on the amount of data in the table. If the new column already exists, the statement will return an error, unless IF NOT EXISTS is used in which case the operation is a no-op. [...] For versions before 4.1, you need to use Aaron's answer based on system_schema. A: So I checked Tasos's answer, and it works with Apache Cassandra 4.1. It does not work with 4.0 or any version prior to that. If you're using an older version, you can try querying system_schema like this: SELECT COUNT(*) FROm system_schema.columns WHERE keyspace_name = 'nosql1' AND table_name = 'users' AND column_name='description'; If you're trying to do something programatically, you can check whether or not that query returns 0 or 1, and then apply the ALTER TABLE command.
Does it have an equivalent query in cql/cassandra for "alter table add column if column not exists"?
I need to add the column for table that if the column is not existed. I ran the Alter Table <table> add <column_name> <type>; however, it will have this error message if the column already exists. InvalidRequest: Error from server: code=2200 [Invalid query] message="Invalid column name <column_name> because it conflicts with an existing column" Does it have a way to do a similar check on whether the column exists or not? Thank
[ "According to the official documentation of Cassandra 4.1 you can use the IF NOT EXISTS clause, i.e.:\nALTER TABLE addamsFamily ADD IF NOT EXISTS gravesite varchar;\n\nI quote (emphasis mine):\n\nThe ALTER TABLE statement can:\nADD a new column to a table. The primary key of a table cannot ever be altered. A new column, thus, cannot be part of the primary key. Adding a column is a constant-time operation based on the amount of data in the table. If the new column already exists, the statement will return an error, unless IF NOT EXISTS is used in which case the operation is a no-op.\n[...]\n\nFor versions before 4.1, you need to use Aaron's answer based on system_schema.\n", "So I checked Tasos's answer, and it works with Apache Cassandra 4.1. It does not work with 4.0 or any version prior to that.\nIf you're using an older version, you can try querying system_schema like this:\nSELECT COUNT(*) FROm system_schema.columns\nWHERE keyspace_name = 'nosql1' AND table_name = 'users' AND column_name='description';\n\nIf you're trying to do something programatically, you can check whether or not that query returns 0 or 1, and then apply the ALTER TABLE command.\n" ]
[ 1, 1 ]
[]
[]
[ "cassandra", "cql" ]
stackoverflow_0074661725_cassandra_cql.txt
Q: Django json response stay in the same page I'm making a like button for a post in django. What I need is that when the like button is clicked, the function is executed, but I need the page not to be reloaded (To later use javascript). To do that I return a jsonresponse() instead of a return render. But the real problem is that it redirects me to the page that I show in the photo. The page is not reloaded. as I want it. but I don't want it to show me the blank page with the jsonresponse data (like this photo).I want to stay in the same page without reload. My view function: def liking (request, pk): posts = get_object_or_404(Post, id = pk) if request.user in posts.likes.all(): posts.likes.remove(request.user) else: posts.likes.add(request.user.id) likes_count = posts.likes.all().count() print(f'likes_count = {likes_count}') data= { 'likes_count': likes_count, } #return redirect ('index')# This is commented return JsonResponse(data, safe=False, status=200 ) A: You can use AJAX. Simply place the code below in the template and trigger it with buttons. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> function get_likes(pk){ $.ajax({ url: '{% url "url-name" pk %}', type: 'GET', success: function (res) { var likes = JSON.parse(res); return likes["likes_count"] } }); } </script> If you need to post any data, you can use the lines below. function get_likes(pk){ $.ajax({ url: '{% url "url-name" pk %}', type: 'POST', data: { csrfmiddlewaretoken: "{{ csrf_token }}", data1:"data", data2:"data" }, success: function (res) { var likes = JSON.parse(res); return likes["likes_count"] } }); } You can add the following lines in your function to use the posted data on the django side. data1 = request.POST.get("data1") data2 = request.POST.get("data2") A: After trying for a while, I found the problem. It had nothing to do with the ajax request or a fetch, which is what I ended up using. It was simply that I had the url of the views.py function in the href="" and for this reason the white screen came out with the jsonresponse() data: I had to change: <a class="btn btn-dark like" id="like_button" href="{% url 'liking' post.id %}"> Like</a> So: <a class="btn btn-dark like" id="like_button" href="#"> Like</a> Thanks for all the answers!
Django json response stay in the same page
I'm making a like button for a post in django. What I need is that when the like button is clicked, the function is executed, but I need the page not to be reloaded (To later use javascript). To do that I return a jsonresponse() instead of a return render. But the real problem is that it redirects me to the page that I show in the photo. The page is not reloaded. as I want it. but I don't want it to show me the blank page with the jsonresponse data (like this photo).I want to stay in the same page without reload. My view function: def liking (request, pk): posts = get_object_or_404(Post, id = pk) if request.user in posts.likes.all(): posts.likes.remove(request.user) else: posts.likes.add(request.user.id) likes_count = posts.likes.all().count() print(f'likes_count = {likes_count}') data= { 'likes_count': likes_count, } #return redirect ('index')# This is commented return JsonResponse(data, safe=False, status=200 )
[ "You can use AJAX. Simply place the code below in the template and trigger it with buttons.\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js\"></script>\n<script>\n function get_likes(pk){\n $.ajax({\n url: '{% url \"url-name\" pk %}',\n type: 'GET',\n success: function (res) {\n var likes = JSON.parse(res);\n return likes[\"likes_count\"]\n }\n });\n }\n</script>\n\nIf you need to post any data, you can use the lines below.\nfunction get_likes(pk){\n $.ajax({\n url: '{% url \"url-name\" pk %}',\n type: 'POST',\n data: { \n csrfmiddlewaretoken: \"{{ csrf_token }}\",\n data1:\"data\",\n data2:\"data\"\n },\n success: function (res) {\n var likes = JSON.parse(res);\n return likes[\"likes_count\"]\n }\n });\n}\n\nYou can add the following lines in your function to use the posted data on the django side.\ndata1 = request.POST.get(\"data1\")\ndata2 = request.POST.get(\"data2\")\n\n", "After trying for a while, I found the problem. It had nothing to do with the ajax request or a fetch, which is what I ended up using. It was simply that I had the url of the views.py function in the href=\"\" and for this reason the white screen came out with the jsonresponse() data:\nI had to change:\n<a class=\"btn btn-dark like\" id=\"like_button\" href=\"{% url 'liking' post.id %}\"> Like</a>\n\nSo:\n<a class=\"btn btn-dark like\" id=\"like_button\" href=\"#\"> Like</a>\n\nThanks for all the answers!\n" ]
[ 0, 0 ]
[]
[]
[ "django", "javascript", "json", "redirect", "render" ]
stackoverflow_0074615642_django_javascript_json_redirect_render.txt
Q: React Native custom Progress Bar i need mathematical statement i'm working on react native expo project, i'm trying to build custom ProgressBar, I have state call step if the step increase by 1 then the width value of the view has to increase, if the step decreases then the width value of the view has to decrease, so if the value increase or decrease it seems the view has some animation on it const ProgressBar =({step , requset}) =>{ const [ steps , setSteps ]= useState(0); const [accessToken, setAccessToken] = useState(null); const [ width , setWidth ] = useState(50); useEffect( ()=> { const getToken = async ()=>{ const accessToken = await token.get(); setAccessToken(accessToken)} getToken(); accessToken ? requset == 1 ? setSteps(6) : setSteps(7) : setSteps(3) }) useEffect (()=>{ const newWidth = (step*50); setWidth(newWidth); }) return( <View style={{flexDirection:'row',}} > <View style={styles.progressBar}> <Animated.View onLayout = {e =>{ const newWidth = e.nativeEvent.layout.width; setWidth(newWidth); }} style ={ [styles.progress,{width: width}]} /> </View> <Text style={styles.progressText}>{steps}/{step}</Text> </View> )} How can I make a mathematical statement that calculates the amount of width increases depend on Total steps? A: const newWidth = (step / steps) * 100; This will calculate the width of the progress bar as a percentage of the total number of steps. If you have a total of 6 steps and the current step is 3, the width of the progress bar will be 50 (3 / 6 * 100). You can then use this value to update the width state variable, and it will be used to set the width of the progress bar. useEffect(() => { const newWidth = (step / steps) * 100; setWidth(newWidth); }); The other way is Animated.View component to animate the width of the progress bar when it changes. This will make the progress bar appear to "fill up" as the user advances through the steps. import { Animated } from 'react-native'; const ProgressBar = ({ step, requset }) => { // ... other code const [width, setWidth] = useState(new Animated.Value(0)); useEffect(() => { const newWidth = (step / steps) * 100; Animated.timing(width, { toValue: newWidth, duration: 1000, // duration of the animation, in A: Here's one possible way to calculate the width of the progress bar: First, calculate the total width of the progress bar by using the width prop of the View component that represents the progress bar. For example, you can use the onLayout event to get the width of the View and store it in a state variable, such as totalWidth. Next, calculate the width of the progress bar at each step by dividing the total width by the number of steps. For example, if the total width is 100 and the number of steps is 10, the width at each step would be 10. Finally, use the step prop to determine the current step and multiply it by the width at each step to get the current width of the progress bar. For example, if the current step is 3 and the width at each step is 10, the current width of the progress bar would be 30. Here's how this approach might look in your code: const ProgressBar = ({ step, request }) => { const [totalWidth, setTotalWidth] = useState(0); const [steps, setSteps] = useState(0); const [accessToken, setAccessToken] = useState(null); const [width, setWidth] = useState(0); useEffect(() => { const getToken = async () => { const accessToken = await token.get(); setAccessToken(accessToken); }; getToken(); accessToken ? (request == 1 ? setSteps(6) : setSteps(7)) : setSteps(3); }); useEffect(() => { const widthAtEachStep = totalWidth / steps; const newWidth = step * widthAtEachStep; setWidth(newWidth); }); return ( <View style={{ flexDirection: "row" }}> <View style={styles.progressBar} onLayout={(e) => { const newWidth = e.nativeEvent.layout.width; setTotalWidth(newWidth); }} > <Animated.View style={[styles.progress, { width }]} /> </View> <Text style={styles.progressText}>{step}/{steps}</Text> </View> ); }; In this example, the totalWidth state variable is used to store the total width of the progress bar, and the width state variable is used to store the current width of the progress bar. The useEffect hooks are used to calculate the width at each step and the current width of the progress bar based on the totalWidth and steps state variables.
React Native custom Progress Bar i need mathematical statement
i'm working on react native expo project, i'm trying to build custom ProgressBar, I have state call step if the step increase by 1 then the width value of the view has to increase, if the step decreases then the width value of the view has to decrease, so if the value increase or decrease it seems the view has some animation on it const ProgressBar =({step , requset}) =>{ const [ steps , setSteps ]= useState(0); const [accessToken, setAccessToken] = useState(null); const [ width , setWidth ] = useState(50); useEffect( ()=> { const getToken = async ()=>{ const accessToken = await token.get(); setAccessToken(accessToken)} getToken(); accessToken ? requset == 1 ? setSteps(6) : setSteps(7) : setSteps(3) }) useEffect (()=>{ const newWidth = (step*50); setWidth(newWidth); }) return( <View style={{flexDirection:'row',}} > <View style={styles.progressBar}> <Animated.View onLayout = {e =>{ const newWidth = e.nativeEvent.layout.width; setWidth(newWidth); }} style ={ [styles.progress,{width: width}]} /> </View> <Text style={styles.progressText}>{steps}/{step}</Text> </View> )} How can I make a mathematical statement that calculates the amount of width increases depend on Total steps?
[ "\nconst newWidth = (step / steps) * 100;\n\nThis will calculate the width of the progress bar as a percentage of the total number of steps.\nIf you have a total of 6 steps and the current step is 3, the width of the progress bar will be 50 (3 / 6 * 100).\nYou can then use this value to update the width state variable, and it will be used to set the width of the progress bar.\nuseEffect(() => {\n const newWidth = (step / steps) * 100;\n setWidth(newWidth);\n});\n\nThe other way is Animated.View component to animate the width of the progress bar when it changes. This will make the progress bar appear to \"fill up\" as the user advances through the steps.\nimport { Animated } from 'react-native';\n\nconst ProgressBar = ({ step, requset }) => {\n // ... other code\n\n const [width, setWidth] = useState(new Animated.Value(0));\n\n useEffect(() => {\n const newWidth = (step / steps) * 100;\n Animated.timing(width, {\n toValue: newWidth,\n duration: 1000, // duration of the animation, in\n\n", "Here's one possible way to calculate the width of the progress bar:\n\nFirst, calculate the total width of the progress bar by using the\nwidth prop of the View component that represents the progress bar.\nFor example, you can use the onLayout event to get the width of the\nView and store it in a state variable, such as totalWidth.\nNext, calculate the width of the progress bar at each step by\ndividing the total width by the number of steps. For example, if the\ntotal width is 100 and the number of steps is 10, the width at each\nstep would be 10.\nFinally, use the step prop to determine the current step and\nmultiply it by the width at each step to get the current width of\nthe progress bar. For example, if the current step is 3 and the\nwidth at each step is 10, the current width of the progress bar\nwould be 30.\n\nHere's how this approach might look in your code:\nconst ProgressBar = ({ step, request }) => {\n const [totalWidth, setTotalWidth] = useState(0);\n const [steps, setSteps] = useState(0);\n const [accessToken, setAccessToken] = useState(null);\n const [width, setWidth] = useState(0);\n\n useEffect(() => {\n const getToken = async () => {\n const accessToken = await token.get();\n setAccessToken(accessToken);\n };\n\n getToken();\n accessToken ? (request == 1 ? setSteps(6) : setSteps(7)) : setSteps(3);\n });\n\n useEffect(() => {\n const widthAtEachStep = totalWidth / steps;\n const newWidth = step * widthAtEachStep;\n setWidth(newWidth);\n });\n\n return (\n <View style={{ flexDirection: \"row\" }}>\n <View\n style={styles.progressBar}\n onLayout={(e) => {\n const newWidth = e.nativeEvent.layout.width;\n setTotalWidth(newWidth);\n }}\n >\n <Animated.View style={[styles.progress, { width }]} />\n </View>\n <Text style={styles.progressText}>{step}/{steps}</Text>\n </View>\n );\n};\n\nIn this example, the totalWidth state variable is used to store the total width of the progress bar, and the width state variable is used to store the current width of the progress bar. The useEffect hooks are used to calculate the width at each step and the current width of the progress bar based on the totalWidth and steps state variables.\n" ]
[ 0, 0 ]
[]
[]
[ "javascript", "react_native" ]
stackoverflow_0074670374_javascript_react_native.txt
Q: How to callback NSStreamDelegate with NSStreamEventOpenCompleted? I have been working on a NSStreamDelegate, I have implemented call back, I have initialized the input and output stream ilke this... CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStringRef host = CFSTR("74.125.224.72"); UInt32 port = 2270; CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &inputStream, &writeStream); if (writeStream && inputStream) { inputStream = (__bridge NSInputStream *)readStream; [inputStream setDelegate:self]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream open]; outputStream = (__bridge NSOutputStream *)writeStream; [outputStream setDelegate:self]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [outputStream open]; } Even after opened both the stream callback(stream:(NSStream *)theStream handleEvent:) is not called with NSStreamEventOpenCompleted for both streams. Can anyone help me what am I doing wrong here. Or What is the possibilities NSStreamEventOpenCompleted won't be called, I have seen in documentation, if opening failed it will not call this, if so why opening of streams is failing. Any idea? thanks for your help. A: I use with very similar code and it works fine for me. Try the code below. NSString* host = @"192.168.2.105"; CFReadStreamRef readStream; CFWriteStreamRef writeStream; UInt32 port = 8008; CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)(host), port, &readStream, &writeStream); if (writeStream && readStream) { self.InputStream = (__bridge NSInputStream *)readStream; [self.InputStream setDelegate:self]; [self.InputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [self.InputStream open]; self.OutputStream = (__bridge NSOutputStream *)writeStream; [self.OutputStream setDelegate:self]; [self.OutputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [self.OutputStream open]; } If it doesn't work for you, I can to send you a small app that implement TCP Client and server for a example. A: If it is running in a new NSThread, make sure the run loop of the thread is started after the stream setup, like CFRunLoopRun(); A: It is possible that the NSStreamEventOpenCompleted event is not being called because the stream has not completed opening yet. The NSStream class has an isOpen property that you can check to determine if the stream has been successfully opened. In your NSStreamDelegate implementation, you should first check if the NSStreamEventOpenCompleted event has been fired for both streams, and then check the isOpen property for each stream to determine if it has successfully opened. If the isOpen property returns NO, then it is possible that there was an error opening the stream. Here is an example of how you could implement this in your NSStreamDelegate: - (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent { switch (streamEvent) { case NSStreamEventOpenCompleted: // Check if the input stream is open if ([inputStream isOpen]) { // Input stream has successfully opened } else { // There was an error opening the input stream } // Check if the output stream is open if ([outputStream isOpen]) { // Output stream has successfully opened } else { // There was an error opening the output stream } break; // Handle other stream events... default: break; } } Alternatively, you could check the streamError property of the NSStream object to determine if there was an error opening the stream. This property will be nil if the stream was opened successfully, and will contain an error object if there was a problem. For example: if (theStream.streamError) { // Handle the error } else { // Stream opened successfully } You can also check the streamStatus property of the NSStream object to determine if the stream is open or not. For example: if (theStream.streamStatus == NSStreamStatusOpen) { // Stream is open } else { // Stream is not open } If the streamStatus is not NSStreamStatusOpen, you can check the streamError property to determine if there was an error opening the stream, as described above.
How to callback NSStreamDelegate with NSStreamEventOpenCompleted?
I have been working on a NSStreamDelegate, I have implemented call back, I have initialized the input and output stream ilke this... CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStringRef host = CFSTR("74.125.224.72"); UInt32 port = 2270; CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &inputStream, &writeStream); if (writeStream && inputStream) { inputStream = (__bridge NSInputStream *)readStream; [inputStream setDelegate:self]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream open]; outputStream = (__bridge NSOutputStream *)writeStream; [outputStream setDelegate:self]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [outputStream open]; } Even after opened both the stream callback(stream:(NSStream *)theStream handleEvent:) is not called with NSStreamEventOpenCompleted for both streams. Can anyone help me what am I doing wrong here. Or What is the possibilities NSStreamEventOpenCompleted won't be called, I have seen in documentation, if opening failed it will not call this, if so why opening of streams is failing. Any idea? thanks for your help.
[ "I use with very similar code and it works fine for me.\nTry the code below.\n NSString* host = @\"192.168.2.105\";\n CFReadStreamRef readStream;\n CFWriteStreamRef writeStream;\n UInt32 port = 8008;\n\n CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)(host), port, &readStream, &writeStream);\n\n if (writeStream && readStream) {\n\n self.InputStream = (__bridge NSInputStream *)readStream;\n [self.InputStream setDelegate:self];\n [self.InputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];\n [self.InputStream open];\n\n self.OutputStream = (__bridge NSOutputStream *)writeStream;\n [self.OutputStream setDelegate:self];\n [self.OutputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];\n [self.OutputStream open];\n }\n\nIf it doesn't work for you, I can to send you a small app that implement TCP Client and server for a example.\n", "If it is running in a new NSThread, make sure the run loop of the thread is started after the stream setup, like CFRunLoopRun();\n", "It is possible that the NSStreamEventOpenCompleted event is not being called because the stream has not completed opening yet. The NSStream class has an isOpen property that you can check to determine if the stream has been successfully opened.\nIn your NSStreamDelegate implementation, you should first check if the NSStreamEventOpenCompleted event has been fired for both streams, and then check the isOpen property for each stream to determine if it has successfully opened. If the isOpen property returns NO, then it is possible that there was an error opening the stream.\nHere is an example of how you could implement this in your NSStreamDelegate:\n- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {\n switch (streamEvent) {\n case NSStreamEventOpenCompleted:\n // Check if the input stream is open\n if ([inputStream isOpen]) {\n // Input stream has successfully opened\n } else {\n // There was an error opening the input stream\n }\n\n // Check if the output stream is open\n if ([outputStream isOpen]) {\n // Output stream has successfully opened\n } else {\n // There was an error opening the output stream\n }\n break;\n // Handle other stream events...\n default:\n break;\n }\n}\n\nAlternatively, you could check the streamError property of the NSStream object to determine if there was an error opening the stream. This property will be nil if the stream was opened successfully, and will contain an error object if there was a problem. For example:\nif (theStream.streamError) {\n// Handle the error\n} else {\n// Stream opened successfully\n}\n\nYou can also check the streamStatus property of the NSStream object to determine if the stream is open or not. For example:\nif (theStream.streamStatus == NSStreamStatusOpen) {\n// Stream is open\n} else {\n// Stream is not open\n}\n\nIf the streamStatus is not NSStreamStatusOpen, you can check the streamError property to determine if there was an error opening the stream, as described above.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "cocoa_touch", "ios", "iphone", "nsstream" ]
stackoverflow_0012594987_cocoa_touch_ios_iphone_nsstream.txt
Q: Microfrontend This component must be used inside a component Build two microfrontends using recoil frontend when accessed indepentenly works fine, when integrated into parent project it shows error. Central package for state management was developed to handle states across multiple frontends. That package is used on root level it still throws same error. Tried added on multiple locations still same error of "This component must be used inside a component" after build. A: I can recommend you a eventrix for state management in microfrontend applications. It has a built-in event bus so you can communicate between elements of your application.
Microfrontend This component must be used inside a component
Build two microfrontends using recoil frontend when accessed indepentenly works fine, when integrated into parent project it shows error. Central package for state management was developed to handle states across multiple frontends. That package is used on root level it still throws same error. Tried added on multiple locations still same error of "This component must be used inside a component" after build.
[ "I can recommend you a eventrix for state management in microfrontend applications. It has a built-in event bus so you can communicate between elements of your application.\n" ]
[ 0 ]
[]
[]
[ "reactjs", "recoiljs" ]
stackoverflow_0074330331_reactjs_recoiljs.txt
Q: Converting week numbers to dates Say I have a week number of a given year (e.g. week number 6 of 2014). How can I convert this to the date of the Monday that starts that week? One brute force solution I thought of would be to go through all Mondays of the year: date1 = datetime.date(1,1,2014) date2 = datetime.date(12,31,2014) def monday_range(date1,date2): while date1 < date2: if date1.weekday() == 0: yield date1 date1 = date1 + timedelta(days=1) and store a hash from the first to the last Monday of the year, but this wouldn't do it, since, the first week of the year may not contain a Monday. A: You could just feed the data into time.asctime(). >>> import time >>> week = 6 >>> year = 2014 >>> atime = time.asctime(time.strptime('{} {} 1'.format(year, week), '%Y %W %w')) >>> atime 'Mon Feb 10 00:00:00 2014' EDIT: To convert this to a datetime.date object: >>> datetime.datetime.fromtimestamp(time.mktime(atime)).date() datetime.date(2014, 2, 10) A: All about strptime \ strftime: https://docs.python.org/2/library/datetime.html mytime.strftime('%U') #for W\C Monday mytime.strftime('%W') #for W\C Sunday Sorry wrong way around from datetime import datetime mytime=datetime.strptime('2012W6 MON'. '%YW%U %a') Strptime needs to see both the year and the weekday to do this. I'm assuming you've got weekly data so just add 'mon' to the end of the string. Enjoy A: A simple function to get the Monday, given a date. def get_monday(dte): return dte - datetime.timedelta(days = dte.weekday()) Some sample output: >>> get_monday(date1) datetime.date(2013, 12, 30) >>> get_monday(date2) datetime.date(2014, 12, 29) Call this function within your loop. A: We can just add the number of weeks to the first day of the year. >>> import datetime >>> from dateutil.relativedelta import relativedelta >>> week = 40 >>> year = 2019 >>> date = datetime.date(year,1,1)+relativedelta(weeks=+week) >>> date datetime.date(2019, 10, 8) A: To piggyback and give a different version of the answer @anon582847382 gave, you can do something like the below code if you're creating a function for it and the week number is given like "11-2023": import time def get_date_from_week_number(str_value): temp_str = time.asctime(time.strptime('{} {} 1'.format(str_value[3:7], str_value[0:2]), '%Y %W %w')) return datetime.strptime(temp_str, '%a %b %d %H:%M:%S %Y').date()
Converting week numbers to dates
Say I have a week number of a given year (e.g. week number 6 of 2014). How can I convert this to the date of the Monday that starts that week? One brute force solution I thought of would be to go through all Mondays of the year: date1 = datetime.date(1,1,2014) date2 = datetime.date(12,31,2014) def monday_range(date1,date2): while date1 < date2: if date1.weekday() == 0: yield date1 date1 = date1 + timedelta(days=1) and store a hash from the first to the last Monday of the year, but this wouldn't do it, since, the first week of the year may not contain a Monday.
[ "You could just feed the data into time.asctime(). \n>>> import time\n>>> week = 6\n>>> year = 2014\n>>> atime = time.asctime(time.strptime('{} {} 1'.format(year, week), '%Y %W %w'))\n>>> atime\n'Mon Feb 10 00:00:00 2014'\n\n\nEDIT:\nTo convert this to a datetime.date object:\n>>> datetime.datetime.fromtimestamp(time.mktime(atime)).date()\ndatetime.date(2014, 2, 10)\n\n", "All about strptime \\ strftime:\nhttps://docs.python.org/2/library/datetime.html\nmytime.strftime('%U') #for W\\C Monday\nmytime.strftime('%W') #for W\\C Sunday\n\nSorry wrong way around\nfrom datetime import datetime\nmytime=datetime.strptime('2012W6 MON'. '%YW%U %a')\n\nStrptime needs to see both the year and the weekday to do this. I'm assuming you've got weekly data so just add 'mon' to the end of the string.\nEnjoy\n", "A simple function to get the Monday, given a date.\ndef get_monday(dte):\n return dte - datetime.timedelta(days = dte.weekday())\n\nSome sample output:\n>>> get_monday(date1)\ndatetime.date(2013, 12, 30)\n>>> get_monday(date2)\ndatetime.date(2014, 12, 29)\n\nCall this function within your loop.\n", "We can just add the number of weeks to the first day of the year.\n>>> import datetime\n>>> from dateutil.relativedelta import relativedelta\n\n>>> week = 40\n>>> year = 2019\n>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)\n>>> date\ndatetime.date(2019, 10, 8)\n\n", "To piggyback and give a different version of the answer @anon582847382 gave, you can do something like the below code if you're creating a function for it and the week number is given like \"11-2023\":\nimport time\n\n\ndef get_date_from_week_number(str_value):\n temp_str = time.asctime(time.strptime('{} {} 1'.format(str_value[3:7], str_value[0:2]), '%Y %W %w'))\n return datetime.strptime(temp_str, '%a %b %d %H:%M:%S %Y').date()\n\n" ]
[ 6, 5, 4, 0, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0022789198_datetime_python.txt
Q: discord.py temprole command First of all i dont really know why its not working properly. Its not returning any errors, messages etc., the code is running properly. Can somebody help me fix my issue? EDIT1: Just want to add that im noob in coding and ive spent about 1 hour trying to solve the problem import discord from discord.ext import commands from discord.ext import tasks from discord.utils import get import asyncio bot = discord.ext.commands.Bot(command_prefix = "$", intents=discord.Intents.default()) intents = discord.Intents.default() intents.message_content = True time_convert = {"sec":1, "min":60, "h":3600,"d":86400} client = discord.Client(intents=intents) @bot.command() async def temprole(ctx, role_time: int, member: discord.Member = None, role: discord.Role = None): if not member: await ctx.send("Who do you want me to give a role?") return if role is None: await ctx.send('Text me a role to add') return await member.add_roles(role) await ctx.send(f"Role has been given to {member.mention} \nfor {role_time}") await asyncio.sleep(role_time) await member.remove_roles(role) await ctx.send(f"{role.mention} has been removed from {member.mention} \n*(expired)*") client.run('My Token Is Here') A: as I can see you have a warning so you there are some missing intents change this bot = discord.ext.commands.Bot(command_prefix = "$", intents=discord.Intents.default()) to bot = discord.ext.commands.Bot(command_prefix = "$", intents=discord.Intents.all())
discord.py temprole command
First of all i dont really know why its not working properly. Its not returning any errors, messages etc., the code is running properly. Can somebody help me fix my issue? EDIT1: Just want to add that im noob in coding and ive spent about 1 hour trying to solve the problem import discord from discord.ext import commands from discord.ext import tasks from discord.utils import get import asyncio bot = discord.ext.commands.Bot(command_prefix = "$", intents=discord.Intents.default()) intents = discord.Intents.default() intents.message_content = True time_convert = {"sec":1, "min":60, "h":3600,"d":86400} client = discord.Client(intents=intents) @bot.command() async def temprole(ctx, role_time: int, member: discord.Member = None, role: discord.Role = None): if not member: await ctx.send("Who do you want me to give a role?") return if role is None: await ctx.send('Text me a role to add') return await member.add_roles(role) await ctx.send(f"Role has been given to {member.mention} \nfor {role_time}") await asyncio.sleep(role_time) await member.remove_roles(role) await ctx.send(f"{role.mention} has been removed from {member.mention} \n*(expired)*") client.run('My Token Is Here')
[ "as I can see you have a warning so you there are some missing intents\nchange this\nbot = discord.ext.commands.Bot(command_prefix = \"$\", intents=discord.Intents.default()) \nto\nbot = discord.ext.commands.Bot(command_prefix = \"$\", intents=discord.Intents.all())\n\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074668821_discord_discord.py_python.txt
Q: How to change the keys in nested array of objects Following is my array, and I need to replace the keys name with title and Email with subtitle. I tried some ways, but I still need to fulfill my requirement. Please provide any solution to this. const newUpdatedList = []; resArr.forEach((res) => { const obj = { title: res.name, subtitle: res.attributes.Email }; if (res.children) { const newList = res.children.map((ch) => { return { title: ch.name, subtitle: ch.attributes.Email, }; }); obj.children = newList; } newUpdatedList.push(obj); }); const resArr = [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , name : 'Harsha ABC' , custom_id : 'mani78989-1gfqv04bo' , attributes : { Email: '[email protected]', Role: 'admin'} , children: [ { user_id : 'd748037a-b445-41c2-b82f-4d6ee9396714' , name : 'Lavaraju Allu' , custom_id : 'mani78989-1gfqv472q' , attributes : { Email: '[email protected]', Role: 'Manager'} , children: [ { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , name : 'Ramesh Allu' , custom_id : 'mani78989-1gh14i13t' , attributes : { Email: '[email protected]', Role: 'Retailer'} , children: [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , name : 'Harsha ABC' , custom_id : 'mani78989-1gh15nrev' , attributes : { Email: '[email protected]', Role: 'Delivery Manager'} , children : [] } ] } ] } , { user_id : '550cc296-d7e4-44fb-9d62-4c6755b3f6f2' , name : 'Suresh Kunisetti' , custom_id : 'mani78989-1gfqv6idi' , attributes : { Email: '[email protected]', Role: 'Super Admin'} , children: [ { user_id : '45cf19f8-36c1-4669-9333-1226c4f7b66b' , name : 'Harish Three' , custom_id : 'mani78989-1ggv5vffb' , attributes : { Email: '[email protected]', Role: 'Delivery Manager'} , children : [] } ] } , { user_id : '2c8535be-5fe7-40f0-892f-0f9bcffe0baa' , name : 'Sandeep Bbb' , custom_id : 'mani78989-1gh14m5p4' , attributes : { Email: '[email protected]', Role: 'Delivery Manager'} , children : [] } , { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , name : 'Ramesh Allu' , custom_id : 'mani78989-1gh14pc6p' , attributes : { Email: '[email protected]', Role: 'Manager'} , children : [ ] } ] } ] Expected output is const resArr = [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , title : 'Harsha ABC' , custom_id : 'mani78989-1gfqv04bo' , attributes : { subtitle: '[email protected]', Role: 'admin'} , children: [ { user_id : 'd748037a-b445-41c2-b82f-4d6ee9396714' , title : 'Lavaraju Allu' , custom_id : 'mani78989-1gfqv472q' , attributes : { subtitle: '[email protected]', Role: 'Manager'} , children: [ { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , title : 'Ramesh Allu' , custom_id : 'mani78989-1gh14i13t' , attributes : { subtitle: '[email protected]', Role: 'Retailer'} , children: [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , title : 'Harsha ABC' , custom_id : 'mani78989-1gh15nrev' , attributes : { subtitle: '[email protected]', Role: 'Delivery Manager'} , children : [] } ] } ] } , { user_id : '550cc296-d7e4-44fb-9d62-4c6755b3f6f2' , title : 'Suresh Kunisetti' , custom_id : 'mani78989-1gfqv6idi' , attributes : { subtitle: '[email protected]', Role: 'Super Admin'} , children: [ { user_id : '45cf19f8-36c1-4669-9333-1226c4f7b66b' , title : 'Harish Three' , custom_id : 'mani78989-1ggv5vffb' , attributes : { subtitle: '[email protected]', Role: 'Delivery Manager'} , children : [] } ] } , { user_id : '2c8535be-5fe7-40f0-892f-0f9bcffe0baa' , title : 'Sandeep Bbb' , custom_id : 'mani78989-1gh14m5p4' , attributes : { subtitle: '[email protected]', Role: 'Delivery Manager'} , children : [] } , { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , title : 'Ramesh Allu' , custom_id : 'mani78989-1gh14pc6p' , attributes : { subtitle: '[email protected]', Role: 'Manager'} , children : [] } ] } ] A: Here's a recursive solution. const resArr= [{"user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2","name": "Harsha ABC","custom_id": "mani78989-1gfqv04bo","attributes": {"Email": "[email protected]","Role": "admin"},"children": [{"user_id": "d748037a-b445-41c2-b82f-4d6ee9396714","name": "Lavaraju Allu","custom_id": "mani78989-1gfqv472q","attributes": {"Email": "[email protected]","Role": "Manager"},"children": [{"user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1","name": "Ramesh Allu","custom_id": "mani78989-1gh14i13t","attributes": {"Email": "[email protected]","Role": "Retailer"},"children": [{"user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2","name": "Harsha ABC","custom_id": "mani78989-1gh15nrev","attributes": {"Email": "[email protected]","Role": "Delivery Manager"},"children": []}]}]},{"user_id": "550cc296-d7e4-44fb-9d62-4c6755b3f6f2","name": "Suresh Kunisetti","custom_id": "mani78989-1gfqv6idi","attributes": {"Email": "[email protected]","Role": "Super Admin"},"children": [{"user_id": "45cf19f8-36c1-4669-9333-1226c4f7b66b","name": "Harish Three","custom_id": "mani78989-1ggv5vffb","attributes": {"Email": "[email protected]","Role": "Delivery Manager"},"children": []}]},{"user_id": "2c8535be-5fe7-40f0-892f-0f9bcffe0baa","name": "Sandeep Bbb","custom_id": "mani78989-1gh14m5p4","attributes": {"Email": "[email protected]","Role": "Delivery Manager"},"children": []},{"user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1","name": "Ramesh Allu","custom_id": "mani78989-1gh14pc6p","attributes": {"Email": "[email protected]","Role": "Manager"},"children": []}]}] function changeTitles(Obj){ Obj.title = Obj.name; Obj.attributes.subtitle = Obj.attributes.Email; delete Obj.name; delete Obj.attributes.Email; if (Obj.children) { Obj.children.forEach(changeTitles) } } const clone = JSON.parse(JSON.stringify(resArr)) // Because the function mutates the object clone.forEach(changeTitles) console.log(clone) A: I was a little late with my answer, so it looks like a copy of Brother58697's answer. The only difference is maybe the structuredClone() method, a newish global method: const resArr= [ { "user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2", "name": "Harsha ABC", "custom_id": "mani78989-1gfqv04bo", "attributes": { "Email": "[email protected]", "Role": "admin" }, "children": [ { "user_id": "d748037a-b445-41c2-b82f-4d6ee9396714", "name": "Lavaraju Allu", "custom_id": "mani78989-1gfqv472q", "attributes": { "Email": "[email protected]", "Role": "Manager" }, "children": [ { "user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1", "name": "Ramesh Allu", "custom_id": "mani78989-1gh14i13t", "attributes": { "Email": "[email protected]", "Role": "Retailer" }, "children": [ { "user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2", "name": "Harsha ABC", "custom_id": "mani78989-1gh15nrev", "attributes": { "Email": "[email protected]", "Role": "Delivery Manager" }, "children": [] } ] } ] }, { "user_id": "550cc296-d7e4-44fb-9d62-4c6755b3f6f2", "name": "Suresh Kunisetti", "custom_id": "mani78989-1gfqv6idi", "attributes": { "Email": "[email protected]", "Role": "Super Admin" }, "children": [ { "user_id": "45cf19f8-36c1-4669-9333-1226c4f7b66b", "name": "Harish Three", "custom_id": "mani78989-1ggv5vffb", "attributes": { "Email": "[email protected]", "Role": "Delivery Manager" }, "children": [] } ] }, { "user_id": "2c8535be-5fe7-40f0-892f-0f9bcffe0baa", "name": "Sandeep Bbb", "custom_id": "mani78989-1gh14m5p4", "attributes": { "Email": "[email protected]", "Role": "Delivery Manager" }, "children": [] }, { "user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1", "name": "Ramesh Allu", "custom_id": "mani78989-1gh14pc6p", "attributes": { "Email": "[email protected]", "Role": "Manager" }, "children": [] } ] } ]; function trans(arr){ arr.forEach((o)=>{ o.title=o.name; delete(o.name); o.attributes.subtitle=o.attributes.Email; delete(o.attributes.Email); trans(o.children) }) } let result=structuredClone(resArr); trans(result); console.log(result); A: You can use the recursive function that I created. This function is taking in an object that looks like sample_obj and then recreates the resArr where name is title and email is subtitle. Take a look: function recursive_fix(obj) { const sample_obj = { user_id: obj.user_id, title: obj.name, custom_id: obj.custom_id, attributes: {subtitle: obj.attributes.Email, Role: obj.attributes.Role}, children: [] }; // only adding recursive if the children array is not empty if (obj.children.length !== 0) { obj.children.forEach((childz) => { sample_obj.children.push({children: [recursive_fix(childz)]}) }) } return sample_obj }; const newUpdatedList = []; resArr.forEach((res) => { newUpdatedList.push(recursive_fix(res)) }) A: I am not 100% sure I understand correctly what you're trying to do, but it seems you are trying to change the key names in an array of objects. Let me know if this is wrong. Something like this would work in that case" const arrayOfObj = [{ name: 'value1', email: 'value2' }, { name: 'value1', email: 'value2' }]; const newArrayOfObj = arrayOfObj.map(({ name: title, email: subtitle, ...rest }) => ({ title, subtitle, ...rest })); console.log(newArrayOfObj); found this answer here A: A quick solution could be to stringify, string replace and parse back to object/array. Something like this: const asString = JSON.stringify(resArr); const replacedNames = asString.replace(/name/g, "title"); const replacedEmail = replacedNames.replace(/Email/g, "subtitle"); const result = JSON.parse(replacedEmail); the changed object/array is in result. A: One of the Simplest way we can use is to use Object.assign something like this: a={'name': 'xyz', 'Email': '[email protected]'}; b= Object.assign({'title': a.name, 'subtitle': a.Email});
How to change the keys in nested array of objects
Following is my array, and I need to replace the keys name with title and Email with subtitle. I tried some ways, but I still need to fulfill my requirement. Please provide any solution to this. const newUpdatedList = []; resArr.forEach((res) => { const obj = { title: res.name, subtitle: res.attributes.Email }; if (res.children) { const newList = res.children.map((ch) => { return { title: ch.name, subtitle: ch.attributes.Email, }; }); obj.children = newList; } newUpdatedList.push(obj); }); const resArr = [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , name : 'Harsha ABC' , custom_id : 'mani78989-1gfqv04bo' , attributes : { Email: '[email protected]', Role: 'admin'} , children: [ { user_id : 'd748037a-b445-41c2-b82f-4d6ee9396714' , name : 'Lavaraju Allu' , custom_id : 'mani78989-1gfqv472q' , attributes : { Email: '[email protected]', Role: 'Manager'} , children: [ { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , name : 'Ramesh Allu' , custom_id : 'mani78989-1gh14i13t' , attributes : { Email: '[email protected]', Role: 'Retailer'} , children: [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , name : 'Harsha ABC' , custom_id : 'mani78989-1gh15nrev' , attributes : { Email: '[email protected]', Role: 'Delivery Manager'} , children : [] } ] } ] } , { user_id : '550cc296-d7e4-44fb-9d62-4c6755b3f6f2' , name : 'Suresh Kunisetti' , custom_id : 'mani78989-1gfqv6idi' , attributes : { Email: '[email protected]', Role: 'Super Admin'} , children: [ { user_id : '45cf19f8-36c1-4669-9333-1226c4f7b66b' , name : 'Harish Three' , custom_id : 'mani78989-1ggv5vffb' , attributes : { Email: '[email protected]', Role: 'Delivery Manager'} , children : [] } ] } , { user_id : '2c8535be-5fe7-40f0-892f-0f9bcffe0baa' , name : 'Sandeep Bbb' , custom_id : 'mani78989-1gh14m5p4' , attributes : { Email: '[email protected]', Role: 'Delivery Manager'} , children : [] } , { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , name : 'Ramesh Allu' , custom_id : 'mani78989-1gh14pc6p' , attributes : { Email: '[email protected]', Role: 'Manager'} , children : [ ] } ] } ] Expected output is const resArr = [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , title : 'Harsha ABC' , custom_id : 'mani78989-1gfqv04bo' , attributes : { subtitle: '[email protected]', Role: 'admin'} , children: [ { user_id : 'd748037a-b445-41c2-b82f-4d6ee9396714' , title : 'Lavaraju Allu' , custom_id : 'mani78989-1gfqv472q' , attributes : { subtitle: '[email protected]', Role: 'Manager'} , children: [ { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , title : 'Ramesh Allu' , custom_id : 'mani78989-1gh14i13t' , attributes : { subtitle: '[email protected]', Role: 'Retailer'} , children: [ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2' , title : 'Harsha ABC' , custom_id : 'mani78989-1gh15nrev' , attributes : { subtitle: '[email protected]', Role: 'Delivery Manager'} , children : [] } ] } ] } , { user_id : '550cc296-d7e4-44fb-9d62-4c6755b3f6f2' , title : 'Suresh Kunisetti' , custom_id : 'mani78989-1gfqv6idi' , attributes : { subtitle: '[email protected]', Role: 'Super Admin'} , children: [ { user_id : '45cf19f8-36c1-4669-9333-1226c4f7b66b' , title : 'Harish Three' , custom_id : 'mani78989-1ggv5vffb' , attributes : { subtitle: '[email protected]', Role: 'Delivery Manager'} , children : [] } ] } , { user_id : '2c8535be-5fe7-40f0-892f-0f9bcffe0baa' , title : 'Sandeep Bbb' , custom_id : 'mani78989-1gh14m5p4' , attributes : { subtitle: '[email protected]', Role: 'Delivery Manager'} , children : [] } , { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1' , title : 'Ramesh Allu' , custom_id : 'mani78989-1gh14pc6p' , attributes : { subtitle: '[email protected]', Role: 'Manager'} , children : [] } ] } ]
[ "Here's a recursive solution.\n\n\nconst resArr= [{\"user_id\": \"f7ba4795-d279-4c38-9a84-7a49522c50a2\",\"name\": \"Harsha ABC\",\"custom_id\": \"mani78989-1gfqv04bo\",\"attributes\": {\"Email\": \"[email protected]\",\"Role\": \"admin\"},\"children\": [{\"user_id\": \"d748037a-b445-41c2-b82f-4d6ee9396714\",\"name\": \"Lavaraju Allu\",\"custom_id\": \"mani78989-1gfqv472q\",\"attributes\": {\"Email\": \"[email protected]\",\"Role\": \"Manager\"},\"children\": [{\"user_id\": \"881c7731-b853-4ebc-b271-8f9e9215f7a1\",\"name\": \"Ramesh Allu\",\"custom_id\": \"mani78989-1gh14i13t\",\"attributes\": {\"Email\": \"[email protected]\",\"Role\": \"Retailer\"},\"children\": [{\"user_id\": \"f7ba4795-d279-4c38-9a84-7a49522c50a2\",\"name\": \"Harsha ABC\",\"custom_id\": \"mani78989-1gh15nrev\",\"attributes\": {\"Email\": \"[email protected]\",\"Role\": \"Delivery Manager\"},\"children\": []}]}]},{\"user_id\": \"550cc296-d7e4-44fb-9d62-4c6755b3f6f2\",\"name\": \"Suresh Kunisetti\",\"custom_id\": \"mani78989-1gfqv6idi\",\"attributes\": {\"Email\": \"[email protected]\",\"Role\": \"Super Admin\"},\"children\": [{\"user_id\": \"45cf19f8-36c1-4669-9333-1226c4f7b66b\",\"name\": \"Harish Three\",\"custom_id\": \"mani78989-1ggv5vffb\",\"attributes\": {\"Email\": \"[email protected]\",\"Role\": \"Delivery Manager\"},\"children\": []}]},{\"user_id\": \"2c8535be-5fe7-40f0-892f-0f9bcffe0baa\",\"name\": \"Sandeep Bbb\",\"custom_id\": \"mani78989-1gh14m5p4\",\"attributes\": {\"Email\": \"[email protected]\",\"Role\": \"Delivery Manager\"},\"children\": []},{\"user_id\": \"881c7731-b853-4ebc-b271-8f9e9215f7a1\",\"name\": \"Ramesh Allu\",\"custom_id\": \"mani78989-1gh14pc6p\",\"attributes\": {\"Email\": \"[email protected]\",\"Role\": \"Manager\"},\"children\": []}]}]\n\nfunction changeTitles(Obj){\n Obj.title = Obj.name;\n Obj.attributes.subtitle = Obj.attributes.Email;\n delete Obj.name;\n delete Obj.attributes.Email;\n if (Obj.children) {\n Obj.children.forEach(changeTitles)\n }\n}\n\nconst clone = JSON.parse(JSON.stringify(resArr)) // Because the function mutates the object\nclone.forEach(changeTitles)\n\nconsole.log(clone)\n\n\n\n", "I was a little late with my answer, so it looks like a copy of Brother58697's answer. The only difference is maybe the structuredClone() method, a newish global method:\n\n\nconst resArr= [ { \"user_id\": \"f7ba4795-d279-4c38-9a84-7a49522c50a2\", \"name\": \"Harsha ABC\", \"custom_id\": \"mani78989-1gfqv04bo\", \"attributes\": { \"Email\": \"[email protected]\", \"Role\": \"admin\" }, \"children\": [ { \"user_id\": \"d748037a-b445-41c2-b82f-4d6ee9396714\", \"name\": \"Lavaraju Allu\", \"custom_id\": \"mani78989-1gfqv472q\", \"attributes\": { \"Email\": \"[email protected]\", \"Role\": \"Manager\" }, \"children\": [ { \"user_id\": \"881c7731-b853-4ebc-b271-8f9e9215f7a1\", \"name\": \"Ramesh Allu\", \"custom_id\": \"mani78989-1gh14i13t\", \"attributes\": { \"Email\": \"[email protected]\", \"Role\": \"Retailer\" }, \"children\": [ { \"user_id\": \"f7ba4795-d279-4c38-9a84-7a49522c50a2\", \"name\": \"Harsha ABC\", \"custom_id\": \"mani78989-1gh15nrev\", \"attributes\": { \"Email\": \"[email protected]\", \"Role\": \"Delivery Manager\" }, \"children\": [] } ] } ] }, { \"user_id\": \"550cc296-d7e4-44fb-9d62-4c6755b3f6f2\", \"name\": \"Suresh Kunisetti\", \"custom_id\": \"mani78989-1gfqv6idi\", \"attributes\": { \"Email\": \"[email protected]\", \"Role\": \"Super Admin\" }, \"children\": [ { \"user_id\": \"45cf19f8-36c1-4669-9333-1226c4f7b66b\", \"name\": \"Harish Three\", \"custom_id\": \"mani78989-1ggv5vffb\", \"attributes\": { \"Email\": \"[email protected]\", \"Role\": \"Delivery Manager\" }, \"children\": [] } ] }, { \"user_id\": \"2c8535be-5fe7-40f0-892f-0f9bcffe0baa\", \"name\": \"Sandeep Bbb\", \"custom_id\": \"mani78989-1gh14m5p4\", \"attributes\": { \"Email\": \"[email protected]\", \"Role\": \"Delivery Manager\" }, \"children\": [] }, { \"user_id\": \"881c7731-b853-4ebc-b271-8f9e9215f7a1\", \"name\": \"Ramesh Allu\", \"custom_id\": \"mani78989-1gh14pc6p\", \"attributes\": { \"Email\": \"[email protected]\", \"Role\": \"Manager\" }, \"children\": [] } ] } ];\n\nfunction trans(arr){\n arr.forEach((o)=>{\n o.title=o.name; delete(o.name);\n o.attributes.subtitle=o.attributes.Email; delete(o.attributes.Email);\n trans(o.children)\n })\n}\nlet result=structuredClone(resArr);\ntrans(result);\nconsole.log(result);\n\n\n\n", "You can use the recursive function that I created. This function is taking in an object that looks like sample_obj and then recreates the resArr where name is title and email is subtitle. Take a look:\n\n\nfunction recursive_fix(obj) {\n const sample_obj = {\n user_id: obj.user_id,\n title: obj.name,\n custom_id: obj.custom_id,\n attributes: {subtitle: obj.attributes.Email, Role: obj.attributes.Role},\n children: []\n };\n \n // only adding recursive if the children array is not empty\n if (obj.children.length !== 0) {\n obj.children.forEach((childz) => {\n sample_obj.children.push({children: [recursive_fix(childz)]})\n })\n }\n\n return sample_obj\n};\n\nconst newUpdatedList = [];\nresArr.forEach((res) => {\n newUpdatedList.push(recursive_fix(res))\n})\n\n\n\n", "I am not 100% sure I understand correctly what you're trying to do, but it seems you are trying to change the key names in an array of objects. Let me know if this is wrong. Something like this would work in that case\"\nconst arrayOfObj = [{\n name: 'value1',\n email: 'value2'\n }, {\n name: 'value1',\n email: 'value2'\n }];\n const newArrayOfObj = arrayOfObj.map(({\n name: title,\n email: subtitle,\n ...rest\n }) => ({\n title,\n subtitle,\n ...rest\n }));\n \n console.log(newArrayOfObj);\n\nfound this answer here\n", "A quick solution could be to stringify, string replace and parse back to object/array.\nSomething like this:\nconst asString = JSON.stringify(resArr);\nconst replacedNames = asString.replace(/name/g, \"title\");\nconst replacedEmail = replacedNames.replace(/Email/g, \"subtitle\");\nconst result = JSON.parse(replacedEmail);\n\nthe changed object/array is in result.\n", "One of the Simplest way we can use is to use Object.assign something like this:\na={'name': 'xyz', 'Email': '[email protected]'};\nb= Object.assign({'title': a.name, 'subtitle': a.Email});\n\n" ]
[ 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "javascript", "lodash" ]
stackoverflow_0074669705_javascript_lodash.txt
Q: Pixels Per Unit for unity sprite not aligning the correct amount of pixels This might be a simple question, but I'm having trouble with the pixel per unit setting in unity. As you can see in this picture, I have a sprite that is about 1000 pixels tall, and the ppu is set to 100, but the sprite is only taking up about 3 units. Shouldn't it take up ten units? Is there another setting I have turned on? Or am I just misunderstanding how ppu works? The sprite image is a png if that means anything. A: I'm sure you already found the answer, just for others with the same problem: You have to set the filter mode from "Bilinear" to "Point(No Filter)"
Pixels Per Unit for unity sprite not aligning the correct amount of pixels
This might be a simple question, but I'm having trouble with the pixel per unit setting in unity. As you can see in this picture, I have a sprite that is about 1000 pixels tall, and the ppu is set to 100, but the sprite is only taking up about 3 units. Shouldn't it take up ten units? Is there another setting I have turned on? Or am I just misunderstanding how ppu works? The sprite image is a png if that means anything.
[ "I'm sure you already found the answer, just for others with the same problem:\nYou have to set the filter mode from \"Bilinear\" to \"Point(No Filter)\"\n" ]
[ 0 ]
[]
[]
[ "game_development", "unity3d" ]
stackoverflow_0071025077_game_development_unity3d.txt
Q: Is it possible to change the Terraform Cloud workspace execution mode within the code block instead of in the web interface? Is it possible to change the Terraform Cloud workspace to Local execution mode rather than the Remote default? As the workspace can be created locally, it seems inconvenient to not be able to set options within the code block. terraform { required_version = ">= 1.3.6" cloud { organization = "org" workspaces { tags = ["foo", "bar"] } } } A: This is the open issue in the terraform, but you can do that via curl, as for example: TF_WORKSPACE="something" MY_ORGANISATION="else" TF_BACKEND_TOKEN="1234567890" TF_URL="https://app.terraform.io/api/v2/organizations/${MY_ORGANISATION}/workspaces/${TF_WORKSPACE}" terraform workspace new ${TF_WORKSPACE} && \ curl \ --header "Authorization: Bearer ${TF_BACKEND_TOKEN}" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH --data \ '{"data": {"type": "workspaces", "attributes": {"execution-mode": "local"}}}' \ ${TF_URL} # ... later terraform workspace select ${TF_WORKSPACE} terraform apply -auto-approve
Is it possible to change the Terraform Cloud workspace execution mode within the code block instead of in the web interface?
Is it possible to change the Terraform Cloud workspace to Local execution mode rather than the Remote default? As the workspace can be created locally, it seems inconvenient to not be able to set options within the code block. terraform { required_version = ">= 1.3.6" cloud { organization = "org" workspaces { tags = ["foo", "bar"] } } }
[ "This is the open issue in the terraform, but you can do that via curl, as for example:\nTF_WORKSPACE=\"something\"\nMY_ORGANISATION=\"else\"\nTF_BACKEND_TOKEN=\"1234567890\"\nTF_URL=\"https://app.terraform.io/api/v2/organizations/${MY_ORGANISATION}/workspaces/${TF_WORKSPACE}\"\nterraform workspace new ${TF_WORKSPACE} && \\\ncurl \\\n --header \"Authorization: Bearer ${TF_BACKEND_TOKEN}\" \\\n --header \"Content-Type: application/vnd.api+json\" \\\n --request PATCH --data \\\n '{\"data\": {\"type\": \"workspaces\", \"attributes\": {\"execution-mode\": \"local\"}}}' \\\n ${TF_URL}\n# ... later\nterraform workspace select ${TF_WORKSPACE}\nterraform apply -auto-approve\n\n" ]
[ 1 ]
[]
[]
[ "terraform" ]
stackoverflow_0074668153_terraform.txt
Q: Terminal is showing "error:03000086:digital envelope routines::initialization error" when I run "npm run prod" command I have a vue + laravel application. I need to run the production command using this: npm run prod but I got this error message : opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'digital envelope routines', reason: 'unsupported', code: 'ERR_OSSL_EVP_UNSUPPORTED' } Node.js v17.9.1 I search on google and added this to the package.json scripts key: "serve": "vue-cli-service --openssl-legacy-provider serve", "build": "vue-cli-service --openssl-legacy-provider build", "lint": "vue-cli-service --openssl-legacy-provider lint" but stil no solutions. Can you tell me how can I fix it ? my full package.json file now: https://codeshare.io/3AXbBg A: This error message suggests that there is an issue with the OpenSSL library that your application is using. This library is responsible for encrypting and decrypting data, so it is likely that your application is unable to properly encrypt or decrypt data due to this error. One possible solution is to try using the --openssl-legacy-provider flag when running the npm run command. This flag tells the application to use an older version of the OpenSSL library, which may not have the same compatibility issues. You could try running the following command: npm run --openssl-legacy-provider prod If this does not solve the issue, you may need to try updating the OpenSSL library to the latest version. You can do this by running the following command: npm install openssl This should install the latest version of the OpenSSL library, which may be able to fix the issue. If the problem persists, you may need to try reaching out to the maintainers of the application for assistance.
Terminal is showing "error:03000086:digital envelope routines::initialization error" when I run "npm run prod" command
I have a vue + laravel application. I need to run the production command using this: npm run prod but I got this error message : opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'digital envelope routines', reason: 'unsupported', code: 'ERR_OSSL_EVP_UNSUPPORTED' } Node.js v17.9.1 I search on google and added this to the package.json scripts key: "serve": "vue-cli-service --openssl-legacy-provider serve", "build": "vue-cli-service --openssl-legacy-provider build", "lint": "vue-cli-service --openssl-legacy-provider lint" but stil no solutions. Can you tell me how can I fix it ? my full package.json file now: https://codeshare.io/3AXbBg
[ "This error message suggests that there is an issue with the OpenSSL library that your application is using. This library is responsible for encrypting and decrypting data, so it is likely that your application is unable to properly encrypt or decrypt data due to this error.\nOne possible solution is to try using the --openssl-legacy-provider flag when running the npm run command. This flag tells the application to use an older version of the OpenSSL library, which may not have the same compatibility issues.\nYou could try running the following command:\nnpm run --openssl-legacy-provider prod\nIf this does not solve the issue, you may need to try updating the OpenSSL library to the latest version. You can do this by running the following command:\nnpm install openssl\nThis should install the latest version of the OpenSSL library, which may be able to fix the issue. If the problem persists, you may need to try reaching out to the maintainers of the application for assistance.\n" ]
[ 0 ]
[]
[]
[ "javascript", "npm" ]
stackoverflow_0074664587_javascript_npm.txt
Q: Jest onFailure hook I have a test suite running using Jest. I would like to trigger a hook after any failed test, ideally with the context of the test still available. Specifically, I am using Puppeteer via jest-puppeteer. The goal is to take a screenshot of the page after a test failure, before the page is closed in the tearDown function. What's the best way to achieve that? An example of my test suite: describe('My tests', () => { beforeAll(async () => { await page.goto('http://example.com'); }); // TODO I need something like this onFailure(async (something) => { page.takeScrenshot(); }); test('My example test', async () => { return await page.waitFor('.example-selector'); }); }); I have found that there is onTestFailure option when setting up a test-runner, is it possible to leverage that? A: You can use the onTestFailure option when setting up Jest to trigger a hook after a failed test. This option allows you to specify a function that will be called whenever a test fails. This function can be used to take a screenshot of the page, or to perform any other actions that you want to take when a test fails. Here is an example of how you can use the onTestFailure option in your test suite: describe('My tests', () => { beforeAll(async () => { await page.goto('http://example.com'); }); test('My example test', async () => { return await page.waitFor('.example-selector'); }); }); const jestConfig = { // Other Jest options... onTestFailure: async (test) => { // Access the page object here page.takeScreenshot(); } }; In this example, the onTestFailure function will be called whenever a test fails. The function has access to the test object, which contains information about the failed test, such as the test name and the error that occurred. You can use this information to take a screenshot of the page, or to perform any other actions that you want to take when a test fails. I hope this helps!
Jest onFailure hook
I have a test suite running using Jest. I would like to trigger a hook after any failed test, ideally with the context of the test still available. Specifically, I am using Puppeteer via jest-puppeteer. The goal is to take a screenshot of the page after a test failure, before the page is closed in the tearDown function. What's the best way to achieve that? An example of my test suite: describe('My tests', () => { beforeAll(async () => { await page.goto('http://example.com'); }); // TODO I need something like this onFailure(async (something) => { page.takeScrenshot(); }); test('My example test', async () => { return await page.waitFor('.example-selector'); }); }); I have found that there is onTestFailure option when setting up a test-runner, is it possible to leverage that?
[ "You can use the onTestFailure option when setting up Jest to trigger a hook after a failed test. This option allows you to specify a function that will be called whenever a test fails. This function can be used to take a screenshot of the page, or to perform any other actions that you want to take when a test fails.\nHere is an example of how you can use the onTestFailure option in your test suite:\ndescribe('My tests', () => {\n beforeAll(async () => {\n await page.goto('http://example.com');\n });\n\n test('My example test', async () => {\n return await page.waitFor('.example-selector');\n });\n});\n\nconst jestConfig = {\n // Other Jest options...\n\n onTestFailure: async (test) => {\n // Access the page object here\n page.takeScreenshot();\n }\n};\n\nIn this example, the onTestFailure function will be called whenever a test fails. The function has access to the test object, which contains information about the failed test, such as the test name and the error that occurred. You can use this information to take a screenshot of the page, or to perform any other actions that you want to take when a test fails.\nI hope this helps!\n" ]
[ 0 ]
[]
[]
[ "javascript", "jestjs", "puppeteer" ]
stackoverflow_0051617918_javascript_jestjs_puppeteer.txt
Q: How do I show a console output/window in a forms application? To get stuck in straight away, a very basic example: using System; using System.Windows.Forms; class test { static void Main() { Console.WriteLine("test"); MessageBox.Show("test"); } } If I compile this with default options (using csc at command line), as expected, it will compile to a console application. Also, because I imported System.Windows.Forms, it will also show a message box. Now, if I use the option /target:winexe, which I think is the same as choosing Windows Application from within project options, as expected I will only see the Message Box and no console output. (In fact, the moment it is launched from command line, I can issue the next command before the application has even completed). So, my question is - I know that you can have "windows"/forms output from a console application, but is there anyway to show the console from a Windows application? A: this one should work. using System.Runtime.InteropServices; private void Form1_Load(object sender, EventArgs e) { AllocConsole(); } [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool AllocConsole(); A: Perhaps this is over-simplistic... Create a Windows Form project... Then: Project Properties -> Application -> Output Type -> Console Application Then can have Console and Forms running together, works for me A: If you are not worrying about opening a console on-command, you can go into the properties for your project and change it to Console Application . This will still show your form as well as popping up a console window. You can't close the console window, but it works as an excellent temporary logger for debugging. Just remember to turn it back off before you deploy the program. A: You can call AttachConsole using pinvoke to get a console window attached to a WinForms project: http://www.csharp411.com/console-output-from-winforms-application/ You may also want to consider Log4net ( http://logging.apache.org/log4net/index.html ) for configuring log output in different configurations. A: Create a Windows Forms Application, and change the output type to Console. It will result in both a console and the form to open. A: This worked for me, to pipe the output to a file. Call the console with cmd /c "C:\path\to\your\application.exe" > myfile.txt Add this code to your application. [DllImport("kernel32.dll")] static extern bool AttachConsole(UInt32 dwProcessId); [DllImport("kernel32.dll")] private static extern bool GetFileInformationByHandle( SafeFileHandle hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation ); [DllImport("kernel32.dll")] private static extern SafeFileHandle GetStdHandle(UInt32 nStdHandle); [DllImport("kernel32.dll")] private static extern bool SetStdHandle(UInt32 nStdHandle, SafeFileHandle hHandle); [DllImport("kernel32.dll")] private static extern bool DuplicateHandle( IntPtr hSourceProcessHandle, SafeFileHandle hSourceHandle, IntPtr hTargetProcessHandle, out SafeFileHandle lpTargetHandle, UInt32 dwDesiredAccess, Boolean bInheritHandle, UInt32 dwOptions ); private const UInt32 ATTACH_PARENT_PROCESS = 0xFFFFFFFF; private const UInt32 STD_OUTPUT_HANDLE = 0xFFFFFFF5; private const UInt32 STD_ERROR_HANDLE = 0xFFFFFFF4; private const UInt32 DUPLICATE_SAME_ACCESS = 2; struct BY_HANDLE_FILE_INFORMATION { public UInt32 FileAttributes; public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime; public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime; public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime; public UInt32 VolumeSerialNumber; public UInt32 FileSizeHigh; public UInt32 FileSizeLow; public UInt32 NumberOfLinks; public UInt32 FileIndexHigh; public UInt32 FileIndexLow; } static void InitConsoleHandles() { SafeFileHandle hStdOut, hStdErr, hStdOutDup, hStdErrDup; BY_HANDLE_FILE_INFORMATION bhfi; hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); hStdErr = GetStdHandle(STD_ERROR_HANDLE); // Get current process handle IntPtr hProcess = Process.GetCurrentProcess().Handle; // Duplicate Stdout handle to save initial value DuplicateHandle(hProcess, hStdOut, hProcess, out hStdOutDup, 0, true, DUPLICATE_SAME_ACCESS); // Duplicate Stderr handle to save initial value DuplicateHandle(hProcess, hStdErr, hProcess, out hStdErrDup, 0, true, DUPLICATE_SAME_ACCESS); // Attach to console window – this may modify the standard handles AttachConsole(ATTACH_PARENT_PROCESS); // Adjust the standard handles if (GetFileInformationByHandle(GetStdHandle(STD_OUTPUT_HANDLE), out bhfi)) { SetStdHandle(STD_OUTPUT_HANDLE, hStdOutDup); } else { SetStdHandle(STD_OUTPUT_HANDLE, hStdOut); } if (GetFileInformationByHandle(GetStdHandle(STD_ERROR_HANDLE), out bhfi)) { SetStdHandle(STD_ERROR_HANDLE, hStdErrDup); } else { SetStdHandle(STD_ERROR_HANDLE, hStdErr); } } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { // initialize console handles InitConsoleHandles(); if (args.Length != 0) { if (args[0].Equals("waitfordebugger")) { MessageBox.Show("Attach the debugger now"); } if (args[0].Equals("version")) { #if DEBUG String typeOfBuild = "d"; #else String typeOfBuild = "r"; #endif String output = typeOfBuild + Assembly.GetExecutingAssembly() .GetName().Version.ToString(); //Just for the fun of it Console.Write(output); Console.Beep(4000, 100); Console.Beep(2000, 100); Console.Beep(1000, 100); Console.Beep(8000, 100); return; } } } I found this code here: http://www.csharp411.com/console-output-from-winforms-application/ I thought is was worthy to post it here as well. A: There are basically two things that can happen here. Console output It is possible for a winforms program to attach itself to the console window that created it (or to a different console window, or indeed to a new console window if desired). Once attached to the console window Console.WriteLine() etc works as expected. One gotcha to this approach is that the program returns control to the console window immediately, and then carries on writing to it, so the user can also type away in the console window. You can use start with the /wait parameter to handle this I think. Link to start Command syntax Redirected console output This is when someone pipes the output from your program somewhere else, eg. yourapp > file.txt Attaching to a console window in this case effectively ignores the piping. To make this work you can call Console.OpenStandardOutput() to get a handle to the stream that the output should be piped to. This only works if the output is piped, so if you want to handle both of the scenarios you need to open the standard output and write to it and attach to the console window. This does mean that the output is sent to the console window and to the pipe but its the best solution I could find. Below the code I use to do this. // This always writes to the parent console window and also to a redirected stdout if there is one. // It would be better to do the relevant thing (eg write to the redirected file if there is one, otherwise // write to the console) but it doesn't seem possible. public class GUIConsoleWriter : IConsoleWriter { [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool AttachConsole(int dwProcessId); private const int ATTACH_PARENT_PROCESS = -1; StreamWriter _stdOutWriter; // this must be called early in the program public GUIConsoleWriter() { // this needs to happen before attachconsole. // If the output is not redirected we still get a valid stream but it doesn't appear to write anywhere // I guess it probably does write somewhere, but nowhere I can find out about var stdout = Console.OpenStandardOutput(); _stdOutWriter = new StreamWriter(stdout); _stdOutWriter.AutoFlush = true; AttachConsole(ATTACH_PARENT_PROCESS); } public void WriteLine(string line) { _stdOutWriter.WriteLine(line); Console.WriteLine(line); } } A: //From your application set the Console to write to your RichTextkBox //object: Console.SetOut(new RichTextBoxWriter(yourRichTextBox)); //To ensure that your RichTextBox object is scrolled down when its text is //changed add this event: private void yourRichTextBox_TextChanged(object sender, EventArgs e) { yourRichTextBox.SelectionStart = yourRichTextBox.Text.Length; yourRichTextBox.ScrollToCaret(); } public delegate void StringArgReturningVoidDelegate(string text); public class RichTextBoxWriter : TextWriter { private readonly RichTextBox _richTextBox; public RichTextBoxWriter(RichTextBox richTexttbox) { _richTextBox = richTexttbox; } public override void Write(char value) { SetText(value.ToString()); } public override void Write(string value) { SetText(value); } public override void WriteLine(char value) { SetText(value + Environment.NewLine); } public override void WriteLine(string value) { SetText(value + Environment.NewLine); } public override Encoding Encoding => Encoding.ASCII; //Write to your UI object in thread safe way: private void SetText(string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (_richTextBox.InvokeRequired) { var d = new StringArgReturningVoidDelegate(SetText); _richTextBox.Invoke(d, text); } else { _richTextBox.Text += text; } } } A: Building on Chaz's answer, in .NET 5 there is a breaking change, so two modifications are required in the project file, i.e. changing OutputType and adding DisableWinExeOutputInference. Example: <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0-windows10.0.17763.0</TargetFramework> <UseWindowsForms>true</UseWindowsForms> <DisableWinExeOutputInference>true</DisableWinExeOutputInference> <Platforms>AnyCPU;x64;x86</Platforms> </PropertyGroup> A: using System; using System.Runtime.InteropServices; namespace SomeProject { class GuiRedirect { [DllImport("kernel32.dll", SetLastError = true)] private static extern bool AttachConsole(int dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(StandardHandle nStdHandle); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetStdHandle(StandardHandle nStdHandle, IntPtr handle); [DllImport("kernel32.dll", SetLastError = true)] private static extern FileType GetFileType(IntPtr handle); private enum StandardHandle : uint { Input = unchecked((uint)-10), Output = unchecked((uint)-11), Error = unchecked((uint)-12) } private enum FileType : uint { Unknown = 0x0000, Disk = 0x0001, Char = 0x0002, Pipe = 0x0003 } private static bool IsRedirected(IntPtr handle) { FileType fileType = GetFileType(handle); return (fileType == FileType.Disk) || (fileType == FileType.Pipe); } public static void Redirect() { if (IsRedirected(GetStdHandle(StandardHandle.Output))) { var initialiseOut = Console.Out; } bool errorRedirected = IsRedirected(GetStdHandle(StandardHandle.Error)); if (errorRedirected) { var initialiseError = Console.Error; } AttachConsole(-1); if (!errorRedirected) SetStdHandle(StandardHandle.Error, GetStdHandle(StandardHandle.Output)); } } A: Setting the output type as Console in the project properties will give you a Console application along with the form you created. A: if what you want is simple debug output the following works for me. I am using VS 2022 programming in C# add "using System.Diagnostics" then Debug.WriteLine("*****"); Debug.WriteLine(...); Debug.WriteLine(""); THe output appears in the debug console of VS2022. There is a lot of stuff there so I use the Debug.WriteLine("*****") and Debug.WriteLine("") to help me find my output. You can also clear the debug output after start up. I am still working but running under VS there is no output when running wo debugging
How do I show a console output/window in a forms application?
To get stuck in straight away, a very basic example: using System; using System.Windows.Forms; class test { static void Main() { Console.WriteLine("test"); MessageBox.Show("test"); } } If I compile this with default options (using csc at command line), as expected, it will compile to a console application. Also, because I imported System.Windows.Forms, it will also show a message box. Now, if I use the option /target:winexe, which I think is the same as choosing Windows Application from within project options, as expected I will only see the Message Box and no console output. (In fact, the moment it is launched from command line, I can issue the next command before the application has even completed). So, my question is - I know that you can have "windows"/forms output from a console application, but is there anyway to show the console from a Windows application?
[ "this one should work.\nusing System.Runtime.InteropServices;\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n AllocConsole();\n}\n\n[DllImport(\"kernel32.dll\", SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool AllocConsole();\n\n", "Perhaps this is over-simplistic...\nCreate a Windows Form project...\nThen: Project Properties -> Application -> Output Type -> Console Application\nThen can have Console and Forms running together, works for me\n", "If you are not worrying about opening a console on-command, you can go into the properties for your project and change it to Console Application\n. \nThis will still show your form as well as popping up a console window. You can't close the console window, but it works as an excellent temporary logger for debugging.\nJust remember to turn it back off before you deploy the program.\n", "You can call AttachConsole using pinvoke to get a console window attached to a WinForms project: http://www.csharp411.com/console-output-from-winforms-application/\nYou may also want to consider Log4net ( http://logging.apache.org/log4net/index.html ) for configuring log output in different configurations.\n", "Create a Windows Forms Application, and change the output type to Console.\nIt will result in both a console and the form to open.\n\n", "This worked for me, to pipe the output to a file. \nCall the console with \n\ncmd /c \"C:\\path\\to\\your\\application.exe\" > myfile.txt\n\nAdd this code to your application.\n [DllImport(\"kernel32.dll\")]\n static extern bool AttachConsole(UInt32 dwProcessId);\n [DllImport(\"kernel32.dll\")]\n private static extern bool GetFileInformationByHandle(\n SafeFileHandle hFile,\n out BY_HANDLE_FILE_INFORMATION lpFileInformation\n );\n [DllImport(\"kernel32.dll\")]\n private static extern SafeFileHandle GetStdHandle(UInt32 nStdHandle);\n [DllImport(\"kernel32.dll\")]\n private static extern bool SetStdHandle(UInt32 nStdHandle, SafeFileHandle hHandle);\n [DllImport(\"kernel32.dll\")]\n private static extern bool DuplicateHandle(\n IntPtr hSourceProcessHandle,\n SafeFileHandle hSourceHandle,\n IntPtr hTargetProcessHandle,\n out SafeFileHandle lpTargetHandle,\n UInt32 dwDesiredAccess,\n Boolean bInheritHandle,\n UInt32 dwOptions\n );\n private const UInt32 ATTACH_PARENT_PROCESS = 0xFFFFFFFF;\n private const UInt32 STD_OUTPUT_HANDLE = 0xFFFFFFF5;\n private const UInt32 STD_ERROR_HANDLE = 0xFFFFFFF4;\n private const UInt32 DUPLICATE_SAME_ACCESS = 2;\n struct BY_HANDLE_FILE_INFORMATION\n {\n public UInt32 FileAttributes;\n public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;\n public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;\n public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;\n public UInt32 VolumeSerialNumber;\n public UInt32 FileSizeHigh;\n public UInt32 FileSizeLow;\n public UInt32 NumberOfLinks;\n public UInt32 FileIndexHigh;\n public UInt32 FileIndexLow;\n }\n static void InitConsoleHandles()\n {\n SafeFileHandle hStdOut, hStdErr, hStdOutDup, hStdErrDup;\n BY_HANDLE_FILE_INFORMATION bhfi;\n hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);\n hStdErr = GetStdHandle(STD_ERROR_HANDLE);\n // Get current process handle\n IntPtr hProcess = Process.GetCurrentProcess().Handle;\n // Duplicate Stdout handle to save initial value\n DuplicateHandle(hProcess, hStdOut, hProcess, out hStdOutDup,\n 0, true, DUPLICATE_SAME_ACCESS);\n // Duplicate Stderr handle to save initial value\n DuplicateHandle(hProcess, hStdErr, hProcess, out hStdErrDup,\n 0, true, DUPLICATE_SAME_ACCESS);\n // Attach to console window – this may modify the standard handles\n AttachConsole(ATTACH_PARENT_PROCESS);\n // Adjust the standard handles\n if (GetFileInformationByHandle(GetStdHandle(STD_OUTPUT_HANDLE), out bhfi))\n {\n SetStdHandle(STD_OUTPUT_HANDLE, hStdOutDup);\n }\n else\n {\n SetStdHandle(STD_OUTPUT_HANDLE, hStdOut);\n }\n if (GetFileInformationByHandle(GetStdHandle(STD_ERROR_HANDLE), out bhfi))\n {\n SetStdHandle(STD_ERROR_HANDLE, hStdErrDup);\n }\n else\n {\n SetStdHandle(STD_ERROR_HANDLE, hStdErr);\n }\n }\n\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main(string[] args)\n {\n // initialize console handles\n InitConsoleHandles();\n\n if (args.Length != 0)\n {\n\n if (args[0].Equals(\"waitfordebugger\"))\n {\n MessageBox.Show(\"Attach the debugger now\");\n }\n if (args[0].Equals(\"version\"))\n {\n#if DEBUG\n String typeOfBuild = \"d\";\n#else\n String typeOfBuild = \"r\";\n#endif\n String output = typeOfBuild + Assembly.GetExecutingAssembly()\n .GetName().Version.ToString();\n //Just for the fun of it\n Console.Write(output);\n Console.Beep(4000, 100);\n Console.Beep(2000, 100);\n Console.Beep(1000, 100);\n Console.Beep(8000, 100);\n return;\n }\n }\n }\n\nI found this code here: http://www.csharp411.com/console-output-from-winforms-application/\nI thought is was worthy to post it here as well.\n", "There are basically two things that can happen here.\nConsole output\nIt is possible for a winforms program to attach itself to the console window that created it (or to a different console window, or indeed to a new console window if desired). Once attached to the console window Console.WriteLine() etc works as expected. One gotcha to this approach is that the program returns control to the console window immediately, and then carries on writing to it, so the user can also type away in the console window. You can use start with the /wait parameter to handle this I think.\nLink to start Command syntax\nRedirected console output\nThis is when someone pipes the output from your program somewhere else, eg.\nyourapp > file.txt\nAttaching to a console window in this case effectively ignores the piping. To make this work you can call Console.OpenStandardOutput() to get a handle to the stream that the output should be piped to. This only works if the output is piped, so if you want to handle both of the scenarios you need to open the standard output and write to it and attach to the console window. This does mean that the output is sent to the console window and to the pipe but its the best solution I could find. Below the code I use to do this.\n// This always writes to the parent console window and also to a redirected stdout if there is one.\n// It would be better to do the relevant thing (eg write to the redirected file if there is one, otherwise\n// write to the console) but it doesn't seem possible.\npublic class GUIConsoleWriter : IConsoleWriter\n{\n [System.Runtime.InteropServices.DllImport(\"kernel32.dll\")]\n private static extern bool AttachConsole(int dwProcessId);\n\n private const int ATTACH_PARENT_PROCESS = -1;\n\n StreamWriter _stdOutWriter;\n\n // this must be called early in the program\n public GUIConsoleWriter()\n {\n // this needs to happen before attachconsole.\n // If the output is not redirected we still get a valid stream but it doesn't appear to write anywhere\n // I guess it probably does write somewhere, but nowhere I can find out about\n var stdout = Console.OpenStandardOutput();\n _stdOutWriter = new StreamWriter(stdout);\n _stdOutWriter.AutoFlush = true;\n\n AttachConsole(ATTACH_PARENT_PROCESS);\n }\n\n public void WriteLine(string line)\n {\n _stdOutWriter.WriteLine(line);\n Console.WriteLine(line);\n }\n}\n\n", "//From your application set the Console to write to your RichTextkBox \n//object:\nConsole.SetOut(new RichTextBoxWriter(yourRichTextBox));\n\n//To ensure that your RichTextBox object is scrolled down when its text is \n//changed add this event:\nprivate void yourRichTextBox_TextChanged(object sender, EventArgs e)\n{\n yourRichTextBox.SelectionStart = yourRichTextBox.Text.Length;\n yourRichTextBox.ScrollToCaret();\n}\n\npublic delegate void StringArgReturningVoidDelegate(string text);\npublic class RichTextBoxWriter : TextWriter\n{\n private readonly RichTextBox _richTextBox;\n public RichTextBoxWriter(RichTextBox richTexttbox)\n {\n _richTextBox = richTexttbox;\n }\n\n public override void Write(char value)\n {\n SetText(value.ToString());\n }\n\n public override void Write(string value)\n {\n SetText(value);\n }\n\n public override void WriteLine(char value)\n {\n SetText(value + Environment.NewLine);\n }\n\n public override void WriteLine(string value)\n {\n SetText(value + Environment.NewLine);\n }\n\n public override Encoding Encoding => Encoding.ASCII;\n\n //Write to your UI object in thread safe way:\n private void SetText(string text)\n {\n // InvokeRequired required compares the thread ID of the \n // calling thread to the thread ID of the creating thread. \n // If these threads are different, it returns true. \n if (_richTextBox.InvokeRequired)\n {\n var d = new StringArgReturningVoidDelegate(SetText);\n _richTextBox.Invoke(d, text);\n }\n else\n {\n _richTextBox.Text += text;\n }\n }\n}\n\n", "Building on Chaz's answer, in .NET 5 there is a breaking change, so two modifications are required in the project file, i.e. changing OutputType and adding DisableWinExeOutputInference. Example:\n<PropertyGroup>\n <OutputType>Exe</OutputType>\n <TargetFramework>net5.0-windows10.0.17763.0</TargetFramework>\n <UseWindowsForms>true</UseWindowsForms>\n <DisableWinExeOutputInference>true</DisableWinExeOutputInference>\n <Platforms>AnyCPU;x64;x86</Platforms>\n</PropertyGroup>\n\n", "using System;\nusing System.Runtime.InteropServices;\n\nnamespace SomeProject\n{\n class GuiRedirect\n {\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n private static extern bool AttachConsole(int dwProcessId);\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n private static extern IntPtr GetStdHandle(StandardHandle nStdHandle);\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n private static extern bool SetStdHandle(StandardHandle nStdHandle, IntPtr handle);\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n private static extern FileType GetFileType(IntPtr handle);\n\n private enum StandardHandle : uint\n {\n Input = unchecked((uint)-10),\n Output = unchecked((uint)-11),\n Error = unchecked((uint)-12)\n }\n\n private enum FileType : uint\n {\n Unknown = 0x0000,\n Disk = 0x0001,\n Char = 0x0002,\n Pipe = 0x0003\n }\n\n private static bool IsRedirected(IntPtr handle)\n {\n FileType fileType = GetFileType(handle);\n\n return (fileType == FileType.Disk) || (fileType == FileType.Pipe);\n }\n\n public static void Redirect()\n {\n if (IsRedirected(GetStdHandle(StandardHandle.Output)))\n {\n var initialiseOut = Console.Out;\n }\n\n bool errorRedirected = IsRedirected(GetStdHandle(StandardHandle.Error));\n if (errorRedirected)\n {\n var initialiseError = Console.Error;\n }\n\n AttachConsole(-1);\n\n if (!errorRedirected)\n SetStdHandle(StandardHandle.Error, GetStdHandle(StandardHandle.Output));\n }\n}\n\n", "Setting the output type as Console in the project properties will give you a Console application along with the form you created.\n", "if what you want is simple debug output the following works for me. I am using VS 2022 programming in C#\nadd \"using System.Diagnostics\"\nthen\n Debug.WriteLine(\"*****\");\n Debug.WriteLine(...);\n Debug.WriteLine(\"\");\n\nTHe output appears in the debug console of VS2022. There is a lot of stuff there so I use the Debug.WriteLine(\"*****\") and Debug.WriteLine(\"\") to help me find my output. You can also clear the debug output after start up.\nI am still working but running under VS there is no output when running wo debugging\n" ]
[ 197, 188, 83, 20, 17, 14, 12, 7, 6, 3, 3, 0 ]
[ "Why not just leave it as a Window Forms app, and create a simple form to mimic the Console. The form can be made to look just like the black-screened Console, and have it respond directly to key press.\nThen, in the program.cs file, you decide whether you need to Run the main form or the ConsoleForm. For example, I use this approach to capture the command line arguments in the program.cs file. I create the ConsoleForm, initially hide it, then pass the command line strings to an AddCommand function in it, which displays the allowed commands. Finally, if the user gave the -h or -? command, I call the .Show on the ConsoleForm and when the user hits any key on it, I shut down the program. If the user doesn't give the -? command, I close the hidden ConsoleForm and Run the main form.\n", "You can any time switch between type of applications, to console or windows. So, you will not write special logic to see the stdout. Also, when running application in debugger, you will see all the stdout in output window. You might also just add a breakpoint, and in breakpoint properties change \"When Hit...\", you can output any messages, and variables. Also you can check/uncheck \"Continue execution\", and your breakpoint will become square shaped. So, the breakpoint messages without changhing anything in the application in the debug output window.\n" ]
[ -1, -3 ]
[ "c#", "compilation", "console_application", "winforms" ]
stackoverflow_0004362111_c#_compilation_console_application_winforms.txt
Q: Reverse proxy on Nginx, redirect all http requests to https with specific port number I have two nodejs app running on same NGINX server with different ports. eg. frontend.js on port 3000 accessible on http://example.com:3000 backend.js on port 3001 accessible on http://example.com:3001 Even a website is live on same server too :) with same domain which is accessible using http://example.com (On default port i.e :80) Now I would like to make sure that all these 3 url accepts only https. In case any request received for non-https(i.e http) then it should be redirected to respective "https url". I have tried with multiple solution provided over internet including stackoverflow with some tweak but haven't succeed yet. Belows are the solution I've tried. Both the tried solution did NOT worked including dozens of other. Most probably because may be I couldn't grab it well as I am totally new for Reverse Pxoxy setup of Nginx. Below are the result of my tried solutions. http://example.com redirects to https version http://example.com:3000 NOT redirects to https version & shows error(SSL_ERROR_RX_RECORD_TOO_LONG) if tried opening https version directly http://example.com:3001 NOT redirects to https version & shows error(SSL_ERROR_RX_RECORD_TOO_LONG) if tried opening https version directly Full error shown in Firefox Web Browser: Secure Connection Failed An error occurred during a connection to byteglance.com:3003. SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG Solution 1: Tried to redirect all traffic to https server { listen 80; #listen [::]:80; server_name example.com; index index.html index.htm index.php default.html default.htm default.php; root /home/example.com; #include rewrite/none.conf; #error_page 404 /404.html; # Deny access to PHP files in specific directory #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; } include enable-php.conf; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /.well-known { allow all; } location ~ /\. { deny all; } location / { return 301 https://$host$request_uri; } access_log off; } server { listen 443 ssl http2; #listen [::]:443 ssl http2; server_name example.com; index index.html index.htm index.php default.html default.htm default.php; root /home/example.com; ssl_certificate /usr/local/nginx/conf/ssl/example.com/fullchain.cer; ssl_certificate_key /usr/local/nginx/conf/ssl/example.com/example.com.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ssl_ciphers "TLS13-AES-256-GCM-SHA384:TLS13-.....CHACHA20-RSA+3DES:!MD5"; ssl_session_cache builtin:1000 shared:SSL:10m; # openssl dhparam -out /usr/local/nginx/conf/ssl/dhparam.pem 2048 ssl_dhparam /usr/local/nginx/conf/ssl/dhparam.pem; include rewrite/none.conf; #error_page 404 /404.html; # Deny access to PHP files in specific directory #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; } include enable-php.conf; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /.well-known { allow all; } location ~ /\. { deny all; } access_log off; } Solution 2: Tried using Nginx Reverse Proxy to achieve the solution server { listen 80; #listen [::]:80; server_name example.com; index index.html index.htm index.php default.html default.htm default.php; root /home/example.com; #include rewrite/none.conf; #error_page 404 /404.html; # Deny access to PHP files in specific directory #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; } include enable-php.conf; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /.well-known { allow all; } location ~ /\. { deny all; } location / { return 301 https://$host$request_uri; } access_log off; } server { listen 443 ssl http2; #listen [::]:443 ssl http2; server_name example.com; index index.html index.htm index.php default.html default.htm default.php; root /home/example.com; ssl_certificate /usr/local/nginx/conf/ssl/example.com/fullchain.cer; ssl_certificate_key /usr/local/nginx/conf/ssl/example.com/example.com.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ssl_ciphers "TLS13-AES-256-GCM-SHA384:TLS13-.....CHACHA20-RSA+3DES:!MD5"; ssl_session_cache builtin:1000 shared:SSL:10m; # openssl dhparam -out /usr/local/nginx/conf/ssl/dhparam.pem 2048 ssl_dhparam /usr/local/nginx/conf/ssl/dhparam.pem; include rewrite/none.conf; #error_page 404 /404.html; # Deny access to PHP files in specific directory #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; } include enable-php.conf; location ~* \.(js)$ { proxy_pass http://localhost:3000 proxy_http_version 1.1 proxy_cache_bypass $http_upgrade proxy_set_header Upgrade $http_upgrade proxy_set_header Connection β€œupgrade” proxy_set_header Host $host proxy_set_header X-Real-IP $remote_addr proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for proxy_set_header X-Forwarded-Proto $scheme proxy_set_header X-Forwarded-Host $host proxy_set_header X-Forwarded-Port $server_port } location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /.well-known { allow all; } location ~ /\. { deny all; } access_log off; } Could anyone please look at my configuration and correct what I'm doing wrong? A: It sounds like the SSL certificate is not set up correctly for the domains running on ports 3000 and 3001. In order to serve HTTPS traffic on a specific port, you will need to make sure that the SSL certificate covers that domain and port. For example, if your SSL certificate only covers the domain example.com, it will not be valid for the domain example.com:3000 or example.com:3001. One way to fix this issue would be to generate a new SSL certificate that covers all of the domains and ports that you want to serve HTTPS traffic on. You can use a service like Let's Encrypt to generate a free SSL certificate that covers multiple domains. Once you have the new SSL certificate, you will need to update your NGINX configuration to use the new certificate. In the server block that listens on port 443 (the HTTPS port), you will need to update the ssl_certificate and ssl_certificate_key directives to point to the new SSL certificate and its private key. After you have updated the NGINX configuration and reloaded the server, all HTTPS traffic on the domains covered by the SSL certificate should be served correctly.
Reverse proxy on Nginx, redirect all http requests to https with specific port number
I have two nodejs app running on same NGINX server with different ports. eg. frontend.js on port 3000 accessible on http://example.com:3000 backend.js on port 3001 accessible on http://example.com:3001 Even a website is live on same server too :) with same domain which is accessible using http://example.com (On default port i.e :80) Now I would like to make sure that all these 3 url accepts only https. In case any request received for non-https(i.e http) then it should be redirected to respective "https url". I have tried with multiple solution provided over internet including stackoverflow with some tweak but haven't succeed yet. Belows are the solution I've tried. Both the tried solution did NOT worked including dozens of other. Most probably because may be I couldn't grab it well as I am totally new for Reverse Pxoxy setup of Nginx. Below are the result of my tried solutions. http://example.com redirects to https version http://example.com:3000 NOT redirects to https version & shows error(SSL_ERROR_RX_RECORD_TOO_LONG) if tried opening https version directly http://example.com:3001 NOT redirects to https version & shows error(SSL_ERROR_RX_RECORD_TOO_LONG) if tried opening https version directly Full error shown in Firefox Web Browser: Secure Connection Failed An error occurred during a connection to byteglance.com:3003. SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG Solution 1: Tried to redirect all traffic to https server { listen 80; #listen [::]:80; server_name example.com; index index.html index.htm index.php default.html default.htm default.php; root /home/example.com; #include rewrite/none.conf; #error_page 404 /404.html; # Deny access to PHP files in specific directory #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; } include enable-php.conf; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /.well-known { allow all; } location ~ /\. { deny all; } location / { return 301 https://$host$request_uri; } access_log off; } server { listen 443 ssl http2; #listen [::]:443 ssl http2; server_name example.com; index index.html index.htm index.php default.html default.htm default.php; root /home/example.com; ssl_certificate /usr/local/nginx/conf/ssl/example.com/fullchain.cer; ssl_certificate_key /usr/local/nginx/conf/ssl/example.com/example.com.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ssl_ciphers "TLS13-AES-256-GCM-SHA384:TLS13-.....CHACHA20-RSA+3DES:!MD5"; ssl_session_cache builtin:1000 shared:SSL:10m; # openssl dhparam -out /usr/local/nginx/conf/ssl/dhparam.pem 2048 ssl_dhparam /usr/local/nginx/conf/ssl/dhparam.pem; include rewrite/none.conf; #error_page 404 /404.html; # Deny access to PHP files in specific directory #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; } include enable-php.conf; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /.well-known { allow all; } location ~ /\. { deny all; } access_log off; } Solution 2: Tried using Nginx Reverse Proxy to achieve the solution server { listen 80; #listen [::]:80; server_name example.com; index index.html index.htm index.php default.html default.htm default.php; root /home/example.com; #include rewrite/none.conf; #error_page 404 /404.html; # Deny access to PHP files in specific directory #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; } include enable-php.conf; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /.well-known { allow all; } location ~ /\. { deny all; } location / { return 301 https://$host$request_uri; } access_log off; } server { listen 443 ssl http2; #listen [::]:443 ssl http2; server_name example.com; index index.html index.htm index.php default.html default.htm default.php; root /home/example.com; ssl_certificate /usr/local/nginx/conf/ssl/example.com/fullchain.cer; ssl_certificate_key /usr/local/nginx/conf/ssl/example.com/example.com.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ssl_ciphers "TLS13-AES-256-GCM-SHA384:TLS13-.....CHACHA20-RSA+3DES:!MD5"; ssl_session_cache builtin:1000 shared:SSL:10m; # openssl dhparam -out /usr/local/nginx/conf/ssl/dhparam.pem 2048 ssl_dhparam /usr/local/nginx/conf/ssl/dhparam.pem; include rewrite/none.conf; #error_page 404 /404.html; # Deny access to PHP files in specific directory #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; } include enable-php.conf; location ~* \.(js)$ { proxy_pass http://localhost:3000 proxy_http_version 1.1 proxy_cache_bypass $http_upgrade proxy_set_header Upgrade $http_upgrade proxy_set_header Connection β€œupgrade” proxy_set_header Host $host proxy_set_header X-Real-IP $remote_addr proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for proxy_set_header X-Forwarded-Proto $scheme proxy_set_header X-Forwarded-Host $host proxy_set_header X-Forwarded-Port $server_port } location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /.well-known { allow all; } location ~ /\. { deny all; } access_log off; } Could anyone please look at my configuration and correct what I'm doing wrong?
[ "It sounds like the SSL certificate is not set up correctly for the domains running on ports 3000 and 3001. In order to serve HTTPS traffic on a specific port, you will need to make sure that the SSL certificate covers that domain and port. For example, if your SSL certificate only covers the domain example.com, it will not be valid for the domain example.com:3000 or example.com:3001.\nOne way to fix this issue would be to generate a new SSL certificate that covers all of the domains and ports that you want to serve HTTPS traffic on. You can use a service like Let's Encrypt to generate a free SSL certificate that covers multiple domains.\nOnce you have the new SSL certificate, you will need to update your NGINX configuration to use the new certificate. In the server block that listens on port 443 (the HTTPS port), you will need to update the ssl_certificate and ssl_certificate_key directives to point to the new SSL certificate and its private key.\nAfter you have updated the NGINX configuration and reloaded the server, all HTTPS traffic on the domains covered by the SSL certificate should be served correctly.\n" ]
[ 0 ]
[]
[]
[ "nginx_config", "nginx_location", "nginx_reverse_proxy", "node.js", "reverse_proxy" ]
stackoverflow_0074670049_nginx_config_nginx_location_nginx_reverse_proxy_node.js_reverse_proxy.txt
Q: How can I render a SwiftUI MapAnnotation with a real world size? I want to render circles etc on a SwiftUI Map with a radius specified in metres representing a size in the real world. Android Jetpack Compose's GoogleMap composable has functions for rendering circles, polygons and lines using real world sizes, but in SwiftUI the only facility I can find is MapAnnotation. It can render any View at a map coordinate, so for many use-cases it's easier to use than Compose, but the content's size can only be specified in device pixels, and I can't see any way to read a scale factor from the Map. Its coordinateRegion is a Binding, so does it write back to that with values that accurately represent the limits of the screen? If so, I could work with that. Or am I going to have to embed a MKMapView instead? A: While the MapAnnotation view in SwiftUI does allow you to specify the size of the annotation content in device pixels, it does not provide a way to specify the size in real-world units. One option you could consider is using the MKMapView class from the MapKit framework to display the map and rendering your circles and other shapes on top of it using MapAnnotation. The MKMapView class does provide methods for rendering overlays, such as MKCircle, which allows you to specify the radius in real-world units. Another option would be to use the MapView class from the MapKit framework, which provides a similar interface to MKMapView but uses SwiftUI views for its annotations and overlays. This would allow you to specify the size of your annotations and overlays using the same coordinate system as the MapView itself, which supports specifying sizes in real-world units.
How can I render a SwiftUI MapAnnotation with a real world size?
I want to render circles etc on a SwiftUI Map with a radius specified in metres representing a size in the real world. Android Jetpack Compose's GoogleMap composable has functions for rendering circles, polygons and lines using real world sizes, but in SwiftUI the only facility I can find is MapAnnotation. It can render any View at a map coordinate, so for many use-cases it's easier to use than Compose, but the content's size can only be specified in device pixels, and I can't see any way to read a scale factor from the Map. Its coordinateRegion is a Binding, so does it write back to that with values that accurately represent the limits of the screen? If so, I could work with that. Or am I going to have to embed a MKMapView instead?
[ "While the MapAnnotation view in SwiftUI does allow you to specify the size of the annotation content in device pixels, it does not provide a way to specify the size in real-world units.\nOne option you could consider is using the MKMapView class from the MapKit framework to display the map and rendering your circles and other shapes on top of it using MapAnnotation. The MKMapView class does provide methods for rendering overlays, such as MKCircle, which allows you to specify the radius in real-world units.\nAnother option would be to use the MapView class from the MapKit framework, which provides a similar interface to MKMapView but uses SwiftUI views for its annotations and overlays. This would allow you to specify the size of your annotations and overlays using the same coordinate system as the MapView itself, which supports specifying sizes in real-world units.\n" ]
[ 0 ]
[]
[]
[ "mapkit", "swiftui" ]
stackoverflow_0074670447_mapkit_swiftui.txt
Q: What could be causing a System.TypeLoadException? I'm developing, with VS2008 using C#, an application for Honeywell Dolphin 6100, a mobile computer with a barcode scanner that uses Windows CE 5.0 like OS. I want to add a functionality that can send files from the local device to the distant server. I found the library "Tamir.SharpSSH" which can guarantee this. I tested the code on a console application and on normal windows forms application and it works perfectly. But when I tried to use the same code on the winCE device, I get a TypeLoadException and I have the error message: Could not load type 'Tamir.SharpSsh.SshTransferProtocolBase' from assembly 'Tamir.SharpSSH, Version=1.1.1.13, Culture=neutral, PublicKeyToken=null'. the code that I'm use is like below : SshTransferProtocolBase sshCp = new Scp(Tools.GlobalVarMeth.hostName, Tools.GlobalVarMeth.serverUserName); sshCp.Password = Tools.GlobalVarMeth.serverUserpassword; sshCp.Connect(); string localFile = Tools.GlobalVarMeth.applicationPath + "/" + fileName + ".csv"; string remoteFile = Tools.GlobalVarMeth.serverRemoteFilePath + "/" + fileName + ".csv"; sshCp.Put(localFile, remoteFile); sshCp.Close(); Any one have any idea on this ? I will be really grateful !!! A: It could be any number of things. Likely causes are: The assembly cannot be found An assembly that your assembly depends upon cannot be found The assembly is found but the type isn't in it The type's static constructor throws an exception Your best bet is to use the Fusion log viewer to help diagnose it. Documentation is here: http://msdn.microsoft.com/en-us/library/e74a18c4(v=vs.110).aspx (FYI "Fusion" was the code name of the team that designed the assembly loading system; it is somewhat unfortunate that the code name ended up in the file name of the shipped product. The thing should have been called "AssemblyBindingLogViewer.exe" or some such thing.) A: The answer of Eric Lippert perfectly describes the situation. I just want to add a quick answer about a case which is usually not covered by help pages regarding this exception. I've created a quick & dirty test project for some open source stuff (Akka.Net, to name it) and I name the project itself "Akka". It perfectly builds, but at startup it throws it type load exception regarding a class in Akka.dll. This is just because my executable (akka.exe) and the reference (akka.dll) have the same name. It took me a few minutes to figure this (I've began by things such as copy local, target platform, exact version... etc). It's something very dumb but not forcibly the first thing which you will think (especially since I used nuget for dependancies), so I thought it could be interesting to share it : you will encounter TypeLoadException if your EXE and a dependancy have the same name. A: I don't know how I managed this, but for some reason I had an old version of the DLL in GAC (Global Assembly Cache). Try looking for an old assembly there and remove it. A: This could be caused by any number of things, MSDN has it said as: TypeLoadException is thrown when the common language runtime cannot find the assembly, the type within the assembly, or cannot load the type. So it's clear that a type can't be found, either the assembly is missing, the type is missing or there's a clash between runtime configurations. Sometimes the issue can arise because the assembly you're referencing is a different platform type (32bit / 64bit etc) than the one you're consuming from. I would recommend catching the exception and examining it in more detail to identify what it's having trouble with. Further to my previous information Sometimes I've seen this issue arise because (for one reason or another) a referenced assembly can't actually be resolved, even though it's referenced and loaded. I typically see this when AppDomain boundaries are involved. One way I've found that sometimes resolves the issue (but only if the assembly is already in the AppDomain) is this code snippet: AppDomain.CurrentDomain.AssemblyResolve += (s, e) => { return AppDomain.CurrentDomain.GetAssemblies() .SingleOrDefault(asm => asm.FullName == e.Name); } Like I said, I see this issue when AppDomains get involved and this does seem to solve it when the assembly is indeed already referenced and loaded. I've no idea why the framework fails to resolve the reference itself. A: You can get loader log files out of the .NET Compact Framework by enabling some settings in the registry. The Power Toys for .NET Compact Framework include a tool called NETCFLogging, which sets the registry values for you. The registry values are documented here: http://msdn.microsoft.com/en-us/library/ms229650(v=VS.90).aspx A: In my case the problem turned out to be a namespace conflict. I had multiple startup projects in the solution whose Main() was in class Program and I discovered that I had multiple Program classes defined in the same namespace, albeit in different assemblies. A: In my case problem was that I had two projects that used the same libraries in one solution. I've updated DLLs only in first project. So when I built solution, second project its override DLLs from first project(project build order). Example: Solution: --MainProject ------MyDll v5.3.2.0 --Prototype ------MyDll v5.0.0.0 Problem gone after update DLLs in second project. A: Make sure the names (namespaces, class names, etc) are what they are supposed to be. I got this error when I had to start over on my project and I copied the contents of my class from a template and failed to change the class name from "Template Class" to the correct name (it was supposed to match the project name). A: the typeName string parameter must be a fully qualified type name For instance : Activator.CreateInstance("assemblyFullName","namespace.typename") A: My TypeLoadException was caused by a struct with FieldOffset(1). Could not load type '...' because it contains an object field at offset 1 that is incorrectly aligned or overlapped by a non-object field with a struct definition starting with [StructLayout(LayoutKind.Explicit, Pack = 1)] unsafe struct Metadata { [FieldOffset(0)] public readonly byte Length; [FieldOffset(1)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)] public string ApplicationName; ... A: In my case, the issue was caused by the methods that were part of the new version of the software but when a previous version was loaded those methods simply did not exists. My solution was to create a separate class with all the methods that are available in one of the versions and in the main class I only call that separate class after checking the version. If you are using Revit API, you can do so with: application.ControlledApplication.VersionNumber
What could be causing a System.TypeLoadException?
I'm developing, with VS2008 using C#, an application for Honeywell Dolphin 6100, a mobile computer with a barcode scanner that uses Windows CE 5.0 like OS. I want to add a functionality that can send files from the local device to the distant server. I found the library "Tamir.SharpSSH" which can guarantee this. I tested the code on a console application and on normal windows forms application and it works perfectly. But when I tried to use the same code on the winCE device, I get a TypeLoadException and I have the error message: Could not load type 'Tamir.SharpSsh.SshTransferProtocolBase' from assembly 'Tamir.SharpSSH, Version=1.1.1.13, Culture=neutral, PublicKeyToken=null'. the code that I'm use is like below : SshTransferProtocolBase sshCp = new Scp(Tools.GlobalVarMeth.hostName, Tools.GlobalVarMeth.serverUserName); sshCp.Password = Tools.GlobalVarMeth.serverUserpassword; sshCp.Connect(); string localFile = Tools.GlobalVarMeth.applicationPath + "/" + fileName + ".csv"; string remoteFile = Tools.GlobalVarMeth.serverRemoteFilePath + "/" + fileName + ".csv"; sshCp.Put(localFile, remoteFile); sshCp.Close(); Any one have any idea on this ? I will be really grateful !!!
[ "It could be any number of things. Likely causes are:\n\nThe assembly cannot be found\nAn assembly that your assembly depends upon cannot be found\nThe assembly is found but the type isn't in it\nThe type's static constructor throws an exception\n\nYour best bet is to use the Fusion log viewer to help diagnose it. Documentation is here:\nhttp://msdn.microsoft.com/en-us/library/e74a18c4(v=vs.110).aspx\n(FYI \"Fusion\" was the code name of the team that designed the assembly loading system; it is somewhat unfortunate that the code name ended up in the file name of the shipped product. The thing should have been called \"AssemblyBindingLogViewer.exe\" or some such thing.)\n", "The answer of Eric Lippert perfectly describes the situation. \nI just want to add a quick answer about a case which is usually not covered by help pages regarding this exception.\nI've created a quick & dirty test project for some open source stuff (Akka.Net, to name it) and I name the project itself \"Akka\". \nIt perfectly builds, but at startup it throws it type load exception regarding a class in Akka.dll.\nThis is just because my executable (akka.exe) and the reference (akka.dll) have the same name. It took me a few minutes to figure this (I've began by things such as copy local, target platform, exact version... etc). \nIt's something very dumb but not forcibly the first thing which you will think (especially since I used nuget for dependancies), so I thought it could be interesting to share it : you will encounter TypeLoadException if your EXE and a dependancy have the same name.\n", "I don't know how I managed this, but for some reason I had an old version of the DLL in GAC (Global Assembly Cache). Try looking for an old assembly there and remove it.\n", "This could be caused by any number of things, MSDN has it said as:\n\nTypeLoadException is thrown when the common language runtime cannot find the assembly, the type within the assembly, or cannot load the type.\n\nSo it's clear that a type can't be found, either the assembly is missing, the type is missing or there's a clash between runtime configurations.\nSometimes the issue can arise because the assembly you're referencing is a different platform type (32bit / 64bit etc) than the one you're consuming from.\nI would recommend catching the exception and examining it in more detail to identify what it's having trouble with.\n\nFurther to my previous information\nSometimes I've seen this issue arise because (for one reason or another) a referenced assembly can't actually be resolved, even though it's referenced and loaded.\nI typically see this when AppDomain boundaries are involved.\nOne way I've found that sometimes resolves the issue (but only if the assembly is already in the AppDomain) is this code snippet:\nAppDomain.CurrentDomain.AssemblyResolve += (s, e) =>\n{\n return AppDomain.CurrentDomain.GetAssemblies()\n .SingleOrDefault(asm => asm.FullName == e.Name);\n}\n\nLike I said, I see this issue when AppDomains get involved and this does seem to solve it when the assembly is indeed already referenced and loaded. I've no idea why the framework fails to resolve the reference itself.\n", "You can get loader log files out of the .NET Compact Framework by enabling some settings in the registry. The Power Toys for .NET Compact Framework include a tool called NETCFLogging, which sets the registry values for you.\nThe registry values are documented here:\nhttp://msdn.microsoft.com/en-us/library/ms229650(v=VS.90).aspx\n", "In my case the problem turned out to be a namespace conflict. I had multiple startup projects in the solution whose Main() was in class Program and I discovered that I had multiple Program classes defined in the same namespace, albeit in different assemblies.\n", "In my case problem was that I had two projects that used the same libraries in one solution. I've updated DLLs only in first project.\nSo when I built solution, second project its override DLLs from first project(project build order).\n\nExample:\nSolution:\n--MainProject\n------MyDll v5.3.2.0\n--Prototype\n------MyDll v5.0.0.0\n\nProblem gone after update DLLs in second project.\n", "Make sure the names (namespaces, class names, etc) are what they are supposed to be. I got this error when I had to start over on my project and I copied the contents of my class from a template and failed to change the class name from \"Template Class\" to the correct name (it was supposed to match the project name).\n", "the typeName string parameter must be a fully qualified type name\nFor instance :\nActivator.CreateInstance(\"assemblyFullName\",\"namespace.typename\")\n", "My TypeLoadException was caused by a struct with FieldOffset(1).\n\nCould not load type '...' because it contains an object field at offset 1 that is incorrectly aligned or overlapped by a non-object field\n\nwith a struct definition starting with\n[StructLayout(LayoutKind.Explicit, Pack = 1)]\nunsafe struct Metadata\n{\n [FieldOffset(0)]\n public readonly byte Length;\n [FieldOffset(1)]\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)]\n public string ApplicationName;\n...\n\n", "In my case, the issue was caused by the methods that were part of the new version of the software but when a previous version was loaded those methods simply did not exists.\nMy solution was to create a separate class with all the methods that are available in one of the versions and in the main class I only call that separate class after checking the version. If you are using Revit API, you can do so with:\n application.ControlledApplication.VersionNumber\n\n" ]
[ 45, 26, 5, 3, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "c#", "smart_device", "ssh", "visual_studio", "windows_ce" ]
stackoverflow_0016086178_c#_smart_device_ssh_visual_studio_windows_ce.txt
Q: Creating Oracle APEX Dynamic Menu via oracle table I am trying to add dynamic menu in Oracle APEX through oracle table using sql query. It will have n levels of menu (Menu will have sub-menu, sub menu will have further menu under it), should not be restricted to any number of nodes. I have already created the dynamic navigation menu bar with oracle table and hierarchical query but the sequence is not coming correct. Could you please help me with below to achieve this - Table structure Sample table data SQL Query I am attaching a sample snapshot to show what I am trying to achieve. Nested Menu Sample Please Note - I am not looking for dynamic menu which is fully Javascript driven. A: To create a dynamic menu in Oracle APEX using an Oracle table and apply a hierarchical query to retrieve the data from the table and then use it to populate the menu items. A common approach is to have a parent-child relationship in the table, where each row has a foreign key reference to its parent row. Here is an example of a table structure that you can use: CREATE TABLE menu_items ( id NUMBER PRIMARY KEY, // uniquely identifies each menu item parent_id NUMBER, // references the `id` of the parent menu item title VARCHAR2(255), link VARCHAR2(255), sequence NUMBER // specifies the order of displaying menu items ); Let's populate this table with sample data: INSERT INTO menu_items (id, parent_id, title, link, sequence) VALUES (1, NULL, 'Home', '/home', 1); INSERT INTO menu_items (id, parent_id, title, link, sequence) VALUES (2, NULL, 'About', '/about', 2); INSERT INTO menu_items (id, parent_id, title, link, sequence) VALUES (3, 2, 'Our Team', '/about/team', 1); INSERT INTO menu_items (id, parent_id, title, link, sequence) VALUES (4, 2, 'Our History', '/about/history', 2); INSERT INTO menu_items (id, parent_id, title, link, sequence) VALUES (5, NULL, 'Contact', '/contact', 3); This will create a top-level menu with three items: "Home", "About", and "Contact". The "About" menu will have two sub-items: "Our Team" and "Our History". To retrieve the data from this table and use it to populate the menu in Oracle APEX, you can use a hierarchical query: SELECT LEVEL AS "Level", id AS "ID", parent_id AS "Parent ID", title AS "Title", link AS "Link", sequence AS "Sequence" FROM menu_items START WITH parent_id IS NULL CONNECT BY PRIOR id = parent_id ORDER SIBLINGS BY sequence; This query uses the CONNECT BY and START WITH clauses to traverse the hierarchy of menu items and the ORDER SIBLINGS BY clause to order the menu items at each level by the sequence column. Use the result of this query to populate the menu in Oracle APEX. For example, you can use the LEVEL column to determine the level of each menu item and create the necessary indentation in the menu, and use the title and link columns to display the text and URL for each menu item.
Creating Oracle APEX Dynamic Menu via oracle table
I am trying to add dynamic menu in Oracle APEX through oracle table using sql query. It will have n levels of menu (Menu will have sub-menu, sub menu will have further menu under it), should not be restricted to any number of nodes. I have already created the dynamic navigation menu bar with oracle table and hierarchical query but the sequence is not coming correct. Could you please help me with below to achieve this - Table structure Sample table data SQL Query I am attaching a sample snapshot to show what I am trying to achieve. Nested Menu Sample Please Note - I am not looking for dynamic menu which is fully Javascript driven.
[ "To create a dynamic menu in Oracle APEX using an Oracle table and apply a hierarchical query to retrieve the data from the table and then use it to populate the menu items. A common approach is to have a parent-child relationship in the table, where each row has a foreign key reference to its parent row.\nHere is an example of a table structure that you can use:\nCREATE TABLE menu_items (\n id NUMBER PRIMARY KEY, // uniquely identifies each menu item\n parent_id NUMBER, // references the `id` of the parent menu item\n title VARCHAR2(255), \n link VARCHAR2(255), \n sequence NUMBER // specifies the order of displaying menu items \n);\n\nLet's populate this table with sample data:\nINSERT INTO menu_items (id, parent_id, title, link, sequence) VALUES (1, NULL, 'Home', '/home', 1);\nINSERT INTO menu_items (id, parent_id, title, link, sequence) VALUES (2, NULL, 'About', '/about', 2);\nINSERT INTO menu_items (id, parent_id, title, link, sequence) VALUES (3, 2, 'Our Team', '/about/team', 1);\nINSERT INTO menu_items (id, parent_id, title, link, sequence) VALUES (4, 2, 'Our History', '/about/history', 2);\nINSERT INTO menu_items (id, parent_id, title, link, sequence) VALUES (5, NULL, 'Contact', '/contact', 3);\n\nThis will create a top-level menu with three items: \"Home\", \"About\", and \"Contact\". The \"About\" menu will have two sub-items: \"Our Team\" and \"Our History\".\nTo retrieve the data from this table and use it to populate the menu in Oracle APEX, you can use a hierarchical query:\nSELECT\n LEVEL AS \"Level\",\n id AS \"ID\",\n parent_id AS \"Parent ID\",\n title AS \"Title\",\n link AS \"Link\",\n sequence AS \"Sequence\"\nFROM menu_items\nSTART WITH parent_id IS NULL\nCONNECT BY PRIOR id = parent_id\nORDER SIBLINGS BY sequence;\n\nThis query uses the CONNECT BY and START WITH clauses to traverse the hierarchy of menu items and the ORDER SIBLINGS BY clause to order the menu items at each level by the sequence column.\nUse the result of this query to populate the menu in Oracle APEX. For example, you can use the LEVEL column to determine the level of each menu item and create the necessary indentation in the menu, and use the title and link columns to display the text and URL for each menu item.\n" ]
[ 1 ]
[]
[]
[ "database", "oracle", "oracle_apex", "plsql", "sql" ]
stackoverflow_0074664387_database_oracle_oracle_apex_plsql_sql.txt
Q: How can I make permanent changes to a list using a function in python tkinter? I want to enter an item into the entry box press a button and add the item to the list changing the list permanently, however I cannot seem to make a permanent change to the list. The program always returns "[]" and never the updated list. Is there a way I can do this? I have tested and there are no issues involving extracting text from the entry box and adding It to the list. The only problem is making the change permanent. here is the code: from tkinter import * window = Tk() names = [] ent = Entry(window) ent.pack() def change(): names.append(ent.get()) btn = Button (window, command = change ) btn.pack() print(names) window.mainloop() why is the response always "[]" and not the updated list A: It is printing an empty list because the list is empty. You are not printing after appending from tkinter import * window = Tk() names = [] ent = Entry(window) ent.pack() def change(): names.append(ent.get()) print(names) btn = Button (window, command = change ) btn.pack() #print(names) window.mainloop() A: While mapperx's answer is correct, I think what you're trying to do is to persist the list, so that when you close the program and open it again, the names are still there. If this is what you intend, you need to store the list (or its content) into a file before closing the program. You can do this using pickle. from tkinter import * import pickle window = Tk() # Create list from file (if no file exists, create empty list) try: with open('names.pickle', 'rb') as f: names = pickle.load(f) except: names = [] ent = Entry(window) ent.pack() def change(): names.append(ent.get()) btn = Button (window, command = change ) btn.pack() print(names) def onClose(): with open('names.pickle', 'wb') as f: pickle.dump(names, f) # Store (persist) the list window.destroy() # This will call "onClose" before closing the window window.protocol("WM_DELETE_WINDOW", onClose) window.mainloop() You can change names.pickle to any filename you want
How can I make permanent changes to a list using a function in python tkinter?
I want to enter an item into the entry box press a button and add the item to the list changing the list permanently, however I cannot seem to make a permanent change to the list. The program always returns "[]" and never the updated list. Is there a way I can do this? I have tested and there are no issues involving extracting text from the entry box and adding It to the list. The only problem is making the change permanent. here is the code: from tkinter import * window = Tk() names = [] ent = Entry(window) ent.pack() def change(): names.append(ent.get()) btn = Button (window, command = change ) btn.pack() print(names) window.mainloop() why is the response always "[]" and not the updated list
[ "It is printing an empty list because the list is empty. You are not printing after appending\nfrom tkinter import *\n\nwindow = Tk()\n\nnames = []\n\nent = Entry(window) ent.pack()\n\ndef change():\n names.append(ent.get())\n print(names)\n\nbtn = Button (window, command = change ) btn.pack()\n\n#print(names)\n\nwindow.mainloop()\n\n", "While mapperx's answer is correct, I think what you're trying to do is to persist the list, so that when you close the program and open it again, the names are still there. If this is what you intend, you need to store the list (or its content) into a file before closing the program. You can do this using pickle. \nfrom tkinter import *\nimport pickle\n\nwindow = Tk()\n\n# Create list from file (if no file exists, create empty list)\ntry:\n with open('names.pickle', 'rb') as f: names = pickle.load(f)\nexcept: names = []\n\nent = Entry(window)\nent.pack()\n\ndef change():\n names.append(ent.get())\n\nbtn = Button (window, command = change )\nbtn.pack()\n\nprint(names)\n\ndef onClose():\n with open('names.pickle', 'wb') as f: pickle.dump(names, f) # Store (persist) the list\n window.destroy()\n\n# This will call \"onClose\" before closing the window\nwindow.protocol(\"WM_DELETE_WINDOW\", onClose)\nwindow.mainloop()\n\nYou can change names.pickle to any filename you want\n" ]
[ 1, 0 ]
[]
[]
[ "list", "python", "tkinter" ]
stackoverflow_0074670268_list_python_tkinter.txt
Q: Wordpress ACF fields not showing or letting me update them on POST request I am trying to create an application. I created a custom post type and added custom fields using ACF. When I try to post to save the data, it doesn't save it and when I create one inside wordpress and request it using it's ID, it doesn't show the data in the response. Below is the JSON (I tried with acf, fields and with leaving everything outside of an object), response and URL. { "title": "title 7", "acf": { "feeling": "ok", "feeling_at_the_moment": "relieved", "what_have_you_been_doing": "chores", "cognitive_distortions": "", "challenge": "", "interpretation": "", "feeling_now": "", "email": "gmail.com" } } { "id": 4392, "date": "2022-12-03T19:49:14", "date_gmt": "2022-12-03T19:49:14", "guid": { "rendered": "/?post_type=mood_tracker&p=4392", "raw": "/?post_type=mood_tracker&p=4392" }, "modified": "2022-12-03T19:49:14", "modified_gmt": "2022-12-03T19:49:14", "password": "", "slug": "", "status": "draft", "type": "mood_tracker", "link": "/?post_type=mood_tracker&p=4392", "title": { "raw": "title 7", "rendered": "title 7" }, "content": { "raw": "", "rendered": "", "protected": false, "block_version": 0 }, "featured_media": 0, "template": "", "meta": { "_mi_skip_tracking": false }, "permalink_template": "/mood_tracker/%pagename%/", "generated_slug": "title-7", "_links": { "self": [ { "href": "/wp-json/wp/v2/mood_tracker/4392" } ], "collection": [ { "href": "/wp-json/wp/v2/mood_tracker" } ], "about": [ { "href": "/wp-json/wp/v2/types/mood_tracker" } ], "wp:attachment": [ { "href": "/wp-json/wp/v2/media?parent=4392" } ], "wp:action-publish": [ { "href": "/wp-json/wp/v2/mood_tracker/4392" } ], "wp:action-unfiltered-html": [ { "href": "/wp-json/wp/v2/mood_tracker/4392" } ], "curies": [ { "name": "wp", "href": "https://api.w.org/{rel}", "templated": true } ] } } https://link.com/wp-json/wp/v2/mood_tracker
Wordpress ACF fields not showing or letting me update them on POST request
I am trying to create an application. I created a custom post type and added custom fields using ACF. When I try to post to save the data, it doesn't save it and when I create one inside wordpress and request it using it's ID, it doesn't show the data in the response. Below is the JSON (I tried with acf, fields and with leaving everything outside of an object), response and URL. { "title": "title 7", "acf": { "feeling": "ok", "feeling_at_the_moment": "relieved", "what_have_you_been_doing": "chores", "cognitive_distortions": "", "challenge": "", "interpretation": "", "feeling_now": "", "email": "gmail.com" } } { "id": 4392, "date": "2022-12-03T19:49:14", "date_gmt": "2022-12-03T19:49:14", "guid": { "rendered": "/?post_type=mood_tracker&p=4392", "raw": "/?post_type=mood_tracker&p=4392" }, "modified": "2022-12-03T19:49:14", "modified_gmt": "2022-12-03T19:49:14", "password": "", "slug": "", "status": "draft", "type": "mood_tracker", "link": "/?post_type=mood_tracker&p=4392", "title": { "raw": "title 7", "rendered": "title 7" }, "content": { "raw": "", "rendered": "", "protected": false, "block_version": 0 }, "featured_media": 0, "template": "", "meta": { "_mi_skip_tracking": false }, "permalink_template": "/mood_tracker/%pagename%/", "generated_slug": "title-7", "_links": { "self": [ { "href": "/wp-json/wp/v2/mood_tracker/4392" } ], "collection": [ { "href": "/wp-json/wp/v2/mood_tracker" } ], "about": [ { "href": "/wp-json/wp/v2/types/mood_tracker" } ], "wp:attachment": [ { "href": "/wp-json/wp/v2/media?parent=4392" } ], "wp:action-publish": [ { "href": "/wp-json/wp/v2/mood_tracker/4392" } ], "wp:action-unfiltered-html": [ { "href": "/wp-json/wp/v2/mood_tracker/4392" } ], "curies": [ { "name": "wp", "href": "https://api.w.org/{rel}", "templated": true } ] } } https://link.com/wp-json/wp/v2/mood_tracker
[]
[]
[ "As per the ACF document. Make sure this is turned on\n\nMake sure you do the same while you are creating the custom field group in case it overwrites the general settings\n\nSometimes I need to republish the already created posts so they get affected\n" ]
[ -1 ]
[ "advanced_custom_fields", "wordpress", "wordpress_rest_api" ]
stackoverflow_0074670189_advanced_custom_fields_wordpress_wordpress_rest_api.txt
Q: How do you properly execute removeEventListener in this case? I'm new to coding and here is a very basic code for a simple tic tac toe game: function game(id) { let round = ''; round = playRound(id, getComputerChoice()); if(round == "win") { win++; } else if(round == "lose") { lose++; } score.textContent = "Score is " + win + "-" + lose; if(win == 5) { over.textContent = "Game is over, you win!"; } else if(lose == 5) { over.textContent = "Game is over, you lose!"; } } let win = 0; let lose = 0; const result = document.querySelector('#results'); const buttons = document.querySelectorAll('button'); const score = document.querySelector('#score'); const over = document.querySelector('#over'); buttons.forEach((button) => { button.addEventListener('click', () => game(button.id)); }); playRound returns win, lose or tie and getComputerChoice returns random choice for the computer. Once either player gets to 5, I want to use removeEventListener to leave the page as is, but I'm having trouble using it correctly. Also I don't know if my code is the best way to write this program. Any advice on how to optimize/better ways to write this program would be very much appreciated. Thank you. I've tried to stick removeEventListener as so, but it is not working as expected: function game(id) { ... if(win == 5) { over.textContent = "Game is over, you win!"; button.removeEventListener('click', () => game(button.id)); } else if(lose == 5) { over.textContent = "Game is over, you lose!"; button.removeEventListener('click', () => game(button.id)); } } I know this is terribly wrong but this is the only way I could come up with. I went on reference pages online but am having trouble understanding. Thanks for any help. A: While you could save all 5 handlers in an array of functions and then iterate through them to remove at the end, or use event delegation and have just one event handler to remove - why not just check inside game whether either limit has been reached before continuing? function game(id) { if (win === 5 || lose === 5) { return; } // ... Other suggestions: playRound returns a string indicating a win or loss - consider naming the variable more precisely to indicate that, such as roundResult Unless you and everyone who'll ever see the code understands the pretty odd behavior of sloppy comparisons with ==, better to use strict equality with ===
How do you properly execute removeEventListener in this case?
I'm new to coding and here is a very basic code for a simple tic tac toe game: function game(id) { let round = ''; round = playRound(id, getComputerChoice()); if(round == "win") { win++; } else if(round == "lose") { lose++; } score.textContent = "Score is " + win + "-" + lose; if(win == 5) { over.textContent = "Game is over, you win!"; } else if(lose == 5) { over.textContent = "Game is over, you lose!"; } } let win = 0; let lose = 0; const result = document.querySelector('#results'); const buttons = document.querySelectorAll('button'); const score = document.querySelector('#score'); const over = document.querySelector('#over'); buttons.forEach((button) => { button.addEventListener('click', () => game(button.id)); }); playRound returns win, lose or tie and getComputerChoice returns random choice for the computer. Once either player gets to 5, I want to use removeEventListener to leave the page as is, but I'm having trouble using it correctly. Also I don't know if my code is the best way to write this program. Any advice on how to optimize/better ways to write this program would be very much appreciated. Thank you. I've tried to stick removeEventListener as so, but it is not working as expected: function game(id) { ... if(win == 5) { over.textContent = "Game is over, you win!"; button.removeEventListener('click', () => game(button.id)); } else if(lose == 5) { over.textContent = "Game is over, you lose!"; button.removeEventListener('click', () => game(button.id)); } } I know this is terribly wrong but this is the only way I could come up with. I went on reference pages online but am having trouble understanding. Thanks for any help.
[ "While you could save all 5 handlers in an array of functions and then iterate through them to remove at the end, or use event delegation and have just one event handler to remove - why not just check inside game whether either limit has been reached before continuing?\nfunction game(id) {\n if (win === 5 || lose === 5) {\n return;\n }\n // ...\n\nOther suggestions:\n\nplayRound returns a string indicating a win or loss - consider naming the variable more precisely to indicate that, such as roundResult\nUnless you and everyone who'll ever see the code understands the pretty odd behavior of sloppy comparisons with ==, better to use strict equality with ===\n\n" ]
[ 1 ]
[]
[]
[ "dom", "javascript" ]
stackoverflow_0074670451_dom_javascript.txt
Q: How do closures infer their type based on the trait they're required to implement? I'm writing a function that accepts different trait implementors. One of them is a closure. Some closures need an argument type annotation and some don't, depending on their bodies. Example (playground): fn main() { bar(|x| x); bar(|x: bool| !x); // Why is the annotation needed? } trait Foo<T> { type Output; } impl<F: Fn(T) -> O, T, O> Foo<T> for F { type Output = O; } fn bar(_: impl Foo<bool, Output = bool>) {} Why do some closures infer the argument type and others need annotation? Is it possible to redesign trait or function to never require annotation? My (invalid) reasoning is that inference is the same for both closures: bar needs Foo<bool, Output = bool> Only Fn(bool) -> bool implements Foo<bool, Output = bool> The closure must be |bool| -> bool The fact that negation (Not trait) detaches the input type from the output type should not matter, but it seems to somehow be a crucial element. A: In the code you provided, the first closure |x| x does not need an argument type annotation because the compiler is able to infer the type of x based on the context in which the closure is used. In this case, the closure is being passed as an argument to the bar function, which has a trait bound that specifies that the closure must accept a bool as an argument and return a bool as output. Since the closure body does not use x in any way, the compiler knows that it must have the same type as the argument passed to bar, which is a bool. The second closure |x: bool| !x does require an argument type annotation because the body of the closure uses x in a way that cannot be inferred from the context. In this case, the closure negates the value of x using the ! operator, which is only defined for bool values. Therefore, the compiler cannot infer the type of x and requires an explicit type annotation. To avoid requiring argument type annotations in closures, you could redesign the Foo trait to take an additional type parameter for the closure's argument type, like this: trait Foo<T, U> { type Output; } impl<F: Fn(U) -> O, T, O> Foo<T, U> for F { type Output = O; } fn bar(_: impl Foo<bool, bool, Output = bool>) {} Now, the bar function has a trait bound that specifies the argument type for the closure, so the compiler can infer the argument type without requiring an annotation. You can call bar with either of the closures from the original code without an argument type annotation: fn main() { bar(|x| x); bar(|x| !x); } This redesign allows the compiler to infer the argument type for the closure based on the trait bound, rather than relying on context.
How do closures infer their type based on the trait they're required to implement?
I'm writing a function that accepts different trait implementors. One of them is a closure. Some closures need an argument type annotation and some don't, depending on their bodies. Example (playground): fn main() { bar(|x| x); bar(|x: bool| !x); // Why is the annotation needed? } trait Foo<T> { type Output; } impl<F: Fn(T) -> O, T, O> Foo<T> for F { type Output = O; } fn bar(_: impl Foo<bool, Output = bool>) {} Why do some closures infer the argument type and others need annotation? Is it possible to redesign trait or function to never require annotation? My (invalid) reasoning is that inference is the same for both closures: bar needs Foo<bool, Output = bool> Only Fn(bool) -> bool implements Foo<bool, Output = bool> The closure must be |bool| -> bool The fact that negation (Not trait) detaches the input type from the output type should not matter, but it seems to somehow be a crucial element.
[ "In the code you provided, the first closure |x| x does not need an argument type annotation because the compiler is able to infer the type of x based on the context in which the closure is used. In this case, the closure is being passed as an argument to the bar function, which has a trait bound that specifies that the closure must accept a bool as an argument and return a bool as output. Since the closure body does not use x in any way, the compiler knows that it must have the same type as the argument passed to bar, which is a bool.\nThe second closure |x: bool| !x does require an argument type annotation because the body of the closure uses x in a way that cannot be inferred from the context. In this case, the closure negates the value of x using the ! operator, which is only defined for bool values. Therefore, the compiler cannot infer the type of x and requires an explicit type annotation.\nTo avoid requiring argument type annotations in closures, you could redesign the Foo trait to take an additional type parameter for the closure's argument type, like this:\ntrait Foo<T, U> {\ntype Output;\n}\n\nimpl<F: Fn(U) -> O, T, O> Foo<T, U> for F {\ntype Output = O;\n}\n\nfn bar(_: impl Foo<bool, bool, Output = bool>) {}\n\nNow, the bar function has a trait bound that specifies the argument type for the closure, so the compiler can infer the argument type without requiring an annotation. You can call bar with either of the closures from the original code without an argument type annotation:\nfn main() {\nbar(|x| x);\nbar(|x| !x);\n}\n\nThis redesign allows the compiler to infer the argument type for the closure based on the trait bound, rather than relying on context.\n" ]
[ 0 ]
[]
[]
[ "closures", "generics", "rust", "traits" ]
stackoverflow_0054929200_closures_generics_rust_traits.txt
Q: Unable to Deploy Cloud Functions - Permission denied to enable service [artifactregistry.googleapis.com] I'm trying to deploy the default test function to check that everything works. const functions = require("firebase-functions"); exports.helloWorld = functions.https.onRequest((request, response) => { functions.logger.info("Hello logs!", {structuredData: true}); response.send("Hello from Firebase!"); }); But when I run firebase deploy or firebase deploy --only functions, I get the following error: i artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled... ! artifactregistry: missing required API artifactregistry.googleapis.com. Enabling now... Error: HTTP Error: 403, Permission denied to enable service [artifactregistry.googleapis.com] The owner has granted me Cloud Functions Admin, Firebase Admin and Service Account User roles, which is sufficient according to the Firebase Support representative. I have tried logging in/out, reinstalling Firebase command line tools via npm install -g firebase-tools, rerunning firebase init. But I still receive the same error. Does anyone have any experience with this particular error? A: I found a solution and I'm now able to deploy. Here's the answer that worked for me. As I mentioned in my question, enabling Cloud Functions Admin, Firebase Admin and Service Account User roles did not fix the problem. So I asked the owner to give me the API Keys Admin role. Also, I noticed the Artefact Registry API was not enabled at https://console.cloud.google.com/marketplace/product/google/artifactregistry.googleapis.com Since the error was Permission denied to enable service [artifactregistry.googleapis.com], I asked the owner to enable it manually. Doing these two things solved the problem, and I am now able to deploy cloud functions. A: I had the same problem. I had a pending payment of $2, I paid and solved the problem. I was able to update my function and deploy my function
Unable to Deploy Cloud Functions - Permission denied to enable service [artifactregistry.googleapis.com]
I'm trying to deploy the default test function to check that everything works. const functions = require("firebase-functions"); exports.helloWorld = functions.https.onRequest((request, response) => { functions.logger.info("Hello logs!", {structuredData: true}); response.send("Hello from Firebase!"); }); But when I run firebase deploy or firebase deploy --only functions, I get the following error: i artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled... ! artifactregistry: missing required API artifactregistry.googleapis.com. Enabling now... Error: HTTP Error: 403, Permission denied to enable service [artifactregistry.googleapis.com] The owner has granted me Cloud Functions Admin, Firebase Admin and Service Account User roles, which is sufficient according to the Firebase Support representative. I have tried logging in/out, reinstalling Firebase command line tools via npm install -g firebase-tools, rerunning firebase init. But I still receive the same error. Does anyone have any experience with this particular error?
[ "I found a solution and I'm now able to deploy. Here's the answer that worked for me.\nAs I mentioned in my question, enabling Cloud Functions Admin, Firebase Admin and Service Account User roles did not fix the problem. So I asked the owner to give me the API Keys Admin role.\nAlso, I noticed the Artefact Registry API was not enabled at https://console.cloud.google.com/marketplace/product/google/artifactregistry.googleapis.com\nSince the error was Permission denied to enable service [artifactregistry.googleapis.com], I asked the owner to enable it manually.\nDoing these two things solved the problem, and I am now able to deploy cloud functions.\n", "I had the same problem.\nI had a pending payment of $2, I paid and solved the problem. I was able to update my function and deploy my function\n" ]
[ 2, 0 ]
[]
[]
[ "firebase", "firebase_cli", "google_cloud_functions" ]
stackoverflow_0073586030_firebase_firebase_cli_google_cloud_functions.txt
Q: junit test case for function class CheckInbox I have a junit test case created. The function retreives all data in mysql related to the user and stores it all in a csv file. `import static org.junit.Assert.assertEquals; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.DataBaseConnection.Statement; //import static org.junit.Assert.assertEquals; import org.junit.Assert.*; import org.junit.Test; import com.mysql.cj.jdbc.result.ResultSetMetaData; imort static assert.asserEquals public class CheckInboxTest { @Test public void getFileTest() { String url = "jdbc:mysql://localhost/petcare"; String password = "ParkSideRoad161997"; String username = "root"; Connection con = null; PreparedStatement p = null; ResultSet rs = null; String sql2 = "select * from message where " + "senderID = 1 OR receiverID = 1"; try { con = DriverManager.getConnection(url, username, password); p = con.prepareStatement(sql2); rs = p.executeQuery(sql2); ResultSetMetaData rsmd; rsmd = rs.getMetaData(); } catch (Exception e) { e.printStackTrace(); } } }` I tried the above code but I keet getting an error at line ' rsmd = rs.getMetaData();' saying "Type mismatch: cannot convert from java.sql.ResultSetMetaData to com.mysql.cj.jdbc.result.ResultSetMetaData" How can I fix this error? A: It seems you've imported the wrong ResultSetMetaData class. Some IDEs offer you the ability to auto-import classes, perhaps you used this functionality, it suggested a list of classes to import but you chose the wrong one. Try replacing the line import com.mysql.cj.jdbc.result.ResultSetMetaData; with import java.sql.ResultSetMetaData;
junit test case for function class CheckInbox
I have a junit test case created. The function retreives all data in mysql related to the user and stores it all in a csv file. `import static org.junit.Assert.assertEquals; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.DataBaseConnection.Statement; //import static org.junit.Assert.assertEquals; import org.junit.Assert.*; import org.junit.Test; import com.mysql.cj.jdbc.result.ResultSetMetaData; imort static assert.asserEquals public class CheckInboxTest { @Test public void getFileTest() { String url = "jdbc:mysql://localhost/petcare"; String password = "ParkSideRoad161997"; String username = "root"; Connection con = null; PreparedStatement p = null; ResultSet rs = null; String sql2 = "select * from message where " + "senderID = 1 OR receiverID = 1"; try { con = DriverManager.getConnection(url, username, password); p = con.prepareStatement(sql2); rs = p.executeQuery(sql2); ResultSetMetaData rsmd; rsmd = rs.getMetaData(); } catch (Exception e) { e.printStackTrace(); } } }` I tried the above code but I keet getting an error at line ' rsmd = rs.getMetaData();' saying "Type mismatch: cannot convert from java.sql.ResultSetMetaData to com.mysql.cj.jdbc.result.ResultSetMetaData" How can I fix this error?
[ "It seems you've imported the wrong ResultSetMetaData class. Some IDEs offer you the ability to auto-import classes, perhaps you used this functionality, it suggested a list of classes to import but you chose the wrong one.\nTry replacing the line\nimport com.mysql.cj.jdbc.result.ResultSetMetaData;\n\nwith\nimport java.sql.ResultSetMetaData;\n\n" ]
[ 0 ]
[]
[]
[ "java", "junit" ]
stackoverflow_0074670266_java_junit.txt
Q: How can I parse command-line switches in Perl? In order to extend my "grep" emulator in Perl I have added support for a -r switch which enables recursive searching in sub-directories. Now the command line invocation looks something like this: perl pgrep.pl -r <directory> <expression> Both -r and the directory arguments are optional (directory defaults to '.'). As of now I simply check if the first argument is -r and if yes set the appropriate flag, and scan in the rest two arguments using the shift operation. This obviously would be a problem if -r were to appear at the end of the argument list or worse still - in between the directory name and the search expression. One workaround would be to simply delete the -r item from the @ARGV array so that I can simply shift-in the remaining arguments, but I can't figure out a way to do it without getting an 'undef' in an odd position in my array. Any suggestions or different strategies that you might have used are welcome. A: You should be using GetOpt::Long. This will do everything you need as described. A: use Getopt::Std; our $opt_r; # will be set to its value if used. getopts('r:'); # -r has an option. A: Add a -d switch for your directory. My opinion is, "if a command is optional it should have a switch to enable it." Also I would remove the switches(and their arguments) from the array as I read them, leaving just my "expression". If there's more than 1 element in that array, someone wrote something wrong. A: My chapter on "Configuration" in Mastering Perl goes through several possibilities for command-line switch processing, from perl's -s to the popular modules for handling these. For your example, I'd probably start with Getopt::Std and convert to Getopt::Long if I needed it later. Good luck, :) A: One simple and lazy way, is to use -s switch: #!/usr/bin/perl -s use strict; use warnings; use feature qw/say/; our ($dir, $expr); say $dir if ($dir); say $expr if ($expr); Usage ./script.pl -dir=. -expr='/foobar/' Output . /foobar/
How can I parse command-line switches in Perl?
In order to extend my "grep" emulator in Perl I have added support for a -r switch which enables recursive searching in sub-directories. Now the command line invocation looks something like this: perl pgrep.pl -r <directory> <expression> Both -r and the directory arguments are optional (directory defaults to '.'). As of now I simply check if the first argument is -r and if yes set the appropriate flag, and scan in the rest two arguments using the shift operation. This obviously would be a problem if -r were to appear at the end of the argument list or worse still - in between the directory name and the search expression. One workaround would be to simply delete the -r item from the @ARGV array so that I can simply shift-in the remaining arguments, but I can't figure out a way to do it without getting an 'undef' in an odd position in my array. Any suggestions or different strategies that you might have used are welcome.
[ "You should be using GetOpt::Long. This will do everything you need as described.\n", "use Getopt::Std;\n\nour $opt_r; # will be set to its value if used.\ngetopts('r:'); # -r has an option.\n\n", "\nAdd a -d switch for your directory. My opinion is, \"if a command is optional it should have a switch to enable it.\" \nAlso I would remove the switches(and their arguments) from the array as I read them, leaving just my \"expression\". If there's more than 1 element in that array, someone wrote something wrong.\n\n", "My chapter on \"Configuration\" in Mastering Perl goes through several possibilities for command-line switch processing, from perl's -s to the popular modules for handling these. For your example, I'd probably start with Getopt::Std and convert to Getopt::Long if I needed it later.\nGood luck, :)\n", "One simple and lazy way, is to use -s switch:\n#!/usr/bin/perl -s\n\nuse strict; use warnings;\nuse feature qw/say/;\n\nour ($dir, $expr);\n\nsay $dir if ($dir);\nsay $expr if ($expr);\n\nUsage\n./script.pl -dir=. -expr='/foobar/'\n\nOutput\n.\n/foobar/\n\n" ]
[ 21, 4, 1, 0, 0 ]
[]
[]
[ "arguments", "command_line", "parsing", "perl" ]
stackoverflow_0000507387_arguments_command_line_parsing_perl.txt
Q: Server apache-tomcat-9.0.55 at localhost failed to start -- no idea what I can do to resolve this I am having a really big issue that I would really appreciate help on. Essentially, my class project that was a dynamic web page got completely messed up. I was able to recover some of the files, but have to start a new maven-archtype-webpage and restructure the project so I can copy and paste these files in. I am trying to run a sample index.jsp page that says "hello world" on apache 9.0.55, and it is not working. I get an error that reads "Server apache-tomcat-9.0.55 at localhost failed to start.". The deeper error messages on the console say ''' SEVERE: The required Server component failed to start so Tomcat is unable to start. org.apache.catalina.LifecycleException: A child container failed during start at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:938) at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:263) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.StandardService.startInternal(StandardService.java:432) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:927) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.startup.Catalina.start(Catalina.java:772) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:345) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:476) Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: A child container failed during start at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:926) ... 13 more Caused by: org.apache.catalina.LifecycleException: A child container failed during start at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:938) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ... 13 more Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@3f363cf5] at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:926) ... 21 more Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@3f363cf5] at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198) at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4885) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5023) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ... 21 more Caused by: java.lang.IllegalArgumentException: The main resource set specified [/Users/teutaelazaj/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Job_Portal] is not valid at org.apache.catalina.webresources.StandardRoot.createMainResourceSet(StandardRoot.java:762) at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:719) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ... 30 more Dec 03, 2022 2:01:17 PM org.apache.coyote.AbstractProtocol pause INFO: Pausing ProtocolHandler ["http-nio-8082"] Dec 03, 2022 2:01:17 PM org.apache.catalina.core.StandardService stopInternal INFO: Stopping service [Catalina] Dec 03, 2022 2:01:17 PM org.apache.coyote.AbstractProtocol destroy INFO: Destroying ProtocolHandler ["http-nio-8082"] ``` I was not having this issue at all before and I am honestly at a loss for what I can do. This is my POM.XML file <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.prog</groupId> <artifactId>ProjectCUS1156</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ProjectCUS1156 Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>ProjectCUS1156</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.3.1</version> </plugin> </plugins> </build> </project> and this is my web.xml <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> This is how my project is currently structured And this is what my java build path and target runtimes look like Any help at all would be extremely appreciated. I will make sure to mark your response as correct and upvote. Thank you so much A: i wrealy tryed to figered out what line of code is wrong in your pom. the simple way to fix it, replace everything (4.1. Creating the POM) and add dependency web <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>myproject</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.0.0</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>3.0.0</version> </dependency> </dependencies> </project>
Server apache-tomcat-9.0.55 at localhost failed to start -- no idea what I can do to resolve this
I am having a really big issue that I would really appreciate help on. Essentially, my class project that was a dynamic web page got completely messed up. I was able to recover some of the files, but have to start a new maven-archtype-webpage and restructure the project so I can copy and paste these files in. I am trying to run a sample index.jsp page that says "hello world" on apache 9.0.55, and it is not working. I get an error that reads "Server apache-tomcat-9.0.55 at localhost failed to start.". The deeper error messages on the console say ''' SEVERE: The required Server component failed to start so Tomcat is unable to start. org.apache.catalina.LifecycleException: A child container failed during start at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:938) at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:263) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.StandardService.startInternal(StandardService.java:432) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:927) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.startup.Catalina.start(Catalina.java:772) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:345) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:476) Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: A child container failed during start at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:926) ... 13 more Caused by: org.apache.catalina.LifecycleException: A child container failed during start at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:938) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ... 13 more Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@3f363cf5] at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:926) ... 21 more Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@3f363cf5] at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198) at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4885) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5023) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ... 21 more Caused by: java.lang.IllegalArgumentException: The main resource set specified [/Users/teutaelazaj/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Job_Portal] is not valid at org.apache.catalina.webresources.StandardRoot.createMainResourceSet(StandardRoot.java:762) at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:719) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ... 30 more Dec 03, 2022 2:01:17 PM org.apache.coyote.AbstractProtocol pause INFO: Pausing ProtocolHandler ["http-nio-8082"] Dec 03, 2022 2:01:17 PM org.apache.catalina.core.StandardService stopInternal INFO: Stopping service [Catalina] Dec 03, 2022 2:01:17 PM org.apache.coyote.AbstractProtocol destroy INFO: Destroying ProtocolHandler ["http-nio-8082"] ``` I was not having this issue at all before and I am honestly at a loss for what I can do. This is my POM.XML file <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.prog</groupId> <artifactId>ProjectCUS1156</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ProjectCUS1156 Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>ProjectCUS1156</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.3.1</version> </plugin> </plugins> </build> </project> and this is my web.xml <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> This is how my project is currently structured And this is what my java build path and target runtimes look like Any help at all would be extremely appreciated. I will make sure to mark your response as correct and upvote. Thank you so much
[ "i wrealy tryed to figered out what line of code is wrong in your pom.\nthe simple way to fix it, replace everything\n(4.1. Creating the POM)\nand add dependency web\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.example</groupId>\n <artifactId>myproject</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>3.0.0</version>\n </parent>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n <version>3.0.0</version>\n </dependency>\n </dependencies>\n</project> \n\n" ]
[ 1 ]
[]
[]
[ "java", "tomcat" ]
stackoverflow_0074669819_java_tomcat.txt
Q: Can sync 2 GitHub accounts together? Enterprise to personal? I have a GitHub Enterprise account from school and I have a personal GitHub account. Throughout my course I have been uploading all of my projects to the enterprise account and although I am told I would have "lifetime" access to said enterprise account, I would still like my work to be attached to my personal account. Is there a way I could link or sync both of my accounts together? Or a way if I push a repo to my enterprise account it will also push to my personal account at the same time? A: The answer is yes, you can push your repo's to multiple GitHub accounts. When you first pull from an account, you have access to said account until further notice, even after you exit your terminal. All you need to do is to push your files to the "main" branch of each GitHub account. For example. My schools repo main branch is not called "main" it is called "master." So after all the commits I would just git push origin master . This will push it to school. My personal account however is named main. So right after I push to my school I can just git push origin main and it will push it to my personal. Using these two back to back works just fine and it does not matter which one you use first.
Can sync 2 GitHub accounts together? Enterprise to personal?
I have a GitHub Enterprise account from school and I have a personal GitHub account. Throughout my course I have been uploading all of my projects to the enterprise account and although I am told I would have "lifetime" access to said enterprise account, I would still like my work to be attached to my personal account. Is there a way I could link or sync both of my accounts together? Or a way if I push a repo to my enterprise account it will also push to my personal account at the same time?
[ "The answer is yes, you can push your repo's to multiple GitHub accounts. When you first pull from an account, you have access to said account until further notice, even after you exit your terminal. All you need to do is to push your files to the \"main\" branch of each GitHub account.\nFor example. My schools repo main branch is not called \"main\" it is called \"master.\" So after all the commits I would just git push origin master . This will push it to school. My personal account however is named main. So right after I push to my school I can just git push origin main and it will push it to my personal. Using these two back to back works just fine and it does not matter which one you use first.\n" ]
[ 0 ]
[]
[]
[ "github" ]
stackoverflow_0074413732_github.txt
Q: How to redirect to new route when click on anchor tag using JS? I have an anchor tag in an `EJs file- <a href="/posts/" tile>Read More</a> And a route in app.js file- app.get('/posts/:userId', function (request6, response6) { var resquestedTitle = _.lowerCase(request6.params.userId); // For each postObject(elements)inside posts array we check the if condition posts.forEach(function (elements) { // Inside {} we have access to individual postObjects inside posts array // From the compose var storedTitle = _.lowerCase(elements.tile); // Checking for each postObject whether if storedTitle matches the requested title if (resquestedTitle === storedTitle) { // When the requestedTitle matches the storedTitle(tile of postObject), only then we render the post page // Rendering post.ejs using respose6.render method, post is the name of page we want to render response6.render('post', { // Inside {} we pass in JavaScript objects with key value pair // actualPosts and elements.tile are key value pair actualPosts: elements.tile, postContent: elements.bodytext, id: request6.params.userId, }); } else { console.log('Match Not Found' + resquestedTitle); } }); }); Here is the anchor tag on which click I want to redirect to some route i.e /posts/anything. <a href="/posts/<%=tile%>">Read More</a> A: To redirect to a new route using the anchor tag in EJS, you can use the <%= %> tag to insert a variable in the href attribute of the anchor tag. For example, if you want to redirect to the /posts/:userId route and pass in a userId parameter, you can use the following anchor tag: <a href="/posts/<%= userId %>">Read More</a> You could also do the same for the title attribute as well. Furthermore, you can also use the app.get() method to define the route in your app.js file: app.get('/posts/:userId', function (request6, response6) { // Get the userId parameter from the request object var userId = request6.params.userId; // Redirect to the /posts/:userId route and pass in the userId parameter response6.redirect(`/posts/${userId}`); });
How to redirect to new route when click on anchor tag using JS?
I have an anchor tag in an `EJs file- <a href="/posts/" tile>Read More</a> And a route in app.js file- app.get('/posts/:userId', function (request6, response6) { var resquestedTitle = _.lowerCase(request6.params.userId); // For each postObject(elements)inside posts array we check the if condition posts.forEach(function (elements) { // Inside {} we have access to individual postObjects inside posts array // From the compose var storedTitle = _.lowerCase(elements.tile); // Checking for each postObject whether if storedTitle matches the requested title if (resquestedTitle === storedTitle) { // When the requestedTitle matches the storedTitle(tile of postObject), only then we render the post page // Rendering post.ejs using respose6.render method, post is the name of page we want to render response6.render('post', { // Inside {} we pass in JavaScript objects with key value pair // actualPosts and elements.tile are key value pair actualPosts: elements.tile, postContent: elements.bodytext, id: request6.params.userId, }); } else { console.log('Match Not Found' + resquestedTitle); } }); }); Here is the anchor tag on which click I want to redirect to some route i.e /posts/anything. <a href="/posts/<%=tile%>">Read More</a>
[ "To redirect to a new route using the anchor tag in EJS, you can use the <%= %> tag to insert a variable in the href attribute of the anchor tag. For example, if you want to redirect to the /posts/:userId route and pass in a userId parameter, you can use the following anchor tag:\n<a href=\"/posts/<%= userId %>\">Read More</a>\n\nYou could also do the same for the title attribute as well.\nFurthermore, you can also use the app.get() method to define the route in your app.js file:\napp.get('/posts/:userId', function (request6, response6) {\n // Get the userId parameter from the request object\n var userId = request6.params.userId;\n\n // Redirect to the /posts/:userId route and pass in the userId parameter\n response6.redirect(`/posts/${userId}`);\n});\n\n" ]
[ 0 ]
[]
[]
[ "javascript" ]
stackoverflow_0074664560_javascript.txt
Q: Django rest framework CORS( Cross Origin Resource Sharing) is not working I have done token authentication for the url 'localhost:8000/api/posts' and according to django-cors-headers library I have also changed the settings.py file. Here is my settings.py file, INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'rest_framework', 'rest_framework.authtoken' ] Here is my middleware settings, MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Here are my other settings, CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:4000"] Here I have given access only for "http://127.0.0.1:4000" This is my client django project views file which is hosted on "http://127.0.0.1:3000" import requests from django.http import HttpResponse def get_token(): url = "http://127.0.0.1:8000/api/authentication/" response = requests.post(url, data={'username':'thomas','password':'thomas1234567890'}) token=response.json() return token token=get_token() def get_details(): url = "http://127.0.0.1:8000/api/posts/" header = {"Authorization": "Token {}".format(token['token'])} response = requests.get(url, headers = header) return response.text def homepage(request): x= get_details() return HttpResponse(x) Now even though I am requesting for the data from other domain which is not mentioned on django cors origin whitelist, I am able to fetch the data without any error, I am not able to restrict other domains for accessing the data. Can anyone please help me in solving this issue. A: use this setting for your app. This happened because of the fact that you are using HTTPS over HTTP. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
Django rest framework CORS( Cross Origin Resource Sharing) is not working
I have done token authentication for the url 'localhost:8000/api/posts' and according to django-cors-headers library I have also changed the settings.py file. Here is my settings.py file, INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'rest_framework', 'rest_framework.authtoken' ] Here is my middleware settings, MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Here are my other settings, CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:4000"] Here I have given access only for "http://127.0.0.1:4000" This is my client django project views file which is hosted on "http://127.0.0.1:3000" import requests from django.http import HttpResponse def get_token(): url = "http://127.0.0.1:8000/api/authentication/" response = requests.post(url, data={'username':'thomas','password':'thomas1234567890'}) token=response.json() return token token=get_token() def get_details(): url = "http://127.0.0.1:8000/api/posts/" header = {"Authorization": "Token {}".format(token['token'])} response = requests.get(url, headers = header) return response.text def homepage(request): x= get_details() return HttpResponse(x) Now even though I am requesting for the data from other domain which is not mentioned on django cors origin whitelist, I am able to fetch the data without any error, I am not able to restrict other domains for accessing the data. Can anyone please help me in solving this issue.
[ "use this setting for your app. This happened because of the fact that you are using HTTPS over HTTP.\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n" ]
[ 0 ]
[ "According to docs for CORS_ALLOW_ALL_ORIGINS\n\nIf True, all origins will be allowed. Other settings restricting\nallowed origins will be ignored. Defaults to False.\n\nSo it looks like your CORS_ALLOWED_ORIGINS is ignored because CORS_ALLOW_ALL_ORIGINS is explicitly set to False forbidding all origins.\n" ]
[ -1 ]
[ "django", "django_cors_headers", "django_rest_framework", "python" ]
stackoverflow_0063626757_django_django_cors_headers_django_rest_framework_python.txt
Q: PHP Deprecated: Automatic conversion of false to array is deprecated adodb-mssqlnative.inc.php on line 154 We are upgrading PHP to version 8.1. Using MS Sql Server DB. It all seems to work correctly but I see repeated messages in the log file: [03-Feb-2022 11:51:18 America/New_York] PHP Deprecated: Automatic conversion of false to array is deprecated in C:...\includes\adodb\drivers\adodb-mssqlnative.inc.php on line 154 I've updated adodb to version version 5.22 but that did not stop the messges from logging. The ini file has extension=php_sqlsrv_81_nts_x64.dll extension=php_pdo_sqlsrv_81_nts_x64.dll Does anyone know how to fix this problem? A: This is a known issue of backwards incompatibility, affecting the ADOdb library version 5.22.1 and older. PHP 8.1 warns you on autovivification of false-y values and some future version of PHP will throw an error when you do it. PHP natively allows for autovivification (auto-creation of arrays from falsey values). This feature is very useful and used in a lot of PHP projects, especially if the variable is undefined. However, there is a little oddity that allows creating an array from a false and null value. And they give this example // From false $arr = false; $arr[] = 2; I went and found the file in question and this is the function it's in function ServerInfo() { global $ADODB_FETCH_MODE; static $arr = false; if (is_array($arr)) return $arr; if ($this->fetchMode === false) { $savem = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; } elseif ($this->fetchMode >=0 && $this->fetchMode <=2) { $savem = $this->fetchMode; } else $savem = $this->SetFetchMode(ADODB_FETCH_NUM); $arrServerInfo = sqlsrv_server_info($this->_connectionID); $ADODB_FETCH_MODE = $savem; $arr['description'] = $arrServerInfo['SQLServerName'].' connected to '.$arrServerInfo['CurrentDatabase']; $arr['version'] = $arrServerInfo['SQLServerVersion'];//ADOConnection::_findvers($arr['description']); return $arr; } The problem is that it starts with static $arr = false; and then tries to autovivificate a non-array (line 154 in your error) $arr['description'] = $arrServerInfo['SQLServerName'].' connected to '.$arrServerInfo['CurrentDatabase']; You should be able to fix it (in theory) by making sure it's an array (something they should have done anyways). Add this above that line to make it one before it tries to append if(!is_array($arr)) $arr = []; A: Try to add: if(!is_array($yourarray)) $yourarray = []; because
PHP Deprecated: Automatic conversion of false to array is deprecated adodb-mssqlnative.inc.php on line 154
We are upgrading PHP to version 8.1. Using MS Sql Server DB. It all seems to work correctly but I see repeated messages in the log file: [03-Feb-2022 11:51:18 America/New_York] PHP Deprecated: Automatic conversion of false to array is deprecated in C:...\includes\adodb\drivers\adodb-mssqlnative.inc.php on line 154 I've updated adodb to version version 5.22 but that did not stop the messges from logging. The ini file has extension=php_sqlsrv_81_nts_x64.dll extension=php_pdo_sqlsrv_81_nts_x64.dll Does anyone know how to fix this problem?
[ "This is a known issue of backwards incompatibility, affecting the ADOdb library version 5.22.1 and older. PHP 8.1 warns you on autovivification of false-y values and some future version of PHP will throw an error when you do it.\n\nPHP natively allows for autovivification (auto-creation of arrays from falsey values). This feature is very useful and used in a lot of PHP projects, especially if the variable is undefined. However, there is a little oddity that allows creating an array from a false and null value.\n\nAnd they give this example\n// From false\n$arr = false;\n$arr[] = 2;\n\nI went and found the file in question and this is the function it's in\nfunction ServerInfo() {\n global $ADODB_FETCH_MODE;\n static $arr = false;\n if (is_array($arr))\n return $arr;\n if ($this->fetchMode === false) {\n $savem = $ADODB_FETCH_MODE;\n $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\n } elseif ($this->fetchMode >=0 && $this->fetchMode <=2) {\n $savem = $this->fetchMode;\n } else\n $savem = $this->SetFetchMode(ADODB_FETCH_NUM);\n\n $arrServerInfo = sqlsrv_server_info($this->_connectionID);\n $ADODB_FETCH_MODE = $savem;\n $arr['description'] = $arrServerInfo['SQLServerName'].' connected to '.$arrServerInfo['CurrentDatabase'];\n $arr['version'] = $arrServerInfo['SQLServerVersion'];//ADOConnection::_findvers($arr['description']);\n return $arr;\n}\n\nThe problem is that it starts with\nstatic $arr = false;\n\nand then tries to autovivificate a non-array (line 154 in your error)\n$arr['description'] = $arrServerInfo['SQLServerName'].' connected to '.$arrServerInfo['CurrentDatabase'];\n\nYou should be able to fix it (in theory) by making sure it's an array (something they should have done anyways). Add this above that line to make it one before it tries to append\nif(!is_array($arr)) $arr = [];\n\n", "Try to add:\nif(!is_array($yourarray)) $yourarray = [];\n\nbecause\n" ]
[ 8, 0 ]
[]
[]
[ "adodb_php", "autovivification", "php", "php_8.1", "sql_server" ]
stackoverflow_0071035322_adodb_php_autovivification_php_php_8.1_sql_server.txt
Q: Finishing time of cyclic graphs in algorithm I have a question about the strongly connected graphs(graph with cycle) so basically I would like to know what is the finishing time of this graph. and how can I decide whether graph is strongly connected or not based on its finishing time? I have seen some people mentioning reversing the direction of arcs and stuff like that but couldn't understand the concept behind it. A: Check Out Kosaraju Sharir or Tarjan for strongly connected component detection. Complexitys are asintotically the same O(n+m) even though Kosaraju is sligthly slower due to double DFS.
Finishing time of cyclic graphs in algorithm
I have a question about the strongly connected graphs(graph with cycle) so basically I would like to know what is the finishing time of this graph. and how can I decide whether graph is strongly connected or not based on its finishing time? I have seen some people mentioning reversing the direction of arcs and stuff like that but couldn't understand the concept behind it.
[ "Check Out Kosaraju Sharir or Tarjan for strongly connected component detection. Complexitys are asintotically the same O(n+m) even though Kosaraju is sligthly slower due to double DFS.\n" ]
[ 0 ]
[ "I found this helpful website\nlink : https://www.geeksforgeeks.org/detect-cycle-in-a-graph/\nHope it will help you!!\n" ]
[ -1 ]
[ "algorithm", "graph" ]
stackoverflow_0074669888_algorithm_graph.txt
Q: How to change element top border color in component through props using Tailwind CSS ( Solved ) I'm trying to change the color of the top border by passing the color value as props to the component, but It doesn't make any effects. I'm looking for a solution. Please help me! export default function TargetsProgressInfo(props) { return ( <ul> <span className={` after:border-[7px] after:w-4 ${props.colorTip} after:border-b-transparent`}></span></li> </ul> </div > ) } **home.jsx** <TargetsProgressInfo colorTip="after-border-t-red-600"/> A: The solution is to pass the whole name of Tailwind CSS as props <TargetsProgressInfo colorTip="after:border-t-red-600"/> A: You can use the border-t-{color} utility class. You can also use the after pseudo-class to add a border to the element after it has been rendered. <ul> <li className="after:border-[7px] after:w-4 after:border-t-{props.colorTip} after:border-b-transparent"> {/* ... */} </li> </ul> You can then pass the desired color as a prop to your component: This will add a 7px red-600 top border to the li element in your component.
How to change element top border color in component through props using Tailwind CSS ( Solved )
I'm trying to change the color of the top border by passing the color value as props to the component, but It doesn't make any effects. I'm looking for a solution. Please help me! export default function TargetsProgressInfo(props) { return ( <ul> <span className={` after:border-[7px] after:w-4 ${props.colorTip} after:border-b-transparent`}></span></li> </ul> </div > ) } **home.jsx** <TargetsProgressInfo colorTip="after-border-t-red-600"/>
[ "The solution is to pass the whole name of Tailwind CSS as props\n <TargetsProgressInfo colorTip=\"after:border-t-red-600\"/>\n\n", "You can use the border-t-{color} utility class. You can also use the after pseudo-class to add a border to the element after it has been rendered.\n<ul>\n <li className=\"after:border-[7px] after:w-4 after:border-t-{props.colorTip} after:border-b-transparent\">\n {/* ... */}\n </li>\n</ul>\n\nYou can then pass the desired color as a prop to your component:\n\n\nThis will add a 7px red-600 top border to the li element in your component.\n" ]
[ 1, 0 ]
[]
[]
[ "css", "javascript", "react_props", "reactjs", "tailwind_css" ]
stackoverflow_0074669431_css_javascript_react_props_reactjs_tailwind_css.txt
Q: R create new variable if other variable contains vector I want a create a treatment variable that takes the value of 1 for treated countries and 0 otherwise. I know how to do this individually for each country with transform but I was wondering if I can also add a vector to make it faster? I tired the following but I got an error (Warning: longer object length is not a multiple of shorter object length) countries_vector <- c("USA", "UK", "ESP", "FR", "ITA") df <- transform(df, treated = ifelse(Country == countries_vector, 1, 0)) A: You can use mutate, ifelse, and %in% to quickly assign 0 or 1. library(dplyr) treated_countries <- c("USA", "UK", "ESP", "FR", "ITA") all_countries <- sample(x = c("USA", "UK", "ESP", "FR", "ITA", "BRA", "JAP", "CHN", "ZAF", "DEU"), size = 100, replace = TRUE) df <- as.data.frame(all_countries) df <- df %>% mutate(treated = ifelse(all_countries %in% treated_countries, 1, 0)) df %>% group_by(treated, all_countries) %>% summarize() #> `summarise()` has grouped output by 'treated'. You can override using the #> `.groups` argument. #> # A tibble: 10 Γ— 2 #> # Groups: treated [2] #> treated all_countries #> <dbl> <chr> #> 1 0 BRA #> 2 0 CHN #> 3 0 DEU #> 4 0 JAP #> 5 0 ZAF #> 6 1 ESP #> 7 1 FR #> 8 1 ITA #> 9 1 UK #> 10 1 USA
R create new variable if other variable contains vector
I want a create a treatment variable that takes the value of 1 for treated countries and 0 otherwise. I know how to do this individually for each country with transform but I was wondering if I can also add a vector to make it faster? I tired the following but I got an error (Warning: longer object length is not a multiple of shorter object length) countries_vector <- c("USA", "UK", "ESP", "FR", "ITA") df <- transform(df, treated = ifelse(Country == countries_vector, 1, 0))
[ "You can use mutate, ifelse, and %in% to quickly assign 0 or 1.\nlibrary(dplyr)\ntreated_countries <- c(\"USA\", \"UK\", \"ESP\", \"FR\", \"ITA\")\nall_countries <- sample(x = c(\"USA\", \"UK\", \"ESP\", \"FR\", \"ITA\", \"BRA\", \"JAP\", \"CHN\", \"ZAF\", \"DEU\"),\n size = 100, replace = TRUE)\ndf <- as.data.frame(all_countries)\ndf <- df %>%\n mutate(treated = ifelse(all_countries %in% treated_countries, 1, 0))\n\ndf %>%\n group_by(treated, all_countries) %>%\n summarize()\n#> `summarise()` has grouped output by 'treated'. You can override using the\n#> `.groups` argument.\n#> # A tibble: 10 Γ— 2\n#> # Groups: treated [2]\n#> treated all_countries\n#> <dbl> <chr> \n#> 1 0 BRA \n#> 2 0 CHN \n#> 3 0 DEU \n#> 4 0 JAP \n#> 5 0 ZAF \n#> 6 1 ESP \n#> 7 1 FR \n#> 8 1 ITA \n#> 9 1 UK \n#> 10 1 USA\n\n" ]
[ 2 ]
[]
[]
[ "r" ]
stackoverflow_0074670432_r.txt
Q: How to change background color of specific grid/div in MUI in react js from multiple div/grid Hi i want to change color of Grid clicked . I have tried but unfortunately it is changing background color of all the grids. Here is my code . i am trying to handle this through state but can't change color of specific or clicked div import React, { useState } from "react"; import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd"; import { styled } from "@mui/system"; import { Container, Grid } from "@mui/material"; const Index = () => { const listItems = [ { id: "1", label: "5,018", text: "Attendence" }, { id: "2", label: "45%", text: "First time entries" }, { id: "3", label: "55%", text: "Returning attendees" }, { id: "4", label: "12", text: "Events Organised" }, ]; const [dragDropList, setDragDropList] = useState(listItems); const [clicked, setClicked] = useState(false); const toggleClicked = (ind) => setClicked((prev) => !prev); const Heading = styled("div")({ fontWeight: "500", fontSize: "1rem", marginBottom: "2%", }); const DragDropListContainer = styled("div")({}); const ItemCard = styled("div")({ width: "99%", backgroundColor: !clicked ? "#1B2130" : "#1036fc", borderRight: "0.7px solid Grey", borderBottom: "0.7px solid Grey", display: "flex", flexDirection: "column", height: "100%", alignItems: "center", padding: "5% 0 5% 0", justifyContent: "center", position: "relative", }); const Symbol = styled("div")({ color: "#ced6e0", fontSize: "1.3rem", position: "absolute", top: "5px", right: "5px", }); const UpperHeading = styled("div")({ fontSize: "2.2rem", fontWeight: "bolder", color: "#fff", }); const Label = styled("div")({ fontSize: "0.9rem", fontWeight: "500", color: "#FFFFFF", marginTop: "0.4rem", opacity: "0.3", }); const onDragComplete = (result) => { if (!result.destination) return; const arr = [...dragDropList]; let removedItem = arr.splice(result.source.index, 1)[0]; arr.splice(result.destination.index, 0, removedItem); setDragDropList(arr); }; return ( <React.Fragment> <Container maxWidth="false"> <Heading style={{}}>Metric Count</Heading> <DragDropContext onDragEnd={onDragComplete}> <Droppable droppableId="drag-drop-list" direction="horizontal"> {(provided, snapshot) => ( <DragDropListContainer {...provided.droppableProps} ref={provided.innerRef} > <Grid container> {dragDropList.map((item, index) => ( <Draggable key={item.id} draggableId={item.label} index={index} > {(provided) => ( <Grid onClick={toggleClicked} item xs={12} sm={12} md={6} lg={3} > <ItemCard ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} > <Symbol>icon</Symbol> <UpperHeading>{item.label}</UpperHeading> <Label>{item.text}</Label> </ItemCard> </Grid> )} </Draggable> ))} </Grid> {provided.placeholder} </DragDropListContainer> )} </Droppable> </DragDropContext> </Container> </React.Fragment> ); }; export default Index; i am attaching screen shot of ui Mui Grid Hi i want to change color of Grid clicked . I have tried but unfortunately it is changing background color of all the grids. Here is my code . i am trying to handle this through state but can't change color of specific or clicked div A: const listItems = [ { id: "1", label: "5,018", text: "Attendence" }, { id: "2", label: "45%", text: "First time entries" }, { id: "3", label: "55%", text: "Returning attendees" }, { id: "4", label: "12", text: "Events Organised" }, ]; const [dragDropList, setDragDropList] = useState(listItems); const [clicked, setClicked] = useState({}); // Initialize the clicked state to an empty object const toggleClicked = (ind) => { setClicked((prev) => ({ ...prev, [ind]: !prev[ind] })); // Update the clicked state with the id of the clicked grid }; // ... <Grid container> {dragDropList.map((item, index) => ( <Grid key={item.id} item xs={12} sm={6} md={4}> <ItemCard onClick={() => toggleClicked(item.id)} // Pass the id of the grid to the toggleClicked function style={{ backgroundColor: clicked[item.id] ? "#1036fc" : "#1B2130", // Use the clicked state to determine the color of the grid }} > <UpperHeading>{item.text}</UpperHeading> <Label>{item.label}</Label> </ItemCard> </Grid> ))} </Grid> By this snippet you can use the id of that grid to determine which grid to update the color of. You can use the map method to iterate over your list of grid items, and use the id property of each item to check if it matches the grid that was clicked. If it does, you can use the toggleClicked function to update the color of that grid.
How to change background color of specific grid/div in MUI in react js from multiple div/grid
Hi i want to change color of Grid clicked . I have tried but unfortunately it is changing background color of all the grids. Here is my code . i am trying to handle this through state but can't change color of specific or clicked div import React, { useState } from "react"; import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd"; import { styled } from "@mui/system"; import { Container, Grid } from "@mui/material"; const Index = () => { const listItems = [ { id: "1", label: "5,018", text: "Attendence" }, { id: "2", label: "45%", text: "First time entries" }, { id: "3", label: "55%", text: "Returning attendees" }, { id: "4", label: "12", text: "Events Organised" }, ]; const [dragDropList, setDragDropList] = useState(listItems); const [clicked, setClicked] = useState(false); const toggleClicked = (ind) => setClicked((prev) => !prev); const Heading = styled("div")({ fontWeight: "500", fontSize: "1rem", marginBottom: "2%", }); const DragDropListContainer = styled("div")({}); const ItemCard = styled("div")({ width: "99%", backgroundColor: !clicked ? "#1B2130" : "#1036fc", borderRight: "0.7px solid Grey", borderBottom: "0.7px solid Grey", display: "flex", flexDirection: "column", height: "100%", alignItems: "center", padding: "5% 0 5% 0", justifyContent: "center", position: "relative", }); const Symbol = styled("div")({ color: "#ced6e0", fontSize: "1.3rem", position: "absolute", top: "5px", right: "5px", }); const UpperHeading = styled("div")({ fontSize: "2.2rem", fontWeight: "bolder", color: "#fff", }); const Label = styled("div")({ fontSize: "0.9rem", fontWeight: "500", color: "#FFFFFF", marginTop: "0.4rem", opacity: "0.3", }); const onDragComplete = (result) => { if (!result.destination) return; const arr = [...dragDropList]; let removedItem = arr.splice(result.source.index, 1)[0]; arr.splice(result.destination.index, 0, removedItem); setDragDropList(arr); }; return ( <React.Fragment> <Container maxWidth="false"> <Heading style={{}}>Metric Count</Heading> <DragDropContext onDragEnd={onDragComplete}> <Droppable droppableId="drag-drop-list" direction="horizontal"> {(provided, snapshot) => ( <DragDropListContainer {...provided.droppableProps} ref={provided.innerRef} > <Grid container> {dragDropList.map((item, index) => ( <Draggable key={item.id} draggableId={item.label} index={index} > {(provided) => ( <Grid onClick={toggleClicked} item xs={12} sm={12} md={6} lg={3} > <ItemCard ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} > <Symbol>icon</Symbol> <UpperHeading>{item.label}</UpperHeading> <Label>{item.text}</Label> </ItemCard> </Grid> )} </Draggable> ))} </Grid> {provided.placeholder} </DragDropListContainer> )} </Droppable> </DragDropContext> </Container> </React.Fragment> ); }; export default Index; i am attaching screen shot of ui Mui Grid Hi i want to change color of Grid clicked . I have tried but unfortunately it is changing background color of all the grids. Here is my code . i am trying to handle this through state but can't change color of specific or clicked div
[ "const listItems = [\n { id: \"1\", label: \"5,018\", text: \"Attendence\" },\n { id: \"2\", label: \"45%\", text: \"First time entries\" },\n { id: \"3\", label: \"55%\", text: \"Returning attendees\" },\n { id: \"4\", label: \"12\", text: \"Events Organised\" },\n];\nconst [dragDropList, setDragDropList] = useState(listItems);\nconst [clicked, setClicked] = useState({}); // Initialize the clicked state to an empty object\n\nconst toggleClicked = (ind) => {\n setClicked((prev) => ({ ...prev, [ind]: !prev[ind] })); // Update the clicked state with the id of the clicked grid\n};\n\n// ...\n\n<Grid container>\n {dragDropList.map((item, index) => (\n <Grid key={item.id} item xs={12} sm={6} md={4}>\n <ItemCard\n onClick={() => toggleClicked(item.id)} // Pass the id of the grid to the toggleClicked function\n style={{\n backgroundColor: clicked[item.id] ? \"#1036fc\" : \"#1B2130\", // Use the clicked state to determine the color of the grid\n }}\n >\n <UpperHeading>{item.text}</UpperHeading>\n <Label>{item.label}</Label>\n </ItemCard>\n </Grid>\n ))}\n</Grid>\n\nBy this snippet you can use the id of that grid to determine which grid to update the color of. You can use the map method to iterate over your list of grid items, and use the id property of each item to check if it matches the grid that was clicked. If it does, you can use the toggleClicked function to update the color of that grid.\n" ]
[ 1 ]
[]
[]
[ "frontend", "grid", "javascript", "material_ui", "reactjs" ]
stackoverflow_0074670305_frontend_grid_javascript_material_ui_reactjs.txt
Q: MongoDB: add or update items with nested array I have a document with the following data: Chest: { ChestID: 400, // Chest ID is unique Items: [{ ItemID: 200, //Item ID unique too ItemIndexes: ['aaa10', 'bbb20'] // indexes should not be repeated }] } I tried to do this but I can't find a way to make it work: public async appendItems(chestId: number, items: Array < ChestItem > ) { const tokensIds = items.map(item => item.tokenId) // bidimensional array [][] const tokenIndexes = items.map(item => item.indexesAsArray) await this.raw.updateOne({ ChestID: chestId }, { $push: { "Items.$[item].token_indexes": { // in that bidimensional array there can be repeated indexes $each: tokenIndexes, position: "$" } } }, { arrayFilters: [{ "item.token_id": { $in: tokensIds } }], }) } So I want to do the following: First I have to find the chest id, then I have to find the items id, then if the item id exists, just add new indexes ( there can be no more than 1 repeating index ) if it doesn't add the item. A: To update or add items with a nested array in MongoDB, you can use the $set and $addToSet operators. The $set operator is used to update the value of a field, while the $addToSet operator is used to add new items to an array if they do not already exist in the array. public async appendItems(chestId: number, items: Array < ChestItem > ) { const tokensIds = items.map(item => item.tokenId); const tokenIndexes = items.map(item => item.indexesAsArray); await this.raw.updateOne({ ChestID: chestId }, { $set: { "Items": { ItemID: tokensIds, ItemIndexes: tokenIndexes } }, $addToSet: { "Items.$.ItemIndexes": { $each: tokenIndexes } } }); }
MongoDB: add or update items with nested array
I have a document with the following data: Chest: { ChestID: 400, // Chest ID is unique Items: [{ ItemID: 200, //Item ID unique too ItemIndexes: ['aaa10', 'bbb20'] // indexes should not be repeated }] } I tried to do this but I can't find a way to make it work: public async appendItems(chestId: number, items: Array < ChestItem > ) { const tokensIds = items.map(item => item.tokenId) // bidimensional array [][] const tokenIndexes = items.map(item => item.indexesAsArray) await this.raw.updateOne({ ChestID: chestId }, { $push: { "Items.$[item].token_indexes": { // in that bidimensional array there can be repeated indexes $each: tokenIndexes, position: "$" } } }, { arrayFilters: [{ "item.token_id": { $in: tokensIds } }], }) } So I want to do the following: First I have to find the chest id, then I have to find the items id, then if the item id exists, just add new indexes ( there can be no more than 1 repeating index ) if it doesn't add the item.
[ "To update or add items with a nested array in MongoDB, you can use the $set and $addToSet operators. The $set operator is used to update the value of a field, while the $addToSet operator is used to add new items to an array if they do not already exist in the array.\npublic async appendItems(chestId: number, items: Array < ChestItem > ) {\n const tokensIds = items.map(item => item.tokenId);\n const tokenIndexes = items.map(item => item.indexesAsArray);\n\n await this.raw.updateOne({\n ChestID: chestId\n }, {\n $set: {\n \"Items\": {\n ItemID: tokensIds,\n ItemIndexes: tokenIndexes\n }\n },\n $addToSet: {\n \"Items.$.ItemIndexes\": {\n $each: tokenIndexes\n }\n }\n });\n}\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "javascript", "mongodb", "multidimensional_array", "typescript" ]
stackoverflow_0074664516_arrays_javascript_mongodb_multidimensional_array_typescript.txt
Q: Django Crispy Form doesn't add or update database Hello, I am writing a small project about a car shop and this is the problem I came up with. I'm trying to add a new car and everything seems to work, but when I fill out the form and click submit, it just redirects me to products page without errors and without adding a new car to the database. Here is the code. views.py class AddProductView(View): action = 'Add' template_name = 'myApp/manipulate_product.html' context = { } form_class = ManipulateProductForm def get(self, req, *args, **kwargs): form = self.form_class() self.context['action'] = self.action self.context['form'] = form return render(req, self.template_name, self.context) def post(self, req, *args, **kwargs): form = self.form_class(req.POST or None) if form.is_valid(): form.save() else: print(form.errors) return redirect('products', permanent=True) models.py class Car(models.Model): name = models.CharField(max_length=32) model = models.CharField(max_length=32, unique=True) price = models.IntegerField(validators=[ MinValueValidator(0), ]) def __str__(self): return f'{self.name} {self.model}' forms.py class ManipulateProductForm(forms.ModelForm): def __init__(self, action="Submit", *args, **kwargs): super().__init__(*args, **kwargs) self.action = action self.helper = FormHelper(self) self.helper.add_input(Submit('submit', self.action, css_class='btn btn-primary')) class Meta: model = Car fields = '__all__' manipulate_product.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="product-manipulate-container"> {% crispy form form.helper%} </div> {% endblock %} I'm sure the problem is in Crispy, because if I replace code in forms.py and manipulate_product.html to this forms.py class ManipulateProductForm(forms.ModelForm): class Meta: model = Car fields = '__all__' manipulate_product.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="product-manipulate-container"> <form action="" method="POST"> {% csrf_token %} {{ form.as_div }} <input type="submit" value="Submit"> </form> </div> {% endblock %} Everything is working fine! I noticed that when I use Crispy in AddProductView post method is_valid() method returns False but without Crispy it returns True I have tried everything except one delete the whole project and start over. I searched on youtube , google , stackoverflow but didn't find anything similar. Looked at the Crysp documentation, but it's also empty. I hope someone has come across this problem and can help me. Thank you! A: Try rewriting your form like this: class ManipulateProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ManipulateProductForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_action = 'Submit' self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary')) class Meta: model = Car fields = '__all__' And in your template you can just do the following, since you used the default name of the helper: {% crispy form %}
Django Crispy Form doesn't add or update database
Hello, I am writing a small project about a car shop and this is the problem I came up with. I'm trying to add a new car and everything seems to work, but when I fill out the form and click submit, it just redirects me to products page without errors and without adding a new car to the database. Here is the code. views.py class AddProductView(View): action = 'Add' template_name = 'myApp/manipulate_product.html' context = { } form_class = ManipulateProductForm def get(self, req, *args, **kwargs): form = self.form_class() self.context['action'] = self.action self.context['form'] = form return render(req, self.template_name, self.context) def post(self, req, *args, **kwargs): form = self.form_class(req.POST or None) if form.is_valid(): form.save() else: print(form.errors) return redirect('products', permanent=True) models.py class Car(models.Model): name = models.CharField(max_length=32) model = models.CharField(max_length=32, unique=True) price = models.IntegerField(validators=[ MinValueValidator(0), ]) def __str__(self): return f'{self.name} {self.model}' forms.py class ManipulateProductForm(forms.ModelForm): def __init__(self, action="Submit", *args, **kwargs): super().__init__(*args, **kwargs) self.action = action self.helper = FormHelper(self) self.helper.add_input(Submit('submit', self.action, css_class='btn btn-primary')) class Meta: model = Car fields = '__all__' manipulate_product.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="product-manipulate-container"> {% crispy form form.helper%} </div> {% endblock %} I'm sure the problem is in Crispy, because if I replace code in forms.py and manipulate_product.html to this forms.py class ManipulateProductForm(forms.ModelForm): class Meta: model = Car fields = '__all__' manipulate_product.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="product-manipulate-container"> <form action="" method="POST"> {% csrf_token %} {{ form.as_div }} <input type="submit" value="Submit"> </form> </div> {% endblock %} Everything is working fine! I noticed that when I use Crispy in AddProductView post method is_valid() method returns False but without Crispy it returns True I have tried everything except one delete the whole project and start over. I searched on youtube , google , stackoverflow but didn't find anything similar. Looked at the Crysp documentation, but it's also empty. I hope someone has come across this problem and can help me. Thank you!
[ "Try rewriting your form like this:\nclass ManipulateProductForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(ManipulateProductForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper(self)\n self.helper.form_action = 'Submit'\n self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary'))\n\n class Meta:\n model = Car\n fields = '__all__'\n\nAnd in your template you can just do the following, since you used the default name of the helper:\n{% crispy form %}\n\n" ]
[ 1 ]
[]
[]
[ "backend", "django", "django_crispy_forms", "python" ]
stackoverflow_0074670091_backend_django_django_crispy_forms_python.txt
Q: quit button not working properly with electron and render script I'm trying to make a quit button for my Electron app, but every time I press it it does nothing. I currently have the following set up in my files: main.js: const {app, BrowserWindow, ipcMain, Menu} = require('electron'); const url = require('url'); const path = require('path') ... ipcMain.on('quitApp', () => { app.quit(); }) render.js: const {ipcRenderer} = require('electron').ipcRenderer; const closeApp = document.getElementById('closeApp'); closeApp.addEventListener('click', () => { ipcRenderer.send('quitApp'); }); index.html: <body> <div class="menu"> ... <button id="closeApp">Quit</button> <script src="./scripts/render.js"></script> </div> </body> </html> A: First edit the first line of render.js to const {ipcRenderer} = require('electron'); Besides, Check that you put in the BrowserWindow.webPreferences nodeINtegration:true and contextIsolation : false.
quit button not working properly with electron and render script
I'm trying to make a quit button for my Electron app, but every time I press it it does nothing. I currently have the following set up in my files: main.js: const {app, BrowserWindow, ipcMain, Menu} = require('electron'); const url = require('url'); const path = require('path') ... ipcMain.on('quitApp', () => { app.quit(); }) render.js: const {ipcRenderer} = require('electron').ipcRenderer; const closeApp = document.getElementById('closeApp'); closeApp.addEventListener('click', () => { ipcRenderer.send('quitApp'); }); index.html: <body> <div class="menu"> ... <button id="closeApp">Quit</button> <script src="./scripts/render.js"></script> </div> </body> </html>
[ "First edit the first line of render.js to\nconst {ipcRenderer} = require('electron');\n\nBesides, Check that you put in the BrowserWindow.webPreferences nodeINtegration:true and contextIsolation : false.\n" ]
[ 0 ]
[]
[]
[ "electron", "html", "javascript" ]
stackoverflow_0074669294_electron_html_javascript.txt
Q: Problem with adding totals from user selected CheckBoxes I am creating a form that allows the user to select from a group of checkboxes for automotive services. In the form, the user selects from a list of priced services and a final total is calculated based on what is selected. The logic of the selected services being added up is placed within a method that returns the total. . Once the user clicks on the calculate button, all selected prices will be added up and displayed by the total fees label. public partial class Automotive_Shop : Form { const int salesTax = (6 / 100); // prices for services const int oilChange = 26, lubeJob = 18, radiatorFlush = 30, transissionFlush = 80, inspection = 15, mufflerReplacement = 100, tireRotation = 20; int total = 0; public Automotive_Shop() { InitializeComponent(); } private int OilLubeCharges() { if (oilChangeCheckBox.Checked == true) { total += oilChange; } if (lubeJobCheckBox.Checked == true) { total += lubeJob; } return total; } private void calculateButton_Click(object sender, EventArgs e) { totalFeesOutput.Text = OilLubeCharges().ToString("C"); } private void exitButton_Click(object sender, EventArgs e) { // close application this.Close(); } } The total should only be added once. For instance: if the "oil change" check box is selected, then the total should be $26. if the "lube job" check box is selected, then the total should be $18. And if both check boxes are selected, then the total should be $44. What ends up happening is that after the first check box is selected and the calculate button is clicked, the "total" variable value continues to be added up. So if i select "oil change" then click calculate, I get $26. if I deselect it and select "lube job" the total doesn't equal $18, but $44. A: To fix this problem, the total variable needs to be reset to 0 before the calculation happens. The calculate button click event should be updated to look like this: private void calculateButton_Click(object sender, EventArgs e) { total = 0; totalFeesOutput.Text = OilLubeCharges().ToString("C"); } A: A function should be responsible for whatever it does. So everything it does should be there, nothing more and nothing less. This means when a member function is calculating a total, and in the comments you refer to it as a subtotal, this is what the function should do. Therefore you declare in that function int subtotal = 0; and return that. Then you could store this to a member variable if you like. As an example regarding your comments, I have added the member function int ApplyDiscount(...). The only thing it does is applying a discount to 'a' subtotal you pass in. It should be improved for a working application. At the button click the OilLubeCharges are calcultated, then that is passed into ApplyDiscount. This return value you could store at a global variable. Both you could to event specify the full cost, the discount in price and the total. // Added a functionality due to the comments // When `discount` is 0.2f for 20% private int ApplyDiscount(int subtotal, float discount) { return (int)( subtotal - ( subtotal * discount ) ); } private int OilLubeCharges() { int subtotal = 0; if (oilChangeCheckBox.Checked == true) { subtotal += oilChange; } if (lubeJobCheckBox.Checked == true) { subtotal += lubeJob; } return subtotal; } ... private void calculateButton_Click(object sender, EventArgs e) { int subtotal = OilLubeCharges(); int total = ApplyDiscount(subtotal, 0.2f); totalFeesOutput.Text = total.ToString("C"); } A: You mention "the logic of the selected services..." and this phrase is insightful! Consider that one approach is to separate that logic from the view (i.e. the Form that allows interaction with that logic) because it's clear enough that when any property changes it causes ripple effects in certain other properties and the behavior is well-defined. If this "business logic" is placed in a non-UI class that models the desired behavior, the properties can be made smart enough to send notification events whenever they change. For example, if the dollar amount for Parts is changed, it triggers a recalculation of Tax and the new value for Tax triggers a recalculation of the TotalFees property in turn. class AutoShopModel : INotifyPropertyChanged { protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); switch (propertyName) { case nameof(Parts): recalcTax(); break; case nameof(StandardServiceCharges): case nameof(Tax): case nameof(Labor): recalcTotalFees(); break; default: recalcStandardServiceCharges(); break; } } public event PropertyChangedEventHandler PropertyChanged; private void recalcTotalFees() => TotalFees = StandardServiceCharges + Parts + Labor + Tax; . . . } This demonstrates that the model is smart enough to maintain the relative values in a consistent internal state regardless of which property changes. Then, synchronizing the changes to the UI is a simple matter of binding controls like CheckBox and TextBox to properties in the model that have been set up to be bindable. For example, the OilChange property is just a bool and making it bindable simply means firing an event when its value changes: partial class AutoShopModel { public bool OilChange { get => _oilChange; set { if (!Equals(_oilChange, value)) { _oilChange = value; OnPropertyChanged(); } } } bool _oilChange = false; . . . } Finally, the glue that holds it all together takes place in the Load method of the MainForm where the checkBoxOilChange gets bound to changes of the AutoShopModel.OilChange boolean: public partial class MainForm : Form { public MainForm() => InitializeComponent(); protected override void OnLoad(EventArgs e) { base.OnLoad(e); Binding binding = new Binding( nameof(CheckBox.Checked), AutoShopModel, nameof(AutoShopModel.OilChange), false, DataSourceUpdateMode.OnPropertyChanged); checkBoxOilChange.DataBindings.Add(binding); . . . } AutoShopModel AutoShopModel { get; } = new AutoShopModel(); } As a bonus, when you go to make the Android or iOS version of your app, the AutoShopModel is portable and reusable because it doesn't reference any platform-specific UI elements. If you're inclined to play around with this View-Model idea, I put together a short demo you can clone.
Problem with adding totals from user selected CheckBoxes
I am creating a form that allows the user to select from a group of checkboxes for automotive services. In the form, the user selects from a list of priced services and a final total is calculated based on what is selected. The logic of the selected services being added up is placed within a method that returns the total. . Once the user clicks on the calculate button, all selected prices will be added up and displayed by the total fees label. public partial class Automotive_Shop : Form { const int salesTax = (6 / 100); // prices for services const int oilChange = 26, lubeJob = 18, radiatorFlush = 30, transissionFlush = 80, inspection = 15, mufflerReplacement = 100, tireRotation = 20; int total = 0; public Automotive_Shop() { InitializeComponent(); } private int OilLubeCharges() { if (oilChangeCheckBox.Checked == true) { total += oilChange; } if (lubeJobCheckBox.Checked == true) { total += lubeJob; } return total; } private void calculateButton_Click(object sender, EventArgs e) { totalFeesOutput.Text = OilLubeCharges().ToString("C"); } private void exitButton_Click(object sender, EventArgs e) { // close application this.Close(); } } The total should only be added once. For instance: if the "oil change" check box is selected, then the total should be $26. if the "lube job" check box is selected, then the total should be $18. And if both check boxes are selected, then the total should be $44. What ends up happening is that after the first check box is selected and the calculate button is clicked, the "total" variable value continues to be added up. So if i select "oil change" then click calculate, I get $26. if I deselect it and select "lube job" the total doesn't equal $18, but $44.
[ "To fix this problem, the total variable needs to be reset to 0 before the calculation happens.\nThe calculate button click event should be updated to look like this:\nprivate void calculateButton_Click(object sender, EventArgs e)\n{\n total = 0;\n totalFeesOutput.Text = OilLubeCharges().ToString(\"C\");\n}\n\n", "A function should be responsible for whatever it does. So everything it does should be there, nothing more and nothing less.\nThis means when a member function is calculating a total, and in the comments you refer to it as a subtotal, this is what the function should do.\nTherefore you declare in that function int subtotal = 0; and return that.\nThen you could store this to a member variable if you like.\n\nAs an example regarding your comments, I have added the member function int ApplyDiscount(...).\nThe only thing it does is applying a discount to 'a' subtotal you pass in. It should be improved for a working application.\n\nAt the button click the OilLubeCharges are calcultated, then that is passed into ApplyDiscount.\nThis return value you could store at a global variable. Both you could to event specify the full cost, the discount in price and the total.\n // Added a functionality due to the comments\n // When `discount` is 0.2f for 20%\n private int ApplyDiscount(int subtotal, float discount)\n {\n return (int)( subtotal - ( subtotal * discount ) );\n }\n\n private int OilLubeCharges()\n {\n\n int subtotal = 0;\n\n if (oilChangeCheckBox.Checked == true)\n {\n subtotal += oilChange;\n } \n if (lubeJobCheckBox.Checked == true)\n {\n subtotal += lubeJob;\n }\n \n return subtotal;\n\n }\n\n ...\n\n private void calculateButton_Click(object sender, EventArgs e)\n {\n\n int subtotal = OilLubeCharges();\n int total = ApplyDiscount(subtotal, 0.2f);\n\n totalFeesOutput.Text = total.ToString(\"C\");\n \n }\n\n", "You mention \"the logic of the selected services...\" and this phrase is insightful! Consider that one approach is to separate that logic from the view (i.e. the Form that allows interaction with that logic) because it's clear enough that when any property changes it causes ripple effects in certain other properties and the behavior is well-defined. If this \"business logic\" is placed in a non-UI class that models the desired behavior, the properties can be made smart enough to send notification events whenever they change.\nFor example, if the dollar amount for Parts is changed, it triggers a recalculation of Tax and the new value for Tax triggers a recalculation of the TotalFees property in turn.\nclass AutoShopModel : INotifyPropertyChanged\n{\n protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n switch (propertyName)\n {\n case nameof(Parts):\n recalcTax();\n break;\n case nameof(StandardServiceCharges):\n case nameof(Tax):\n case nameof(Labor):\n recalcTotalFees();\n break;\n default:\n recalcStandardServiceCharges();\n break;\n }\n }\n public event PropertyChangedEventHandler PropertyChanged; \n\n private void recalcTotalFees() =>\n TotalFees =\n StandardServiceCharges +\n Parts +\n Labor +\n Tax;\n .\n .\n .\n}\n\nThis demonstrates that the model is smart enough to maintain the relative values in a consistent internal state regardless of which property changes. Then, synchronizing the changes to the UI is a simple matter of binding controls like CheckBox and TextBox to properties in the model that have been set up to be bindable.\nFor example, the OilChange property is just a bool and making it bindable simply means firing an event when its value changes:\npartial class AutoShopModel\n{\n public bool OilChange\n {\n get => _oilChange;\n set\n {\n if (!Equals(_oilChange, value))\n {\n _oilChange = value;\n OnPropertyChanged();\n }\n }\n }\n bool _oilChange = false;\n .\n .\n .\n}\n\nFinally, the glue that holds it all together takes place in the Load method of the MainForm where the checkBoxOilChange gets bound to changes of the AutoShopModel.OilChange boolean:\npublic partial class MainForm : Form\n{\n public MainForm() => InitializeComponent();\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n\n Binding binding = new Binding(\n nameof(CheckBox.Checked), \n AutoShopModel, \n nameof(AutoShopModel.OilChange), \n false, \n DataSourceUpdateMode.OnPropertyChanged);\n checkBoxOilChange.DataBindings.Add(binding);\n .\n .\n .\n }\n AutoShopModel AutoShopModel { get; } = new AutoShopModel();\n}\n\nAs a bonus, when you go to make the Android or iOS version of your app, the AutoShopModel is portable and reusable because it doesn't reference any platform-specific UI elements.\nIf you're inclined to play around with this View-Model idea, I put together a short demo you can clone.\n\n" ]
[ 1, 1, 1 ]
[]
[]
[ "c#", "winforms" ]
stackoverflow_0074662635_c#_winforms.txt
Q: How to use Context API with useParams I have an api with details of a farm and I want to show them in different components using an id. Like the data is used in many components and I want to use Context API to display the data in the components. So here is the code that fetches the data let navigate = useNavigate(); const [farm, setFarm] = useState(''); const { username } = useParams(); const { farmId } = useParams(); const [isLoading, setIsLoading] = useState(true); const user = React.useContext(UserContext); useEffect(() => { let isMounted = true; axios.get(`/api/farm/${username}/${farmId}`).then(res => { if (isMounted) { if (res.data.status === 200) { setFarm(res.data.farm); setIsLoading(false); console.warn(res.data.farm) } else if (res.data.status === 404) { navigate('/'); toast.error(res.data.message, "error"); } } }); return () => { isMounted = false }; }, []); The username is okay because I will use the user context to get the user details. Now, how do Use this from a context into the components, because I have tried, and it is not working. A: Well you can do it by adding another context for farm. Your context file: export const FarmContext = React.createContext(); export function FarmProvider({ children }) { const [farm, setFarm] = useState(); return ( <FarmContext.Provider value={{farm, setFarm}}> { children } </FarmContext.Provider> ) } And instead of this: const [farm, setFarm] = useState(); Use this: const { farm, setFarm } = useContext(FarmContext);
How to use Context API with useParams
I have an api with details of a farm and I want to show them in different components using an id. Like the data is used in many components and I want to use Context API to display the data in the components. So here is the code that fetches the data let navigate = useNavigate(); const [farm, setFarm] = useState(''); const { username } = useParams(); const { farmId } = useParams(); const [isLoading, setIsLoading] = useState(true); const user = React.useContext(UserContext); useEffect(() => { let isMounted = true; axios.get(`/api/farm/${username}/${farmId}`).then(res => { if (isMounted) { if (res.data.status === 200) { setFarm(res.data.farm); setIsLoading(false); console.warn(res.data.farm) } else if (res.data.status === 404) { navigate('/'); toast.error(res.data.message, "error"); } } }); return () => { isMounted = false }; }, []); The username is okay because I will use the user context to get the user details. Now, how do Use this from a context into the components, because I have tried, and it is not working.
[ "Well you can do it by adding another context for farm.\nYour context file:\nexport const FarmContext = React.createContext();\n\nexport function FarmProvider({ children }) {\n const [farm, setFarm] = useState();\n\n return (\n <FarmContext.Provider value={{farm, setFarm}}>\n { children }\n </FarmContext.Provider>\n )\n}\n\nAnd instead of this:\nconst [farm, setFarm] = useState();\n\nUse this:\nconst { farm, setFarm } = useContext(FarmContext);\n\n" ]
[ 0 ]
[ "Include setIsLoading and setFarm into your dependency array. The dispatch function changes during a re-render. In your case, during development double renders components to detect issues with state management.\nuseEffect(() => {\n ....\n\n}, [ setIsLoading, setFarm]);\n\n" ]
[ -1 ]
[ "javascript", "react_context", "reactjs" ]
stackoverflow_0074670147_javascript_react_context_reactjs.txt
Q: How would I delete a class object allocated with new, then use the same pointer variable for another new class object? If I have a pointer pointing to an object class allocated with new, such as: myClass* ptr = new myClass(); and I want to change the ptr to a new class object, how would I do that? I tried doing this: delete ptr; ptr = new myClass(); but it causes a crash when I try to access the ptr variable, but I want to be sure I don't just point it at a new object and cause a memory leak. How would I go about this? A: I rarely, if ever, reassign individual heap allocated objects. But this is how it is done: // Allocate a new myClass instance and let x point at that instance myClass* x = new myClass(); // Replace the data pointed at by x to be a new myClass instance *x = myClass(); // At this point, x points at the same piece of memory // but the data stored at that memory is different. // Call the destructor of myClass and free the memory delete x;
How would I delete a class object allocated with new, then use the same pointer variable for another new class object?
If I have a pointer pointing to an object class allocated with new, such as: myClass* ptr = new myClass(); and I want to change the ptr to a new class object, how would I do that? I tried doing this: delete ptr; ptr = new myClass(); but it causes a crash when I try to access the ptr variable, but I want to be sure I don't just point it at a new object and cause a memory leak. How would I go about this?
[ "I rarely, if ever, reassign individual heap allocated objects. But this is how it is done:\n // Allocate a new myClass instance and let x point at that instance\n myClass* x = new myClass();\n\n // Replace the data pointed at by x to be a new myClass instance\n *x = myClass();\n\n // At this point, x points at the same piece of memory\n // but the data stored at that memory is different.\n\n // Call the destructor of myClass and free the memory\n delete x;\n\n" ]
[ 0 ]
[]
[]
[ "c++", "memory_leaks", "pointers" ]
stackoverflow_0074670329_c++_memory_leaks_pointers.txt
Q: Flutter App: How to create a Favourite List using a Tappable IconButton on a Container? I'm trying to add an IconButton to my Cryptolist. That Button should be tappable and when it's tapped the Crypto should be added to the Favouritelist and the Color of the Button should change to red. I know that the best method might be to use a ListTile but I just don't know how I can change everything to ListTile as I already have this CoinCard/Container where data are styled/positioned accordingly. I would really appreciate any help. Flutter, Dart and Visual Studio are totally knew for me. Sorry for the messy code. This is how my Home code looks like. import 'dart:async'; import 'package:flutter/material.dart'; import '../infrastructure/coin_model.dart'; import '../infrastructure/coin_repository.dart'; import 'coin_card.dart'; import 'coincard_tile.dart'; class CoinHome extends StatefulWidget { const CoinHome({super.key}); @override State<CoinHome> createState() => _CoinHomeState(); } class _CoinHomeState extends State<CoinHome> { List<CoinCard> coinCardList = []; List<CoinCard> favouriteCoins = []; CoinRepository coinRepository = CoinRepository(); List<Coin> coinList = []; void fetchCoin() { setState(() { coinRepository.findAll().then((value) { //debugPrint('Value:${value.length}'); coinList.clear(); coinList.addAll(value); //debugPrint('Coinlist${coinList.length}'); }); //debugPrint('Coinlist${coinList.length}'); }); } @override void initState() { super.initState(); fetchCoin(); Timer.periodic(Duration(seconds: 10), (timer) => fetchCoin()); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color.fromARGB(255, 119, 194, 202), appBar: AppBar( backgroundColor: Color.fromARGB(255, 119, 194, 202), title: Center( child: Text( 'Cryptostatistics'.toUpperCase(), style: TextStyle( color: Color.fromARGB(255, 255, 255, 255), fontSize: 25, fontWeight: FontWeight.bold, ), ), ), actions: [ IconButton( icon: const Icon(Icons.list), onPressed: _pushFavorite, tooltip: 'Favourite Coins', ) ], ), body: _buildCoinCard()); } Widget _buildCoinCard() { return ListView.builder( scrollDirection: Axis.vertical, itemCount: coinList.length, itemBuilder: (context, index) { coinCardList.add(CoinCard( coinName: coinList[index].coinName, symbol: coinList[index].symbol, imageUrl: coinList[index].imageUrl, price: coinList[index].price.toDouble(), change: coinList[index].change.toDouble(), changePercentage: coinList[index].changePercentage.toDouble(), favorite: Icons.favorite_border, )); return CoinCard( coinName: coinList[index].coinName, symbol: coinList[index].symbol, imageUrl: coinList[index].imageUrl, price: coinList[index].price.toDouble(), change: coinList[index].change.toDouble(), changePercentage: coinList[index].changePercentage.toDouble(), favorite: Icons.favorite_border, ); // return CoinCardTile( // coincard: CoinCard( // coinName: coinList[index].coinName, // symbol: coinList[index].symbol, // imageUrl: coinList[index].imageUrl, // price: coinList[index].price.toDouble(), // change: coinList[index].change.toDouble(), // changePercentage: coinList[index].changePercentage.toDouble(), // favorite: Icons.favorite_border, // ), // trailing: coinCardList[index].favorite, // onTilePressed: (coincard) => onFavouriteSelected(coincard), // ); }, ); } void _pushFavorite() { Navigator.of(context).push( MaterialPageRoute<void>( builder: (BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color.fromARGB(255, 119, 194, 202), title: Center( child: Text( 'Favourite Coins'.toUpperCase(), style: TextStyle( color: Color.fromARGB(255, 255, 255, 255), fontSize: 25, fontWeight: FontWeight.bold, ), )), ), body: _buildFavourite(), ); }, ), // ...to here. ); } Widget _buildFavourite() { return ListView.builder(itemBuilder: (BuildContext context, int index) { CoinCard( coinName: coinCardList[index].coinName, symbol: coinCardList[index].symbol, imageUrl: coinCardList[index].imageUrl, price: coinCardList[index].price, change: coinCardList[index].change, changePercentage: coinCardList[index].changePercentage, favorite: coinCardList[index].favorite); CoinCardTile( coincard: coinCardList[index], trailing: coinCardList[index].favorite, onTilePressed: (coincard) => onFavouriteSelected(coincard), ); }); } void onFavouriteSelected(CoinCard coincard) { setState(() { { favouriteCoins.add(coincard); } final alreadySaved = favouriteCoins.contains(coincard); Icon( alreadySaved ? coincard.favorite : coincard.favorite = Icons.favorite_border, color: alreadySaved ? Colors.red : null, semanticLabel: alreadySaved ? 'Remove from saved' : 'Save', ); }); } } At first I tried to return the CoinCard and CoinCardTile but I remembered that only 1 return value is possible. When I return CoinCard I have the Icon but can't tap on them. When I return the CoinCardTile the Icons are tappable but the CoinCards/Cryptos are not there anymore. A: If you want to add an IconButton to your CoinCard, you can create a ListTile with the CoinCard as the leading widget and the IconButton as the trailing widget. You can then use the onTap property of the ListTile to specify the action that should be performed when the IconButton is tapped. Here's an example of how you could do this: ListTile( leading: CoinCard(...), // Replace "..." with the appropriate arguments trailing: IconButton( icon: Icon(Icons.add), onPressed: () { // Add the crypto to the Favouritelist // Change the color of the button to red } ), onTap: () { // This will be called when the CoinCard is tapped, // in addition to the onPressed callback of the IconButton } ) Alternatively, you can use a Stack widget to overlay the IconButton on top of the CoinCard. This will allow you to keep the CoinCard and IconButton as separate widgets, but still be able to tap on the IconButton to trigger an action. Here's an example of how you could do this: Stack( children: [ CoinCard(...), // Replace "..." with the appropriate arguments Positioned( right: 0, bottom: 0, child: IconButton( icon: Icon(Icons.add), onPressed: () { // Add the crypto to the Favouritelist // Change the color of the button to red } ), ), ], )
Flutter App: How to create a Favourite List using a Tappable IconButton on a Container?
I'm trying to add an IconButton to my Cryptolist. That Button should be tappable and when it's tapped the Crypto should be added to the Favouritelist and the Color of the Button should change to red. I know that the best method might be to use a ListTile but I just don't know how I can change everything to ListTile as I already have this CoinCard/Container where data are styled/positioned accordingly. I would really appreciate any help. Flutter, Dart and Visual Studio are totally knew for me. Sorry for the messy code. This is how my Home code looks like. import 'dart:async'; import 'package:flutter/material.dart'; import '../infrastructure/coin_model.dart'; import '../infrastructure/coin_repository.dart'; import 'coin_card.dart'; import 'coincard_tile.dart'; class CoinHome extends StatefulWidget { const CoinHome({super.key}); @override State<CoinHome> createState() => _CoinHomeState(); } class _CoinHomeState extends State<CoinHome> { List<CoinCard> coinCardList = []; List<CoinCard> favouriteCoins = []; CoinRepository coinRepository = CoinRepository(); List<Coin> coinList = []; void fetchCoin() { setState(() { coinRepository.findAll().then((value) { //debugPrint('Value:${value.length}'); coinList.clear(); coinList.addAll(value); //debugPrint('Coinlist${coinList.length}'); }); //debugPrint('Coinlist${coinList.length}'); }); } @override void initState() { super.initState(); fetchCoin(); Timer.periodic(Duration(seconds: 10), (timer) => fetchCoin()); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color.fromARGB(255, 119, 194, 202), appBar: AppBar( backgroundColor: Color.fromARGB(255, 119, 194, 202), title: Center( child: Text( 'Cryptostatistics'.toUpperCase(), style: TextStyle( color: Color.fromARGB(255, 255, 255, 255), fontSize: 25, fontWeight: FontWeight.bold, ), ), ), actions: [ IconButton( icon: const Icon(Icons.list), onPressed: _pushFavorite, tooltip: 'Favourite Coins', ) ], ), body: _buildCoinCard()); } Widget _buildCoinCard() { return ListView.builder( scrollDirection: Axis.vertical, itemCount: coinList.length, itemBuilder: (context, index) { coinCardList.add(CoinCard( coinName: coinList[index].coinName, symbol: coinList[index].symbol, imageUrl: coinList[index].imageUrl, price: coinList[index].price.toDouble(), change: coinList[index].change.toDouble(), changePercentage: coinList[index].changePercentage.toDouble(), favorite: Icons.favorite_border, )); return CoinCard( coinName: coinList[index].coinName, symbol: coinList[index].symbol, imageUrl: coinList[index].imageUrl, price: coinList[index].price.toDouble(), change: coinList[index].change.toDouble(), changePercentage: coinList[index].changePercentage.toDouble(), favorite: Icons.favorite_border, ); // return CoinCardTile( // coincard: CoinCard( // coinName: coinList[index].coinName, // symbol: coinList[index].symbol, // imageUrl: coinList[index].imageUrl, // price: coinList[index].price.toDouble(), // change: coinList[index].change.toDouble(), // changePercentage: coinList[index].changePercentage.toDouble(), // favorite: Icons.favorite_border, // ), // trailing: coinCardList[index].favorite, // onTilePressed: (coincard) => onFavouriteSelected(coincard), // ); }, ); } void _pushFavorite() { Navigator.of(context).push( MaterialPageRoute<void>( builder: (BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color.fromARGB(255, 119, 194, 202), title: Center( child: Text( 'Favourite Coins'.toUpperCase(), style: TextStyle( color: Color.fromARGB(255, 255, 255, 255), fontSize: 25, fontWeight: FontWeight.bold, ), )), ), body: _buildFavourite(), ); }, ), // ...to here. ); } Widget _buildFavourite() { return ListView.builder(itemBuilder: (BuildContext context, int index) { CoinCard( coinName: coinCardList[index].coinName, symbol: coinCardList[index].symbol, imageUrl: coinCardList[index].imageUrl, price: coinCardList[index].price, change: coinCardList[index].change, changePercentage: coinCardList[index].changePercentage, favorite: coinCardList[index].favorite); CoinCardTile( coincard: coinCardList[index], trailing: coinCardList[index].favorite, onTilePressed: (coincard) => onFavouriteSelected(coincard), ); }); } void onFavouriteSelected(CoinCard coincard) { setState(() { { favouriteCoins.add(coincard); } final alreadySaved = favouriteCoins.contains(coincard); Icon( alreadySaved ? coincard.favorite : coincard.favorite = Icons.favorite_border, color: alreadySaved ? Colors.red : null, semanticLabel: alreadySaved ? 'Remove from saved' : 'Save', ); }); } } At first I tried to return the CoinCard and CoinCardTile but I remembered that only 1 return value is possible. When I return CoinCard I have the Icon but can't tap on them. When I return the CoinCardTile the Icons are tappable but the CoinCards/Cryptos are not there anymore.
[ "If you want to add an IconButton to your CoinCard, you can create a ListTile with the CoinCard as the leading widget and the IconButton as the trailing widget. You can then use the onTap property of the ListTile to specify the action that should be performed when the IconButton is tapped.\nHere's an example of how you could do this:\nListTile(\n leading: CoinCard(...), // Replace \"...\" with the appropriate arguments\n trailing: IconButton(\n icon: Icon(Icons.add),\n onPressed: () {\n // Add the crypto to the Favouritelist\n // Change the color of the button to red\n }\n ),\n onTap: () {\n // This will be called when the CoinCard is tapped,\n // in addition to the onPressed callback of the IconButton\n }\n)\n\nAlternatively, you can use a Stack widget to overlay the IconButton on top of the CoinCard. This will allow you to keep the CoinCard and IconButton as separate widgets, but still be able to tap on the IconButton to trigger an action.\nHere's an example of how you could do this:\nStack(\n children: [\n CoinCard(...), // Replace \"...\" with the appropriate arguments\n Positioned(\n right: 0,\n bottom: 0,\n child: IconButton(\n icon: Icon(Icons.add),\n onPressed: () {\n // Add the crypto to the Favouritelist\n // Change the color of the button to red\n }\n ),\n ),\n ],\n)\n\n" ]
[ 0 ]
[]
[]
[ "button", "containers", "dart", "flutter", "listtile" ]
stackoverflow_0074670489_button_containers_dart_flutter_listtile.txt
Q: CSV file data to Excel (Remove csv file after workbook save not working) I'm having trouble removing the csv file after the data is integrated into the workbook. I'm getting a message The process cannot access the file because it is being used by another process! and I tried closing the file before I am applying the os.remove syntax to my code. I am curretly stuck in what I should do. I've tried a few methods, but the end statement keeps popping up. # importing pandas #importing os import pandas as pd import os csv_1 = open('SearchResults.csv', 'r') csv_2 = open('SearchResults (1).csv', 'r') csv_3 = open('SearchResults (2).csv', 'r') writer = pd.ExcelWriter('DB_1.xlsx', engine='xlsxwriter') # merging three csv files df = pd.concat(map(pd.read_csv,[csv_1,csv_2,csv_3]), ignore_index=True) #Exports csv files to excel sheet on DB_1.xlsx df.to_excel(writer, sheet_name='sheetname') csv_1.close() csv_2.close() csv_3.close() writer.save() try: os.remove('SearchResults.csv') print("The file: {} is deleted!".format('SearchResults.csv')) except OSError as e: print("Error: {} - {}!".format(e.filename, e.strerror)) try: os.remove('SearchResults (1).csv') print("The file: {} is deleted!".format('SearchResults (1).csv')) except OSError as e: print("Error: {} - {}!".format(e.filename, e.strerror)) try: os.remove('SearchResults (2).csv') print("The file: {} is deleted!".format('SearchResults (2).csv')) except OSError as e: print("Error: {} - {}!".format(e.filename, e.strerror)) #Results: Error: SearchResults.csv - The process cannot access the file because it is being used by another process! Error: SearchResults (1).csv - The process cannot access the file because it is being used by another process! Error: SearchResults (2).csv - The process cannot access the file because it is being used by another process! A: Using pathlib.glob to find all files, concatenate the csv files with a generator to excel. Finally delete csv files. import contextlib from pathlib import Path import pandas as pd def concatenate_csvs(path: str) -> None: pd.concat( (pd.read_csv(x) for x in Path(f"{path}/").glob("SearchResults*.csv")), ignore_index=True ).to_excel(f"{path}/DB_1.xlsx", index=False, sheet_name="sheetname") with contextlib.suppress(PermissionError): [Path(x).unlink() for x in Path(f"{path}/").glob("SearchResults*.csv")] concatenate_csvs("/path/to/files") A: Unless you need to do line by line operations on your three .csv files (and it doesn't seem to be the case here), there is no need to use python's built-in funciton open with pandas.read_csv. Try this : import pandas as pd import os csv_1 = 'SearchResults.csv' csv_2 = 'SearchResults (1).csv' csv_3 = 'SearchResults (2).csv' # merging three csv files df = pd.concat(map(pd.read_csv,[csv_1,csv_2,csv_3]), ignore_index=True) with pd.ExcelWriter('DB_1.xlsx', engine='xlsxwriter') as writer : #Exports csv files to excel sheet on DB_1.xlsx df.to_excel(writer, sheet_name='sheetname') try: os.remove('SearchResults.csv') print("The file: {} is deleted!".format('SearchResults.csv')) except OSError as e: print("Error: {} - {}!".format(e.filename, e.strerror)) try: os.remove('SearchResults (1).csv') print("The file: {} is deleted!".format('SearchResults (1).csv')) except OSError as e: print("Error: {} - {}!".format(e.filename, e.strerror)) try: os.remove('SearchResults (2).csv') print("The file: {} is deleted!".format('SearchResults (2).csv')) except OSError as e: print("Error: {} - {}!".format(e.filename, e.strerror))
CSV file data to Excel (Remove csv file after workbook save not working)
I'm having trouble removing the csv file after the data is integrated into the workbook. I'm getting a message The process cannot access the file because it is being used by another process! and I tried closing the file before I am applying the os.remove syntax to my code. I am curretly stuck in what I should do. I've tried a few methods, but the end statement keeps popping up. # importing pandas #importing os import pandas as pd import os csv_1 = open('SearchResults.csv', 'r') csv_2 = open('SearchResults (1).csv', 'r') csv_3 = open('SearchResults (2).csv', 'r') writer = pd.ExcelWriter('DB_1.xlsx', engine='xlsxwriter') # merging three csv files df = pd.concat(map(pd.read_csv,[csv_1,csv_2,csv_3]), ignore_index=True) #Exports csv files to excel sheet on DB_1.xlsx df.to_excel(writer, sheet_name='sheetname') csv_1.close() csv_2.close() csv_3.close() writer.save() try: os.remove('SearchResults.csv') print("The file: {} is deleted!".format('SearchResults.csv')) except OSError as e: print("Error: {} - {}!".format(e.filename, e.strerror)) try: os.remove('SearchResults (1).csv') print("The file: {} is deleted!".format('SearchResults (1).csv')) except OSError as e: print("Error: {} - {}!".format(e.filename, e.strerror)) try: os.remove('SearchResults (2).csv') print("The file: {} is deleted!".format('SearchResults (2).csv')) except OSError as e: print("Error: {} - {}!".format(e.filename, e.strerror)) #Results: Error: SearchResults.csv - The process cannot access the file because it is being used by another process! Error: SearchResults (1).csv - The process cannot access the file because it is being used by another process! Error: SearchResults (2).csv - The process cannot access the file because it is being used by another process!
[ "Using pathlib.glob to find all files, concatenate the csv files with a generator to excel. Finally delete csv files.\nimport contextlib\nfrom pathlib import Path\n\nimport pandas as pd\n\n\ndef concatenate_csvs(path: str) -> None:\n pd.concat(\n (pd.read_csv(x) for x in Path(f\"{path}/\").glob(\"SearchResults*.csv\")), ignore_index=True\n ).to_excel(f\"{path}/DB_1.xlsx\", index=False, sheet_name=\"sheetname\")\n\n with contextlib.suppress(PermissionError):\n [Path(x).unlink() for x in Path(f\"{path}/\").glob(\"SearchResults*.csv\")]\n\n\nconcatenate_csvs(\"/path/to/files\")\n\n", "Unless you need to do line by line operations on your three .csv files (and it doesn't seem to be the case here), there is no need to use python's built-in funciton open with pandas.read_csv.\nTry this :\nimport pandas as pd\nimport os\n\ncsv_1 = 'SearchResults.csv'\ncsv_2 = 'SearchResults (1).csv'\ncsv_3 = 'SearchResults (2).csv'\n \n# merging three csv files\ndf = pd.concat(map(pd.read_csv,[csv_1,csv_2,csv_3]), ignore_index=True)\n \nwith pd.ExcelWriter('DB_1.xlsx', engine='xlsxwriter') as writer :\n #Exports csv files to excel sheet on DB_1.xlsx\n df.to_excel(writer, sheet_name='sheetname')\n\ntry:\n os.remove('SearchResults.csv')\n print(\"The file: {} is deleted!\".format('SearchResults.csv'))\nexcept OSError as e:\n print(\"Error: {} - {}!\".format(e.filename, e.strerror))\n\ntry:\n os.remove('SearchResults (1).csv')\n print(\"The file: {} is deleted!\".format('SearchResults (1).csv'))\nexcept OSError as e:\n print(\"Error: {} - {}!\".format(e.filename, e.strerror))\n \ntry:\n os.remove('SearchResults (2).csv')\n print(\"The file: {} is deleted!\".format('SearchResults (2).csv'))\nexcept OSError as e:\n print(\"Error: {} - {}!\".format(e.filename, e.strerror))\n\n" ]
[ 0, 0 ]
[]
[]
[ "operating_system", "pandas", "permissions", "python" ]
stackoverflow_0074670286_operating_system_pandas_permissions_python.txt
Q: How to get matching characters? I'm trying to get common characters from two separate vectors. Example: x <- c("abcde") y <- c("efghi") df <- data.frame(x, y) Desired output x y z abcde efghi e lmnop uvmxw m I've tried something like this, but it is a bad result: df |> mutate(m = unique(x, y)) If there are multiple matches, returning a list would work great. A: str_intersect <- function(s1,s2) { paste0(intersect(strsplit(s1,"")[[1]],strsplit(s2,"")[[1]]),collapse = "") } x <- c("abcde","abc") y <- c("efghi","b") df <- data.frame(x, y) library(dplyr) df %>% rowwise() %>% mutate(m = str_intersect(x,y)) A: Using R base approach: > df$z <- intersect(unlist(strsplit(df$x, "")), unlist(strsplit(df$y, ""))) > df x y z 1 abcde efghi e 2 lmnop uvmxw m Data structure(list(x = c("abcde", "lmnop"), y = c("efghi", "uvmxw" ), z = c("e", "m")), row.names = c(NA, -2L), class = "data.frame") A: Here is one method where we update the 'y' column by wrapping it inside the [] and add the ^ so that all those characters other than those will be matched as pattern and gets removed with str_remove_all library(stringr) library(dplyr) df %>% mutate(z = str_remove_all(x, sprintf("[^%s]", y))) -output x y z 1 abcde efghi e 2 lmnop uvmxw m It also handles multiple characters, df1 %>% mutate(z = str_remove_all(x, sprintf("[^%s]", y))) x y z 1 abcde efghi e 2 lmnop ovmxw mo data df <- structure(list(x = c("abcde", "lmnop"), y = c("efghi", "uvmxw" )), row.names = c(NA, -2L), class = "data.frame") df1 <- structure(list(x = c("abcde", "lmnop"), y = c("efghi", "ovmxw" )), class = "data.frame", row.names = c(NA, -2L)) A: Here's a tidyverse solution with functions from stringr, which can also handle multiple common characters: library(stringr) df %>% mutate( # convert `x` to alternation pattern: y1 = str_replace_all(x, "(?<=.)(?=.)", "|"), # which of `y1` are contained in `x`?: match = str_extract_all(y, y1) ) x y y1 match 1 abcde efghi a|b|c|d|e e 2 lmnop ovmxw l|m|n|o|p o, m You can remove y1by adding %>% select(-y1) Data: x <- c("abcde", "lmnop") y <- c("efghi", "ovmxw") df <- data.frame(x, y) A: Using strsplit and intersect in a function with some case handling. strintr <- \(x) { o <- apply(x, 1, \(.) do.call(intersect, strsplit(., ''))) dx <- dim(x)[1] if (!identical(o, dx)) length(o) <- dx o[lengths(o) == 0L] <- NA_character_ if (any(lengths(o) > 1L)) lapply(o, as.list) else o } Usage cols <- c('x', 'y') Using within. within(df1, foo <- strintr(df1[cols])) # x y foo # 1 abcde efghi e within(df2, foo <- strintr(df2[cols])) # x y foo # 1 abcde efghi e # 2 lmnop uvmxw m within(df3, foo <- strintr(df3[cols])) # x y foo # 1 abcde defghi d, e # 2 lmnop uvmxw m within(df4, foo <- strintr(df4[cols])) # x y foo # 1 abcde xyz <NA> # 2 lmnop xyz <NA> within(df5, foo <- strintr(df5[cols])) # x y foo # 1 abcde defghi d, e # 2 lmnop xyz NA Using $. df3$foo <- strintr(df3[cols]) df3 # x y foo # 1 abcde defghi d, e # 2 lmnop uvmxw m Using dplyr::mutate. dplyr::mutate(df3, fo=strintr(df3[cols])) # x y fo # 1 abcde defghi d, e # 2 lmnop uvmxw m Note: This won't work with transform due to some kind of bug. Data: df1 <- data.frame(x="abcde", y="efghi") df2 <- data.frame(x=c('abcde', 'lmnop'), y=c('efghi', 'uvmxw')) df3 <- data.frame(x=c('abcde', 'lmnop'), y=c('defghi', 'uvmxw')) df4 <- data.frame(x=c('abcde', 'lmnop'), y=c('xyz', 'xyz')) df5 <- data.frame(x=c('abcde', 'lmnop'), y=c('defghi', 'xyz'))
How to get matching characters?
I'm trying to get common characters from two separate vectors. Example: x <- c("abcde") y <- c("efghi") df <- data.frame(x, y) Desired output x y z abcde efghi e lmnop uvmxw m I've tried something like this, but it is a bad result: df |> mutate(m = unique(x, y)) If there are multiple matches, returning a list would work great.
[ "str_intersect <- function(s1,s2) {\n paste0(intersect(strsplit(s1,\"\")[[1]],strsplit(s2,\"\")[[1]]),collapse = \"\")\n}\n\nx <- c(\"abcde\",\"abc\")\ny <- c(\"efghi\",\"b\")\ndf <- data.frame(x, y)\n\nlibrary(dplyr)\ndf %>%\n rowwise() %>%\n mutate(m = str_intersect(x,y))\n\n", "Using R base approach:\n> df$z <- intersect(unlist(strsplit(df$x, \"\")), unlist(strsplit(df$y, \"\")))\n> df\n x y z\n1 abcde efghi e\n2 lmnop uvmxw m\n\nData\nstructure(list(x = c(\"abcde\", \"lmnop\"), y = c(\"efghi\", \"uvmxw\"\n), z = c(\"e\", \"m\")), row.names = c(NA, -2L), class = \"data.frame\")\n\n", "Here is one method where we update the 'y' column by wrapping it inside the [] and add the ^ so that all those characters other than those will be matched as pattern and gets removed with str_remove_all\nlibrary(stringr)\nlibrary(dplyr)\ndf %>%\n mutate(z = str_remove_all(x, sprintf(\"[^%s]\", y)))\n\n-output\n x y z\n1 abcde efghi e\n2 lmnop uvmxw m\n\n\nIt also handles multiple characters,\ndf1 %>%\n mutate(z = str_remove_all(x, sprintf(\"[^%s]\", y)))\n x y z\n1 abcde efghi e\n2 lmnop ovmxw mo\n\ndata\ndf <- structure(list(x = c(\"abcde\", \"lmnop\"), y = c(\"efghi\", \"uvmxw\"\n)), row.names = c(NA, -2L), class = \"data.frame\")\ndf1 <- structure(list(x = c(\"abcde\", \"lmnop\"), y = c(\"efghi\", \"ovmxw\"\n)), class = \"data.frame\", row.names = c(NA, -2L))\n\n", "Here's a tidyverse solution with functions from stringr, which can also handle multiple common characters:\nlibrary(stringr)\ndf %>%\n mutate(\n # convert `x` to alternation pattern:\n y1 = str_replace_all(x, \"(?<=.)(?=.)\", \"|\"),\n # which of `y1` are contained in `x`?:\n match = str_extract_all(y, y1)\n ) \n x y y1 match\n1 abcde efghi a|b|c|d|e e\n2 lmnop ovmxw l|m|n|o|p o, m\n\nYou can remove y1by adding %>% select(-y1)\nData:\nx <- c(\"abcde\", \"lmnop\")\ny <- c(\"efghi\", \"ovmxw\")\ndf <- data.frame(x, y)\n\n", "Using strsplit and intersect in a function with some case handling.\nstrintr <- \\(x) {\n o <- apply(x, 1, \\(.) do.call(intersect, strsplit(., '')))\n dx <- dim(x)[1]\n if (!identical(o, dx)) length(o) <- dx\n o[lengths(o) == 0L] <- NA_character_\n if (any(lengths(o) > 1L)) lapply(o, as.list) else o\n}\n\nUsage\ncols <- c('x', 'y')\n\nUsing within.\nwithin(df1, foo <- strintr(df1[cols]))\n# x y foo\n# 1 abcde efghi e\nwithin(df2, foo <- strintr(df2[cols]))\n# x y foo\n# 1 abcde efghi e\n# 2 lmnop uvmxw m\nwithin(df3, foo <- strintr(df3[cols]))\n# x y foo\n# 1 abcde defghi d, e\n# 2 lmnop uvmxw m\nwithin(df4, foo <- strintr(df4[cols]))\n# x y foo\n# 1 abcde xyz <NA>\n# 2 lmnop xyz <NA>\nwithin(df5, foo <- strintr(df5[cols]))\n# x y foo\n# 1 abcde defghi d, e\n# 2 lmnop xyz NA\n\nUsing $.\ndf3$foo <- strintr(df3[cols])\ndf3\n# x y foo\n# 1 abcde defghi d, e\n# 2 lmnop uvmxw m\n\nUsing dplyr::mutate.\ndplyr::mutate(df3, fo=strintr(df3[cols]))\n# x y fo\n# 1 abcde defghi d, e\n# 2 lmnop uvmxw m\n\nNote: This won't work with transform due to some kind of bug.\n\nData:\ndf1 <- data.frame(x=\"abcde\", y=\"efghi\")\ndf2 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('efghi', 'uvmxw'))\ndf3 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('defghi', 'uvmxw'))\ndf4 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('xyz', 'xyz'))\ndf5 <- data.frame(x=c('abcde', 'lmnop'),\n y=c('defghi', 'xyz'))\n\n" ]
[ 2, 2, 2, 2, 0 ]
[]
[]
[ "r" ]
stackoverflow_0074669001_r.txt
Q: Issue deploying React app on Github pages After creating my portfolio app with React I have integrated the required lines of code to use GitHub pages. The app throws no error but no components appeared except the background color. The code of App.js: import './App.scss'; import { Route, Routes } from 'react-router-dom' import Layout from './components/Layout'; import Home from './components/Home' import About from './components/About' import Contact from './components/Contact'; function App() { return ( <Routes> <Route path="/" element={<Layout />}> <Route index element={<Home />}/> <Route path="about" element={<About />}/> <Route path="contact" element={<Contact />}/> </Route> </Routes> ); } export default App; The website is deployed at https://gregwdumont.github.io/Portfolio/. A: 2 ways you might end up like this; either you are not rendering any components on your page so in your index.js file, you are only setting the background-color of the page, but not rendering any components. you need to import and render the components that you want to display on your page. For example, you could import your App component and render it: import { App } from './App'; ReactDOM.render(<App />, document.getElementById('root')); you may need to adjust the homepage field in your package.json file to match the URL of your deployed site. This field is used by the gh-pages package to determine the URL that the site will be deployed to. A: Your site is deployed to a "subfolder" of the domain, so React Router does not match any route. You have to set the basename as: <BrowserRouter basename='/Portfolio'> ... </BrowserRouter> See docs
Issue deploying React app on Github pages
After creating my portfolio app with React I have integrated the required lines of code to use GitHub pages. The app throws no error but no components appeared except the background color. The code of App.js: import './App.scss'; import { Route, Routes } from 'react-router-dom' import Layout from './components/Layout'; import Home from './components/Home' import About from './components/About' import Contact from './components/Contact'; function App() { return ( <Routes> <Route path="/" element={<Layout />}> <Route index element={<Home />}/> <Route path="about" element={<About />}/> <Route path="contact" element={<Contact />}/> </Route> </Routes> ); } export default App; The website is deployed at https://gregwdumont.github.io/Portfolio/.
[ "2 ways you might end up like this; either you are not rendering any components on your page so in your index.js file, you are only setting the background-color of the page, but not rendering any components.\nyou need to import and render the components that you want to display on your page. For example, you could import your App component and render it:\nimport { App } from './App';\n\nReactDOM.render(<App />, document.getElementById('root'));\n\nyou may need to adjust the homepage field in your package.json file to match the URL of your deployed site. This field is used by the gh-pages package to determine the URL that the site will be deployed to.\n", "Your site is deployed to a \"subfolder\" of the domain, so React Router does not match any route. You have to set the basename as:\n<BrowserRouter basename='/Portfolio'>\n...\n</BrowserRouter>\n\nSee docs\n" ]
[ 0, 0 ]
[]
[]
[ "github_pages", "reactjs" ]
stackoverflow_0074670441_github_pages_reactjs.txt
Q: How can I dispatch on traits relating two types, where the second type that co-satisfies the trait is uniquely determined by the first? Say I have a Julia trait that relates to two types: one type is a sort of "base" type that may satisfy a sort of partial trait, the other is an associated type that is uniquely determined by the base type. (That is, the relation from BaseType -> AssociatedType is a function.) Together, these types satisfy a composite trait that is the one of interest to me. For example: using Traits @traitdef IsProduct{X} begin isnew(X) -> Bool coolness(X) -> Float64 end @traitdef IsProductWithMeasurement{X,M} begin @constraints begin istrait(IsProduct{X}) end measurements(X) -> M #Maybe some other stuff that dispatches on (X,M), e.g. #fits_in(X,M) -> Bool #how_many_fit_in(X,M) -> Int64 #But I don't want to implement these now end Now here are a couple of example types. Please ignore the particulars of the examples; they are just meant as MWEs and there is nothing relevant in the details: type Rope color::ASCIIString age_in_years::Float64 strength::Float64 length::Float64 end type Paper color::ASCIIString age_in_years::Int64 content::ASCIIString width::Float64 height::Float64 end function isnew(x::Rope) (x.age_in_years < 10.0)::Bool end function coolness(x::Rope) if x.color=="Orange" return 2.0::Float64 elseif x.color!="Taupe" return 1.0::Float64 else return 0.0::Float64 end end function isnew(x::Paper) (x.age_in_years < 1.0)::Bool end function coolness(x::Paper) (x.content=="StackOverflow Answers" ? 1000.0 : 0.0)::Float64 end Since I've defined these functions, I can do @assert istrait(IsProduct{Rope}) @assert istrait(IsProduct{Paper}) And now if I define function measurements(x::Rope) (x.length)::Float64 end function measurements(x::Paper) (x.height,x.width)::Tuple{Float64,Float64} end Then I can do @assert istrait(IsProductWithMeasurement{Rope,Float64}) @assert istrait(IsProductWithMeasurement{Paper,Tuple{Float64,Float64}}) So far so good; these run without error. Now, what I want to do is write a function like the following: @traitfn function get_measurements{X,M;IsProductWithMeasurement{X,M}}(similar_items::Array{X,1}) all_measurements = Array{M,1}(length(similar_items)) for i in eachindex(similar_items) all_measurements[i] = measurements(similar_items[i])::M end all_measurements::Array{M,1} end Generically, this function is meant to be an example of "I want to use the fact that I, as the programmer, know that BaseType is always associated to AssociatedType to help the compiler with type inference. I know that whenever I do a certain task [in this case, get_measurements, but generically this could work in a bunch of cases] then I want the compiler to infer the output type of that function in a consistently patterned way." That is, e.g. do_something_that_makes_arrays_of_assoc_type(x::BaseType) will always spit out Array{AssociatedType}, and do_something_that_makes_tuples(x::BaseType) will always spit out Tuple{Int64,BaseType,AssociatedType}. AND, one such relationship holds for all pairs of <BaseType,AssociatedType>; e.g. if BatmanType is the base type to which RobinType is associated, and SupermanType is the base type to which LexLutherType is always associated, then do_something_that_makes_tuple(x::BatManType) will always output Tuple{Int64,BatmanType,RobinType}, and do_something_that_makes_tuple(x::SuperManType) will always output Tuple{Int64,SupermanType,LexLutherType}. So, I understand this relationship, and I want the compiler to understand it for the sake of speed. Now, back to the function example. If this makes sense, you will have realized that while the function definition I gave as an example is 'correct' in the sense that it satisfies this relationship and does compile, it is un-callable because the compiler doesn't understand the relationship between X and M, even though I do. In particular, since M doesn't appear in the method signature, there is no way for Julia to dispatch on the function. So far, the only thing I have thought to do to solve this problem is to create a sort of workaround where I "compute" the associated type on the fly, and I can still use method dispatch to do this computation. Consider: function get_measurement_type_of_product(x::Rope) Float64 end function get_measurement_type_of_product(x::Paper) Tuple{Float64,Float64} end @traitfn function get_measurements{X;IsProduct{X}}(similar_items::Array{X,1}) M = get_measurement_type_of_product(similar_items[1]::X) all_measurements = Array{M,1}(length(similar_items)) for i in eachindex(similar_items) all_measurements[i] = measurements(similar_items[i])::M end all_measurements::Array{M,1} end Then indeed this compiles and is callable: julia> get_measurements(Array{Rope,1}([Rope("blue",1.0,1.0,1.0),Rope("red",2.0,2.0,2.0)])) 2-element Array{Float64,1}: 1.0 2.0 But this is not ideal, because (a) I have to redefine this map each time, even though I feel as though I already told the compiler about the relationship between X and M by making them satisfy the trait, and (b) as far as I can guess--maybe this is wrong; I don't have direct evidence for this--the compiler won't necessarily be able to optimize as well as I want, since the relationship between X and M is "hidden" inside the return value of the function call. One last thought: if I had the ability, what I would ideally do is something like this: @traitdef IsProduct{X} begin isnew(X) -> Bool coolness(X) -> Float64 βˆƒ ! M s.t. measurements(X) -> M end and then have some way of referring to the type that uniquely witnesses the existence relationship, so e.g. @traitfn function get_measurements{X;IsProduct{X},IsWitnessType{IsProduct{X},M}}(similar_items::Array{X,1}) all_measurements = Array{M,1}(length(similar_items)) for i in eachindex(similar_items) all_measurements[i] = measurements(similar_items[i])::M end all_measurements::Array{M,1} end because this would be somehow dispatchable. So: what is my specific question? I am asking, given that you presumably by this point understand that my goals are Have my code exhibit this sort of structure generically, so that I can effectively repeat this design pattern across a lot of cases and then program in the abstract at the high-level of X and M, and do (1) in such a way that the compiler can still optimize to the best of its ability / is as aware of the relationship among types as I, the coder, am then, how should I do this? I think the answer is Use Traits.jl Do something pretty similar to what you've done so far Also do ____some clever thing____ that the answerer will indicate, but I'm open to the idea that in fact the correct answer is Abandon this approach, you're thinking about the problem the wrong way Instead, think about it this way: ____MWE____ I'd also be perfectly satisfied by answers of the form What you are asking for is a "sophisticated" feature of Julia that is still under development, and is expected to be included in v0.x.y, so just wait... and I'm less enthusiastic about (but still curious to hear) an answer such as Abandon Julia; instead use the language ________ that is designed for this type of thing I also think this might be related to the question of typing Julia's function outputs, which as I take it is also under consideration, though I haven't been able to puzzle out the exact representation of this problem in terms of that one. A: To solve your problem, you can try using the @traitfn macro in your get_measurements function. This macro is used to specify trait constraints on the input and output types of a function. In this case, you can use the IsProductWithMeasurement{X,M} trait as a constraint on the input and output types of the function. Here is how you can modify your get_measurements function to use the @traitfn macro: @traitfn function get_measurements{X,M;IsProductWithMeasurement{X,M}}(similar_items::Array{X,1}) all_measurements = Array{M,1}(length(similar_items)) for i in eachindex(similar_items) all_measurements[i] = measurements(similar_items[i])::M end all_measurements::Array{M,1} end With this modification, the type of the similar_items input will be constrained to be an Array of a type X that satisfies the IsProductWithMeasurement trait, and the type of the all_measurements output will be constrained to be an Array of a type M. A: To dispatch on traits relating two types, where the second type that co-satisfies the trait is uniquely determined by the first, you can use trait bounds in the function signature. This allows the compiler to infer the associated type based on the type of the argument passed to the function. Here is an example of how you could rewrite the get_measurements function to use trait bounds: @traitfn function get_measurements{X,M}(similar_items::Array{X,1}) where IsProductWithMeasurement{X,M} all_measurements = Array{M,1}(length(similar_items)) for i in eachindex(similar_items) all_measurements[i] = measurements(similar_items[i])::M end all_measurements::Array{M,1} end Here, the trait bounds where IsProductWithMeasurement{X,M} specify that the types X and M must satisfy the IsProductWithMeasurement trait. This allows the compiler to infer the associated type M based on the type of the similar_items argument. You can then call the get_measurements function with an Array of a type that satisfies the IsProductWithMeasurement trait, and the compiler will infer the associated type automatically: julia> get_measurements([Rope("Orange", 5, 10, 100), Rope("Taupe", 15, 20, 200)]) 2-element Array{Float64,1}: 100.0 200.0 julia> get_measurements([Paper("White", 0, "StackOverflow Answers", 8.5, 11), Paper("Yellow", 3, "Foo", 11, 17)]) 2-element Array{Tuple{Float64,Float64},1}: (11.0, 8.5) (17.0, 11.0) In this way, you can use trait bounds to dispatch on traits relating two types and infer the associated type automatically based on the type of the argument passed to the function.
How can I dispatch on traits relating two types, where the second type that co-satisfies the trait is uniquely determined by the first?
Say I have a Julia trait that relates to two types: one type is a sort of "base" type that may satisfy a sort of partial trait, the other is an associated type that is uniquely determined by the base type. (That is, the relation from BaseType -> AssociatedType is a function.) Together, these types satisfy a composite trait that is the one of interest to me. For example: using Traits @traitdef IsProduct{X} begin isnew(X) -> Bool coolness(X) -> Float64 end @traitdef IsProductWithMeasurement{X,M} begin @constraints begin istrait(IsProduct{X}) end measurements(X) -> M #Maybe some other stuff that dispatches on (X,M), e.g. #fits_in(X,M) -> Bool #how_many_fit_in(X,M) -> Int64 #But I don't want to implement these now end Now here are a couple of example types. Please ignore the particulars of the examples; they are just meant as MWEs and there is nothing relevant in the details: type Rope color::ASCIIString age_in_years::Float64 strength::Float64 length::Float64 end type Paper color::ASCIIString age_in_years::Int64 content::ASCIIString width::Float64 height::Float64 end function isnew(x::Rope) (x.age_in_years < 10.0)::Bool end function coolness(x::Rope) if x.color=="Orange" return 2.0::Float64 elseif x.color!="Taupe" return 1.0::Float64 else return 0.0::Float64 end end function isnew(x::Paper) (x.age_in_years < 1.0)::Bool end function coolness(x::Paper) (x.content=="StackOverflow Answers" ? 1000.0 : 0.0)::Float64 end Since I've defined these functions, I can do @assert istrait(IsProduct{Rope}) @assert istrait(IsProduct{Paper}) And now if I define function measurements(x::Rope) (x.length)::Float64 end function measurements(x::Paper) (x.height,x.width)::Tuple{Float64,Float64} end Then I can do @assert istrait(IsProductWithMeasurement{Rope,Float64}) @assert istrait(IsProductWithMeasurement{Paper,Tuple{Float64,Float64}}) So far so good; these run without error. Now, what I want to do is write a function like the following: @traitfn function get_measurements{X,M;IsProductWithMeasurement{X,M}}(similar_items::Array{X,1}) all_measurements = Array{M,1}(length(similar_items)) for i in eachindex(similar_items) all_measurements[i] = measurements(similar_items[i])::M end all_measurements::Array{M,1} end Generically, this function is meant to be an example of "I want to use the fact that I, as the programmer, know that BaseType is always associated to AssociatedType to help the compiler with type inference. I know that whenever I do a certain task [in this case, get_measurements, but generically this could work in a bunch of cases] then I want the compiler to infer the output type of that function in a consistently patterned way." That is, e.g. do_something_that_makes_arrays_of_assoc_type(x::BaseType) will always spit out Array{AssociatedType}, and do_something_that_makes_tuples(x::BaseType) will always spit out Tuple{Int64,BaseType,AssociatedType}. AND, one such relationship holds for all pairs of <BaseType,AssociatedType>; e.g. if BatmanType is the base type to which RobinType is associated, and SupermanType is the base type to which LexLutherType is always associated, then do_something_that_makes_tuple(x::BatManType) will always output Tuple{Int64,BatmanType,RobinType}, and do_something_that_makes_tuple(x::SuperManType) will always output Tuple{Int64,SupermanType,LexLutherType}. So, I understand this relationship, and I want the compiler to understand it for the sake of speed. Now, back to the function example. If this makes sense, you will have realized that while the function definition I gave as an example is 'correct' in the sense that it satisfies this relationship and does compile, it is un-callable because the compiler doesn't understand the relationship between X and M, even though I do. In particular, since M doesn't appear in the method signature, there is no way for Julia to dispatch on the function. So far, the only thing I have thought to do to solve this problem is to create a sort of workaround where I "compute" the associated type on the fly, and I can still use method dispatch to do this computation. Consider: function get_measurement_type_of_product(x::Rope) Float64 end function get_measurement_type_of_product(x::Paper) Tuple{Float64,Float64} end @traitfn function get_measurements{X;IsProduct{X}}(similar_items::Array{X,1}) M = get_measurement_type_of_product(similar_items[1]::X) all_measurements = Array{M,1}(length(similar_items)) for i in eachindex(similar_items) all_measurements[i] = measurements(similar_items[i])::M end all_measurements::Array{M,1} end Then indeed this compiles and is callable: julia> get_measurements(Array{Rope,1}([Rope("blue",1.0,1.0,1.0),Rope("red",2.0,2.0,2.0)])) 2-element Array{Float64,1}: 1.0 2.0 But this is not ideal, because (a) I have to redefine this map each time, even though I feel as though I already told the compiler about the relationship between X and M by making them satisfy the trait, and (b) as far as I can guess--maybe this is wrong; I don't have direct evidence for this--the compiler won't necessarily be able to optimize as well as I want, since the relationship between X and M is "hidden" inside the return value of the function call. One last thought: if I had the ability, what I would ideally do is something like this: @traitdef IsProduct{X} begin isnew(X) -> Bool coolness(X) -> Float64 βˆƒ ! M s.t. measurements(X) -> M end and then have some way of referring to the type that uniquely witnesses the existence relationship, so e.g. @traitfn function get_measurements{X;IsProduct{X},IsWitnessType{IsProduct{X},M}}(similar_items::Array{X,1}) all_measurements = Array{M,1}(length(similar_items)) for i in eachindex(similar_items) all_measurements[i] = measurements(similar_items[i])::M end all_measurements::Array{M,1} end because this would be somehow dispatchable. So: what is my specific question? I am asking, given that you presumably by this point understand that my goals are Have my code exhibit this sort of structure generically, so that I can effectively repeat this design pattern across a lot of cases and then program in the abstract at the high-level of X and M, and do (1) in such a way that the compiler can still optimize to the best of its ability / is as aware of the relationship among types as I, the coder, am then, how should I do this? I think the answer is Use Traits.jl Do something pretty similar to what you've done so far Also do ____some clever thing____ that the answerer will indicate, but I'm open to the idea that in fact the correct answer is Abandon this approach, you're thinking about the problem the wrong way Instead, think about it this way: ____MWE____ I'd also be perfectly satisfied by answers of the form What you are asking for is a "sophisticated" feature of Julia that is still under development, and is expected to be included in v0.x.y, so just wait... and I'm less enthusiastic about (but still curious to hear) an answer such as Abandon Julia; instead use the language ________ that is designed for this type of thing I also think this might be related to the question of typing Julia's function outputs, which as I take it is also under consideration, though I haven't been able to puzzle out the exact representation of this problem in terms of that one.
[ "To solve your problem, you can try using the @traitfn macro in your get_measurements function. This macro is used to specify trait constraints on the input and output types of a function. In this case, you can use the IsProductWithMeasurement{X,M} trait as a constraint on the input and output types of the function. Here is how you can modify your get_measurements function to use the @traitfn macro:\n@traitfn function get_measurements{X,M;IsProductWithMeasurement{X,M}}(similar_items::Array{X,1})\n all_measurements = Array{M,1}(length(similar_items))\n for i in eachindex(similar_items)\n all_measurements[i] = measurements(similar_items[i])::M\n end\n all_measurements::Array{M,1}\nend\n\nWith this modification, the type of the similar_items input will be constrained to be an Array of a type X that satisfies the IsProductWithMeasurement trait, and the type of the all_measurements output will be constrained to be an Array of a type M.\n", "To dispatch on traits relating two types, where the second type that co-satisfies the trait is uniquely determined by the first, you can use trait bounds in the function signature. This allows the compiler to infer the associated type based on the type of the argument passed to the function.\nHere is an example of how you could rewrite the get_measurements function to use trait bounds:\n@traitfn function get_measurements{X,M}(similar_items::Array{X,1}) where IsProductWithMeasurement{X,M}\n all_measurements = Array{M,1}(length(similar_items))\n for i in eachindex(similar_items)\n all_measurements[i] = measurements(similar_items[i])::M\n end\n all_measurements::Array{M,1}\nend\n\nHere, the trait bounds where IsProductWithMeasurement{X,M} specify that the types X and M must satisfy the IsProductWithMeasurement trait. This allows the compiler to infer the associated type M based on the type of the similar_items argument.\nYou can then call the get_measurements function with an Array of a type that satisfies the IsProductWithMeasurement trait, and the compiler will infer the associated type automatically:\njulia> get_measurements([Rope(\"Orange\", 5, 10, 100), Rope(\"Taupe\", 15, 20, 200)])\n2-element Array{Float64,1}:\n 100.0\n 200.0\n\njulia> get_measurements([Paper(\"White\", 0, \"StackOverflow Answers\", 8.5, 11), Paper(\"Yellow\", 3, \"Foo\", 11, 17)])\n2-element Array{Tuple{Float64,Float64},1}:\n (11.0, 8.5)\n (17.0, 11.0)\n\nIn this way, you can use trait bounds to dispatch on traits relating two types and infer the associated type automatically based on the type of the argument passed to the function.\n" ]
[ 0, 0 ]
[]
[]
[ "julia", "traits" ]
stackoverflow_0035614353_julia_traits.txt
Q: AXON: Use MySql for EventStore and MongoDb for Projection - Events recreating records I have an existing app that saved collections in MongoDb. As mentioned in documentation and on https://www.youtube.com/watch?v=342tqAORbAM that MongoDB is not right and that I should use plain RDBMS like MySQL /- Axon Server. I am able to do that but when I restart the server, all the events are replayed and I get collections repeated again. Here's how my code looks like. Below, I am using MongoDb for saving Products in ProductDB and MySQL for eventStore. Application Yaml spring: data: mongodb: database: productsDB port: 27017 host: localhost mvc: pathmatch: matching-strategy: ant_path_matcher datasource: url: jdbc:mysql://localhost:3306/mysql?autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true username: dinesh password: abc123 name: mysql jpa: show-sql: true hibernate: ddl-auto: create properties: hibernate: dialect: org.hibernate.dialect.MySQL8Dialect ##Axon configuration axon: serializer: events: jackson general: jackson messages: jackson In Pom.Xml, I tried excluding axon-server-connector and including as well. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>2.7.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.7.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>${springfox.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox.version}</version> </dependency> <dependency> <groupId>org.axonframework</groupId> <artifactId>axon-spring-boot-starter</artifactId> <version>${axon-spring-boot-starter.version}</version> <exclusions> <exclusion> <groupId>org.axonframework</groupId> <artifactId>axon-server-connector</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>${commons-beanutils.version}</version> </dependency> <dependency> <groupId>org.axonframework.extensions.mongo</groupId> <artifactId>axon-mongo</artifactId> <version>${axon-mongo.version}</version> </dependency> <dependency> <groupId>org.axonframework</groupId> <artifactId>axon-metrics</artifactId> <version>${axon-metrics.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.0.31</version> </dependency> Here's my AxonConfig @Configuration public class AxonConfig { @Bean public EntityManagerProvider getEntityManagerProvider(){ return new ContainerManagedEntityManagerProvider(); } /* @Bean public EventStore eventStore(EventStorageEngine storageEngine, GlobalMetricRegistry metricRegistry) { return EmbeddedEventStore.builder() .storageEngine(storageEngine) .messageMonitor(metricRegistry .registerEventBus("eventStore")) .build(); }*/ @Bean public TokenStore tokenStore( EntityManagerProvider entityManagerProvider) { return JpaTokenStore.builder().entityManagerProvider(entityManagerProvider) .serializer(JacksonSerializer.defaultSerializer()).build(); } @Bean public EventStorageEngine eventStorageEngine(Serializer serializer, PersistenceExceptionResolver persistenceExceptionResolver, @Qualifier("eventSerializer") Serializer eventSerializer, EntityManagerProvider entityManagerProvider, TransactionManager transactionManager) throws SQLException { JpaEventStorageEngine eventStorageEngine = JpaEventStorageEngine.builder() .snapshotSerializer(serializer) .persistenceExceptionResolver(persistenceExceptionResolver) .eventSerializer(serializer) .entityManagerProvider(entityManagerProvider) .transactionManager(transactionManager) .build(); return eventStorageEngine; } @Bean public EventUpcasterChain eventUpcasters(){ return new EventUpcasterChain(); } } I start my axon server and Application. Step 1: Http POST Create a new product (WORKS) Step 2: On Axon Server dashboard , event is created (WORKS) Step 3: In MongoDb, Product collection is created and entry can be verified (WORKS) Step 4: Stop the Springboot applicatio and restart. Step 5: MongoDb has an additional record because event was played again. What's missing here? Here's what I already tried: Create EventStore also in MOngo (Works) but I don't want to use Mongo for eventStore and want to stick to MySql/PostgreSql for Axon server ( All examples on Youtube, documents just show with H2) Tried adding and also removing the axon-server-connector (DomainEventEntry is not created in either case) When I enable the code to exclude <exclusions> <exclusion> <groupId>org.axonframework</groupId> <artifactId>axon-server-connector</artifactId> </exclusion> </exclusions> I get below error 2022-12-03 03:24:47.844 WARN 43476 --- [cessor[event]-0] o.a.e.TrackingEventProcessor : Fetch Segments for Processor 'event' failed: org.hibernate.hql.internal.ast.QuerySyntaxException: DomainEventEntry is not mapped [SELECT MIN(e.globalIndex) - 1 FROM DomainEventEntry e]. Preparing for retry in 1s java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: DomainEventEntry is not mapped [SELECT MIN(e.globalIndex) - 1 FROM DomainEventEntry e] at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:757) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:848) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:114) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na] at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311) ~[spring-orm-5.3.24.jar:5.3.24] at com.sun.proxy.$Proxy147.createQuery(Unknown Source) ~[na:na] at org.axonframework.eventsourcing.eventstore.jpa.JpaEventStorageEngine.createTailToken(JpaEventStorageEngine.java:361) ~[axon-eventsourcing-4.6.2.jar:4.6.2] at org.axonframework.eventsourcing.eventstore.AbstractEventStore.createTailToken(AbstractEventStore.java:171) ~[axon-eventsourcing-4.6.2.jar:4.6.2] at org.axonframework.eventhandling.TrackingEventProcessor$WorkerLauncher.lambda$run$1(TrackingEventProcessor.java:1218) ~[axon-messaging-4.6.2.jar:4.6.2] at org.axonframework.common.transaction.TransactionManager.executeInTransaction(TransactionManager.java:47) ~[axon-messaging-4.6.2.jar:4.6.2] at org.axonframework.eventhandling.TrackingEventProcessor$WorkerLauncher.run(TrackingEventProcessor.java:1216) ~[axon-messaging-4.6.2.jar:4.6.2] at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na] Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: DomainEventEntry is not mapped [SELECT MIN(e.globalIndex) - 1 FROM DomainEventEntry e] at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:220) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:162) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:636) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:748) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] ... 14 common frames omitted Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: DomainEventEntry is not mapped at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:170) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:77) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:334) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3782) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3671) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:746) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:602) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:339) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:287) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:276) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:192) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] ... 20 common frames omitted What else can I try? A: I found the issue. Here's short summary how I fixed it. Addinng Entity Scan fixed the issue @SpringBootApplication @EnableSwagger2 **@EntityScan(basePackageClasses = {DomainEventEntry.class, SagaEntry.class, TokenEntry.class})** public class EventEventApplication { public static void main(String[] args) { SpringApplication.run(EventEventApplication.class, args); } } Here's the Axon documentation https://docs.axoniq.io/reference-guide/axon-framework/spring-boot-integration#jpa-and-persistence-contexts TLDR : Long explanation I figured it out what was happening. I think this will help people who are getting same issue. Summary: Scenario 1 By default when you use <dependency> <groupId>org.axonframework</groupId> <artifactId>axon-spring-boot-starter</artifactId> <version>${axon-spring-boot-starter.version}</version> </dependency> the axon-server is included and app the wants to use the axon-server to store events. The Axon framework, will pick the first available JPA from you code and use it to store the events. Ex: If you use "JUST" H2 or MySQL database, the "Your tables" along with Axon-server event tables like Saga/Token Entry etc are saved in the same schema. This is when you don't create any AxonConfiguration and override to create a different Schema. Senario2: You have a table called "Product" in schema "ProductDB". On an event handler senario, your data will get saved in ProductDB/Product table. If you have not added any Axon configuration class, AxonAutoConfigure will save the Axon-server table also in "ProductsDB" ex: ProductsDB/Token-entry. If you want to keep Same DB but different Schemas ex: Products in ProductDB and Axon tables in AXONDB schema then you need to write AxonConfiguration, provide EntityManagerProvider, TokenStore and EventStorageEngine. Scenario 3 This was my scenario. My entity Product is saved in MONGODB and I wanted to save Axon events in MySQL. Now I added Axon configuration and provide the three amigo beans @Bean public EntityManagerProvider getEntityManagerProvider(){ return new ContainerManagedEntityManagerProvider(); } @Bean public TokenStore tokenStore(EntityManagerProvider entityManagerProvider) { return JpaTokenStore.builder().entityManagerProvider(entityManagerProvider) .serializer(JacksonSerializer.defaultSerializer()).build(); } @Bean public EventStorageEngine eventStorageEngine(Serializer serializer, PersistenceExceptionResolver persistenceExceptionResolver, @Qualifier("eventSerializer") Serializer eventSerializer, EntityManagerProvider entityManagerProvider, TransactionManager transactionManager) throws SQLException { JpaEventStorageEngine eventStorageEngine = JpaEventStorageEngine.builder() .snapshotSerializer(serializer) .persistenceExceptionResolver(persistenceExceptionResolver) .eventSerializer(serializer) .entityManagerProvider(entityManagerProvider) .transactionManager(transactionManager) .build(); return eventStorageEngine; } Now the problem as I stated was that everything was fine, but in MySQL, I was not seeing domain_entry_event table and snapshot_entry_event tables. I assumed it was OK as I was using AXON-SERVER. The problem came when I restarted the application and I saw that Events were getting reapplied which was already executed to save Product entry in DB. Root Cause: When you use a Jpa then you must also override default configuration to tell axon to stop using Axon-server (exlude axon-server-connector from starter), then you must tell the persistent context to scan table @EntityScan(basePackageClasses = {DomainEventEntry.class, SagaEntry.class, TokenEntry.class}) Addinng Entity Scan fixed the issue @SpringBootApplication @EnableSwagger2 **@EntityScan(basePackageClasses = {DomainEventEntry.class, SagaEntry.class, TokenEntry.class})** public class EventEventApplication { public static void main(String[] args) { SpringApplication.run(EventEventApplication.class, args); } }
AXON: Use MySql for EventStore and MongoDb for Projection - Events recreating records
I have an existing app that saved collections in MongoDb. As mentioned in documentation and on https://www.youtube.com/watch?v=342tqAORbAM that MongoDB is not right and that I should use plain RDBMS like MySQL /- Axon Server. I am able to do that but when I restart the server, all the events are replayed and I get collections repeated again. Here's how my code looks like. Below, I am using MongoDb for saving Products in ProductDB and MySQL for eventStore. Application Yaml spring: data: mongodb: database: productsDB port: 27017 host: localhost mvc: pathmatch: matching-strategy: ant_path_matcher datasource: url: jdbc:mysql://localhost:3306/mysql?autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true username: dinesh password: abc123 name: mysql jpa: show-sql: true hibernate: ddl-auto: create properties: hibernate: dialect: org.hibernate.dialect.MySQL8Dialect ##Axon configuration axon: serializer: events: jackson general: jackson messages: jackson In Pom.Xml, I tried excluding axon-server-connector and including as well. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>2.7.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.7.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>${springfox.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox.version}</version> </dependency> <dependency> <groupId>org.axonframework</groupId> <artifactId>axon-spring-boot-starter</artifactId> <version>${axon-spring-boot-starter.version}</version> <exclusions> <exclusion> <groupId>org.axonframework</groupId> <artifactId>axon-server-connector</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>${commons-beanutils.version}</version> </dependency> <dependency> <groupId>org.axonframework.extensions.mongo</groupId> <artifactId>axon-mongo</artifactId> <version>${axon-mongo.version}</version> </dependency> <dependency> <groupId>org.axonframework</groupId> <artifactId>axon-metrics</artifactId> <version>${axon-metrics.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.0.31</version> </dependency> Here's my AxonConfig @Configuration public class AxonConfig { @Bean public EntityManagerProvider getEntityManagerProvider(){ return new ContainerManagedEntityManagerProvider(); } /* @Bean public EventStore eventStore(EventStorageEngine storageEngine, GlobalMetricRegistry metricRegistry) { return EmbeddedEventStore.builder() .storageEngine(storageEngine) .messageMonitor(metricRegistry .registerEventBus("eventStore")) .build(); }*/ @Bean public TokenStore tokenStore( EntityManagerProvider entityManagerProvider) { return JpaTokenStore.builder().entityManagerProvider(entityManagerProvider) .serializer(JacksonSerializer.defaultSerializer()).build(); } @Bean public EventStorageEngine eventStorageEngine(Serializer serializer, PersistenceExceptionResolver persistenceExceptionResolver, @Qualifier("eventSerializer") Serializer eventSerializer, EntityManagerProvider entityManagerProvider, TransactionManager transactionManager) throws SQLException { JpaEventStorageEngine eventStorageEngine = JpaEventStorageEngine.builder() .snapshotSerializer(serializer) .persistenceExceptionResolver(persistenceExceptionResolver) .eventSerializer(serializer) .entityManagerProvider(entityManagerProvider) .transactionManager(transactionManager) .build(); return eventStorageEngine; } @Bean public EventUpcasterChain eventUpcasters(){ return new EventUpcasterChain(); } } I start my axon server and Application. Step 1: Http POST Create a new product (WORKS) Step 2: On Axon Server dashboard , event is created (WORKS) Step 3: In MongoDb, Product collection is created and entry can be verified (WORKS) Step 4: Stop the Springboot applicatio and restart. Step 5: MongoDb has an additional record because event was played again. What's missing here? Here's what I already tried: Create EventStore also in MOngo (Works) but I don't want to use Mongo for eventStore and want to stick to MySql/PostgreSql for Axon server ( All examples on Youtube, documents just show with H2) Tried adding and also removing the axon-server-connector (DomainEventEntry is not created in either case) When I enable the code to exclude <exclusions> <exclusion> <groupId>org.axonframework</groupId> <artifactId>axon-server-connector</artifactId> </exclusion> </exclusions> I get below error 2022-12-03 03:24:47.844 WARN 43476 --- [cessor[event]-0] o.a.e.TrackingEventProcessor : Fetch Segments for Processor 'event' failed: org.hibernate.hql.internal.ast.QuerySyntaxException: DomainEventEntry is not mapped [SELECT MIN(e.globalIndex) - 1 FROM DomainEventEntry e]. Preparing for retry in 1s java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: DomainEventEntry is not mapped [SELECT MIN(e.globalIndex) - 1 FROM DomainEventEntry e] at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:757) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:848) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:114) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na] at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311) ~[spring-orm-5.3.24.jar:5.3.24] at com.sun.proxy.$Proxy147.createQuery(Unknown Source) ~[na:na] at org.axonframework.eventsourcing.eventstore.jpa.JpaEventStorageEngine.createTailToken(JpaEventStorageEngine.java:361) ~[axon-eventsourcing-4.6.2.jar:4.6.2] at org.axonframework.eventsourcing.eventstore.AbstractEventStore.createTailToken(AbstractEventStore.java:171) ~[axon-eventsourcing-4.6.2.jar:4.6.2] at org.axonframework.eventhandling.TrackingEventProcessor$WorkerLauncher.lambda$run$1(TrackingEventProcessor.java:1218) ~[axon-messaging-4.6.2.jar:4.6.2] at org.axonframework.common.transaction.TransactionManager.executeInTransaction(TransactionManager.java:47) ~[axon-messaging-4.6.2.jar:4.6.2] at org.axonframework.eventhandling.TrackingEventProcessor$WorkerLauncher.run(TrackingEventProcessor.java:1216) ~[axon-messaging-4.6.2.jar:4.6.2] at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na] Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: DomainEventEntry is not mapped [SELECT MIN(e.globalIndex) - 1 FROM DomainEventEntry e] at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:220) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:162) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:636) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:748) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] ... 14 common frames omitted Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: DomainEventEntry is not mapped at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:170) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:77) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:334) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3782) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3671) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:746) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:602) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:339) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:287) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:276) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:192) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final] ... 20 common frames omitted What else can I try?
[ "I found the issue. Here's short summary how I fixed it.\nAddinng Entity Scan fixed the issue\n@SpringBootApplication\n@EnableSwagger2\n**@EntityScan(basePackageClasses = {DomainEventEntry.class, SagaEntry.class, TokenEntry.class})**\npublic class EventEventApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(EventEventApplication.class, args);\n }\n\n}\n\n\nHere's the Axon documentation\nhttps://docs.axoniq.io/reference-guide/axon-framework/spring-boot-integration#jpa-and-persistence-contexts\nTLDR : Long explanation\nI figured it out what was happening. I think this will help people who are getting same issue.\nSummary:\nScenario 1\nBy default when you use\n<dependency>\n <groupId>org.axonframework</groupId>\n <artifactId>axon-spring-boot-starter</artifactId>\n <version>${axon-spring-boot-starter.version}</version>\n </dependency>\n\nthe axon-server is included and app the wants to use the axon-server to store events. The Axon framework, will pick the first available JPA from you code and use it to store the events.\nEx: If you use \"JUST\" H2 or MySQL database, the \"Your tables\" along with Axon-server event tables like Saga/Token Entry etc are saved in the same schema. This is when you don't create any AxonConfiguration and override to create a different Schema.\nSenario2:\nYou have a table called \"Product\" in schema \"ProductDB\". On an event handler senario, your data will get saved in ProductDB/Product table. If you have not added any Axon configuration class, AxonAutoConfigure will save the Axon-server table also in \"ProductsDB\" ex: ProductsDB/Token-entry.\nIf you want to keep Same DB but different Schemas ex: Products in ProductDB and Axon tables in AXONDB schema then you need to write AxonConfiguration, provide EntityManagerProvider, TokenStore and EventStorageEngine.\nScenario 3\nThis was my scenario. My entity Product is saved in MONGODB and I wanted to save Axon events in MySQL. Now I added Axon configuration and provide the three amigo beans\n@Bean\n public EntityManagerProvider getEntityManagerProvider(){\n return new ContainerManagedEntityManagerProvider();\n }\n\n @Bean\n public TokenStore tokenStore(EntityManagerProvider entityManagerProvider) {\n return JpaTokenStore.builder().entityManagerProvider(entityManagerProvider)\n .serializer(JacksonSerializer.defaultSerializer()).build();\n }\n\n@Bean\n public EventStorageEngine eventStorageEngine(Serializer serializer,\n PersistenceExceptionResolver persistenceExceptionResolver,\n @Qualifier(\"eventSerializer\") Serializer eventSerializer,\n EntityManagerProvider entityManagerProvider,\n TransactionManager transactionManager) throws SQLException {\n\n JpaEventStorageEngine eventStorageEngine = JpaEventStorageEngine.builder()\n .snapshotSerializer(serializer)\n .persistenceExceptionResolver(persistenceExceptionResolver)\n .eventSerializer(serializer)\n .entityManagerProvider(entityManagerProvider)\n .transactionManager(transactionManager)\n .build();\n\n return eventStorageEngine;\n }\n\n\nNow the problem as I stated was that everything was fine, but in MySQL, I was not seeing domain_entry_event table and snapshot_entry_event tables. I assumed it was OK as I was using AXON-SERVER. The problem came when I restarted the application and I saw that Events were getting reapplied which was already executed to save Product entry in DB.\nRoot Cause: When you use a Jpa then you must also override default configuration to tell axon to stop using Axon-server (exlude axon-server-connector from starter), then you must tell the persistent context to scan table\n@EntityScan(basePackageClasses = {DomainEventEntry.class, SagaEntry.class, TokenEntry.class})\nAddinng Entity Scan fixed the issue\n@SpringBootApplication\n@EnableSwagger2\n**@EntityScan(basePackageClasses = {DomainEventEntry.class, SagaEntry.class, TokenEntry.class})**\npublic class EventEventApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(EventEventApplication.class, args);\n }\n\n}\n\n\n" ]
[ 0 ]
[]
[]
[ "axon" ]
stackoverflow_0074665121_axon.txt
Q: FCM flutter enable notification vibration I'm developing a Flutter application for Android and IOS. I have created notification channels for Android according to this article. My node.js payload: const payload = { notification: { title: "title", }, android: { priority: "high", ttl: 60 * 60 * 1, notification: { channel_id: 'YO', }, }, apns: { payload: { aps: { sound: "sound_03.caf" } }, headers: { "apns-collapse-id": "yo", "apns-priority": "10" } }, priority: 10 } My notifications are working just fine, for both Android and IOS using. The problem is that vibration is disabled by default. How to enable notification vibration for Android and IOS for Firebase Cloud Messaging? A: You can set the sound property to default so it makes uses the default sound if sound is enabled and it vibrates if the device is on vibrate. You can update your payload to this: const payload = { notification: { title: "title", sound: "default" }, android: { priority: "high", ttl: 60 * 60 * 1, notification: { channel_id: 'YO', }, }, apns: { payload: { aps: { sound: "default" } }, headers: { "apns-collapse-id": "yo", "apns-priority": "10" } }, priority: 10 } A: For me, I only needed to add it to the notification portion of the message payload. Below is how it looks in Typescript (but the message JSON is all that matters). let tokens = ... let message = { message: { notification: { title: title, body: body, sound: 'default', // <----- All I needed }, data: { ... }, } } firebase.messaging().sendToDevice(tokens, message)
FCM flutter enable notification vibration
I'm developing a Flutter application for Android and IOS. I have created notification channels for Android according to this article. My node.js payload: const payload = { notification: { title: "title", }, android: { priority: "high", ttl: 60 * 60 * 1, notification: { channel_id: 'YO', }, }, apns: { payload: { aps: { sound: "sound_03.caf" } }, headers: { "apns-collapse-id": "yo", "apns-priority": "10" } }, priority: 10 } My notifications are working just fine, for both Android and IOS using. The problem is that vibration is disabled by default. How to enable notification vibration for Android and IOS for Firebase Cloud Messaging?
[ "You can set the sound property to default so it makes uses the default sound if sound is enabled and it vibrates if the device is on vibrate.\nYou can update your payload to this:\nconst payload = {\n notification: {\n title: \"title\",\n sound: \"default\"\n },\n android: {\n priority: \"high\",\n ttl: 60 * 60 * 1,\n notification: {\n channel_id: 'YO',\n },\n },\n apns: {\n payload: {\n aps: {\n sound: \"default\"\n }\n },\n headers: {\n \"apns-collapse-id\": \"yo\",\n \"apns-priority\": \"10\"\n }\n },\n priority: 10\n}\n\n", "For me, I only needed to add it to the notification portion of the message payload.\nBelow is how it looks in Typescript (but the message JSON is all that matters).\nlet tokens = ...\nlet message = {\n message: {\n notification: {\n title: title,\n body: body,\n sound: 'default', // <----- All I needed\n },\n data: {\n ...\n },\n }\n}\n\nfirebase.messaging().sendToDevice(tokens, message)\n\n" ]
[ 2, 0 ]
[]
[]
[ "firebase", "firebase_cloud_messaging", "flutter", "notifications" ]
stackoverflow_0069029951_firebase_firebase_cloud_messaging_flutter_notifications.txt
Q: React: how to toggle css class in a component based on 3 different state elements I have a Card component that has 4 potential states: "active", "selected", "discarded", "complete". Depending on the state, I need to display a different css class. The states are set by clicking on specific parts of the card and each part is a "toggle" (one click sets it, another click "unsets" it): default state is active, if the user click on the card, it gets selected (the css class I need to add is "overlay-selected") if the user click on "discard" btn inside the card it sets to "discarded" (the css class I need to add is "overlay-discarded" ) if the user click on "complete" btn inside the card it sets to "complete" (the css class I need to add is "overlay-complete" ) The state is stored at the "App" level and I am passing it to the component through props. This means that for updating the states I am passing some "handler" from the app to the component (SelectCard, DiscardCard) Here below is my code. I think they way I am approaching the problem is not ideal because I am having problem on how to best defyining the ClassName of the variable. I initially thought about using a ternary if statement, but with more than one status it doesn't work. Especially because I need to take care of the "toggle" use-case. App function App() { const [people, setPeople] = useState(data['people'].map( el=>{ return { ...el, 'key' : nanoid(), } } )) function SelectCard(CardKey){ setPeople(oldPeople=>{ return oldPeople.map(el=>{ return el.key === CardKey ? { ...el, 'selected':!el.selected} : { ...el, 'selected':false} }) }) } function DiscardCard(CardKey){ setPeople(oldPeople=>{ return oldPeople.map(el=>{ return el.key === CardKey ? { ...el, 'active':!el.active} : { ...el} }) }) } const cards = people.map(el=>{ return <Card key = {el.key} item={el} onPress={()=>SelectCard(el.key)} onDiscard={()=>DiscardCard(el.key)} /> }) return ( <div className="App"> <div className='container'> <div className='left'> <div className='cards'> {cards} </div> </div> <div className = 'right'> .... </div> </div> </div> ) } export default App Card function Card(props) { const className = `card ${props.item.selected ? "overlay-selected" : ""}` return ( <div className={className} onClick={(event)=>{props.onPress()}}> <img className='card-img' alt='Card Image' src={props.item.img} /> <h3 className='card-title'>{props.item.name} </h3> { props.item.selected ? <div className='card-cta'> <button className='btn btn-back' onClick={ props.item.selected ? (event)=> { event.preventDefault() props.onPress } : ()=>{}} >Back</button> <button className='btn btn-discard' onClick={ props.item.selected ? (event) =>{ event.preventDefault() props.onDiscard } : ()=>{}} >Discard</button> </div> : <p className='card-description'>{props.item.description} </p> } </div> ) } A: Achieving this can be creating a function that maps the state of your card to the appropriate class name. This function can be called from within the Card component and would return the class name as a string. function getClassName(state) { switch (state) { case "active": return ""; case "selected": return "overlay-selected"; case "discarded": return "overlay-discarded"; case "complete": return "overlay-complete"; default: return ""; } } Then, in your Card component, you can call this function to get the appropriate class name based on the state of the card. function Card(props) { const className = `card ${getClassName(props.item.state)}`; return ( // ... ) } So you can easily update the class name of your card based on its state by simply calling getClassName and passing in the current state of the card.
React: how to toggle css class in a component based on 3 different state elements
I have a Card component that has 4 potential states: "active", "selected", "discarded", "complete". Depending on the state, I need to display a different css class. The states are set by clicking on specific parts of the card and each part is a "toggle" (one click sets it, another click "unsets" it): default state is active, if the user click on the card, it gets selected (the css class I need to add is "overlay-selected") if the user click on "discard" btn inside the card it sets to "discarded" (the css class I need to add is "overlay-discarded" ) if the user click on "complete" btn inside the card it sets to "complete" (the css class I need to add is "overlay-complete" ) The state is stored at the "App" level and I am passing it to the component through props. This means that for updating the states I am passing some "handler" from the app to the component (SelectCard, DiscardCard) Here below is my code. I think they way I am approaching the problem is not ideal because I am having problem on how to best defyining the ClassName of the variable. I initially thought about using a ternary if statement, but with more than one status it doesn't work. Especially because I need to take care of the "toggle" use-case. App function App() { const [people, setPeople] = useState(data['people'].map( el=>{ return { ...el, 'key' : nanoid(), } } )) function SelectCard(CardKey){ setPeople(oldPeople=>{ return oldPeople.map(el=>{ return el.key === CardKey ? { ...el, 'selected':!el.selected} : { ...el, 'selected':false} }) }) } function DiscardCard(CardKey){ setPeople(oldPeople=>{ return oldPeople.map(el=>{ return el.key === CardKey ? { ...el, 'active':!el.active} : { ...el} }) }) } const cards = people.map(el=>{ return <Card key = {el.key} item={el} onPress={()=>SelectCard(el.key)} onDiscard={()=>DiscardCard(el.key)} /> }) return ( <div className="App"> <div className='container'> <div className='left'> <div className='cards'> {cards} </div> </div> <div className = 'right'> .... </div> </div> </div> ) } export default App Card function Card(props) { const className = `card ${props.item.selected ? "overlay-selected" : ""}` return ( <div className={className} onClick={(event)=>{props.onPress()}}> <img className='card-img' alt='Card Image' src={props.item.img} /> <h3 className='card-title'>{props.item.name} </h3> { props.item.selected ? <div className='card-cta'> <button className='btn btn-back' onClick={ props.item.selected ? (event)=> { event.preventDefault() props.onPress } : ()=>{}} >Back</button> <button className='btn btn-discard' onClick={ props.item.selected ? (event) =>{ event.preventDefault() props.onDiscard } : ()=>{}} >Discard</button> </div> : <p className='card-description'>{props.item.description} </p> } </div> ) }
[ "Achieving this can be creating a function that maps the state of your card to the appropriate class name. This function can be called from within the Card component and would return the class name as a string.\nfunction getClassName(state) {\n switch (state) {\n case \"active\":\n return \"\";\n case \"selected\":\n return \"overlay-selected\";\n case \"discarded\":\n return \"overlay-discarded\";\n case \"complete\":\n return \"overlay-complete\";\n default:\n return \"\";\n }\n}\n\nThen, in your Card component, you can call this function to get the appropriate class name based on the state of the card.\nfunction Card(props) {\n const className = `card ${getClassName(props.item.state)}`;\n\n return (\n // ...\n )\n}\n\nSo you can easily update the class name of your card based on its state by simply calling getClassName and passing in the current state of the card.\n" ]
[ 1 ]
[]
[]
[ "css", "javascript", "reactjs" ]
stackoverflow_0074670488_css_javascript_reactjs.txt
Q: httpx.RemoteProtocolError: peer closed connection without sending complete message body I am getting the above error despite setting the timeout to None for the httpx call. I am not sure what I am doing wrong. from httpx import stream with stream("GET", url, params=url_parameters, headers=headers, timeout=None) as streamed_response: A: I've got the same error when using httpx via openapi-client autogenerated client response = httpx.request(verify=client.verify_ssl,**kwargs,) It turned out in kwargs parameter headers contained wrong authorization token. So basically in my case that error meant "authorization error". You might want to check if what you sending in your parameters is correct too.
httpx.RemoteProtocolError: peer closed connection without sending complete message body
I am getting the above error despite setting the timeout to None for the httpx call. I am not sure what I am doing wrong. from httpx import stream with stream("GET", url, params=url_parameters, headers=headers, timeout=None) as streamed_response:
[ "I've got the same error when using httpx via openapi-client autogenerated client\nresponse = httpx.request(verify=client.verify_ssl,**kwargs,)\n\nIt turned out in kwargs parameter headers contained wrong authorization token.\nSo basically in my case that error meant \"authorization error\".\nYou might want to check if what you sending in your parameters is correct too.\n" ]
[ 0 ]
[]
[]
[ "httpx", "python" ]
stackoverflow_0074153345_httpx_python.txt
Q: What are the uses of circular buffer? What are some of the uses of circular buffer? What are the benefits of using a circular buffer? is it an alternative to double linked list? A: I've used it for an in-memory log with a restricted size. For example, the application would write log entries while processing user requests. Whenever an exception occurred (that would be disruptive to the processing) the log records currently in memory would be dumped along with it. The benefit of a circular buffer is, that you don't need infinite amounts of memory, since older entries get overridden automatically. The "challange" is, that you need to find a suitable size for your usecase. In the example above, it would be very unfortunate when the log record with the most vital information about the exception would have already been overridden. Some systems/applications have tools to let you extract the current content of the buffer on demand, and not only when it would be extract automatically (if ever). I believe ETW and the CLRs stress log, amongst many other system's kernel or highperformance trace/logging, are implemented that way. The concept of using such buffers for in-memory tracing/logging is actually pretty common (not to say that this is the only use - certainly not), because it is way faster than written records to a file/database that you might never be interested in unless an error occurs. And on a related note, it conserves harddisk space. A: Circular buffers are good for serial data streams in embedded systems. Microcontrollers often have a UART to handle a serial byte coming in, these need to be stored in order and dealt with later (bytes often come in at a faster rate than they can be handled). The buffer effectively splits the timing-critical response required (when the bytes come in, in microseconds) to the non timing-critical response to the whole message (for example displaying the message which came in, in milliseconds), e.g.: 1) Upon the receipt of a byte the UART can generate an interrupt to which the software responds by quickly taking the received byte and shoves it onto the end of the buffer. 2) Background software routines can then regularly check if the buffer has anything in it yet and empty it as required. As the circular buffer size can be defined pre-compilation the size is then limited. This helps improve space efficiency and should eliminate memory corruption at a trade off to how many bytes can be received before data starts to become lost. A: A circular buffer is a nice mechanism for efficiently maintaining a sliding/moving list of values/items in an ordered fashion. One example might be to maintain a sliding average of the last N items. Suppose you want to track the average cost of the last 100 operations of computing some value. To do this, you would need to remove the oldest cost and add in the newest cost. Without a circular buffer, a costly mechanism for doing this (C style) would be to have an array of 100 elements. Each time a new cost is computed, you could memmove the 99 elements down and put the new one in at the last position. This is obviously costly. Using a circular buffer idea, you would just track the β€œend” of the buffer (position 0-99). It would mark the position of the oldest (or newest … whichever you choose) cost item. After reading the old value (for updating the running average), you replace it with the newest value and increment the buffer position (if it is at 99, you set it back to 0 … thus, the circular part). Comparing it to a doubly linked list doesn’t really make sense. A circular buffer could certainly be implemented with a doubly linked list (or even a singly linked list). But comparing them is a little bit like comparing apples and oranges so to speak. A: I know this is cheating, but wikipedia does have a very good explaination. http://en.wikipedia.org/wiki/Circular_buffer A circular buffer, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. This structure lends itself easily to buffering data streams An example that could possibly use an overwriting circular buffer is with multimedia. If the buffer is used as the bounded buffer in the producer-consumer problem then it is probably desired for the producer (e.g., an audio generator) to overwrite old data if the consumer (e.g., the sound card) is unable to momentarily keep up. Another example is the digital waveguide synthesis method which uses circular buffers to efficiently simulate the sound of vibrating strings or wind instruments. With regards comparing to double-linked lists, I imagine it really does depend on what you are using the list for... Implementation of cirular buffers seems to be more complex, please (again) refer to the wiki page; this explains implementation, considerations etc and also shows example code. Thanks, Neil A: I've used it as an easy way of implementing round-robin scheduling. Basically I had a bunch of different objects that can produce a value that a consumer could then process. I stuck all the producers in a ring and asked each one in turn. A: I have used a ring buffer in multi-threaded code. Basically, if all slots are full the producer(s) have to wait. The consumers simply process items in slots that are "full". Here's a thread I started on it. It has some good advice on implementation. .NET multi-threaded variable access A: I think the all-consuming answer is, "memory sensitive tasks when you want to read sequentially generated data in order of creation, and don't care about old data beyond the nth to last received datum."
What are the uses of circular buffer?
What are some of the uses of circular buffer? What are the benefits of using a circular buffer? is it an alternative to double linked list?
[ "I've used it for an in-memory log with a restricted size. For example, the application would write log entries while processing user requests. Whenever an exception occurred (that would be disruptive to the processing) the log records currently in memory would be dumped along with it.\nThe benefit of a circular buffer is, that you don't need infinite amounts of memory, since older entries get overridden automatically. The \"challange\" is, that you need to find a suitable size for your usecase. In the example above, it would be very unfortunate when the log record with the most vital information about the exception would have already been overridden.\nSome systems/applications have tools to let you extract the current content of the buffer on demand, and not only when it would be extract automatically (if ever).\nI believe ETW and the CLRs stress log, amongst many other system's kernel or highperformance trace/logging, are implemented that way.\nThe concept of using such buffers for in-memory tracing/logging is actually pretty common (not to say that this is the only use - certainly not), because it is way faster than written records to a file/database that you might never be interested in unless an error occurs. And on a related note, it conserves harddisk space.\n", "Circular buffers are good for serial data streams in embedded systems. Microcontrollers often have a UART to handle a serial byte coming in, these need to be stored in order and dealt with later (bytes often come in at a faster rate than they can be handled). \nThe buffer effectively splits the timing-critical response required (when the bytes come in, in microseconds) to the non timing-critical response to the whole message (for example displaying the message which came in, in milliseconds), e.g.:\n1) Upon the receipt of a byte the UART can generate an interrupt to which the software responds by quickly taking the received byte and shoves it onto the end of the buffer.\n2) Background software routines can then regularly check if the buffer has anything in it yet and empty it as required.\nAs the circular buffer size can be defined pre-compilation the size is then limited. This helps improve space efficiency and should eliminate memory corruption at a trade off to how many bytes can be received before data starts to become lost.\n", "A circular buffer is a nice mechanism for efficiently maintaining a sliding/moving list of values/items in an ordered fashion. One example might be to maintain a sliding average of the last N items. Suppose you want to track the average cost of the last 100 operations of computing some value. To do this, you would need to remove the oldest cost and add in the newest cost. \nWithout a circular buffer, a costly mechanism for doing this (C style) would be to have an array of 100 elements. Each time a new cost is computed, you could memmove the 99 elements down and put the new one in at the last position. This is obviously costly. Using a circular buffer idea, you would just track the β€œend” of the buffer (position 0-99). It would mark the position of the oldest (or newest … whichever you choose) cost item. After reading the old value (for updating the running average), you replace it with the newest value and increment the buffer position (if it is at 99, you set it back to 0 … thus, the circular part). \nComparing it to a doubly linked list doesn’t really make sense. A circular buffer could certainly be implemented with a doubly linked list (or even a singly linked list). But comparing them is a little bit like comparing apples and oranges so to speak.\n", "I know this is cheating, but wikipedia does have a very good explaination.\nhttp://en.wikipedia.org/wiki/Circular_buffer\n\nA circular buffer, cyclic buffer or\n ring buffer is a data structure that\n uses a single, fixed-size buffer as if\n it were connected end-to-end. This\n structure lends itself easily to\n buffering data streams\nAn example that could possibly use an\n overwriting circular buffer is with\n multimedia. If the buffer is used as\n the bounded buffer in the\n producer-consumer problem then it is\n probably desired for the producer\n (e.g., an audio generator) to\n overwrite old data if the consumer\n (e.g., the sound card) is unable to\n momentarily keep up. Another example\n is the digital waveguide synthesis\n method which uses circular buffers to\n efficiently simulate the sound of\n vibrating strings or wind instruments.\n\nWith regards comparing to double-linked lists, I imagine it really does depend on what you are using the list for... Implementation of cirular buffers seems to be more complex, please (again) refer to the wiki page; this explains implementation, considerations etc and also shows example code.\nThanks, Neil\n", "I've used it as an easy way of implementing round-robin scheduling. Basically I had a bunch of different objects that can produce a value that a consumer could then process. I stuck all the producers in a ring and asked each one in turn.\n", "I have used a ring buffer in multi-threaded code. Basically, if all slots are full the producer(s) have to wait. The consumers simply process items in slots that are \"full\".\nHere's a thread I started on it. It has some good advice on implementation.\n.NET multi-threaded variable access\n", "I think the all-consuming answer is, \"memory sensitive tasks when you want to read sequentially generated data in order of creation, and don't care about old data beyond the nth to last received datum.\"\n" ]
[ 40, 15, 9, 7, 0, 0, 0 ]
[]
[]
[ ".net", "c#", "circular_buffer", "data_structures" ]
stackoverflow_0002553637_.net_c#_circular_buffer_data_structures.txt
Q: Firebase notification won`t sound or vibrate flutter So I have enabled firebase messaging on my futter app everything works fine but, when I receive the notification in my app it wont sound or vibrate, neither android or ios. I believe FCM does it by default, I also have "IosNotificationSettings(sound: true, badge: true, alert: true)", but the notification just come mute. Do you guys have any Idea what could be happening? I searched for this situation but couldnt find anything about it. Thanks in advance for your help. class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMixin { String _homeScreenText = "Waiting for token..."; final FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); static const String contato = "contato"; TabController _tabController; @override void initState() { _tabController = new TabController(length: 5, vsync: this); super.initState(); _firebaseMessaging.configure( onMessage: (Map<String, dynamic> message) { print('on message $message'); }, onResume: (Map<String, dynamic> message) { print('on resume $message'); }, onLaunch: (Map<String, dynamic> message) { print('on launch $message'); }, ); _firebaseMessaging.requestNotificationPermissions( const IosNotificationSettings(sound: true, badge: true, alert: true)); _firebaseMessaging.onIosSettingsRegistered .listen((IosNotificationSettings settings) { print("Settings registered: $settings"); }); _firebaseMessaging.getToken().then((String token) { assert(token != null); setState(() { _homeScreenText = "Push Messaging token: $token"; }); print(_homeScreenText); }); _firebaseMessaging.getToken().then((token) { Firestore.instance.collection("pushtokens").document().setData({"devtoken": token}); }); } A: To enable sound on notification you need to add sound: default part in notification data like this: { data: { google.sent_time: 1588863942303, click_action: FLUTTER_NOTIFICATION_CLICK, google.original_priority: high, collapse_key: YourPackageName, google.delivered_priority: high, sound: default, from: YourSenderId, google.message_id: 0:1588863942508709%a91ceea4a91ceea4, google.ttl: 60 }, notification: {} } A: You can add something like this for the http request to send the notification. But first thing you need to check is whether your phone is allowing the app to notify. which lost my most part of time. { topic: topic, android: { priority: "high", notification: { defaultSound: true, //sound: "default", }, }, data: { somedata: "value", }, notification: { title: title, body: description, imageUrl: "https://i.picsum.photos/id/999/536/354.jpg?hmac=xYKikWHOVjOpBeVAsIlSzDv9J0UYTj_tNODJCKJsDo4", }, } A: I'm sending messages from my node (Typescript) backend. I only needed to add the sound property to the notification portion of the message payload. I'm using the Firebase Message flutter SDK and didn't need to add any special configuration there. Below is how it looks in Typescript (but the message JSON is all that matters). let tokens = ... let message = { message: { notification: { title: title, body: body, sound: 'default', // <----- All I needed }, data: { ... }, } } firebase.messaging().sendToDevice(tokens, message)
Firebase notification won`t sound or vibrate flutter
So I have enabled firebase messaging on my futter app everything works fine but, when I receive the notification in my app it wont sound or vibrate, neither android or ios. I believe FCM does it by default, I also have "IosNotificationSettings(sound: true, badge: true, alert: true)", but the notification just come mute. Do you guys have any Idea what could be happening? I searched for this situation but couldnt find anything about it. Thanks in advance for your help. class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMixin { String _homeScreenText = "Waiting for token..."; final FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); static const String contato = "contato"; TabController _tabController; @override void initState() { _tabController = new TabController(length: 5, vsync: this); super.initState(); _firebaseMessaging.configure( onMessage: (Map<String, dynamic> message) { print('on message $message'); }, onResume: (Map<String, dynamic> message) { print('on resume $message'); }, onLaunch: (Map<String, dynamic> message) { print('on launch $message'); }, ); _firebaseMessaging.requestNotificationPermissions( const IosNotificationSettings(sound: true, badge: true, alert: true)); _firebaseMessaging.onIosSettingsRegistered .listen((IosNotificationSettings settings) { print("Settings registered: $settings"); }); _firebaseMessaging.getToken().then((String token) { assert(token != null); setState(() { _homeScreenText = "Push Messaging token: $token"; }); print(_homeScreenText); }); _firebaseMessaging.getToken().then((token) { Firestore.instance.collection("pushtokens").document().setData({"devtoken": token}); }); }
[ "To enable sound on notification you need to add sound: default part in notification data like this:\n{\n data: {\n google.sent_time: 1588863942303, \n click_action: FLUTTER_NOTIFICATION_CLICK, \n google.original_priority: high,\n collapse_key: YourPackageName,\n google.delivered_priority: high,\n sound: default,\n from: YourSenderId,\n google.message_id: 0:1588863942508709%a91ceea4a91ceea4,\n google.ttl: 60\n },\n notification: {}\n}\n\n", "You can add something like this for the http request to send the notification.\nBut first thing you need to check is whether your phone is allowing the app to notify. which lost my most part of time.\n{\n topic: topic,\n android: {\n priority: \"high\",\n notification: {\n defaultSound: true,\n //sound: \"default\",\n },\n },\n data: {\n somedata: \"value\",\n },\n notification: {\n title: title,\n body: description,\n imageUrl: \"https://i.picsum.photos/id/999/536/354.jpg?hmac=xYKikWHOVjOpBeVAsIlSzDv9J0UYTj_tNODJCKJsDo4\",\n },\n}\n\n", "I'm sending messages from my node (Typescript) backend. I only needed to add the sound property to the notification portion of the message payload. I'm using the Firebase Message flutter SDK and didn't need to add any special configuration there.\nBelow is how it looks in Typescript (but the message JSON is all that matters).\nlet tokens = ...\nlet message = {\n message: {\n notification: {\n title: title,\n body: body,\n sound: 'default', // <----- All I needed\n },\n data: {\n ...\n },\n }\n}\n\nfirebase.messaging().sendToDevice(tokens, message)\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "firebase_cloud_messaging", "flutter", "push_notification" ]
stackoverflow_0060892402_firebase_cloud_messaging_flutter_push_notification.txt
Q: IF ELSE in robot framework [Keyword as a condition] I just can't figure out how to map a keyword as a condition. @keyword("Is the Closed Message Page Present") def check_closedMsg_page(self): result = self.CLOSED_TEXT.is_displayed self.LOG(f"It returns {self.CLOSED_TEXT.is_displayed}") return result The above function returns a bool value either True or False. "Is the Closed Message Page Present" is a keyword which I want to make condition. If the condition is true then it should execute the below two keywords else skip it. IF Is the Closed Message Page Present = True Then Login username password And Close Browsers END I tried following: IF Is the Closed Message Page Present == 'True' Then Login username password And Close Browsers END IF 'Is the Closed Message Page Present' == 'True' Then Login username password And Close Browsers END Is the Closed Message Page Present IF True Then Login username password And Close Browsers END I am expecting the keyword (Is the Closed Message Page Present) to be condition which needs to be true to execute the other two statements or keywords. A: I'm still new to the framework, but the only simple method I found is to store the keyword return value to a local variable and use that in the IF statement. *** Settings *** Library SeleniumLibrary Library ../stackoverflow.py *** Test Cases *** robot Example ${value} Is the Closed Message Page Present IF ${value} Login username password Close Browser END *** Keywords *** Login [Arguments] ${username} ${password} log 'Logs in to system' stackoverflow.py returns a random True/False value import random from robot.api.deco import keyword class stackoverflow: @keyword("Is the Closed Message Page Present") def check_closedMsg_page(self): return random.choice([True, False]) There is an exhaustive list of conditional expressions that you could further use at https://robocorp.com/docs/languages-and-frameworks/robot-framework/conditional-execution
IF ELSE in robot framework [Keyword as a condition]
I just can't figure out how to map a keyword as a condition. @keyword("Is the Closed Message Page Present") def check_closedMsg_page(self): result = self.CLOSED_TEXT.is_displayed self.LOG(f"It returns {self.CLOSED_TEXT.is_displayed}") return result The above function returns a bool value either True or False. "Is the Closed Message Page Present" is a keyword which I want to make condition. If the condition is true then it should execute the below two keywords else skip it. IF Is the Closed Message Page Present = True Then Login username password And Close Browsers END I tried following: IF Is the Closed Message Page Present == 'True' Then Login username password And Close Browsers END IF 'Is the Closed Message Page Present' == 'True' Then Login username password And Close Browsers END Is the Closed Message Page Present IF True Then Login username password And Close Browsers END I am expecting the keyword (Is the Closed Message Page Present) to be condition which needs to be true to execute the other two statements or keywords.
[ "I'm still new to the framework, but the only simple method I found is to store the keyword return value to a local variable and use that in the IF statement.\n*** Settings ***\nLibrary SeleniumLibrary\nLibrary ../stackoverflow.py\n\n*** Test Cases ***\nrobot Example\n\n ${value} Is the Closed Message Page Present\n IF ${value}\n Login username password\n Close Browser\n END\n\n*** Keywords ***\nLogin\n [Arguments] ${username} ${password} \n log 'Logs in to system'\n\nstackoverflow.py returns a random True/False value\nimport random\nfrom robot.api.deco import keyword\n\nclass stackoverflow:\n @keyword(\"Is the Closed Message Page Present\")\n def check_closedMsg_page(self):\n return random.choice([True, False])\n\nThere is an exhaustive list of conditional expressions that you could further use at https://robocorp.com/docs/languages-and-frameworks/robot-framework/conditional-execution\n" ]
[ 0 ]
[]
[]
[ "python", "robot", "selenium" ]
stackoverflow_0074657581_python_robot_selenium.txt
Q: How to find and remove blank paragraphs in a Google Document with Google Apps Script? I am working with Google documents that contain hundreds of empty paragraphs. I want to remove these blank lines automatically. In LibreOffice Writer you can use the Find & Replace tool to replace ^$ with nothing, but that didn't work in Google Docs. My search for ^$ or ^\s*$ returned 0 results even though there should be 3 matches How can I remove the blank paragraphs with Google Apps Script? I already tried body.findText("^$");, but that returns null function removeBlankParagraphs(doc) { var body = doc.getBody(); result = body.findText("^$"); } A: I think there has to be a last empty paragraph but this seems to work. function myFunction() { var body = DocumentApp.getActiveDocument().getBody(); var paras = body.getParagraphs(); var i = 0; for (var i = 0; i < paras.length; i++) { if (paras[i].getText() === ""){ paras[i].removeFromParent() } } } A: Adding to Tom's answer and apmouse's comment, here's a revised solution that: 1) prevents removing paragraphs consisting of images or horizontal rules; 2) also removes paragraphs that only contain whitespace. function removeEmptyParagraphs() { var pars = DocumentApp.getActiveDocument().getBody().getParagraphs(); // for each paragraph in the active document... pars.forEach(function(e) { // does the paragraph contain an image or a horizontal rule? // (you may want to add other element types to this check) no_img = e.findElement(DocumentApp.ElementType.INLINE_IMAGE) === null; no_rul = e.findElement(DocumentApp.ElementType.HORIZONTAL_RULE) === null; // proceed if it only has text if (no_img && no_rul) { // clean up paragraphs that only contain whitespace e.replaceText("^\\s+$", "") // remove blank paragraphs if(e.getText() === "") { e.removeFromParent(); } } }) } A: function DeleteEmpty(doc) { var body = doc.getBody(); var paragraphs = body.getParagraphs(); for (var i = 0; i < paragraphs.length; i++) { var paragraph = paragraphs[i]; if (paragraph.getNumChildren() == 0 && paragraph.getPositionedImages().length == 0) { paragraph.removeFromParent(); } } } This solution takes into account PositionedImages, which were missing in other solutions and could be removed
How to find and remove blank paragraphs in a Google Document with Google Apps Script?
I am working with Google documents that contain hundreds of empty paragraphs. I want to remove these blank lines automatically. In LibreOffice Writer you can use the Find & Replace tool to replace ^$ with nothing, but that didn't work in Google Docs. My search for ^$ or ^\s*$ returned 0 results even though there should be 3 matches How can I remove the blank paragraphs with Google Apps Script? I already tried body.findText("^$");, but that returns null function removeBlankParagraphs(doc) { var body = doc.getBody(); result = body.findText("^$"); }
[ "I think there has to be a last empty paragraph but this seems to work. \nfunction myFunction() {\n var body = DocumentApp.getActiveDocument().getBody();\n\n var paras = body.getParagraphs();\n var i = 0;\n\n for (var i = 0; i < paras.length; i++) {\n if (paras[i].getText() === \"\"){\n paras[i].removeFromParent()\n }\n}\n}\n\n", "Adding to Tom's answer and apmouse's comment, here's a revised solution that: 1) prevents removing paragraphs consisting of images or horizontal rules; 2) also removes paragraphs that only contain whitespace.\nfunction removeEmptyParagraphs() {\n var pars = DocumentApp.getActiveDocument().getBody().getParagraphs();\n // for each paragraph in the active document...\n pars.forEach(function(e) {\n // does the paragraph contain an image or a horizontal rule?\n // (you may want to add other element types to this check)\n no_img = e.findElement(DocumentApp.ElementType.INLINE_IMAGE) === null;\n no_rul = e.findElement(DocumentApp.ElementType.HORIZONTAL_RULE) === null;\n // proceed if it only has text\n if (no_img && no_rul) {\n // clean up paragraphs that only contain whitespace\n e.replaceText(\"^\\\\s+$\", \"\")\n // remove blank paragraphs\n if(e.getText() === \"\") {\n e.removeFromParent();\n }\n } \n })\n}\n\n", "function DeleteEmpty(doc)\n{\n var body = doc.getBody();\n var paragraphs = body.getParagraphs();\n for (var i = 0; i < paragraphs.length; i++) {\n var paragraph = paragraphs[i];\n if (paragraph.getNumChildren() == 0 && paragraph.getPositionedImages().length == 0) {\n paragraph.removeFromParent();\n } \n }\n}\n\nThis solution takes into account PositionedImages, which were missing in other solutions and could be removed\n" ]
[ 7, 4, 0 ]
[]
[]
[ "google_apps_script", "google_docs" ]
stackoverflow_0039962369_google_apps_script_google_docs.txt
Q: Question about where the JSON global object comes from I am following a tutorial which introduced the global JSON object to stringify objects, in the tutorial they mention that this JSON object and it's methods is provided by the browser. I've also looked at the MDN page for JSON and they list it as a standard built in object. I'm trying to understand if an object such as this is the same as the Date or Math objects and is built into Javascript or is it something extra that is provided by browsers implementing it? A: The JSON object is a built-in object in JavaScript that provides methods for parsing JavaScript Object Notation (JSON) strings and converting values to JSON. It is part of the ECMAScript standard, which is the standard that defines the core features of the JavaScript language. This means that the JSON object is included in all JavaScript implementations, including web browsers. A: Yes, it's a built-in object that's a property of the global object, as the specification requires for implementations of ECMAScript - just like Date and Math and many others. Generally, if you want to find whether a particular object or method is universal, see if the ES specification or DOM standard says anything about it. (That said, just because something's in the standard doesn't mean that it'll be implemented everywhere - even some modern environments are not spec-compliant in a number of areas.)
Question about where the JSON global object comes from
I am following a tutorial which introduced the global JSON object to stringify objects, in the tutorial they mention that this JSON object and it's methods is provided by the browser. I've also looked at the MDN page for JSON and they list it as a standard built in object. I'm trying to understand if an object such as this is the same as the Date or Math objects and is built into Javascript or is it something extra that is provided by browsers implementing it?
[ "The JSON object is a built-in object in JavaScript that provides methods for parsing JavaScript Object Notation (JSON) strings and converting values to JSON. It is part of the ECMAScript standard, which is the standard that defines the core features of the JavaScript language. This means that the JSON object is included in all JavaScript implementations, including web browsers.\n", "Yes, it's a built-in object that's a property of the global object, as the specification requires for implementations of ECMAScript - just like Date and Math and many others.\nGenerally, if you want to find whether a particular object or method is universal, see if the ES specification or DOM standard says anything about it. (That said, just because something's in the standard doesn't mean that it'll be implemented everywhere - even some modern environments are not spec-compliant in a number of areas.)\n" ]
[ 0, 0 ]
[ "The JSON object is a built-in object in JavaScript that provides methods for converting JavaScript objects to and from JSON (JavaScript Object Notation) strings. This object is defined in the ECMAScript specification, which is the standard that defines the syntax and semantics of the JavaScript language.\nUnlike other built-in objects like Date and Math, the JSON object is not automatically available in all JavaScript environments. In some environments, such as web browsers, the JSON object is provided by the browser as a global object, which means it can be used without having to import any additional libraries or modules. In other environments, such as Node.js, the JSON object is not provided by default, and you will need to use require('json') to import it.\nIn summary, the JSON object is a built-in object in JavaScript that is provided by some environments, such as web browsers, but not by others, such as Node.js. It is useful for converting JavaScript objects to and from JSON strings.\n" ]
[ -1 ]
[ "built_in", "ecmascript_6", "javascript", "json", "methods" ]
stackoverflow_0074670496_built_in_ecmascript_6_javascript_json_methods.txt
Q: Not able to access a variable (created in a child frame) from the root window I am trying to create an application where the user enters a directory name and it gets printed in the console. For this I have created 2 classes: class FolderInputFrame(tk.Frame): ## child frame class def __init__(self, parent): tk.Frame.__init__(self, parent) self._widgets() self.pack() def _widgets(self): self.directory = tk.StringVar() buttonDir = tk.Button(self, text = 'Source Directory: ', command = self.browse_button) buttonDir.pack(side = 'left', padx = 10, pady = 10) dirEntry = tk.Entry(self, textvariable = self.directory, width = 70) dirEntry.pack(side = 'left', padx = 10, pady = 10) def browse_button(self): dirname = filedialog.askdirectory(initialdir='/', title='Please select a directory') self.directory.set(dirname) print(self.directory.get()) ## directory string from child class class MainWindow(tk.Tk): ## root class def __init__(self): tk.Tk.__init__(self) self.folder_input_container = FolderInputFrame(self) print(self.folder_input_container.directory.get()) ## directory string from root class Now when I am trying to print the directory string from the 2 classes, the child class shows the appropriate directory entered, but the root class shows an empty output. I am confused why this is happening? I am fairly new to Tkinter, so any help is appreciated here. I was expecting the strings from both root and child class should have been same after the button is pressed. I need to know how the flow of control is happening here. A: You need to access the data from the instance of the FolderInputFrame since that is the class that created the variable: print(self.folder_input_container.directory.get()) You need to make sure you do this after the user has clicked the button. In your example you're attempting to print the value immediately after creating the instance of FolderInputFrame. Use this modified version of MainWindow to see that the value has been updated. After selecting the directory, click the "Show Directory" button to have it print the value to the console. class MainWindow(tk.Tk): ## root class def __init__(self): tk.Tk.__init__(self) self.folder_input_container = FolderInputFrame(self) button = tk.Button(self, text="Print Directory", command=self.print_directory) button.pack() def print_directory(self): print(f"directory: {self.folder_input_container.directory.get()}")
Not able to access a variable (created in a child frame) from the root window
I am trying to create an application where the user enters a directory name and it gets printed in the console. For this I have created 2 classes: class FolderInputFrame(tk.Frame): ## child frame class def __init__(self, parent): tk.Frame.__init__(self, parent) self._widgets() self.pack() def _widgets(self): self.directory = tk.StringVar() buttonDir = tk.Button(self, text = 'Source Directory: ', command = self.browse_button) buttonDir.pack(side = 'left', padx = 10, pady = 10) dirEntry = tk.Entry(self, textvariable = self.directory, width = 70) dirEntry.pack(side = 'left', padx = 10, pady = 10) def browse_button(self): dirname = filedialog.askdirectory(initialdir='/', title='Please select a directory') self.directory.set(dirname) print(self.directory.get()) ## directory string from child class class MainWindow(tk.Tk): ## root class def __init__(self): tk.Tk.__init__(self) self.folder_input_container = FolderInputFrame(self) print(self.folder_input_container.directory.get()) ## directory string from root class Now when I am trying to print the directory string from the 2 classes, the child class shows the appropriate directory entered, but the root class shows an empty output. I am confused why this is happening? I am fairly new to Tkinter, so any help is appreciated here. I was expecting the strings from both root and child class should have been same after the button is pressed. I need to know how the flow of control is happening here.
[ "You need to access the data from the instance of the FolderInputFrame since that is the class that created the variable:\nprint(self.folder_input_container.directory.get())\n\nYou need to make sure you do this after the user has clicked the button. In your example you're attempting to print the value immediately after creating the instance of FolderInputFrame.\nUse this modified version of MainWindow to see that the value has been updated. After selecting the directory, click the \"Show Directory\" button to have it print the value to the console.\nclass MainWindow(tk.Tk):\n ## root class\n def __init__(self):\n tk.Tk.__init__(self)\n self.folder_input_container = FolderInputFrame(self)\n button = tk.Button(self, text=\"Print Directory\", command=self.print_directory)\n button.pack()\n\n def print_directory(self):\n print(f\"directory: {self.folder_input_container.directory.get()}\")\n\n" ]
[ 0 ]
[]
[]
[ "oop", "python", "tkinter" ]
stackoverflow_0074669692_oop_python_tkinter.txt
Q: Play Store updates/installs app using a different account than the one the user made IAP through On this bug report on Github https://github.com/googlesamples/android-play-billing/issues/2#issuecomment-305380836 we were asked to raise the issue here. The issue is simple. The user has 2 or more accounts on their phone, let's say [email protected] and [email protected]. They install an app with the account [email protected]. They purchase some IAP items. The app updates and now the app is under [email protected] and the user has lost the purchase. This happens a lot when using staged rollouts. The main issue, as developers we aren't allowed to let the user choose which account to buy with or which account to check for purchases with. The second issue, the Play Store app on Android ignores the user account selected on the hamburger menu. The only workaround for this is to use the Play Store website as described in this workaround https://github.com/googlesamples/android-play-billing/issues/2#issuecomment-259108286 on the same bug report. I don't know what the ideal solution is, all I know is that this is a huge hassle for developers leading to a lot of 1-star reviews after each update. EDIT: As pointed out in a comment, when I refer to multiple accounts I am talking about multiple Google accounts for a single Android User, I am not talking about multiple Android users within the same phone. A: One potential solution to this issue is to use the account that the user made the purchase with to verify the purchase. The Google Play Developer API allows developers to retrieve information about in-app products and subscriptions, including their purchase status. By using this API and checking the purchase status with the account that the user made the purchase with, developers can ensure that the user's purchases are properly recognized even if the app is installed under a different account. Another potential solution is to implement the "Account Chooser" feature in the app. This allows the user to choose which Google account they want to use for in-app purchases, and ensures that the purchases are properly associated with the chosen account. This feature is available through the Google Play Billing Library and can be implemented by following the instructions in the documentation. It is important to note that the user must have multiple Google accounts on their device in order for either of these solutions to be effective. If the user only has one Google account on their device, then there is no risk of the app being installed under a different account and the user's purchases being lost.
Play Store updates/installs app using a different account than the one the user made IAP through
On this bug report on Github https://github.com/googlesamples/android-play-billing/issues/2#issuecomment-305380836 we were asked to raise the issue here. The issue is simple. The user has 2 or more accounts on their phone, let's say [email protected] and [email protected]. They install an app with the account [email protected]. They purchase some IAP items. The app updates and now the app is under [email protected] and the user has lost the purchase. This happens a lot when using staged rollouts. The main issue, as developers we aren't allowed to let the user choose which account to buy with or which account to check for purchases with. The second issue, the Play Store app on Android ignores the user account selected on the hamburger menu. The only workaround for this is to use the Play Store website as described in this workaround https://github.com/googlesamples/android-play-billing/issues/2#issuecomment-259108286 on the same bug report. I don't know what the ideal solution is, all I know is that this is a huge hassle for developers leading to a lot of 1-star reviews after each update. EDIT: As pointed out in a comment, when I refer to multiple accounts I am talking about multiple Google accounts for a single Android User, I am not talking about multiple Android users within the same phone.
[ "One potential solution to this issue is to use the account that the user made the purchase with to verify the purchase. The Google Play Developer API allows developers to retrieve information about in-app products and subscriptions, including their purchase status. By using this API and checking the purchase status with the account that the user made the purchase with, developers can ensure that the user's purchases are properly recognized even if the app is installed under a different account.\nAnother potential solution is to implement the \"Account Chooser\" feature in the app. This allows the user to choose which Google account they want to use for in-app purchases, and ensures that the purchases are properly associated with the chosen account. This feature is available through the Google Play Billing Library and can be implemented by following the instructions in the documentation.\nIt is important to note that the user must have multiple Google accounts on their device in order for either of these solutions to be effective. If the user only has one Google account on their device, then there is no risk of the app being installed under a different account and the user's purchases being lost.\n" ]
[ 0 ]
[]
[]
[ "google_play", "google_play_services", "in_app_billing", "in_app_purchase" ]
stackoverflow_0044397765_google_play_google_play_services_in_app_billing_in_app_purchase.txt
Q: Flutter InAppWebView iOS goes to live broadcast instead of camera I'm using the flutter_inappwebview package to show our website as a web view in our Flutter iOS app. The website supports video recording, and everything works fine on the web. Whenever the user starts recording from the app, it accidentally redirects them to live broadcast instead of the camera. It's a bit complicated to explain, So I'm attaching this short video: Any suggestions why it happens? Is that an InAppWebView issue? Check out our discussion on GitHub. flutter doctor: [βœ“] Flutter (Channel stable, 3.3.7, on macOS 13.0 22A380 darwin-x64, locale en-IL) [βœ“] Android toolchain - develop for Android devices (Android SDK version 33.0.0) [βœ“] Xcode - develop for iOS and macOS (Xcode 14.1) [βœ“] Chrome - develop for the web [βœ“] Android Studio (version 2021.2) [βœ“] VS Code (version 1.73.1) [βœ“] Connected device (2 available) [βœ“] HTTP Host Availability IOS version: 15.2.1 Update Facing the exact same issue also on the flutter_webview_plugin package. Both the flutter_inappwebview and flutter_webview_plugin packages didn't provide full detailed information about their dependencies, but they both encountered the same issue on opening a video recording. A: remove the userAgent from InAppWebViewOptions A: It sounds like there may be an issue with the InAppWebView plugin in your Flutter app. One possible solution is to try using a different web view plugin, such as the flutter_webview_plugin package. This package provides a WebviewScaffold widget which you can use to display a web view in your app, and it has a userAgent property which you can use to specify the user agent string that the web view should use. This may help to prevent the issue with the redirect to live broadcast. Here's an example of how you could use the flutter_webview_plugin package to display a web view in your Flutter app: WebviewScaffold( url: "https://www.example.com", appBar: AppBar( title: Text("Example Website"), ), withZoom: true, withLocalStorage: true, userAgent: "Your custom user agent string", ) You can also try using the webview_flutter package, which is the official web view plugin for Flutter. It provides a WebView widget which you can use to display a web view in your app, and it has a userAgent property which you can use to specify the user agent string that the web view should use. Here's an example of how you could use the webview_flutter package to display a web view in your Flutter app: WebView( initialUrl: "https://www.example.com", javascriptMode: JavascriptMode.unrestricted, userAgent: "Your custom user agent string", )
Flutter InAppWebView iOS goes to live broadcast instead of camera
I'm using the flutter_inappwebview package to show our website as a web view in our Flutter iOS app. The website supports video recording, and everything works fine on the web. Whenever the user starts recording from the app, it accidentally redirects them to live broadcast instead of the camera. It's a bit complicated to explain, So I'm attaching this short video: Any suggestions why it happens? Is that an InAppWebView issue? Check out our discussion on GitHub. flutter doctor: [βœ“] Flutter (Channel stable, 3.3.7, on macOS 13.0 22A380 darwin-x64, locale en-IL) [βœ“] Android toolchain - develop for Android devices (Android SDK version 33.0.0) [βœ“] Xcode - develop for iOS and macOS (Xcode 14.1) [βœ“] Chrome - develop for the web [βœ“] Android Studio (version 2021.2) [βœ“] VS Code (version 1.73.1) [βœ“] Connected device (2 available) [βœ“] HTTP Host Availability IOS version: 15.2.1 Update Facing the exact same issue also on the flutter_webview_plugin package. Both the flutter_inappwebview and flutter_webview_plugin packages didn't provide full detailed information about their dependencies, but they both encountered the same issue on opening a video recording.
[ "remove the userAgent from InAppWebViewOptions\n", "It sounds like there may be an issue with the InAppWebView plugin in your Flutter app. One possible solution is to try using a different web view plugin, such as the flutter_webview_plugin package. This package provides a WebviewScaffold widget which you can use to display a web view in your app, and it has a userAgent property which you can use to specify the user agent string that the web view should use. This may help to prevent the issue with the redirect to live broadcast.\nHere's an example of how you could use the flutter_webview_plugin package to display a web view in your Flutter app:\nWebviewScaffold(\n url: \"https://www.example.com\",\n appBar: AppBar(\n title: Text(\"Example Website\"),\n ),\n withZoom: true,\n withLocalStorage: true,\n userAgent: \"Your custom user agent string\",\n)\n\nYou can also try using the webview_flutter package, which is the official web view plugin for Flutter. It provides a WebView widget which you can use to display a web view in your app, and it has a userAgent property which you can use to specify the user agent string that the web view should use.\nHere's an example of how you could use the webview_flutter package to display a web view in your Flutter app:\nWebView(\n initialUrl: \"https://www.example.com\",\n javascriptMode: JavascriptMode.unrestricted,\n userAgent: \"Your custom user agent string\",\n)\n\n" ]
[ 0, 0 ]
[]
[]
[ "camera", "flutter", "ios", "webview" ]
stackoverflow_0073320367_camera_flutter_ios_webview.txt
Q: How to make sure custom script stays loaded after pagination? I have some custom jQuery that disappears after paginating. I couldn't figure out how to keep it loaded so I figured I would try to reload it after click but thats not working either. here is what i was trying to get it to run: $(document).ready(function() { $('.pagination>li>a').live("click", function(){ any ideas how to make this work? what I would really like is to keep the custom jQuery while paginating, since there could potentially be 2 separate paginations on any given page (displaying notes and activities). A: It looks like you are trying to use the live method in your jQuery code, which was deprecated in jQuery 1.7 and removed in jQuery 1.9. Instead of using the live method, you can use the on method to attach an event handler to the a elements within the .pagination>li elements. Here is an example of how you could use the on method to attach a click event handler to the pagination links: $(document).ready(function() { $(document).on("click", ".pagination>li>a", function() { // Your code here }); }); The on method takes three arguments: the event type (e.g., "click"), a selector that matches the elements that you want to attach the event handler to, and the event handler function. In this example, the event type is "click" and the selector is ".pagination>li>a", which will match all a elements that are descendants of li elements that are descendants of an element with the pagination class. When a click event occurs on one of these elements, the event handler function will be called. Note that the on method should be called on a parent element that exists on the page when the event handler is attached. In this case, I have called the on method on the document element, which will always exist on the page. This is important because the pagination links may be dynamically added to the page after the initial page load, and the on method will not be able to attach the event handler to these elements unless it is called on a parent element that exists on the page. A: It sounds like you're trying to add a click event listener to elements with the class pagination and a descendant li and a elements. The .live() method is no longer supported in newer versions of jQuery, so you'll need to use a different method to attach the event listener. One option is to use the .on() method, which allows you to attach event listeners to elements that will be dynamically added to the page in the future. This method works by attaching the event listener to a parent element that exists on the page when the listener is added, and then listening for events that bubble up to that parent element from the dynamically added elements. Here's how you might modify your code to use the .on() method: $(document).ready(function() { // Attach the event listener to the document, since it exists when the listener is added $(document).on("click", '.pagination>li>a', function() { // Your code here }); }); Alternatively, you can use the .delegate() method, which works in a similar way to .on(), but allows you to specify the parent element to which the event listener should be attached. Here's how you might modify your code to use .delegate(): $(document).ready(function() { // Attach the event listener to the .pagination element, since it exists when the listener is added $('.pagination').delegate("li a", "click", function() { // Your code here }); });
How to make sure custom script stays loaded after pagination?
I have some custom jQuery that disappears after paginating. I couldn't figure out how to keep it loaded so I figured I would try to reload it after click but thats not working either. here is what i was trying to get it to run: $(document).ready(function() { $('.pagination>li>a').live("click", function(){ any ideas how to make this work? what I would really like is to keep the custom jQuery while paginating, since there could potentially be 2 separate paginations on any given page (displaying notes and activities).
[ "It looks like you are trying to use the live method in your jQuery code, which was deprecated in jQuery 1.7 and removed in jQuery 1.9. Instead of using the live method, you can use the on method to attach an event handler to the a elements within the .pagination>li elements.\nHere is an example of how you could use the on method to attach a click event handler to the pagination links:\n$(document).ready(function() {\n $(document).on(\"click\", \".pagination>li>a\", function() {\n // Your code here\n });\n});\n\nThe on method takes three arguments: the event type (e.g., \"click\"), a selector that matches the elements that you want to attach the event handler to, and the event handler function. In this example, the event type is \"click\" and the selector is \".pagination>li>a\", which will match all a elements that are descendants of li elements that are descendants of an element with the pagination class. When a click event occurs on one of these elements, the event handler function will be called.\nNote that the on method should be called on a parent element that exists on the page when the event handler is attached. In this case, I have called the on method on the document element, which will always exist on the page. This is important because the pagination links may be dynamically added to the page after the initial page load, and the on method will not be able to attach the event handler to these elements unless it is called on a parent element that exists on the page.\n", "It sounds like you're trying to add a click event listener to elements with the class pagination and a descendant li and a elements. The .live() method is no longer supported in newer versions of jQuery, so you'll need to use a different method to attach the event listener.\nOne option is to use the .on() method, which allows you to attach event listeners to elements that will be dynamically added to the page in the future. This method works by attaching the event listener to a parent element that exists on the page when the listener is added, and then listening for events that bubble up to that parent element from the dynamically added elements. Here's how you might modify your code to use the .on() method:\n$(document).ready(function() {\n // Attach the event listener to the document, since it exists when the listener is added\n $(document).on(\"click\", '.pagination>li>a', function() {\n // Your code here\n });\n});\n\nAlternatively, you can use the .delegate() method, which works in a similar way to .on(), but allows you to specify the parent element to which the event listener should be attached. Here's how you might modify your code to use .delegate():\n$(document).ready(function() {\n // Attach the event listener to the .pagination element, since it exists when the listener is added\n $('.pagination').delegate(\"li a\", \"click\", function() {\n // Your code here\n });\n});\n\n" ]
[ 0, 0 ]
[]
[]
[ "jquery", "pagination" ]
stackoverflow_0074670537_jquery_pagination.txt
Q: Laravel has-one-of-many Polymorphic relationship On my project, I have Report and Chart models. They have a many-to-many polymorphic relationship. The polymorphic pivot table has an additional flag (is_main_chart column) which states whether the chart is the main one for a report. A report can have only one main chart. Is it possible to create a relation between the report and the main chart only? Polymorphic pivot table: I have these three relations: public function charts() { return $this->morphToMany(Chart::class, 'model', ModelHasChartPivot::class); } public function mainChart() { return $this->morphToMany(Chart::class, 'model', ModelHasChartPivot::class)->wherePivot('is_main_chart', true); } public function otherCharts() { return $this->morphToMany(Chart::class, 'model', ModelHasChartPivot::class)->wherePivot('is_main_chart', false); } The problem is that the mainChart relation returns a collection of charts when I would like to have a direct relation to the chart. By the way, I am on Laravel v.8. A: I guess you can achieve it just by selecting the element [0] inside your function: public function mainChart() { return $this->morphToMany(Chart::class, 'model', ModelHasChartPivot::class)->wherePivot('is_main_chart', true)[0]; }
Laravel has-one-of-many Polymorphic relationship
On my project, I have Report and Chart models. They have a many-to-many polymorphic relationship. The polymorphic pivot table has an additional flag (is_main_chart column) which states whether the chart is the main one for a report. A report can have only one main chart. Is it possible to create a relation between the report and the main chart only? Polymorphic pivot table: I have these three relations: public function charts() { return $this->morphToMany(Chart::class, 'model', ModelHasChartPivot::class); } public function mainChart() { return $this->morphToMany(Chart::class, 'model', ModelHasChartPivot::class)->wherePivot('is_main_chart', true); } public function otherCharts() { return $this->morphToMany(Chart::class, 'model', ModelHasChartPivot::class)->wherePivot('is_main_chart', false); } The problem is that the mainChart relation returns a collection of charts when I would like to have a direct relation to the chart. By the way, I am on Laravel v.8.
[ "I guess you can achieve it just by selecting the element [0] inside your function:\npublic function mainChart()\n{\n return $this->morphToMany(Chart::class, 'model', ModelHasChartPivot::class)->wherePivot('is_main_chart', true)[0];\n}\n\n" ]
[ 0 ]
[]
[]
[ "eloquent", "eloquent_relationship", "laravel", "laravel_8", "php" ]
stackoverflow_0074655913_eloquent_eloquent_relationship_laravel_laravel_8_php.txt
Q: How to create a shortcut of the ".url" format with python I need to use python 3 to create a shortcut to go to some site. The file must have the extension ".url". How can I do this? I found some code but it doesn't work for me bmurl = card.url # some link bmpath = path_to_card + "link.url" # path to file ws = win32com.client.Dispatch("wscript.shell") scut = ws.CreateShortcut(bmpath) scut.TargetPath = bmurl # in this place I got an error scut.Save() A: To create a shortcut file with the ".url" extension in Python, you can use the win32com module to create a ShellLinkObject and set its TargetPath property to the URL that you want the shortcut to point to. Here is an example of how you could do this: import win32com.client bmurl = "https://www.example.com" bmpath = "link.url" # Create a ShellLinkObject. scut = win32com.client.Dispatch("wscript.shell").CreateShortcut(bmpath) # Set the TargetPath property of the shortcut to the URL. scut.TargetPath = bmurl # Save the shortcut. scut.Save() In the code above, I first import the win32com module, which provides access to the Windows Script Host Object Model. I then create a ShellLinkObject by calling the Dispatch method of the win32com.client module and passing it the string "wscript.shell", which specifies the type of object to create. I call the CreateShortcut method of the ShellLinkObject and pass it the path of the shortcut file (bmpath) to create the shortcut. Next, I set the TargetPath property of the shortcut to the URL that I want the shortcut to point to (bmurl). Finally, I call the Save method of the ShellLinkObject to save the shortcut file.
How to create a shortcut of the ".url" format with python
I need to use python 3 to create a shortcut to go to some site. The file must have the extension ".url". How can I do this? I found some code but it doesn't work for me bmurl = card.url # some link bmpath = path_to_card + "link.url" # path to file ws = win32com.client.Dispatch("wscript.shell") scut = ws.CreateShortcut(bmpath) scut.TargetPath = bmurl # in this place I got an error scut.Save()
[ "To create a shortcut file with the \".url\" extension in Python, you can use the win32com module to create a ShellLinkObject and set its TargetPath property to the URL that you want the shortcut to point to. Here is an example of how you could do this:\nimport win32com.client\n\nbmurl = \"https://www.example.com\"\nbmpath = \"link.url\"\n\n# Create a ShellLinkObject.\nscut = win32com.client.Dispatch(\"wscript.shell\").CreateShortcut(bmpath)\n\n# Set the TargetPath property of the shortcut to the URL.\nscut.TargetPath = bmurl\n\n# Save the shortcut.\nscut.Save()\n\nIn the code above, I first import the win32com module, which provides access to the Windows Script Host Object Model. I then create a ShellLinkObject by calling the Dispatch method of the win32com.client module and passing it the string \"wscript.shell\", which specifies the type of object to create. I call the CreateShortcut method of the ShellLinkObject and pass it the path of the shortcut file (bmpath) to create the shortcut.\nNext, I set the TargetPath property of the shortcut to the URL that I want the shortcut to point to (bmurl). Finally, I call the Save method of the ShellLinkObject to save the shortcut file.\n" ]
[ 0 ]
[]
[]
[ "python_3.x", "windows" ]
stackoverflow_0074670559_python_3.x_windows.txt