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: Android MSAL Login failed incase if My app is already Auto enrollment successful using Company portal app We are migrating our authentication of Azure from ADAL to MSAL. Our app support Intune feature. We are facing login failure during MSAL login, if the app is already automatically enrolled using Company portal app or open-in work flow from the other apps is already Intune Enrollment successfully completed. We are getting MsalException as unknown_error. Exception screenshot below I am expecting there could be some workaround for user to do login and get a accessToken and IdToken through MSAL even MAMErollment is completed for the app OR is there a way to block Auto enrollment through Company portal app. publicClientApplication.acquireToken( new AcquireTokenParameters.Builder().startAuthorizationFromActivity(mActivity) .withScopes(Collections.singletonList(azureInfoOnInterActiveLogin.getResourceUri().concat("/.default"))) .withCallback(authenticationCallback) .withPrompt(Prompt.WHEN_REQUIRED) .withLoginHint("[email protected]") .build() ); Note: With our legacy implementation of ADAL, acquireToken request is getting successful & able to get acessToken and idToken even the app is already automatically enrolled using Company portal. This is came up on MSAL only. Not on ADAL. A: Looks like a bug. isFullBrowser(final ResolveInfo resolveInfo) is getting a null value which is not expected. Ensure you're using the latest version of the library. If the problem persists, please open a Github issue and share it's URL.
Android MSAL Login failed incase if My app is already Auto enrollment successful using Company portal app
We are migrating our authentication of Azure from ADAL to MSAL. Our app support Intune feature. We are facing login failure during MSAL login, if the app is already automatically enrolled using Company portal app or open-in work flow from the other apps is already Intune Enrollment successfully completed. We are getting MsalException as unknown_error. Exception screenshot below I am expecting there could be some workaround for user to do login and get a accessToken and IdToken through MSAL even MAMErollment is completed for the app OR is there a way to block Auto enrollment through Company portal app. publicClientApplication.acquireToken( new AcquireTokenParameters.Builder().startAuthorizationFromActivity(mActivity) .withScopes(Collections.singletonList(azureInfoOnInterActiveLogin.getResourceUri().concat("/.default"))) .withCallback(authenticationCallback) .withPrompt(Prompt.WHEN_REQUIRED) .withLoginHint("[email protected]") .build() ); Note: With our legacy implementation of ADAL, acquireToken request is getting successful & able to get acessToken and idToken even the app is already automatically enrolled using Company portal. This is came up on MSAL only. Not on ADAL.
[ "Looks like a bug. isFullBrowser(final ResolveInfo resolveInfo) is getting a null value which is not expected. Ensure you're using the latest version of the library. If the problem persists, please open a Github issue and share it's URL.\n" ]
[ 0 ]
[]
[]
[ "adal", "azure_android_sdk", "intune", "microsoft_graph_intune", "msal" ]
stackoverflow_0074411662_adal_azure_android_sdk_intune_microsoft_graph_intune_msal.txt
Q: How to see whether a vector is empty in R First of all, I need to initialize an empty vector in R, Does the following work ? vec <- vector() And how I can evaluate whether vec is empty or not ? A: It seems that using length(vector_object) works: vector.is.empty <- function(x) return(length(x) ==0 ) > v <- vector() > class(v) [1] "logical" > length(v) [1] 0 > vector.is.empty(v) [1] TRUE > > vector.is.empty(c()) [1] TRUE > vector.is.empty(c(1)[-1]) [1] TRUE Please tell if there is any case not covered. A: From the help file of vector: vector produces a vector of the given length and mode. ... Usage vector(mode = "logical", length = 0) If you run the code, vec <- vector() and evaluate it, vec, returns logical(0). A logical vector of size 0. This makes sense, seeing as how the default arguments for the vector function is vector(mode="logical", length=0). If you check length(vec), we know the length of our vector is also 0, meaning that our vector, vec, is empty. If you want to create other types of vectors that are not of type logical, you can also read the help file of vector using ?vector. You will find that vector(mode='character') will make an empty character vector, vector(mode='integer') will make an empty integer vector, and so on. You can also create empty vectors by calling the names of the other "atomic modes", as the help file calls them: character(), integer(), numeric()/double(), complex(), character(), and raw(). A: The NULL case is not covered in the excellent example of @yu-shen. Sometimes it is not the same to have a NULL object and length-zero object. The function below cover those cases. Best, is_empty <- function(x) { if (length(x) == 0 & !is.null(x)) { TRUE } else { FALSE } } x <- vector() is_empty(x) #> [1] TRUE y <- NULL length(y) #> [1] 0 is_empty(y) #> [1] FALSE Created on 2022-08-26 with reprex v2.0.2 A: I used to use length() but I now use !any() as it is more human readable when used in an if statement > v <- vector() > !any(v) # TRUE > !any(c()) # TRUE > !any(c(1)[-1) # TRUE > if(any(v)) { > print("not empty") > } else { > print("empty!") > } # [1] empty!
How to see whether a vector is empty in R
First of all, I need to initialize an empty vector in R, Does the following work ? vec <- vector() And how I can evaluate whether vec is empty or not ?
[ "It seems that using length(vector_object) works:\nvector.is.empty <- function(x) return(length(x) ==0 )\n\n> v <- vector()\n> class(v)\n[1] \"logical\"\n> length(v)\n[1] 0\n> vector.is.empty(v)\n[1] TRUE\n> \n> vector.is.empty(c())\n[1] TRUE\n> vector.is.empty(c(1)[-1])\n[1] TRUE\n\nPlease tell if there is any case not covered. \n", "From the help file of vector:\n\nvector produces a vector of the given length and mode.\n...\nUsage\nvector(mode = \"logical\", length = 0)\n\nIf you run the code, vec <- vector() and evaluate it, vec, returns logical(0). A logical vector of size 0. This makes sense, seeing as how the default arguments for the vector function is vector(mode=\"logical\", length=0).\nIf you check length(vec), we know the length of our vector is also 0, meaning that our vector, vec, is empty.\nIf you want to create other types of vectors that are not of type logical, you can also read the help file of vector using ?vector. You will find that vector(mode='character') will make an empty character vector, vector(mode='integer') will make an empty integer vector, and so on.\nYou can also create empty vectors by calling the names of the other \"atomic modes\", as the help file calls them:\ncharacter(), integer(), numeric()/double(), complex(), character(), and raw().\n", "The NULL case is not covered in the excellent example of @yu-shen. Sometimes it is not the same to have a NULL object and length-zero object. The function below cover those cases.\nBest,\nis_empty <- function(x) {\n if (length(x) == 0 & !is.null(x)) {\n TRUE\n } else {\n FALSE\n }\n}\n\nx <- vector()\nis_empty(x)\n#> [1] TRUE\n\ny <- NULL\nlength(y)\n#> [1] 0\nis_empty(y)\n#> [1] FALSE\n\nCreated on 2022-08-26 with reprex v2.0.2\n", "I used to use length() but I now use !any() as it is more human readable when used in an if statement\n> v <- vector()\n> !any(v)\n# TRUE\n> !any(c())\n# TRUE\n> !any(c(1)[-1)\n# TRUE\n\n\n> if(any(v)) {\n> print(\"not empty\")\n> } else {\n> print(\"empty!\")\n> }\n# [1] empty!\n\n" ]
[ 23, 4, 0, 0 ]
[]
[]
[ "r" ]
stackoverflow_0020061228_r.txt
Q: .Net Core Updating to 3.1.31 from 3.1.5 - Internal Server Error I inherited a project that uses .Net Core and don't really know too much about how to set it up and configure it in IIS. Prior to updating everything was working and loading fine. Now I am getting "Internal Server Error: An error occurred while starting the application". Initially to update I downloaded and installed (in this order): aspnetcore-runtime-3.1.31-win-x64 dotnet-runtime-3.1.31-win-x64 On installing the ASP Net Core runtime (1) the site broke, then I installed the dotnet-runtime (2) and the site came back up and everything was loading and running as expected. Then a colleague noticed that there was a .Net Core 3.1.5 Windows Server Hosting installed and not sure what it was we uninstalled it to see if it broke anything and yes, uninstalling that broke the sites. So I then downloaded and installed the Hosting Bundle for .Net Core 3.1.31, rebooted, and it still won't load/startup. From there I uninstalled everything, and re-installed the 3.1.5 version (what was previously installed) and it's still broken. As best as I can tell, uninstalling the Hosting Bundle (Windows Server Hosting) broke something and I cannot figure out what it is or how to fix it. Possibly something that handles the IIS Support? I'm hoping someone else has had a similar issue or can maybe direct me to what I should be looking at or for. This doesn't really make sense that a minor version update would cause all these problems and I'm not sure what uninstalling that app changed that didn't get repaired or replaced when installing it again. A: I found that there are multiple app settings files one for each environment and this is controlled by an environment variable (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-7.0). It would appear that uninstalling the Hosting Bundle (Windows Server Hosting) caused this environment variable to be erased and the environment defaults to Production when there is not one set. So in our case it was using the production config in a staging environment. We started investigating this once we were able to find a SQL connection error in the server logs which tipped us off to check a few things and this was one of them. Hopefully someone finds this helpful and it can save someone else some time and frustration.
.Net Core Updating to 3.1.31 from 3.1.5 - Internal Server Error
I inherited a project that uses .Net Core and don't really know too much about how to set it up and configure it in IIS. Prior to updating everything was working and loading fine. Now I am getting "Internal Server Error: An error occurred while starting the application". Initially to update I downloaded and installed (in this order): aspnetcore-runtime-3.1.31-win-x64 dotnet-runtime-3.1.31-win-x64 On installing the ASP Net Core runtime (1) the site broke, then I installed the dotnet-runtime (2) and the site came back up and everything was loading and running as expected. Then a colleague noticed that there was a .Net Core 3.1.5 Windows Server Hosting installed and not sure what it was we uninstalled it to see if it broke anything and yes, uninstalling that broke the sites. So I then downloaded and installed the Hosting Bundle for .Net Core 3.1.31, rebooted, and it still won't load/startup. From there I uninstalled everything, and re-installed the 3.1.5 version (what was previously installed) and it's still broken. As best as I can tell, uninstalling the Hosting Bundle (Windows Server Hosting) broke something and I cannot figure out what it is or how to fix it. Possibly something that handles the IIS Support? I'm hoping someone else has had a similar issue or can maybe direct me to what I should be looking at or for. This doesn't really make sense that a minor version update would cause all these problems and I'm not sure what uninstalling that app changed that didn't get repaired or replaced when installing it again.
[ "I found that there are multiple app settings files one for each environment and this is controlled by an environment variable (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-7.0).\nIt would appear that uninstalling the Hosting Bundle (Windows Server Hosting) caused this environment variable to be erased and the environment defaults to Production when there is not one set.\nSo in our case it was using the production config in a staging environment.\nWe started investigating this once we were able to find a SQL connection error in the server logs which tipped us off to check a few things and this was one of them.\nHopefully someone finds this helpful and it can save someone else some time and frustration.\n" ]
[ 0 ]
[]
[]
[ ".net_core", "asp.net_core", "asp.net_core_3.1" ]
stackoverflow_0074659404_.net_core_asp.net_core_asp.net_core_3.1.txt
Q: Unity error "Internal build system error. Backend exited with code -1073740791." has Destroyed/Killed my Project Ok I might be over Exaggerating here but it's true, the project is broken due to error when I start opening it "Internal build system error. Backend exited with code -1073740791".The app of this Project has already been released on Google Play, maybe there is something to do with the settings? Can Please Anyone Help? The Full Error: Internal build system error. Backend exited with code -1073740791. STDOUT: [ 0s] Delete 9 artifact files that are no longer in use. (like Library\Bee\artifacts\movedfrom\Unity.VisualScripting.Antlr3.Runtime.dll_2086064903115821086.movedfrom) [ 80/296 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.VisualScripting.IonicZip.dll_2325611340324208551.movedfrom [ 81/296 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.VisualScripting.YamlDotNet.dll_640181916459675141.movedfrom [ 82/297 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.UI.dll.movedfrom.rsp [ 83/299 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.TestRunner.rsp [ 84/299 1s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.Plastic.Antlr3.Runtime.dll_5744707985310546343.movedfrom [ 89/302 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEditor.TestRunner.rsp [ 90/304 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.UI.rsp [ 91/304 1s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.Plastic.Newtonsoft.Json.dll_2125035100625013150.movedfrom [ 92/305 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEditor.UI.dll.movedfrom.rsp [ 93/307 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEditor.UI.rsp [ 94/308 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/AstarPathfindingProject.dll.movedfrom.rsp [ 95/309 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/PsdPlugin.dll.movedfrom.rsp [ 96/310 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Triangle.Runtime.dll.movedfrom.rsp [ 97/311 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Common.Runtime.dll.movedfrom.rsp [ 98/312 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.IK.Runtime.dll.movedfrom.rsp [ 99/313 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Path.Editor.dll.movedfrom.rsp [100/314 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.PixelPerfect.dll.movedfrom.rsp [101/315 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Sprite.Editor.dll.movedfrom.rsp [102/316 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Editor.dll.movedfrom.rsp [103/317 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Extras.dll.movedfrom.rsp [104/318 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.CollabProxy.Editor.dll.movedfrom.rsp [105/319 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.InternalAPIEngineBridge.001.dll.movedfrom.rsp [106/320 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mathematics.dll.movedfrom.rsp [107/321 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mobile.AndroidLogcat.Editor.dll.movedfrom.rsp [108/322 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.Android.dll.movedfrom.rsp [109/323 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.iOS.dll.movedfrom.rsp [110/324 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.PlasticSCM.Editor.dll.movedfrom.rsp [112/326 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.TextMeshPro.dll.movedfrom.rsp [113/327 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Timeline.dll.movedfrom.rsp [114/328 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VSCode.Editor.dll.movedfrom.rsp [115/329 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Core.dll.movedfrom.rsp [118/332 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Advertisements.Editor.dll.movedfrom.rsp [119/333 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Advertisements.dll.movedfrom.rsp [120/334 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/PackageToolsEditor.dll.movedfrom.rsp [121/336 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Common.Runtime.rsp [122/338 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.InternalAPIEngineBridge.001.rsp [123/340 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mathematics.rsp [124/341 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Runtime.dll.movedfrom.rsp [125/343 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Sprite.Editor.rsp [126/344 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Common.Editor.dll.movedfrom.rsp [127/346 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.PixelPerfect.rsp [128/347 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.PixelPerfect.Editor.dll.movedfrom.rsp [129/348 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.SpriteShape.Runtime.dll.movedfrom.rsp [130/350 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Editor.rsp [131/352 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Extras.rsp [132/353 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Extras.Editor.dll.movedfrom.rsp [133/354 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.InternalAPIEditorBridge.001.dll.movedfrom.rsp [134/355 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mathematics.Editor.dll.movedfrom.rsp [135/357 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.Android.rsp [136/359 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.iOS.rsp [137/360 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.dll.movedfrom.rsp [138/362 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.TextMeshPro.rsp [139/363 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.TextMeshPro.Editor.dll.movedfrom.rsp [140/365 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Timeline.rsp [141/366 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Timeline.Editor.dll.movedfrom.rsp [142/368 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Core.rsp [143/369 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Core.Editor.dll.movedfrom.rsp [144/370 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Flow.dll.movedfrom.rsp [145/372 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Advertisements.rsp [146/373 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Monetization.dll.movedfrom.rsp [147/374 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/AstarPathfindingProjectEditor.dll.movedfrom.rsp [148/376 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Runtime.rsp [149/378 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Triangle.Runtime.rsp [150/380 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Common.Editor.rsp [151/382 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.InternalAPIEditorBridge.001.rsp [152/383 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Editor.dll.movedfrom.rsp [153/385 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Path.Editor.rsp [154/387 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.SpriteShape.Runtime.rsp [155/388 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.SpriteShape.Editor.dll.movedfrom.rsp [156/390 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Core.Editor.rsp [157/392 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Flow.rsp [158/393 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Flow.Editor.dll.movedfrom.rsp [159/394 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.State.dll.movedfrom.rsp [160/396 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Editor.rsp [161/398 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.IK.Runtime.rsp [162/399 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.IK.Editor.dll.movedfrom.rsp [163/400 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Psdimporter.Editor.dll.movedfrom.rsp [164/402 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Flow.Editor.rsp [165/404 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.State.rsp [166/405 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.State.Editor.dll.movedfrom.rsp [167/406 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/VSSettingsProvider.dll.movedfrom.rsp [168/408 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.IK.Editor.rsp [169/410 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.PixelPerfect.Editor.rsp [170/414 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/PsdPlugin.rsp [171/414 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Psdimporter.Editor.rsp [172/416 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.SpriteShape.Editor.rsp [173/418 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Extras.Editor.rsp [174/420 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mathematics.Editor.rsp [175/422 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mobile.AndroidLogcat.Editor.rsp [176/424 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.rsp [177/426 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.PlasticSCM.Editor.rsp [178/428 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Rider.Editor.rsp [179/430 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.TextMeshPro.Editor.rsp [180/432 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Timeline.Editor.rsp [181/434 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VSCode.Editor.rsp [182/436 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.State.Editor.rsp [183/438 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualStudio.Editor.rsp [184/440 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Advertisements.Editor.rsp [185/442 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Monetization.rsp [186/443 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Assembly-CSharp.dll.movedfrom.rsp [187/445 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/AstarPathfindingProject.rsp [188/447 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.CollabProxy.Editor.rsp [189/449 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Advertisements.DevX.Editor.rsp [190/451 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/PackageToolsEditor.rsp [191/453 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/AstarPathfindingProjectEditor.rsp [192/455 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/VSSettingsProvider.rsp [193/457 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Assembly-CSharp.rsp [196/457 3s] Csc Library/Bee/artifacts/1300b0aE.dag/UnityEngine.TestRunner.dll (+2 others) [197/457 0s] CopyTool Library/ScriptAssemblies/UnityEngine.TestRunner.pdb [198/457 0s] CopyTool Library/ScriptAssemblies/UnityEngine.TestRunner.dll [199/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/UnityEngine.TestRunner.ref.dll_8368799695770714308.movedfrom [200/457 3s] Csc Library/Bee/artifacts/1300b0aE.dag/UnityEngine.UI.dll (+2 others) [201/457 0s] CopyTool Library/ScriptAssemblies/UnityEngine.UI.pdb [203/457 0s] CopyTool Library/ScriptAssemblies/UnityEngine.UI.dll [204/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/UnityEngine.UI.ref.dll_13680447769613716870.movedfrom [205/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/UnityEditor.TestRunner.dll (+2 others) [208/457 0s] CopyTool Library/ScriptAssemblies/UnityEditor.TestRunner.dll [209/457 0s] CopyTool Library/ScriptAssemblies/UnityEditor.TestRunner.pdb [210/457 1s] Csc Library/Bee/artifacts/1300b0aE.dag/UnityEditor.UI.dll (+2 others) [219/457 4s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Editor.dll (+2 others) [220/457 4s] Csc Library/Bee/artifacts/1300b0aE.dag/AstarPathfindingProject.dll (+2 others) [220/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Tilemap.Editor.pdb [222/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Tilemap.Editor.dll [223/457 3s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Common.Runtime.dll (+2 others) [224/457 0s] CopyTool Library/ScriptAssemblies/AstarPathfindingProject.pdb [225/457 0s] CopyTool Library/ScriptAssemblies/AstarPathfindingProject.dll [226/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Common.Runtime.dll [229/457 5s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.PlasticSCM.Editor.dll (+2 others) [231/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.2D.Common.Runtime.ref.dll_17822817306688496483.movedfrom [232/457 0s] CopyTool Library/ScriptAssemblies/Unity.PlasticSCM.Editor.pdb [239/457 0s] CopyTool Library/ScriptAssemblies/Unity.PlasticSCM.Editor.dll [240/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.iOS.dll (+2 others) [241/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Extras.dll (+2 others) [242/457 0s] CopyTool Library/ScriptAssemblies/Unity.Notifications.iOS.pdb [243/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.Android.dll (+2 others) [244/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Tilemap.Extras.dll [245/457 0s] CopyTool Library/ScriptAssemblies/Unity.Notifications.Android.dll [246/457 0s] CopyTool Library/ScriptAssemblies/Unity.Notifications.Android.pdb [248/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Triangle.Runtime.dll (+2 others) [249/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.Notifications.Android.ref.dll_15514552198952893227.movedfrom [250/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.2D.Tilemap.Extras.ref.dll_13185418342785991921.movedfrom [251/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.2D.Animation.Triangle.Runtime.ref.dll_17903118484747357354.movedfrom [252/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Animation.Triangle.Runtime.dll [253/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Animation.Triangle.Runtime.pdb [254/457 0s] CopyTool Library/ScriptAssemblies/Unity.Notifications.iOS.dll [259/457 1s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.dll (+2 others) [261/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.Notifications.iOS.ref.dll_8642665151043550249.movedfrom [262/457 0s] CopyTool Library/ScriptAssemblies/Unity.Notifications.dll [264/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.Rider.Editor.dll (+2 others) [266/457 0s] CopyTool Library/ScriptAssemblies/Unity.Rider.Editor.dll [267/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Sprite.Editor.dll (+2 others) [269/457 0s] CopyTool Library/ScriptAssemblies/Unity.Rider.Editor.pdb [270/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Sprite.Editor.pdb [271/457 1s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.IK.Runtime.dll (+2 others) [276/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Sprite.Editor.dll [277/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.VisualStudio.Editor.dll (+2 others) [278/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.IK.Runtime.dll STDERR: tundra: error: Couldn't launch process errno: 2 (No such file or directory) GetLastError: 5 (0x00000005): Access is denied. Additional Errors: 1. (Why is number 1 is blank? it's because it is, Its in the error log) > 2.Library\ScriptAssemblies\Unity.2D.Common.Runtime.pdb: 3.Library\ScriptAssemblies\Unity.2D.Tilemap.Extras.pdb: 4.Library\ScriptAssemblies\Unity.Notifications.pdb: A: Back up everything now in case anything you try makes things worse. If you have any previous backups be sure to keep them safe. While unlikely, if it turned out the issues were caused by drive trouble it could be that the drive is on the verge of failing. After having backed everything up, try closing Unity and then deleting the Library\Bee folder from your project directory. Hopefully your problem is now solved. ... If your problem was not solved: try deleting or moving the following folders and files from your project folder: .vs Library obj Temp UserSettings .vsconfig *.csproj *.sln Basically everything except Assets, Packages, and ProjectSettings (unless you added any custom files or folders to the root folder manually, though even if so you just backed them up a moment ago right?) If your Unity project directory is under an unusual or long full directory name e.g. C:\Users\Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch\Documents\Unity Projects\UnityProject or C:\Users\JokūbasØy̸̧̓ṽ̴͉̬̰̌͘ì̷͓ṋ̶̮̓͊͝d̴̢̫͉͋\Documents\UnityProject, try moving it somewhere simpler like C:\Unity\UnityProject. Restart your PC. You can never be too certain of what problems might potentially be fixed by turning it off and on again. Load the project into Unity and pray it imports successfully this time. If none of that works: If you updated Unity immediately before the problem began, reinstall the older version and try the above steps again. If that fails too, trying a newer Unity version in desperation would not be unreasonable. Probably the Bee folder thing solved your problem and you never got here though. A: I am on Ubuntu 20.04 this worked for me: Open in safe mode then exit safe mode without fixing anything Go to Library/Bee/ and delete the TundraBuildState.state.map Press the play button and the game starts. The deleted file is also rebuilt. Hope it helps someone A: You could try turning off your anti-virus software. That solved the problem when I started having it out of the blue.
Unity error "Internal build system error. Backend exited with code -1073740791." has Destroyed/Killed my Project
Ok I might be over Exaggerating here but it's true, the project is broken due to error when I start opening it "Internal build system error. Backend exited with code -1073740791".The app of this Project has already been released on Google Play, maybe there is something to do with the settings? Can Please Anyone Help? The Full Error: Internal build system error. Backend exited with code -1073740791. STDOUT: [ 0s] Delete 9 artifact files that are no longer in use. (like Library\Bee\artifacts\movedfrom\Unity.VisualScripting.Antlr3.Runtime.dll_2086064903115821086.movedfrom) [ 80/296 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.VisualScripting.IonicZip.dll_2325611340324208551.movedfrom [ 81/296 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.VisualScripting.YamlDotNet.dll_640181916459675141.movedfrom [ 82/297 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.UI.dll.movedfrom.rsp [ 83/299 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.TestRunner.rsp [ 84/299 1s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.Plastic.Antlr3.Runtime.dll_5744707985310546343.movedfrom [ 89/302 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEditor.TestRunner.rsp [ 90/304 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.UI.rsp [ 91/304 1s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.Plastic.Newtonsoft.Json.dll_2125035100625013150.movedfrom [ 92/305 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEditor.UI.dll.movedfrom.rsp [ 93/307 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEditor.UI.rsp [ 94/308 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/AstarPathfindingProject.dll.movedfrom.rsp [ 95/309 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/PsdPlugin.dll.movedfrom.rsp [ 96/310 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Triangle.Runtime.dll.movedfrom.rsp [ 97/311 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Common.Runtime.dll.movedfrom.rsp [ 98/312 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.IK.Runtime.dll.movedfrom.rsp [ 99/313 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Path.Editor.dll.movedfrom.rsp [100/314 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.PixelPerfect.dll.movedfrom.rsp [101/315 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Sprite.Editor.dll.movedfrom.rsp [102/316 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Editor.dll.movedfrom.rsp [103/317 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Extras.dll.movedfrom.rsp [104/318 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.CollabProxy.Editor.dll.movedfrom.rsp [105/319 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.InternalAPIEngineBridge.001.dll.movedfrom.rsp [106/320 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mathematics.dll.movedfrom.rsp [107/321 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mobile.AndroidLogcat.Editor.dll.movedfrom.rsp [108/322 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.Android.dll.movedfrom.rsp [109/323 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.iOS.dll.movedfrom.rsp [110/324 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.PlasticSCM.Editor.dll.movedfrom.rsp [112/326 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.TextMeshPro.dll.movedfrom.rsp [113/327 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Timeline.dll.movedfrom.rsp [114/328 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VSCode.Editor.dll.movedfrom.rsp [115/329 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Core.dll.movedfrom.rsp [118/332 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Advertisements.Editor.dll.movedfrom.rsp [119/333 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Advertisements.dll.movedfrom.rsp [120/334 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/PackageToolsEditor.dll.movedfrom.rsp [121/336 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Common.Runtime.rsp [122/338 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.InternalAPIEngineBridge.001.rsp [123/340 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mathematics.rsp [124/341 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Runtime.dll.movedfrom.rsp [125/343 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Sprite.Editor.rsp [126/344 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Common.Editor.dll.movedfrom.rsp [127/346 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.PixelPerfect.rsp [128/347 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.PixelPerfect.Editor.dll.movedfrom.rsp [129/348 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.SpriteShape.Runtime.dll.movedfrom.rsp [130/350 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Editor.rsp [131/352 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Extras.rsp [132/353 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Extras.Editor.dll.movedfrom.rsp [133/354 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.InternalAPIEditorBridge.001.dll.movedfrom.rsp [134/355 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mathematics.Editor.dll.movedfrom.rsp [135/357 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.Android.rsp [136/359 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.iOS.rsp [137/360 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.dll.movedfrom.rsp [138/362 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.TextMeshPro.rsp [139/363 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.TextMeshPro.Editor.dll.movedfrom.rsp [140/365 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Timeline.rsp [141/366 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Timeline.Editor.dll.movedfrom.rsp [142/368 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Core.rsp [143/369 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Core.Editor.dll.movedfrom.rsp [144/370 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Flow.dll.movedfrom.rsp [145/372 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Advertisements.rsp [146/373 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Monetization.dll.movedfrom.rsp [147/374 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/AstarPathfindingProjectEditor.dll.movedfrom.rsp [148/376 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Runtime.rsp [149/378 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Triangle.Runtime.rsp [150/380 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Common.Editor.rsp [151/382 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.InternalAPIEditorBridge.001.rsp [152/383 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Editor.dll.movedfrom.rsp [153/385 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Path.Editor.rsp [154/387 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.SpriteShape.Runtime.rsp [155/388 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.SpriteShape.Editor.dll.movedfrom.rsp [156/390 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Core.Editor.rsp [157/392 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Flow.rsp [158/393 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Flow.Editor.dll.movedfrom.rsp [159/394 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.State.dll.movedfrom.rsp [160/396 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Editor.rsp [161/398 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.IK.Runtime.rsp [162/399 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.IK.Editor.dll.movedfrom.rsp [163/400 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Psdimporter.Editor.dll.movedfrom.rsp [164/402 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.Flow.Editor.rsp [165/404 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.State.rsp [166/405 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.State.Editor.dll.movedfrom.rsp [167/406 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/VSSettingsProvider.dll.movedfrom.rsp [168/408 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.IK.Editor.rsp [169/410 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.PixelPerfect.Editor.rsp [170/414 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/PsdPlugin.rsp [171/414 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Psdimporter.Editor.rsp [172/416 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.SpriteShape.Editor.rsp [173/418 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Extras.Editor.rsp [174/420 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mathematics.Editor.rsp [175/422 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Mobile.AndroidLogcat.Editor.rsp [176/424 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.rsp [177/426 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.PlasticSCM.Editor.rsp [178/428 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Rider.Editor.rsp [179/430 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.TextMeshPro.Editor.rsp [180/432 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.Timeline.Editor.rsp [181/434 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VSCode.Editor.rsp [182/436 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualScripting.State.Editor.rsp [183/438 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.VisualStudio.Editor.rsp [184/440 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Advertisements.Editor.rsp [185/442 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Monetization.rsp [186/443 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Assembly-CSharp.dll.movedfrom.rsp [187/445 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/AstarPathfindingProject.rsp [188/447 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Unity.CollabProxy.Editor.rsp [189/449 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/UnityEngine.Advertisements.DevX.Editor.rsp [190/451 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/PackageToolsEditor.rsp [191/453 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/AstarPathfindingProjectEditor.rsp [192/455 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/VSSettingsProvider.rsp [193/457 0s] WriteText Library/Bee/artifacts/1300b0aE.dag/Assembly-CSharp.rsp [196/457 3s] Csc Library/Bee/artifacts/1300b0aE.dag/UnityEngine.TestRunner.dll (+2 others) [197/457 0s] CopyTool Library/ScriptAssemblies/UnityEngine.TestRunner.pdb [198/457 0s] CopyTool Library/ScriptAssemblies/UnityEngine.TestRunner.dll [199/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/UnityEngine.TestRunner.ref.dll_8368799695770714308.movedfrom [200/457 3s] Csc Library/Bee/artifacts/1300b0aE.dag/UnityEngine.UI.dll (+2 others) [201/457 0s] CopyTool Library/ScriptAssemblies/UnityEngine.UI.pdb [203/457 0s] CopyTool Library/ScriptAssemblies/UnityEngine.UI.dll [204/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/UnityEngine.UI.ref.dll_13680447769613716870.movedfrom [205/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/UnityEditor.TestRunner.dll (+2 others) [208/457 0s] CopyTool Library/ScriptAssemblies/UnityEditor.TestRunner.dll [209/457 0s] CopyTool Library/ScriptAssemblies/UnityEditor.TestRunner.pdb [210/457 1s] Csc Library/Bee/artifacts/1300b0aE.dag/UnityEditor.UI.dll (+2 others) [219/457 4s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Editor.dll (+2 others) [220/457 4s] Csc Library/Bee/artifacts/1300b0aE.dag/AstarPathfindingProject.dll (+2 others) [220/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Tilemap.Editor.pdb [222/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Tilemap.Editor.dll [223/457 3s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Common.Runtime.dll (+2 others) [224/457 0s] CopyTool Library/ScriptAssemblies/AstarPathfindingProject.pdb [225/457 0s] CopyTool Library/ScriptAssemblies/AstarPathfindingProject.dll [226/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Common.Runtime.dll [229/457 5s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.PlasticSCM.Editor.dll (+2 others) [231/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.2D.Common.Runtime.ref.dll_17822817306688496483.movedfrom [232/457 0s] CopyTool Library/ScriptAssemblies/Unity.PlasticSCM.Editor.pdb [239/457 0s] CopyTool Library/ScriptAssemblies/Unity.PlasticSCM.Editor.dll [240/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.iOS.dll (+2 others) [241/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Tilemap.Extras.dll (+2 others) [242/457 0s] CopyTool Library/ScriptAssemblies/Unity.Notifications.iOS.pdb [243/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.Android.dll (+2 others) [244/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Tilemap.Extras.dll [245/457 0s] CopyTool Library/ScriptAssemblies/Unity.Notifications.Android.dll [246/457 0s] CopyTool Library/ScriptAssemblies/Unity.Notifications.Android.pdb [248/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Animation.Triangle.Runtime.dll (+2 others) [249/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.Notifications.Android.ref.dll_15514552198952893227.movedfrom [250/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.2D.Tilemap.Extras.ref.dll_13185418342785991921.movedfrom [251/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.2D.Animation.Triangle.Runtime.ref.dll_17903118484747357354.movedfrom [252/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Animation.Triangle.Runtime.dll [253/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Animation.Triangle.Runtime.pdb [254/457 0s] CopyTool Library/ScriptAssemblies/Unity.Notifications.iOS.dll [259/457 1s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.Notifications.dll (+2 others) [261/457 0s] MovedFromExtractor Library/Bee/artifacts/movedfrom/Unity.Notifications.iOS.ref.dll_8642665151043550249.movedfrom [262/457 0s] CopyTool Library/ScriptAssemblies/Unity.Notifications.dll [264/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.Rider.Editor.dll (+2 others) [266/457 0s] CopyTool Library/ScriptAssemblies/Unity.Rider.Editor.dll [267/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.Sprite.Editor.dll (+2 others) [269/457 0s] CopyTool Library/ScriptAssemblies/Unity.Rider.Editor.pdb [270/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Sprite.Editor.pdb [271/457 1s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.2D.IK.Runtime.dll (+2 others) [276/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.Sprite.Editor.dll [277/457 2s] Csc Library/Bee/artifacts/1300b0aE.dag/Unity.VisualStudio.Editor.dll (+2 others) [278/457 0s] CopyTool Library/ScriptAssemblies/Unity.2D.IK.Runtime.dll STDERR: tundra: error: Couldn't launch process errno: 2 (No such file or directory) GetLastError: 5 (0x00000005): Access is denied. Additional Errors: 1. (Why is number 1 is blank? it's because it is, Its in the error log) > 2.Library\ScriptAssemblies\Unity.2D.Common.Runtime.pdb: 3.Library\ScriptAssemblies\Unity.2D.Tilemap.Extras.pdb: 4.Library\ScriptAssemblies\Unity.Notifications.pdb:
[ "\nBack up everything now in case anything you try makes things worse. If you have any previous backups be sure to keep them safe. While\nunlikely, if it turned out the issues were caused by drive trouble it could be that the drive is on the verge of failing.\n\nAfter having backed everything up, try closing Unity and then deleting the Library\\Bee folder from your project directory. Hopefully your problem is now solved.\n\n\n...\n\nIf your problem was not solved: try deleting or moving the following folders and files from your project folder:\n\n\n.vs\nLibrary\nobj\nTemp\nUserSettings\n.vsconfig\n*.csproj\n*.sln\n\nBasically everything except Assets, Packages, and ProjectSettings (unless you added any custom files or folders to the root folder manually, though even if so you just backed them up a moment ago right?)\n\nIf your Unity project directory is under an unusual or long full directory name e.g. C:\\Users\\Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch\\Documents\\Unity Projects\\UnityProject or C:\\Users\\JokūbasØy̸̧̓ṽ̴͉̬̰̌͘ì̷͓ṋ̶̮̓͊͝d̴̢̫͉͋\\Documents\\UnityProject, try moving it somewhere simpler like C:\\Unity\\UnityProject.\n\nRestart your PC. You can never be too certain of what problems might potentially be fixed by turning it off and on again.\n\nLoad the project into Unity and pray it imports successfully this time.\n\n\nIf none of that works: If you updated Unity immediately before the problem began, reinstall the older version and try the above steps again. If that fails too, trying a newer Unity version in desperation would not be unreasonable. Probably the Bee folder thing solved your problem and you never got here though.\n", "I am on Ubuntu 20.04 this worked for me:\n\nOpen in safe mode then exit safe mode without fixing anything\nGo to Library/Bee/ and delete the TundraBuildState.state.map\nPress the play button and the game starts. The deleted file is also rebuilt.\n\nHope it helps someone\n", "You could try turning off your anti-virus software. That solved the problem when I started having it out of the blue.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "c#", "unity3d" ]
stackoverflow_0071750529_c#_unity3d.txt
Q: How to initialize a derived class from base class I'm using C# with the .NET 6 framework. I have a class called Message and another called TaggedMessage which inherits from Message. The idea is simple. A function receives an object of type Message and then adds several Tags to it and returns it as a TaggedMessage. A list of TaggedMessage objects is later displayed in a table. For databinding to remain nice and easy I want TaggedMessage to not contain nested properties. So it shouldn't hold an instance of Message for example. Instead it should contain all the properties from Message plus additional ones. So I thought it should inherit from Message. However I cannot find a way to instantiate TaggedMessage from Message unless I specifically assign every column from Message to TaggedMessage in its constructor. Which seems overly difficult and would mean everytime I add a property to Message, I would have to revisit the constructor of TaggedMessage. Exmaple (obviously the real thing is more complex) public class Message { public string MessageID { get; set; } = "5"; public string Subject{ get; set; } = "Test"; } Public class TaggedMessage : Message { public string MyTag { get; set; } } Message m = new Message(); TaggedMessage t = TaggedMessage; t = (TaggedMessage)m; //This ovbiously doesn't work t.Tag = "Nature"; Now the casting doesn't work because I'm casting a base class in a derived class. But then, how to I get the values from m into t? Let's assume m has 50 properties and they could change in the future. How can get an object t that has all the values m had, but with extra tags added? There must be a more elegant way than assigning all 50 properties in the constructor!? I feel like I'm missing a simple solution here. A: Message object cannot be cast to a TaggedMessage type. What are you looking for is called mapping and there are a lot of libraries for that, including but not limited to Automapper, Mapster or ExpressMapper for example. AutoMapper: static void Main() { var config = new MapperConfiguration(cfg => { cfg.CreateMap<Message, TaggedMessage>() .IncludeAllDerived(); }); var mapper = config.CreateMapper(); var m = new Message() { MessageID = "SomeMessageID", Subject = "SomeSubject" }; var t = mapper.Map<TaggedMessage>(m); t.MyTag = "MyTag"; Console.WriteLine(t.MessageID); Console.WriteLine(t.Subject); Console.WriteLine(t.MyTag); } A: There are certain ways to do what you intend to do without bothering writing the mappings manually. One of them is using a library that does it for you, like AutoMapper as Viachaslau suggests. Another can can be serializing and deserializing the object: var message = new Message(); var str = System.Text.Json.JsonSerializer.Serialize(message); var taggedMessage = System.Text.Json.JsonSerializer.Deserialize<TaggedMessage>(str); taggedMessage.MyTag = "Nature"; Both alternatives to writing that code in the constructor have their cons and can be expensive in their own ways depending on the use case, so it's not about whether you can avoid it, but about whether you should do it or not!
How to initialize a derived class from base class
I'm using C# with the .NET 6 framework. I have a class called Message and another called TaggedMessage which inherits from Message. The idea is simple. A function receives an object of type Message and then adds several Tags to it and returns it as a TaggedMessage. A list of TaggedMessage objects is later displayed in a table. For databinding to remain nice and easy I want TaggedMessage to not contain nested properties. So it shouldn't hold an instance of Message for example. Instead it should contain all the properties from Message plus additional ones. So I thought it should inherit from Message. However I cannot find a way to instantiate TaggedMessage from Message unless I specifically assign every column from Message to TaggedMessage in its constructor. Which seems overly difficult and would mean everytime I add a property to Message, I would have to revisit the constructor of TaggedMessage. Exmaple (obviously the real thing is more complex) public class Message { public string MessageID { get; set; } = "5"; public string Subject{ get; set; } = "Test"; } Public class TaggedMessage : Message { public string MyTag { get; set; } } Message m = new Message(); TaggedMessage t = TaggedMessage; t = (TaggedMessage)m; //This ovbiously doesn't work t.Tag = "Nature"; Now the casting doesn't work because I'm casting a base class in a derived class. But then, how to I get the values from m into t? Let's assume m has 50 properties and they could change in the future. How can get an object t that has all the values m had, but with extra tags added? There must be a more elegant way than assigning all 50 properties in the constructor!? I feel like I'm missing a simple solution here.
[ "Message object cannot be cast to a TaggedMessage type.\nWhat are you looking for is called mapping and there are a lot of libraries for that, including but not limited to Automapper, Mapster or ExpressMapper for example.\nAutoMapper:\nstatic void Main()\n {\n var config = new MapperConfiguration(cfg =>\n {\n cfg.CreateMap<Message, TaggedMessage>()\n .IncludeAllDerived();\n });\n\n var mapper = config.CreateMapper();\n\n var m = new Message() { MessageID = \"SomeMessageID\", Subject = \"SomeSubject\" };\n var t = mapper.Map<TaggedMessage>(m);\n t.MyTag = \"MyTag\";\n Console.WriteLine(t.MessageID);\n Console.WriteLine(t.Subject);\n Console.WriteLine(t.MyTag);\n }\n\n", "There are certain ways to do what you intend to do without bothering writing the mappings manually.\nOne of them is using a library that does it for you, like AutoMapper as Viachaslau suggests.\nAnother can can be serializing and deserializing the object:\n var message = new Message();\n var str = System.Text.Json.JsonSerializer.Serialize(message);\n var taggedMessage = System.Text.Json.JsonSerializer.Deserialize<TaggedMessage>(str);\n taggedMessage.MyTag = \"Nature\";\n\nBoth alternatives to writing that code in the constructor have their cons and can be expensive in their own ways depending on the use case, so it's not about whether you can avoid it, but about whether you should do it or not!\n" ]
[ 2, 1 ]
[]
[]
[ ".net", "c#", "inheritance" ]
stackoverflow_0074659146_.net_c#_inheritance.txt
Q: Checking corectness of parsers in Haskell For a uni assignment I need to write parsers in Haskell, right now I have the following parser i think is correct: parseYear :: Parser Char Year parseYear = Year <$> ... I want to check if it works, for example with > parseYear "2004" in ghci. this command is not valid, but i there another way to quickly check if a parser I'm writing is correct? Edit: Example, for the parser:nesting :: Parser Char Int, this would be what i want A: From your comment responses, I understand that you're using the uu-tc library, but your Parser type does not come from ParseLib.Simple, because it's not a function. This means your Parser type must come either from ParseLib.Parallel or from ParseLib.Abstract. Both of those modules define their Parser type as data, and both expose a parse function - here's the one from ParseLib.Abstract and here's the one from ParseLib.Parallel. Both these parse functions have the same shape: they take a Parser as first parameter and an input list as second. So that's how you would call it: import ParseLib.(either Parallel or Abstract).Core (parse) > parse parseYear "2004"
Checking corectness of parsers in Haskell
For a uni assignment I need to write parsers in Haskell, right now I have the following parser i think is correct: parseYear :: Parser Char Year parseYear = Year <$> ... I want to check if it works, for example with > parseYear "2004" in ghci. this command is not valid, but i there another way to quickly check if a parser I'm writing is correct? Edit: Example, for the parser:nesting :: Parser Char Int, this would be what i want
[ "From your comment responses, I understand that you're using the uu-tc library, but your Parser type does not come from ParseLib.Simple, because it's not a function.\nThis means your Parser type must come either from ParseLib.Parallel or from ParseLib.Abstract. Both of those modules define their Parser type as data, and both expose a parse function - here's the one from ParseLib.Abstract and here's the one from ParseLib.Parallel.\nBoth these parse functions have the same shape: they take a Parser as first parameter and an input list as second. So that's how you would call it:\nimport ParseLib.(either Parallel or Abstract).Core (parse)\n\n> parse parseYear \"2004\"\n\n" ]
[ 1 ]
[]
[]
[ "debugging", "haskell", "haskell_prelude", "parsing" ]
stackoverflow_0074659681_debugging_haskell_haskell_prelude_parsing.txt
Q: Unable to fetch data: fetch is not defined => when defined, TypeError: fetch is not a function I'm creating a generator that uses your google catchall domain to generate a list of email accounts and how I'm going about it, is that a function will generate a random first & last name from an array and merges it together with the catchall domain. Essentially the result would be fname + lname + domain = [email protected], but for some reason I'm getting an error. The terminal says "Fetch is not defined" but when I define it by either the node-fetch package (const fetch = require('node-fetch');, it then says "fetch is not a function". I was attempting to use the built in Fetch API to fetch the data because the script I'm basing it off of instructed to do so, after the terminal said it wasn't defined, I tried using the node-fetch package to define the variable fetch in hopes of it fixing it, but no luck either. Does anyone have a solution on why I'm getting both fetch is not a function and fetch is not defined? const prompt = require("prompt-sync") ({sigint: true }); const fs = require("fs").promises; const request = require('request'); // const fetch = require('node-fetch'); const random_useragent = require('random-useragent'); const { Webhook, MessageBuilder } = require('discord-webhook-node'); const StealthPlugin = require('puppeteer-extra-plugin-stealth'); puppeteer.use(StealthPlugin()); ( async () => { const browser = await puppeteer.launch({ headless: false, executablePath: `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`, userDataDir: `/Users/bran_d0_n/Library/Application Support/Google/Chrome/Default`, ignoreHTTPSErrors: true, ignoreDefaultArgs: ['--enable-automation'], args: [ `--disable-blink-features=AutomationControlled`, `--enable-blink-feautres=IdleDetection`, `--window-size=1920,1080`, `--disable-features=IsolateOrigins,site-per-process`, `--blink-settings=imagesEnabled=true` ] }); //------------------ Random Password Generator Function ------------------// function generatePassword() { let pass = ''; let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz0123456789@#$'; for ( let i = 1; i <= 8; i++) { var char = Math.floor(Math.random() * str.length + 1); pass += str.charAt(char) } return pass; } //------------------ First & Last Name Generator Function ------------------// async function fetchData(url) { const response = await fetch(url); return response.json(); } async function fetchData(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error('Network Response Invalid'); } return response.json(); } catch (error) { console.error('Unable To Fetch Data:', error) } } function fetchNames(nameType) { return fetchData(`https://www.randomlists.com/data/names-${nameType}.json`); } function pickRandom(list) { return list[Math.floor(Math.random() * list.length)]; } async function generateName(gender) { try { const response = await Promise.all ([ fetchNames(gender || pickRandom(['male', 'female'])), fetchNames('surnames') ]); const [ firstNames, lastNames] = response; const firstName = pickRandom(firstNames.data); const lastName = pickRandom(lastNames.data); return `${firstName} ${lastName}`; } catch (error) { console.error('Unable To Generate Name:', error); } } console.log('Loading Browser...'); // Account Values var bDayval = '01/05/22' + (Math.floor((Math.random() * ( 99-55 )) + 55 )).toString(); var passwordVal = generatePassword(); var fnameVal = generateName(); var lnameVal = generateName(); var info; var themessage; var phoneNum; var userpass; A: Loading and configuring the module node-fetch from v3 is an ESM-only module - you are not able to import it with require(). If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2. You should either use import fetch from 'node-fetch'; (Remember to add "type": "module" to the package.json) Or install the older version npm install node-fetch@2
Unable to fetch data: fetch is not defined => when defined, TypeError: fetch is not a function
I'm creating a generator that uses your google catchall domain to generate a list of email accounts and how I'm going about it, is that a function will generate a random first & last name from an array and merges it together with the catchall domain. Essentially the result would be fname + lname + domain = [email protected], but for some reason I'm getting an error. The terminal says "Fetch is not defined" but when I define it by either the node-fetch package (const fetch = require('node-fetch');, it then says "fetch is not a function". I was attempting to use the built in Fetch API to fetch the data because the script I'm basing it off of instructed to do so, after the terminal said it wasn't defined, I tried using the node-fetch package to define the variable fetch in hopes of it fixing it, but no luck either. Does anyone have a solution on why I'm getting both fetch is not a function and fetch is not defined? const prompt = require("prompt-sync") ({sigint: true }); const fs = require("fs").promises; const request = require('request'); // const fetch = require('node-fetch'); const random_useragent = require('random-useragent'); const { Webhook, MessageBuilder } = require('discord-webhook-node'); const StealthPlugin = require('puppeteer-extra-plugin-stealth'); puppeteer.use(StealthPlugin()); ( async () => { const browser = await puppeteer.launch({ headless: false, executablePath: `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`, userDataDir: `/Users/bran_d0_n/Library/Application Support/Google/Chrome/Default`, ignoreHTTPSErrors: true, ignoreDefaultArgs: ['--enable-automation'], args: [ `--disable-blink-features=AutomationControlled`, `--enable-blink-feautres=IdleDetection`, `--window-size=1920,1080`, `--disable-features=IsolateOrigins,site-per-process`, `--blink-settings=imagesEnabled=true` ] }); //------------------ Random Password Generator Function ------------------// function generatePassword() { let pass = ''; let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz0123456789@#$'; for ( let i = 1; i <= 8; i++) { var char = Math.floor(Math.random() * str.length + 1); pass += str.charAt(char) } return pass; } //------------------ First & Last Name Generator Function ------------------// async function fetchData(url) { const response = await fetch(url); return response.json(); } async function fetchData(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error('Network Response Invalid'); } return response.json(); } catch (error) { console.error('Unable To Fetch Data:', error) } } function fetchNames(nameType) { return fetchData(`https://www.randomlists.com/data/names-${nameType}.json`); } function pickRandom(list) { return list[Math.floor(Math.random() * list.length)]; } async function generateName(gender) { try { const response = await Promise.all ([ fetchNames(gender || pickRandom(['male', 'female'])), fetchNames('surnames') ]); const [ firstNames, lastNames] = response; const firstName = pickRandom(firstNames.data); const lastName = pickRandom(lastNames.data); return `${firstName} ${lastName}`; } catch (error) { console.error('Unable To Generate Name:', error); } } console.log('Loading Browser...'); // Account Values var bDayval = '01/05/22' + (Math.floor((Math.random() * ( 99-55 )) + 55 )).toString(); var passwordVal = generatePassword(); var fnameVal = generateName(); var lnameVal = generateName(); var info; var themessage; var phoneNum; var userpass;
[ "Loading and configuring the module\n\nnode-fetch from v3 is an ESM-only module - you are not able to import it with require().\n\n\nIf you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2.\n\nYou should either use\nimport fetch from 'node-fetch';\n\n(Remember to add \"type\": \"module\" to the package.json)\nOr install the older version\nnpm install node-fetch@2\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "node.js", "puppeteer" ]
stackoverflow_0074660151_javascript_node.js_puppeteer.txt
Q: My code works fine from constructor but always returns 1 using a setter My Java teacher asked for an exponentiation exercise. He wants us to use bucle (for or while) for this, not math functions. Well, I have wrote the code but I realised that if I use the constructor, it works fine. But if I try to choose the value from a setter it always return 1. package potencia; public class potencia { private int base = 0; private int exponente = 0; private int resultado = 1; public int getBase() { return base; } public int getExponente() { return exponente; } public int getResultado() { // De la variable resultado solo creamos el getter pues no nos interesa "settear" el resultado, sino que lo calcule el programa return resultado; } public void setBase(int base) { this.base = base; } public void setExponente(int exponente) { this.exponente = exponente; } public potencia(){} public potencia(int base, int exponente){ this.base = base; this.exponente = exponente; if (exponente == 0) { // Si la variable EXPONENTE se inicializa a 0, la variable RESULTADO será 1 this.resultado = 1; } if (base == 1) { // Si la variable BASE se inicializa a 1, la variable RESULTADO será 1 this.resultado = 1; } if (base > 1 && exponente > 0) { for (int i=1; i<=exponente; i++) { resultado *= base; // Uso de operador de asignación "*=", significa lo mismo que "resultado = resultado * base" } } } public void muestraResultado () { System.out.println("El resultado es " + resultado); } } The next example works perfectly: package potencia; public class calcularPotencia { public static void main(String[] args) { potencia MiCalculadora = new potencia(5, 4); MiCalculadora.muestraResultado(); System.out.println(MiCalculadora.getResultado()); } } It returns: "El resultado es 625 625" But when I use setters: package potencia; public class calcularPotencia { public static void main(String[] args) { potencia MiCalculadora = new potencia(); MiCalculadora.setBase(5); MiCalculadora.setExponente(4); MiCalculadora.muestraResultado(); System.out.println(MiCalculadora.getResultado()); } } Returns: "El resultado es 1 1" I supposed that something went wrong with setters and getters, so I deleted them and inserted them again. It was resultless, the fail persists. I also have checked methods and classes, but I can not see the mistake. Thank you all for your help, mates. A: You aren't calculating the result when you use the setter. You could remove the member variable for resultado and calculate it in the getter: public int getResultado() { // De la variable resultado solo creamos el getter pues no nos interesa "settear" el resultado, sino que lo calcule el programa if (exponente == 0) { // Si la variable EXPONENTE se inicializa a 0, la variable RESULTADO será 1 return 1; } if (base == 1) { // Si la variable BASE se inicializa a 1, la variable RESULTADO será 1 return = 1; } if (base > 1 && exponente > 0) { int resultado = 1; for (int i=1; i<=exponente; i++) { resultado *= base; // Uso de operador de asignación "*=", significa lo mismo que "resultado = resultado * base" } return resultado; } else { throw new RuntimeException("base or exponente < 0"); } } You could also keep the field and cache the result after calculating it. initialize it to -1, since that is not a valid result. Then do: public int getResultado() { if (resultado < 0) { calculateResultado(); } return resultado; } Where the calculate method will be similar to what you are doing in the constructor (in fact you can call it from the constructor).
My code works fine from constructor but always returns 1 using a setter
My Java teacher asked for an exponentiation exercise. He wants us to use bucle (for or while) for this, not math functions. Well, I have wrote the code but I realised that if I use the constructor, it works fine. But if I try to choose the value from a setter it always return 1. package potencia; public class potencia { private int base = 0; private int exponente = 0; private int resultado = 1; public int getBase() { return base; } public int getExponente() { return exponente; } public int getResultado() { // De la variable resultado solo creamos el getter pues no nos interesa "settear" el resultado, sino que lo calcule el programa return resultado; } public void setBase(int base) { this.base = base; } public void setExponente(int exponente) { this.exponente = exponente; } public potencia(){} public potencia(int base, int exponente){ this.base = base; this.exponente = exponente; if (exponente == 0) { // Si la variable EXPONENTE se inicializa a 0, la variable RESULTADO será 1 this.resultado = 1; } if (base == 1) { // Si la variable BASE se inicializa a 1, la variable RESULTADO será 1 this.resultado = 1; } if (base > 1 && exponente > 0) { for (int i=1; i<=exponente; i++) { resultado *= base; // Uso de operador de asignación "*=", significa lo mismo que "resultado = resultado * base" } } } public void muestraResultado () { System.out.println("El resultado es " + resultado); } } The next example works perfectly: package potencia; public class calcularPotencia { public static void main(String[] args) { potencia MiCalculadora = new potencia(5, 4); MiCalculadora.muestraResultado(); System.out.println(MiCalculadora.getResultado()); } } It returns: "El resultado es 625 625" But when I use setters: package potencia; public class calcularPotencia { public static void main(String[] args) { potencia MiCalculadora = new potencia(); MiCalculadora.setBase(5); MiCalculadora.setExponente(4); MiCalculadora.muestraResultado(); System.out.println(MiCalculadora.getResultado()); } } Returns: "El resultado es 1 1" I supposed that something went wrong with setters and getters, so I deleted them and inserted them again. It was resultless, the fail persists. I also have checked methods and classes, but I can not see the mistake. Thank you all for your help, mates.
[ "You aren't calculating the result when you use the setter.\nYou could remove the member variable for resultado and calculate it in the getter:\n public int getResultado() { // De la variable resultado solo creamos el getter pues no nos interesa \"settear\" el resultado, sino que lo calcule el programa\n if (exponente == 0) { // Si la variable EXPONENTE se inicializa a 0, la variable RESULTADO será 1\n return 1;\n }\n if (base == 1) { // Si la variable BASE se inicializa a 1, la variable RESULTADO será 1\n return = 1;\n }\n if (base > 1 && exponente > 0) {\n int resultado = 1;\n for (int i=1; i<=exponente; i++) {\n resultado *= base; // Uso de operador de asignación \"*=\", significa lo mismo que \"resultado = resultado * base\"\n }\n return resultado;\n } else {\n throw new RuntimeException(\"base or exponente < 0\");\n }\n }\n\nYou could also keep the field and cache the result after calculating it. initialize it to -1, since that is not a valid result. Then do:\n public int getResultado() {\n if (resultado < 0) {\n calculateResultado();\n }\n return resultado;\n }\n\nWhere the calculate method will be similar to what you are doing in the constructor (in fact you can call it from the constructor).\n" ]
[ 1 ]
[]
[]
[ "constructor", "java", "return", "setter" ]
stackoverflow_0074659970_constructor_java_return_setter.txt
Q: how can i count chars from word which in the array? i have an array ["academy"] and i need count chars from the string in the array. output: a:2 c:1 d:1 e:1 m:1 y:1 like this i tried two for loops function sumChar(arr){ let alph="abcdefghijklmnopqrstuvxyz"; let count=0; for (const iterator of arr) { for(let i=0; i<alph.length; i++){ if(iterator.charAt(i)==alph[i]){ count++; console.log(`${iterator[i]} : ${count}`); count=0; } } } } console.log(sumChar(["abdulloh"])); it works wrong Output: a : 1 b : 1 h : 1 undefined A: To count the number of occurrences of each character in a string, you can use a for loop to iterate through the string and add each character to an object as a key, with the value being the number of times it occurs. Here is an example: // create an empty object to store the character counts var charCounts = {}; // get the string from the array var str = ["academy"][0]; // iterate through the string and count the occurrences of each character for (var i = 0; i < str.length; i++) { var char = str[i]; if (charCounts[char] === undefined) { // if the character has not been encountered before, set its count to 1 charCounts[char] = 1; } else { // if the character has been encountered before, increment its count by 1 charCounts[char]++; } } // print the character counts for (var char in charCounts) { console.log(char + ": " + charCounts[char]); } A: Here's a concise method. [...new Set(word.split(''))] creates an array of letters omitting any duplicates. .map takes each letter from that array and runs it through the length checker. ({ [m]: word.split(m).length - 1 }) sets the letter as the object key and the word.split(m).length - 1is a quick way to determine how many times that letter shows up. const countLetters = word => ( [...new Set(word.split(''))].map(m => ({ [m]: word.split(m).length - 1 }))) console.log(countLetters("academy")) A: You can check the occurrences using regex also. in this i made a method which checks for the character in the string. Hope it helps. word: string = 'abcdefghijklkmnopqrstuvwxyzgg'; charsArrayWithCount = {}; CheckWordCount(): void { for(var i = 0;i < this.word.length; i++){ if(this.charsArrayWithCount[this.word[i]] === undefined){ this.charsArrayWithCount[this.word[i]] = this.charCount(this.word, this.word[i]); } } console.log(this.charsArrayWithCount); } charCount(string, char) { let expression = new RegExp(char, "g"); return string.match(expression).length; } A: You can simply achieve this requirement with the help of Array.reduce() method. Live Demo : const arr = ["academy"]; const res = arr.map(word => { return word.split('').reduce((obj, cur) => { obj[cur] = obj[cur] ? obj[cur] + 1 : 1 return obj; }, {}); }); console.log(res); A: I think this is the simplest: const input = 'academy'; const res = {}; input.split('').forEach(a => res[a] = (res[a] ?? 0) + 1); console.log(res);
how can i count chars from word which in the array?
i have an array ["academy"] and i need count chars from the string in the array. output: a:2 c:1 d:1 e:1 m:1 y:1 like this i tried two for loops function sumChar(arr){ let alph="abcdefghijklmnopqrstuvxyz"; let count=0; for (const iterator of arr) { for(let i=0; i<alph.length; i++){ if(iterator.charAt(i)==alph[i]){ count++; console.log(`${iterator[i]} : ${count}`); count=0; } } } } console.log(sumChar(["abdulloh"])); it works wrong Output: a : 1 b : 1 h : 1 undefined
[ "To count the number of occurrences of each character in a string, you can use a for loop to iterate through the string and add each character to an object as a key, with the value being the number of times it occurs. Here is an example:\n\n\n// create an empty object to store the character counts\nvar charCounts = {};\n\n// get the string from the array\nvar str = [\"academy\"][0];\n\n// iterate through the string and count the occurrences of each character\nfor (var i = 0; i < str.length; i++) {\n var char = str[i];\n if (charCounts[char] === undefined) {\n // if the character has not been encountered before, set its count to 1\n charCounts[char] = 1;\n } else {\n // if the character has been encountered before, increment its count by 1\n charCounts[char]++;\n }\n}\n\n// print the character counts\nfor (var char in charCounts) {\n console.log(char + \": \" + charCounts[char]);\n}\n\n\n\n", "Here's a concise method. [...new Set(word.split(''))] creates an array of letters omitting any duplicates. .map takes each letter from that array and runs it through the length checker. ({ [m]: word.split(m).length - 1 }) sets the letter as the object key and the word.split(m).length - 1is a quick way to determine how many times that letter shows up.\n\n\nconst countLetters = word => (\n [...new Set(word.split(''))].map(m => ({\n [m]: word.split(m).length - 1\n })))\n\nconsole.log(countLetters(\"academy\"))\n\n\n\n", "You can check the occurrences using regex also. in this i made a method which checks for the character in the string. Hope it helps.\nword: string = 'abcdefghijklkmnopqrstuvwxyzgg';\ncharsArrayWithCount = {};\nCheckWordCount(): void {\n for(var i = 0;i < this.word.length; i++){\n if(this.charsArrayWithCount[this.word[i]] === undefined){\n this.charsArrayWithCount[this.word[i]] = this.charCount(this.word, this.word[i]);\n }\n }\n console.log(this.charsArrayWithCount);\n}\ncharCount(string, char) {\n let expression = new RegExp(char, \"g\");\n return string.match(expression).length;\n}\n\n", "You can simply achieve this requirement with the help of Array.reduce() method.\nLive Demo :\n\n\nconst arr = [\"academy\"];\n\nconst res = arr.map(word => {\n return word.split('').reduce((obj, cur) => {\n obj[cur] = obj[cur] ? obj[cur] + 1 : 1\n return obj;\n }, {});\n});\n\nconsole.log(res);\n\n\n\n", "I think this is the simplest:\n\n\nconst input = 'academy';\n\nconst res = {};\n\ninput.split('').forEach(a => res[a] = (res[a] ?? 0) + 1);\n\nconsole.log(res);\n\n\n\n" ]
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "arrays", "char", "count", "javascript", "string" ]
stackoverflow_0074647878_arrays_char_count_javascript_string.txt
Q: Export tex document which uses the exam class (Part 2) I would like to export a text document which uses the exam class to markdown. To do so, I am currently using a workaround which was suggested in this answer, which relies on pseudo-definitions which in turn overwrite the definitions of the exam class such that pandoc can produce a clean markdown file. Although, the workaround works for the suggested multiple-choice questions, I cannot adopt the solution to work for text with “fillin gaps” such as the document below: \documentclass[answers]{exam} \usepackage{minted} \let\oldpart\part \renewcommand{\part}[1][]{\oldpart[#1]{}} \begin{document} \begin{questions} \question Exercise 1 \begin{parts} \part[1] This fills in the \fillin[blanks][3cm] \end{parts} \end{questions} \end{document} If I use the following pseudo-definitions in a separate file: % ignore \part \renewcommand{\part}[0][1]{} % Treat checkboxes like an itemized list \newenvironment{checkboxes}{\begin{itemize}}{\end{itemize}} \renewcommand{\CorrectChoice}{\item ☒ } \renewcommand{\choice}{\item ☐ } \renewcommand\fillin[2][{}]{\textbf{#1}} I get the following broken markdown output This fills in the **blanks**3cm\] Moreover is there a way for pandoc to ignore \begin{parts} and \end{parts} so that there are no ::: in the final Markdown file? A: The \fillin problem can be solved with \newcommand{\fillin}[1][1]{\textbf{#1}\noop} whereas the parts div can be removed with \newenvironment{parts}{}{}
Export tex document which uses the exam class (Part 2)
I would like to export a text document which uses the exam class to markdown. To do so, I am currently using a workaround which was suggested in this answer, which relies on pseudo-definitions which in turn overwrite the definitions of the exam class such that pandoc can produce a clean markdown file. Although, the workaround works for the suggested multiple-choice questions, I cannot adopt the solution to work for text with “fillin gaps” such as the document below: \documentclass[answers]{exam} \usepackage{minted} \let\oldpart\part \renewcommand{\part}[1][]{\oldpart[#1]{}} \begin{document} \begin{questions} \question Exercise 1 \begin{parts} \part[1] This fills in the \fillin[blanks][3cm] \end{parts} \end{questions} \end{document} If I use the following pseudo-definitions in a separate file: % ignore \part \renewcommand{\part}[0][1]{} % Treat checkboxes like an itemized list \newenvironment{checkboxes}{\begin{itemize}}{\end{itemize}} \renewcommand{\CorrectChoice}{\item ☒ } \renewcommand{\choice}{\item ☐ } \renewcommand\fillin[2][{}]{\textbf{#1}} I get the following broken markdown output This fills in the **blanks**3cm\] Moreover is there a way for pandoc to ignore \begin{parts} and \end{parts} so that there are no ::: in the final Markdown file?
[ "The \\fillin problem can be solved with\n\\newcommand{\\fillin}[1][1]{\\textbf{#1}\\noop}\n\nwhereas the parts div can be removed with\n\\newenvironment{parts}{}{}\n\n" ]
[ 0 ]
[]
[]
[ "converters", "latex", "markdown", "pandoc" ]
stackoverflow_0074646430_converters_latex_markdown_pandoc.txt
Q: Update selected failed I use this code to open another screen in SO301000 public virtual IEnumerable EcrListemodele(PXAdapter adapter) { var cmdencours = TransactionsOrder.Current; if (cmdencours==null) return adapter.Get(); ZMODELEFILTER.Current.Immatriculation=cmdencours.GetExtension<SOOrderExt>().UsrImmatriculation; ZMODELEFILTER.AskExt(); foreach (ZMODELE un_modele in SOZmodele.Select()) { if (un_modele.Selected == true) { cmdencours.GetExtension<SOOrderExt>().Usrlistmodele=un_modele.Modele; cmdencours.GetExtension<SOOrderExt>().Usrlistpiece=un_modele.Piece; TransactionsOrder.Update(cmdencours); } } //} return adapter.Get(); } I have this error when I select one option Thanks, Xavier A: Make sure that the audit fields use the proper attributes. For example, CreatedByID uses: #region CreatedByID public abstract class createdByID : PX.Data.BQL.BqlGuid.Field<createdByID> { } protected Guid? _CreatedByID; [PXDBCreatedByID()] public virtual Guid? CreatedByID { get { return this._CreatedByID; } set { this._CreatedByID = value; } } #endregion The attributes you would want to use on the respective fields are: PXDBCreatedByID PXDBCreatedByScreenID PXDBCreatedDateTime PXDBLastModifiedByID PXDBLastModifiedByScreenID PXDBLastModifiedDateTime PXDBTimestamp
Update selected failed
I use this code to open another screen in SO301000 public virtual IEnumerable EcrListemodele(PXAdapter adapter) { var cmdencours = TransactionsOrder.Current; if (cmdencours==null) return adapter.Get(); ZMODELEFILTER.Current.Immatriculation=cmdencours.GetExtension<SOOrderExt>().UsrImmatriculation; ZMODELEFILTER.AskExt(); foreach (ZMODELE un_modele in SOZmodele.Select()) { if (un_modele.Selected == true) { cmdencours.GetExtension<SOOrderExt>().Usrlistmodele=un_modele.Modele; cmdencours.GetExtension<SOOrderExt>().Usrlistpiece=un_modele.Piece; TransactionsOrder.Update(cmdencours); } } //} return adapter.Get(); } I have this error when I select one option Thanks, Xavier
[ "Make sure that the audit fields use the proper attributes. For example, CreatedByID uses:\n #region CreatedByID\n public abstract class createdByID : PX.Data.BQL.BqlGuid.Field<createdByID>\n {\n }\n protected Guid? _CreatedByID;\n [PXDBCreatedByID()]\n public virtual Guid? CreatedByID\n {\n get\n {\n return this._CreatedByID;\n }\n set\n {\n this._CreatedByID = value;\n }\n }\n #endregion\n\nThe attributes you would want to use on the respective fields are:\n\nPXDBCreatedByID\nPXDBCreatedByScreenID\nPXDBCreatedDateTime\nPXDBLastModifiedByID\nPXDBLastModifiedByScreenID\nPXDBLastModifiedDateTime\nPXDBTimestamp\n\n" ]
[ 0 ]
[]
[]
[ "acumatica" ]
stackoverflow_0074607039_acumatica.txt
Q: Merging txt file into a dataframe on R I have a txt file with 100,000+ lines of data. I want to turn it into a dataframe but do not need every line of data. An example of the data entry looks like this: FN Clarivate Analytics Web of Science VR 1.0 PT J AU Yang, Qiang Liu, Yang Chen, Tianjian Tong, Yongxin TI Federated Machine Learning: Concept and Applications SO ACM TRANSACTIONS ON INTELLIGENT SYSTEMS AND TECHNOLOGY VL 10 IS 2 AR 12 DI 10.1145/3298981 DT Article PD FEB 2019 PY 2019 AB Today's artificial intelligence still faces two major challenges (...) etc. I only want the rows that begin TI, AU, PD, AB and extract them into corresponding named columns. This is as far as I have gotten too and I am really struggling! read.table("groupprojectdatabase.txt", header = FALSE, sep = ",", quote = "", dec = ".", numerals = c("allow.loss"), row.names = c("TI", "AU", "PB","AB"), col.names = c('title_col','author_col','date_col','summary_col'), as.is = !stringsAsFactors, na.strings = "NA", colClasses = NA, nrows = -1, skip = 0, check.names = TRUE, fill = FALSE, strip.white = FALSE, blank.lines.skip = TRUE, comment.char = "#", allowEscapes = FALSE, flush = FALSE, stringsAsFactors = FALSE, fileEncoding = "", encoding = "unknown", text, skipNul = FALSE) Any help would be really appreciated, even if it was what functions I need to look up or if I am on the right tracks. I was thinking that sep = command is relevant but I couldnt work out how to tell it to skip everything but the TI,AU,PB and AB rows In particular I am not sure how to program R to treat entire sentences as variables, not each word etc. Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec, : line 1 did not have 4 elements A: I have made a file test.txt based on your data above. After having some problems using read.table I switched to read::read_delim from the tidyverse. This reads the file line by line. This line is then separated by the first whitespace, i.e. after the first 2 letters. Because there were 4 lines (AU first two letters) which belong together the last part of the code below bings those lines together. library(tidyverse) df <- read_delim("path_to_your/test.txt", delim = ";", col_names = TRUE) ddf <- df |> separate(`FN Clarivate Analytics Web of Science`, into = c("first", "rest"), sep = " ", extra = 'merge') |> mutate(first = ifelse(first == "", NA, first)) |> fill(first) |> group_by(first) |> mutate(rest = paste0(rest, collapse = "")) |> distinct(first, .keep_all = T) ddf |> filter(first %in% c('TI', 'AU', 'PD', 'AB')) #> # A tibble: 4 × 2 #> # Groups: first [4] #> first rest #> <chr> <chr> #> 1 AU Yang, Qiang Liu, Yang Chen, Tianjian Tong, Yongxin #> 2 TI Federated Machine Learning: Concept and Applications #> 3 PD FEB 2019 #> 4 AB Today's artificial intelligence still faces two major challenges
Merging txt file into a dataframe on R
I have a txt file with 100,000+ lines of data. I want to turn it into a dataframe but do not need every line of data. An example of the data entry looks like this: FN Clarivate Analytics Web of Science VR 1.0 PT J AU Yang, Qiang Liu, Yang Chen, Tianjian Tong, Yongxin TI Federated Machine Learning: Concept and Applications SO ACM TRANSACTIONS ON INTELLIGENT SYSTEMS AND TECHNOLOGY VL 10 IS 2 AR 12 DI 10.1145/3298981 DT Article PD FEB 2019 PY 2019 AB Today's artificial intelligence still faces two major challenges (...) etc. I only want the rows that begin TI, AU, PD, AB and extract them into corresponding named columns. This is as far as I have gotten too and I am really struggling! read.table("groupprojectdatabase.txt", header = FALSE, sep = ",", quote = "", dec = ".", numerals = c("allow.loss"), row.names = c("TI", "AU", "PB","AB"), col.names = c('title_col','author_col','date_col','summary_col'), as.is = !stringsAsFactors, na.strings = "NA", colClasses = NA, nrows = -1, skip = 0, check.names = TRUE, fill = FALSE, strip.white = FALSE, blank.lines.skip = TRUE, comment.char = "#", allowEscapes = FALSE, flush = FALSE, stringsAsFactors = FALSE, fileEncoding = "", encoding = "unknown", text, skipNul = FALSE) Any help would be really appreciated, even if it was what functions I need to look up or if I am on the right tracks. I was thinking that sep = command is relevant but I couldnt work out how to tell it to skip everything but the TI,AU,PB and AB rows In particular I am not sure how to program R to treat entire sentences as variables, not each word etc. Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec, : line 1 did not have 4 elements
[ "I have made a file test.txt based on your data above. After having some problems using read.table I switched to read::read_delim from the tidyverse.\nThis reads the file line by line. This line is then separated by the first whitespace, i.e. after the first 2 letters.\nBecause there were 4 lines (AU first two letters) which belong together the last part of the code below bings those lines together.\nlibrary(tidyverse)\n\ndf <- read_delim(\"path_to_your/test.txt\", delim = \";\", col_names = TRUE)\n\nddf <- df |> \n separate(`FN Clarivate Analytics Web of Science`, \n into = c(\"first\", \"rest\"), \n sep = \" \", extra = 'merge') |> \n mutate(first = ifelse(first == \"\", NA, first)) |> \n fill(first) |> \n group_by(first) |> \n mutate(rest = paste0(rest, collapse = \"\")) |> \n distinct(first, .keep_all = T)\n \nddf |> \n filter(first %in% c('TI', 'AU', 'PD', 'AB'))\n\n#> # A tibble: 4 × 2\n#> # Groups: first [4]\n#> first rest \n#> <chr> <chr> \n#> 1 AU Yang, Qiang Liu, Yang Chen, Tianjian Tong, Yongxin \n#> 2 TI Federated Machine Learning: Concept and Applications \n#> 3 PD FEB 2019 \n#> 4 AB Today's artificial intelligence still faces two major challenges\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "r", "transform" ]
stackoverflow_0074644656_dataframe_r_transform.txt
Q: how to dynamically allocate a 2d array with the help of a function in C void alloc_matrix(int ***mat, int *m, int *n) { mat = (int **)malloc(*m * sizeof(int *)); for(int i = 0; i < *m; i++) mat[i] = (int *)malloc(*n * sizeof(int)); for(int i = 0; i < *m; i++) for(int j = 0; j < *n; j++) scanf("%d", &mat[i][j]); for(int i = 0; i < *m; i++) for(int j = 0; j < *n; j++) { printf("%d ", mat[i][j]); printf('\n'); } } i wanted to read and allocate the matrix in the same function, but when i call it, nothing will print, i think there is something wrong with the way i used the pointers, but i cant figure out what is the problem A: The expressions like &mat[i][j] or mat[i][j] used in the for loops and the expression mat used in the statement that allocates memory for an array of pointers mat = (int **)malloc(*m * sizeof(int *)); for(int i = 0; i < *m; i++) mat[i] = (int *)malloc(*n * sizeof(int)); for(int i = 0; i < *m; i++) for(int j = 0; j < *n; j++) scanf("%d", &mat[i][j]); for(int i = 0; i < *m; i++) for(int j = 0; j < *n; j++) { printf("%d ", mat[i][j]); printf('\n'); } are incorect. Instead you have to write *mat = (int **)malloc(*m * sizeof(int *)); for(int i = 0; i < *m; i++) ( * mat )[i] = (int *)malloc(*n * sizeof(int)); for(int i = 0; i < *m; i++) for(int j = 0; j < *n; j++) scanf("%d", &( *mat )[i][j]); for(int i = 0; i < *m; i++) { for(int j = 0; j < *n; j++) { printf("%d ", ( *mat )[i][j]); } printf( "\n" ); } That is the parameter mat has the type int ***. This means that the original pointer of the type int ** is passed to the function by reference indirectly through a pointer to it. Thus you need to dereference the parameter to get an access to the original pointer. And this call of printf printf('\n'); where you are incorrectly using the integer character constant '\n' instead of the string literal "\n" should be placed after the inner for loop. Also there is no sense to declare m and n as pointers. The function could be declared at least like void alloc_matrix(int ***mat, int m, int n) { Here is a demonstration program #include <stdio.h> #include <stdlib.h> void alloc_matrix( int ***mat, int m, int n ) { *mat = ( int ** )malloc( m * sizeof( int * ) ); for (int i = 0; i < m; i++) ( * mat )[i] = ( int * )malloc( n * sizeof( int ) ); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) scanf( "%d", &( *mat )[i][j] ); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { printf( "%d ", ( *mat )[i][j] ); } putchar( '\n' ); } } int main( void ) { enum { M = 2, N = 3 }; int **mat = NULL; alloc_matrix( &mat, M, N ); for (int i = 0; i < M; i++) { free( mat[i] ); } free( mat ); } Its output might look like 1 2 3 4 5 6 1 2 3 4 5 6 The first two lines is the user input and the next two lines is the output of elements of the dynamically allocated arrays.
how to dynamically allocate a 2d array with the help of a function in C
void alloc_matrix(int ***mat, int *m, int *n) { mat = (int **)malloc(*m * sizeof(int *)); for(int i = 0; i < *m; i++) mat[i] = (int *)malloc(*n * sizeof(int)); for(int i = 0; i < *m; i++) for(int j = 0; j < *n; j++) scanf("%d", &mat[i][j]); for(int i = 0; i < *m; i++) for(int j = 0; j < *n; j++) { printf("%d ", mat[i][j]); printf('\n'); } } i wanted to read and allocate the matrix in the same function, but when i call it, nothing will print, i think there is something wrong with the way i used the pointers, but i cant figure out what is the problem
[ "The expressions like &mat[i][j] or mat[i][j] used in the for loops and the expression mat used in the statement that allocates memory for an array of pointers\nmat = (int **)malloc(*m * sizeof(int *));\n\nfor(int i = 0; i < *m; i++)\n mat[i] = (int *)malloc(*n * sizeof(int));\n\nfor(int i = 0; i < *m; i++)\n for(int j = 0; j < *n; j++)\n scanf(\"%d\", &mat[i][j]);\n\nfor(int i = 0; i < *m; i++)\n for(int j = 0; j < *n; j++) {\n printf(\"%d \", mat[i][j]);\n printf('\\n');\n }\n\nare incorect.\nInstead you have to write\n*mat = (int **)malloc(*m * sizeof(int *));\n\nfor(int i = 0; i < *m; i++)\n ( * mat )[i] = (int *)malloc(*n * sizeof(int));\n\nfor(int i = 0; i < *m; i++)\n for(int j = 0; j < *n; j++)\n scanf(\"%d\", &( *mat )[i][j]);\n\nfor(int i = 0; i < *m; i++)\n{\n for(int j = 0; j < *n; j++) {\n printf(\"%d \", ( *mat )[i][j]);\n }\n printf( \"\\n\" );\n}\n\nThat is the parameter mat has the type int ***. This means that the original pointer of the type int ** is passed to the function by reference indirectly through a pointer to it. Thus you need to dereference the parameter to get an access to the original pointer.\nAnd this call of printf\nprintf('\\n');\n\nwhere you are incorrectly using the integer character constant '\\n' instead of the string literal \"\\n\" should be placed after the inner for loop.\nAlso there is no sense to declare m and n as pointers. The function could be declared at least like\nvoid alloc_matrix(int ***mat, int m, int n) {\n\nHere is a demonstration program\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid alloc_matrix( int ***mat, int m, int n ) \n{\n *mat = ( int ** )malloc( m * sizeof( int * ) );\n\n for (int i = 0; i < m; i++)\n ( * mat )[i] = ( int * )malloc( n * sizeof( int ) );\n\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++)\n scanf( \"%d\", &( *mat )[i][j] );\n\n for (int i = 0; i < m; i++)\n {\n for (int j = 0; j < n; j++) {\n printf( \"%d \", ( *mat )[i][j] );\n }\n putchar( '\\n' );\n }\n}\n\nint main( void )\n{\n enum { M = 2, N = 3 };\n int **mat = NULL;\n\n alloc_matrix( &mat, M, N );\n\n for (int i = 0; i < M; i++)\n {\n free( mat[i] );\n }\n free( mat );\n}\n\nIts output might look like\n1 2 3\n4 5 6\n1 2 3\n4 5 6\n\nThe first two lines is the user input and the next two lines is the output of elements of the dynamically allocated arrays.\n" ]
[ 1 ]
[]
[]
[ "c", "dereference", "dynamic_memory_allocation", "pass_by_reference", "pointer_to_pointer" ]
stackoverflow_0074660153_c_dereference_dynamic_memory_allocation_pass_by_reference_pointer_to_pointer.txt
Q: In DynamoDB, How do we Update if ConditionExpression failed? Perhaps an Else expression Is it possible to do if ConditionExpression fails i will instead UpdateExpression this expression. I am trying to do something like this, i know ElseUpdateExpression doesn't exist: const params = { TableName: "Services", Key: { id: 1, }, UpdateExpression: "SET nextPageNumber = nextPageNumber + :incr", // increments page number if less than 99 ElseUpdateExpression: "SET nextChapter = nextChapter + :incr", ConditionExpression: "nextPageNumber < :max", // Update fails if reached 99 ExpressionAttributeValues: { ":incr": 1, ":max": 1 }, ReturnValues: 'ALL_NEW', }; return ddbClient.update(params).promise(); A: You cannot do logic like that within the database. You could however pull the item to the client first and then issue whatever appropriate update. Use optimistic concurrency control if you expect potentially multiple concurrent requests.
In DynamoDB, How do we Update if ConditionExpression failed? Perhaps an Else expression
Is it possible to do if ConditionExpression fails i will instead UpdateExpression this expression. I am trying to do something like this, i know ElseUpdateExpression doesn't exist: const params = { TableName: "Services", Key: { id: 1, }, UpdateExpression: "SET nextPageNumber = nextPageNumber + :incr", // increments page number if less than 99 ElseUpdateExpression: "SET nextChapter = nextChapter + :incr", ConditionExpression: "nextPageNumber < :max", // Update fails if reached 99 ExpressionAttributeValues: { ":incr": 1, ":max": 1 }, ReturnValues: 'ALL_NEW', }; return ddbClient.update(params).promise();
[ "You cannot do logic like that within the database. You could however pull the item to the client first and then issue whatever appropriate update. Use optimistic concurrency control if you expect potentially multiple concurrent requests.\n" ]
[ 1 ]
[]
[]
[ "amazon_dynamodb" ]
stackoverflow_0074659712_amazon_dynamodb.txt
Q: How to hide/remove slider ticks/steps and their labels in plotly.js? Is it possible to remove or hide the animation slider's step ticks and labels? I would like to remove the slider step markers (ticks) and their labels: 'Red', 'Green' and 'Blue' from underneath the slider. However still keeping the current frame/step label displayed. (Above slider on right side) Preferably would like to be able to do it with plotly's layout configuration but if it's possible to hide via CSS rules I'm all ears. The example below is taken directly from their sample page here: https://codepen.io/plotly/pen/NbKmmQ Plotly.plot('graph', { data: [{ x: [1, 2, 3], y: [2, 1, 3], line: { color: 'red', simplify: false, } }], layout: { sliders: [{ pad: {t: 30}, x: 0.05, len: 0.95, currentvalue: { xanchor: 'right', prefix: 'color: ', font: { color: '#888', size: 20 } }, transition: {duration: 500}, // By default, animate commands are bound to the most recently animated frame: steps: [{ label: 'red', method: 'animate', args: [['red'], { mode: 'immediate', frame: {redraw: false, duration: 500}, transition: {duration: 500} }] }, { label: 'green', method: 'animate', args: [['green'], { mode: 'immediate', frame: {redraw: false, duration: 500}, transition: {duration: 500} }] }, { label: 'blue', method: 'animate', args: [['blue'], { mode: 'immediate', frame: {redraw: false, duration: 500}, transition: {duration: 500} }] }] }], updatemenus: [{ type: 'buttons', showactive: false, x: 0.05, y: 0, xanchor: 'right', yanchor: 'top', direction: 'left', pad: {t: 60, r: 20}, buttons: [{ label: 'Play', method: 'animate', args: [null, { fromcurrent: true, frame: {redraw: false, duration: 1000}, transition: {duration: 500} }] }, { label: 'Pause', method: 'animate', args: [[null], { mode: 'immediate', frame: {redraw: false, duration: 0} }] }] }] }, // The slider itself does not contain any notion of timing, so animating a slider // must be accomplished through a sequence of frames. Here we'll change the color // and the data of a single trace: frames: [{ name: 'red', data: [{ y: [2, 1, 3], 'line.color': 'red' }] }, { name: 'green', data: [{ y: [3, 2, 1], 'line.color': 'green'}] }, { name: 'blue', data: [{ y: [1, 3, 2], 'line.color': 'blue'}] }] }); html, body { margin: 0; padding: 0; } #graph { vertical-align: top; } <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <div id="graph"></div> </body> A: Currently there is no property in the official docs, So please consider this alternate, where we set the tickcolor and font.color of the slider label and tick as white, which is same as the background. The properties that do this, are shown below. tickcolor: 'white', font: { color: 'white' } Plotly.plot('graph', { data: [{ x: [1, 2, 3], y: [2, 1, 3], line: { color: 'red', simplify: false, } }], layout: { sliders: [{ pad: { t: 30 }, x: 0.05, len: 0.95, currentvalue: { xanchor: 'right', prefix: 'color: ', font: { color: '#888', size: 20 } }, transition: { duration: 500 }, tickcolor: 'white', font: { color: 'white' }, // By default, animate commands are bound to the most recently animated frame: steps: [{ label: 'red', method: 'animate', args: [ ['red'], { mode: 'immediate', frame: { redraw: false, duration: 500 }, transition: { duration: 500 } } ] }, { label: 'green', method: 'animate', args: [ ['green'], { mode: 'immediate', frame: { redraw: false, duration: 500 }, transition: { duration: 500 } } ] }, { label: 'blue', method: 'animate', args: [ ['blue'], { mode: 'immediate', frame: { redraw: false, duration: 500 }, transition: { duration: 500 } } ] }] }], updatemenus: [{ type: 'buttons', showactive: false, x: 0.05, y: 0, xanchor: 'right', yanchor: 'top', direction: 'left', pad: { t: 60, r: 20 }, buttons: [{ label: 'Play', method: 'animate', args: [null, { fromcurrent: true, frame: { redraw: false, duration: 1000 }, transition: { duration: 500 } }] }, { label: 'Pause', method: 'animate', args: [ [null], { mode: 'immediate', frame: { redraw: false, duration: 0 } } ] }] }] }, // The slider itself does not contain any notion of timing, so animating a slider // must be accomplished through a sequence of frames. Here we'll change the color // and the data of a single trace: frames: [{ name: 'red', data: [{ y: [2, 1, 3], 'line.color': 'red' }] }, { name: 'green', data: [{ y: [3, 2, 1], 'line.color': 'green' }] }, { name: 'blue', data: [{ y: [1, 3, 2], 'line.color': 'blue' }] }] }); html, body { margin: 0; padding: 0; } #graph { vertical-align: top; } <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <div id="graph"></div> </body>
How to hide/remove slider ticks/steps and their labels in plotly.js?
Is it possible to remove or hide the animation slider's step ticks and labels? I would like to remove the slider step markers (ticks) and their labels: 'Red', 'Green' and 'Blue' from underneath the slider. However still keeping the current frame/step label displayed. (Above slider on right side) Preferably would like to be able to do it with plotly's layout configuration but if it's possible to hide via CSS rules I'm all ears. The example below is taken directly from their sample page here: https://codepen.io/plotly/pen/NbKmmQ Plotly.plot('graph', { data: [{ x: [1, 2, 3], y: [2, 1, 3], line: { color: 'red', simplify: false, } }], layout: { sliders: [{ pad: {t: 30}, x: 0.05, len: 0.95, currentvalue: { xanchor: 'right', prefix: 'color: ', font: { color: '#888', size: 20 } }, transition: {duration: 500}, // By default, animate commands are bound to the most recently animated frame: steps: [{ label: 'red', method: 'animate', args: [['red'], { mode: 'immediate', frame: {redraw: false, duration: 500}, transition: {duration: 500} }] }, { label: 'green', method: 'animate', args: [['green'], { mode: 'immediate', frame: {redraw: false, duration: 500}, transition: {duration: 500} }] }, { label: 'blue', method: 'animate', args: [['blue'], { mode: 'immediate', frame: {redraw: false, duration: 500}, transition: {duration: 500} }] }] }], updatemenus: [{ type: 'buttons', showactive: false, x: 0.05, y: 0, xanchor: 'right', yanchor: 'top', direction: 'left', pad: {t: 60, r: 20}, buttons: [{ label: 'Play', method: 'animate', args: [null, { fromcurrent: true, frame: {redraw: false, duration: 1000}, transition: {duration: 500} }] }, { label: 'Pause', method: 'animate', args: [[null], { mode: 'immediate', frame: {redraw: false, duration: 0} }] }] }] }, // The slider itself does not contain any notion of timing, so animating a slider // must be accomplished through a sequence of frames. Here we'll change the color // and the data of a single trace: frames: [{ name: 'red', data: [{ y: [2, 1, 3], 'line.color': 'red' }] }, { name: 'green', data: [{ y: [3, 2, 1], 'line.color': 'green'}] }, { name: 'blue', data: [{ y: [1, 3, 2], 'line.color': 'blue'}] }] }); html, body { margin: 0; padding: 0; } #graph { vertical-align: top; } <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <div id="graph"></div> </body>
[ "Currently there is no property in the official docs, So please consider this alternate, where we set the tickcolor and font.color of the slider label and tick as white, which is same as the background.\nThe properties that do this, are shown below.\ntickcolor: 'white',\nfont: {\n color: 'white'\n}\n\n\n\nPlotly.plot('graph', {\r\n data: [{\r\n x: [1, 2, 3],\r\n y: [2, 1, 3],\r\n line: {\r\n color: 'red',\r\n simplify: false,\r\n }\r\n }],\r\n layout: {\r\n sliders: [{\r\n pad: {\r\n t: 30\r\n },\r\n x: 0.05,\r\n len: 0.95,\r\n currentvalue: {\r\n xanchor: 'right',\r\n prefix: 'color: ',\r\n font: {\r\n color: '#888',\r\n size: 20\r\n }\r\n },\r\n transition: {\r\n duration: 500\r\n },\r\n tickcolor: 'white',\r\n font: {\r\n color: 'white'\r\n },\r\n // By default, animate commands are bound to the most recently animated frame:\r\n steps: [{\r\n label: 'red',\r\n method: 'animate',\r\n args: [\r\n ['red'], {\r\n mode: 'immediate',\r\n frame: {\r\n redraw: false,\r\n duration: 500\r\n },\r\n transition: {\r\n duration: 500\r\n }\r\n }\r\n ]\r\n }, {\r\n label: 'green',\r\n method: 'animate',\r\n args: [\r\n ['green'], {\r\n mode: 'immediate',\r\n frame: {\r\n redraw: false,\r\n duration: 500\r\n },\r\n transition: {\r\n duration: 500\r\n }\r\n }\r\n ]\r\n }, {\r\n label: 'blue',\r\n method: 'animate',\r\n args: [\r\n ['blue'], {\r\n mode: 'immediate',\r\n frame: {\r\n redraw: false,\r\n duration: 500\r\n },\r\n transition: {\r\n duration: 500\r\n }\r\n }\r\n ]\r\n }]\r\n }],\r\n updatemenus: [{\r\n type: 'buttons',\r\n showactive: false,\r\n x: 0.05,\r\n y: 0,\r\n xanchor: 'right',\r\n yanchor: 'top',\r\n direction: 'left',\r\n pad: {\r\n t: 60,\r\n r: 20\r\n },\r\n buttons: [{\r\n label: 'Play',\r\n method: 'animate',\r\n args: [null, {\r\n fromcurrent: true,\r\n frame: {\r\n redraw: false,\r\n duration: 1000\r\n },\r\n transition: {\r\n duration: 500\r\n }\r\n }]\r\n }, {\r\n label: 'Pause',\r\n method: 'animate',\r\n args: [\r\n [null], {\r\n mode: 'immediate',\r\n frame: {\r\n redraw: false,\r\n duration: 0\r\n }\r\n }\r\n ]\r\n }]\r\n }]\r\n },\r\n // The slider itself does not contain any notion of timing, so animating a slider\r\n // must be accomplished through a sequence of frames. Here we'll change the color\r\n // and the data of a single trace:\r\n frames: [{\r\n name: 'red',\r\n data: [{\r\n y: [2, 1, 3],\r\n 'line.color': 'red'\r\n }]\r\n }, {\r\n name: 'green',\r\n data: [{\r\n y: [3, 2, 1],\r\n 'line.color': 'green'\r\n }]\r\n }, {\r\n name: 'blue',\r\n data: [{\r\n y: [1, 3, 2],\r\n 'line.color': 'blue'\r\n }]\r\n }]\r\n});\nhtml,\r\nbody {\r\n margin: 0;\r\n padding: 0;\r\n}\r\n\r\n#graph {\r\n vertical-align: top;\r\n}\n<head>\r\n <script src=\"https://cdn.plot.ly/plotly-latest.min.js\"></script>\r\n</head>\r\n\r\n<body>\r\n <div id=\"graph\"></div>\r\n</body>\n\n\n\n" ]
[ 3 ]
[ "To hide or remove the ticks and their labels on a slider in plotly.js, you can use the tickvals and ticktext properties of the slider object. These properties allow you to specify the values and labels for the ticks on the slider, and by setting them to empty arrays, you can hide the ticks and their labels.\nHere is an example of how you can hide the ticks and their labels on a slider in plotly.js:\nvar data = [\n {\n x: [1, 2, 3, 4],\n y: [1, 2, 3, 4],\n type: 'scatter'\n }\n];\n\nvar layout = {\n xaxis: {\n range: [0, 5]\n },\n yaxis: {\n range: [0, 5]\n },\n sliders: [\n {\n // Hide the ticks and their labels by setting\n // tickvals and ticktext to empty arrays\n tickvals: [],\n ticktext: [],\n steps: [\n {\n method: 'restyle',\n args: ['visible', [false, true, true]],\n label: 'A'\n },\n {\n method: 'restyle',\n args: ['visible', [true, false, true]],\n label: 'B'\n },\n {\n method: 'restyle',\n args: ['visible', [true, true, false]],\n label: 'C'\n }\n ]\n }\n ]\n};\n\nPlotly.newPlot('myDiv', data, layout);\n\n\nIn this example, the tickvals and ticktext properties of the slider are set to empty arrays, which hides the ticks and their labels on the slider. This will create a slider with no ticks or labels, and you can use the steps property to define the different steps for the slider as usual.\nYou can also use the visible property of the slider object to hide the entire slider and its labels, like this:\nvar data = [\n {\n x: [1, 2, 3, 4],\n y: [1, 2, 3, 4],\n type: 'scatter'\n }\n];\n\nvar layout = {\n xaxis: {\n range: [0, 5]\n },\n yaxis: {\n range: [0, 5]\n },\n sliders: [\n {\n // Hide the entire slider by setting the visible property to false\n visible: false,\n steps: [\n {\n method: 'restyle',\n args: ['visible', [false, true, true]],\n label: 'A'\n },\n {\n method: 'restyle',\n args: ['visible', [true, false, true]],\n label: 'B'\n },\n {\n method: 'restyle',\n args: ['visible', [true, true, false]],\n label: 'C'\n }\n ]\n }\n ]\n};\n\nPlotly.newPlot('myDiv', data, layout);\n\n\nIn this example, the visible property of the slider object is set to false, which hides the entire slider.\n" ]
[ -1 ]
[ "css", "javascript", "plotly", "plotly.js" ]
stackoverflow_0051835657_css_javascript_plotly_plotly.js.txt
Q: How to use a gRPC interceptor to attach/update logging MDC in a Spring-Boot app Problem I have a Spring-Boot application in which I am also starting a gRPC server/service. Both the servlet and gRPC code send requests to a common object to process the request. When the request comes in I want to update the logging to display a unique 'ID' so I can track the request through the system. On the Spring side I have setup a 'Filter' which updates the logging MDC to add some data to the log request (see this example). this works fine On the gRPC side I have created an 'ServerInterceptor' and added it to the service, while the interceptor gets called the code to update the MDC does not stick, so when a request comes through the gRPC service I do not get the ID printed in the log. I realize this has to do with the fact that I'm intercepting the call in one thread and it's being dispatched by gRPC in another, what I can't seem to figure out is how to either intercept the call in the thread doing the work or add the MDC information so it is properly propagated to the thread doing the work. What I've tried I have done a lot of searches and was quite surprised to not find this asked/answered, I can only assume my query skills are lacking :( I'm fairly new to gRPC and this is the first Interceptor I'm writing. I've tried adding the interceptor several different ways (via ServerInterceptors.intercept, BindableService instance.intercept). I've looked at LogNet's Spring Boot gRPC Starter, but I'm not sure this would solve the issue. Here is the code I have added in my interceptor class @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, final Metadata headers, final ServerCallHandler<ReqT, RespT> next) { try { final String mdcData = String.format("[requestID=%s]", UUID.randomUUID().toString()); MDC.put(MDC_DATA_KEY, mdcData); return next.startCall(call, headers); } finally { MDC.clear(); } } Expected Result When a request comes in via the RESTful API I see log output like this 2019-04-09 10:19:16.331 [requestID=380e28db-c8da-4e35-a097-4b8c90c006f4] INFO 87100 --- [nio-8080-exec-1] c.c.es.xxx: processing request step 1 2019-04-09 10:19:16.800 [requestID=380e28db-c8da-4e35-a097-4b8c90c006f4] INFO 87100 --- [nio-8080-exec-1] c.c.es.xxx: processing request step 2 2019-04-09 10:19:16.803 [requestID=380e28db-c8da-4e35-a097-4b8c90c006f4] INFO 87100 --- [nio-8080-exec-1] c.c.es.xxx: Processing request step 3 ... I'm hoping to get similar output when the request comes through the gRPC service. Thanks A: Since no one replied, I kept trying and came up with the following solution for my interceptCall function. I'm not 100% sure why this works, but it works for my use case. private class LogInterceptor implements ServerInterceptor { @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, final Metadata headers, final ServerCallHandler<ReqT, RespT> next) { Context context = Context.current(); final String requestId = UUID.randomUUID().toString(); return Contexts.interceptCall(context, call, headers, new ServerCallHandler<ReqT, RespT>() { @Override public ServerCall.Listener<ReqT> startCall(ServerCall<ReqT, RespT> call, Metadata headers) { return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(next.startCall(call, headers)) { /** * The actual service call happens during onHalfClose(). */ @Override public void onHalfClose() { try (final CloseableThreadContext.Instance ctc = CloseableThreadContext.put("requestID", UUID.randomUUID().toString())) { super.onHalfClose(); } } }; } }); } } In my application.properties I added the following (which I already had) logging.pattern.level=[%X] %-5level The '%X' tells the logging system to print all of the CloseableThreadContext key/values. Hopefully this may help someone else. A: MDC stores data in ThreadLocal variable and you are right about - "I realize this has to do with the fact that I'm intercepting the call in one thread and it's being dispatched by gRPC in another". Check @Eric Anderson answer about the right way to use ThradLocal in the post - https://stackoverflow.com/a/56842315/2478531 Here is a working example - public class GrpcMDCInterceptor implements ServerInterceptor { private static final String MDC_DATA_KEY = "Key"; @Override public <R, S> ServerCall.Listener<R> interceptCall( ServerCall<R, S> serverCall, Metadata metadata, ServerCallHandler<R, S> next ) { log.info("Setting user context, metadata {}", metadata); final String mdcData = String.format("[requestID=%s]", UUID.randomUUID().toString()); MDC.put(MDC_DATA_KEY, mdcData); try { return new WrappingListener<>(next.startCall(serverCall, metadata), mdcData); } finally { MDC.clear(); } } private static class WrappingListener<R> extends ForwardingServerCallListener.SimpleForwardingServerCallListener<R> { private final String mdcData; public WrappingListener(ServerCall.Listener<R> delegate, String mdcData) { super(delegate); this.mdcData = mdcData; } @Override public void onMessage(R message) { MDC.put(MDC_DATA_KEY, mdcData); try { super.onMessage(message); } finally { MDC.clear(); } } @Override public void onHalfClose() { MDC.put(MDC_DATA_KEY, mdcData); try { super.onHalfClose(); } finally { MDC.clear(); } } @Override public void onCancel() { MDC.put(MDC_DATA_KEY, mdcData); try { super.onCancel(); } finally { MDC.clear(); } } @Override public void onComplete() { MDC.put(MDC_DATA_KEY, mdcData); try { super.onComplete(); } finally { MDC.clear(); } } @Override public void onReady() { MDC.put(MDC_DATA_KEY, mdcData); try { super.onReady(); } finally { MDC.clear(); } } } } A: To update the logging MDC in a gRPC server interceptor, you can use the Context.current method to access the current Context and set the MDC values in that context. This will ensure that the MDC values are propagated to the thread that handles the gRPC request and are available when logging messages are printed. Here is an example of how you can use the Context.current method to update the MDC in a gRPC server interceptor: public class MyServerInterceptor implements ServerInterceptor { @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall( ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { // Access the current Context using the Context.current() method Context ctx = Context.current(); // Set the MDC values in the current Context ctx.put("request_id", UUID.randomUUID().toString()); ctx.put("user_id", headers.get(Metadata.Key.of("user_id", Metadata.ASCII_STRING_MARSHALLER))); // Dispatch the call using the next ServerCallHandler return next.startCall(call, headers); } } In the code above, we are implementing the ServerInterceptor interface and overriding the interceptCall method. In this method, we are using the Context.current method to access the current Context and set the MDC values in that context. This will ensure that the MDC values are propagated to the thread that handles the gRPC request.
How to use a gRPC interceptor to attach/update logging MDC in a Spring-Boot app
Problem I have a Spring-Boot application in which I am also starting a gRPC server/service. Both the servlet and gRPC code send requests to a common object to process the request. When the request comes in I want to update the logging to display a unique 'ID' so I can track the request through the system. On the Spring side I have setup a 'Filter' which updates the logging MDC to add some data to the log request (see this example). this works fine On the gRPC side I have created an 'ServerInterceptor' and added it to the service, while the interceptor gets called the code to update the MDC does not stick, so when a request comes through the gRPC service I do not get the ID printed in the log. I realize this has to do with the fact that I'm intercepting the call in one thread and it's being dispatched by gRPC in another, what I can't seem to figure out is how to either intercept the call in the thread doing the work or add the MDC information so it is properly propagated to the thread doing the work. What I've tried I have done a lot of searches and was quite surprised to not find this asked/answered, I can only assume my query skills are lacking :( I'm fairly new to gRPC and this is the first Interceptor I'm writing. I've tried adding the interceptor several different ways (via ServerInterceptors.intercept, BindableService instance.intercept). I've looked at LogNet's Spring Boot gRPC Starter, but I'm not sure this would solve the issue. Here is the code I have added in my interceptor class @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, final Metadata headers, final ServerCallHandler<ReqT, RespT> next) { try { final String mdcData = String.format("[requestID=%s]", UUID.randomUUID().toString()); MDC.put(MDC_DATA_KEY, mdcData); return next.startCall(call, headers); } finally { MDC.clear(); } } Expected Result When a request comes in via the RESTful API I see log output like this 2019-04-09 10:19:16.331 [requestID=380e28db-c8da-4e35-a097-4b8c90c006f4] INFO 87100 --- [nio-8080-exec-1] c.c.es.xxx: processing request step 1 2019-04-09 10:19:16.800 [requestID=380e28db-c8da-4e35-a097-4b8c90c006f4] INFO 87100 --- [nio-8080-exec-1] c.c.es.xxx: processing request step 2 2019-04-09 10:19:16.803 [requestID=380e28db-c8da-4e35-a097-4b8c90c006f4] INFO 87100 --- [nio-8080-exec-1] c.c.es.xxx: Processing request step 3 ... I'm hoping to get similar output when the request comes through the gRPC service. Thanks
[ "Since no one replied, I kept trying and came up with the following solution for my interceptCall function. I'm not 100% sure why this works, but it works for my use case.\n private class LogInterceptor implements ServerInterceptor {\n @Override\n public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,\n final Metadata headers,\n final ServerCallHandler<ReqT, RespT> next) {\n Context context = Context.current();\n final String requestId = UUID.randomUUID().toString();\n return Contexts.interceptCall(context, call, headers, new ServerCallHandler<ReqT, RespT>() {\n @Override\n public ServerCall.Listener<ReqT> startCall(ServerCall<ReqT, RespT> call, Metadata headers) {\n\n return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(next.startCall(call, headers)) {\n /**\n * The actual service call happens during onHalfClose().\n */\n @Override\n public void onHalfClose() {\n try (final CloseableThreadContext.Instance ctc = CloseableThreadContext.put(\"requestID\",\n UUID.randomUUID().toString())) {\n super.onHalfClose();\n }\n }\n };\n }\n });\n }\n }\n\nIn my application.properties I added the following (which I already had)\n\nlogging.pattern.level=[%X] %-5level\n\nThe '%X' tells the logging system to print all of the CloseableThreadContext key/values.\nHopefully this may help someone else.\n", "MDC stores data in ThreadLocal variable and you are right about - \"I realize this has to do with the fact that I'm intercepting the call in one thread and it's being dispatched by gRPC in another\". Check @Eric Anderson answer about the right way to use ThradLocal in the post -\nhttps://stackoverflow.com/a/56842315/2478531\nHere is a working example -\npublic class GrpcMDCInterceptor implements ServerInterceptor {\n private static final String MDC_DATA_KEY = \"Key\";\n\n @Override\n public <R, S> ServerCall.Listener<R> interceptCall(\n ServerCall<R, S> serverCall,\n Metadata metadata,\n ServerCallHandler<R, S> next\n ) {\n\n log.info(\"Setting user context, metadata {}\", metadata);\n\n final String mdcData = String.format(\"[requestID=%s]\", UUID.randomUUID().toString());\n\n MDC.put(MDC_DATA_KEY, mdcData);\n\n try {\n return new WrappingListener<>(next.startCall(serverCall, metadata), mdcData);\n } finally {\n MDC.clear();\n }\n }\n\n private static class WrappingListener<R>\n extends ForwardingServerCallListener.SimpleForwardingServerCallListener<R> {\n private final String mdcData;\n\n public WrappingListener(ServerCall.Listener<R> delegate, String mdcData) {\n super(delegate);\n this.mdcData = mdcData;\n }\n\n @Override\n public void onMessage(R message) {\n MDC.put(MDC_DATA_KEY, mdcData);\n try {\n super.onMessage(message);\n } finally {\n MDC.clear();\n }\n }\n\n @Override\n public void onHalfClose() {\n MDC.put(MDC_DATA_KEY, mdcData);\n try {\n super.onHalfClose();\n } finally {\n MDC.clear();\n }\n }\n\n @Override\n public void onCancel() {\n MDC.put(MDC_DATA_KEY, mdcData);\n try {\n super.onCancel();\n } finally {\n MDC.clear();\n }\n }\n\n @Override\n public void onComplete() {\n MDC.put(MDC_DATA_KEY, mdcData);\n try {\n super.onComplete();\n } finally {\n MDC.clear();\n }\n }\n\n @Override\n public void onReady() {\n MDC.put(MDC_DATA_KEY, mdcData);\n try {\n super.onReady();\n } finally {\n MDC.clear();\n }\n }\n }\n}\n\n", "To update the logging MDC in a gRPC server interceptor, you can use the Context.current method to access the current Context and set the MDC values in that context. This will ensure that the MDC values are propagated to the thread that handles the gRPC request and are available when logging messages are printed.\nHere is an example of how you can use the Context.current method to update the MDC in a gRPC server interceptor:\npublic class MyServerInterceptor implements ServerInterceptor {\n @Override\n public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(\n ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {\n\n // Access the current Context using the Context.current() method\n Context ctx = Context.current();\n\n // Set the MDC values in the current Context\n ctx.put(\"request_id\", UUID.randomUUID().toString());\n ctx.put(\"user_id\", headers.get(Metadata.Key.of(\"user_id\", Metadata.ASCII_STRING_MARSHALLER)));\n\n // Dispatch the call using the next ServerCallHandler\n return next.startCall(call, headers);\n }\n}\n\nIn the code above, we are implementing the ServerInterceptor interface and overriding the interceptCall method. In this method, we are using the Context.current method to access the current Context and set the MDC values in that context. This will ensure that the MDC values are propagated to the thread that handles the gRPC request.\n" ]
[ 8, 0, 0 ]
[]
[]
[ "grpc", "grpc_java", "mdc", "slf4j", "spring_boot" ]
stackoverflow_0055595361_grpc_grpc_java_mdc_slf4j_spring_boot.txt
Q: Pass multiple parameters to call stored procedure with LINQ I want to call a stored procedure in my Linq code. When I use only one parameter, it works fine, but when I want to use multiple parameters, it shows an error. Here is what I have done - this work fine: SqlParameter param1 = new SqlParameter("@Value1", val); var abc = db.tablename.SqlQuery("SP_Name @Value1", param1).ToList(); Now I want to add second parameter SqlParameter param2 = new SqlParameter("@Value2", val2); var abc = db.tablename.SqlQuery("SP_Name @Value1,@Value2", param1, param2 ).ToList(); it returns an error: An error occurred while reading from the store provider's data reader. See the inner exception for details. A: Hope this sample code helps you!! var param1 = new SqlParameter(); param1.ParameterName = "@Value1"; param1.SqlDbType = SqlDbType.Int; param1.SqlValue = val1; var param2 = new SqlParameter(); param2.ParameterName = "@Value2"; param2.SqlDbType = SqlDbType.NVarChar; param2.SqlValue = val2; var result = db.tablename.SqlQuery("SP_Name @Value1,@Value2", param1, param2 ).ToList(); A: This is how I used the Store procedure with 2 parameters you can use as per your need. adxGYMDataContext db = new adxGYMDataContext(); var mysp = db.sp_memb_info_get_del(int.Parse(txt_id_memb.Text), true).Select(x=>x).ToList(); foreach (var item in mysp) { cmb_duration_memb.Text = item.memb_dur.ToString(); txt_tel_memb.Text = item.memb_tel.ToString(); }
Pass multiple parameters to call stored procedure with LINQ
I want to call a stored procedure in my Linq code. When I use only one parameter, it works fine, but when I want to use multiple parameters, it shows an error. Here is what I have done - this work fine: SqlParameter param1 = new SqlParameter("@Value1", val); var abc = db.tablename.SqlQuery("SP_Name @Value1", param1).ToList(); Now I want to add second parameter SqlParameter param2 = new SqlParameter("@Value2", val2); var abc = db.tablename.SqlQuery("SP_Name @Value1,@Value2", param1, param2 ).ToList(); it returns an error: An error occurred while reading from the store provider's data reader. See the inner exception for details.
[ "Hope this sample code helps you!!\nvar param1 = new SqlParameter(); \nparam1.ParameterName = \"@Value1\"; \nparam1.SqlDbType = SqlDbType.Int; \nparam1.SqlValue = val1;\n\nvar param2 = new SqlParameter(); \nparam2.ParameterName = \"@Value2\"; \nparam2.SqlDbType = SqlDbType.NVarChar; \nparam2.SqlValue = val2;\n\nvar result = db.tablename.SqlQuery(\"SP_Name @Value1,@Value2\", param1, param2 ).ToList();\n\n", "This is how I used the Store procedure with 2 parameters you can use as per your need.\nadxGYMDataContext db = new adxGYMDataContext();\nvar mysp = db.sp_memb_info_get_del(int.Parse(txt_id_memb.Text), true).Select(x=>x).ToList();\n\nforeach (var item in mysp)\n{\ncmb_duration_memb.Text = item.memb_dur.ToString();\ntxt_tel_memb.Text = item.memb_tel.ToString();\n}\n\n" ]
[ 3, 0 ]
[]
[]
[ "c#", "linq", "stored_procedures" ]
stackoverflow_0039547516_c#_linq_stored_procedures.txt
Q: Use inline commands for tclsh Is there such a thing like inline command for tclsh? Like : tclsh -e "set a 7 ; puts $a" Of course I tried the above and it does not work. But you get the idea? Thanks, Gert A: With Expect, you can achieve this. expect -c 'set a 10; puts $a' The -c flag provides a way of executing commands specified on the command line rather than in a script. Notice that the entire argument to -c is quoted using single quotes. This tells the shell not to perform any variable expansion. The -c flag can also be used to execute commands before a script takes control. For example, you can set the variable debug to 1 by invoking Expect from the shell as: expect -c 'set debug 1' myscript.exp Inside the script, you can check the value of this variable: if [info exists debug] { puts "debugging mode: on" else { set debug 0 } A: I used just simple echo command with pipe to TCL interpreter. echo 'set a "Hello TCL!" ; puts $a ; exit' | tclsh A: Standard tclsh doesn't. You can make a small script to do it though: set argv [lassign $argv theUserScript] eval $theUserScript Call that docmd.tcl and run it like this: tclsh docmd.tcl 'puts "Hi from Tcl"; after 1000; puts "Bye from Tcl"' It even handles arguments (and stdin/stdout) correctly: tclsh docmd.tcl 'foreach v $argv {puts [incr i]:$v}' abc def "ghi jkl" m123 You'll probably want to use single quotes around any script you pass in. A: If you use a shell like Bash or Zsh, you can use input redirection, for example (using a "here-string"): tclsh <<<'set a 7 ; puts $a' Note the usage of single quotes do avoid the shell expanding $a.
Use inline commands for tclsh
Is there such a thing like inline command for tclsh? Like : tclsh -e "set a 7 ; puts $a" Of course I tried the above and it does not work. But you get the idea? Thanks, Gert
[ "With Expect, you can achieve this.\nexpect -c 'set a 10; puts $a'\n\nThe -c flag provides a way of executing commands specified on the command line\nrather than in a script. Notice that the entire argument to -c is quoted using\nsingle quotes. This tells the shell not to perform any variable expansion.\nThe -c flag can also be used to execute commands before a script takes control. For example, you can set the variable debug to 1 by invoking Expect from the shell as:\nexpect -c 'set debug 1' myscript.exp\n\nInside the script, you can check the value of this variable:\nif [info exists debug] {\n puts \"debugging mode: on\"\nelse {\n set debug 0\n}\n\n", "I used just simple echo command with pipe to TCL interpreter.\necho 'set a \"Hello TCL!\" ; puts $a ; exit' | tclsh\n\n", "Standard tclsh doesn't. You can make a small script to do it though:\nset argv [lassign $argv theUserScript]\neval $theUserScript\n\nCall that docmd.tcl and run it like this:\ntclsh docmd.tcl 'puts \"Hi from Tcl\"; after 1000; puts \"Bye from Tcl\"'\n\nIt even handles arguments (and stdin/stdout) correctly:\ntclsh docmd.tcl 'foreach v $argv {puts [incr i]:$v}' abc def \"ghi jkl\" m123\n\nYou'll probably want to use single quotes around any script you pass in.\n", "If you use a shell like Bash or Zsh, you can use input redirection, for example (using a \"here-string\"):\ntclsh <<<'set a 7 ; puts $a'\n\nNote the usage of single quotes do avoid the shell expanding $a.\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "tcl" ]
stackoverflow_0044057339_tcl.txt
Q: CS1513 error but I don't have a missing "}" namespace HelloWorld { class HelloThere { static void Main(string[] args) { Game.play(); } } class Game { public static void play() { int toGuess = randomNum(); while (true) { int playerGuess = takePlayerGuess(); bool won = hasWon(toGuess,playerGuess); if (won) { Console.WriteLine("You Win!"); } else { bool hOrL = higherOrLower(toGuess,playerGuess); if (hOrL == true) { Console.WriteLine("Your value is too low! Try Again!"); } else { Console.WriteLine("Your value is too high! Try Again!"); } } } } // random function, take input function, return if win, stop if win public static int randomNum() { Random rnd = new Random(); int num = rnd.Next(0,100); return num; } public static int takePlayerGuess() { Console.WriteLine("Your Guess from 1 to 100 (not 0)>> "); string input = "-1"; input = Console.ReadLine(); if (!(input == null)) { int e = Int32.Parse(input); // convert string to int return e; } else { return 0; } } public static bool hasWon(int toGuess,int playerGuess) { if (toGuess == playerGuess) { return true; } return false; } public static bool higherOrLower(int toGuess, int playerGuess) { if (toGuess > playerGuess) { return true; } else if (toGuess < playerGuess) { return false; } return true; } } } My first little C# project to learn a bit of C# for school. Never used C# before so I have no idea what the problem could be. I run the program and get this error : TESTS\tempCodeRunnerFile.cs(1,17): error CS1513: } expected [TESTS\TESTS.csproj] I have no idea what is going on, can anyone help? I've looked it up, used stuff on here, my friend ran it and got no errors (after running a code cleanup program) and nothing worked.
CS1513 error but I don't have a missing "}"
namespace HelloWorld { class HelloThere { static void Main(string[] args) { Game.play(); } } class Game { public static void play() { int toGuess = randomNum(); while (true) { int playerGuess = takePlayerGuess(); bool won = hasWon(toGuess,playerGuess); if (won) { Console.WriteLine("You Win!"); } else { bool hOrL = higherOrLower(toGuess,playerGuess); if (hOrL == true) { Console.WriteLine("Your value is too low! Try Again!"); } else { Console.WriteLine("Your value is too high! Try Again!"); } } } } // random function, take input function, return if win, stop if win public static int randomNum() { Random rnd = new Random(); int num = rnd.Next(0,100); return num; } public static int takePlayerGuess() { Console.WriteLine("Your Guess from 1 to 100 (not 0)>> "); string input = "-1"; input = Console.ReadLine(); if (!(input == null)) { int e = Int32.Parse(input); // convert string to int return e; } else { return 0; } } public static bool hasWon(int toGuess,int playerGuess) { if (toGuess == playerGuess) { return true; } return false; } public static bool higherOrLower(int toGuess, int playerGuess) { if (toGuess > playerGuess) { return true; } else if (toGuess < playerGuess) { return false; } return true; } } } My first little C# project to learn a bit of C# for school. Never used C# before so I have no idea what the problem could be. I run the program and get this error : TESTS\tempCodeRunnerFile.cs(1,17): error CS1513: } expected [TESTS\TESTS.csproj] I have no idea what is going on, can anyone help? I've looked it up, used stuff on here, my friend ran it and got no errors (after running a code cleanup program) and nothing worked.
[]
[]
[ "Your code looks and works OK (no way to exit...mayby if input equals 0?). Use a good editor like Visual Studio Code (free) so any error can be caugth even before compiling. It runs on Linux and Windows.\n" ]
[ -2 ]
[ "c#" ]
stackoverflow_0074659991_c#.txt
Q: Changing HTML attribute with URL I'm not entirely sure if this is possible and have been unable to find any info on this matter, which isn't giving me much hope, but maybe I can find an answer this way. For some context, my question concerns this page. For reference: I'll be referring to "tabs" in my question, this is about the tabs towards the bottom of that page, not browser tabs. I'm working on a revamp of the website for the company I work for as a Communications employee. As part of this revamp, we want to place an infographic on the website detailing our work process, and allow users to click it to get information about the step of the infographic they just clicked on. We use Wordpress and a free version of Elementor, which limits my ability to make any changes outside of the front-end that Wordpress/Elementor gives me. I'm currently using Adobe Illustrator to create an image map of the infographic using Illustrator's Attributes menu, and have been able to use hash signs to make the page jump down to the text about the step by using the div id of the tab in question. However, in order to make this work, I also need to be able to actually change the open tab on the page. I've figured out that this relies on two HTML attributes needing to be changed: The class attribute of both the tab that needs to close and the tab that needs to be opened needs to be adjusted. A closed tab uses elementor-tab-title elementor-tab-desktop-title, an open tab uses elementor-tab-title elementor-tab-desktop-title elementor-active. The aria-expanded attribute of the tab that needs to close needs to be changed to false, while the tab that needs to be opened requries the attribute to be set to true. Is there any way to pull this off using the URL? If not, what other methods can I use, given the limitations of the system I'm working with? I've searched across the internet for solutions, taken a look at Elementor-focused tutorials, and searched Stack Exchange. While I have found solutions that involve JS/JQuery scripting, this is unfortunately not possible due to the limitations of the software I'm working with. If there's something that involves a URL, I can use that through image mapping, which should allow me to work around these limitations. A: You question is not entirely clear on what you expect the URL to look like. Or how you expect to change the URL. But you can surely change the elements on the front-end page based on the URL. For example like this: // get and parse url parameters let urlParams = new URLSearchParams(window.location.search); // extract the ones you are interested in let currentTabID = urlParams.get('currentTab'); let closedTabID = urlParams.get('closedTab'); // since you don't specify what sets the URL I suppose it will be blank by default // and only be filled on page visit. So lets set the default currentTabID = currentTabID || 'home'; // get the tab HTML elements // Note: the usage of $ prefix on elements is just a naming habit from jQuery and not mandatory let $closedTab = document.getElementById(closedTabID); let $currentTab = document.getElementById(currentTabID); // change their classes or whatver else you need to if($closedTab) $closedTab.addClass('tab-closing'); if($currentTab) $currentTab.addClass('tab-selected'); This would work for an URL matching: https://example.com?currentTab=about&closedTab=contacts You will likely want to set the URL parameters on each tab link. To change the URL when the user clicks the tab link. <a class='tab'href="?currentTab=about">About us</a> This will however not include the closed tab in the URL, you need to do that through Javascript: //continuing from the above script where we captured the urlParams document.getElementsByClassName('tab').forEach(($element)=>{ $element.href = $element.href + '&closedTab=' + currentTab })
Changing HTML attribute with URL
I'm not entirely sure if this is possible and have been unable to find any info on this matter, which isn't giving me much hope, but maybe I can find an answer this way. For some context, my question concerns this page. For reference: I'll be referring to "tabs" in my question, this is about the tabs towards the bottom of that page, not browser tabs. I'm working on a revamp of the website for the company I work for as a Communications employee. As part of this revamp, we want to place an infographic on the website detailing our work process, and allow users to click it to get information about the step of the infographic they just clicked on. We use Wordpress and a free version of Elementor, which limits my ability to make any changes outside of the front-end that Wordpress/Elementor gives me. I'm currently using Adobe Illustrator to create an image map of the infographic using Illustrator's Attributes menu, and have been able to use hash signs to make the page jump down to the text about the step by using the div id of the tab in question. However, in order to make this work, I also need to be able to actually change the open tab on the page. I've figured out that this relies on two HTML attributes needing to be changed: The class attribute of both the tab that needs to close and the tab that needs to be opened needs to be adjusted. A closed tab uses elementor-tab-title elementor-tab-desktop-title, an open tab uses elementor-tab-title elementor-tab-desktop-title elementor-active. The aria-expanded attribute of the tab that needs to close needs to be changed to false, while the tab that needs to be opened requries the attribute to be set to true. Is there any way to pull this off using the URL? If not, what other methods can I use, given the limitations of the system I'm working with? I've searched across the internet for solutions, taken a look at Elementor-focused tutorials, and searched Stack Exchange. While I have found solutions that involve JS/JQuery scripting, this is unfortunately not possible due to the limitations of the software I'm working with. If there's something that involves a URL, I can use that through image mapping, which should allow me to work around these limitations.
[ "You question is not entirely clear on what you expect the URL to look like.\nOr how you expect to change the URL.\nBut you can surely change the elements on the front-end page based on the URL.\nFor example like this:\n// get and parse url parameters\nlet urlParams = new URLSearchParams(window.location.search);\n\n// extract the ones you are interested in\nlet currentTabID = urlParams.get('currentTab');\nlet closedTabID = urlParams.get('closedTab');\n\n// since you don't specify what sets the URL I suppose it will be blank by default \n// and only be filled on page visit. So lets set the default\ncurrentTabID = currentTabID || 'home';\n\n// get the tab HTML elements\n// Note: the usage of $ prefix on elements is just a naming habit from jQuery and not mandatory\nlet $closedTab = document.getElementById(closedTabID);\nlet $currentTab = document.getElementById(currentTabID);\n\n// change their classes or whatver else you need to\nif($closedTab) $closedTab.addClass('tab-closing');\nif($currentTab) $currentTab.addClass('tab-selected');\n\n\nThis would work for an URL matching:\nhttps://example.com?currentTab=about&closedTab=contacts\nYou will likely want to set the URL parameters on each tab link.\nTo change the URL when the user clicks the tab link.\n<a class='tab'href=\"?currentTab=about\">About us</a>\n\nThis will however not include the closed tab in the URL, you need to do that through Javascript:\n //continuing from the above script where we captured the urlParams\n\ndocument.getElementsByClassName('tab').forEach(($element)=>{\n $element.href = $element.href + '&closedTab=' + currentTab\n})\n\n" ]
[ 0 ]
[]
[]
[ "attributes", "elementor", "html", "javascript", "wordpress" ]
stackoverflow_0074561163_attributes_elementor_html_javascript_wordpress.txt
Q: I'm not seeing "Publish" button in Amazon Lex Bot and all the tutorials' screenshots I'm finding don't align with my AWS Consoles Hello Stackoverflow Friends: Context: My goal is to use Amazon Lex Bot to communicate via an SMS text channel using an Amazon Pinpoint phone number associated with my account. Users will send utterances via their native text client, i.e. the Messages application on their iPhone. It would reply to them in the same channel. I did also want to include a 'middleware' layer of having a Lambda functions extract certain user utterances and or the user's phone number and store that in a Dynamo DB. Problem(s): I found this tutorial and I am blocked [Blockers listed below]. There seems to be a disconnect between what I'm seeing in my AWS console and this tutorial (and documentation on AWS) as well as many video tutorials I'm seeing on YouTube - or I'm maybe doing something wrong? Version 2? I did observe that my AWS Lex console that the URL that includes a "V2" in the url ("https://console.aws.amazon.com/lexv2/home?region=us-east-1#bots") I am not observing that "V2" in various instructors' videos that I've watched. Which leads me to wonder if perhaps V2 is a new version of Lex and the documentation hasn't been released? Here is a link to a video done by one of the author's of the above linked tutorial and as you can see from the screenshot in his video it isn't /lexv2/ it is just /lex/. Screenshot from instructional video: Screenshot from my AWS console: Blockers / Questions: 1. [Tutorial says]1 (in Step 1; Request a long code for your country. When I do that - there is no focus / SMS capability is grayed out indicating [to me anyway] that the outcome / goal of this tutorial is not possible using a long code? Question: As a workaround I selected a toll free number which had SMS capabilities. Is that permissible? 2. In Step 2; the tutorial says, Use the default IAM role - there is no default, I selected. Question: Is that a good path forward? 3. Also in Step 2; [the tutorial says]1, When the bot finishes building, choose Publish. For Create an alias, enter Latest. Choose Publish. - I see no "Publish" button and this is highly confusing as in many, many, many tutorials I've watched on YouTube the instructors have that button visible. Here is my screenshot of what I see [no "Publish" button]: Here is Amazon document tutorial with a "Publish" button. And here is a various tutorial I see online with a "Publish" button. Question: Did I miss a step (I did build it and test it and those controls to do that were on the bottom of the UI not on the top as all the tutorials I've found are. Is it possibly V2 of this Lex bot that has changed? Assuming I can get past these blockers - in Step 3 of the tutorial it says, Under Execution role, choose View the LexPinpointIntegrationDemoLambda role. Question: Not to be really dense but I have swirl on how to do that / where to do that. Can I get some direction / steps on exact steps to do that please? A: Yes, the problem is that the tutorial, which i also followed, is based on the Version 1 of the service and the console. On the lower left corner there is a button that says "Switch to V1 console" After this you will get the same interface as the tutorial and you can continue with it. A: AWS does not have the Publish Button in the Lex V2. You will have to follow the following steps to publish your Bot in AWS Lex V2: 1. Build the bot 2. Create the bot version 3. Create an Alias 3. Associate that version to a required alias so once you create the bot version, it is considered published.
I'm not seeing "Publish" button in Amazon Lex Bot and all the tutorials' screenshots I'm finding don't align with my AWS Consoles
Hello Stackoverflow Friends: Context: My goal is to use Amazon Lex Bot to communicate via an SMS text channel using an Amazon Pinpoint phone number associated with my account. Users will send utterances via their native text client, i.e. the Messages application on their iPhone. It would reply to them in the same channel. I did also want to include a 'middleware' layer of having a Lambda functions extract certain user utterances and or the user's phone number and store that in a Dynamo DB. Problem(s): I found this tutorial and I am blocked [Blockers listed below]. There seems to be a disconnect between what I'm seeing in my AWS console and this tutorial (and documentation on AWS) as well as many video tutorials I'm seeing on YouTube - or I'm maybe doing something wrong? Version 2? I did observe that my AWS Lex console that the URL that includes a "V2" in the url ("https://console.aws.amazon.com/lexv2/home?region=us-east-1#bots") I am not observing that "V2" in various instructors' videos that I've watched. Which leads me to wonder if perhaps V2 is a new version of Lex and the documentation hasn't been released? Here is a link to a video done by one of the author's of the above linked tutorial and as you can see from the screenshot in his video it isn't /lexv2/ it is just /lex/. Screenshot from instructional video: Screenshot from my AWS console: Blockers / Questions: 1. [Tutorial says]1 (in Step 1; Request a long code for your country. When I do that - there is no focus / SMS capability is grayed out indicating [to me anyway] that the outcome / goal of this tutorial is not possible using a long code? Question: As a workaround I selected a toll free number which had SMS capabilities. Is that permissible? 2. In Step 2; the tutorial says, Use the default IAM role - there is no default, I selected. Question: Is that a good path forward? 3. Also in Step 2; [the tutorial says]1, When the bot finishes building, choose Publish. For Create an alias, enter Latest. Choose Publish. - I see no "Publish" button and this is highly confusing as in many, many, many tutorials I've watched on YouTube the instructors have that button visible. Here is my screenshot of what I see [no "Publish" button]: Here is Amazon document tutorial with a "Publish" button. And here is a various tutorial I see online with a "Publish" button. Question: Did I miss a step (I did build it and test it and those controls to do that were on the bottom of the UI not on the top as all the tutorials I've found are. Is it possibly V2 of this Lex bot that has changed? Assuming I can get past these blockers - in Step 3 of the tutorial it says, Under Execution role, choose View the LexPinpointIntegrationDemoLambda role. Question: Not to be really dense but I have swirl on how to do that / where to do that. Can I get some direction / steps on exact steps to do that please?
[ "Yes, the problem is that the tutorial, which i also followed, is based on the Version 1 of the service and the console. On the lower left corner there is a button that says \"Switch to V1 console\"\nAfter this you will get the same interface as the tutorial and you can continue with it.\n", "AWS does not have the Publish Button in the Lex V2. You will have to follow the following steps to publish your Bot in AWS Lex V2:\n1. Build the bot\n\n2. Create the bot version\n\n\n3. Create an Alias\n\n3. Associate that version to a required alias\n\nso once you create the bot version, it is considered published.\n" ]
[ 2, 0 ]
[]
[]
[ "amazon_lex", "amazon_sns", "amazon_web_services", "aws_pinpoint" ]
stackoverflow_0068179341_amazon_lex_amazon_sns_amazon_web_services_aws_pinpoint.txt
Q: Find all unique occurrences of first 3 char, count number of occurrences and write output to a file I have a text file with over 250 million lines. Each line has a 3 digit area code followed by a comma and a 7 digit number. Sample Input File: 201,2220000 201,5551212 310,5552481 376,1239876 443,0002222 572,8880099 ... I would like to generate an output file which lists each unique area code and the number of occurrences of that area code (only looking at the first 3 characters of each line). Example output (area code, count): 201, 44556 202, 34529 ... I am working in a Windows 10 environment. After considerable research, I was able to use the Switch function with regex in PowerShell to achieve something very close. The problem with this solution is that I need to know which area codes I am looking for (and I don't know all the area codes listed in this file). I would like to modify the solution such that it finds all unique area codes and then run the code. Here's what I have tried: Say, I want to search for the following four area codes: 201,202,203,205 My text file is datafile.txt $count1 = 0 $count2 = 0 $count3 = 0 $count4 = 0 switch -File C:\datafile.txt -Exact -Regex { '201\S{8}' { ++$count1 } } Write-Output "Area Code 201: $($count1)" | Format-Table | Out-File "C:\summary.txt" -append switch -File C:\datafile.txt -Exact -Regex { '202\S{8}' { ++$count2 } } Write-Output "Area Code 202: $($count2)" | Format-Table | Out-File "C:\summary.txt" -append switch -File C:\datafile.txt -Exact -Regex { '203\S{8}' { ++$count3 } } Write-Output "Area Code 203: $($count3)" | Format-Table | Out-File "C:\summary.txt" -append switch -File C:\datafile.txt -Exact -Regex { '205\S{8}' { ++$count4 } } Write-Output "Area Code 204: $($count4)" | Format-Table | Out-File "C:\summary.txt" -append This code generates the file summary.txt and appends the counts to the area codes. However, I think this is inefficient as: I need to know all the area codes that are in this datafile. I have to add 3 lines of code for every additional area code. Would appreciate any help improving this code or for using an alternate solution (I found a thread on Stackoverflow that uses grep https://stackoverflow.com/questions/61229157/using-regex-in-grep-for-windows-command-line, but it has the same limitation - you need to know what string you are searching for. A: Assuming I understood correctly, there is no regex needed here, just .SubString(0, 3) to get the first 3 characters from each line and a hashtable to ensure unique codes and efficiency. Indeed, switch -File is awesome for this task and should be used to read your file. Otherwise, for simplicity and also keeping it efficient, you could use File.ReadLines. $map = @{ } switch -File path\to\source\file.txt { Default { $map[$_.Substring(0, 3)] += 1 } } $map.GetEnumerator() | ForEach-Object { [pscustomobject]@{ Code = $_.Key Count = $_.Value } } | Export-Csv path\to\resultOfUniqueCodes.csv -NoTypeInformation A: Just my two cents for a streaming approach - trying to avoid everything that's comparatively slow, like ForEach-Object, pscustomobject and Export-Csv. # Create a scriptblock to be able to pipe output of foreach loop & { foreach( $line in [IO.File]::ReadLines( 'input.txt' ) ) { $line.Substring( 0, 3 ) } } | Group-Object -NoElement | & { begin { 'Code,Count' } process { '{0},{1}' -f $_.Name, $_.Count } } | Set-Content output.csv Remarks: foreach( $line in [IO.File]::ReadLines( 'input.txt' ) ) processes the input file lazily, so it's not read into memory as a whole. This works because ReadLines returns an iterator (not a collection) which foreach understands. As mentioned by others ReadLines is considered one of the fastest ways for line-by-line processing of text files, while still providing ease-of-use (compared to using .NET streams for instance). Group-Object -NoElement just counts the number of occurences of unique input elements, propably using an internal hashtable, so it should be as fast as a manually created hashtable (not measured though - it would be really interesting). Piping from Group-Object to a script block is much faster than ForEach-Object with a script block, see GitHub issue. Though in your case it doesn't matter much, the bottleneck will be reading and processing the input file. As the kind of input data is known, we can avoid Export-Csv's complexities (like escaping rules) and create the CSV directly using simple string operations and Set-Content. Again, won't really make a difference here, but might still be good to know for other cases that are more output-heavy. A: Try following : $input = @" area,number 201,44556 202,34529 201,44556 202,34529 201,44556 202,34529 201,44556 202,34529 "@ $table = $input | ConvertFrom-Csv $table | Format-Table $groups = $table | Group-Object {$_.area} $outputTable = [System.Collections.ArrayList]::new() foreach($group in $groups) { $group | Format-Table $newRow = New-Object -TypeName psobject $newRow | Add-Member -NotePropertyName area -NotePropertyValue $group.Name $newRow | Add-Member -NotePropertyName count -NotePropertyValue $group.Count $outputTable.Add($newRow) | Out-Null } $outputTable | Format-Table
Find all unique occurrences of first 3 char, count number of occurrences and write output to a file
I have a text file with over 250 million lines. Each line has a 3 digit area code followed by a comma and a 7 digit number. Sample Input File: 201,2220000 201,5551212 310,5552481 376,1239876 443,0002222 572,8880099 ... I would like to generate an output file which lists each unique area code and the number of occurrences of that area code (only looking at the first 3 characters of each line). Example output (area code, count): 201, 44556 202, 34529 ... I am working in a Windows 10 environment. After considerable research, I was able to use the Switch function with regex in PowerShell to achieve something very close. The problem with this solution is that I need to know which area codes I am looking for (and I don't know all the area codes listed in this file). I would like to modify the solution such that it finds all unique area codes and then run the code. Here's what I have tried: Say, I want to search for the following four area codes: 201,202,203,205 My text file is datafile.txt $count1 = 0 $count2 = 0 $count3 = 0 $count4 = 0 switch -File C:\datafile.txt -Exact -Regex { '201\S{8}' { ++$count1 } } Write-Output "Area Code 201: $($count1)" | Format-Table | Out-File "C:\summary.txt" -append switch -File C:\datafile.txt -Exact -Regex { '202\S{8}' { ++$count2 } } Write-Output "Area Code 202: $($count2)" | Format-Table | Out-File "C:\summary.txt" -append switch -File C:\datafile.txt -Exact -Regex { '203\S{8}' { ++$count3 } } Write-Output "Area Code 203: $($count3)" | Format-Table | Out-File "C:\summary.txt" -append switch -File C:\datafile.txt -Exact -Regex { '205\S{8}' { ++$count4 } } Write-Output "Area Code 204: $($count4)" | Format-Table | Out-File "C:\summary.txt" -append This code generates the file summary.txt and appends the counts to the area codes. However, I think this is inefficient as: I need to know all the area codes that are in this datafile. I have to add 3 lines of code for every additional area code. Would appreciate any help improving this code or for using an alternate solution (I found a thread on Stackoverflow that uses grep https://stackoverflow.com/questions/61229157/using-regex-in-grep-for-windows-command-line, but it has the same limitation - you need to know what string you are searching for.
[ "Assuming I understood correctly, there is no regex needed here, just .SubString(0, 3) to get the first 3 characters from each line and a hashtable to ensure unique codes and efficiency.\nIndeed, switch -File is awesome for this task and should be used to read your file. Otherwise, for simplicity and also keeping it efficient, you could use File.ReadLines.\n$map = @{ }\nswitch -File path\\to\\source\\file.txt {\n Default {\n $map[$_.Substring(0, 3)] += 1\n }\n}\n\n$map.GetEnumerator() | ForEach-Object {\n [pscustomobject]@{\n Code = $_.Key\n Count = $_.Value\n }\n} | Export-Csv path\\to\\resultOfUniqueCodes.csv -NoTypeInformation\n\n", "Just my two cents for a streaming approach - trying to avoid everything that's comparatively slow, like ForEach-Object, pscustomobject and Export-Csv.\n# Create a scriptblock to be able to pipe output of foreach loop\n& { \n foreach( $line in [IO.File]::ReadLines( 'input.txt' ) ) { \n $line.Substring( 0, 3 )\n }\n} | Group-Object -NoElement | & {\n begin {\n 'Code,Count'\n }\n process {\n '{0},{1}' -f $_.Name, $_.Count\n }\n} | Set-Content output.csv\n\nRemarks:\n\nforeach( $line in [IO.File]::ReadLines( 'input.txt' ) ) processes the input file lazily, so it's not read into memory as a whole. This works because ReadLines returns an iterator (not a collection) which foreach understands. As mentioned by others ReadLines is considered one of the fastest ways for line-by-line processing of text files, while still providing ease-of-use (compared to using .NET streams for instance).\nGroup-Object -NoElement just counts the number of occurences of unique input elements, propably using an internal hashtable, so it should be as fast as a manually created hashtable (not measured though - it would be really interesting).\nPiping from Group-Object to a script block is much faster than ForEach-Object with a script block, see GitHub issue. Though in your case it doesn't matter much, the bottleneck will be reading and processing the input file.\nAs the kind of input data is known, we can avoid Export-Csv's complexities (like escaping rules) and create the CSV directly using simple string operations and Set-Content. Again, won't really make a difference here, but might still be good to know for other cases that are more output-heavy.\n\n", "Try following :\n$input = @\"\narea,number\n201,44556\n202,34529\n201,44556\n202,34529\n201,44556\n202,34529\n201,44556\n202,34529\n\"@\n\n$table = $input | ConvertFrom-Csv\n$table | Format-Table\n\n$groups = $table | Group-Object {$_.area}\n\n$outputTable = [System.Collections.ArrayList]::new()\nforeach($group in $groups)\n{\n$group | Format-Table\n\n $newRow = New-Object -TypeName psobject\n $newRow | Add-Member -NotePropertyName area -NotePropertyValue $group.Name\n\n $newRow | Add-Member -NotePropertyName count -NotePropertyValue $group.Count\n\n $outputTable.Add($newRow) | Out-Null\n}\n$outputTable | Format-Table\n\n" ]
[ 4, 1, 0 ]
[]
[]
[ "grep", "powershell", "regex", "switch_statement", "windows" ]
stackoverflow_0074659476_grep_powershell_regex_switch_statement_windows.txt
Q: How to make align in java toString method I use toString and I print out the output like below. I want to align it like a timetable using toString, but I can't. what I print NAME: Poon IC NO: 000912 TAXABLE INCOME 85000.0 STATUS :S TAX AMOUNT: 17000.0 what I use public String toString(){ return person+"\nTAXABLE INCOME" + taxableIncome +"\nSTATUS :"+status+ "\nTAX AMOUNT: " + taxAmount ; } Required output: name iCNO taxableincome taxableAmount Poon 00654 6546546 465 the required output is somekind like this format I want to print A: You're looking for something like: String.format("%20s %05d %10dd %12d", name, icNumber, income, amount); %20s means: Print a string, and if it's shorter than 20 characters, pad it out to the right by adding spaces. The formatter page explains it all. %05d means: Print a number, pad it out if it's less than 5 long, and pad it with zeroes instead of spaces. And so on. A: In your Class, you first need to create Getters: public void getName(){ return name; } public void geticNumber(){ return icNumber; } public void getincome(){ return income; } public void amount(){ return amount; } After that you can print out your desired text in your Main: System.out.println("name iCNO taxableincome taxableAmount); System.out.printf("%s %d %d %d",yourClass.getName(),yourClass.geticNumber(),yourClass.getincome(),yourClass.amount()) Alternatively you can edit your .toString in your Class like this: String format = String.format("name iCNO taxableIncome taxableAmount%n%s %d %d %d",person,taxableIncome,status,taxAmount);
How to make align in java toString method
I use toString and I print out the output like below. I want to align it like a timetable using toString, but I can't. what I print NAME: Poon IC NO: 000912 TAXABLE INCOME 85000.0 STATUS :S TAX AMOUNT: 17000.0 what I use public String toString(){ return person+"\nTAXABLE INCOME" + taxableIncome +"\nSTATUS :"+status+ "\nTAX AMOUNT: " + taxAmount ; } Required output: name iCNO taxableincome taxableAmount Poon 00654 6546546 465 the required output is somekind like this format I want to print
[ "You're looking for something like:\nString.format(\"%20s %05d %10dd %12d\", name, icNumber, income, amount);\n\n%20s means: Print a string, and if it's shorter than 20 characters, pad it out to the right by adding spaces. The formatter page explains it all. %05d means: Print a number, pad it out if it's less than 5 long, and pad it with zeroes instead of spaces. And so on.\n", "In your Class, you first need to create Getters:\npublic void getName(){\nreturn name;\n}\npublic void geticNumber(){\nreturn icNumber;\n}\npublic void getincome(){\nreturn income;\n}\npublic void amount(){\nreturn amount;\n}\n\nAfter that you can print out your desired text in your Main:\nSystem.out.println(\"name iCNO taxableincome taxableAmount);\nSystem.out.printf(\"%s %d %d %d\",yourClass.getName(),yourClass.geticNumber(),yourClass.getincome(),yourClass.amount())\n\nAlternatively you can edit your .toString in your Class like this:\nString format = String.format(\"name iCNO taxableIncome taxableAmount%n%s %d %d %d\",person,taxableIncome,status,taxAmount);\n\n" ]
[ 0, 0 ]
[]
[]
[ "arrays", "java" ]
stackoverflow_0074658907_arrays_java.txt
Q: Best way to deal with managing mutable aspects of a struct in rust Here's an example of a problem I ran into: pub struct Item { name: String, value: LockableValue, // another struct that I'd like to mutate } impl Item { pub fn name(&self) -> &str { &self.name } pub fn value_mut(&mut self) -> &mut LockableValue { &self.value } } pub fn update(item: &mut Item) { let value = item.value_mut(); value.change(); // how it changes is unimportant println!("Updated item: {}", item.name()); } Now, I know why this fails. I have a mutable reference to item through the mutable reference to the value. If I convert the reference to an owned String, it works fine, but looks strange to me: pub fn update(item: &mut Item) { let name = { item.name().to_owned() }; let value = item.value_mut(); value.change(); // how it changes is unimportant println!("Updated item: {}", name); // It works! } If I let value reference drop, then everything is fine. pub fn update(item: &mut Item) { { let value = item.value_mut(); value.change(); // how it changes is unimportant } println!("Updated item: {}", item.name()); // It works! } The value.change() block is rather large, and accessing other fields in item might be helpful. So while I do have solutions to this issue, I'm wondering if there is a better (code-smell) way to do this. Any suggestions? My intention behind the above structs was to allow Items to change values, but the name should be immutable. LockableValue is an tool to interface with another memory system, and copying/cloning the struct is not a good idea, as the memory is managed there. (I implement Drop on LockableValue to clean up.) I was hoping it would be straight-forward to protect members of the struct from modification (even if it were immutable) like this... and I can, but it ends up looking weird to me. Maybe I just need to get used to it? A: You could use interior mutability on only the part that you want to mutate by using a RefCell like ths: use std::cell::{RefCell, RefMut}; pub struct LockableValue; impl LockableValue { fn change(&mut self) {} } pub struct Item { name: String, value: RefCell<LockableValue>, // another struct that I'd like to mutate } impl Item { pub fn name(&self) -> &str { &self.name } pub fn value_mut(&self) -> RefMut<'_, LockableValue> { self.value.borrow_mut() } } pub fn update(item: &Item) { let name = item.name(); let mut value = item.value_mut(); value.change(); // how it changes is unimportant println!("Updated item: {}", name); } That way you only need a shared reference to Item and you don't run into an issue with the borrow checker. Not that this forces the borrow checks on value to be done at runtime though and thus comes with a performance hit.
Best way to deal with managing mutable aspects of a struct in rust
Here's an example of a problem I ran into: pub struct Item { name: String, value: LockableValue, // another struct that I'd like to mutate } impl Item { pub fn name(&self) -> &str { &self.name } pub fn value_mut(&mut self) -> &mut LockableValue { &self.value } } pub fn update(item: &mut Item) { let value = item.value_mut(); value.change(); // how it changes is unimportant println!("Updated item: {}", item.name()); } Now, I know why this fails. I have a mutable reference to item through the mutable reference to the value. If I convert the reference to an owned String, it works fine, but looks strange to me: pub fn update(item: &mut Item) { let name = { item.name().to_owned() }; let value = item.value_mut(); value.change(); // how it changes is unimportant println!("Updated item: {}", name); // It works! } If I let value reference drop, then everything is fine. pub fn update(item: &mut Item) { { let value = item.value_mut(); value.change(); // how it changes is unimportant } println!("Updated item: {}", item.name()); // It works! } The value.change() block is rather large, and accessing other fields in item might be helpful. So while I do have solutions to this issue, I'm wondering if there is a better (code-smell) way to do this. Any suggestions? My intention behind the above structs was to allow Items to change values, but the name should be immutable. LockableValue is an tool to interface with another memory system, and copying/cloning the struct is not a good idea, as the memory is managed there. (I implement Drop on LockableValue to clean up.) I was hoping it would be straight-forward to protect members of the struct from modification (even if it were immutable) like this... and I can, but it ends up looking weird to me. Maybe I just need to get used to it?
[ "You could use interior mutability on only the part that you want to mutate by using a RefCell like ths:\nuse std::cell::{RefCell, RefMut};\npub struct LockableValue;\nimpl LockableValue {\n fn change(&mut self) {}\n}\npub struct Item {\n name: String,\n value: RefCell<LockableValue>, // another struct that I'd like to mutate\n}\nimpl Item {\n pub fn name(&self) -> &str {\n &self.name\n }\n\n pub fn value_mut(&self) -> RefMut<'_, LockableValue> {\n self.value.borrow_mut()\n }\n}\n\npub fn update(item: &Item) {\n let name = item.name();\n let mut value = item.value_mut();\n value.change(); // how it changes is unimportant\n println!(\"Updated item: {}\", name);\n}\n\nThat way you only need a shared reference to Item and you don't run into an issue with the borrow checker.\nNot that this forces the borrow checks on value to be done at runtime though and thus comes with a performance hit.\n" ]
[ 1 ]
[]
[]
[ "rust" ]
stackoverflow_0074657590_rust.txt
Q: Inline declaration of an internal table of string leads to type incompatibility Following an example given here, I'm using the VALUE operator to declare and populate a table of string values: DATA tab TYPE TABLE OF STRING. tab = VALUE #( ( 'abc' ) ( 'xyz' ) ) SAP gives the following error message : "'abc'" and the row type of "TAB" are incompatible. However, this works: DATA tab TYPE TABLE OF STRING. tab = VALUE #( ( conv string('abc') ) ( conv string('xyz') ) ) This is a version 2021 system. What is causing this error ? Shouldn't a literal be recognized directly as a string ? A: Instead of 'abc' use `abc` and your problem will be solved. 'abc' is always interpreted as a CHAR type of the given length `abc` however is interpreted as STRING type by the compiler, no need to cast.
Inline declaration of an internal table of string leads to type incompatibility
Following an example given here, I'm using the VALUE operator to declare and populate a table of string values: DATA tab TYPE TABLE OF STRING. tab = VALUE #( ( 'abc' ) ( 'xyz' ) ) SAP gives the following error message : "'abc'" and the row type of "TAB" are incompatible. However, this works: DATA tab TYPE TABLE OF STRING. tab = VALUE #( ( conv string('abc') ) ( conv string('xyz') ) ) This is a version 2021 system. What is causing this error ? Shouldn't a literal be recognized directly as a string ?
[ "Instead of 'abc' use `abc` and your problem will be solved.\n'abc' is always interpreted as a CHAR type of the given length\n`abc` however is interpreted as STRING type by the compiler, no need to cast.\n" ]
[ 2 ]
[]
[]
[ "abap" ]
stackoverflow_0074659066_abap.txt
Q: How could I find specific texts in one column of another dataset? Python I have 2 datasets. One contains a column of companies name, and another contains a column of headlines of news. So the aim I want to achieve is to find all the news whose headline contains one company in the other datasets.Basically the two datasets are like this, and I wanna select the news with specific company names I have tried to use for loop to achieve my goals, but I think it takes too much time and I think pandas or some other libraries can do this in an easier way. I am a starter in python. A: If I understand correctly you should have 2 data sets with different columns, first, you need to loop through the dataset that contains the company name to search in the headline, then you could use obj. find(“search”) to find matches in both datasets. Also if every query is stored in a CSV format you could use the split() function to get the only column you wanna use A: Supposing that you have saved your company names in a pd.Series called company and headlines and texts in a pd.DataFrame called df, this will be what you are looking for: # it will add a column called "company" to your initial df for org, headline in zip(company, df['headline']): if org in headline: df.loc[df['headline'] == headline, 'company'] = org You should pay attention to lower and upper case letters, as this will only find the corresponding company if the exact same word appears in the headline.
How could I find specific texts in one column of another dataset? Python
I have 2 datasets. One contains a column of companies name, and another contains a column of headlines of news. So the aim I want to achieve is to find all the news whose headline contains one company in the other datasets.Basically the two datasets are like this, and I wanna select the news with specific company names I have tried to use for loop to achieve my goals, but I think it takes too much time and I think pandas or some other libraries can do this in an easier way. I am a starter in python.
[ "If I understand correctly you should have 2 data sets with different columns, first, you need to loop through the dataset that contains the company name to search in the headline, then you could use obj. find(“search”) to find matches in both datasets.\nAlso if every query is stored in a CSV format you could use the split() function to get the only column you wanna use\n", "Supposing that you have saved your company names in a pd.Series called company and headlines and texts in a pd.DataFrame called df, this will be what you are looking for:\n# it will add a column called \"company\" to your initial df\nfor org, headline in zip(company, df['headline']):\n if org in headline:\n df.loc[df['headline'] == headline, 'company'] = org\n\nYou should pay attention to lower and upper case letters, as this will only find the corresponding company if the exact same word appears in the headline.\n" ]
[ 0, 0 ]
[]
[]
[ "dataset", "pandas", "python", "python_3.x" ]
stackoverflow_0074659809_dataset_pandas_python_python_3.x.txt
Q: Inherit signals and slots from a base class in Qt I have created: class A : public QObject { Q_OBJECT public signals: Q_SIGNAL void mySignal(); }; And I would like to derive: class B : public A { //Some added functionality }; And still be able to connect mySignal() emitted by B (which it inherited from A) to a slot in my QMainWindow: B b; connect(&b, SIGNAL(mySignal()), this, SLOT(aSlot())); Currently this method results in "multiple definition of "A::disconnected()" and the compiler points me to the moc file here: void A::disconnected() { QMetaObject::activate(this, &staticMetaObject, 0, nullptr); } What is the problem here? I have done my research but what I found seems to be on different types of inheritance patterns and I don't understand Qt enough to port conclusions here. Edit: I had stupidly forgotten the & in my original post, thanks Scheff's cat - I've updated my problem. A: For those of you who have the same problem as this one, check your source file for a potential definition of A::mySignal()... I had created an empty definition of the function, as usual, whereas apparently MOC creates one for us. Resulting in multiple definitions.
Inherit signals and slots from a base class in Qt
I have created: class A : public QObject { Q_OBJECT public signals: Q_SIGNAL void mySignal(); }; And I would like to derive: class B : public A { //Some added functionality }; And still be able to connect mySignal() emitted by B (which it inherited from A) to a slot in my QMainWindow: B b; connect(&b, SIGNAL(mySignal()), this, SLOT(aSlot())); Currently this method results in "multiple definition of "A::disconnected()" and the compiler points me to the moc file here: void A::disconnected() { QMetaObject::activate(this, &staticMetaObject, 0, nullptr); } What is the problem here? I have done my research but what I found seems to be on different types of inheritance patterns and I don't understand Qt enough to port conclusions here. Edit: I had stupidly forgotten the & in my original post, thanks Scheff's cat - I've updated my problem.
[ "For those of you who have the same problem as this one, check your source file for a potential definition of A::mySignal()... I had created an empty definition of the function, as usual, whereas apparently MOC creates one for us. Resulting in multiple definitions.\n" ]
[ 0 ]
[]
[]
[ "c++", "inheritance", "qt5" ]
stackoverflow_0074651725_c++_inheritance_qt5.txt
Q: Adding count of children per parent in single data frame and count of all descendants Have a table of employees (key emp id) with one column being the boss (same key format). I was able to build out the hierarchy by doing repeated joins (took 10 for my real organization), but now I need to add a column for: employee_count (count of rows with the boss_id = emp_id of current row) empire_count (count of rows with the hierarchy starting the same way) I'm most comfortable in the Tidyverse, here's some simplified fake data of what I have so far as example: library(tidyverse) employees = tibble( emp_id = c(1,2,3,4,5,6,7), emp_name = c('BigBoss','MedBoss','MedBoss2','Emp1','Emp2','Emp3','Emp4'), boss_name = c('','BigBoss','BigBoss','MedBoss','MedBoss','MedBoss2','MedBoss2'), hierarchy = c('','BigBoss','BigBoss','BigBoss>MedBoss','BigBoss>MedBoss','BigBoss>MedBoss2','BigBoss>MedBoss2') ) Which looks like this: # A tibble: 7 × 4 emp_id emp_name boss_name hierarchy <dbl> <chr> <chr> <chr> 1 1 BigBoss "" "" 2 2 MedBoss "Bigboss" "BigBoss" 3 3 MedBoss2 "BigBoss" "BigBoss" 4 4 Emp1 "MedBoss" "BigBoss>MedBoss" 5 5 Emp2 "MedBoss" "BigBoss>MedBoss" 6 6 Emp3 "MedBoss2" "BigBoss>MedBoss2" 7 7 Emp4 "MedBoss2" "BigBoss>MedBoss2" As far as what I'm looking for, employee_count should be 2 for each of the MedBosses and BigBoss, and then the empire_count for BigBoss would be 6. For the employee_count piece, I could separately do a: data %>% group_by(boss_name) %>% summarize(employee_count=n(emp_id)) and then join it back, but then the hierarchy wouldn't work the same way... I think the answer is some map function from purrr or creating a function, and Vectorize()'ing it and calling within a mutate, but that hasn't worked for me. This is as close as I can get... # Function to get the count of employees for a boss_name get_employee_count = function(table,bossname) table %>% filter(boss_name==bossname) %>% nrow() # This call works (returns 2) get_employee_count(employees,'BigBoss') # Try to add the count in via a mutate (returns 7 for each) employees %>% mutate(employee_count=get_employee_count(.,boss_name)) If I can get that to work, I think I could figure out the harder piece as I could do it also as a function. A: After a lot of trial and error, I can do it if I hard-code the dataframe name, which is close enough for me. # This is the solution employees %>% mutate(employee_count = map_int(emp_name,function(name) employees %>% filter(boss_name==name) %>% nrow())) %>% mutate(empire_count = map_int(emp_name,function(name) employees %>% filter(str_detect(hierarchy,name)) %>% nrow())) A: Definitely a graph/tree problem. For employee count, just find all the adjacent nodes. For empire_count, enumerate all the simple paths and count the unique nodes. All easy enough with igraph library(igraph) empTree <- graph_from_data_frame( employees |> filter(boss_name != "") |> select(from = emp_name, to = boss_name) ) Count_Empire <- function(node) { paths <- all_simple_paths(empTree, node, mode = "in") if(length(paths) == 0) return(0) ct <- paths |> map(~as.vector(.x)) |> reduce(c) |> unique() |> length() # minus 1 for self ct - 1 } Count_Employees <- function(node) { adjacent_vertices(empTree, node, mode = "in")[[1]] |> as.vector() |> length() } employees |> mutate( employee_count = map_dbl(emp_name, Count_Employees), empire_count = map_dbl(emp_name, Count_Empire) )
Adding count of children per parent in single data frame and count of all descendants
Have a table of employees (key emp id) with one column being the boss (same key format). I was able to build out the hierarchy by doing repeated joins (took 10 for my real organization), but now I need to add a column for: employee_count (count of rows with the boss_id = emp_id of current row) empire_count (count of rows with the hierarchy starting the same way) I'm most comfortable in the Tidyverse, here's some simplified fake data of what I have so far as example: library(tidyverse) employees = tibble( emp_id = c(1,2,3,4,5,6,7), emp_name = c('BigBoss','MedBoss','MedBoss2','Emp1','Emp2','Emp3','Emp4'), boss_name = c('','BigBoss','BigBoss','MedBoss','MedBoss','MedBoss2','MedBoss2'), hierarchy = c('','BigBoss','BigBoss','BigBoss>MedBoss','BigBoss>MedBoss','BigBoss>MedBoss2','BigBoss>MedBoss2') ) Which looks like this: # A tibble: 7 × 4 emp_id emp_name boss_name hierarchy <dbl> <chr> <chr> <chr> 1 1 BigBoss "" "" 2 2 MedBoss "Bigboss" "BigBoss" 3 3 MedBoss2 "BigBoss" "BigBoss" 4 4 Emp1 "MedBoss" "BigBoss>MedBoss" 5 5 Emp2 "MedBoss" "BigBoss>MedBoss" 6 6 Emp3 "MedBoss2" "BigBoss>MedBoss2" 7 7 Emp4 "MedBoss2" "BigBoss>MedBoss2" As far as what I'm looking for, employee_count should be 2 for each of the MedBosses and BigBoss, and then the empire_count for BigBoss would be 6. For the employee_count piece, I could separately do a: data %>% group_by(boss_name) %>% summarize(employee_count=n(emp_id)) and then join it back, but then the hierarchy wouldn't work the same way... I think the answer is some map function from purrr or creating a function, and Vectorize()'ing it and calling within a mutate, but that hasn't worked for me. This is as close as I can get... # Function to get the count of employees for a boss_name get_employee_count = function(table,bossname) table %>% filter(boss_name==bossname) %>% nrow() # This call works (returns 2) get_employee_count(employees,'BigBoss') # Try to add the count in via a mutate (returns 7 for each) employees %>% mutate(employee_count=get_employee_count(.,boss_name)) If I can get that to work, I think I could figure out the harder piece as I could do it also as a function.
[ "After a lot of trial and error, I can do it if I hard-code the dataframe name, which is close enough for me.\n# This is the solution\nemployees %>% \n mutate(employee_count = map_int(emp_name,function(name) employees %>% filter(boss_name==name) %>% nrow())) %>% \n mutate(empire_count = map_int(emp_name,function(name) employees %>% filter(str_detect(hierarchy,name)) %>% nrow()))\n\n", "Definitely a graph/tree problem. For employee count, just find all the adjacent nodes. For empire_count, enumerate all the simple paths and count the unique nodes. All easy enough with igraph\nlibrary(igraph)\n\nempTree <- graph_from_data_frame(\n employees |> \n filter(boss_name != \"\") |> \n select(from = emp_name, to = boss_name)\n)\n\nCount_Empire <- function(node) {\n \n paths <- all_simple_paths(empTree, node, mode = \"in\") \n \n if(length(paths) == 0) return(0)\n \n ct <- paths |> \n map(~as.vector(.x)) |> \n reduce(c) |> \n unique() |> \n length()\n \n # minus 1 for self \n ct - 1\n}\n\nCount_Employees <- function(node) {\n \n adjacent_vertices(empTree, node, mode = \"in\")[[1]] |> \n as.vector() |> \n length()\n}\n\nemployees |> \n mutate(\n employee_count = map_dbl(emp_name, Count_Employees),\n empire_count = map_dbl(emp_name, Count_Empire)\n )\n\n" ]
[ 0, 0 ]
[]
[]
[ "dplyr", "purrr", "r" ]
stackoverflow_0074658107_dplyr_purrr_r.txt
Q: How to replace original content:" - " inside a class='btn'>" - "< after the element has been :hover:after Output on ':hover' is always "1IPSUM" And if i decide to add a ':before' element with 'content:"1"' it just adds a 1 making the output before hover "11" The output i am looking for is: on 'hover' "IPSUM" Fiddle: https://jsfiddle.net/Zxdfvv/u9xgoks3/ .btn:hover:after { padding-bottom: 200px; content:"IPSUM"; } <div class='btn'>1</div> A: You're setting the content: for the pseudo-element, not for the element itself. That's why when you add content to ::before it shows up before the text of the element, and then why in turn it shows after if you use ::after. What you could do is set the initial text using pseudo-elements, too. So you could do: html, body { margin: 0; padding: 0; height: 100%; } body { background-color: #006400; display: grid; place-items: center; } main { padding: 1em; display: flex; flex-direction: column; gap: 1em; } .btn { border: 3px solid black; text-align: center; border-radius: 20px; letter-spacing: 2px; padding: 1em 1.5em; background-color: #ffd700; color: black; font-family: monospace; display: inline-block; margin: 1em; } .btn::after { display: inline-block; } .btn--empty::after { content: ""; } .btn--pseudo::after { content: "lorem"; } .btn:hover::after { content: "ipsum"; } <html> <body> <main> <a class="btn btn--empty" href="#"></a> <a class="btn btn--pseudo" href="#"></a> </main> </body> </html> A: Thank u, EmSixTeen! Im away at school so I am unable to log into my account. Will Pseudo elements work the same on different browsers?
How to replace original content:" - " inside a class='btn'>" - "< after the element has been :hover:after
Output on ':hover' is always "1IPSUM" And if i decide to add a ':before' element with 'content:"1"' it just adds a 1 making the output before hover "11" The output i am looking for is: on 'hover' "IPSUM" Fiddle: https://jsfiddle.net/Zxdfvv/u9xgoks3/ .btn:hover:after { padding-bottom: 200px; content:"IPSUM"; } <div class='btn'>1</div>
[ "You're setting the content: for the pseudo-element, not for the element itself. That's why when you add content to ::before it shows up before the text of the element, and then why in turn it shows after if you use ::after.\nWhat you could do is set the initial text using pseudo-elements, too. So you could do:\n\n\nhtml,\nbody {\n margin: 0;\n padding: 0;\n height: 100%;\n}\n\nbody {\n background-color: #006400;\n display: grid;\n place-items: center;\n}\n\nmain {\n padding: 1em;\n display: flex;\n flex-direction: column;\n gap: 1em;\n}\n\n.btn {\n border: 3px solid black;\n text-align: center;\n border-radius: 20px;\n letter-spacing: 2px;\n padding: 1em 1.5em;\n background-color: #ffd700;\n color: black;\n font-family: monospace;\n display: inline-block;\n margin: 1em;\n}\n\n.btn::after {\n display: inline-block;\n}\n\n.btn--empty::after {\n content: \"\";\n}\n\n.btn--pseudo::after {\n content: \"lorem\";\n}\n.btn:hover::after {\n content: \"ipsum\";\n}\n<html>\n\n<body>\n <main>\n \n <a class=\"btn btn--empty\" href=\"#\"></a>\n\n <a class=\"btn btn--pseudo\" href=\"#\"></a>\n\n </main>\n</body>\n\n</html>\n\n\n\n", "Thank u, EmSixTeen! Im away at school so I am unable to log into my account. Will Pseudo elements work the same on different browsers?\n" ]
[ 0, 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074646312_css_html.txt
Q: Can I extend a Typescript tuple type? Say I have a Typescript tuple: type Sandwich = [name: string, toppings: object] Now I want to extend it: type HotDog = [name: string, toppings: object, length: number] Can HotDog extend Sandwich without duplication? A: Yes, you can extend a tuple type in TypeScript. In TypeScript, a tuple is a way to represent a fixed-size array of elements with a known number of elements, where the types of the elements are known. You can extend a tuple type by adding additional elements to the tuple type with their corresponding types. Here is an example of how you can extend a tuple type in TypeScript: // Define a tuple type with three elements type Tuple = [string, number, boolean]; // Extend the tuple type by adding an additional element // with the type Date type ExtendedTuple = [...Tuple, Date]; // Create a variable of the extended tuple type const tuple: ExtendedTuple = ['Hello', 42, true, new Date()]; In this example, the tuple type Tuple is defined with three elements of different types: string, number, and boolean. The tuple type is then extended with an additional element of the type Date, using the spread operator (...) to include the original elements of the Tuple type in the new extended tuple type. You can then create a variable of the extended tuple type and assign it a tuple with the additional element. In this case, the variable tuple is of the type ExtendedTuple, which includes the four elements from the original Tuple type plus the additional Date element. Note that when extending a tuple type, you must maintain the order of the original tuple elements and add the new element at the end of the tuple. This is because the order of the elements in a tuple is significant, and changing the order of the elements would result in a different tuple type. In summary, you can extend a tuple type in TypeScript by adding additional elements to the tuple type with their corresponding types, using the spread operator (...) to include the original elements of the tuple type in the extended tuple type. You must maintain the order of the original tuple elements when extending the tuple type. A: Just spread one into the other: type Sandwich = [name: string, toppings: object] type HotDog = [...sandwich: Sandwich, length: number] // ^ type is [name: string, toppings: object, length: number] See Playground
Can I extend a Typescript tuple type?
Say I have a Typescript tuple: type Sandwich = [name: string, toppings: object] Now I want to extend it: type HotDog = [name: string, toppings: object, length: number] Can HotDog extend Sandwich without duplication?
[ "Yes, you can extend a tuple type in TypeScript. In TypeScript, a tuple is a way to represent a fixed-size array of elements with a known number of elements, where the types of the elements are known. You can extend a tuple type by adding additional elements to the tuple type with their corresponding types.\nHere is an example of how you can extend a tuple type in TypeScript:\n// Define a tuple type with three elements\ntype Tuple = [string, number, boolean];\n\n// Extend the tuple type by adding an additional element\n// with the type Date\ntype ExtendedTuple = [...Tuple, Date];\n\n// Create a variable of the extended tuple type\nconst tuple: ExtendedTuple = ['Hello', 42, true, new Date()];\n\n\nIn this example, the tuple type Tuple is defined with three elements of different types: string, number, and boolean. The tuple type is then extended with an additional element of the type Date, using the spread operator (...) to include the original elements of the Tuple type in the new extended tuple type.\nYou can then create a variable of the extended tuple type and assign it a tuple with the additional element. In this case, the variable tuple is of the type ExtendedTuple, which includes the four elements from the original Tuple type plus the additional Date element.\nNote that when extending a tuple type, you must maintain the order of the original tuple elements and add the new element at the end of the tuple. This is because the order of the elements in a tuple is significant, and changing the order of the elements would result in a different tuple type.\nIn summary, you can extend a tuple type in TypeScript by adding additional elements to the tuple type with their corresponding types, using the spread operator (...) to include the original elements of the tuple type in the extended tuple type. You must maintain the order of the original tuple elements when extending the tuple type.\n", "Just spread one into the other:\ntype Sandwich = [name: string, toppings: object]\ntype HotDog = [...sandwich: Sandwich, length: number]\n// ^ type is [name: string, toppings: object, length: number]\n\nSee Playground\n" ]
[ 2, 1 ]
[]
[]
[ "tuples", "typescript" ]
stackoverflow_0074660182_tuples_typescript.txt
Q: Inconsistent Object.is logic with NaN This code evaluates to false: Object.is(parseFloat('26-broadway'), NaN); // returns false However this example evaluates as true: Object.is(parseFloat('broadway-26'), NaN); // returns true I would have expected the last code snippet to return false though. Why does it return true when I paste it in a Browser console like Google Chrome? A: As Sebastian pointed out, the real question has nothing to do with Object.is and all about the parseFloat(). “parseFloat() picks the longest substring starting from the beginning that generates a valid number literal.” It parses a string from left to right. b is not a digit, so it stops right there.
Inconsistent Object.is logic with NaN
This code evaluates to false: Object.is(parseFloat('26-broadway'), NaN); // returns false However this example evaluates as true: Object.is(parseFloat('broadway-26'), NaN); // returns true I would have expected the last code snippet to return false though. Why does it return true when I paste it in a Browser console like Google Chrome?
[ "As Sebastian pointed out, the real question has nothing to do with Object.is and all about the parseFloat().\n\n“parseFloat() picks the longest substring starting from the beginning that generates a valid number literal.” It parses a string from left to right. b is not a digit, so it stops right there.\n\n" ]
[ 0 ]
[]
[]
[ "javascript" ]
stackoverflow_0074660064_javascript.txt
Q: How to define custom check according to my rules and how to implement Django I using Python 3.10, Django 4.1.2, djangorestframework==3.14.0 (front separately) In an order, the products received field is empty by default. As we receive the order, we must remove these elements from the ordered field and transfer them to the received ones. received products must contain only products from requested Products After submitting request with amount of received products, this particular products should be removed from requested Products and addiing to recived_products I have two ideas for a theoretical implementation. Using the patch, the received_product and the elements in it Separate method I have this code: class Orders(models.Model): delivery_model_choices = (("Pickup", "Pickup"), ("Delivery", "Delivery")) order_status_choices = (("Draft", "Draft"), ("Open", "Open"), ("Partially Received", "Partially Received"), ("Received", "Received"), ("Cancelled", "Cancelled")) costumer = models.ManyToManyField(Costumers) products = models.ManyToManyField(Products) recived_products = ??? date_create = models.DateTimeField(auto_now_add=True) delivery = models.CharField(max_length=40, choices=delivery_model_choices) delivery_date = models.DateField() order_status = models.CharField(max_length=40, choices=order_status_choices) total_price = models.CharField(max_length=10) Please, I ask you for a correct example on this implementation. I'm still new to development A: I will not write the complete code, but you can try this logic - Define a Create method for the viewset or views (whatever you use) def create(self, request, format=None): request.data is the data that you receive all_product_recieved = all products that you have received recived_products = all_product_recieved - ordered product custom_data = create a new dictionary with valid data then ... serializer = self.get_serializer(data=custom_data) if serializer.is_valid(): serializer.save() return Response() return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Hope this helps.
How to define custom check according to my rules and how to implement Django
I using Python 3.10, Django 4.1.2, djangorestframework==3.14.0 (front separately) In an order, the products received field is empty by default. As we receive the order, we must remove these elements from the ordered field and transfer them to the received ones. received products must contain only products from requested Products After submitting request with amount of received products, this particular products should be removed from requested Products and addiing to recived_products I have two ideas for a theoretical implementation. Using the patch, the received_product and the elements in it Separate method I have this code: class Orders(models.Model): delivery_model_choices = (("Pickup", "Pickup"), ("Delivery", "Delivery")) order_status_choices = (("Draft", "Draft"), ("Open", "Open"), ("Partially Received", "Partially Received"), ("Received", "Received"), ("Cancelled", "Cancelled")) costumer = models.ManyToManyField(Costumers) products = models.ManyToManyField(Products) recived_products = ??? date_create = models.DateTimeField(auto_now_add=True) delivery = models.CharField(max_length=40, choices=delivery_model_choices) delivery_date = models.DateField() order_status = models.CharField(max_length=40, choices=order_status_choices) total_price = models.CharField(max_length=10) Please, I ask you for a correct example on this implementation. I'm still new to development
[ "I will not write the complete code, but you can try this logic -\nDefine a Create method for the viewset or views (whatever you use)\ndef create(self, request, format=None):\n request.data is the data that you receive\n all_product_recieved = all products that you have received\n recived_products = all_product_recieved - ordered product\n custom_data = create a new dictionary with valid data\n then ...\n serializer = self.get_serializer(data=custom_data)\n if serializer.is_valid():\n serializer.save()\n return Response()\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\nHope this helps.\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "python" ]
stackoverflow_0074657076_django_django_models_django_rest_framework_python.txt
Q: Terminal can't find version of python despite it being installed I'm trying to install packages on multiple versions of Python. I'm currently running 3.8.8, and 3.11.0. Following this post Install a module using pip for specific python version called python3.11 -m pip install pandas which results in File "<stdin>", line 1 python3.11 -m pip install pandas SyntaxError: invalid syntax This seems to indicate an issue with python, so I double checked that python3.11 is installed. the python3.11 works in isolation seems to work. I don't understand why the install command isn't working. A: If you’re using Linux try just python3 —-version In Windows you may need to add path to folder with installed Python to PATH variable.
Terminal can't find version of python despite it being installed
I'm trying to install packages on multiple versions of Python. I'm currently running 3.8.8, and 3.11.0. Following this post Install a module using pip for specific python version called python3.11 -m pip install pandas which results in File "<stdin>", line 1 python3.11 -m pip install pandas SyntaxError: invalid syntax This seems to indicate an issue with python, so I double checked that python3.11 is installed. the python3.11 works in isolation seems to work. I don't understand why the install command isn't working.
[ "If you’re using Linux try just\npython3 —-version\n\nIn Windows you may need to add path to folder with installed Python to PATH variable.\n" ]
[ 0 ]
[ "Check your environment variables, you could try removing the variables pointing to the 3.8 version until you get the packages you want installed.\nYou could also try navigating to that python 3.11 installation directly, and executing the python shell from there, then run the command.\n" ]
[ -1 ]
[ "module", "python", "version" ]
stackoverflow_0074660181_module_python_version.txt
Q: How do I save the owner of a group in Sequelize I am working with Sequelize and Koa. I created both a User and a Group model using the Sequelize-CLI. They have a Many-to-Many association between each other. I want to store which user is the owner of the group is by using his UUID. Do I create another another association using a One-To-Many association (1 User is the owner of 0 or more groups). I wouldn't know how to go about making this association on top of the many-to-many. Or do I just store the UUID of the User in my Group model? What would be the best way to go about this. Thanks! I searched for an example online with a similar situation but I didn't find one. A: If a group can have the one and only owner then it's obvious that you need to add something like ownerId to the Group and add associations like these ones: User.hasMany(Group, { as: 'OwnedGroups', foreignKey: 'ownerId' }) Group.belongsTo(User, { as: 'Owner', foreignKey: 'ownerId' }
How do I save the owner of a group in Sequelize
I am working with Sequelize and Koa. I created both a User and a Group model using the Sequelize-CLI. They have a Many-to-Many association between each other. I want to store which user is the owner of the group is by using his UUID. Do I create another another association using a One-To-Many association (1 User is the owner of 0 or more groups). I wouldn't know how to go about making this association on top of the many-to-many. Or do I just store the UUID of the User in my Group model? What would be the best way to go about this. Thanks! I searched for an example online with a similar situation but I didn't find one.
[ "If a group can have the one and only owner then it's obvious that you need to add something like ownerId to the Group and add associations like these ones:\nUser.hasMany(Group, { as: 'OwnedGroups', foreignKey: 'ownerId' })\nGroup.belongsTo(User, { as: 'Owner', foreignKey: 'ownerId' }\n\n" ]
[ 0 ]
[]
[]
[ "database", "koa", "mysql", "sequelize.js", "sequelize_cli" ]
stackoverflow_0074660056_database_koa_mysql_sequelize.js_sequelize_cli.txt
Q: (DaisyUI) - How to change primary color of DaisyUI outside the tailwind.config.js I want to add a button, when a user clicks on it, the DaisyUI primary color get changed, ie. from hsl(var(--p) / var(--tw-text-opacity)) to be another color. I know I can change it through tailwind.config.js, but I need a dynamic button to do it for me. Any Help Appreciated. For the web app I will implement both of dark & light mode, I can add more themes say theme1, theme2 and theme3 that all require light mode only the primary color get changed, but in that case, I have to add a lot of themes for both of light & dark mode that only primary color get changed into a few different colors. A: To change the primary color of DaisyUI, you will need to edit the appropriate CSS styles in your application. DaisyUI is a user interface (UI) library that is built on top of the Tailwind CSS framework, and it uses Tailwind's default color palette for its default styles. To change the primary color of DaisyUI, you will need to override the default color styles in your application's CSS. This can be done by defining new styles that use the desired primary color, and by applying these styles to the appropriate elements in your HTML. For example, to change the primary color of DaisyUI to the color #3182ce, you could add the following styles to your application's CSS: .bg-primary { background-color: #3182ce; } .text-primary { color: #3182ce; } These styles would override the default primary color styles in DaisyUI, and would apply the color #3182ce to any elements with the bg-primary or text-primary classes. You can then use these classes in your HTML to apply the primary color to the desired elements. It is important to note that changing the primary color of DaisyUI in this way will only affect the styles of your application, and will not modify the default color palette or styles in the Tailwind CSS framework. To change the default colors in Tailwind, you will need to edit the tailwind.config.js file in your project and define new colors in the colors section of the configuration. Overall, to change the primary color of DaisyUI, you will need to edit the appropriate CSS styles in your application and apply the desired color to the relevant elements. This will allow you to customize the appearance of your application and to use the primary color that is best suited to your needs and preferences.
(DaisyUI) - How to change primary color of DaisyUI outside the tailwind.config.js
I want to add a button, when a user clicks on it, the DaisyUI primary color get changed, ie. from hsl(var(--p) / var(--tw-text-opacity)) to be another color. I know I can change it through tailwind.config.js, but I need a dynamic button to do it for me. Any Help Appreciated. For the web app I will implement both of dark & light mode, I can add more themes say theme1, theme2 and theme3 that all require light mode only the primary color get changed, but in that case, I have to add a lot of themes for both of light & dark mode that only primary color get changed into a few different colors.
[ "To change the primary color of DaisyUI, you will need to edit the appropriate CSS styles in your application. DaisyUI is a user interface (UI) library that is built on top of the Tailwind CSS framework, and it uses Tailwind's default color palette for its default styles.\nTo change the primary color of DaisyUI, you will need to override the default color styles in your application's CSS. This can be done by defining new styles that use the desired primary color, and by applying these styles to the appropriate elements in your HTML.\nFor example, to change the primary color of DaisyUI to the color #3182ce, you could add the following styles to your application's CSS:\n.bg-primary {\n background-color: #3182ce;\n}\n\n.text-primary {\n color: #3182ce;\n}\n\nThese styles would override the default primary color styles in DaisyUI, and would apply the color #3182ce to any elements with the bg-primary or text-primary classes. You can then use these classes in your HTML to apply the primary color to the desired elements.\nIt is important to note that changing the primary color of DaisyUI in this way will only affect the styles of your application, and will not modify the default color palette or styles in the Tailwind CSS framework. To change the default colors in Tailwind, you will need to edit the tailwind.config.js file in your project and define new colors in the colors section of the configuration.\nOverall, to change the primary color of DaisyUI, you will need to edit the appropriate CSS styles in your application and apply the desired color to the relevant elements. This will allow you to customize the appearance of your application and to use the primary color that is best suited to your needs and preferences.\n" ]
[ -1 ]
[]
[]
[ "daisyui", "reactjs", "tailwind_css" ]
stackoverflow_0074660186_daisyui_reactjs_tailwind_css.txt
Q: I am running a cnn model on a remotely accessed Linux but it throws an error for the same code that runs perfectly on windows axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])numpy.axiserror: axis 3 is out of bounds for array of dimension 2 axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])numpy.axiserror: axis 3 is out of bounds for array of dimension 2
I am running a cnn model on a remotely accessed Linux but it throws an error for the same code that runs perfectly on windows
axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])numpy.axiserror: axis 3 is out of bounds for array of dimension 2 axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])numpy.axiserror: axis 3 is out of bounds for array of dimension 2
[]
[]
[ "I fixed this replacing that lines with:\n wind =np.expand_dims(wind, 1)\n wind = wind * wind.transpose()\n wind = np.stack((wind, wind, wind), axis=-1)\n\n" ]
[ -1 ]
[ "conv_neural_network", "deep_learning", "hpc", "linux" ]
stackoverflow_0074660199_conv_neural_network_deep_learning_hpc_linux.txt
Q: Linux sed -i -e command include / in replacement i have a problem with my sed command. I have the following file and want to replace line number 4. text.txt content: 1 Hi World! 2 Okey 3 Test 4 ;date.timezone = cmd command: sed -i -e "s/;date.timezone =/date.timezone = Europe/Berlin/" text.txt Because my replacement holds a / inside, the sed command cant execute properly because of Europe/Berlin. My Folder Structure: folder structrure /Users/user/dev/repos/docker └── text.txt My fix would be to ignore the / between Europe and Berlin. I didn't really find the answer in the web, that's why I reach out for you? Output: sed: 1: "s/;date.timezone =/date ...": bad flag in substitute command: 'B' A: Thanks, the following worked for me! sed -i -e "s/;date\.timezone =/date.timezone = Europe\/Berlin/" text.txt A: You can use any separator in the sed command terms. I usually use # in these cases. For instance this should work: sed -i -e "s#;date.timezone =#date.timezone = Europe/Berlin#" text.txt
Linux sed -i -e command include / in replacement
i have a problem with my sed command. I have the following file and want to replace line number 4. text.txt content: 1 Hi World! 2 Okey 3 Test 4 ;date.timezone = cmd command: sed -i -e "s/;date.timezone =/date.timezone = Europe/Berlin/" text.txt Because my replacement holds a / inside, the sed command cant execute properly because of Europe/Berlin. My Folder Structure: folder structrure /Users/user/dev/repos/docker └── text.txt My fix would be to ignore the / between Europe and Berlin. I didn't really find the answer in the web, that's why I reach out for you? Output: sed: 1: "s/;date.timezone =/date ...": bad flag in substitute command: 'B'
[ "Thanks, the following worked for me!\nsed -i -e \"s/;date\\.timezone =/date.timezone = Europe\\/Berlin/\" text.txt\n\n", "You can use any separator in the sed command terms.\nI usually use # in these cases. For instance this should work:\nsed -i -e \"s#;date.timezone =#date.timezone = Europe/Berlin#\" text.txt\n\n" ]
[ 0, 0 ]
[]
[]
[ "linux", "replace", "sed", "unix" ]
stackoverflow_0074657455_linux_replace_sed_unix.txt
Q: How to set up proxy in .htaccess The Apache documentation states that RewriteRule and the should be put in the server configuration, but they can be put in htaccess because of shared hosting situations. I am in such a situation. I am trying to set up a transparent proxy: RewriteEngine On RewriteCond %{REQUEST_URI} ^/foo [OR] RewriteCond %{REQUEST_URI} ^/bar RewriteRule ^(.*)$ http://example.com/$1 [P] This is working fine...except for redirects (like if /foo redirects to /bar). Redirects go back to example.com, not my server. I understand the the ProxyPassReverse directive will solve this, but I get an "Internal Server Error" page when I add this to .htaccess Unlike the Rewrite directives, ProxyPassReverse will not work in htaccess. How do I set up a transparent proxy in shared hosting situation, or is this not possible? (This seems reasonable, since Rewrite already gets 80% of the way there, and having a transparent proxy in one htaccess would not interfere with having it in another.) A: Unfortunately, I'm fairly sure what you want to do isn't possible: I'm trying to do the exact same thing! From my research, I'm fairly confident it's not possible. Put simply, you need to use ProxyPassReverse, which is only available at a VirtualHost level (or similar); not a htaccess level. Edit: the only way I have achieved this is by also configuring the responding server/application to know it's behind a proxy, and serving pages appropriately. That is, I use .htaccess to redirect to another server as follows: RewriteEngine on RewriteRule (.*) http://localhost:8080/$1 [P,L] Then on the application server -- in this case, a JIRA installation -- I configured the Java Tomcat/Catalina appropriately to serve pages with the proxied information: proxyName="my.public.address.com" proxyPort="80" However, that's not completely transparent; the app server needs to serve pages in a proxied manner. It might be of some use, though. A: I managed to gather a few sources to figure out how to do this. I use a shared hosting provider, so I don't have access to server configuration (httpd.conf). I can only use .htaccess to accomplish the proxying. This example is for a WordPress site where I want most of the content served by origin.example.com, but will have some pages served locally, sort of like an overlay. You could go the other way and ONLY proxy specific subdirectories using different RewriteCond rules. Things to know: You can’t use ProxyPass or ProxyPassReverse in .htaccess, so we have to use other methods to mimic what they do. You can’t make proxy calls over HTTPS if SSLProxyEngine is not turned on by your provider, so you will lose some security if you have concerns about MITM attacks. If the origin server is internal, this may not be an issue. You could also use .htaccess on the origin server to enforce HTTPS from everywhere except the proxy server. You need to rewrite headers You need to rewrite the HTML that comes back from the origin server, and that needs to be done on the origin server. You can restrict it to certain IPs (i.e. the IP of the proxy) so it won’t break if you access it elsewhere. What I want: I want calls to proxy.example.com to serve content origin.example.com. In my case, I want to map everything with a few exceptions. If you only want to map a portion of your site, adjust your rules accordingly. How to do it: Configure the .htaccess file on proxy.example.com to proxy all URIs to origin.example.com. I want to be able to log into proxy.example.com, so I don’t rewrite /wp-admin or /wp-login.php. In my case, I have a /programs/ section that I want served by the proxy server itself (also a WordPress instance). Prevent looping by checking REDIRECT_STATUS. # I force everything coming into proxy.example.com to be HTTPS <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteCond %{HTTPS} off RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule> <IfModule mod_proxy.c> # Redirect access for / (or any index) to the origin. NOTE target is http:// without SSLProxyEngine RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteRule ^(index\.(php|html|cgi))?$ http://origin.example.com/ [P] # Do NOT redirect these patterns RewriteCond %{REQUEST_URI} !^/wp-admin/ RewriteCond %{REQUEST_URI} !^/wp-login.php RewriteCond %{REQUEST_URI} !^/programs/ # Redirect everything else. NOTE target is http:// without SSLProxyEngine RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteRule ^(.+)$ "http://origin.example.com/$1" [P] # Mimic ProxyPassReverse. Fix the headers. Force to be https. Header edit Location ^https?://origin\.example\.com/(.*)$ https://proxy.example.com/$1 Header edit* Link https?://origin\.example\.com/ https://proxy.example.com/ </IfModule> ONLY for the IP of the PROXY server, rewrite any references in the HTML itself. This example is for a WordPress site. Stolen from WordPress filter to modify final html output 2a) Add a Must Use plugin to add a ‘final_output’ hook. Add a file in wp-content/mu-plugins/buffer.php: <?php /** * Output Buffering * * Buffers the entire WP process, capturing the final output for manipulation. */ ob_start(); add_action('shutdown', function() { $final = ''; // We'll need to get the number of ob levels we're in, so that we can iterate over each, collecting // that buffer's output into the final output. $levels = ob_get_level(); for ($i = 0; $i < $levels; $i++) { $final .= ob_get_clean(); } // Apply any filters to the final output echo apply_filters('final_output', $final); }, 0); ?> 2b) Add the following PHP to the wp-content/themes//functions.php. It uses the ‘final_output’ hook above. (PHP 5.3 or later required for use of anonymous function.) add_filter('final_output', function($output) { // IP of the proxy server $WWW_IP = “4.4.4.4”; //$WWW_IP = “4.4.2.2”; // My workstation, for testing purpose only if ($_SERVER[REMOTE_ADDR] == $WWW_IP) { // Force HTTPS when rewriting $output = str_replace('http://origin.example.com', 'https://proxy.example.com’, $output); // Catch anything that wasn’t a URL return str_replace(‘origin.example.com, 'proxy.example.com', $output); } return $output; }); If all goes well, you should now see the content from origin.example.com served from proxy.example.com. I'm still testing this, so if you find errors or omissions, please add a comment.
How to set up proxy in .htaccess
The Apache documentation states that RewriteRule and the should be put in the server configuration, but they can be put in htaccess because of shared hosting situations. I am in such a situation. I am trying to set up a transparent proxy: RewriteEngine On RewriteCond %{REQUEST_URI} ^/foo [OR] RewriteCond %{REQUEST_URI} ^/bar RewriteRule ^(.*)$ http://example.com/$1 [P] This is working fine...except for redirects (like if /foo redirects to /bar). Redirects go back to example.com, not my server. I understand the the ProxyPassReverse directive will solve this, but I get an "Internal Server Error" page when I add this to .htaccess Unlike the Rewrite directives, ProxyPassReverse will not work in htaccess. How do I set up a transparent proxy in shared hosting situation, or is this not possible? (This seems reasonable, since Rewrite already gets 80% of the way there, and having a transparent proxy in one htaccess would not interfere with having it in another.)
[ "Unfortunately, I'm fairly sure what you want to do isn't possible: I'm trying to do the exact same thing! From my research, I'm fairly confident it's not possible.\nPut simply, you need to use ProxyPassReverse, which is only available at a VirtualHost level (or similar); not a htaccess level.\nEdit: the only way I have achieved this is by also configuring the responding server/application to know it's behind a proxy, and serving pages appropriately. That is, I use .htaccess to redirect to another server as follows:\n RewriteEngine on\n RewriteRule (.*) http://localhost:8080/$1 [P,L] \n\nThen on the application server -- in this case, a JIRA installation -- I configured the Java Tomcat/Catalina appropriately to serve pages with the proxied information:\n proxyName=\"my.public.address.com\"\n proxyPort=\"80\"\n\nHowever, that's not completely transparent; the app server needs to serve pages in a proxied manner. It might be of some use, though.\n", "I managed to gather a few sources to figure out how to do this. I use a shared hosting provider, so I don't have access to server configuration (httpd.conf). I can only use .htaccess to accomplish the proxying. This example is for a WordPress site where I want most of the content served by origin.example.com, but will have some pages served locally, sort of like an overlay. You could go the other way and ONLY proxy specific subdirectories using different RewriteCond rules.\nThings to know:\n\nYou can’t use ProxyPass or ProxyPassReverse in .htaccess, so we have to use other methods to mimic what they do.\nYou can’t make proxy calls over HTTPS if SSLProxyEngine is not turned on by your provider, so you will lose some security if you have concerns about MITM attacks. If the origin server is internal, this may not be an issue. You could also use .htaccess on the origin server to enforce HTTPS from everywhere except the proxy server.\nYou need to rewrite headers\nYou need to rewrite the HTML that comes back from the origin server, and that needs to be done on the origin server. You can restrict it to certain IPs (i.e. the IP of the proxy) so it won’t break if you access it elsewhere.\n\nWhat I want:\nI want calls to proxy.example.com to serve content origin.example.com. In my case, I want to map everything with a few exceptions. If you only want to map a portion of your site, adjust your rules accordingly.\nHow to do it:\n\nConfigure the .htaccess file on proxy.example.com to proxy all URIs to origin.example.com. I want to be able to log into proxy.example.com, so I don’t rewrite /wp-admin or /wp-login.php. In my case, I have a /programs/ section that I want served by the proxy server itself (also a WordPress instance). Prevent looping by checking REDIRECT_STATUS.\n\n\n# I force everything coming into proxy.example.com to be HTTPS <IfModule mod_rewrite.c>\nRewriteEngine On\n\nRewriteCond %{HTTP:X-Forwarded-Proto} !https\nRewriteCond %{HTTPS} off\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule> <IfModule mod_proxy.c>\n# Redirect access for / (or any index) to the origin. NOTE target is http:// without SSLProxyEngine\nRewriteCond %{ENV:REDIRECT_STATUS} ^$\nRewriteRule ^(index\\.(php|html|cgi))?$ http://origin.example.com/ [P]\n\n# Do NOT redirect these patterns\nRewriteCond %{REQUEST_URI} !^/wp-admin/\nRewriteCond %{REQUEST_URI} !^/wp-login.php\nRewriteCond %{REQUEST_URI} !^/programs/\n\n# Redirect everything else. NOTE target is http:// without SSLProxyEngine\nRewriteCond %{ENV:REDIRECT_STATUS} ^$\nRewriteRule ^(.+)$ \"http://origin.example.com/$1\" [P]\n\n# Mimic ProxyPassReverse. Fix the headers. Force to be https.\nHeader edit Location ^https?://origin\\.example\\.com/(.*)$ https://proxy.example.com/$1\nHeader edit* Link https?://origin\\.example\\.com/ https://proxy.example.com/ </IfModule>\n\n\n\nONLY for the IP of the PROXY server, rewrite any references in the HTML itself. This example is for a WordPress site.\n\nStolen from WordPress filter to modify final html output\n2a) Add a Must Use plugin to add a ‘final_output’ hook. Add a file in wp-content/mu-plugins/buffer.php:\n\n<?php\n\n/** * Output Buffering * * Buffers the entire WP process, capturing\nthe final output for manipulation. */\n\nob_start();\n\nadd_action('shutdown', function() {\n $final = '';\n\n // We'll need to get the number of ob levels we're in, so that we can iterate over each, collecting\n // that buffer's output into the final output.\n $levels = ob_get_level();\n\n for ($i = 0; $i < $levels; $i++) {\n $final .= ob_get_clean();\n }\n\n // Apply any filters to the final output\n echo apply_filters('final_output', $final); }, 0); ?>\n\n\n2b) Add the following PHP to the wp-content/themes//functions.php. It uses the ‘final_output’ hook above. (PHP 5.3 or later required for use of anonymous function.)\n\nadd_filter('final_output', function($output) {\n // IP of the proxy server\n $WWW_IP = “4.4.4.4”; \n //$WWW_IP = “4.4.2.2”; // My workstation, for testing purpose only\n if ($_SERVER[REMOTE_ADDR] == $WWW_IP) {\n // Force HTTPS when rewriting\n $output = str_replace('http://origin.example.com', 'https://proxy.example.com’, $output);\n // Catch anything that wasn’t a URL\n return str_replace(‘origin.example.com, 'proxy.example.com', $output);\n }\n return $output;\n});\n\n\nIf all goes well, you should now see the content from origin.example.com served from proxy.example.com.\nI'm still testing this, so if you find errors or omissions, please add a comment.\n" ]
[ 24, 0 ]
[]
[]
[ ".htaccess", "apache", "proxy", "transparentproxy" ]
stackoverflow_0019205092_.htaccess_apache_proxy_transparentproxy.txt
Q: What's the meaning of 'trim' when use in mongoose? The link is http://mongoosejs.com/docs/api.html#schema_string_SchemaString-trim I'm beginner in mongoosejs. I just don't get it... I saw this question How to update mongoose default string schema property trim? but don't understand why trim. Im creating my first schema today like a 'hello world'. I saw this to https://stackoverflow.com/tags/trim/info ... but when i need to use it, i want to learn more about it. Im looking for an explanation for a beginner... A: It's basically there to ensure the strings you save through the schema are properly trimmed. If you add { type: String, trim: true } to a field in your schema, then trying to save strings like " hello", or "hello ", or " hello ", would end up being saved as "hello" in Mongo - i.e. white spaces will be removed from both sides of the string. A: Using trim will help in removing the white spaces present (beginning and ending of the string) in the string that you want to save to the DB like "ABC " , " ABC ", will be saved in the form "ABC" A: trim in mongoose use to remove the white spaces from the strings A: trim: true will remove leading and trailing whitespaces so something like " hello " will be saved as "hello"
What's the meaning of 'trim' when use in mongoose?
The link is http://mongoosejs.com/docs/api.html#schema_string_SchemaString-trim I'm beginner in mongoosejs. I just don't get it... I saw this question How to update mongoose default string schema property trim? but don't understand why trim. Im creating my first schema today like a 'hello world'. I saw this to https://stackoverflow.com/tags/trim/info ... but when i need to use it, i want to learn more about it. Im looking for an explanation for a beginner...
[ "It's basically there to ensure the strings you save through the schema are properly trimmed. If you add { type: String, trim: true } to a field in your schema, then trying to save strings like \" hello\", or \"hello \", or \" hello \", would end up being saved as \"hello\" in Mongo - i.e. white spaces will be removed from both sides of the string.\n", "Using trim will help in removing the white spaces present (beginning and ending of the string) in the string that you want to save to the DB like \n\"ABC \" , \" ABC \",\n\nwill be saved in the form \n\"ABC\"\n\n", "trim in mongoose use to remove the white spaces from the strings\n", "trim: true\n\nwill remove leading and trailing whitespaces\nso something like\n\n\" hello \"\n\nwill be saved as\n\n\"hello\"\n\n" ]
[ 114, 3, 0, 0 ]
[]
[]
[ "mongodb", "mongoose", "node.js", "trim" ]
stackoverflow_0020766360_mongodb_mongoose_node.js_trim.txt
Q: Use of int function in Python This code is working fine but I am confused why I only have to change age into an integer and not months, weeks or days. If I simply add age = 25, then it does not give any error. age = input("What is your current age? ") Years_remaining = Years_remaining = (90 - int(age)) months = Years_remaining * 12 weeks = Years_remaining * 52 days = Years_remaining * 365 print (f"you have {days} days, {weeks} weeks, and {months} months left") A: This is why: age is str as this is what the input method returns, therefore, you have to cast to int to subtract it to 90 and store it in Years_remaining. At this point, Years_remaining is an int, so months does not need any cast as both of its operands are now int (Years_remaining and 12). If for example, you would cast age to float, then months, weeks, etc would be a float as well. Does this make sense to you?
Use of int function in Python
This code is working fine but I am confused why I only have to change age into an integer and not months, weeks or days. If I simply add age = 25, then it does not give any error. age = input("What is your current age? ") Years_remaining = Years_remaining = (90 - int(age)) months = Years_remaining * 12 weeks = Years_remaining * 52 days = Years_remaining * 365 print (f"you have {days} days, {weeks} weeks, and {months} months left")
[ "This is why:\nage is str as this is what the input method returns, therefore, you have to cast to int to subtract it to 90 and store it in Years_remaining.\nAt this point, Years_remaining is an int, so months does not need any cast as both of its operands are now int (Years_remaining and 12).\nIf for example, you would cast age to float, then months, weeks, etc would be a float as well.\nDoes this make sense to you?\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074660044_python_python_3.x.txt
Q: Spring boot index page not mapped to / in Tomcat deployment Yet another issue with deploying Spring Boot WAR to Tomcat... I have read the dozen of similar questions but have not found any fix for my issue. I have a Spring Boot web app which is working fine when using the embedded tomcat web server (I can reach the index.html page using localhost:8080). However when I deploy the WAR to Tomcat (the war is called ROOT.war so am I deploying the app at Tomcat's root), localhost:8080 returns 404. I need to call localhost:8080/index.html to get an answer. I just cannot figure out why! pom.xml <modelVersion>4.0.0</modelVersion> <groupId>...</groupId> <artifactId>...</artifactId> <version>...</version> <packaging>war</packaging> <properties> <java.version>11</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.5</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> ... </dependencies> <build> <finalName>ROOT</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>com.github.eirslett</groupId> <artifactId>frontend-maven-plugin</artifactId> <version>1.12.1</version> <executions> ... </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project> Application.java @SpringBootApplication public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } I have one @RestController which does not override "/", and that's it. In the generated WAR, the index.html is located at the top level (so same level as WEB-INF). I also noticed that when Tomcat starts the web app, it prints: INFO ServletWebServerApplicationContext ServletWebServerApplicationContext.prepareWebApplicationContext(ServletWebServerApplicationContext.java:292) [main] Root WebApplicationContext: initialization completed in 1674 ms INFO WelcomePageHandlerMapping WelcomePageHandlerMapping.<init>(WelcomePageHandlerMapping.java:53) [main] Adding welcome page: ServletContext resource [/index.html] I find the second line strange: it looks like Spring Boot is choosing to default back to a WelcomePageHandlerMapping instead of using the expected spring boot context. No idea where that comes from. Maybe another indication: it does not print Initializing Spring embedded WebApplicationContext while this is printed when I start the app using the embedded Tomcat web server. But maybe it is fine if it is not there. Tomcat version: 9.0.65 Tomcat config: default config: did not change anything there since installation. Help! A: I could reproduce! With: Dockerfile: FROM tomcat:9.0.69-jre17-temurin-jammy ARG WAR_FILE=target/ROOT.war RUN addgroup --system tomcat \ && adduser --system --ingroup tomcat tomcat \ && chown -Rfh tomcat:tomcat $CATALINA_HOME USER tomcat:tomcat COPY ${WAR_FILE} $CATALINA_HOME/webapps/ CMD ["catalina.sh", "run"] pom.xml: <?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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <!-- max spring boot version for tomcat 9 (servlet-api): --> <version>2.7.6</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>traditional</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <description>Demo project for Spring Boot</description> <properties> <java.version>17</java.version> <!-- latest tomcat9 version, property controls spring dependency management: --> <tomcat.version>9.0.69</tomcat.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <finalName>ROOT</finalName> <!-- no spring-boot plugin!(?) --> </build> </project> App/Entry: package com.example.traditional; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class TraditionalApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(TraditionalApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(TraditionalApplication.class); } } (Some /custom controller, (mockMvc) tests) and a "static index.html" in src/main/webapp (maven war default): <html> <body> <h1>Hello</h1> Hello World! </body> </html> the (embedded tomcat) test succeeds: @WebMvcTest public class WebTest { @Autowired MockMvc mockMvc; @Test void testRoot() throws Exception { mockMvc .perform( get("/") ).andExpectAll( status().isOk(), forwardedUrl("index.html") ); } // ... } but after: mvn clean install \ && docker build -t my/tomcat9-app . \ && docker run -p 8080:8080 my/tomcat9-app, we get: 404 (tomcat error page) from http://localhost:8080 (http://localhost:8080/index.html, http://localhost:8080/custom work as expected ;(# Simplest Solution Move index.html from src/main/webapp to src/main/resources/static ! (stop running container, repeat mvn clean install && docker build ... && docker run);p #
Spring boot index page not mapped to / in Tomcat deployment
Yet another issue with deploying Spring Boot WAR to Tomcat... I have read the dozen of similar questions but have not found any fix for my issue. I have a Spring Boot web app which is working fine when using the embedded tomcat web server (I can reach the index.html page using localhost:8080). However when I deploy the WAR to Tomcat (the war is called ROOT.war so am I deploying the app at Tomcat's root), localhost:8080 returns 404. I need to call localhost:8080/index.html to get an answer. I just cannot figure out why! pom.xml <modelVersion>4.0.0</modelVersion> <groupId>...</groupId> <artifactId>...</artifactId> <version>...</version> <packaging>war</packaging> <properties> <java.version>11</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.5</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> ... </dependencies> <build> <finalName>ROOT</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>com.github.eirslett</groupId> <artifactId>frontend-maven-plugin</artifactId> <version>1.12.1</version> <executions> ... </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project> Application.java @SpringBootApplication public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } I have one @RestController which does not override "/", and that's it. In the generated WAR, the index.html is located at the top level (so same level as WEB-INF). I also noticed that when Tomcat starts the web app, it prints: INFO ServletWebServerApplicationContext ServletWebServerApplicationContext.prepareWebApplicationContext(ServletWebServerApplicationContext.java:292) [main] Root WebApplicationContext: initialization completed in 1674 ms INFO WelcomePageHandlerMapping WelcomePageHandlerMapping.<init>(WelcomePageHandlerMapping.java:53) [main] Adding welcome page: ServletContext resource [/index.html] I find the second line strange: it looks like Spring Boot is choosing to default back to a WelcomePageHandlerMapping instead of using the expected spring boot context. No idea where that comes from. Maybe another indication: it does not print Initializing Spring embedded WebApplicationContext while this is printed when I start the app using the embedded Tomcat web server. But maybe it is fine if it is not there. Tomcat version: 9.0.65 Tomcat config: default config: did not change anything there since installation. Help!
[ "I could reproduce!\nWith:\n\nDockerfile:\nFROM tomcat:9.0.69-jre17-temurin-jammy\nARG WAR_FILE=target/ROOT.war\nRUN addgroup --system tomcat \\\n && adduser --system --ingroup tomcat tomcat \\\n && chown -Rfh tomcat:tomcat $CATALINA_HOME\nUSER tomcat:tomcat\nCOPY ${WAR_FILE} $CATALINA_HOME/webapps/\nCMD [\"catalina.sh\", \"run\"]\n\n\npom.xml:\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 <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <!-- max spring boot version for tomcat 9 (servlet-api): -->\n <version>2.7.6</version> \n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n <groupId>com.example</groupId>\n <artifactId>traditional</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>war</packaging>\n <description>Demo project for Spring Boot</description>\n <properties>\n <java.version>17</java.version>\n <!-- latest tomcat9 version, property controls spring dependency management: -->\n <tomcat.version>9.0.69</tomcat.version> \n </properties>\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-tomcat</artifactId>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>\n <build>\n <finalName>ROOT</finalName>\n <!-- no spring-boot plugin!(?) -->\n </build>\n</project>\n\n\nApp/Entry:\npackage com.example.traditional;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.builder.SpringApplicationBuilder;\nimport org.springframework.boot.web.servlet.support.SpringBootServletInitializer;\n\n@SpringBootApplication\npublic class TraditionalApplication extends SpringBootServletInitializer {\n public static void main(String[] args) {\n SpringApplication.run(TraditionalApplication.class, args);\n }\n @Override\n protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {\n return builder.sources(TraditionalApplication.class);\n }\n}\n\n\n(Some /custom controller, (mockMvc) tests)\nand a \"static index.html\" in src/main/webapp (maven war default):\n<html>\n <body>\n <h1>Hello</h1>\n Hello World!\n </body>\n</html>\n\n\nthe (embedded tomcat) test succeeds:\n@WebMvcTest\npublic class WebTest {\n\n @Autowired\n MockMvc mockMvc;\n\n @Test\n void testRoot() throws Exception {\n mockMvc\n .perform(\n get(\"/\")\n ).andExpectAll(\n status().isOk(),\n forwardedUrl(\"index.html\")\n );\n } // ...\n}\n\n\nbut after:\n\nmvn clean install \\\n&& docker build -t my/tomcat9-app . \\\n&& docker run -p 8080:8080 my/tomcat9-app,\n\n\nwe get:\n\n404 (tomcat error page) from http://localhost:8080\n(http://localhost:8080/index.html, http://localhost:8080/custom work as expected ;(#\n\n\n\nSimplest Solution\nMove index.html from src/main/webapp to src/main/resources/static ! (stop running container, repeat mvn clean install && docker build ... && docker run);p #\n" ]
[ 0 ]
[]
[]
[ "spring_boot", "tomcat9" ]
stackoverflow_0074653930_spring_boot_tomcat9.txt
Q: Get null value after filled value in SQL I need to perform a count of how many records in the Accounts ids column had a null value in the Lead Source column, after having a Valid LeadSource (valid LeadSource is just a LeadSource not null) There are same Account ID and exists values null and not null I need count values null that exists another values not null. Table that exists values null and not null for same account ID I try with CTE and subquery but I can't reach result expectated. A: try this query : select account_id, sum(case when leadsource is null then 1 else 0 end) as null_count, sum(case when leadsource is not null then 1 else 1 end) as not_null_count from table_name group by account_id
Get null value after filled value in SQL
I need to perform a count of how many records in the Accounts ids column had a null value in the Lead Source column, after having a Valid LeadSource (valid LeadSource is just a LeadSource not null) There are same Account ID and exists values null and not null I need count values null that exists another values not null. Table that exists values null and not null for same account ID I try with CTE and subquery but I can't reach result expectated.
[ "try this query :\nselect account_id,\nsum(case when leadsource is null then 1 else 0 end) as null_count,\nsum(case when leadsource is not null then 1 else 1 end) as not_null_count\nfrom table_name group by account_id\n\n" ]
[ 0 ]
[]
[]
[ "count", "databricks", "sql" ]
stackoverflow_0074658356_count_databricks_sql.txt
Q: How to create custom CSS for dynamic-named DIV I want to restrict content height of external DIV loaded to website through ad, it is too big and I want to limit height of that div element. Issue is that every time on refresh, that DIV has new name, for example: First load: <div id="vdzw_9waM"></div> Second load: <div id="vdzw_6tzW"></div> Third load: <div id="vdzw_2tpSd"></div> and so on... Any idea how to override this? Thank you I tried common CSS, but because div id is dynamically populated every time with different name, I could not implement any CSS rule. EDIT: I tried to manipulate with CSS of the element which contains this ID, but no success...only impact on CSS which changes layout of this ID is to change CSS of this particular ID A: If the id pattern is consistent-- as it is in the examples you supplied-- you could apply your styles by partial id match: div[id^='vdzw'] { max-height: 500px; } That selector will apply the max-height to all div elements that have an id starting with (^=) "vdzw". A more reliable way is to ensure your ads get rendered into a container that you define, and then set the styles based on selectors that identify the container you've defined.
How to create custom CSS for dynamic-named DIV
I want to restrict content height of external DIV loaded to website through ad, it is too big and I want to limit height of that div element. Issue is that every time on refresh, that DIV has new name, for example: First load: <div id="vdzw_9waM"></div> Second load: <div id="vdzw_6tzW"></div> Third load: <div id="vdzw_2tpSd"></div> and so on... Any idea how to override this? Thank you I tried common CSS, but because div id is dynamically populated every time with different name, I could not implement any CSS rule. EDIT: I tried to manipulate with CSS of the element which contains this ID, but no success...only impact on CSS which changes layout of this ID is to change CSS of this particular ID
[ "If the id pattern is consistent-- as it is in the examples you supplied-- you could apply your styles by partial id match:\ndiv[id^='vdzw'] {\n max-height: 500px;\n}\n\nThat selector will apply the max-height to all div elements that have an id starting with (^=) \"vdzw\".\nA more reliable way is to ensure your ads get rendered into a container that you define, and then set the styles based on selectors that identify the container you've defined.\n" ]
[ 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074660219_css_html.txt
Q: Jetpack Compose Breaking GSON I have an working Android project whenever I add Jetpack Compose Dependencies my GSON is not working as expected. The Strange things if I remove excludeFieldsWithModifiers or if I don't use any inheritance for the classes which I am parsing using GSON then it's working. Steps to Reproduce: Add Jetpack Compose Runtime or Jetpack Compose Dependencies Add GSON Dependencies Use GsonBuilder to create GSON Object and add excludeFieldsWithModifiers option Create a simple class hierarchy Try to parse any json using to Child class which you have created above using the same GSON Object (Created in Step 3) For Illustration purpose I am adding one sample class Response(@SerializedName("id") var id : Int = 0) : BaseResponse() open class BaseResponse val gsonMapper: Gson by lazy { GsonBuilder() .excludeFieldsWithModifiers( java.lang.reflect.Modifier.TRANSIENT. // Can you any other modifier ) .create() } fun responseProcess() { try { val response = """{"id": 3}""" val data = gsonMapper.fromJson(response, Response::class.java) Log.d(TAG, "responseProcess: $data") } catch (e: Exception) { e.printStackTrace() } } StackTrace for the above Code 2022-11-30 18:14:12.162 14856-14856/com.bhaskar.myapplication W/System.err: java.lang.IllegalArgumentException: class com.bhaskar.myapplication.Response declares multiple JSON fields named $stable 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:172) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.Gson.getAdapter(Gson.java:458) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.Gson.fromJson(Gson.java:926) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.Gson.fromJson(Gson.java:892) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.Gson.fromJson(Gson.java:841) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.Gson.fromJson(Gson.java:813) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.bhaskar.myapplication.MainActivityKt.responseProcess(MainActivity.kt:74) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.bhaskar.myapplication.MainActivityKt$Greeting$1$1.invoke(MainActivity.kt:54) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.bhaskar.myapplication.MainActivityKt$Greeting$1$1.invoke(MainActivity.kt:53) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.foundation.ClickableKt$clickable$4$gesture$1$2.invoke-k-4lQ0M(Clickable.kt:153) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.foundation.ClickableKt$clickable$4$gesture$1$2.invoke(Clickable.kt:142) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.foundation.gestures.TapGestureDetectorKt$detectTapAndPress$2$1$1.invokeSuspend(TapGestureDetector.kt:223) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.DispatchedTaskKt.resume(DispatchedTask.kt:178) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.DispatchedTaskKt.dispatch(DispatchedTask.kt:166) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.CancellableContinuationImpl.dispatchResume(CancellableContinuationImpl.kt:397) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.CancellableContinuationImpl.resumeImpl(CancellableContinuationImpl.kt:431) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.CancellableContinuationImpl.resumeImpl$default(CancellableContinuationImpl.kt:420) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.CancellableContinuationImpl.resumeWith(CancellableContinuationImpl.kt:328) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.SuspendingPointerInputFilter$PointerEventHandlerCoroutine.offerPointerEvent(SuspendingPointerInputFilter.kt:511) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.SuspendingPointerInputFilter.dispatchPointerEvent(SuspendingPointerInputFilter.kt:406) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.SuspendingPointerInputFilter.onPointerEvent-H0pRuoY(SuspendingPointerInputFilter.kt:419) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.Node.dispatchMainEventPass(HitPathTracker.kt:310) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.Node.dispatchMainEventPass(HitPathTracker.kt:297) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.Node.dispatchMainEventPass(HitPathTracker.kt:297) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.NodeParent.dispatchMainEventPass(HitPathTracker.kt:179) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.HitPathTracker.dispatchChanges(HitPathTracker.kt:98) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.PointerInputEventProcessor.process-BIzXfog(PointerInputEventProcessor.kt:80) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.platform.AndroidComposeView.sendMotionEvent-8iAsVTc(AndroidComposeView.android.kt:1159) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.platform.AndroidComposeView.handleMotionEvent-8iAsVTc(AndroidComposeView.android.kt:1109) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.platform.AndroidComposeView.dispatchTouchEvent(AndroidComposeView.android.kt:1059) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3920) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3594) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3920) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3594) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3920) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3594) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3920) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3594) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:915) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1957) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.app.Activity.dispatchTouchEvent(Activity.java:4182) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:873) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.View.dispatchPointerEvent(View.java:15458) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:7457) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:7233) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6595) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:6652) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:6618) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:6786) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:6626) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:6843) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6599) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:6652) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:6618) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:6626) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6599) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:9880) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:9718) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:9671) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:10014) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:220) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.os.MessageQueue.nativePollOnce(Native Method) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at android.os.MessageQueue.next(MessageQueue.java:335) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at android.os.Looper.loop(Looper.java:206) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8633) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at java.lang.reflect.Method.invoke(Native Method) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130) Thank You A: By calling excludeFieldsWithModifiers you overwrite the default modifier exclusions. Therefore now you (accidentally?) include static fields, and $stable seems to be a synthetic field added by the compiler (not sure though why Gson is not detecting that it is synthetic). You can solve this by adding Modifier.STATIC to the modifiers as well: excludeFieldsWithModifiers(Modifier.TRANSIENT or Modifier.STATIC) (though note that this is effectively the same as the default Gson field exclusion) If you need to serialize static fields for some reason, then you might have to write a custom ExclusionStrategy to ignore the unwanted $stable field.
Jetpack Compose Breaking GSON
I have an working Android project whenever I add Jetpack Compose Dependencies my GSON is not working as expected. The Strange things if I remove excludeFieldsWithModifiers or if I don't use any inheritance for the classes which I am parsing using GSON then it's working. Steps to Reproduce: Add Jetpack Compose Runtime or Jetpack Compose Dependencies Add GSON Dependencies Use GsonBuilder to create GSON Object and add excludeFieldsWithModifiers option Create a simple class hierarchy Try to parse any json using to Child class which you have created above using the same GSON Object (Created in Step 3) For Illustration purpose I am adding one sample class Response(@SerializedName("id") var id : Int = 0) : BaseResponse() open class BaseResponse val gsonMapper: Gson by lazy { GsonBuilder() .excludeFieldsWithModifiers( java.lang.reflect.Modifier.TRANSIENT. // Can you any other modifier ) .create() } fun responseProcess() { try { val response = """{"id": 3}""" val data = gsonMapper.fromJson(response, Response::class.java) Log.d(TAG, "responseProcess: $data") } catch (e: Exception) { e.printStackTrace() } } StackTrace for the above Code 2022-11-30 18:14:12.162 14856-14856/com.bhaskar.myapplication W/System.err: java.lang.IllegalArgumentException: class com.bhaskar.myapplication.Response declares multiple JSON fields named $stable 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:172) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.Gson.getAdapter(Gson.java:458) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.Gson.fromJson(Gson.java:926) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.Gson.fromJson(Gson.java:892) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.Gson.fromJson(Gson.java:841) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.google.gson.Gson.fromJson(Gson.java:813) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.bhaskar.myapplication.MainActivityKt.responseProcess(MainActivity.kt:74) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.bhaskar.myapplication.MainActivityKt$Greeting$1$1.invoke(MainActivity.kt:54) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at com.bhaskar.myapplication.MainActivityKt$Greeting$1$1.invoke(MainActivity.kt:53) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.foundation.ClickableKt$clickable$4$gesture$1$2.invoke-k-4lQ0M(Clickable.kt:153) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.foundation.ClickableKt$clickable$4$gesture$1$2.invoke(Clickable.kt:142) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.foundation.gestures.TapGestureDetectorKt$detectTapAndPress$2$1$1.invokeSuspend(TapGestureDetector.kt:223) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.DispatchedTaskKt.resume(DispatchedTask.kt:178) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.DispatchedTaskKt.dispatch(DispatchedTask.kt:166) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.CancellableContinuationImpl.dispatchResume(CancellableContinuationImpl.kt:397) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.CancellableContinuationImpl.resumeImpl(CancellableContinuationImpl.kt:431) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.CancellableContinuationImpl.resumeImpl$default(CancellableContinuationImpl.kt:420) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at kotlinx.coroutines.CancellableContinuationImpl.resumeWith(CancellableContinuationImpl.kt:328) 2022-11-30 18:14:12.163 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.SuspendingPointerInputFilter$PointerEventHandlerCoroutine.offerPointerEvent(SuspendingPointerInputFilter.kt:511) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.SuspendingPointerInputFilter.dispatchPointerEvent(SuspendingPointerInputFilter.kt:406) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.SuspendingPointerInputFilter.onPointerEvent-H0pRuoY(SuspendingPointerInputFilter.kt:419) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.Node.dispatchMainEventPass(HitPathTracker.kt:310) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.Node.dispatchMainEventPass(HitPathTracker.kt:297) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.Node.dispatchMainEventPass(HitPathTracker.kt:297) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.NodeParent.dispatchMainEventPass(HitPathTracker.kt:179) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.HitPathTracker.dispatchChanges(HitPathTracker.kt:98) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.input.pointer.PointerInputEventProcessor.process-BIzXfog(PointerInputEventProcessor.kt:80) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.platform.AndroidComposeView.sendMotionEvent-8iAsVTc(AndroidComposeView.android.kt:1159) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.platform.AndroidComposeView.handleMotionEvent-8iAsVTc(AndroidComposeView.android.kt:1109) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at androidx.compose.ui.platform.AndroidComposeView.dispatchTouchEvent(AndroidComposeView.android.kt:1059) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3920) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3594) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3920) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3594) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3920) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3594) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3920) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3594) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:915) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1957) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at android.app.Activity.dispatchTouchEvent(Activity.java:4182) 2022-11-30 18:14:12.164 14856-14856/com.bhaskar.myapplication W/System.err: at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:873) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.View.dispatchPointerEvent(View.java:15458) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:7457) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:7233) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6595) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:6652) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:6618) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:6786) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:6626) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:6843) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6599) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:6652) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:6618) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:6626) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6599) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:9880) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:9718) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:9671) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:10014) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:220) 2022-11-30 18:14:12.165 14856-14856/com.bhaskar.myapplication W/System.err: at android.os.MessageQueue.nativePollOnce(Native Method) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at android.os.MessageQueue.next(MessageQueue.java:335) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at android.os.Looper.loop(Looper.java:206) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8633) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at java.lang.reflect.Method.invoke(Native Method) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602) 2022-11-30 18:14:12.166 14856-14856/com.bhaskar.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130) Thank You
[ "By calling excludeFieldsWithModifiers you overwrite the default modifier exclusions. Therefore now you (accidentally?) include static fields, and $stable seems to be a synthetic field added by the compiler (not sure though why Gson is not detecting that it is synthetic).\nYou can solve this by adding Modifier.STATIC to the modifiers as well:\nexcludeFieldsWithModifiers(Modifier.TRANSIENT or Modifier.STATIC)\n\n(though note that this is effectively the same as the default Gson field exclusion)\nIf you need to serialize static fields for some reason, then you might have to write a custom ExclusionStrategy to ignore the unwanted $stable field.\n" ]
[ 1 ]
[]
[]
[ "android", "android_jetpack_compose", "gson", "kotlin" ]
stackoverflow_0074628558_android_android_jetpack_compose_gson_kotlin.txt
Q: How to get the ID of an element with class name with BS4 I have a site where there are multiple li elements whos ID I need but I only have the class name. I also need the IDs to be put into a list The html: <ul class="price-list"> <li class="price-box" id="200"></li> <li class="price-box" id="300"></li> <li class="price-box" id="400"></li> </ul> I have tried the following but to no avail list = [] div = soup.find("ul", {"class": "price-list"}) for size in div: id = soup.find_all("li", {"class": "price-box"})['id'] list.append(id)
How to get the ID of an element with class name with BS4
I have a site where there are multiple li elements whos ID I need but I only have the class name. I also need the IDs to be put into a list The html: <ul class="price-list"> <li class="price-box" id="200"></li> <li class="price-box" id="300"></li> <li class="price-box" id="400"></li> </ul> I have tried the following but to no avail list = [] div = soup.find("ul", {"class": "price-list"}) for size in div: id = soup.find_all("li", {"class": "price-box"})['id'] list.append(id)
[]
[]
[ "import requests\nimport bs4\n\nresult = requests.get(\"url\")\nsoup = bs4.BeautifulSoup(result.text,\"html.parser\")\nclass_name = \"the class name\"\ndivs = soup.find_all(\"div\", {'class':class_name})\n# this will give you a list of divs with the class name\n# if you want to find the first div the soup find or you are looking for a unique class name\ndiv = soup.find(\"div\", {\"class\": class_name})\n# also you can do it like this\ndiv = soup.find(\"div\", class_= class_name)\n\n" ]
[ -1 ]
[ "beautifulsoup", "python", "python_requests" ]
stackoverflow_0074660222_beautifulsoup_python_python_requests.txt
Q: Setting up username and password for npm registry URL I am trying to use npm to install a package from url : http://host:80 I did the following: npm config set strict-ssl false npm config set registry "<>" npm --proxy http://host:port install <> (our proxy does not require authentication) When I tired to run above install package command it throws npm ERR! code E401 npm ERR! 401 Authorization Required: @latest When I should I set the username and pwd for registry url.I googled and found that registry url and details are part of .npmrc file. Currently it has strict-ssl=false registry=<>enter code here Should I add username and password here in this file ? If so can you give me the format or how to add it or where to add it.Thank you. A: If you want to auth to your NPM registry (like Artifactory) You can provide the login details as below at runtime npm login Alternatively you can paste following in the .npmrc file. _auth = <USERNAME>:<PASSWORD> (converted to base 64) email = [email protected] always-auth = true If you are getting any SSL issues you can add following to disable SSL strict-ssl=false If you want to configure proxy settings npm config set proxy http://"username:mystrongpassword"@proxy.mycompany.com:PORT npm config set https-proxy http://"username:mystrongpassword"@proxy.mycompany.com:PORT A: You can set separate profile(s) for the secondary registry, in your case http://host:80 using npmrc tool. First install npmrc globally on your machine with: npm i npmrc -g Make sure installation went fine, by listing all available profiles: npmrc It should show your default profile. Add a separate profile, so you can customise your registry hostname, with: npmrc -c work where work can be any preferable name for your profile. Select it with: npmrc work Then add your specific hostname with: npm config set registry http://host:80 Finally add user with credentials and email, using: npm adduser It will prompt you for all needed data. To switch back to default profile (with default npm registry), you can use: npmrc default
Setting up username and password for npm registry URL
I am trying to use npm to install a package from url : http://host:80 I did the following: npm config set strict-ssl false npm config set registry "<>" npm --proxy http://host:port install <> (our proxy does not require authentication) When I tired to run above install package command it throws npm ERR! code E401 npm ERR! 401 Authorization Required: @latest When I should I set the username and pwd for registry url.I googled and found that registry url and details are part of .npmrc file. Currently it has strict-ssl=false registry=<>enter code here Should I add username and password here in this file ? If so can you give me the format or how to add it or where to add it.Thank you.
[ "If you want to auth to your NPM registry (like Artifactory)\nYou can provide the login details as below at runtime \nnpm login\n\nAlternatively you can paste following in the .npmrc file.\n_auth = <USERNAME>:<PASSWORD> (converted to base 64)\nemail = [email protected]\nalways-auth = true\n\nIf you are getting any SSL issues you can add following to disable SSL\nstrict-ssl=false\n\nIf you want to configure proxy settings\nnpm config set proxy http://\"username:mystrongpassword\"@proxy.mycompany.com:PORT\nnpm config set https-proxy http://\"username:mystrongpassword\"@proxy.mycompany.com:PORT\n\n", "You can set separate profile(s) for the secondary registry, in your case http://host:80 using npmrc tool.\nFirst install npmrc globally on your machine with:\nnpm i npmrc -g\n\nMake sure installation went fine, by listing all available profiles:\nnpmrc\n\nIt should show your default profile.\nAdd a separate profile, so you can customise your registry hostname, with:\nnpmrc -c work\n\nwhere work can be any preferable name for your profile.\nSelect it with:\nnpmrc work\n\nThen add your specific hostname with:\nnpm config set registry http://host:80\n\nFinally add user with credentials and email, using:\nnpm adduser\n\nIt will prompt you for all needed data.\nTo switch back to default profile (with default npm registry), you can use:\nnpmrc default\n\n" ]
[ 7, 0 ]
[]
[]
[ "node.js", "npm", "npm_config", "npm_install", "npm_registry" ]
stackoverflow_0050612549_node.js_npm_npm_config_npm_install_npm_registry.txt
Q: Acumatica - Override ConvertQuoteToProject to include custom fields I am trying to override the base method ConvertQuoteToProject in PMQuoteMaint so that I can add our custom fields from the Project that are required. Currently with the required fields in Project, we cannot convert the Quote. Partial Snippet: public virtual void ConvertQuoteToProject(PMQuote row, ConvertToProjectFilter settings) { if (!ValidateQuoteBeforeConvertToProject(row)) { throw new PXException(Messages.QuoteConversionFailed); } ProjectEntry projectEntry = CreateInstance<ProjectEntry>(); projectEntry.Clear(); PMProject project = new PMProject(); project.BaseType = PMProject.ProjectBaseType.Project; CM.CurrencyInfo info = PXSelect<CM.CurrencyInfo, Where<CurrencyInfo.curyInfoID, Equal<Current<PMQuote.curyInfoID>>>>.Select(this); info.CuryInfoID = null; info = (CM.CurrencyInfo)projectEntry.Caches<CM.CurrencyInfo>().Insert(info); project.CuryID = row.CuryID; project.CuryInfoID = info.CuryInfoID; project.RateTypeID = info.CuryRateTypeID; if (!DimensionMaint.IsAutonumbered(this, ProjectAttribute.DimensionName)) project.ContractCD = row.QuoteProjectCD; project = projectEntry.Project.Insert(project); project.CustomerID = row.BAccountID; if (row.LocationID != null) project.LocationID = row.LocationID; if (row.TermsID != null) project.TermsID = row.TermsID; project.QuoteNbr = row.QuoteNbr; project.UsrOffice = row.UsrOffice; project.UsrBuildingtype = row.UsrBuildingtype; project.UsrProjAdmin = row.UsrProjAdmin; project.UsrProjectManager = row.UsrProjectManager; project = projectEntry.Project.Update(project); In a customization, even trying a simple override of the method throws this error: Method Void ConvertQuoteToProject(PX.Objects.PM.PMQuote, ConvertToProjectFilter, ConvertQuoteToProjectDelegate) in graph extension is marked as [PXOverride], but its signature is not compatible with original method Customization Code: public delegate void ConvertQuoteToProjectDelegate(PMQuote row, ConvertToProjectFilter settings); [PXOverride] public void ConvertQuoteToProject(PMQuote row, ConvertToProjectFilter settings, ConvertQuoteToProjectDelegate baseMethod) { baseMethod(row,settings); } A: The best way to accomplish this would be to trap the event that ties the two together and update additional fields. In that function there is this block: project.CustomerID = row.BAccountID; if (row.LocationID != null) project.LocationID = row.LocationID; if (row.TermsID != null) project.TermsID = row.TermsID; project.QuoteNbr = row.QuoteNbr; project = projectEntry.Project.Update(project); You could do a graph extension of the project entry and tie to updating quoteNbr, the foreign key. public virtual void _(Events.FieldUpdated<PMProject.quoteNbr> e, PXFieldUpdated del) { del?.Invoke(e.Cache, e.Args); string QuoteNbr = (string)e.NewValue; //Get the quote var Quote = PMQuote.PK.Find(Base, QuoteNbr); if (Quote != null) { //get your dac extension PMQuoteExt quoteExt = Quote.GetExtension<PMQuoteExt>(); //now set values based on your extension e.Cache.SetValueExt<PMProjectExt.field>(e.Row, ext.field); } }
Acumatica - Override ConvertQuoteToProject to include custom fields
I am trying to override the base method ConvertQuoteToProject in PMQuoteMaint so that I can add our custom fields from the Project that are required. Currently with the required fields in Project, we cannot convert the Quote. Partial Snippet: public virtual void ConvertQuoteToProject(PMQuote row, ConvertToProjectFilter settings) { if (!ValidateQuoteBeforeConvertToProject(row)) { throw new PXException(Messages.QuoteConversionFailed); } ProjectEntry projectEntry = CreateInstance<ProjectEntry>(); projectEntry.Clear(); PMProject project = new PMProject(); project.BaseType = PMProject.ProjectBaseType.Project; CM.CurrencyInfo info = PXSelect<CM.CurrencyInfo, Where<CurrencyInfo.curyInfoID, Equal<Current<PMQuote.curyInfoID>>>>.Select(this); info.CuryInfoID = null; info = (CM.CurrencyInfo)projectEntry.Caches<CM.CurrencyInfo>().Insert(info); project.CuryID = row.CuryID; project.CuryInfoID = info.CuryInfoID; project.RateTypeID = info.CuryRateTypeID; if (!DimensionMaint.IsAutonumbered(this, ProjectAttribute.DimensionName)) project.ContractCD = row.QuoteProjectCD; project = projectEntry.Project.Insert(project); project.CustomerID = row.BAccountID; if (row.LocationID != null) project.LocationID = row.LocationID; if (row.TermsID != null) project.TermsID = row.TermsID; project.QuoteNbr = row.QuoteNbr; project.UsrOffice = row.UsrOffice; project.UsrBuildingtype = row.UsrBuildingtype; project.UsrProjAdmin = row.UsrProjAdmin; project.UsrProjectManager = row.UsrProjectManager; project = projectEntry.Project.Update(project); In a customization, even trying a simple override of the method throws this error: Method Void ConvertQuoteToProject(PX.Objects.PM.PMQuote, ConvertToProjectFilter, ConvertQuoteToProjectDelegate) in graph extension is marked as [PXOverride], but its signature is not compatible with original method Customization Code: public delegate void ConvertQuoteToProjectDelegate(PMQuote row, ConvertToProjectFilter settings); [PXOverride] public void ConvertQuoteToProject(PMQuote row, ConvertToProjectFilter settings, ConvertQuoteToProjectDelegate baseMethod) { baseMethod(row,settings); }
[ "The best way to accomplish this would be to trap the event that ties the two together and update additional fields.\nIn that function there is this block:\n project.CustomerID = row.BAccountID;\n if (row.LocationID != null)\n project.LocationID = row.LocationID;\n if (row.TermsID != null)\n project.TermsID = row.TermsID;\n project.QuoteNbr = row.QuoteNbr;\n project = projectEntry.Project.Update(project);\n\nYou could do a graph extension of the project entry and tie to updating quoteNbr, the foreign key.\n public virtual void _(Events.FieldUpdated<PMProject.quoteNbr> e, PXFieldUpdated del)\n {\n del?.Invoke(e.Cache, e.Args);\n string QuoteNbr = (string)e.NewValue;\n //Get the quote\n var Quote = PMQuote.PK.Find(Base, QuoteNbr);\n if (Quote != null)\n {\n //get your dac extension\n PMQuoteExt quoteExt = Quote.GetExtension<PMQuoteExt>();\n //now set values based on your extension \n e.Cache.SetValueExt<PMProjectExt.field>(e.Row, ext.field);\n }\n }\n\n" ]
[ 0 ]
[]
[]
[ "acumatica", "c#" ]
stackoverflow_0074536072_acumatica_c#.txt
Q: cursor in mysql for row having multiple values in it I have table emails_grouping in that I have one column named 'to_ids' this column contains multiple employee Id's . Now I want to change that Id's with respective employee names. employee data is in employee table. this is in mysql. I tried multiple ways but I'm not able to replace id's with names because , that 'to_ids' column contains multiple 'Ids'. description to_ids 'Inactive Employees with missing Last working day', '11041,11109,899,13375,1715,1026' above is the column which I want to change Id's with employee names. A: This problem should demonstrate to you why it's a bad idea to store "lists" of id's like you're doing. You should instead store one id per row. You can join to your employee table like this: SELECT e.name FROM emails_grouping AS g JOIN employee AS e ON FIND_IN_SET(e.id, g.to_ids) WHERE g.description = 'Inactive Employees with missing Last working day'; But be aware that joining using a function like this is not possible to optimize. It will have very slow performance, because it can't look up the respective employee id's using an index. It has to do a table-scan of the employee table, and evaluate the id's against your comma-separated list one by one. This is just one reason why using comma-separated lists instead of normal columns is trouble. See my answer to Is storing a delimited list in a database column really that bad?
cursor in mysql for row having multiple values in it
I have table emails_grouping in that I have one column named 'to_ids' this column contains multiple employee Id's . Now I want to change that Id's with respective employee names. employee data is in employee table. this is in mysql. I tried multiple ways but I'm not able to replace id's with names because , that 'to_ids' column contains multiple 'Ids'. description to_ids 'Inactive Employees with missing Last working day', '11041,11109,899,13375,1715,1026' above is the column which I want to change Id's with employee names.
[ "This problem should demonstrate to you why it's a bad idea to store \"lists\" of id's like you're doing. You should instead store one id per row.\nYou can join to your employee table like this:\nSELECT e.name\nFROM emails_grouping AS g\nJOIN employee AS e\n ON FIND_IN_SET(e.id, g.to_ids)\nWHERE g.description = 'Inactive Employees with missing Last working day';\n\nBut be aware that joining using a function like this is not possible to optimize. It will have very slow performance, because it can't look up the respective employee id's using an index. It has to do a table-scan of the employee table, and evaluate the id's against your comma-separated list one by one.\nThis is just one reason why using comma-separated lists instead of normal columns is trouble. See my answer to Is storing a delimited list in a database column really that bad?\n" ]
[ 0 ]
[]
[]
[ "cursor", "database", "inner_join", "join", "mysql" ]
stackoverflow_0074660232_cursor_database_inner_join_join_mysql.txt
Q: DevExtreme DataGrid row right click Does anyone know how to handle the right-click event on Datagrid? I look in the document but found nothing. A: You need to add a ContextMenuStrip componen. Once added the ContextMenuStrip componen in the gridview you look for the ContextMenuStrip property and specify the one you added. To the ContextMenuStrip you add the options you need for example edit or delete. To each button you add a click event and use the following code: private void EditToolStripMenuItem_Click(object sender, EventArgs e) { //With this code we retrieve the information from the table where the right click was executed var info = gridview1.GetFocusedRow(); code.... } PS: C# code. Please specify what language you work in when you ask a question Sorry for my English, but my native language is Spanish.
DevExtreme DataGrid row right click
Does anyone know how to handle the right-click event on Datagrid? I look in the document but found nothing.
[ "You need to add a ContextMenuStrip componen.\nOnce added the ContextMenuStrip componen in the gridview you look for the ContextMenuStrip property and specify the one you added.\nTo the ContextMenuStrip you add the options you need for example edit or delete.\nTo each button you add a click event and use the following code:\nprivate void EditToolStripMenuItem_Click(object sender, EventArgs e)\n{\n //With this code we retrieve the information from the table where the right click was executed\n var info = gridview1.GetFocusedRow();\n\n code....\n}\n\nPS:\nC# code.\nPlease specify what language you work in when you ask a question\nSorry for my English, but my native language is Spanish.\n" ]
[ 0 ]
[]
[]
[ "devexpress", "devextreme" ]
stackoverflow_0074624966_devexpress_devextreme.txt
Q: How to use the gRPC tools to generate code I've read the tutorial and I'm able to generate the .cs file but it doesn't include any of my service or rpc definitions. I've added protoc to my PATH and from inside the project directory. protoc project1.proto --csharp_out="C:\output" --plugin=protoc-gen-grpc="c:\Users\me\.nuget\packages\grpc.tools\1.8.0\tools\windows_x64\grpc_csharp_plugin.exe" No errors output in console A: You need to add the --grpc_out command line option, e.g. add --grpc_out="C:\output\" Note that it won't write any files if you don't have any services. Here's a complete example. From a root directory, create: An empty output directory A tools directory with protoc.exe and grpc_csharp_plugin.exe A protos directory with test.proto as shown below: test.proto: syntax = "proto3"; service StackOverflowService { rpc GetAnswer(Question) returns (Answer); } message Question { string text = 1; string user = 2; repeated string tags = 3; } message Answer { string text = 1; string user = 2; } Then run (all on one line; I've broken it just for readability here): tools\protoc.exe -I protos protos\test.proto --csharp_out=output --grpc_out=output --plugin=protoc-gen-grpc=tools\grpc_csharp_plugin.exe In the output directory, you'll find Test.cs and TestGrpc.cs A: Just an idle comment here for other that find this, the documentation about this is terribly out of date and just flat out wrong. Installing Grpc.Tools does not install anything in a packages folder; that is legacy behaviour which is no longer true even on windows. When you install Grpc.Tools it will be hidden away in your local package cache, which you can see by calling: $ dotnet nuget locals all --list info : http-cache: /Users/doug/.local/share/NuGet/v3-cache info : global-packages: /Users/doug/.nuget/packages/ info : temp: /var/folders/xx/s2hnzbrj3yn4hp1bg8q9gb_m0000gn/T/NuGetScratch The binaries you want will be in one of these folders. The easiest way to do this is to download the Grpc.Tools package directly from nuget, and install it locally. I've hacked up this little helper script to do that, which works on windows/mac/linux, which may ease the difficulty of getting starting with this for others: using System; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Http; using System.Reflection; using System.Runtime.InteropServices; using System.Threading.Tasks; using Mono.Unix; namespace BuildProtocol { public class Program { private const string ToolsUrl = "https://www.nuget.org/api/v2/package/Grpc.Tools/"; private const string Service = "Greeter"; private static string ProtocolPath = Path.Combine("..", "protos"); private static string Protocol = Path.Combine(ProtocolPath, "helloworld.proto"); private static string Output = Path.Combine("..", "Greeter"); public static void Main(string[] args) { RequireTools().Wait(); var protoc = ProtocPath(); var plugin = ProtocPluginPath(); Console.WriteLine($"Using: {protoc}"); Console.WriteLine($"Using: {plugin}"); var command = new string[] { $"-I{ProtocolPath}", $"--csharp_out={Output}", $"--grpc_out={Output}", $"--plugin=protoc-gen-grpc=\"{plugin}\"", Protocol, }; Console.WriteLine($"Exec: {protoc} {string.Join(' ', command)}"); var process = new Process { StartInfo = new ProcessStartInfo { UseShellExecute = false, FileName = protoc, Arguments = string.Join(' ', command) } }; process.Start(); process.WaitForExit(); Console.WriteLine($"Completed status: {process.ExitCode}"); } public static async Task RequireTools() { if (!Directory.Exists("Tools")) { Console.WriteLine("No local tools found, downloading binaries from nuget..."); Directory.CreateDirectory("Tools"); await DownloadTools(); ExtractTools(); } } private static void ExtractTools() { ZipFile.ExtractToDirectory(Path.Combine("Tools", "tools.zip"), Path.Combine("Tools", "bin")); } private static async Task DownloadTools() { using (var client = new HttpClient()) { Console.WriteLine($"Fetching: {ToolsUrl}"); using (var result = await client.GetAsync(ToolsUrl)) { if (!result.IsSuccessStatusCode) throw new Exception($"Unable to download tools ({result.StatusCode}), check URL"); var localArchive = Path.Combine("Tools", "tools.zip"); Console.WriteLine($"Saving to: {localArchive}"); File.WriteAllBytes(localArchive, await result.Content.ReadAsByteArrayAsync()); } } } private static string ProtocPath() { var path = Path.Combine("Tools", "bin", "tools", DetermineArch(), "protoc"); RequireExecutablePermission(path); return WithExeExtensionIfRequired(path); } private static string ProtocPluginPath() { var path = Path.Combine("Tools", "bin", "tools", DetermineArch(), "grpc_csharp_plugin"); RequireExecutablePermission(path); return WithExeExtensionIfRequired(path); } private static void RequireExecutablePermission(string path) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return; Console.WriteLine($"Ensuring +x on {path}"); var unixFileInfo = new UnixFileInfo(path); unixFileInfo.FileAccessPermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.UserExecute; } private static string WithExeExtensionIfRequired(string path) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { path += ".exe"; } return path; } private static string DetermineArch() { var arch = RuntimeInformation.OSArchitecture; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return WithArch("windows_", arch); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return WithArch("macosx_", arch); } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return WithArch("linux_", arch); } throw new Exception("Unable to determine runtime"); } private static string WithArch(string platform, Architecture arch) { switch (arch) { case Architecture.X64: return $"{platform}x86"; case Architecture.X86: return $"{platform}x64"; default: throw new ArgumentOutOfRangeException(nameof(arch), arch, null); } } } } A: the following approach helped me : Create a gRPC client and server in ASP.NET Core in project, where .proto file located, edit the .csproj file <ItemGroup> .... <Protobuf Include="Shipping.proto" GrpcServices="Server" /> </ItemGroup> rebuild the project, the all necessary .cs files will be added automaticaly \obj\Debug\[TARGET_FRAMEWORK]\Shipping.cs \obj\Debug\[TARGET_FRAMEWORK]\ShippingGrpc.cs
How to use the gRPC tools to generate code
I've read the tutorial and I'm able to generate the .cs file but it doesn't include any of my service or rpc definitions. I've added protoc to my PATH and from inside the project directory. protoc project1.proto --csharp_out="C:\output" --plugin=protoc-gen-grpc="c:\Users\me\.nuget\packages\grpc.tools\1.8.0\tools\windows_x64\grpc_csharp_plugin.exe" No errors output in console
[ "You need to add the --grpc_out command line option, e.g. add\n--grpc_out=\"C:\\output\\\"\n\nNote that it won't write any files if you don't have any services.\nHere's a complete example. From a root directory, create:\n\nAn empty output directory\nA tools directory with protoc.exe and grpc_csharp_plugin.exe\nA protos directory with test.proto as shown below:\n\ntest.proto:\nsyntax = \"proto3\";\n\nservice StackOverflowService {\n rpc GetAnswer(Question) returns (Answer);\n}\n\nmessage Question {\n string text = 1;\n string user = 2;\n repeated string tags = 3;\n}\n\nmessage Answer {\n string text = 1;\n string user = 2;\n}\n\nThen run (all on one line; I've broken it just for readability here):\ntools\\protoc.exe -I protos protos\\test.proto --csharp_out=output\n --grpc_out=output --plugin=protoc-gen-grpc=tools\\grpc_csharp_plugin.exe \n\nIn the output directory, you'll find Test.cs and TestGrpc.cs\n", "Just an idle comment here for other that find this, the documentation about this is terribly out of date and just flat out wrong.\nInstalling Grpc.Tools does not install anything in a packages folder; that is legacy behaviour which is no longer true even on windows.\nWhen you install Grpc.Tools it will be hidden away in your local package cache, which you can see by calling:\n$ dotnet nuget locals all --list\ninfo : http-cache: /Users/doug/.local/share/NuGet/v3-cache\ninfo : global-packages: /Users/doug/.nuget/packages/\ninfo : temp: /var/folders/xx/s2hnzbrj3yn4hp1bg8q9gb_m0000gn/T/NuGetScratch\n\nThe binaries you want will be in one of these folders.\nThe easiest way to do this is to download the Grpc.Tools package directly from nuget, and install it locally.\nI've hacked up this little helper script to do that, which works on windows/mac/linux, which may ease the difficulty of getting starting with this for others:\nusing System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing Mono.Unix;\n\nnamespace BuildProtocol\n{\n public class Program\n {\n private const string ToolsUrl = \"https://www.nuget.org/api/v2/package/Grpc.Tools/\";\n private const string Service = \"Greeter\";\n private static string ProtocolPath = Path.Combine(\"..\", \"protos\");\n private static string Protocol = Path.Combine(ProtocolPath, \"helloworld.proto\");\n private static string Output = Path.Combine(\"..\", \"Greeter\");\n\n public static void Main(string[] args)\n {\n RequireTools().Wait();\n\n var protoc = ProtocPath();\n var plugin = ProtocPluginPath();\n\n Console.WriteLine($\"Using: {protoc}\");\n Console.WriteLine($\"Using: {plugin}\");\n\n var command = new string[]\n {\n $\"-I{ProtocolPath}\",\n $\"--csharp_out={Output}\",\n $\"--grpc_out={Output}\",\n $\"--plugin=protoc-gen-grpc=\\\"{plugin}\\\"\",\n Protocol,\n };\n\n Console.WriteLine($\"Exec: {protoc} {string.Join(' ', command)}\");\n\n var process = new Process\n {\n StartInfo = new ProcessStartInfo\n {\n UseShellExecute = false,\n FileName = protoc,\n Arguments = string.Join(' ', command)\n }\n };\n\n process.Start();\n process.WaitForExit();\n\n Console.WriteLine($\"Completed status: {process.ExitCode}\");\n }\n\n public static async Task RequireTools()\n {\n if (!Directory.Exists(\"Tools\"))\n {\n Console.WriteLine(\"No local tools found, downloading binaries from nuget...\");\n Directory.CreateDirectory(\"Tools\");\n await DownloadTools();\n ExtractTools();\n }\n }\n\n private static void ExtractTools()\n {\n ZipFile.ExtractToDirectory(Path.Combine(\"Tools\", \"tools.zip\"), Path.Combine(\"Tools\", \"bin\"));\n }\n\n private static async Task DownloadTools()\n {\n using (var client = new HttpClient())\n {\n Console.WriteLine($\"Fetching: {ToolsUrl}\");\n using (var result = await client.GetAsync(ToolsUrl))\n {\n if (!result.IsSuccessStatusCode) throw new Exception($\"Unable to download tools ({result.StatusCode}), check URL\");\n var localArchive = Path.Combine(\"Tools\", \"tools.zip\");\n Console.WriteLine($\"Saving to: {localArchive}\");\n File.WriteAllBytes(localArchive, await result.Content.ReadAsByteArrayAsync());\n }\n }\n }\n\n private static string ProtocPath()\n {\n var path = Path.Combine(\"Tools\", \"bin\", \"tools\", DetermineArch(), \"protoc\");\n RequireExecutablePermission(path);\n return WithExeExtensionIfRequired(path);\n }\n\n private static string ProtocPluginPath()\n {\n var path = Path.Combine(\"Tools\", \"bin\", \"tools\", DetermineArch(), \"grpc_csharp_plugin\");\n RequireExecutablePermission(path);\n return WithExeExtensionIfRequired(path);\n }\n\n private static void RequireExecutablePermission(string path)\n {\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;\n Console.WriteLine($\"Ensuring +x on {path}\");\n var unixFileInfo = new UnixFileInfo(path);\n unixFileInfo.FileAccessPermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.UserExecute;\n }\n\n private static string WithExeExtensionIfRequired(string path)\n {\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n path += \".exe\";\n }\n\n return path;\n }\n\n private static string DetermineArch()\n {\n var arch = RuntimeInformation.OSArchitecture;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n return WithArch(\"windows_\", arch);\n }\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n return WithArch(\"macosx_\", arch);\n }\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))\n {\n return WithArch(\"linux_\", arch);\n }\n\n throw new Exception(\"Unable to determine runtime\");\n }\n\n private static string WithArch(string platform, Architecture arch)\n {\n switch (arch)\n {\n case Architecture.X64:\n return $\"{platform}x86\";\n case Architecture.X86:\n return $\"{platform}x64\";\n default:\n throw new ArgumentOutOfRangeException(nameof(arch), arch, null);\n }\n }\n }\n}\n\n", "the following approach helped me :\nCreate a gRPC client and server in ASP.NET Core\nin project, where .proto file located, edit the .csproj file\n <ItemGroup>\n ....\n <Protobuf Include=\"Shipping.proto\" GrpcServices=\"Server\" />\n </ItemGroup>\n\nrebuild the project, the all necessary .cs files will be added automaticaly\n\\obj\\Debug\\[TARGET_FRAMEWORK]\\Shipping.cs\n\\obj\\Debug\\[TARGET_FRAMEWORK]\\ShippingGrpc.cs\n\n" ]
[ 16, 6, 0 ]
[]
[]
[ "c#", "grpc", "protocol_buffers" ]
stackoverflow_0050687335_c#_grpc_protocol_buffers.txt
Q: DCMTK storescp listener for many AE Titles I want to use DCMTK's storescp (or perhaps dcmrecv) to receive DICOM files. I want to give each potential sender a different AE_Title that they should send to. Then I want to be able to identify the sender because I will see which AE_Title the DICOM was received on. How to do this? It looks like the dcmrecv with the -uca option might be the way, but I don't see how to tell which AE Title was used by the sender. A: Each DICOM Storage SCU identifies itself with an AE Title (so-called Calling AE Title), which is used by DCMTK's storescp to specify the value of the Source Application Entity Title (0002,0016) Attribute in the File Meta Information of the created DICOM files. What you were asking for is the Called AE Title.
DCMTK storescp listener for many AE Titles
I want to use DCMTK's storescp (or perhaps dcmrecv) to receive DICOM files. I want to give each potential sender a different AE_Title that they should send to. Then I want to be able to identify the sender because I will see which AE_Title the DICOM was received on. How to do this? It looks like the dcmrecv with the -uca option might be the way, but I don't see how to tell which AE Title was used by the sender.
[ "Each DICOM Storage SCU identifies itself with an AE Title (so-called Calling AE Title), which is used by DCMTK's storescp to specify the value of the Source Application Entity Title (0002,0016) Attribute in the File Meta Information of the created DICOM files.\nWhat you were asking for is the Called AE Title.\n" ]
[ 0 ]
[]
[]
[ "dcmtk" ]
stackoverflow_0074647464_dcmtk.txt
Q: How to use a div as the node component in visx network I want to create a custom node inside the nodeComponent attribute of Graph. I basically want it to be the MUI popover component but html in here doesn't seem to be allowed. I can't even get a <h1>hello</h1> to be the node. What do I need to do to use HTML or any other custom components in here? Thanks! A: It sounds like you are trying to use a custom component as the nodeComponent prop for a Graph, but you are encountering errors. There could be a few different reasons why this is happening. One possible reason is that you are not properly importing the custom component into the file where you are using it. If you are using a custom component that is defined in a separate file, you will need to import it at the top of your file using the import keyword, like this: import React from 'react'; import MyCustomNodeComponent from './MyCustomNodeComponent'; const MyGraph = () => { return ( <Graph nodeComponent={MyCustomNodeComponent} /> ); }; Another possible reason is that your custom component is not properly returning a React element. The nodeComponent prop expects a component that returns a React element, so if your component is not returning a React element, the Graph will not be able to render it. Here is an example of a custom component that returns a React element: import React from 'react'; import Button from '@material-ui/core/Button'; const MyCustomNodeComponent = ({ node, children }) => { return ( <Button>hi</Button> ); }; If you are still encountering errors, it would be helpful to see the specific error messages that you are getting. This would allow me to provide more specific advice on how to fix the problem.
How to use a div as the node component in visx network
I want to create a custom node inside the nodeComponent attribute of Graph. I basically want it to be the MUI popover component but html in here doesn't seem to be allowed. I can't even get a <h1>hello</h1> to be the node. What do I need to do to use HTML or any other custom components in here? Thanks!
[ "It sounds like you are trying to use a custom component as the nodeComponent prop for a Graph, but you are encountering errors. There could be a few different reasons why this is happening.\nOne possible reason is that you are not properly importing the custom component into the file where you are using it. If you are using a custom component that is defined in a separate file, you will need to import it at the top of your file using the import keyword, like this:\nimport React from 'react';\nimport MyCustomNodeComponent from './MyCustomNodeComponent';\n\nconst MyGraph = () => {\n return (\n <Graph nodeComponent={MyCustomNodeComponent} />\n );\n};\n\nAnother possible reason is that your custom component is not properly returning a React element. The nodeComponent prop expects a component that returns a React element, so if your component is not returning a React element, the Graph will not be able to render it. Here is an example of a custom component that returns a React element:\nimport React from 'react';\nimport Button from '@material-ui/core/Button';\n\nconst MyCustomNodeComponent = ({ node, children }) => {\n return (\n <Button>hi</Button>\n );\n};\n\nIf you are still encountering errors, it would be helpful to see the specific error messages that you are getting. This would allow me to provide more specific advice on how to fix the problem.\n" ]
[ 0 ]
[]
[]
[ "reactjs", "visx" ]
stackoverflow_0074660300_reactjs_visx.txt
Q: How to use Sweetalert in main.js Vue 3 I was learning Vue 3 and get some trouble to use SweetAlert2 in app.js. everything is ok and worked when i use SweetAlert2 in component Vue but not work in app.js my goal: i want to show alert with confirm button when get error response Unauthenticated. from axios interceptors and redirect user to login page app.js import {createApp} from 'vue' require('./bootstrap') import App from './App.vue' import axios from 'axios' import router from './router' import store from './store' // SweetAlert2 import VueSweetalert2 from 'vue-sweetalert2'; import 'sweetalert2/dist/sweetalert2.min.css'; axios.interceptors.response.use(function (response) { return response }, function (error) { console.log(error.response.data.message) if (error.response.data.message === 'Unauthenticated.') { swal({ title: "Session Expired", text: "Your session has expired. Would you like to be redirected to the login page?", icon: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes", closeOnConfirm: false }).then((result) => { if (result.value) { window.location.href = "/login" } }); } return Promise.reject(error) }) const app = createApp(App) app.config.globalProperties.$axios = axios; app.use(router) app.use(VueSweetalert2) app.use(store) app.mount('#app') it work when i change error response with this, (but not elegant like this for me) ... axios.interceptors.response.use(function (response) { return response }, function (error) { console.log(error.response.data.message) if (error.response.data.message === 'Unauthenticated.') { alert('Session Expired'); window.location.href = "/login" } return Promise.reject(error) }) ... i think it would be good if using sweetalert, thank youu... A: Explanation I faced the same problem when using Vue 3, and I wanted to use sweetalert2 in my router/index.js to add an alert when a user goes to an unauthorized route. The same problem will appear if you want to use a sweetalert2 in store/index.js after calling an action fetching data from the backend. To work around this problem, you must use the native package of sweetalert2, then you can use swal in any .js file. By the way, I don't want to install any external package, so I found that when you are installing the vue-sweetalert2, the native package will be installed also (because it is a dependency of vue-sweetalert2). Workaround All you have to do is: Keep what you had done in main.js (to use sweetalert2 inside components). In any .js file where you want to use swal, add this import Swal from 'sweetalert2/dist/sweetalert2', and now you can access and use Swal.fire({}). Example I will attach an example of what I want to do (in my case), and how I work around the problem: My main.js file: import { createApp } from 'vue'; import App from './App.vue'; import store from './store'; import router from './router'; import VueSweetalert2 from 'vue-sweetalert2'; import 'sweetalert2/dist/sweetalert2.min.css'; const app = createApp(App); app.use(store); app.use(router); app.use(VueSweetalert2); app.mount('#app'); My router/index.js import { createRouter, createWebHistory } from 'vue-router'; import Swal from 'sweetalert2/dist/sweetalert2'; import store from '../store/index'; const router = createRouter({ routes: [ // ... ], }); router.beforeEach((to, from, next) => { if (to.matched.some((record) => record.meta['requiresAuth']) && store.state.auth.isAuthenticated === false) { Swal.fire({ toast: true, position: 'bottom-end', showConfirmButton: false, timer: 3000, timerProgressBar: true, icon: 'error', title: 'Permission denied', text: 'You are not authenticated to access this page.' }); next({ name: 'login', params: { nextUrl: to.fullPath } }); } next(); }); export default router;
How to use Sweetalert in main.js Vue 3
I was learning Vue 3 and get some trouble to use SweetAlert2 in app.js. everything is ok and worked when i use SweetAlert2 in component Vue but not work in app.js my goal: i want to show alert with confirm button when get error response Unauthenticated. from axios interceptors and redirect user to login page app.js import {createApp} from 'vue' require('./bootstrap') import App from './App.vue' import axios from 'axios' import router from './router' import store from './store' // SweetAlert2 import VueSweetalert2 from 'vue-sweetalert2'; import 'sweetalert2/dist/sweetalert2.min.css'; axios.interceptors.response.use(function (response) { return response }, function (error) { console.log(error.response.data.message) if (error.response.data.message === 'Unauthenticated.') { swal({ title: "Session Expired", text: "Your session has expired. Would you like to be redirected to the login page?", icon: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes", closeOnConfirm: false }).then((result) => { if (result.value) { window.location.href = "/login" } }); } return Promise.reject(error) }) const app = createApp(App) app.config.globalProperties.$axios = axios; app.use(router) app.use(VueSweetalert2) app.use(store) app.mount('#app') it work when i change error response with this, (but not elegant like this for me) ... axios.interceptors.response.use(function (response) { return response }, function (error) { console.log(error.response.data.message) if (error.response.data.message === 'Unauthenticated.') { alert('Session Expired'); window.location.href = "/login" } return Promise.reject(error) }) ... i think it would be good if using sweetalert, thank youu...
[ "Explanation\nI faced the same problem when using Vue 3, and I wanted to use sweetalert2 in my router/index.js to add an alert when a user goes to an unauthorized route.\nThe same problem will appear if you want to use a sweetalert2 in store/index.js after calling an action fetching data from the backend.\nTo work around this problem, you must use the native package of sweetalert2, then you can use swal in any .js file.\nBy the way, I don't want to install any external package, so I found that when you are installing the vue-sweetalert2, the native package will be installed also (because it is a dependency of vue-sweetalert2).\nWorkaround\nAll you have to do is:\n\nKeep what you had done in main.js (to use sweetalert2 inside components).\nIn any .js file where you want to use swal, add this import Swal from 'sweetalert2/dist/sweetalert2', and now you can access and use Swal.fire({}).\n\nExample\nI will attach an example of what I want to do (in my case), and how I work around the problem:\nMy main.js file:\nimport { createApp } from 'vue';\nimport App from './App.vue';\nimport store from './store';\nimport router from './router';\nimport VueSweetalert2 from 'vue-sweetalert2';\nimport 'sweetalert2/dist/sweetalert2.min.css';\n\nconst app = createApp(App);\n\napp.use(store);\napp.use(router);\napp.use(VueSweetalert2);\n\napp.mount('#app');\n\nMy router/index.js\nimport { createRouter, createWebHistory } from 'vue-router';\nimport Swal from 'sweetalert2/dist/sweetalert2';\nimport store from '../store/index';\n\nconst router = createRouter({\n routes: [\n // ...\n ],\n});\n\nrouter.beforeEach((to, from, next) => {\n if (to.matched.some((record) => record.meta['requiresAuth']) && store.state.auth.isAuthenticated === false) {\n Swal.fire({\n toast: true,\n position: 'bottom-end',\n showConfirmButton: false,\n timer: 3000,\n timerProgressBar: true,\n\n icon: 'error',\n title: 'Permission denied',\n text: 'You are not authenticated to access this page.'\n });\n\n next({\n name: 'login',\n params: { nextUrl: to.fullPath }\n });\n }\n\n next();\n});\n\nexport default router;\n\n" ]
[ 0 ]
[ "i think you need to try withoud condition first,\ntry only sweet alert without :\naxios.interceptors.response.use(function (response) {\n return response\n}, function (error) {\n console.log(error.response.data.message)\n if (error.response.data.message === 'Unauthenticated.') {\n swal({\n title: \"Session Expired\",\n text: \"Your session has expired. Would you like to be redirected to the login page?\",\n icon: \"warning\",\n showCancelButton: true,\n confirmButtonColor: \"#DD6B55\",\n confirmButtonText: \"Yes\",\n closeOnConfirm: false\n }).then((result) => {\n if (result.value) {\n window.location.href = \"/login\"\n }\n }); \n}\n return Promise.reject(error)\n})\n\nu can try\n\nhttps://www.npmjs.com/package/vue-sweetalert2\n\n" ]
[ -1 ]
[ "axios", "vue.js" ]
stackoverflow_0070950346_axios_vue.js.txt
Q: "chromedriver unexpectedly exited" when importing selenium through a DAG on local airflow deployment I am trying to orchestrate a ETL pipeline with Airflow running on my local machine. I am using the "standard" docker-compose.yaml file from the apache.airflow webpage (this one: https://airflow.apache.org/docs/apache-airflow/2.4.3/docker-compose.yaml), my only alterations are mounting parts of my local file system onto docker, and using a custom image for allowing some python libraries to be installed (like selenium). This setup is working fine for some of my pipelines, but I have one involving webscraping with selenium that I cannot get to work. I get an DAG import error: Broken DAG: [/opt/airflow/dags/brand_delta/my_dags/amazon_italy_dag.py] Traceback (most recent call last): File "/home/airflow/.local/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 106, in start self.assert_process_still_running() File "/home/airflow/.local/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 119, in assert_process_still_running raise WebDriverException(f"Service {self.path} unexpectedly exited. Status code was: {return_code}") selenium.common.exceptions.WebDriverException: Message: Service /opt/airflow/chromedriver unexpectedly exited. Status code was: 127 The DAG imports a separate script, where the driver is initialized like this: def init_chrome_browser(chrome_driver_path, url): options = Options() options.add_argument('--no-sandbox') options.add_argument('--headless') options.add_argument('--disable-dev-shm-usage') options.add_argument('--start-maximized') options.add_argument('window-size=2560,1440') browser = webdriver.Chrome(service=Service(chrome_driver_path), options=options) browser.get(url) return browser For some reason the chromedriver keeps "unexpectedly exiting". I have tried both installing the chromedriver on my local machine and mounting the file location to the docker-compose image, and installing chromedriver inside of the docker container of the airflow-worker, but in both cases I get this error. I have also tried complementing the chromedriver with packages such as "libglib2.0..." inside of the worker and I do get chromedriver to start if I run it from the terminal of the worker. But still it gives me the same error when trying to run it with airflow. A: Are you sure you have your chromedriver installed on all running airflow docker containers? Are you able to run your webscraping python code on worker and/or scheduler container out of airflow?
"chromedriver unexpectedly exited" when importing selenium through a DAG on local airflow deployment
I am trying to orchestrate a ETL pipeline with Airflow running on my local machine. I am using the "standard" docker-compose.yaml file from the apache.airflow webpage (this one: https://airflow.apache.org/docs/apache-airflow/2.4.3/docker-compose.yaml), my only alterations are mounting parts of my local file system onto docker, and using a custom image for allowing some python libraries to be installed (like selenium). This setup is working fine for some of my pipelines, but I have one involving webscraping with selenium that I cannot get to work. I get an DAG import error: Broken DAG: [/opt/airflow/dags/brand_delta/my_dags/amazon_italy_dag.py] Traceback (most recent call last): File "/home/airflow/.local/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 106, in start self.assert_process_still_running() File "/home/airflow/.local/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 119, in assert_process_still_running raise WebDriverException(f"Service {self.path} unexpectedly exited. Status code was: {return_code}") selenium.common.exceptions.WebDriverException: Message: Service /opt/airflow/chromedriver unexpectedly exited. Status code was: 127 The DAG imports a separate script, where the driver is initialized like this: def init_chrome_browser(chrome_driver_path, url): options = Options() options.add_argument('--no-sandbox') options.add_argument('--headless') options.add_argument('--disable-dev-shm-usage') options.add_argument('--start-maximized') options.add_argument('window-size=2560,1440') browser = webdriver.Chrome(service=Service(chrome_driver_path), options=options) browser.get(url) return browser For some reason the chromedriver keeps "unexpectedly exiting". I have tried both installing the chromedriver on my local machine and mounting the file location to the docker-compose image, and installing chromedriver inside of the docker container of the airflow-worker, but in both cases I get this error. I have also tried complementing the chromedriver with packages such as "libglib2.0..." inside of the worker and I do get chromedriver to start if I run it from the terminal of the worker. But still it gives me the same error when trying to run it with airflow.
[ "Are you sure you have your chromedriver installed on all running airflow docker containers? Are you able to run your webscraping python code on worker and/or scheduler container out of airflow?\n" ]
[ 0 ]
[]
[]
[ "airflow", "selenium", "selenium_chromedriver" ]
stackoverflow_0074659132_airflow_selenium_selenium_chromedriver.txt
Q: How to download a project folder from sourcecode.apple.com? If I'm looking at an Apple opensource page like this: https://opensource.apple.com/source/Chess/ How can I download one of those projects to my hard drive so I can open it in XCode? The main stumbling block for me is simply downloading one of the root folders (projects). There is a similar existing question, but it is specific to the "wget" utility (this question is more general) and its best answer only suggests this official Apple OSS github repo, but that does NOT include all the projects contained within opensource.apple.com, for example, it only contains the most recent version of chess, not ANY of the previous ones. So, on opensource.apple.com, I cannot: Right-click and select download, because the folders are just links to more HTML, not directly to files. FTP to the url, because I don't have an FTP app installed on my Mac, and even if I did, I don't know if the Apple site would accommodate this. Download each and every file one-by-one, recreating the local folder structure manually... because that seems foolish. And as stated, while it is trivial to download from the Apple OSS github page, it doesn't contain the code I need! I Googled this and surprisingly can't find anything. So, is there a way to easily download from sourcecode.apple.com? A: It looks like that's an older interface to access the open source code. I went to https://opensource.apple.com/, clicked on the View Releases button which takes you to https://opensource.apple.com/releases/. There you can browse the separate projects. For example, to get the latest version of Chess, click on macOS, then macOS 13.0, then find Chess-466.4.1. There should be a download link and/or a link to the project on Github. For instance, all open source projects for macOS 13.0: https://github.com/apple-oss-distributions/distribution-macOS/tree/macos-130.
How to download a project folder from sourcecode.apple.com?
If I'm looking at an Apple opensource page like this: https://opensource.apple.com/source/Chess/ How can I download one of those projects to my hard drive so I can open it in XCode? The main stumbling block for me is simply downloading one of the root folders (projects). There is a similar existing question, but it is specific to the "wget" utility (this question is more general) and its best answer only suggests this official Apple OSS github repo, but that does NOT include all the projects contained within opensource.apple.com, for example, it only contains the most recent version of chess, not ANY of the previous ones. So, on opensource.apple.com, I cannot: Right-click and select download, because the folders are just links to more HTML, not directly to files. FTP to the url, because I don't have an FTP app installed on my Mac, and even if I did, I don't know if the Apple site would accommodate this. Download each and every file one-by-one, recreating the local folder structure manually... because that seems foolish. And as stated, while it is trivial to download from the Apple OSS github page, it doesn't contain the code I need! I Googled this and surprisingly can't find anything. So, is there a way to easily download from sourcecode.apple.com?
[ "It looks like that's an older interface to access the open source code.\nI went to https://opensource.apple.com/, clicked on the View Releases button which takes you to https://opensource.apple.com/releases/. There you can browse the separate projects. For example, to get the latest version of Chess, click on macOS, then macOS 13.0, then find Chess-466.4.1. There should be a download link and/or a link to the project on Github.\nFor instance, all open source projects for macOS 13.0: https://github.com/apple-oss-distributions/distribution-macOS/tree/macos-130.\n" ]
[ 1 ]
[]
[]
[ "apple_open_source", "macos", "open_source", "repository", "xcode" ]
stackoverflow_0074649589_apple_open_source_macos_open_source_repository_xcode.txt
Q: [Exception Occurred: System.Runtime.InteropServices.COMException (0x80070296): Exception from HRESULT: 0x80070296 When I'm running prefview tool (https://github.com/microsoft/perfview) in the windows container, I encounter this exception: [Exception Occurred: System.Runtime.InteropServices.COMException (0x80070296): Exception from HRESULT: 0x80070296 at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) at Microsoft.Diagnostics.Tracing.Extensions.ETWControl.EnableStackCaching(UInt64 traceHandle) at Microsoft.Diagnostics.Tracing.Session.TraceEventSession.EnableKernelProvider(Keywords flags, Keywords stackCapture) at PerfView.CommandProcessor.Start(CommandLineArgs parsedArgs) at PerfView.CommandProcessor.Collect(CommandLineArgs parsedArgs) at PerfView.CommandProcessor.ExecuteCommand(CommandLineArgs parsedArgs)] Here is my usage: Download the latest prefview from: https://github.com/microsoft/perfview/releases/download/v3.0.6/PerfView.exe Copy the PerfView.exe into the windows container use crictl exec <contianer id> powershell command to open a Powershell in the container Running the command .\PerfView "/DataFile:PerfViewData.etl" /BufferSizeMB:256 /StackCompression /CircularMB:500 /logFile=log.txt /maxCollectSec=30 /NoGui collect My windows container's base image is: mcr.microsoft.com/windows/nanoserver:1809 My isolation runtime is: runhcs-wcow-hypervisor Anything I can do about it? Thanks in advance. I have read this post: https://githublab.com/repository/issues/microsoft/perfview/1601. It said that we should use hyper-v isolation and that's exactly what I'm using. A: Have you tried to use the Server Core image? It might be the case that PerfView is trying to access OS APIs that are not present in Nano Server.
[Exception Occurred: System.Runtime.InteropServices.COMException (0x80070296): Exception from HRESULT: 0x80070296
When I'm running prefview tool (https://github.com/microsoft/perfview) in the windows container, I encounter this exception: [Exception Occurred: System.Runtime.InteropServices.COMException (0x80070296): Exception from HRESULT: 0x80070296 at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) at Microsoft.Diagnostics.Tracing.Extensions.ETWControl.EnableStackCaching(UInt64 traceHandle) at Microsoft.Diagnostics.Tracing.Session.TraceEventSession.EnableKernelProvider(Keywords flags, Keywords stackCapture) at PerfView.CommandProcessor.Start(CommandLineArgs parsedArgs) at PerfView.CommandProcessor.Collect(CommandLineArgs parsedArgs) at PerfView.CommandProcessor.ExecuteCommand(CommandLineArgs parsedArgs)] Here is my usage: Download the latest prefview from: https://github.com/microsoft/perfview/releases/download/v3.0.6/PerfView.exe Copy the PerfView.exe into the windows container use crictl exec <contianer id> powershell command to open a Powershell in the container Running the command .\PerfView "/DataFile:PerfViewData.etl" /BufferSizeMB:256 /StackCompression /CircularMB:500 /logFile=log.txt /maxCollectSec=30 /NoGui collect My windows container's base image is: mcr.microsoft.com/windows/nanoserver:1809 My isolation runtime is: runhcs-wcow-hypervisor Anything I can do about it? Thanks in advance. I have read this post: https://githublab.com/repository/issues/microsoft/perfview/1601. It said that we should use hyper-v isolation and that's exactly what I'm using.
[ "Have you tried to use the Server Core image? It might be the case that PerfView is trying to access OS APIs that are not present in Nano Server.\n" ]
[ 0 ]
[]
[]
[ "comexception", "perfview", "windows_container" ]
stackoverflow_0074598803_comexception_perfview_windows_container.txt
Q: Graphing equations where x and y have trigonometric functions applied to them in r I am trying to graph the function ((sin(a*(pi/10))+x)^2 + (cos(a*(pi/10))+y)^2 -1)/(0.7*abs(x))=y (with a being any value from 1-20) in r but am struggling as all the r functions seem to need to have equations in the format function(x) = y with no ys in function(x), and no trigonometric functions being applied to y. I've tried: curve((((sin(1*(pi/10))+x)^2 + (cos(1*(pi/10))+y)^2 -1)/(0.7abs(x)))) and curve((((sin(1(pi/10))+x)^2 + (cos(1*(pi/10))+y)^2 -1)/(0.7*abs(x)))-y) where I've specified y as: y <- seq(-3,3,length=100) (and a=1) but I get warning messages of: Warning messages: 1: In (sin(1 * (pi/10)) + x)^2 + (cos(1 * (pi/10)) + y)^2 : longer object length is not a multiple of shorter object length 2: In (((sin(1 * (pi/10)) + x)^2 + (cos(1 * (pi/10)) + y)^2 - 1)/(0.7 * : longer object length is not a multiple of shorter object length and the graphs it produced are not right (I have checked by plotting it on Wolfram alpha). My problem seems to be the same as the one here Graphing more complicated trigonometric functions in R (sorry if this isn't the right way to link to other questions, I'm new to stack overflow) but it hasn't been satisfactorily answered. Any help would be much appreciated! A: This is an implicit equation. a <- 1 f <- function(x, y) { y - ((sin(a*(pi/10))+x)^2 + (cos(a*(pi/10))+y)^2 -1)/(0.7*abs(x)) } x <- seq(-1.5, 1, len = 200) y <- seq(-2.5, 0.5, len = 200) z <- outer(x, y, f) cr <- contourLines(x, y, z, levels = 0) plot(cr[[1]]$x, cr[[1]]$y, type = "l")
Graphing equations where x and y have trigonometric functions applied to them in r
I am trying to graph the function ((sin(a*(pi/10))+x)^2 + (cos(a*(pi/10))+y)^2 -1)/(0.7*abs(x))=y (with a being any value from 1-20) in r but am struggling as all the r functions seem to need to have equations in the format function(x) = y with no ys in function(x), and no trigonometric functions being applied to y. I've tried: curve((((sin(1*(pi/10))+x)^2 + (cos(1*(pi/10))+y)^2 -1)/(0.7abs(x)))) and curve((((sin(1(pi/10))+x)^2 + (cos(1*(pi/10))+y)^2 -1)/(0.7*abs(x)))-y) where I've specified y as: y <- seq(-3,3,length=100) (and a=1) but I get warning messages of: Warning messages: 1: In (sin(1 * (pi/10)) + x)^2 + (cos(1 * (pi/10)) + y)^2 : longer object length is not a multiple of shorter object length 2: In (((sin(1 * (pi/10)) + x)^2 + (cos(1 * (pi/10)) + y)^2 - 1)/(0.7 * : longer object length is not a multiple of shorter object length and the graphs it produced are not right (I have checked by plotting it on Wolfram alpha). My problem seems to be the same as the one here Graphing more complicated trigonometric functions in R (sorry if this isn't the right way to link to other questions, I'm new to stack overflow) but it hasn't been satisfactorily answered. Any help would be much appreciated!
[ "This is an implicit equation.\na <- 1\nf <- function(x, y) {\n y - ((sin(a*(pi/10))+x)^2 + (cos(a*(pi/10))+y)^2 -1)/(0.7*abs(x))\n}\n\nx <- seq(-1.5, 1, len = 200)\ny <- seq(-2.5, 0.5, len = 200)\nz <- outer(x, y, f)\ncr <- contourLines(x, y, z, levels = 0)\n\nplot(cr[[1]]$x, cr[[1]]$y, type = \"l\")\n\n\n" ]
[ 0 ]
[]
[]
[ "graph", "r", "trigonometry" ]
stackoverflow_0074660271_graph_r_trigonometry.txt
Q: What are SSLv3-compatible login.microsoftonline.com ClientHello Handshake parameters when examining in Fiddler? I am using Fiddler to inspect my call into Azure for authentication from my Windows desktop application. Looking at the details in Fiddler for login.microsoftline.com I see the following. A SSLv3-compatible ClientHello handshake was found. Fiddler extracted the parameters below. Version: 3.3 (TLS/1.2) Random: 63 72 83 65 25 67 E0 D4 C9 1F F6 FF C1 60 DB E3 36 DC 82 29 18 9F 6E EB BF DA B0 7C AF 04 30 8C "Time": 12/20/2023 6:01:55 PM SessionID: empty Extensions: What does the time field represent in this instance? A: My educated guess is that it's the SSL certificate Not After field. That is, it's expiration date.
What are SSLv3-compatible login.microsoftonline.com ClientHello Handshake parameters when examining in Fiddler?
I am using Fiddler to inspect my call into Azure for authentication from my Windows desktop application. Looking at the details in Fiddler for login.microsoftline.com I see the following. A SSLv3-compatible ClientHello handshake was found. Fiddler extracted the parameters below. Version: 3.3 (TLS/1.2) Random: 63 72 83 65 25 67 E0 D4 C9 1F F6 FF C1 60 DB E3 36 DC 82 29 18 9F 6E EB BF DA B0 7C AF 04 30 8C "Time": 12/20/2023 6:01:55 PM SessionID: empty Extensions: What does the time field represent in this instance?
[ "My educated guess is that it's the SSL certificate Not After field. That is, it's expiration date.\n" ]
[ 0 ]
[]
[]
[ "azure_active_directory", "sslv3" ]
stackoverflow_0074436270_azure_active_directory_sslv3.txt
Q: missing struct fields error while creating an instance of struct I want to create a struct by calling new member function of a given struct by initializing only some of the fields. I am getting an error error[E0063]: missing fields b and join_handle in initializer of B::B. This is my sample code main.rs mod B; mod A; fn main() { println!("Hello, world!"); } A.rs pub struct AS { a: String } B.rs use crate::A::AS; use std::thread; pub struct B { a: String, b: AS, join_handle: thread::JoinHandle<()> } impl B { fn new() -> B { B { a: String::from("Hi"), } } } How to partially initialize a struct? A: You can't partially initialize a struct. You could just use Options inside of B: struct B { a: String, b: Option<AS>, join_handle: Option<thread::JoinHandle<()>>, } impl B { fn new() -> Self { Self { a: String::from("hi"), b: None, join_handle: None, } } } Or use a builder instead: use std::thread; fn main() { println!("Hello, world!"); } pub struct AS { a: String } pub struct B { a: String, b: AS, join_handle: thread::JoinHandle<()> } impl B { fn builder() -> BBuilder { BBuilder { a: String::from("Hi"), b: None, join_handle: None, } } } struct BBuilder { a: String, b: Option<AS>, join_handle: Option<thread::JoinHandle<()>>, } impl BBuilder { fn a(mut self, b: AS) -> Self { self.b = Some(b); self } fn join_handle(mut self, join_handle: thread::JoinHandle<()>) -> Self { self.join_handle = Some(join_handle); self } fn build(self) -> Option<B> { let Self{ a, b, join_handle } = self; let b = b?; let join_handle = join_handle?; Some(B { a, b, join_handle }) } } A: You don't. You can't partially initialize anything in Rust. Maybe you need to make some of the fields optionals.
missing struct fields error while creating an instance of struct
I want to create a struct by calling new member function of a given struct by initializing only some of the fields. I am getting an error error[E0063]: missing fields b and join_handle in initializer of B::B. This is my sample code main.rs mod B; mod A; fn main() { println!("Hello, world!"); } A.rs pub struct AS { a: String } B.rs use crate::A::AS; use std::thread; pub struct B { a: String, b: AS, join_handle: thread::JoinHandle<()> } impl B { fn new() -> B { B { a: String::from("Hi"), } } } How to partially initialize a struct?
[ "You can't partially initialize a struct.\nYou could just use Options inside of B:\nstruct B {\n a: String,\n b: Option<AS>,\n join_handle: Option<thread::JoinHandle<()>>,\n}\nimpl B {\n fn new() -> Self {\n Self {\n a: String::from(\"hi\"),\n b: None,\n join_handle: None,\n }\n }\n}\n\n\nOr use a builder instead:\nuse std::thread;\nfn main() {\n println!(\"Hello, world!\");\n}\n\npub struct AS {\n a: String\n}\n\npub struct B {\n a: String,\n b: AS,\n join_handle: thread::JoinHandle<()>\n}\n\nimpl B {\n fn builder() -> BBuilder {\n BBuilder {\n a: String::from(\"Hi\"),\n b: None,\n join_handle: None,\n }\n }\n}\n\nstruct BBuilder {\n a: String,\n b: Option<AS>,\n join_handle: Option<thread::JoinHandle<()>>,\n}\n\nimpl BBuilder {\n fn a(mut self, b: AS) -> Self {\n self.b = Some(b);\n self\n }\n fn join_handle(mut self, join_handle: thread::JoinHandle<()>) -> Self {\n self.join_handle = Some(join_handle);\n self\n }\n fn build(self) -> Option<B> {\n let Self{ a, b, join_handle } = self;\n let b = b?;\n let join_handle = join_handle?;\n Some(B { a, b, join_handle })\n }\n}\n\n", "You don't. You can't partially initialize anything in Rust.\nMaybe you need to make some of the fields optionals.\n" ]
[ 3, 2 ]
[]
[]
[ "rust" ]
stackoverflow_0074660194_rust.txt
Q: How to set Company as default based on user login in Acumatica Generic Inquiry I am creating a generic inquiry in Acumatica and I can't set the Company parameter default to user login. I have maintained the parameter "Company" in the Generic Inquiry. Now I want the default company filled up based on user current login. What will be the condition to auto populate it based on user log in? Thank you! Link 1 Link 2 A: You could get the current branch selected in a read-only filter. From there you could get the company from joining the branch table. Branch's OrganizationID is the company of the selected branch. https://asiablog.acumatica.com/2018/11/generic-inquiry-with-filtering-by-current-branch.html
How to set Company as default based on user login in Acumatica Generic Inquiry
I am creating a generic inquiry in Acumatica and I can't set the Company parameter default to user login. I have maintained the parameter "Company" in the Generic Inquiry. Now I want the default company filled up based on user current login. What will be the condition to auto populate it based on user log in? Thank you! Link 1 Link 2
[ "You could get the current branch selected in a read-only filter. From there you could get the company from joining the branch table. Branch's OrganizationID is the company of the selected branch.\nhttps://asiablog.acumatica.com/2018/11/generic-inquiry-with-filtering-by-current-branch.html\n" ]
[ 0 ]
[]
[]
[ "acumatica", "database", "generics", "mysql" ]
stackoverflow_0074497495_acumatica_database_generics_mysql.txt
Q: Why am I getting the error message about each list item should get a unique key when using the react-bootstrap with Nextjs? Here is the current setup of the file right now below. You will see that my file does indeed have a key to each child component but its still flagging it and I think its more internal issues that I am not sure that I can fix. export default function SecondaryNav(props:NavItems) { const router = useRouter(); let [filteredSubNavItems, setFilteredSubNavItems] = useState<{}[]>([]) /* Filtering the props.navigation array and setting the filteredSubNavItems state to the filtered array. */ useEffect(() => { props.navigation.filter((item) => { if(item.link == router.route) { setFilteredSubNavItems(item.subLinks); } }) }) return ( <> <Navbar className={[styles.SecondaryNav].join(' ')}> <div className={['container', styles.secondaryNavContainer].join(' ')}> { filteredSubNavItems.map((navItem, index) => { return ( <> { !navItem.subLinksExist ? <Nav.Link key={navItem.name} href={navItem.link}>{navItem.name}</Nav.Link> : <NavDropdown key={navItem.name} title={navItem.name} id={navItem.name}> { navItem.sublinks.map((item) => { return ( <NavDropdown.Item key={item.label}>{item.label}</NavDropdown.Item> ) }) } </NavDropdown> } </> ) }) } </div> </Navbar> </> ) } And below is the file that I am pulling the data. export const menuItems = [ { primaryLink: 'Home', link: '/', subLinks: [ { name: 'tutorial', subLinksExist: false, link: '/Home/Tutorial' }, { name: 'contact', subLinksExist: false, link: '/Home/Contact' }, { name: 'about', subLinksExist: false, link: '/Home/About' }, { name: 'FAQ', subLinksExist: false, link: '/Home/Faq' }, { name: 'version', subLinksExist: false, link: '/Home/Version' }, { name: 'health check', subLinksExist: false, link: '/Home/Healthcheck' } ] }, { primaryLink: 'Configuration', link: '/Configuration', subLinks: [ { name: 'merchants', link: 'merchants', subLinksExist: true, ariaControls: false, ariaExpanded: false, sublinks: [ { label: 'Billing Groups', key: 'billing groups', link: 'Configuration/Merchants/BillingGroup' }, { label: 'Billing Group Chain', key: 'billing group chain', link: 'Configuration/Merchants/BillingGroupChain' }, { label: 'Payment Channels', key: 'payment channels', link: 'Configuration/Merchants/PaymentChannels' }, { label: 'Relationship Managers', key: 'relationship managers', link: 'Configuration/Merchants/RelationshipManagers' }, { label: 'Fee Templates', key: 'fee templates', link: 'Configuration/Merchants/FeeTemplates' }, { label: 'Billing Group Disbursement Hold', key: 'billing group disbursement hold', link: 'Configuration/Merchants/BillingGroupDisbursementHold' }, ] }, { name: 'partners', subLinksExist: false, link: 'Configuration/Partners' }, { name: 'ODFIs', link: '/odfis', subLinksExist: true, ariaControls: false, ariaExpanded: false, sublinks: [ { label: 'Bank Expenses', key: 'bank expenses', link: 'Configuration/ODFIs/BankExpenses' }, { label: 'Expense Batches', key: 'expense batches', link: 'Configuration/ODFIs/ExpenseBatches' }, { label: 'Routing Numbers', key: 'routing numbers', link: 'Configuration/ODFIs/RoutingNumbers' }, ] }, { name: 'business units', link: '/businessunits', subLinksExist: true, ariaControls: false, ariaExpanded: false, sublinks: [ { label: 'Support Contacts', key: 'support contacts', link: 'Configuration/BusinessUnits/SupportContacts' } ] }, { name: 'profile', link: '/profile', subLinksExist: true, ariaControls: false, ariaExpanded: false, sublinks: [ { label: 'API Profiles', key: 'api profiles', link: 'Configuration/Profile/APIProfiles' }, { label: 'Heartland Users', key: 'heartland users', link: 'Configuration/Profile/HeartlandUsers' }, { label: 'External Users', key: 'external users', link: 'Configuration/Profile/ExternalUsers' }, ] }, { name: 'system', subLinksExist: false, link: 'Configuration/System' } ] }, { primaryLink: 'Support', link: '/Support', subLinks: [ { name: 'automation', link: '/automation', subLinksExist: true, sublinks: [ { label: 'Alerts', link: '/Support/Automation/Alerts' }, { label: 'Subscriptions', link: '/Support/Automation/Subscriptions' }, { label: 'Jobs', link: '/Support/Automation/Jobs' }, ] }, { name: 'consumers', link: '/Consumers', subLinksExist: true, sublinks: [ { label: 'Blacklist', link: '/Support/Consumers/Blacklist' }, { label: 'Whitelist', link: '/Support/Consumers/Whitelist' }, { label: 'Provisional Whitelist', link: '/Support/Consumers/ProvisionalWhitelist' }, ] }, { name: 'invoices', link: '/Invoices', subLinksExist: true, sublinks: [ { label: 'Billing Group', link: '/Support/Invoices/BillingGroup' }, { label: 'Partner', link: '/Support/Invoices/Partner' } ] }, { name: 'logging', link: '/Logging', subLinksExist: true, sublinks: [ { label: 'Failed Api Calls', link: '/Support/Logging/FailedApiCalls' }, { label: 'Logs', link: '/Support/Logging/Logs' }, { label: 'Emails', link: '/Support/Logging/Emails' }, ] }, { name: 'ACH files', link: '/AchFiles', subLinksExist: true, sublinks: [ { label: 'ACH Entry Finder', link: '/Support/AchFiles/AchEntryFinder' }, { label: 'ACH Rejects', link: '/Support/AchFiles/AchRejects' } ] }, { name: 'returns', link: '/Returns', subLinksExist: true, sublinks: [ { label: 'Return Files', link: '/Support/Returns/ReturnFiles' }, { label: 'Return Details', link: '/Support/Returns/ReturnDetails' }, { label: 'Exceptions', link: '/Support/Returns/Exceptions' }, { label: 'Reinitiations', link: '/Support/Returns/Reinitiations' }, { label: 'Notices Of Change', link: '/Support/Returns/NoticeOfChange' }, { label: 'Return Reconciliations', link: '/Support/Returns/ReturnReconciliations' }, ] }, { name: 'bulwark', link: '/Bulwark', subLinksExist: true, sublinks: [ { label: 'Risk Rule Configuration', link: '/Support/Bulwark/RiskRuleConfiguration' }, { label: 'Risk Rule Enforcement', link: '/Support/Bulwark/RiskRuleEnforcement' } ] } ] }, { primaryLink: 'Terminal', link: '/Terminal', subLinks: [ { name: 'virtual terminal', subLinksExist: false, link: '/VirtualTerminal' }, { name: 'history log', subLinksExist: false, link: '/HistoryLog' } ] }, { primaryLink: 'Sagacity', link: '/Sagacity', subLinks: [ { name: 'management', link: '/Management', subLinksExist: true, sublinks: [ { label: 'Business Units', link: '/Sagacity/Management/BusinessUnits' }, { label: 'Merchants', link: '/Sagacity/Management/Merchants' }, { label: 'Users', link: '/Sagacity/Management/Users' }, { label: 'Global', link: '/Sagacity/Management/Global' }, { label: 'GIACT Invoices', link: '/Sagacity/Management/GIACTInvoices' }, ] }, { name: 'history', link: '/History', subLinksExist: true, sublinks: [ { label: 'Bank Accounts', link: '/Sagacity/History/BankAccounts' }, { label: 'Consumers', link: '/Sagacity/History/Consumers' }, { label: 'Verification Requests', link: '/Sagacity/History/VerificationRequests' }, { label: 'Authentication Requests', link: '/Sagacity/History/AuthenticationRequests' }, { label: 'Statics', link: '/Sagacity/History/Statics' }, { label: 'Failed API Calls', link: '/Sagacity/History/FailedApiCalls' }, ] } ] } ] It is primarily flagging just the dropdown menus only. If you remove the dropdown components I dont get the error message. A: It seems that the output of filteredSubNavItems.map() is wrapped in a <></> fragment tag, and the error could be that this does not have an unique key. Perhaps try give the fragment tag a key such as: // '<></>' syntax may not work when keyed, might also need to import 'React' filteredSubNavItems.map((navItem, index) => { return ( <React.Fragment key={navItem.name}> {!navItem.subLinksExist ? ( <Nav.Link key={navItem.name} href={navItem.link}> {navItem.name} </Nav.Link> ) : ( <NavDropdown key={navItem.name} title={navItem.name} id={navItem.name}> {navItem.sublinks.map((item) => { return ( <NavDropdown.Item key={item.label}>{item.label}</NavDropdown.Item> ); })} </NavDropdown> )} </React.Fragment> ); }); Or perhaps not to wrap the return in a <></>, instead do different return with condition: filteredSubNavItems.map((navItem, index) => { if (!navItem.subLinksExist) return ( <Nav.Link key={navItem.name} href={navItem.link}> {navItem.name} </Nav.Link> ); return ( <NavDropdown key={navItem.name} title={navItem.name} id={navItem.name}> {navItem.sublinks.map((item) => { return ( <NavDropdown.Item key={item.label}>{item.label}</NavDropdown.Item> ); })} </NavDropdown> ); });
Why am I getting the error message about each list item should get a unique key when using the react-bootstrap with Nextjs?
Here is the current setup of the file right now below. You will see that my file does indeed have a key to each child component but its still flagging it and I think its more internal issues that I am not sure that I can fix. export default function SecondaryNav(props:NavItems) { const router = useRouter(); let [filteredSubNavItems, setFilteredSubNavItems] = useState<{}[]>([]) /* Filtering the props.navigation array and setting the filteredSubNavItems state to the filtered array. */ useEffect(() => { props.navigation.filter((item) => { if(item.link == router.route) { setFilteredSubNavItems(item.subLinks); } }) }) return ( <> <Navbar className={[styles.SecondaryNav].join(' ')}> <div className={['container', styles.secondaryNavContainer].join(' ')}> { filteredSubNavItems.map((navItem, index) => { return ( <> { !navItem.subLinksExist ? <Nav.Link key={navItem.name} href={navItem.link}>{navItem.name}</Nav.Link> : <NavDropdown key={navItem.name} title={navItem.name} id={navItem.name}> { navItem.sublinks.map((item) => { return ( <NavDropdown.Item key={item.label}>{item.label}</NavDropdown.Item> ) }) } </NavDropdown> } </> ) }) } </div> </Navbar> </> ) } And below is the file that I am pulling the data. export const menuItems = [ { primaryLink: 'Home', link: '/', subLinks: [ { name: 'tutorial', subLinksExist: false, link: '/Home/Tutorial' }, { name: 'contact', subLinksExist: false, link: '/Home/Contact' }, { name: 'about', subLinksExist: false, link: '/Home/About' }, { name: 'FAQ', subLinksExist: false, link: '/Home/Faq' }, { name: 'version', subLinksExist: false, link: '/Home/Version' }, { name: 'health check', subLinksExist: false, link: '/Home/Healthcheck' } ] }, { primaryLink: 'Configuration', link: '/Configuration', subLinks: [ { name: 'merchants', link: 'merchants', subLinksExist: true, ariaControls: false, ariaExpanded: false, sublinks: [ { label: 'Billing Groups', key: 'billing groups', link: 'Configuration/Merchants/BillingGroup' }, { label: 'Billing Group Chain', key: 'billing group chain', link: 'Configuration/Merchants/BillingGroupChain' }, { label: 'Payment Channels', key: 'payment channels', link: 'Configuration/Merchants/PaymentChannels' }, { label: 'Relationship Managers', key: 'relationship managers', link: 'Configuration/Merchants/RelationshipManagers' }, { label: 'Fee Templates', key: 'fee templates', link: 'Configuration/Merchants/FeeTemplates' }, { label: 'Billing Group Disbursement Hold', key: 'billing group disbursement hold', link: 'Configuration/Merchants/BillingGroupDisbursementHold' }, ] }, { name: 'partners', subLinksExist: false, link: 'Configuration/Partners' }, { name: 'ODFIs', link: '/odfis', subLinksExist: true, ariaControls: false, ariaExpanded: false, sublinks: [ { label: 'Bank Expenses', key: 'bank expenses', link: 'Configuration/ODFIs/BankExpenses' }, { label: 'Expense Batches', key: 'expense batches', link: 'Configuration/ODFIs/ExpenseBatches' }, { label: 'Routing Numbers', key: 'routing numbers', link: 'Configuration/ODFIs/RoutingNumbers' }, ] }, { name: 'business units', link: '/businessunits', subLinksExist: true, ariaControls: false, ariaExpanded: false, sublinks: [ { label: 'Support Contacts', key: 'support contacts', link: 'Configuration/BusinessUnits/SupportContacts' } ] }, { name: 'profile', link: '/profile', subLinksExist: true, ariaControls: false, ariaExpanded: false, sublinks: [ { label: 'API Profiles', key: 'api profiles', link: 'Configuration/Profile/APIProfiles' }, { label: 'Heartland Users', key: 'heartland users', link: 'Configuration/Profile/HeartlandUsers' }, { label: 'External Users', key: 'external users', link: 'Configuration/Profile/ExternalUsers' }, ] }, { name: 'system', subLinksExist: false, link: 'Configuration/System' } ] }, { primaryLink: 'Support', link: '/Support', subLinks: [ { name: 'automation', link: '/automation', subLinksExist: true, sublinks: [ { label: 'Alerts', link: '/Support/Automation/Alerts' }, { label: 'Subscriptions', link: '/Support/Automation/Subscriptions' }, { label: 'Jobs', link: '/Support/Automation/Jobs' }, ] }, { name: 'consumers', link: '/Consumers', subLinksExist: true, sublinks: [ { label: 'Blacklist', link: '/Support/Consumers/Blacklist' }, { label: 'Whitelist', link: '/Support/Consumers/Whitelist' }, { label: 'Provisional Whitelist', link: '/Support/Consumers/ProvisionalWhitelist' }, ] }, { name: 'invoices', link: '/Invoices', subLinksExist: true, sublinks: [ { label: 'Billing Group', link: '/Support/Invoices/BillingGroup' }, { label: 'Partner', link: '/Support/Invoices/Partner' } ] }, { name: 'logging', link: '/Logging', subLinksExist: true, sublinks: [ { label: 'Failed Api Calls', link: '/Support/Logging/FailedApiCalls' }, { label: 'Logs', link: '/Support/Logging/Logs' }, { label: 'Emails', link: '/Support/Logging/Emails' }, ] }, { name: 'ACH files', link: '/AchFiles', subLinksExist: true, sublinks: [ { label: 'ACH Entry Finder', link: '/Support/AchFiles/AchEntryFinder' }, { label: 'ACH Rejects', link: '/Support/AchFiles/AchRejects' } ] }, { name: 'returns', link: '/Returns', subLinksExist: true, sublinks: [ { label: 'Return Files', link: '/Support/Returns/ReturnFiles' }, { label: 'Return Details', link: '/Support/Returns/ReturnDetails' }, { label: 'Exceptions', link: '/Support/Returns/Exceptions' }, { label: 'Reinitiations', link: '/Support/Returns/Reinitiations' }, { label: 'Notices Of Change', link: '/Support/Returns/NoticeOfChange' }, { label: 'Return Reconciliations', link: '/Support/Returns/ReturnReconciliations' }, ] }, { name: 'bulwark', link: '/Bulwark', subLinksExist: true, sublinks: [ { label: 'Risk Rule Configuration', link: '/Support/Bulwark/RiskRuleConfiguration' }, { label: 'Risk Rule Enforcement', link: '/Support/Bulwark/RiskRuleEnforcement' } ] } ] }, { primaryLink: 'Terminal', link: '/Terminal', subLinks: [ { name: 'virtual terminal', subLinksExist: false, link: '/VirtualTerminal' }, { name: 'history log', subLinksExist: false, link: '/HistoryLog' } ] }, { primaryLink: 'Sagacity', link: '/Sagacity', subLinks: [ { name: 'management', link: '/Management', subLinksExist: true, sublinks: [ { label: 'Business Units', link: '/Sagacity/Management/BusinessUnits' }, { label: 'Merchants', link: '/Sagacity/Management/Merchants' }, { label: 'Users', link: '/Sagacity/Management/Users' }, { label: 'Global', link: '/Sagacity/Management/Global' }, { label: 'GIACT Invoices', link: '/Sagacity/Management/GIACTInvoices' }, ] }, { name: 'history', link: '/History', subLinksExist: true, sublinks: [ { label: 'Bank Accounts', link: '/Sagacity/History/BankAccounts' }, { label: 'Consumers', link: '/Sagacity/History/Consumers' }, { label: 'Verification Requests', link: '/Sagacity/History/VerificationRequests' }, { label: 'Authentication Requests', link: '/Sagacity/History/AuthenticationRequests' }, { label: 'Statics', link: '/Sagacity/History/Statics' }, { label: 'Failed API Calls', link: '/Sagacity/History/FailedApiCalls' }, ] } ] } ] It is primarily flagging just the dropdown menus only. If you remove the dropdown components I dont get the error message.
[ "It seems that the output of filteredSubNavItems.map() is wrapped in a <></> fragment tag, and the error could be that this does not have an unique key.\nPerhaps try give the fragment tag a key such as:\n// '<></>' syntax may not work when keyed, might also need to import 'React'\n\nfilteredSubNavItems.map((navItem, index) => {\n return (\n <React.Fragment key={navItem.name}>\n {!navItem.subLinksExist ? (\n <Nav.Link key={navItem.name} href={navItem.link}>\n {navItem.name}\n </Nav.Link>\n ) : (\n <NavDropdown key={navItem.name} title={navItem.name} id={navItem.name}>\n {navItem.sublinks.map((item) => {\n return (\n <NavDropdown.Item key={item.label}>{item.label}</NavDropdown.Item>\n );\n })}\n </NavDropdown>\n )}\n </React.Fragment>\n );\n});\n\n\nOr perhaps not to wrap the return in a <></>, instead do different return with condition:\nfilteredSubNavItems.map((navItem, index) => {\n if (!navItem.subLinksExist)\n return (\n <Nav.Link key={navItem.name} href={navItem.link}>\n {navItem.name}\n </Nav.Link>\n );\n return (\n <NavDropdown key={navItem.name} title={navItem.name} id={navItem.name}>\n {navItem.sublinks.map((item) => {\n return (\n <NavDropdown.Item key={item.label}>{item.label}</NavDropdown.Item>\n );\n })}\n </NavDropdown>\n );\n});\n\n" ]
[ 1 ]
[]
[]
[ "javascript", "next.js", "react_bootstrap", "reactjs" ]
stackoverflow_0074660288_javascript_next.js_react_bootstrap_reactjs.txt
Q: angular - dynamically include or remove an interceptor Is it possible to dynamically include or exclude an interceptor? For example, I would like to enable Azure AD based SSO in my application using microsoft's @azure/msal-angular package https://www.npmjs.com/package/@azure/msal-angular that provides an interceptor. However, I intend my application to run in two modes - one with SSO based on msal package provided interceptor and one without (i.e. route authentication to some other backend server instead of azure AD). Therefore, i want to include msal interceptor if SSO mode is selected and i wish to to exclude this interceptor if SSO mode is not selected at run time by a user. How do I implement this dynamically based on what user chooses on login screen? Further details below: Below is what microsoft provides as a sample application that uses their package for authentication https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-angular-v2-samples/angular11-sample-app app.module.ts of sample application has following way of including msal interceptor (snippet included). This always routes http to Azure AD for authenticaion. How can I dynamically remove this if my user doesn't want this type of authentication? @NgModule({ declarations: [ AppComponent, HomeComponent, ProfileComponent, DetailComponent, LogoutComponent ], imports: [ BrowserModule, BrowserAnimationsModule, AppRoutingModule, MatButtonModule, MatToolbarModule, MatListModule, MatMenuModule, HttpClientModule, MsalModule ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true }, { provide: MSAL_INSTANCE, useFactory: MSALInstanceFactory }, { provide: MSAL_GUARD_CONFIG, useFactory: MSALGuardConfigFactory }, { provide: MSAL_INTERCEPTOR_CONFIG, useFactory: MSALInterceptorConfigFactory }, MsalService, MsalGuard, MsalBroadcastService ], bootstrap: [AppComponent, MsalRedirectComponent] }) export class AppModule { } A: You can add an environment variable flag like sso and based on its value add msal providers. in environment.dev.ts export const ENVIRONMENT = { .........., sso: false, .........., }; in environment.prod.ts export const ENVIRONMENT = { .........., sso: true, .........., }; in app.module.ts const MSAL_PROVIDERS = [ { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true }, { provide: MSAL_INSTANCE, useFactory: MSALInstanceFactory }, { provide: MSAL_GUARD_CONFIG, useFactory: MSALGuardConfigFactory }, { provide: MSAL_INTERCEPTOR_CONFIG, useFactory: MSALInterceptorConfigFactory }, MsalService, MsalGuard, MsalBroadcastService ] @NgModule({ declarations: [ ....... ], imports: [ ....... ], providers: [ ............, ENVIRONMENT.sso ? MSAL_PROVIDERS : [] ], }); Hope it works.
angular - dynamically include or remove an interceptor
Is it possible to dynamically include or exclude an interceptor? For example, I would like to enable Azure AD based SSO in my application using microsoft's @azure/msal-angular package https://www.npmjs.com/package/@azure/msal-angular that provides an interceptor. However, I intend my application to run in two modes - one with SSO based on msal package provided interceptor and one without (i.e. route authentication to some other backend server instead of azure AD). Therefore, i want to include msal interceptor if SSO mode is selected and i wish to to exclude this interceptor if SSO mode is not selected at run time by a user. How do I implement this dynamically based on what user chooses on login screen? Further details below: Below is what microsoft provides as a sample application that uses their package for authentication https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-angular-v2-samples/angular11-sample-app app.module.ts of sample application has following way of including msal interceptor (snippet included). This always routes http to Azure AD for authenticaion. How can I dynamically remove this if my user doesn't want this type of authentication? @NgModule({ declarations: [ AppComponent, HomeComponent, ProfileComponent, DetailComponent, LogoutComponent ], imports: [ BrowserModule, BrowserAnimationsModule, AppRoutingModule, MatButtonModule, MatToolbarModule, MatListModule, MatMenuModule, HttpClientModule, MsalModule ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true }, { provide: MSAL_INSTANCE, useFactory: MSALInstanceFactory }, { provide: MSAL_GUARD_CONFIG, useFactory: MSALGuardConfigFactory }, { provide: MSAL_INTERCEPTOR_CONFIG, useFactory: MSALInterceptorConfigFactory }, MsalService, MsalGuard, MsalBroadcastService ], bootstrap: [AppComponent, MsalRedirectComponent] }) export class AppModule { }
[ "You can add an environment variable flag like sso and based on its value add msal providers.\nin environment.dev.ts\nexport const ENVIRONMENT = {\n ..........,\n sso: false,\n ..........,\n};\n\nin environment.prod.ts\nexport const ENVIRONMENT = {\n ..........,\n sso: true,\n ..........,\n};\n\nin app.module.ts\nconst MSAL_PROVIDERS = [\n { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true },\n { provide: MSAL_INSTANCE, useFactory: MSALInstanceFactory },\n { provide: MSAL_GUARD_CONFIG, useFactory: MSALGuardConfigFactory },\n { provide: MSAL_INTERCEPTOR_CONFIG, useFactory: MSALInterceptorConfigFactory },\n MsalService,\n MsalGuard,\n MsalBroadcastService\n]\n\n@NgModule({\n declarations: [ ....... ],\n imports: [ ....... ],\n providers: [\n ............,\n ENVIRONMENT.sso ? MSAL_PROVIDERS : [] \n ],\n});\n\nHope it works.\n" ]
[ 0 ]
[]
[]
[ "angular", "angular_http_interceptors", "msal", "msal_angular" ]
stackoverflow_0072810165_angular_angular_http_interceptors_msal_msal_angular.txt
Q: Using IF function in Google Sheets with Negative numbers (e.g -60 or -180) I'm confused about this. How can I use an IF Function with negative numbers? For example if C2 (with a current value of -60) is more than -60, change the value in another cell using IF. =IF(C2<=-60,"Send","Not Yet") =IF(C2>-180,"True","False") Thanks! ``=IF(C2<=-60,"Send","Not Yet")` `=IF(C2>-180,"True","False")`` A: Your question is not clear, but if in the cell you want to change, you have the following formula: =IF(C2>-60,"Yes","No") This cell value will be Yes if C2 value is greater than -60 and No otherwise exemple: C2 = 0 => 'Yes' in the other cell C2 = -70 => No in the other cell I hope that my answer is helpful
Using IF function in Google Sheets with Negative numbers (e.g -60 or -180)
I'm confused about this. How can I use an IF Function with negative numbers? For example if C2 (with a current value of -60) is more than -60, change the value in another cell using IF. =IF(C2<=-60,"Send","Not Yet") =IF(C2>-180,"True","False") Thanks! ``=IF(C2<=-60,"Send","Not Yet")` `=IF(C2>-180,"True","False")``
[ "Your question is not clear, but if in the cell you want to change, you have the following formula:\n=IF(C2>-60,\"Yes\",\"No\")\nThis cell value will be Yes if C2 value is greater than -60 and No otherwise\nexemple:\n\nC2 = 0 => 'Yes' in the other cell\nC2 = -70 => No in the other cell\n\nI hope that my answer is helpful\n" ]
[ 0 ]
[]
[]
[ "google_sheets" ]
stackoverflow_0074660281_google_sheets.txt
Q: Embedded fonts in SVG not showing correctly in browser There is SVG with two different font types: SymbolMT for the math expressions and Hind-Light for the text. Both fonts are defined in @font-face section in SVG. The font for the math expression looks fine but the font for the text is not the same as Hind-Light. SVGs are embeded in a web page which is using the same font "Hind-Light". here is fiddle example: https://jsfiddle.net/gde58zw9/ An idea how to fix that font for the text ? <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Ebene_1" x="0px" y="0px" width="161.501px" height="64.485px" viewBox="0 0 161.501 64.485" enable-background="new 0 0 161.501 64.485" xml:space="preserve"> <style type="text/css"> <![CDATA[ @font-face { font-family: 'Hind-Light'; src: url('data:font/woff2;charset=utf-8;base64,d09GMgABA') format('woff2'), font-weight: 300; font-style: normal; font-display: swap; } ]]> A: The 'Hind Light' is now correctly embedded in your jsfiddle example. You can also reduce the filesize of the base64 chunk by defining a subset in the transfonter UI. But you still see an error message for the 'Symbol MT'. Unfortunately it's nearly impossible to create a usable subset for embedding since the Symbol MT has a custom character encoding "MS Windows Symbol" (at least the windows version. Regular fonts set the summation/sigma) symbol at: ∑ = &#x2211; regular font ∑ = &#xF0E5 Symbol MT (Data retrieved with fontdrop) Using a desktop application, the Symbol MT encoding gets converted/remapped. When exporting the svg - the <text> element uses the regular encoding &#x2211;. Since 'Symbol MT' doesn't have this codepoint – you see the 'Times New Roman' summation symbol as fallback, which is noticably bigger. <span class="times">&#x2211;</span> <span class="symbol">&#xF0E5;</span> <style> body{ font-size:10vw; } .symbol{ font-family:Symbol; } .times{ font-family:'Times New Roman', serif } </style> Workarounds You could base64 encode the original truetype font without any conversion and change the summation symbol to &#xF0E5 – not very convenient. Working codepen. Alternative: Install all used fonts ('Hind Light') locally so they are avaible in all aplications. Open your svg in your editor (Inkscape, Adobe Illustrator etc.). Apply the fonts to your text elements. Convert all text to paths. Actually, this might quite often produce smaller files than embedding font subsets. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 161.5 64.48"> <path d="M63.89 8.19h-.6V4.91c0-.38-.1-.68-.29-.88-.2-.2-.45-.3-.77-.3-.4 0-.75.15-1.05.46-.29.31-.44.73-.44 1.26v2.74h-.6V3.23h.6v.85c.31-.62.83-.93 1.58-.93.48 0 .86.15 1.14.44.29.29.43.67.43 1.13v3.47zm93.88 8.75h-3.98v-.54c2.09-1.6 3.13-2.93 3.13-3.99 0-.44-.13-.78-.38-1.01s-.59-.35-1.01-.35c-.49 0-.99.19-1.51.57v-.61a2.4 2.4 0 0 1 2.94-.04c.39.32.59.8.59 1.4 0 1.13-.97 2.47-2.91 4.02h3.13v.55zM11.96 20.47h-1.83v6.04h-.61v-6.04H7.7v-.56h4.25v.56zm26 4.77c0 .41-.14.74-.43.97-.28.24-.67.36-1.17.36-.6 0-1.08-.1-1.45-.29v-.62c.44.25.91.37 1.41.37.33 0 .58-.07.76-.21s.26-.32.26-.54c0-.26-.09-.46-.27-.61s-.47-.3-.89-.46c-.4-.16-.71-.34-.95-.55-.23-.21-.35-.5-.35-.86 0-.4.15-.72.44-.95.29-.24.66-.36 1.11-.36.53 0 .95.08 1.23.22v.6a2.46 2.46 0 0 0-1.24-.26c-.29 0-.51.07-.68.2a.63.63 0 0 0-.25.52c0 .13.02.24.07.34.05.1.13.19.25.27a8.47 8.47 0 0 0 .72.36c.46.18.81.38 1.05.6.26.23.38.52.38.9zm1.72-5.57c.08.08.12.18.12.3s-.04.22-.12.29a.4.4 0 0 1-.3.12.37.37 0 0 1-.29-.12.42.42 0 0 1 0-.59.4.4 0 0 1 .29-.12c.12-.01.22.03.3.12zm.01 6.84h-.6v-4.96h.6v4.96zm38.21-6.84c.08.08.12.18.12.3s-.04.22-.12.29a.4.4 0 0 1-.3.12.37.37 0 0 1-.29-.12.42.42 0 0 1 0-.59.4.4 0 0 1 .29-.12c.12-.01.21.03.3.12zm0 6.84h-.6v-4.96h.6v4.96zm24.84-1.27c0 .41-.14.74-.42.97-.28.24-.67.36-1.17.36-.6 0-1.08-.1-1.45-.29v-.62c.44.25.91.37 1.41.37.33 0 .59-.07.76-.21a.67.67 0 0 0 .26-.54.75.75 0 0 0-.27-.61c-.18-.14-.47-.3-.88-.46-.4-.16-.71-.34-.95-.55-.23-.21-.35-.5-.35-.86 0-.4.15-.72.44-.95.29-.24.66-.36 1.11-.36.54 0 .95.08 1.23.22v.6a2.46 2.46 0 0 0-1.24-.26c-.29 0-.51.07-.68.2s-.25.31-.25.52c0 .13.02.24.07.34.05.1.13.19.25.27a8.47 8.47 0 0 0 .72.36c.46.18.81.38 1.05.6.23.23.36.52.36.9zm4.63 1.02c-.39.2-.85.29-1.37.29a2.4 2.4 0 0 1-1.79-.69 2.44 2.44 0 0 1-.69-1.81c0-.8.2-1.42.61-1.88s.93-.68 1.58-.68c.61 0 1.09.2 1.45.6.36.4.54.96.54 1.68 0 .22-.01.4-.04.53h-3.5c.05.55.24.97.57 1.26.33.29.77.44 1.32.44a2.4 2.4 0 0 0 1.34-.33v.59zm-1.69-4.21c-.42 0-.77.15-1.05.44-.28.29-.44.71-.49 1.26h2.93v-.22c0-.45-.13-.81-.38-1.08s-.59-.4-1.01-.4zm27.28 4.46h-.6v-5.74l-1.44.9V21l1.44-.88h.6v6.39zm21.52 0h-.67l1.63-2.55-1.54-2.42h.7l1.21 1.96 1.2-1.96h.7l-1.55 2.43 1.66 2.54h-.71l-1.3-2.08-1.33 2.08zM57.65 29.7c.08.08.12.18.12.3s-.04.22-.12.29a.4.4 0 0 1-.3.12.37.37 0 0 1-.29-.12.42.42 0 0 1 0-.59.4.4 0 0 1 .29-.12.4.4 0 0 1 .3.12zm0 6.84h-.6v-4.96h.6v4.96zm9.38 0h-.6V30.8l-1.43.9v-.67l1.44-.88h.6v6.39zM3.42 18.97H1.99v3.84h-.87v-9.44h2.13c1.1 0 1.92.25 2.47.75.55.5.82 1.21.82 2.12-.02.63-.2 1.18-.53 1.64s-.81.77-1.43.94l2.51 3.99H6.05l-2.37-3.85-.26.01zm-.07-4.83H1.99v4.06h1.53c.69 0 1.22-.19 1.6-.57.37-.38.56-.86.56-1.43-.01-1.38-.78-2.06-2.33-2.06zm27.31 4.83h-1.43v3.84h-.87v-9.44h2.13c1.1 0 1.92.25 2.47.75.55.5.82 1.21.82 2.12-.02.63-.2 1.18-.53 1.64s-.81.77-1.43.94l2.51 3.99h-1.04l-2.37-3.85-.26.01zm-.07-4.83h-1.36v4.06h1.53c.69 0 1.22-.19 1.6-.57.37-.38.56-.86.56-1.43-.01-1.38-.78-2.06-2.33-2.06zm42.25 4.83h-1.43v3.84h-.87v-9.44h2.13c1.1 0 1.92.25 2.47.75.55.5.82 1.21.82 2.12-.02.63-.2 1.18-.53 1.64s-.81.77-1.43.94l2.51 3.99h-1.04l-2.37-3.85-.26.01zm-.07-4.83h-1.36v4.06h1.53c.69 0 1.22-.19 1.6-.57.37-.38.56-.86.56-1.43 0-1.38-.78-2.06-2.33-2.06zm22.65 4.83H94v3.84h-.87v-9.44h2.13c1.1 0 1.92.25 2.47.75.55.5.82 1.21.82 2.12-.02.63-.2 1.18-.53 1.64s-.81.77-1.43.94l2.51 3.99h-1.04l-2.37-3.85-.27.01zm-.07-4.83H94v4.06h1.53c.69 0 1.22-.19 1.6-.57.37-.38.56-.86.56-1.43-.01-1.38-.79-2.06-2.34-2.06zm57.85 8.66h-.85v-4.69c0-.55-.14-.97-.42-1.26a1.47 1.47 0 0 0-1.11-.43c-.58 0-1.08.22-1.5.67s-.63 1.04-.63 1.8v3.92h-.85v-7.1h.85v1.22c.44-.89 1.19-1.33 2.25-1.33.68 0 1.23.21 1.64.63.41.42.62.96.62 1.62v4.95zM7.73 57.96h-.87v-4.41H1.99v4.41h-.87v-9.44h.87v4.23h4.87v-4.23h.87v9.44zm3-9.79c.12.12.18.26.18.43s-.06.31-.18.42c-.12.11-.26.17-.43.17s-.3-.06-.42-.18c-.11-.11-.17-.25-.17-.42s.06-.31.17-.43c.11-.12.25-.17.42-.17s.31.06.43.18zm.01 9.79h-.86v-7.1h.85v7.1zm7.52 0h-.86v-4.69c0-.55-.14-.97-.42-1.26a1.47 1.47 0 0 0-1.11-.43c-.58 0-1.08.22-1.5.67s-.63 1.04-.63 1.8v3.92h-.85v-7.1h.85v1.22c.44-.89 1.19-1.33 2.25-1.33.68 0 1.23.21 1.64.63s.62.96.62 1.62v4.95zm7.71 0h-.85v-1.04a2.44 2.44 0 0 1-2.2 1.15c-.95 0-1.69-.35-2.23-1.04-.53-.7-.8-1.54-.8-2.54 0-1.1.28-2 .85-2.7s1.3-1.04 2.2-1.04c.92 0 1.65.39 2.17 1.18v-3.86h.85v9.89zm-5.18-3.46c0 .81.2 1.47.6 1.99.4.51.9.77 1.5.77.61 0 1.13-.22 1.57-.67.44-.44.66-1.18.66-2.22 0-.52-.07-.98-.22-1.37a2.06 2.06 0 0 0-1.25-1.31 1.93 1.93 0 0 0-2.25.63c-.4.51-.61 1.24-.61 2.18zm11.61 3.46h-.85v-9.9h.85v9.9zm3.08-9.79c.12.12.18.26.18.43s-.06.31-.18.42c-.12.11-.26.17-.43.17s-.31-.06-.42-.17c-.11-.11-.17-.25-.17-.42s.06-.31.17-.43c.11-.12.25-.17.42-.17s.32.05.43.17zm.01 9.79h-.85v-7.1h.85v7.1zm7.63-.55c0 1.07-.29 1.88-.87 2.42-.58.54-1.33.8-2.24.8-.81 0-1.5-.13-2.07-.41v-.84c.58.29 1.25.43 2 .43.71 0 1.27-.19 1.69-.58.42-.39.63-1 .63-1.83v-.92a2.3 2.3 0 0 1-2.13 1.3c-.82 0-1.52-.3-2.09-.91a3.46 3.46 0 0 1-.86-2.46c0-1.06.26-1.94.79-2.63s1.22-1.04 2.08-1.04a2.3 2.3 0 0 1 2.21 1.36v-1.25h.85v6.56zm-5.04-3.03c0 .85.21 1.5.64 1.94s.91.66 1.43.66a2.1 2.1 0 0 0 1.46-.62c.44-.42.66-1.05.66-1.91 0-.98-.21-1.71-.63-2.18a1.87 1.87 0 0 0-2.98.07 3.35 3.35 0 0 0-.58 2.04zm12.35 3.58h-.85v-4.69c0-.55-.14-.97-.42-1.26a1.47 1.47 0 0 0-1.11-.43c-.58 0-1.08.22-1.5.67s-.63 1.04-.63 1.8v3.92h-.85v-9.9h.85v4.02c.43-.89 1.18-1.33 2.25-1.33.68 0 1.23.21 1.64.63s.62.96.62 1.62v4.95zm5.47-.2c-.27.18-.58.27-.94.27-1.34 0-2.02-.69-2.02-2.07v-4.37h-1.16v-.73h1.16v-1.78h.87v1.78h2.03v.73h-2.03V56c0 .81.38 1.22 1.13 1.22.37 0 .69-.11.95-.32v.86zm7.06.2h-.86v-8.22l-2.06 1.29v-.97l2.06-1.26h.85v9.16zm6.89 0h-.84v-2.3h-4.24v-.77l3.67-6.09h1.41v6.09h1.41v.77h-1.41v2.3zm-4.2-3.07h3.36v-5.6l-3.36 5.6zm11.14 5.87h-.85v-9.9h.85v1.04a2.44 2.44 0 0 1 2.2-1.15c.95 0 1.69.35 2.23 1.04.53.7.8 1.54.8 2.54 0 1.1-.29 2-.85 2.7a2.7 2.7 0 0 1-2.2 1.04c-.92 0-1.65-.39-2.17-1.18v3.87zm0-6.31c0 .52.07.98.22 1.36a2.16 2.16 0 0 0 1.25 1.31 1.93 1.93 0 0 0 2.25-.63c.41-.51.62-1.23.62-2.18 0-.81-.2-1.47-.6-1.99-.4-.51-.9-.77-1.5-.77-.61 0-1.13.22-1.57.67-.45.45-.67 1.19-.67 2.23zm10.41 3.31c-.27.18-.58.27-.94.27-1.34 0-2.02-.69-2.02-2.07v-4.37h-1.16v-.73h1.16v-1.78h.87v1.78h2.03v.73h-2.03V56c0 .81.38 1.22 1.13 1.22.37 0 .69-.11.95-.32v.86zm10.21.2h-.85v-1.27c-.37.92-1.12 1.37-2.25 1.37a2.2 2.2 0 0 1-1.64-.62 2.23 2.23 0 0 1-.61-1.64v-4.93h.85v4.69c0 .54.14.96.43 1.25s.66.43 1.13.43a1.9 1.9 0 0 0 1.52-.67c.39-.45.58-1.03.58-1.75v-3.95h.85v7.09zm7.49 0h-.85v-4.69c0-.55-.14-.97-.42-1.26a1.47 1.47 0 0 0-1.11-.43c-.58 0-1.08.22-1.5.67s-.63 1.04-.63 1.8v3.92h-.85v-7.1h.85v1.22c.44-.89 1.19-1.33 2.25-1.33.68 0 1.23.21 1.64.63s.62.96.62 1.62v4.95zm7.74 0h-.85v-1.04a2.44 2.44 0 0 1-2.2 1.15c-.95 0-1.69-.35-2.23-1.04-.53-.7-.8-1.54-.8-2.54 0-1.1.28-2 .85-2.7a2.7 2.7 0 0 1 2.2-1.04c.92 0 1.65.39 2.17 1.18v-3.86h.85v9.89zm-5.18-3.46c0 .81.2 1.47.6 1.99.4.51.9.77 1.5.77s1.13-.22 1.57-.67c.44-.44.66-1.18.66-2.22 0-.52-.07-.98-.22-1.37a2.06 2.06 0 0 0-1.25-1.31 1.93 1.93 0 0 0-2.25.63c-.4.51-.61 1.24-.61 2.18zm16.1 1.02c0 .82-.28 1.45-.83 1.88-.55.43-1.26.65-2.12.65-.97 0-1.8-.21-2.48-.62v-.97a4.43 4.43 0 0 0 2.43.74c.66 0 1.18-.14 1.55-.43.37-.29.55-.71.55-1.25 0-.41-.14-.74-.42-1s-.69-.5-1.22-.74l-.49-.22-.53-.23-.48-.24a3.1 3.1 0 0 1-.47-.29l-.37-.34a1.3 1.3 0 0 1-.32-.42 2.63 2.63 0 0 1-.26-1.11c0-.79.29-1.41.85-1.86a3.3 3.3 0 0 1 2.09-.66c.78 0 1.44.14 1.96.42v.97a3.99 3.99 0 0 0-1.94-.53c-.63 0-1.13.15-1.5.44-.37.29-.56.68-.56 1.17 0 .25.05.48.15.67.1.2.26.38.5.54a6.17 6.17 0 0 0 1.4.74l.74.33c.17.08.38.2.64.37s.46.33.6.5a2.44 2.44 0 0 1 .53 1.49zm4.87 2.26a4.27 4.27 0 0 1-1.26 1.99 2.7 2.7 0 0 1-1.65.55c-.19 0-.36-.02-.53-.07v-.85c.17.05.33.07.48.07 1 0 1.69-.57 2.09-1.71l-2.9-6.9h.98l.96 2.38 1.37 3.42c.06-.21.47-1.35 1.22-3.42l.87-2.38h.95l-2.58 6.92zm13.19.18h-.85v-4.69c0-1.13-.49-1.69-1.48-1.69-.48 0-.92.22-1.29.67a2.67 2.67 0 0 0-.57 1.79v3.92h-.85v-4.69c0-1.13-.5-1.69-1.48-1.69-.49 0-.92.22-1.29.67a2.67 2.67 0 0 0-.57 1.79v3.92h-.85v-7.1h.85v1.16a2.04 2.04 0 0 1 1.99-1.27c1.14 0 1.84.47 2.1 1.4.44-.93 1.14-1.4 2.1-1.4.75 0 1.3.21 1.67.62.36.42.54.96.54 1.63v4.96zm3.03 0h-.85v-9.9h.85v3.86a2.49 2.49 0 0 1 2.17-1.18c.9 0 1.63.35 2.2 1.04s.85 1.59.85 2.7c0 1-.27 1.85-.8 2.54a2.62 2.62 0 0 1-2.23 1.04c-.97 0-1.7-.38-2.2-1.15v1.05zm0-3.58c0 1.04.22 1.78.66 2.22s.96.67 1.57.67 1.11-.26 1.5-.77c.4-.51.59-1.18.59-1.99a3.4 3.4 0 0 0-.62-2.18 1.92 1.92 0 0 0-2.25-.63 2.12 2.12 0 0 0-1.25 1.31c-.13.39-.2.84-.2 1.37zm13.11.07c0 1.05-.3 1.92-.89 2.61a3.05 3.05 0 0 1-2.44 1.03c-1 0-1.79-.34-2.38-1.04a3.86 3.86 0 0 1-.88-2.6c0-1.04.3-1.91.91-2.62a2.95 2.95 0 0 1 2.35-1.06c1.05 0 1.87.35 2.46 1.04.58.69.87 1.57.87 2.64zm-5.7 0c0 .77.22 1.44.65 2 .43.55 1.01.83 1.71.83.78 0 1.38-.27 1.8-.82.43-.55.64-1.22.64-2.01 0-.82-.2-1.5-.6-2.05-.4-.55-1.01-.82-1.83-.82-.74 0-1.32.28-1.74.84a3.27 3.27 0 0 0-.63 2.03zm8.32 3.51h-.85v-9.9h.85v9.9zM58.95 32.91h5.01v.46h-5.01v-.46zm0 1.79h5.01v.47h-5.01v-.47zm-41.7-17.08h7.18v.66h-7.18v-.66zm0 2.55h7.18v.68h-7.18v-.68zm30.35-4.54h.67v3.27h3.25v.66h-3.25v3.25h-.67v-3.25h-3.26v-.66h3.26v-3.27zm38.22 0h.67v3.27h3.25v.66h-3.25v3.25h-.67v-3.25h-3.26v-.66h3.26v-3.27zm26.53.59 2.54 2.53 2.54-2.53.47.46-2.54 2.55 2.54 2.53-.47.48-2.54-2.54-2.54 2.54-.48-.48 2.54-2.54-2.54-2.53.48-.47zm13.58.32v6.07c.35-.07.63-.2.85-.38s.4-.5.56-.95.29-1.25.39-2.41c.09-.96.24-1.62.45-1.98.21-.36.57-.54 1.08-.54.17 0 .43.04.77.12v.23c-.2 0-.34.03-.44.1-.13.1-.24.27-.32.52s-.16.7-.23 1.36a8.6 8.6 0 0 1-.45 2.32 3.6 3.6 0 0 1-1.58 1.7c-.32.16-.68.26-1.08.3v2.83h-.75V23a3.31 3.31 0 0 1-2.67-1.99c-.17-.41-.32-1.19-.45-2.34-.08-.69-.15-1.16-.23-1.39s-.18-.4-.31-.49c-.08-.06-.23-.09-.44-.09v-.23c.38-.08.64-.12.79-.12a1.31 1.31 0 0 1 1.26.92c.11.31.2.84.27 1.6.09 1.13.21 1.92.37 2.37.16.46.34.78.56.97.21.19.5.32.86.4v-6.07h.74zm11.6 2.33h7.18v.68h-7.18v-.68zm-69.05 9.25H55.02v-.37l6.86-8.52-6.86-8.38v-.38h13.1l.28 3.46h-.41c-.11-.94-.37-1.62-.79-2.02a2.46 2.46 0 0 0-1.76-.61h-7.59l5.76 7.04-6.45 7.97h8.39c.48 0 1-.09 1.57-.28.39-.13.71-.36.97-.69.26-.33.47-.85.64-1.55l.41.07-.66 4.26z"/> </svg> Drawback: you can't select any text, since every text was converted to <path> elements.
Embedded fonts in SVG not showing correctly in browser
There is SVG with two different font types: SymbolMT for the math expressions and Hind-Light for the text. Both fonts are defined in @font-face section in SVG. The font for the math expression looks fine but the font for the text is not the same as Hind-Light. SVGs are embeded in a web page which is using the same font "Hind-Light". here is fiddle example: https://jsfiddle.net/gde58zw9/ An idea how to fix that font for the text ? <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Ebene_1" x="0px" y="0px" width="161.501px" height="64.485px" viewBox="0 0 161.501 64.485" enable-background="new 0 0 161.501 64.485" xml:space="preserve"> <style type="text/css"> <![CDATA[ @font-face { font-family: 'Hind-Light'; src: url('data:font/woff2;charset=utf-8;base64,d09GMgABA') format('woff2'), font-weight: 300; font-style: normal; font-display: swap; } ]]>
[ "The 'Hind Light' is now correctly embedded in your jsfiddle example.\nYou can also reduce the filesize of the base64 chunk by defining a subset in the transfonter UI.\n\nBut you still see an error message for the 'Symbol MT'.\nUnfortunately it's nearly impossible to create a usable subset for embedding since the Symbol MT has a custom character encoding \"MS Windows Symbol\" (at least the windows version. \nRegular fonts set the summation/sigma) symbol at:\n∑ = &#x2211; regular font\n∑ = &#xF0E5 Symbol MT\n(Data retrieved with fontdrop)\nUsing a desktop application, the Symbol MT encoding gets converted/remapped.\nWhen exporting the svg - the <text> element uses the regular encoding &#x2211;.\nSince 'Symbol MT' doesn't have this codepoint – you see the 'Times New Roman' summation symbol as fallback, which is noticably bigger.\n\n\n<span class=\"times\">&#x2211;</span> <span class=\"symbol\">&#xF0E5;</span>\n\n<style>\nbody{\nfont-size:10vw;\n}\n\n.symbol{\n font-family:Symbol;\n}\n\n.times{\n font-family:'Times New Roman', serif\n}\n</style>\n\n\n\nWorkarounds\nYou could base64 encode the original truetype font without any conversion and change the summation symbol to &#xF0E5 – not very convenient.\nWorking codepen.\nAlternative: Install all used fonts ('Hind Light') locally so they are avaible in all aplications.\nOpen your svg in your editor (Inkscape, Adobe Illustrator etc.).\nApply the fonts to your text elements.\nConvert all text to paths.\nActually, this might quite often produce smaller files than embedding font subsets.\n\n\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 161.5 64.48\">\n <path d=\"M63.89 8.19h-.6V4.91c0-.38-.1-.68-.29-.88-.2-.2-.45-.3-.77-.3-.4 0-.75.15-1.05.46-.29.31-.44.73-.44 1.26v2.74h-.6V3.23h.6v.85c.31-.62.83-.93 1.58-.93.48 0 .86.15 1.14.44.29.29.43.67.43 1.13v3.47zm93.88 8.75h-3.98v-.54c2.09-1.6 3.13-2.93 3.13-3.99 0-.44-.13-.78-.38-1.01s-.59-.35-1.01-.35c-.49 0-.99.19-1.51.57v-.61a2.4 2.4 0 0 1 2.94-.04c.39.32.59.8.59 1.4 0 1.13-.97 2.47-2.91 4.02h3.13v.55zM11.96 20.47h-1.83v6.04h-.61v-6.04H7.7v-.56h4.25v.56zm26 4.77c0 .41-.14.74-.43.97-.28.24-.67.36-1.17.36-.6 0-1.08-.1-1.45-.29v-.62c.44.25.91.37 1.41.37.33 0 .58-.07.76-.21s.26-.32.26-.54c0-.26-.09-.46-.27-.61s-.47-.3-.89-.46c-.4-.16-.71-.34-.95-.55-.23-.21-.35-.5-.35-.86 0-.4.15-.72.44-.95.29-.24.66-.36 1.11-.36.53 0 .95.08 1.23.22v.6a2.46 2.46 0 0 0-1.24-.26c-.29 0-.51.07-.68.2a.63.63 0 0 0-.25.52c0 .13.02.24.07.34.05.1.13.19.25.27a8.47 8.47 0 0 0 .72.36c.46.18.81.38 1.05.6.26.23.38.52.38.9zm1.72-5.57c.08.08.12.18.12.3s-.04.22-.12.29a.4.4 0 0 1-.3.12.37.37 0 0 1-.29-.12.42.42 0 0 1 0-.59.4.4 0 0 1 .29-.12c.12-.01.22.03.3.12zm.01 6.84h-.6v-4.96h.6v4.96zm38.21-6.84c.08.08.12.18.12.3s-.04.22-.12.29a.4.4 0 0 1-.3.12.37.37 0 0 1-.29-.12.42.42 0 0 1 0-.59.4.4 0 0 1 .29-.12c.12-.01.21.03.3.12zm0 6.84h-.6v-4.96h.6v4.96zm24.84-1.27c0 .41-.14.74-.42.97-.28.24-.67.36-1.17.36-.6 0-1.08-.1-1.45-.29v-.62c.44.25.91.37 1.41.37.33 0 .59-.07.76-.21a.67.67 0 0 0 .26-.54.75.75 0 0 0-.27-.61c-.18-.14-.47-.3-.88-.46-.4-.16-.71-.34-.95-.55-.23-.21-.35-.5-.35-.86 0-.4.15-.72.44-.95.29-.24.66-.36 1.11-.36.54 0 .95.08 1.23.22v.6a2.46 2.46 0 0 0-1.24-.26c-.29 0-.51.07-.68.2s-.25.31-.25.52c0 .13.02.24.07.34.05.1.13.19.25.27a8.47 8.47 0 0 0 .72.36c.46.18.81.38 1.05.6.23.23.36.52.36.9zm4.63 1.02c-.39.2-.85.29-1.37.29a2.4 2.4 0 0 1-1.79-.69 2.44 2.44 0 0 1-.69-1.81c0-.8.2-1.42.61-1.88s.93-.68 1.58-.68c.61 0 1.09.2 1.45.6.36.4.54.96.54 1.68 0 .22-.01.4-.04.53h-3.5c.05.55.24.97.57 1.26.33.29.77.44 1.32.44a2.4 2.4 0 0 0 1.34-.33v.59zm-1.69-4.21c-.42 0-.77.15-1.05.44-.28.29-.44.71-.49 1.26h2.93v-.22c0-.45-.13-.81-.38-1.08s-.59-.4-1.01-.4zm27.28 4.46h-.6v-5.74l-1.44.9V21l1.44-.88h.6v6.39zm21.52 0h-.67l1.63-2.55-1.54-2.42h.7l1.21 1.96 1.2-1.96h.7l-1.55 2.43 1.66 2.54h-.71l-1.3-2.08-1.33 2.08zM57.65 29.7c.08.08.12.18.12.3s-.04.22-.12.29a.4.4 0 0 1-.3.12.37.37 0 0 1-.29-.12.42.42 0 0 1 0-.59.4.4 0 0 1 .29-.12.4.4 0 0 1 .3.12zm0 6.84h-.6v-4.96h.6v4.96zm9.38 0h-.6V30.8l-1.43.9v-.67l1.44-.88h.6v6.39zM3.42 18.97H1.99v3.84h-.87v-9.44h2.13c1.1 0 1.92.25 2.47.75.55.5.82 1.21.82 2.12-.02.63-.2 1.18-.53 1.64s-.81.77-1.43.94l2.51 3.99H6.05l-2.37-3.85-.26.01zm-.07-4.83H1.99v4.06h1.53c.69 0 1.22-.19 1.6-.57.37-.38.56-.86.56-1.43-.01-1.38-.78-2.06-2.33-2.06zm27.31 4.83h-1.43v3.84h-.87v-9.44h2.13c1.1 0 1.92.25 2.47.75.55.5.82 1.21.82 2.12-.02.63-.2 1.18-.53 1.64s-.81.77-1.43.94l2.51 3.99h-1.04l-2.37-3.85-.26.01zm-.07-4.83h-1.36v4.06h1.53c.69 0 1.22-.19 1.6-.57.37-.38.56-.86.56-1.43-.01-1.38-.78-2.06-2.33-2.06zm42.25 4.83h-1.43v3.84h-.87v-9.44h2.13c1.1 0 1.92.25 2.47.75.55.5.82 1.21.82 2.12-.02.63-.2 1.18-.53 1.64s-.81.77-1.43.94l2.51 3.99h-1.04l-2.37-3.85-.26.01zm-.07-4.83h-1.36v4.06h1.53c.69 0 1.22-.19 1.6-.57.37-.38.56-.86.56-1.43 0-1.38-.78-2.06-2.33-2.06zm22.65 4.83H94v3.84h-.87v-9.44h2.13c1.1 0 1.92.25 2.47.75.55.5.82 1.21.82 2.12-.02.63-.2 1.18-.53 1.64s-.81.77-1.43.94l2.51 3.99h-1.04l-2.37-3.85-.27.01zm-.07-4.83H94v4.06h1.53c.69 0 1.22-.19 1.6-.57.37-.38.56-.86.56-1.43-.01-1.38-.79-2.06-2.34-2.06zm57.85 8.66h-.85v-4.69c0-.55-.14-.97-.42-1.26a1.47 1.47 0 0 0-1.11-.43c-.58 0-1.08.22-1.5.67s-.63 1.04-.63 1.8v3.92h-.85v-7.1h.85v1.22c.44-.89 1.19-1.33 2.25-1.33.68 0 1.23.21 1.64.63.41.42.62.96.62 1.62v4.95zM7.73 57.96h-.87v-4.41H1.99v4.41h-.87v-9.44h.87v4.23h4.87v-4.23h.87v9.44zm3-9.79c.12.12.18.26.18.43s-.06.31-.18.42c-.12.11-.26.17-.43.17s-.3-.06-.42-.18c-.11-.11-.17-.25-.17-.42s.06-.31.17-.43c.11-.12.25-.17.42-.17s.31.06.43.18zm.01 9.79h-.86v-7.1h.85v7.1zm7.52 0h-.86v-4.69c0-.55-.14-.97-.42-1.26a1.47 1.47 0 0 0-1.11-.43c-.58 0-1.08.22-1.5.67s-.63 1.04-.63 1.8v3.92h-.85v-7.1h.85v1.22c.44-.89 1.19-1.33 2.25-1.33.68 0 1.23.21 1.64.63s.62.96.62 1.62v4.95zm7.71 0h-.85v-1.04a2.44 2.44 0 0 1-2.2 1.15c-.95 0-1.69-.35-2.23-1.04-.53-.7-.8-1.54-.8-2.54 0-1.1.28-2 .85-2.7s1.3-1.04 2.2-1.04c.92 0 1.65.39 2.17 1.18v-3.86h.85v9.89zm-5.18-3.46c0 .81.2 1.47.6 1.99.4.51.9.77 1.5.77.61 0 1.13-.22 1.57-.67.44-.44.66-1.18.66-2.22 0-.52-.07-.98-.22-1.37a2.06 2.06 0 0 0-1.25-1.31 1.93 1.93 0 0 0-2.25.63c-.4.51-.61 1.24-.61 2.18zm11.61 3.46h-.85v-9.9h.85v9.9zm3.08-9.79c.12.12.18.26.18.43s-.06.31-.18.42c-.12.11-.26.17-.43.17s-.31-.06-.42-.17c-.11-.11-.17-.25-.17-.42s.06-.31.17-.43c.11-.12.25-.17.42-.17s.32.05.43.17zm.01 9.79h-.85v-7.1h.85v7.1zm7.63-.55c0 1.07-.29 1.88-.87 2.42-.58.54-1.33.8-2.24.8-.81 0-1.5-.13-2.07-.41v-.84c.58.29 1.25.43 2 .43.71 0 1.27-.19 1.69-.58.42-.39.63-1 .63-1.83v-.92a2.3 2.3 0 0 1-2.13 1.3c-.82 0-1.52-.3-2.09-.91a3.46 3.46 0 0 1-.86-2.46c0-1.06.26-1.94.79-2.63s1.22-1.04 2.08-1.04a2.3 2.3 0 0 1 2.21 1.36v-1.25h.85v6.56zm-5.04-3.03c0 .85.21 1.5.64 1.94s.91.66 1.43.66a2.1 2.1 0 0 0 1.46-.62c.44-.42.66-1.05.66-1.91 0-.98-.21-1.71-.63-2.18a1.87 1.87 0 0 0-2.98.07 3.35 3.35 0 0 0-.58 2.04zm12.35 3.58h-.85v-4.69c0-.55-.14-.97-.42-1.26a1.47 1.47 0 0 0-1.11-.43c-.58 0-1.08.22-1.5.67s-.63 1.04-.63 1.8v3.92h-.85v-9.9h.85v4.02c.43-.89 1.18-1.33 2.25-1.33.68 0 1.23.21 1.64.63s.62.96.62 1.62v4.95zm5.47-.2c-.27.18-.58.27-.94.27-1.34 0-2.02-.69-2.02-2.07v-4.37h-1.16v-.73h1.16v-1.78h.87v1.78h2.03v.73h-2.03V56c0 .81.38 1.22 1.13 1.22.37 0 .69-.11.95-.32v.86zm7.06.2h-.86v-8.22l-2.06 1.29v-.97l2.06-1.26h.85v9.16zm6.89 0h-.84v-2.3h-4.24v-.77l3.67-6.09h1.41v6.09h1.41v.77h-1.41v2.3zm-4.2-3.07h3.36v-5.6l-3.36 5.6zm11.14 5.87h-.85v-9.9h.85v1.04a2.44 2.44 0 0 1 2.2-1.15c.95 0 1.69.35 2.23 1.04.53.7.8 1.54.8 2.54 0 1.1-.29 2-.85 2.7a2.7 2.7 0 0 1-2.2 1.04c-.92 0-1.65-.39-2.17-1.18v3.87zm0-6.31c0 .52.07.98.22 1.36a2.16 2.16 0 0 0 1.25 1.31 1.93 1.93 0 0 0 2.25-.63c.41-.51.62-1.23.62-2.18 0-.81-.2-1.47-.6-1.99-.4-.51-.9-.77-1.5-.77-.61 0-1.13.22-1.57.67-.45.45-.67 1.19-.67 2.23zm10.41 3.31c-.27.18-.58.27-.94.27-1.34 0-2.02-.69-2.02-2.07v-4.37h-1.16v-.73h1.16v-1.78h.87v1.78h2.03v.73h-2.03V56c0 .81.38 1.22 1.13 1.22.37 0 .69-.11.95-.32v.86zm10.21.2h-.85v-1.27c-.37.92-1.12 1.37-2.25 1.37a2.2 2.2 0 0 1-1.64-.62 2.23 2.23 0 0 1-.61-1.64v-4.93h.85v4.69c0 .54.14.96.43 1.25s.66.43 1.13.43a1.9 1.9 0 0 0 1.52-.67c.39-.45.58-1.03.58-1.75v-3.95h.85v7.09zm7.49 0h-.85v-4.69c0-.55-.14-.97-.42-1.26a1.47 1.47 0 0 0-1.11-.43c-.58 0-1.08.22-1.5.67s-.63 1.04-.63 1.8v3.92h-.85v-7.1h.85v1.22c.44-.89 1.19-1.33 2.25-1.33.68 0 1.23.21 1.64.63s.62.96.62 1.62v4.95zm7.74 0h-.85v-1.04a2.44 2.44 0 0 1-2.2 1.15c-.95 0-1.69-.35-2.23-1.04-.53-.7-.8-1.54-.8-2.54 0-1.1.28-2 .85-2.7a2.7 2.7 0 0 1 2.2-1.04c.92 0 1.65.39 2.17 1.18v-3.86h.85v9.89zm-5.18-3.46c0 .81.2 1.47.6 1.99.4.51.9.77 1.5.77s1.13-.22 1.57-.67c.44-.44.66-1.18.66-2.22 0-.52-.07-.98-.22-1.37a2.06 2.06 0 0 0-1.25-1.31 1.93 1.93 0 0 0-2.25.63c-.4.51-.61 1.24-.61 2.18zm16.1 1.02c0 .82-.28 1.45-.83 1.88-.55.43-1.26.65-2.12.65-.97 0-1.8-.21-2.48-.62v-.97a4.43 4.43 0 0 0 2.43.74c.66 0 1.18-.14 1.55-.43.37-.29.55-.71.55-1.25 0-.41-.14-.74-.42-1s-.69-.5-1.22-.74l-.49-.22-.53-.23-.48-.24a3.1 3.1 0 0 1-.47-.29l-.37-.34a1.3 1.3 0 0 1-.32-.42 2.63 2.63 0 0 1-.26-1.11c0-.79.29-1.41.85-1.86a3.3 3.3 0 0 1 2.09-.66c.78 0 1.44.14 1.96.42v.97a3.99 3.99 0 0 0-1.94-.53c-.63 0-1.13.15-1.5.44-.37.29-.56.68-.56 1.17 0 .25.05.48.15.67.1.2.26.38.5.54a6.17 6.17 0 0 0 1.4.74l.74.33c.17.08.38.2.64.37s.46.33.6.5a2.44 2.44 0 0 1 .53 1.49zm4.87 2.26a4.27 4.27 0 0 1-1.26 1.99 2.7 2.7 0 0 1-1.65.55c-.19 0-.36-.02-.53-.07v-.85c.17.05.33.07.48.07 1 0 1.69-.57 2.09-1.71l-2.9-6.9h.98l.96 2.38 1.37 3.42c.06-.21.47-1.35 1.22-3.42l.87-2.38h.95l-2.58 6.92zm13.19.18h-.85v-4.69c0-1.13-.49-1.69-1.48-1.69-.48 0-.92.22-1.29.67a2.67 2.67 0 0 0-.57 1.79v3.92h-.85v-4.69c0-1.13-.5-1.69-1.48-1.69-.49 0-.92.22-1.29.67a2.67 2.67 0 0 0-.57 1.79v3.92h-.85v-7.1h.85v1.16a2.04 2.04 0 0 1 1.99-1.27c1.14 0 1.84.47 2.1 1.4.44-.93 1.14-1.4 2.1-1.4.75 0 1.3.21 1.67.62.36.42.54.96.54 1.63v4.96zm3.03 0h-.85v-9.9h.85v3.86a2.49 2.49 0 0 1 2.17-1.18c.9 0 1.63.35 2.2 1.04s.85 1.59.85 2.7c0 1-.27 1.85-.8 2.54a2.62 2.62 0 0 1-2.23 1.04c-.97 0-1.7-.38-2.2-1.15v1.05zm0-3.58c0 1.04.22 1.78.66 2.22s.96.67 1.57.67 1.11-.26 1.5-.77c.4-.51.59-1.18.59-1.99a3.4 3.4 0 0 0-.62-2.18 1.92 1.92 0 0 0-2.25-.63 2.12 2.12 0 0 0-1.25 1.31c-.13.39-.2.84-.2 1.37zm13.11.07c0 1.05-.3 1.92-.89 2.61a3.05 3.05 0 0 1-2.44 1.03c-1 0-1.79-.34-2.38-1.04a3.86 3.86 0 0 1-.88-2.6c0-1.04.3-1.91.91-2.62a2.95 2.95 0 0 1 2.35-1.06c1.05 0 1.87.35 2.46 1.04.58.69.87 1.57.87 2.64zm-5.7 0c0 .77.22 1.44.65 2 .43.55 1.01.83 1.71.83.78 0 1.38-.27 1.8-.82.43-.55.64-1.22.64-2.01 0-.82-.2-1.5-.6-2.05-.4-.55-1.01-.82-1.83-.82-.74 0-1.32.28-1.74.84a3.27 3.27 0 0 0-.63 2.03zm8.32 3.51h-.85v-9.9h.85v9.9zM58.95 32.91h5.01v.46h-5.01v-.46zm0 1.79h5.01v.47h-5.01v-.47zm-41.7-17.08h7.18v.66h-7.18v-.66zm0 2.55h7.18v.68h-7.18v-.68zm30.35-4.54h.67v3.27h3.25v.66h-3.25v3.25h-.67v-3.25h-3.26v-.66h3.26v-3.27zm38.22 0h.67v3.27h3.25v.66h-3.25v3.25h-.67v-3.25h-3.26v-.66h3.26v-3.27zm26.53.59 2.54 2.53 2.54-2.53.47.46-2.54 2.55 2.54 2.53-.47.48-2.54-2.54-2.54 2.54-.48-.48 2.54-2.54-2.54-2.53.48-.47zm13.58.32v6.07c.35-.07.63-.2.85-.38s.4-.5.56-.95.29-1.25.39-2.41c.09-.96.24-1.62.45-1.98.21-.36.57-.54 1.08-.54.17 0 .43.04.77.12v.23c-.2 0-.34.03-.44.1-.13.1-.24.27-.32.52s-.16.7-.23 1.36a8.6 8.6 0 0 1-.45 2.32 3.6 3.6 0 0 1-1.58 1.7c-.32.16-.68.26-1.08.3v2.83h-.75V23a3.31 3.31 0 0 1-2.67-1.99c-.17-.41-.32-1.19-.45-2.34-.08-.69-.15-1.16-.23-1.39s-.18-.4-.31-.49c-.08-.06-.23-.09-.44-.09v-.23c.38-.08.64-.12.79-.12a1.31 1.31 0 0 1 1.26.92c.11.31.2.84.27 1.6.09 1.13.21 1.92.37 2.37.16.46.34.78.56.97.21.19.5.32.86.4v-6.07h.74zm11.6 2.33h7.18v.68h-7.18v-.68zm-69.05 9.25H55.02v-.37l6.86-8.52-6.86-8.38v-.38h13.1l.28 3.46h-.41c-.11-.94-.37-1.62-.79-2.02a2.46 2.46 0 0 0-1.76-.61h-7.59l5.76 7.04-6.45 7.97h8.39c.48 0 1-.09 1.57-.28.39-.13.71-.36.97-.69.26-.33.47-.85.64-1.55l.41.07-.66 4.26z\"/>\n</svg>\n\n\n\nDrawback: you can't select any text, since every text was converted to <path> elements.\n" ]
[ 0 ]
[]
[]
[ "css", "fonts", "svg" ]
stackoverflow_0074639728_css_fonts_svg.txt
Q: CS50 Week 2 Substitution: Converting a string to uppercase I'm trying to convert a string to all uppercase using below: string key = argv[1]; for (int i = 0; i < len; i++) { if islower(key[i]) { toupper(key[i]); } } I'm receiving: substitution.c:59:13: error: ignoring return value of function declared with pure attribute [-Werror,-Wunused-value] toupper(key[i]); Could anyone help me understand what this means? The other part of the code is listed below if that's relevant. int main(int argc, string argv[]) { // strlen = 26 int len = strlen(argv[1]); if (len != 26) { printf("Usage: ./substitution key\n"); return 1; } // input must be single string if (argc != 2) { printf("Usage: ./substitution key\n"); return 1; } // check each char as letter for (int i = 0; i < len; i++) { if (!isalpha(argv[1][i])) { printf("Usage: ./substitution key\n"); return 1; } } // check for duplicates for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { if (toupper((argv[1][i])) == toupper((argv[1][j]))) { printf("Usage: ./substitution key\n"); return 1; } } } Thanks! Trying to convert a string to all uppercase but ran into an error that I can't understand. Thanks! A: From the man page: DESCRIPTION: These functions convert lowercase letters to uppercase, and vice versa. If c is a lowercase letter, toupper() returns its uppercase equivalent, if an uppercase representation exists in the current locale. Otherwise, it returns c. The toupper_l() function performs the same task, but uses the locale referred to by the locale handle locale. If c is an uppercase letter, tolower() returns its lowercase equivalent, if a lowercase representation exists in the current locale. Otherwise, it returns c. The tolower_l() function performs the same task, but uses the locale referred to by the locale handle locale. OP's Problem: toupper(key[i]) does not change the supplied argument. It returns the uppercase equivalent of the character, if available. You need to make use of it. Change this: toupper(key[i); to: key[i] = toupper(key[i]); You're also missing a pair of parentheses around the if statement.
CS50 Week 2 Substitution: Converting a string to uppercase
I'm trying to convert a string to all uppercase using below: string key = argv[1]; for (int i = 0; i < len; i++) { if islower(key[i]) { toupper(key[i]); } } I'm receiving: substitution.c:59:13: error: ignoring return value of function declared with pure attribute [-Werror,-Wunused-value] toupper(key[i]); Could anyone help me understand what this means? The other part of the code is listed below if that's relevant. int main(int argc, string argv[]) { // strlen = 26 int len = strlen(argv[1]); if (len != 26) { printf("Usage: ./substitution key\n"); return 1; } // input must be single string if (argc != 2) { printf("Usage: ./substitution key\n"); return 1; } // check each char as letter for (int i = 0; i < len; i++) { if (!isalpha(argv[1][i])) { printf("Usage: ./substitution key\n"); return 1; } } // check for duplicates for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { if (toupper((argv[1][i])) == toupper((argv[1][j]))) { printf("Usage: ./substitution key\n"); return 1; } } } Thanks! Trying to convert a string to all uppercase but ran into an error that I can't understand. Thanks!
[ "From the man page:\nDESCRIPTION:\n\nThese functions convert lowercase letters to uppercase, and vice versa.\n\n\nIf c is a lowercase letter, toupper() returns its uppercase equivalent, if an uppercase representation exists in the current locale. Otherwise, it returns c. The toupper_l() function\nperforms the same task, but uses the locale referred to by the locale handle locale.\n\n\nIf c is an uppercase letter, tolower() returns its lowercase equivalent, if a lowercase representation exists in the current locale. Otherwise, it returns c. The tolower_l() function performs the same task, but uses the locale referred to by the locale handle locale.\n\nOP's Problem:\ntoupper(key[i])\n\ndoes not change the supplied argument. It returns the uppercase equivalent of the character, if available. You need to make use of it.\nChange this:\ntoupper(key[i);\n\nto:\nkey[i] = toupper(key[i]);\n\nYou're also missing a pair of parentheses around the if statement.\n" ]
[ 1 ]
[]
[]
[ "c", "cs50" ]
stackoverflow_0074659258_c_cs50.txt
Q: Puppeteer Memory Increase Problems I'm running Puppeteer script both on my Amazon Linux EC2 Instance and my Macbook Air (OSX). The script has to stay in tact at one page and repeatedly perform form-filling tasks over and over again. I'm encountering issues where i'm running it as a pm2 daemon process, I can see that the memory consumption of that process is increasing every minute or two until it's clogging the server's memory. In order to overcome it, I used --max-memory-restart flag of pm2 and it prevents the server from crashing, but the node process restarts every 30 minutes in average. Here is the example that represents the code i'm running: // Require the puppeteer library const puppeteer = require('puppeteer'); async function scrape() { // Create the browser const browser = await puppeteer.launch({ headless: true, ignoreHTTPSErrors: true, args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-accelerated-2d-canvas', '--no-first-run', '--no-zygote', '--single-process', '--disable-gpu', '--ignore-certificate-errors' ] }); // Wrap scraping/testing code in try try { await initialFlow(browser, null); // Page instance is null for the first time // Catch and log errors } catch (error) { // Your chance to handle errors console.error(error); } finally { // Always close the browser await browser.close(); } } const initialFlow = async (browser, page) => { // Save resources by reusing the browser and page instances try { if (!page) { const pages = await browser.pages(); page = pages[0]; } await page.setRequestInterception(true); page.on('request', (req) => { if (req.resourceType() == 'font' || req.resourceType() == 'image') { // Save resources by denying images and fonts from being rendered req.abort(); } else { req.continue(); } }); await page.goto('about:blank'); // Go to blank page await page.goto('https://www.google.com'); // For the example await page.waitForSelector('#Form', { visible: true }); return await initialFlow(browser, page); // Perform the actions again on the same browser and page instances } catch (err) { return await initialFlow(browser, page); }; } // Run our function scrape().catch(console.error); When running this example, the memory displayed in the pm2 ls command start from around 30mb and continuously increases as the time goes by. Any suggestions to prevent this memory leak? A: Kudos on putting browser.close() in a finally block even though you're entering an infinite loop. For many other visitors to the thread, a typical memory leak problem is failure to close browsers on all paths through the code. However, it's rather bizarre to use recursion instead of a loop. Luckily, since it's async, the stack won't blow, but the code is hard to understand since some conditional initialization occurs in the function. Misunderstanding the control flow is probably leading to your leak. One problem is that you keep adding your request handler to the page over and over on every initialFlow call: page.on('request', (req) => {}); These handlers stack on top of each other, chewing up memory. Here's a minimal example you can run to observe the problem using a memory profiler: const puppeteer = require("puppeteer"); // ^19.1.0 const {setTimeout} = require("timers/promises"); let browser; (async () => { browser = await puppeteer.launch(); const [page] = await browser.pages(); for (;;) { page.on("request", () => {}); await setTimeout(10); } })() .catch(err => console.error(err)) .finally(() => browser?.close()); Just add this handler one time up front and you should be OK, assuming there's nothing else in the code that was lost in translation to the snippet you shared here. Quick rewrite, untested: const puppeteer = require("puppeteer"); async function scrape() { const browser = await puppeteer.launch({ headless: true, ignoreHTTPSErrors: true, args: [ "--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage", "--disable-accelerated-2d-canvas", "--no-first-run", "--no-zygote", "--single-process", "--disable-gpu", "--ignore-certificate-errors", ], }); try { const [page] = await browser.pages(); await page.setRequestInterception(true); page.on("request", (req) => { if ( req.resourceType() == "font" || req.resourceType() == "image" ) { return req.abort(); } req.continue(); }); for (;;) { try { await page.goto("about:blank"); // Go to blank page await page.goto("https://www.google.com"); // For the example await page.waitForSelector("#Form", {visible: true}); } catch (err) {} // FIXME risky -- consider detecting if we hit // this branch repeatedly so we can log it } } catch (error) { console.error(error); } finally { await browser.close(); } } scrape().catch(console.error);
Puppeteer Memory Increase Problems
I'm running Puppeteer script both on my Amazon Linux EC2 Instance and my Macbook Air (OSX). The script has to stay in tact at one page and repeatedly perform form-filling tasks over and over again. I'm encountering issues where i'm running it as a pm2 daemon process, I can see that the memory consumption of that process is increasing every minute or two until it's clogging the server's memory. In order to overcome it, I used --max-memory-restart flag of pm2 and it prevents the server from crashing, but the node process restarts every 30 minutes in average. Here is the example that represents the code i'm running: // Require the puppeteer library const puppeteer = require('puppeteer'); async function scrape() { // Create the browser const browser = await puppeteer.launch({ headless: true, ignoreHTTPSErrors: true, args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-accelerated-2d-canvas', '--no-first-run', '--no-zygote', '--single-process', '--disable-gpu', '--ignore-certificate-errors' ] }); // Wrap scraping/testing code in try try { await initialFlow(browser, null); // Page instance is null for the first time // Catch and log errors } catch (error) { // Your chance to handle errors console.error(error); } finally { // Always close the browser await browser.close(); } } const initialFlow = async (browser, page) => { // Save resources by reusing the browser and page instances try { if (!page) { const pages = await browser.pages(); page = pages[0]; } await page.setRequestInterception(true); page.on('request', (req) => { if (req.resourceType() == 'font' || req.resourceType() == 'image') { // Save resources by denying images and fonts from being rendered req.abort(); } else { req.continue(); } }); await page.goto('about:blank'); // Go to blank page await page.goto('https://www.google.com'); // For the example await page.waitForSelector('#Form', { visible: true }); return await initialFlow(browser, page); // Perform the actions again on the same browser and page instances } catch (err) { return await initialFlow(browser, page); }; } // Run our function scrape().catch(console.error); When running this example, the memory displayed in the pm2 ls command start from around 30mb and continuously increases as the time goes by. Any suggestions to prevent this memory leak?
[ "Kudos on putting browser.close() in a finally block even though you're entering an infinite loop. For many other visitors to the thread, a typical memory leak problem is failure to close browsers on all paths through the code.\nHowever, it's rather bizarre to use recursion instead of a loop. Luckily, since it's async, the stack won't blow, but the code is hard to understand since some conditional initialization occurs in the function. Misunderstanding the control flow is probably leading to your leak.\nOne problem is that you keep adding your request handler to the page over and over on every initialFlow call:\npage.on('request', (req) => {});\n\nThese handlers stack on top of each other, chewing up memory. Here's a minimal example you can run to observe the problem using a memory profiler:\nconst puppeteer = require(\"puppeteer\"); // ^19.1.0\nconst {setTimeout} = require(\"timers/promises\");\n\nlet browser;\n(async () => {\n browser = await puppeteer.launch();\n const [page] = await browser.pages();\n\n for (;;) {\n page.on(\"request\", () => {});\n await setTimeout(10);\n }\n})()\n .catch(err => console.error(err))\n .finally(() => browser?.close());\n\nJust add this handler one time up front and you should be OK, assuming there's nothing else in the code that was lost in translation to the snippet you shared here.\nQuick rewrite, untested:\nconst puppeteer = require(\"puppeteer\");\n\nasync function scrape() {\n const browser = await puppeteer.launch({\n headless: true,\n ignoreHTTPSErrors: true,\n args: [\n \"--no-sandbox\",\n \"--disable-setuid-sandbox\",\n \"--disable-dev-shm-usage\",\n \"--disable-accelerated-2d-canvas\",\n \"--no-first-run\",\n \"--no-zygote\",\n \"--single-process\",\n \"--disable-gpu\",\n \"--ignore-certificate-errors\",\n ],\n });\n\n try {\n const [page] = await browser.pages();\n await page.setRequestInterception(true);\n page.on(\"request\", (req) => {\n if (\n req.resourceType() == \"font\" ||\n req.resourceType() == \"image\"\n ) {\n return req.abort();\n }\n\n req.continue();\n });\n\n for (;;) {\n try {\n await page.goto(\"about:blank\"); // Go to blank page\n await page.goto(\"https://www.google.com\"); // For the example\n await page.waitForSelector(\"#Form\", {visible: true});\n }\n catch (err) {} // FIXME risky -- consider detecting if we hit\n // this branch repeatedly so we can log it\n }\n }\n catch (error) {\n console.error(error);\n }\n finally {\n await browser.close();\n }\n}\n\nscrape().catch(console.error);\n\n" ]
[ 0 ]
[]
[]
[ "memory_leaks", "node.js", "puppeteer" ]
stackoverflow_0067056583_memory_leaks_node.js_puppeteer.txt
Q: Why UNION SELECT gives you the number of columns in SQLI I am trying to figure out why one can figure out the number of columns from using 'union SELECT' For example, if you have a webpage http://www.vulnerable-site.com/index.php?firstArg=1 I learned that you can put http://www.vulnerable-site.com/index.php?firstArg=1 union SELECT 1,2,3,4 -- to find out the number of columns in the table. Basically, you keep adding numbers to till you stop getting errors. Why is that? Can anyone please help me with this basic question. Thanks A: I came to know that the number of columns on both sides of the UNION statement must match. So, this command can be used to find out the number of columns in a table. A: UNION keyword can be used to retrieve data from other tables within the database. This results in an SQL injection UNION attack. so Determining the number of columns required in an SQL injection UNION attack. there are two effective methods to determine how many columns are being returned from the original query. "ORDER BY" and "UNION SELECT"
Why UNION SELECT gives you the number of columns in SQLI
I am trying to figure out why one can figure out the number of columns from using 'union SELECT' For example, if you have a webpage http://www.vulnerable-site.com/index.php?firstArg=1 I learned that you can put http://www.vulnerable-site.com/index.php?firstArg=1 union SELECT 1,2,3,4 -- to find out the number of columns in the table. Basically, you keep adding numbers to till you stop getting errors. Why is that? Can anyone please help me with this basic question. Thanks
[ "I came to know that the number of columns on both sides of the UNION statement must match. So, this command can be used to find out the number of columns in a table.\n", "UNION keyword can be used to retrieve data from other tables within the database. This results in an SQL injection UNION attack. so Determining the number of columns required in an SQL injection UNION attack. there are two effective methods to determine how many columns are being returned from the original query. \"ORDER BY\" and \"UNION SELECT\"\n" ]
[ 0, 0 ]
[]
[]
[ "select", "sql_injection", "union", "web_applications" ]
stackoverflow_0043483164_select_sql_injection_union_web_applications.txt
Q: How to convert JSON array to OBJECT array javascript? Kinda stuck here. I am fetching data from database with php into this variable in javascript. <?php //connection to database include("con.php"); //query $query = "SELECT * FROM magacin_artikli"; $r = mysqli_query($conn, $query); $dataGrafDodArt = array(); while($row = mysqli_fetch_array($r)){ $dataGrafDodArt[] = $row["art_naz"]. ":". $row["art_nabcena"]; } //closing conn $conn->close(); ?> var oData = <?php echo json_encode($dataGrafDodArt);?>; Output is: var oData = ["asd:2","asd:3","asd:2","ddd:3"]; And I need this to be formated like object array like this("asd":2), something like this inside variable: Example output: var oData = { "2008": 10, "2009": 39.9, "2010": 17, "2011": 30.0, "2012": 5.3, "2013": 38.4, "2014": 15.7, "2015": 9.0 }; This is for animated graph which is taking parameters from Example output. Any help would be good. Tried a lot of things from array map to trimming the array and other stuff but none worked. A: You should make the change at the PHP side. Instead of building an indexed array, create an associative array, and it will look in JavaScript just as you wanted it. Change this: $dataGrafDodArt[] = $row["art_naz"]. ":". $row["art_nabcena"]; To: $dataGrafDodArt[$row["art_naz"]] = $row["art_nabcena"];
How to convert JSON array to OBJECT array javascript?
Kinda stuck here. I am fetching data from database with php into this variable in javascript. <?php //connection to database include("con.php"); //query $query = "SELECT * FROM magacin_artikli"; $r = mysqli_query($conn, $query); $dataGrafDodArt = array(); while($row = mysqli_fetch_array($r)){ $dataGrafDodArt[] = $row["art_naz"]. ":". $row["art_nabcena"]; } //closing conn $conn->close(); ?> var oData = <?php echo json_encode($dataGrafDodArt);?>; Output is: var oData = ["asd:2","asd:3","asd:2","ddd:3"]; And I need this to be formated like object array like this("asd":2), something like this inside variable: Example output: var oData = { "2008": 10, "2009": 39.9, "2010": 17, "2011": 30.0, "2012": 5.3, "2013": 38.4, "2014": 15.7, "2015": 9.0 }; This is for animated graph which is taking parameters from Example output. Any help would be good. Tried a lot of things from array map to trimming the array and other stuff but none worked.
[ "You should make the change at the PHP side. Instead of building an indexed array, create an associative array, and it will look in JavaScript just as you wanted it.\nChange this:\n$dataGrafDodArt[] = $row[\"art_naz\"]. \":\". $row[\"art_nabcena\"];\n\nTo:\n$dataGrafDodArt[$row[\"art_naz\"]] = $row[\"art_nabcena\"];\n\n" ]
[ 1 ]
[ "To convert a JSON array to an object array in JavaScript, you can use the map() method of the Array object to convert each element of the JSON array to an object. The map() method allows you to apply a function to each element of an array, and to return a new array containing the transformed elements.\nFor example, given the following JSON array:\n[\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n]\n\nYou can use the map() method to convert the array to an object array, as follows:\nconst jsonArray = [\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n];\n\nconst objectArray = jsonArray.map(jsonObject => {\n return {\n name: jsonObject.name,\n age: jsonObject.age\n };\n});\n\nThis code will convert each element of the JSON array to an object with the same name and age properties, and will return a new array containing these objects. The objectArray variable will then contain the following array:\n[\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n]\n\nOverall, to convert a JSON array to an object array in JavaScript, you can use the map() method of the Array object to transform each element of the JSON array into an object. This allows you to convert the JSON array into an array of objects with the desired properties and values.\n" ]
[ -1 ]
[ "arrayobject", "arrays", "javascript", "json", "php" ]
stackoverflow_0074660274_arrayobject_arrays_javascript_json_php.txt
Q: Why 3rd party REST API's gets null values for request fields when removing @Getter Lombok annotation I am calling a third party REST endpoint. The request for the thrid party REST endpoint looks like this. { "body": { "accountNumber": "12345" }, "header": { "username": "someusername", "password": "somepassword" } } I have created 3 bean classes MyRequest.java @Builder @JsonDeserialize(builder = MyRequest.MyRequestBuilder.class) public class MyRequest { @JsonProperty("header") private MyHeader header; @JsonProperty("body") private MyBody body; } MyBody.java @Getter @Builder public class MyBody { private String accountNumber; } MyHeader.java @Getter @Builder public class MyHeader { private String username; private String password; } I'm creating request object using MyBody body = MyBody.builder().accountNumber("12345").build(); MyHeader header = MyHeader.builder().username("someusername").password("somepassword").build(); MyRequest request = MyRequest.builder().body(body).header(header).build(); I'm calling the 3rd part REST endpoint using the below code HttpEntity<MyRequest> httpEntity = new HttpEntity<>(myRequest, httpHeaders); String url = "someurl"; someResponse = this.restTemplate.postForObject(url, httpEntity, SomeResponse.class); I'm getting proper response. But if I remove @Getter annotation from MyHeader and MyBody, 3rd party REST endpoint is getting null values in request. Why @Getter is necessary here. How to make this work without @Getter. A: if I remove @Getter annotation from MyHeader and MyBody, 3rd party REST endpoint is getting null values in request. Why @Getter is necessary here. How to make this work without @Getter. You need to instruct Jackson somehow which data should be included during serialization. The default mechanism is to use getters for that purpose. That's not the only way. Alternatively, you can annotate certain fields with @JsonProperty, or change the default visibility of the fields either globally or for a particular type using annotation @JsonAutoDetect and set its property fieldVisibility to ANY (that would make the fields discoverable even in the absence of getters) The key point is that the information on which data needs to be present in the serialized JSON should be provided somehow, and it doesn't matter how exactly. Consider a dummy POJO with no getters: @AllArgsConstructor public class Foo { @JsonProperty private String bar; } Property bar would be reflected in the resulting JSON. ObjectMapper mapper = new ObjectMapper(); Foo foo = new Foo("baz"); String jsonFoo = mapper.writeValueAsString(foo); System.out.println(jsonFoo); Output: {"bar":"baz"} Now, if we remove @JsonProperty (no getters as before) that's what would happen. @AllArgsConstructor public class Foo { private String bar; } ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); Foo foo = new Foo("baz"); String jsonFoo = mapper.writeValueAsString(foo); System.out.println(jsonFoo); Output: {} An empty Bean produces an empty JSON (or raises an exception, depending on configuration). And vise versa, Deserialization of an empty JSON gives an empty Bean.
Why 3rd party REST API's gets null values for request fields when removing @Getter Lombok annotation
I am calling a third party REST endpoint. The request for the thrid party REST endpoint looks like this. { "body": { "accountNumber": "12345" }, "header": { "username": "someusername", "password": "somepassword" } } I have created 3 bean classes MyRequest.java @Builder @JsonDeserialize(builder = MyRequest.MyRequestBuilder.class) public class MyRequest { @JsonProperty("header") private MyHeader header; @JsonProperty("body") private MyBody body; } MyBody.java @Getter @Builder public class MyBody { private String accountNumber; } MyHeader.java @Getter @Builder public class MyHeader { private String username; private String password; } I'm creating request object using MyBody body = MyBody.builder().accountNumber("12345").build(); MyHeader header = MyHeader.builder().username("someusername").password("somepassword").build(); MyRequest request = MyRequest.builder().body(body).header(header).build(); I'm calling the 3rd part REST endpoint using the below code HttpEntity<MyRequest> httpEntity = new HttpEntity<>(myRequest, httpHeaders); String url = "someurl"; someResponse = this.restTemplate.postForObject(url, httpEntity, SomeResponse.class); I'm getting proper response. But if I remove @Getter annotation from MyHeader and MyBody, 3rd party REST endpoint is getting null values in request. Why @Getter is necessary here. How to make this work without @Getter.
[ "\nif I remove @Getter annotation from MyHeader and MyBody, 3rd party REST endpoint is getting null values in request. Why @Getter is necessary here. How to make this work without @Getter.\n\nYou need to instruct Jackson somehow which data should be included during serialization. The default mechanism is to use getters for that purpose.\nThat's not the only way.\nAlternatively, you can annotate certain fields with @JsonProperty, or change the default visibility of the fields either globally or for a particular type using annotation @JsonAutoDetect and set its property fieldVisibility to ANY (that would make the fields discoverable even in the absence of getters)\nThe key point is that the information on which data needs to be present in the serialized JSON should be provided somehow, and it doesn't matter how exactly.\nConsider a dummy POJO with no getters:\n@AllArgsConstructor\npublic class Foo {\n @JsonProperty\n private String bar;\n}\n\nProperty bar would be reflected in the resulting JSON.\nObjectMapper mapper = new ObjectMapper();\nFoo foo = new Foo(\"baz\");\nString jsonFoo = mapper.writeValueAsString(foo);\nSystem.out.println(jsonFoo);\n\nOutput:\n{\"bar\":\"baz\"}\n\nNow, if we remove @JsonProperty (no getters as before) that's what would happen.\n@AllArgsConstructor\npublic class Foo {\n private String bar;\n}\n\nObjectMapper mapper = new ObjectMapper();\nmapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);\n\nFoo foo = new Foo(\"baz\");\nString jsonFoo = mapper.writeValueAsString(foo);\nSystem.out.println(jsonFoo);\n\nOutput:\n{}\n\nAn empty Bean produces an empty JSON (or raises an exception, depending on configuration). And vise versa, Deserialization of an empty JSON gives an empty Bean.\n" ]
[ 2 ]
[]
[]
[ "jackson", "java", "lombok", "spring", "spring_boot" ]
stackoverflow_0074660036_jackson_java_lombok_spring_spring_boot.txt
Q: Rounded corners in svg I am trying to create a triangle (polygon element) using svg. Is it possible to give it a rounded corners? I am thinking about using the same option as in this case (https://www.w3schools.com/graphics/svg_rect.asp) in example 4, but I am not sure how to do it. A: Its solution is shown here. stackoverflow.com/questions/10177985/svg-rounded-corner First of all, you should do your research. But the solution is as follows. <svg width="440" height="440"> <path d="M100,100 h200 a20,20 0 0 1 20,20 v200 a20,20 0 0 1 -20,20 h-200 a20,20 0 0 1 -20,-20 v-200 a20,20 0 0 1 20,-20 z" fill="none" stroke="black" stroke-width="3" /> </svg> Also, if you want to practice live, visit this page. plnkr.co/edit/kGnGGyoOCKil02k04snu?preview
Rounded corners in svg
I am trying to create a triangle (polygon element) using svg. Is it possible to give it a rounded corners? I am thinking about using the same option as in this case (https://www.w3schools.com/graphics/svg_rect.asp) in example 4, but I am not sure how to do it.
[ "Its solution is shown here. stackoverflow.com/questions/10177985/svg-rounded-corner\nFirst of all, you should do your research. But the solution is as follows.\n<svg width=\"440\" height=\"440\">\n <path d=\"M100,100 h200 a20,20 0 0 1 20,20 v200 a20,20 0 0 1 -20,20 h-200 a20,20 0 0 1 -20,-20 v-200 a20,20 0 0 1 20,-20 z\" fill=\"none\" stroke=\"black\" stroke-width=\"3\" />\n</svg>\n\nAlso, if you want to practice live, visit this page. plnkr.co/edit/kGnGGyoOCKil02k04snu?preview\n" ]
[ 0 ]
[]
[]
[ "rounded_corners", "svg", "triangle" ]
stackoverflow_0074660334_rounded_corners_svg_triangle.txt
Q: Imploding an associative array in PHP Say I have an array: $array = Array( 'foo' => 5, 'bar' => 12, 'baz' => 8 ); And I'd like to print a line of text in my view like this: "The values are: foo (5), bar (12), baz (8)" What I could do is this: $list = Array(); foreach ($array as $key => $value) { $list[] = "$key ($value)"; } echo 'The values are: '.implode(', ',$list); But I feel like there should be an easier way, without having to create the $list array as an extra step. I've been trying array_map and array_walk, but no success. So my question is: what's the best and shortest way of doing this? A: For me the best and simplest solution is this: $string = http_build_query($array, '', ','); http_build_query (php.net) A: The problem with array_map is that the callback function does not accept the key as an argument. You could write your own function to fill the gap here: function array_map_assoc( $callback , $array ){ $r = array(); foreach ($array as $key=>$value) $r[$key] = $callback($key,$value); return $r; } Now you can do that: echo implode(',',array_map_assoc(function($k,$v){return "$k ($v)";},$array)); A: There is a way, but it's pretty verbose (and possibly less efficient): <?php $array = Array( 'foo' => 5, 'bar' => 12, 'baz' => 8 ); // pre-5.3: echo 'The values are: '. implode(', ', array_map( create_function('$k,$v', 'return "$k ($v)";'), array_keys($array), array_values($array) )); echo "\n"; // 5.3: echo 'The values are: '. implode(', ', array_map( function ($k, $v) { return "$k ($v)"; }, array_keys($array), array_values($array) )); ?> Your original code looks fine to me. A: You could print out the values as you iterate: echo 'The values are: '; foreach ($array as $key => $value) { $result .= "$key ($value),"; } echo rtrim($result,','); A: Taking help from the answer of @linepogl, I edited the code to make it more simple, and it works fine. function array_map_assoc($array){ $r = array(); foreach ($array as $key=>$value) $r[$key] = "$key ($value)"; return $r; } And then, just call the function using echo implode(' , ', array_map_assoc($array)); A: Clearly, the solution proposed by Roberto Santana its the most usefull. Only one appointmen, if you want to use it for parse html attributes (for example data), you need double quotation. This is an approach: Example: var_dump( '<td data-'.urldecode( http_build_query( ['value1'=>'"1"','value2'=>'2' ], '', ' data-' ) ).'></td>'); Output: string '<td data-value1="1" data-value2=2></td>' (length=39) A: I came up with foreach ($array as &$item) { $item = reset($item); } $array = implode(', ', $array); var_dump($array); A: I do it this way : I firstly define a new array to fill with the values of my existing array I check if my associative array is set and is not empty Then loop on my array and fill the new one with the values After the loop has terminated, i implode the new array as you can see : $new_array = []; if (isset($array) && $array != null) { foreach ($array as $el) {$new_array[] = $el->value;} $new_array = implode(',', $new_array); } echo $new_array; A: echo json_encode($array); if it isn't a valid array it will return null. A: Loop throw the array and put , expect the end of loop. $index = 0; // index $len = count($array); // Length of the array // Loop throw the array foreach($array as $key => $a) { echo "$key ($a)" . ($index != $len - 1 ? ',' : ''); $index++; }
Imploding an associative array in PHP
Say I have an array: $array = Array( 'foo' => 5, 'bar' => 12, 'baz' => 8 ); And I'd like to print a line of text in my view like this: "The values are: foo (5), bar (12), baz (8)" What I could do is this: $list = Array(); foreach ($array as $key => $value) { $list[] = "$key ($value)"; } echo 'The values are: '.implode(', ',$list); But I feel like there should be an easier way, without having to create the $list array as an extra step. I've been trying array_map and array_walk, but no success. So my question is: what's the best and shortest way of doing this?
[ "For me the best and simplest solution is this:\n$string = http_build_query($array, '', ',');\n\nhttp_build_query (php.net)\n", "The problem with array_map is that the callback function does not accept the key as an argument. You could write your own function to fill the gap here:\nfunction array_map_assoc( $callback , $array ){\n $r = array();\n foreach ($array as $key=>$value)\n $r[$key] = $callback($key,$value);\n return $r;\n}\n\nNow you can do that:\necho implode(',',array_map_assoc(function($k,$v){return \"$k ($v)\";},$array));\n\n", "There is a way, but it's pretty verbose (and possibly less efficient):\n<?php\n$array = Array(\n 'foo' => 5,\n 'bar' => 12,\n 'baz' => 8\n);\n\n// pre-5.3:\necho 'The values are: '. implode(', ', array_map(\n create_function('$k,$v', 'return \"$k ($v)\";'),\n array_keys($array),\n array_values($array)\n));\n\necho \"\\n\";\n\n// 5.3:\necho 'The values are: '. implode(', ', array_map(\n function ($k, $v) { return \"$k ($v)\"; },\n array_keys($array),\n array_values($array)\n));\n?>\n\nYour original code looks fine to me.\n", "You could print out the values as you iterate:\necho 'The values are: ';\nforeach ($array as $key => $value) {\n $result .= \"$key ($value),\";\n}\necho rtrim($result,',');\n\n", "Taking help from the answer of @linepogl, I edited the code to make it more simple, and it works fine.\nfunction array_map_assoc($array){\n $r = array();\n foreach ($array as $key=>$value)\n $r[$key] = \"$key ($value)\";\n return $r;\n}\n\nAnd then, just call the function using\necho implode(' , ', array_map_assoc($array));\n\n", "Clearly, the solution proposed by Roberto Santana its the most usefull. Only one appointmen, if you want to use it for parse html attributes (for example data), you need double quotation. This is an approach:\nExample: var_dump( '<td data-'.urldecode( http_build_query( ['value1'=>'\"1\"','value2'=>'2' ], '', ' data-' ) ).'></td>');\n\nOutput: string '<td data-value1=\"1\" data-value2=2></td>' (length=39)\n\n", "I came up with\n foreach ($array as &$item)\n {\n $item = reset($item);\n }\n $array = implode(', ', $array);\n var_dump($array);\n\n", "I do it this way :\n\nI firstly define a new array to fill with the values of my existing\narray\nI check if my associative array is set and is not empty\nThen loop on my array and fill the new one with the values\nAfter the loop has terminated, i implode the new array\n\nas you can see :\n$new_array = [];\n\nif (isset($array) && $array != null) {\n foreach ($array as $el) {$new_array[] = $el->value;}\n $new_array = implode(',', $new_array);\n}\n\necho $new_array;\n\n", "echo json_encode($array);\nif it isn't a valid array it will return null.\n", "Loop throw the array and put , expect the end of loop.\n$index = 0; // index\n$len = count($array); // Length of the array\n\n// Loop throw the array\nforeach($array as $key => $a) {\n echo \"$key ($a)\" . ($index != $len - 1 ? ',' : '');\n $index++;\n}\n\n" ]
[ 33, 32, 10, 7, 3, 2, 0, 0, 0, 0 ]
[]
[]
[ "php" ]
stackoverflow_0006556985_php.txt
Q: How do I resolve missing plugin error when trying to add to a Firebase data? MissingPluginException (MissingPluginException(No implementation found for method DocumentReference#set on channel plugins.flutter.io/firebase_firestore)) On this line of code: Future addUserDetails(String username) async { await FirebaseFirestore.instance.collection('users').add({ 'username': username, }); } Could anyone help me with this? Thank you. A: i think you should allow write db in rule tab of Firebase
How do I resolve missing plugin error when trying to add to a Firebase data?
MissingPluginException (MissingPluginException(No implementation found for method DocumentReference#set on channel plugins.flutter.io/firebase_firestore)) On this line of code: Future addUserDetails(String username) async { await FirebaseFirestore.instance.collection('users').add({ 'username': username, }); } Could anyone help me with this? Thank you.
[ "i think you should allow write db in rule tab of Firebase\n" ]
[ 0 ]
[]
[]
[ "firebase", "flutter" ]
stackoverflow_0073890268_firebase_flutter.txt
Q: How to create widgets based on lists in kivy? does anyone knwo whether it is possible in kivy to create buttons based on list items. I have a list of category names within a list, the amount of items can change based on the users previous input. So does anyone know whether, and how, it is possible to create buttons dynamically, and maybe also link these buttons to a new page? It should work like this: List: ["Fruits", "Dessert", "Main"] -> Creates buttons Fruits, Dessert and Mains -> each button opens a new page so FruitsButton -> FruitsPage / DessertButton -> DessertPaige, etc. A: that is an very general question. here is an idea to get you started. A widget is needed that can hold the buttons and you also can bind each button in advance to a specific function using partial from functools import partial def switch_page(self, _this_button, course: str = "") -> None: print(f"Set {course} {_this_button.text}") # code for switching page here for _course in ("fruits", "deserts", "main"): _button: Button = Button(text=f"{_course}") # _this_callback = partial(self.switch_page, course=_course) _button.bind(on_press=_this_callback) # this container could be a box layout or grid layout, etc self.your_container_widget.add_widget(_button)
How to create widgets based on lists in kivy?
does anyone knwo whether it is possible in kivy to create buttons based on list items. I have a list of category names within a list, the amount of items can change based on the users previous input. So does anyone know whether, and how, it is possible to create buttons dynamically, and maybe also link these buttons to a new page? It should work like this: List: ["Fruits", "Dessert", "Main"] -> Creates buttons Fruits, Dessert and Mains -> each button opens a new page so FruitsButton -> FruitsPage / DessertButton -> DessertPaige, etc.
[ "that is an very general question. here is an idea to get you started. A widget is needed that can hold the buttons and you also can bind each button in advance to a specific function using partial\nfrom functools import partial\ndef switch_page(self, _this_button, course: str = \"\") -> None:\n print(f\"Set {course} {_this_button.text}\")\n # code for switching page here\n \n \nfor _course in (\"fruits\", \"deserts\", \"main\"):\n _button: Button = Button(text=f\"{_course}\")\n # \n _this_callback = partial(self.switch_page, course=_course)\n _button.bind(on_press=_this_callback)\n # this container could be a box layout or grid layout, etc\n self.your_container_widget.add_widget(_button)\n\n" ]
[ 0 ]
[]
[]
[ "button", "kivy", "list", "python" ]
stackoverflow_0074657481_button_kivy_list_python.txt
Q: Filter data in django admin inline create view this is my first post here and im hoping to find a solution for my situation: The thing is... I got a admin inline who show the relate info of a model. by this, i can see which contract_product belongs to current client. When im creating a new object in the inline, aka click in the following button enter image description here I cant see a list of option as follow: enter image description here The problem is... the client must see only their products, but here i see all products for all type of clients? PS: product and client has a direct relationship. Hope someone can understand my problem and helps me! Theres a kt if thing i've tried far now, but nothing succesful to talk about A: This is the code of the inline: class ClientContractInline(admin.TabularInline): model = PrivateContractProduct.client_contract.through classes = [ "collapse", ] raw_id_fields = ["client", "contract_product"] fields = ["client", "contract_product",'fr_contract_id', 'created', 'expire', 'quantity', 'quota'] readonly_fields = ['fr_contract_id', 'created', 'expire', 'quantity'] extra: int = 0
Filter data in django admin inline create view
this is my first post here and im hoping to find a solution for my situation: The thing is... I got a admin inline who show the relate info of a model. by this, i can see which contract_product belongs to current client. When im creating a new object in the inline, aka click in the following button enter image description here I cant see a list of option as follow: enter image description here The problem is... the client must see only their products, but here i see all products for all type of clients? PS: product and client has a direct relationship. Hope someone can understand my problem and helps me! Theres a kt if thing i've tried far now, but nothing succesful to talk about
[ "This is the code of the inline:\nclass ClientContractInline(admin.TabularInline):\nmodel = PrivateContractProduct.client_contract.through\nclasses = [\n \"collapse\",\n]\nraw_id_fields = [\"client\", \"contract_product\"]\nfields = [\"client\", \"contract_product\",'fr_contract_id', 'created', 'expire', 'quantity', 'quota']\nreadonly_fields = ['fr_contract_id', 'created', 'expire', 'quantity']\nextra: int = 0\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "django_inline_models" ]
stackoverflow_0074650057_django_django_admin_django_inline_models.txt
Q: Python. View the "import" name of a library Some Python libraries are listed under one name in pip, but imported under a different name in the interpreter. pycroptodome is a good example. In pip list, you see "pycryptodome". In a Python program, you have to call "import Crypto". "import pycryptodome" gives an error that the module doesn't exist. Some libraries I've imported are giving me "module not found" errors. I want to see if they're imported under a different name from what appears in pip. Where can I find that data? For reference, "pip show " and "pip inspect " don't seem to have this information. A: Usually in /lib/site-packages in your Python folder. (At least, on Windows.) You can use sys. path to find out what directories are searched for modules. In the standard Python interpreter, you can type " help('modules') ". At the command-line, you can use pydoc modules . In a script, call pkgutil. iter_modules() pydoc modules works A: Here's how you can get the import name: Open the folder that your packages are installed ( Specified in Location in pip show pycryptodome). Then open the package dist-info folder (pycryptodome-3.16.0.dist-info). open top_level.txt. you can see the name you are looking for.
Python. View the "import" name of a library
Some Python libraries are listed under one name in pip, but imported under a different name in the interpreter. pycroptodome is a good example. In pip list, you see "pycryptodome". In a Python program, you have to call "import Crypto". "import pycryptodome" gives an error that the module doesn't exist. Some libraries I've imported are giving me "module not found" errors. I want to see if they're imported under a different name from what appears in pip. Where can I find that data? For reference, "pip show " and "pip inspect " don't seem to have this information.
[ "Usually in /lib/site-packages in your Python folder. (At least, on Windows.) You can use sys. path to find out what directories are searched for modules.\nIn the standard Python interpreter, you can type \" help('modules') \". At the command-line, you can use pydoc modules . In a script, call pkgutil. iter_modules()\npydoc modules \n\nworks\n", "Here's how you can get the import name:\nOpen the folder that your packages are installed ( Specified in Location in pip show pycryptodome). Then open the package dist-info folder (pycryptodome-3.16.0.dist-info). open top_level.txt. you can see the name you are looking for.\n" ]
[ 0, 0 ]
[ "go https://pypi.org/project/pycryptodome\ndownload the tar file version you downloaded using pip and see the top-level view to see import names\n" ]
[ -1 ]
[ "pip", "python" ]
stackoverflow_0074659686_pip_python.txt
Q: I want to filter a dataframe that contains all the days of year 2021 and 2022 such that I only have the data that belongs to 2021? enter image description here I only want to print only the data for 2021 A: can you try this: df['time'] = pd.to_datetime(df['time']) df = df[df['time'].dt.year == 2021]
I want to filter a dataframe that contains all the days of year 2021 and 2022 such that I only have the data that belongs to 2021?
enter image description here I only want to print only the data for 2021
[ "can you try this:\ndf['time'] = pd.to_datetime(df['time'])\ndf = df[df['time'].dt.year == 2021]\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074660177_dataframe_pandas_python.txt
Q: Rails + Passenger + Nginx + Dokku 504 after 1 minute of activity Got a rails app currently running and stable on heroku server (512mb ram) I took the app as is and put it on dokku (with intercity) on a ubuntu server 14gb ram 2 cpu(azure). The app spins and works very fast, everything looks fine. After 1 min of inactivity I refresh the browser and get a 504 Gateway Time-out I try search for errors or any memory issues but the only thing looks wrong is the 17/01/18 11:24:18 [error] 61198#61198: *2071 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 79.184.17.155, server: cltvf.site, request: "GET /campaigns/5874e4d14bc3600a4a19566/details HTTP/1.1", upstream: "http://172.11.0.3:5000/campaigns/587f4e4d4bc3600a4a19566/details", host: "cltvf.site", referrer: "http://cltv.site/an/u_request_approve" I got from the nginx:error-logs command the 172.11.0.3 is an internal ip, if helps. when trying to check if there is a memory issue I saw CONTAINER CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS ac513d4dd4ea 0.00% 199.8 MiB / 13.69 GiB 1.43% 296.7 kB / 156.5 kB 0 B / 0 B 13 a296ec88b1ef 0.01% 254.2 MiB / 13.69 GiB 1.81% 282.5 kB / 111.4 kB 0 B / 614.4 kB 52 beb69ddc4351 0.13% 254.3 MiB / 13.69 GiB 1.81% 286.9 kB / 112.5 kB 0 B / 614.4 kB 51 43665198a31b 0.00% 231.8 MiB / 13.69 GiB 1.65% 19.33 MB / 21.8 MB 0 B / 0 B 12 7d374f36b240 0.00% 231.6 MiB / 13.69 GiB 1.65% 19.34 MB / 21.81 MB 0 B / 0 B 13 04e98f7914b0 0.01% 343.9 MiB / 13.69 GiB 2.45% 14.37 MB / 9.091 MB 0 B / 614.4 kB 51 1255e7837b19 0.20% 231.5 MiB / 13.69 GiB 1.65% 19.34 MB / 21.78 MB 0 B / 0 B 12 378302bbdb84 0.00% 55.11 MiB / 13.69 GiB 0.39% 64.81 kB / 4.737 kB 0 B / 225.3 kB 40 5b8eb7a5423e 0.01% 52.47 MiB / 13.69 GiB 0.37% 71.75 kB / 8.718 kB 0 B / 225.3 kB 40 You can see nothing serious same for disk usage dev/sda1 28G 7403M 21G 25.5 [##########............................] / /dev/sdb1 27G 44M 26G 0.2 [......................................] /mnt /dev/sda1 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/4631d50385f25bf480fc18f5f2c7d93052b0f2ffecd6d04a14076513344b7338 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/4f8488bdd0a683fda71a6789165d44626215ef4ce00f7d6c70c7ff64d7d89c14 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/553fb1ea82841dd534450e9929513b90d17e4be73e271b861716d8f240ef8d17 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/6909bba1bea70a3781f55bea3d059a014ddae8638021bf4f9a82edffab63cc94 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/7200a36e8f3ca4e9358f83aad1ac5de562068f6458045f291812b8ab9e769abf none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/bd289b0106072a2946e40a60bacb2b1024d1075996aff5bb3388290617ad85b2 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/bd4d4632764af3a8e61b6da8d5f137addc2044615a5a36e72f675a180e6f7c7c none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/e050fcacaeb0d9cb759bc72e768b2ceabd2eb95350f7c9ba6f20933c4696d1ef none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/ffd758a6189aab5eac81950df15779f84f7c93a2a81b1707b082cee2202ece4d I'm posting this question after hours of googling. thanks A: You could start by checking application logs: dokku logs <app> You can try to connect directly to curl http://172.11.0.3:5000/ You can try to enter the container that is running the web process: dokku enter <app> web You can use gdb, strace to connect to the process and use standard linux debugging tools A: Most probably the request is taking to long to execute and it fails with 504 Gateway Timeout. This usually happens when your server response time becomes longer than 60s (depending on the setting in nginx.conf, in dokku 60s is default). The solutions is: The easiest: increase the proxy_read_timeout in /home/dokku/:your_app_name/nginx.conf and reload nginx config. Or find the root cause why your request takes too long to execute and make it respond faster (enable caching for example, or split time expensive tasks in separate workers processes and make web service just respond the status of jobs, allowing frontend to just poll the status of job until its finished)
Rails + Passenger + Nginx + Dokku 504 after 1 minute of activity
Got a rails app currently running and stable on heroku server (512mb ram) I took the app as is and put it on dokku (with intercity) on a ubuntu server 14gb ram 2 cpu(azure). The app spins and works very fast, everything looks fine. After 1 min of inactivity I refresh the browser and get a 504 Gateway Time-out I try search for errors or any memory issues but the only thing looks wrong is the 17/01/18 11:24:18 [error] 61198#61198: *2071 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 79.184.17.155, server: cltvf.site, request: "GET /campaigns/5874e4d14bc3600a4a19566/details HTTP/1.1", upstream: "http://172.11.0.3:5000/campaigns/587f4e4d4bc3600a4a19566/details", host: "cltvf.site", referrer: "http://cltv.site/an/u_request_approve" I got from the nginx:error-logs command the 172.11.0.3 is an internal ip, if helps. when trying to check if there is a memory issue I saw CONTAINER CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS ac513d4dd4ea 0.00% 199.8 MiB / 13.69 GiB 1.43% 296.7 kB / 156.5 kB 0 B / 0 B 13 a296ec88b1ef 0.01% 254.2 MiB / 13.69 GiB 1.81% 282.5 kB / 111.4 kB 0 B / 614.4 kB 52 beb69ddc4351 0.13% 254.3 MiB / 13.69 GiB 1.81% 286.9 kB / 112.5 kB 0 B / 614.4 kB 51 43665198a31b 0.00% 231.8 MiB / 13.69 GiB 1.65% 19.33 MB / 21.8 MB 0 B / 0 B 12 7d374f36b240 0.00% 231.6 MiB / 13.69 GiB 1.65% 19.34 MB / 21.81 MB 0 B / 0 B 13 04e98f7914b0 0.01% 343.9 MiB / 13.69 GiB 2.45% 14.37 MB / 9.091 MB 0 B / 614.4 kB 51 1255e7837b19 0.20% 231.5 MiB / 13.69 GiB 1.65% 19.34 MB / 21.78 MB 0 B / 0 B 12 378302bbdb84 0.00% 55.11 MiB / 13.69 GiB 0.39% 64.81 kB / 4.737 kB 0 B / 225.3 kB 40 5b8eb7a5423e 0.01% 52.47 MiB / 13.69 GiB 0.37% 71.75 kB / 8.718 kB 0 B / 225.3 kB 40 You can see nothing serious same for disk usage dev/sda1 28G 7403M 21G 25.5 [##########............................] / /dev/sdb1 27G 44M 26G 0.2 [......................................] /mnt /dev/sda1 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/4631d50385f25bf480fc18f5f2c7d93052b0f2ffecd6d04a14076513344b7338 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/4f8488bdd0a683fda71a6789165d44626215ef4ce00f7d6c70c7ff64d7d89c14 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/553fb1ea82841dd534450e9929513b90d17e4be73e271b861716d8f240ef8d17 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/6909bba1bea70a3781f55bea3d059a014ddae8638021bf4f9a82edffab63cc94 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/7200a36e8f3ca4e9358f83aad1ac5de562068f6458045f291812b8ab9e769abf none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/bd289b0106072a2946e40a60bacb2b1024d1075996aff5bb3388290617ad85b2 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/bd4d4632764af3a8e61b6da8d5f137addc2044615a5a36e72f675a180e6f7c7c none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/e050fcacaeb0d9cb759bc72e768b2ceabd2eb95350f7c9ba6f20933c4696d1ef none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/ffd758a6189aab5eac81950df15779f84f7c93a2a81b1707b082cee2202ece4d I'm posting this question after hours of googling. thanks
[ "\nYou could start by checking application logs: dokku logs <app>\nYou can try to connect directly to curl http://172.11.0.3:5000/\nYou can try to enter the container that is running the web process: dokku enter <app> web\nYou can use gdb, strace to connect to the process and use standard linux debugging tools\n\n", "Most probably the request is taking to long to execute and it fails with 504 Gateway Timeout.\nThis usually happens when your server response time becomes longer than 60s (depending on the setting in nginx.conf, in dokku 60s is default).\nThe solutions is:\n\nThe easiest: increase the proxy_read_timeout in /home/dokku/:your_app_name/nginx.conf and reload nginx config.\n\nOr find the root cause why your request takes too long to execute and make it respond faster (enable caching for example, or split time expensive tasks in separate workers processes and make web service just respond the status of jobs, allowing frontend to just poll the status of job until its finished)\n\n\n" ]
[ 0, 0 ]
[]
[]
[ "dokku", "nginx", "passenger", "ruby_on_rails" ]
stackoverflow_0041719099_dokku_nginx_passenger_ruby_on_rails.txt
Q: How to specify glue version 3.0 for an AWS crawler with boto3? I have an existing AWS glue crawler with a glue connector to a MySQL database that runs successfully. I need to move it to glue v3 so that it uses an updated MySQL JDBC driver (Glue 2.0 jobs use MySQL JDBC driver version 5.1 but AWS Glue 3.0 use MySQL JDBC driver 8.0.23). The crawler is created/updated with boto3's glue_client.update_crawler. The crawler is set to use a JDBC glue connector that is also created with boto3 and also does not have a glue_version parameter. The documentation on boto3's glue client crawler functions, https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/glue.html#Glue.Client.update_crawler, does not include an option for GlueVersion. I don't see any relevant options in the console either. The crawler configuration has a version but I don't think it's the glue version and it errors out when I set it to 3.0. I'm not sure if there is maybe a default setting for glue version somewhere that crawlers use? Currently I am using: glue_client = boto3.client('glue',region_name=region) configuration= {"Version": 1.0,"Grouping": {"TableGroupingPolicy": "CombineCompatibleSchemas" }} response = glue_client.update_crawler( Name= crawler_name, Role= glue_role_arn, DatabaseName=str(crawler_details['DatabaseName']) + '-' + str(env_suffix), Description=crawler_details['description'], Targets=targets, TablePrefix=crawler_details['TablePrefix'], Schedule=crawler_details['Schedule'], SchemaChangePolicy= crawler_details['SchemaChangePolicy'], Configuration=configuration ) How do I set a glue crawler to use GlueVersion = 3.0 using boto3? A: A Glue Crawler does not have a version, Glue Jobs have. You need to select the correct connection in the target property, so that you are able to connect to a newer version.
How to specify glue version 3.0 for an AWS crawler with boto3?
I have an existing AWS glue crawler with a glue connector to a MySQL database that runs successfully. I need to move it to glue v3 so that it uses an updated MySQL JDBC driver (Glue 2.0 jobs use MySQL JDBC driver version 5.1 but AWS Glue 3.0 use MySQL JDBC driver 8.0.23). The crawler is created/updated with boto3's glue_client.update_crawler. The crawler is set to use a JDBC glue connector that is also created with boto3 and also does not have a glue_version parameter. The documentation on boto3's glue client crawler functions, https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/glue.html#Glue.Client.update_crawler, does not include an option for GlueVersion. I don't see any relevant options in the console either. The crawler configuration has a version but I don't think it's the glue version and it errors out when I set it to 3.0. I'm not sure if there is maybe a default setting for glue version somewhere that crawlers use? Currently I am using: glue_client = boto3.client('glue',region_name=region) configuration= {"Version": 1.0,"Grouping": {"TableGroupingPolicy": "CombineCompatibleSchemas" }} response = glue_client.update_crawler( Name= crawler_name, Role= glue_role_arn, DatabaseName=str(crawler_details['DatabaseName']) + '-' + str(env_suffix), Description=crawler_details['description'], Targets=targets, TablePrefix=crawler_details['TablePrefix'], Schedule=crawler_details['Schedule'], SchemaChangePolicy= crawler_details['SchemaChangePolicy'], Configuration=configuration ) How do I set a glue crawler to use GlueVersion = 3.0 using boto3?
[ "A Glue Crawler does not have a version, Glue Jobs have. You need to select the correct connection in the target property, so that you are able to connect to a newer version.\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_glue", "boto3", "glue_crawler" ]
stackoverflow_0074659907_amazon_web_services_aws_glue_boto3_glue_crawler.txt
Q: fiscal area in the supplier information tab of the purchase order Could you help me, I am changing the tax area code by adaptation, however the taxes are not updated, what am I missing or how can I change the related taxes when I change the tax area? This is my code, through this event that I'm doing. protected void POLine_SiteID_FieldUpdated(PXCache cache, PXFieldUpdatedEventArgs e) { var row = (POLine)e.Row; var head = Base.Document.Current; if (head == null) return; if (row != null && row.OrderType == POOrderType.RegularOrder) { POLine line = PXSelect<POLine, Where<POLine.orderType, Equal<Required<POLine.orderType>>, And<POLine.orderNbr, Equal<Required<POLine.orderNbr>>>>>.Select(Base, row.OrderType, row.OrderNbr); bool? xchange = false; if (line != null) { INSite site = PXSelect<INSite, Where<INSite.siteID, Equal<Required<INSite.siteID>>>>.Select(Base, line.SiteID); if (site != null && line.SiteID == site.SiteID) { var ext = site.GetExtension<INSiteExt>(); if (ext != null) { head.TaxZoneID = ext.UsrTaxZone; xchange = true; } } if (xchange == true) { foreach (PEMclTaxZone zone in PXSelect<PEMclTaxZone, Where<PEMclTaxZone.taxZoneID, Equal<Required<PEMclTaxZone.taxZoneID>>, And<PEMclTaxZone.taxCategoryID, Equal<Required<PEMclTaxZone.taxCategoryID>>>>>.Select(Base, head.TaxZoneID, line.TaxCategoryID)) { if (zone != null) { foreach (POTaxTran potax in PXSelect<POTaxTran, Where<POTaxTran.orderType, Equal<Required<POTaxTran.orderType>>, And<POTaxTran.orderNbr, Equal<Required<POTaxTran.orderNbr>>>>>.Select(Base, head.OrderType, head.OrderNbr)) { if (potax != null) { potax.TaxID = zone.Taxid; potax.TaxZoneID = zone.TaxZoneID; Base.Taxes.Cache.Update(potax); } } } } } } } } When I select the tax area manually, two elements are registered in the tax grid, if I do it by event it only updates the last one, I follow it by code and I see that if it updates, however, it does not reflect in the tax grid. Here I show evidence, with images. This step is with an event that is not working. step 1 step 2: step 3: manually select the tax area, selected from the same tab. step 1: step 2: That's how it should go, that's what I want the event to do. Please tell me what I am failing in the event, I hope I have been clear, thanks. A: The functions that grab these are the Tax Zone Extensions. You would want to override the GetDefaultTaxZone function of POOrderEntry [PXOverride] public virtual string GetDefaultTaxZone(POOrder row, Func<POOrder, string> baseMethod) { //logic before base function baseMethod(row); //logic after base function } If you do not want any of the code to be run, feel free to copy the initial function and do not call the baseMethod delegate.
fiscal area in the supplier information tab of the purchase order
Could you help me, I am changing the tax area code by adaptation, however the taxes are not updated, what am I missing or how can I change the related taxes when I change the tax area? This is my code, through this event that I'm doing. protected void POLine_SiteID_FieldUpdated(PXCache cache, PXFieldUpdatedEventArgs e) { var row = (POLine)e.Row; var head = Base.Document.Current; if (head == null) return; if (row != null && row.OrderType == POOrderType.RegularOrder) { POLine line = PXSelect<POLine, Where<POLine.orderType, Equal<Required<POLine.orderType>>, And<POLine.orderNbr, Equal<Required<POLine.orderNbr>>>>>.Select(Base, row.OrderType, row.OrderNbr); bool? xchange = false; if (line != null) { INSite site = PXSelect<INSite, Where<INSite.siteID, Equal<Required<INSite.siteID>>>>.Select(Base, line.SiteID); if (site != null && line.SiteID == site.SiteID) { var ext = site.GetExtension<INSiteExt>(); if (ext != null) { head.TaxZoneID = ext.UsrTaxZone; xchange = true; } } if (xchange == true) { foreach (PEMclTaxZone zone in PXSelect<PEMclTaxZone, Where<PEMclTaxZone.taxZoneID, Equal<Required<PEMclTaxZone.taxZoneID>>, And<PEMclTaxZone.taxCategoryID, Equal<Required<PEMclTaxZone.taxCategoryID>>>>>.Select(Base, head.TaxZoneID, line.TaxCategoryID)) { if (zone != null) { foreach (POTaxTran potax in PXSelect<POTaxTran, Where<POTaxTran.orderType, Equal<Required<POTaxTran.orderType>>, And<POTaxTran.orderNbr, Equal<Required<POTaxTran.orderNbr>>>>>.Select(Base, head.OrderType, head.OrderNbr)) { if (potax != null) { potax.TaxID = zone.Taxid; potax.TaxZoneID = zone.TaxZoneID; Base.Taxes.Cache.Update(potax); } } } } } } } } When I select the tax area manually, two elements are registered in the tax grid, if I do it by event it only updates the last one, I follow it by code and I see that if it updates, however, it does not reflect in the tax grid. Here I show evidence, with images. This step is with an event that is not working. step 1 step 2: step 3: manually select the tax area, selected from the same tab. step 1: step 2: That's how it should go, that's what I want the event to do. Please tell me what I am failing in the event, I hope I have been clear, thanks.
[ "The functions that grab these are the Tax Zone Extensions. You would want to override the GetDefaultTaxZone function of POOrderEntry\n [PXOverride]\n public virtual string GetDefaultTaxZone(POOrder row,\n Func<POOrder, string> baseMethod)\n {\n //logic before base function\n baseMethod(row);\n //logic after base function\n }\n\nIf you do not want any of the code to be run, feel free to copy the initial function and do not call the baseMethod delegate.\n" ]
[ 0 ]
[]
[]
[ "acumatica", "acumatica_kb", "acumos" ]
stackoverflow_0074435867_acumatica_acumatica_kb_acumos.txt
Q: Create hard/soft links in HDF5 C++ A{O I have an H5::Dataset which I wan't to make it accessible from several H5::Groups. I know this is possible using hard or soft link, but I am completely out of ideas on how to add this link using the C++ API. I have seen that in Python one can do grp["name"] = h5py.SoftLink(target_path) but I can't find anything similar in C++. How can I achieve this? A: If you are not bound to a specific API, you may want to try HDFql as it greatly alleviates users from HDF5 low-level details. Using HDFql in C++, your issue could be solved as follows: // create an HDF5 file named 'test.h5' and use (i.e. open) it HDFql::execute("create and use file test.h5"); // create a dataset named 'dset' of data type integer which stores value '10' HDFql::execute("create dataset dset as int values(10)"); // create three groups named 'grp1', 'grp2' and 'grp3' HDFql::execute("create group grp1, grp2, grp3"); // create a (soft) link named 'lnk' in groups 'grp1', 'grp2' and 'grp3' (all these links point to dataset 'dset') HDFql::execute("create link grp1/lnk, grp2/lnk, grp3/lnk to /dset, /dset, /dset");
Create hard/soft links in HDF5 C++ A{O
I have an H5::Dataset which I wan't to make it accessible from several H5::Groups. I know this is possible using hard or soft link, but I am completely out of ideas on how to add this link using the C++ API. I have seen that in Python one can do grp["name"] = h5py.SoftLink(target_path) but I can't find anything similar in C++. How can I achieve this?
[ "If you are not bound to a specific API, you may want to try HDFql as it greatly alleviates users from HDF5 low-level details. Using HDFql in C++, your issue could be solved as follows:\n// create an HDF5 file named 'test.h5' and use (i.e. open) it \nHDFql::execute(\"create and use file test.h5\");\n\n// create a dataset named 'dset' of data type integer which stores value '10'\nHDFql::execute(\"create dataset dset as int values(10)\");\n\n// create three groups named 'grp1', 'grp2' and 'grp3'\nHDFql::execute(\"create group grp1, grp2, grp3\");\n\n// create a (soft) link named 'lnk' in groups 'grp1', 'grp2' and 'grp3' (all these links point to dataset 'dset')\nHDFql::execute(\"create link grp1/lnk, grp2/lnk, grp3/lnk to /dset, /dset, /dset\");\n\n" ]
[ 0 ]
[]
[]
[ "c++", "hdf5" ]
stackoverflow_0074657760_c++_hdf5.txt
Q: Multicolumn order by a tuple Lets supose I have a tabla A like: bisac1 bisac2 bisac3 desire x y z 10 y z x 8 z y x 6 x y p 20 r y z 13 x s z 1 a y l 12 a x k 2 x p w 1 I would like to be able to count the number of times any of these elements (x,y,z) appears in the cols (bisac1,bisac2,bisac3). So, the expected result should be 3 for the first 3 rows, 2 for the next 3 and 1 for the last 3. A: Seems the following should do what you require? select case when bisac1 in ('x','y','z') then 1 else 0 end + case when bisac2 in ('x','y','z') then 1 else 0 end + case when bisac3 in ('x','y','z') then 1 else 0 end from t; A: You can also use one case per letter instead of one case per column (Stu's approach). The result will be the same for your sample data: SELECT CASE WHEN 'x' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END + CASE WHEN 'y' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END + CASE WHEN 'z' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END FROM yourtable; The result will not be the same if the same letter occurs in different columns, For example, if your row looks like this: bisac1 bisac2 bisac3 x y y Then Stu's query will produce 3 as result, my query here 2. From your description, it is unclear to me if your sample data can contain such rows at all or if the two queries will always create the same result for your data. And even if your data can include such rows, it's still unclear to me whether you want to get 3 or 2 as result. So, summarized, it's up to you what exactly you want to use here.
Multicolumn order by a tuple
Lets supose I have a tabla A like: bisac1 bisac2 bisac3 desire x y z 10 y z x 8 z y x 6 x y p 20 r y z 13 x s z 1 a y l 12 a x k 2 x p w 1 I would like to be able to count the number of times any of these elements (x,y,z) appears in the cols (bisac1,bisac2,bisac3). So, the expected result should be 3 for the first 3 rows, 2 for the next 3 and 1 for the last 3.
[ "Seems the following should do what you require?\nselect \n case when bisac1 in ('x','y','z') then 1 else 0 end +\n case when bisac2 in ('x','y','z') then 1 else 0 end +\n case when bisac3 in ('x','y','z') then 1 else 0 end \nfrom t;\n\n", "You can also use one case per letter instead of one case per column (Stu's approach). The result will be the same for your sample data:\nSELECT \n CASE WHEN 'x' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END +\n CASE WHEN 'y' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END +\n CASE WHEN 'z' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END\nFROM yourtable;\n\nThe result will not be the same if the same letter occurs in different columns, For example, if your row looks like this:\n\n\n\n\nbisac1\nbisac2\nbisac3\n\n\n\n\nx\ny\ny\n\n\n\n\nThen Stu's query will produce 3 as result, my query here 2. From your description, it is unclear to me if your sample data can contain such rows at all or if the two queries will always create the same result for your data.\nAnd even if your data can include such rows, it's still unclear to me whether you want to get 3 or 2 as result.\nSo, summarized, it's up to you what exactly you want to use here.\n" ]
[ 1, 0 ]
[]
[]
[ "postgresql", "sql" ]
stackoverflow_0074660147_postgresql_sql.txt
Q: Why is my api response not inserted into postgres dictionary = testEns(idSession) columns = dictionary.keys() for i in dictionary.values(): sql2='''insert into PERSONS(person_id , person_name) VALUES{};'''.format(i) cursor.execute(sql2) The function testEns(idSession) contains the result of an api call that returns an xml response that has been transformed into a dictionary. i'm trying to insert the response into a table that have been created in a postgres database but here is the error i'm getting. Any idea why? and what am i missing? psycopg2.errors.SyntaxError: syntax error at or near "{" LINE1: ...nsert into PERSONS(person_id, person_name) VALUES{'category... After I changed VALUES{id, name} to VALUES(id, name) I have this error psycopg2.errors.UndefinedColumn: column "id" does not exist LINE 1: ...sert into PERSONS(person_id , person_name) VALUES(id, name) eve though my table PERSONS is created in pgadmin with the columns id and name A: Your SQL statement looks off, I think you want something like: sql2='''insert into PERSONS (person_id , person_name) VALUES (%s, %s);''' cursor.execute(sql2, (i.person_id, i.person_name)) Assuming the property names in i here.
Why is my api response not inserted into postgres
dictionary = testEns(idSession) columns = dictionary.keys() for i in dictionary.values(): sql2='''insert into PERSONS(person_id , person_name) VALUES{};'''.format(i) cursor.execute(sql2) The function testEns(idSession) contains the result of an api call that returns an xml response that has been transformed into a dictionary. i'm trying to insert the response into a table that have been created in a postgres database but here is the error i'm getting. Any idea why? and what am i missing? psycopg2.errors.SyntaxError: syntax error at or near "{" LINE1: ...nsert into PERSONS(person_id, person_name) VALUES{'category... After I changed VALUES{id, name} to VALUES(id, name) I have this error psycopg2.errors.UndefinedColumn: column "id" does not exist LINE 1: ...sert into PERSONS(person_id , person_name) VALUES(id, name) eve though my table PERSONS is created in pgadmin with the columns id and name
[ "Your SQL statement looks off, I think you want something like:\nsql2='''insert into PERSONS (person_id , person_name) VALUES (%s, %s);'''\ncursor.execute(sql2, (i.person_id, i.person_name))\n\nAssuming the property names in i here.\n" ]
[ 0 ]
[ "Your line\nsql2 = '''insert into PERSONS(person_id , person_name) VALUES{};'''.format(i)\n\nShould be fixed\nsql2 = '''INSERT INTO PERSONS (person_id, person_name) VALUES (value1, value2, ...)'''.format(i)\n\n" ]
[ -1 ]
[ "postgresql", "python" ]
stackoverflow_0074660328_postgresql_python.txt
Q: Position Alert dialog in Android Compose How to position alert dialog in Jetpack Compose to the bottom of the screen. Also, set transparent background. A: Thanks, @alekseyHunter & @johann. I can able to achieve this with custom layout modifier. Custom modifier to position alert dialog enum class CustomDialogPosition { BOTTOM, TOP } fun Modifier.customDialogModifier(pos: CustomDialogPosition) = layout { measurable, constraints -> val placeable = measurable.measure(constraints); layout(constraints.maxWidth, constraints.maxHeight){ when(pos) { CustomDialogPosition.BOTTOM -> { placeable.place(0, constraints.maxHeight - placeable.height, 10f) } CustomDialogPosition.TOP -> { placeable.place(0,0,10f) } } } } And in alert dialog implementation as AlertDialog( ..., modifiers = Modifiers.customDialogModifier(CustomDialogPosition.BOTTOM)) { // block }) A: Look so simple. Box(Modifier.fillMaxSize()) { Column() { /* Content */ } /* Box alert */ Box( Modifier .padding(horizontal = 32.dp, vertical = 16.dp) .fillMaxWidth() .background(Color.Transparent, RoundedCornerShape(8.dp)) .border(2.dp, Color.LightGray, RoundedCornerShape(8.dp)) .align(Alignment.BottomCenter) ) { Text( text = "Alert", modifier = Modifier .padding(16.dp) .fillMaxWidth(), textAlign = TextAlign.Center, color = Color.Black ) } } A: The solution provided by @Rameshbabu changes the position of the dialog as expected. However, as was mentioned in the comments the dialog consequently becomes "fullscreen" and it can't be dismissed by tapping on the overlay. I found another tricky solution. You can copy the source code of androidx.compose.ui.window.AndroidDialog.kt which comes with "androidx.compose.ui". By doing this you'll be able to access the dialog's window directly and change its gravity and other parameters. The simplest way would be to add some code in the androidx.compose.ui.window.DialogWrapper class. For example in the init function: private class DialogWrapper( private var onDismissRequest: () -> Unit, ... ) : Dialog(ContextThemeWrapper(...){ ... init { val window = window ?: error("Dialog has no window") window.requestFeature(Window.FEATURE_NO_TITLE) window.setBackgroundDrawableResource(android.R.color.transparent) window.setGravity(Gravity.TOP) // This to be added Hopefully, the Jetpack Compose team will make the compose Dialog more customizable in the future. A: The solution that worked best for me, getting the idea from Vladimir's response, is to get a reference to the window from within the Dialog and set the desired gravity. Dialog( onDismissRequest = [...], properties = [...], ) { val dialogWindowProvider = LocalView.current.parent as DialogWindowProvider dialogWindowProvider.window.setGravity(Gravity.BOTTOM) [...] } The cast shouldn't be an issue but, of course, it could be safe-casted to prevent unpleasant surprises.
Position Alert dialog in Android Compose
How to position alert dialog in Jetpack Compose to the bottom of the screen. Also, set transparent background.
[ "Thanks, @alekseyHunter & @johann. I can able to achieve this with custom layout modifier.\nCustom modifier to position alert dialog\nenum class CustomDialogPosition {\n BOTTOM, TOP\n}\n\nfun Modifier.customDialogModifier(pos: CustomDialogPosition) = layout { measurable, constraints ->\n\n val placeable = measurable.measure(constraints);\n layout(constraints.maxWidth, constraints.maxHeight){\n when(pos) {\n CustomDialogPosition.BOTTOM -> {\n placeable.place(0, constraints.maxHeight - placeable.height, 10f)\n }\n CustomDialogPosition.TOP -> {\n placeable.place(0,0,10f)\n }\n }\n }\n}\n\nAnd in alert dialog implementation as\nAlertDialog( ..., modifiers = Modifiers.customDialogModifier(CustomDialogPosition.BOTTOM)) \n{\n // block\n})\n\n", "Look so simple.\nBox(Modifier.fillMaxSize()) {\n Column() {\n /* Content */\n }\n /* Box alert */\n Box(\n Modifier\n .padding(horizontal = 32.dp, vertical = 16.dp)\n .fillMaxWidth()\n .background(Color.Transparent, RoundedCornerShape(8.dp))\n .border(2.dp, Color.LightGray, RoundedCornerShape(8.dp))\n .align(Alignment.BottomCenter)\n ) {\n Text(\n text = \"Alert\",\n modifier = Modifier\n .padding(16.dp)\n .fillMaxWidth(),\n textAlign = TextAlign.Center,\n color = Color.Black\n )\n }\n }\n\n", "The solution provided by @Rameshbabu changes the position of the dialog as expected. However, as was mentioned in the comments the dialog consequently becomes \"fullscreen\" and it can't be dismissed by tapping on the overlay.\nI found another tricky solution. You can copy the source code of androidx.compose.ui.window.AndroidDialog.kt which comes with \"androidx.compose.ui\". By doing this you'll be able to access the dialog's window directly and change its gravity and other parameters.\nThe simplest way would be to add some code in the androidx.compose.ui.window.DialogWrapper class. For example in the init function:\nprivate class DialogWrapper(\n private var onDismissRequest: () -> Unit,\n ...\n) : Dialog(ContextThemeWrapper(...){\n\n...\n\ninit {\n val window = window ?: error(\"Dialog has no window\")\n window.requestFeature(Window.FEATURE_NO_TITLE)\n window.setBackgroundDrawableResource(android.R.color.transparent)\n window.setGravity(Gravity.TOP) // This to be added\n\nHopefully, the Jetpack Compose team will make the compose Dialog more customizable in the future.\n", "The solution that worked best for me, getting the idea from Vladimir's response, is to get a reference to the window from within the Dialog and set the desired gravity.\nDialog(\n onDismissRequest = [...],\n properties = [...],\n) {\n val dialogWindowProvider = LocalView.current.parent as DialogWindowProvider\n dialogWindowProvider.window.setGravity(Gravity.BOTTOM)\n [...]\n}\n\nThe cast shouldn't be an issue but, of course, it could be safe-casted to prevent unpleasant surprises.\n" ]
[ 9, 1, 0, 0 ]
[]
[]
[ "android", "android_alertdialog", "android_jetpack_compose" ]
stackoverflow_0070390697_android_android_alertdialog_android_jetpack_compose.txt
Q: GOINSECURE to enable http downlaods on packages from Github I'm developing a CLI app at work in order to automate a couple tedious tasks, to do this I need to install a couple packages like gotp. I noticed that installing this new package into my project this error pops up. go get github.com/xlzd/gotp go: module github.com/xlzd/gotp: Get "https://proxy.golang.org/github.com/xlzd/gotp/@v/list": x509: certificate signed by unknown authority I suppose this has something to do with my work PC's firewall or security configuration, since I was able to install a couple packages before the firewall was enabled on my PC. I read about the environment variable GOINSECURE which would enable go get to download packages over HTTP. So here's what I've done in my case. export GOINSECURE="proxy.golang.org/*,github.com,github.com/*" Still the same error pops up, am I missing something in my configuration? A: I also encountered this error when I installed internal package, the solution is selected proper proxy, I change my GOPROXY to internal proxy site address, and made GOPRIVATE, GONOPROXY, GONOSUMDB to null value. In your case, you may attempt GOINSECURE="proxy.golang.org/*,github.com,github.com/*" GONOSUMDB="proxy.golang.org/*,github.com,github.com/*" GOPRIVATE="proxy.golang.org/*,github.com,github.com/*" A: I struggled with this when trying to use go inside a bash shell in a ubuntu22 container running inside docker desktop for windows on a corporate network. I want to do go get github.com/Masterminds/sprig But kept getting x509 errors go get github.com/Masterminds/sprig go: github.com/Masterminds/[email protected]: Get "https://proxy.golang.org/github.com/%21masterminds/goutils/@v/v1.1.1.mod": x509: certificate signed by unknown authority go get --insecure is indeed deprecated and don't work any more export GOINSECURE=github.com didn't work at first it seemed to be more a combination of using GOINSECURE with git config --global http.sslverify false One I'd set this sslVerify to false, it got further.. so I kept iterating the go get github.com/Masterminds/sprig and each time it got further.. calling out another url (probably a package dependency) go get github.com/Masterminds/sprig go: golang.org/x/[email protected]: unrecognized import path "golang.org/x/crypto": https fetch: Get "https://golang.org/x/cr ypto?go-get=1": x509: certificate signed by unknown authority each time I added the url to the GOINSECURE i.e. export GOINSECURE=github.com,golang.org go get github.com/Masterminds/sprig go: sigs.k8s.io/[email protected]: unrecognized import path "sigs.k8s.io/yaml": https fetch: Get "https://sigs.k8s.io/yaml?go-get=1": x509: certificate sig ned by unknown authority export GOINSECURE=github.com,golang.org,sigs.k8s.io Until ultimately everything was downloaded go get github.com/Masterminds/sprig go: downloading github.com/Masterminds/sprig v2.22.0+incompatible go: downloading github.com/Masterminds/goutils v1.1.1 go: downloading github.com/Masterminds/semver v1.5.0 go: downloading github.com/google/uuid v1.3.0 go: downloading github.com/huandu/xstrings v1.3.2 go: downloading github.com/imdario/mergo v0.3.12 go: downloading github.com/mitchellh/copystructure v1.2.0 go: downloading golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa go: downloading github.com/mitchellh/reflectwalk v1.0.2 ""/bin/go build prehelm.go go: downloading sigs.k8s.io/yaml v1.2.0 go: downloading gopkg.in/yaml.v2 v2.3.0 I hope that helps, in short ensure you have git config --global http.sslverify false add the sites to you GOINSECURE= one by one until done. Alternatively but less secure you can add export GOINSECURE=*
GOINSECURE to enable http downlaods on packages from Github
I'm developing a CLI app at work in order to automate a couple tedious tasks, to do this I need to install a couple packages like gotp. I noticed that installing this new package into my project this error pops up. go get github.com/xlzd/gotp go: module github.com/xlzd/gotp: Get "https://proxy.golang.org/github.com/xlzd/gotp/@v/list": x509: certificate signed by unknown authority I suppose this has something to do with my work PC's firewall or security configuration, since I was able to install a couple packages before the firewall was enabled on my PC. I read about the environment variable GOINSECURE which would enable go get to download packages over HTTP. So here's what I've done in my case. export GOINSECURE="proxy.golang.org/*,github.com,github.com/*" Still the same error pops up, am I missing something in my configuration?
[ "I also encountered this error when I installed internal package, the solution is selected proper proxy, I change my GOPROXY to internal proxy site address, and made GOPRIVATE, GONOPROXY, GONOSUMDB to null value.\nIn your case, you may attempt\nGOINSECURE=\"proxy.golang.org/*,github.com,github.com/*\"\nGONOSUMDB=\"proxy.golang.org/*,github.com,github.com/*\"\nGOPRIVATE=\"proxy.golang.org/*,github.com,github.com/*\"\n\n", "I struggled with this when trying to use go inside a bash shell in a ubuntu22 container running inside docker desktop for windows on a corporate network.\nI want to do\ngo get github.com/Masterminds/sprig\n\nBut kept getting x509 errors\ngo get github.com/Masterminds/sprig\ngo: github.com/Masterminds/[email protected]: Get \"https://proxy.golang.org/github.com/%21masterminds/goutils/@v/v1.1.1.mod\": x509: certificate signed by unknown authority\n\n\ngo get --insecure is indeed deprecated and don't work any more\n\nexport GOINSECURE=github.com didn't work at first\n\nit seemed to be more a combination of using GOINSECURE with\ngit config --global http.sslverify false\n\n\nOne I'd set this sslVerify to false, it got further..\nso I kept iterating the go get github.com/Masterminds/sprig and each time it got further.. calling out another url (probably a package dependency)\ngo get github.com/Masterminds/sprig\ngo: golang.org/x/[email protected]: unrecognized import path \"golang.org/x/crypto\": https fetch: Get \"https://golang.org/x/cr\nypto?go-get=1\": x509: certificate signed by unknown authority\n\neach time I added the url to the GOINSECURE i.e.\nexport GOINSECURE=github.com,golang.org\n\ngo get github.com/Masterminds/sprig\ngo: sigs.k8s.io/[email protected]: unrecognized import path \"sigs.k8s.io/yaml\": https fetch: Get \"https://sigs.k8s.io/yaml?go-get=1\": x509: certificate sig\nned by unknown authority\n\nexport GOINSECURE=github.com,golang.org,sigs.k8s.io\n\nUntil ultimately everything was downloaded\ngo get github.com/Masterminds/sprig\ngo: downloading github.com/Masterminds/sprig v2.22.0+incompatible\ngo: downloading github.com/Masterminds/goutils v1.1.1\ngo: downloading github.com/Masterminds/semver v1.5.0\ngo: downloading github.com/google/uuid v1.3.0\ngo: downloading github.com/huandu/xstrings v1.3.2\ngo: downloading github.com/imdario/mergo v0.3.12\ngo: downloading github.com/mitchellh/copystructure v1.2.0\ngo: downloading golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa\ngo: downloading github.com/mitchellh/reflectwalk v1.0.2\n\"\"/bin/go build prehelm.go\ngo: downloading sigs.k8s.io/yaml v1.2.0\ngo: downloading gopkg.in/yaml.v2 v2.3.0\n\nI hope that helps, in short\n\nensure you have git config --global http.sslverify false\nadd the sites to you GOINSECURE= one by one until done.\nAlternatively but less secure you can add export GOINSECURE=*\n\n" ]
[ 0, 0 ]
[]
[]
[ "go", "go_get" ]
stackoverflow_0071623508_go_go_get.txt
Q: Unable to install the jupyter module with pip I would like to be able to install the python module jupyter with pip but I get an error in my terminal when I try 'pip install jupyter' which returns this: ` error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [9 lines of output] C:\Users\nunes\AppData\Local\Temp\pip-build-env-dofs9qdx\overlay\Lib\site-packages\setuptools\_distutils\dist.py:265: UserWarning: Unknown distribution option: 'cffi_modules' warnings.warn(msg) running egg_info writing pyzmq.egg-info\PKG-INFO writing dependency_links to pyzmq.egg-info\dependency_links.txt writing requirements to pyzmq.egg-info\requires.txt writing top-level names to pyzmq.egg-info\top_level.txt running configure error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. ` I have installed Microsoft Visual Studio Builds Tools as indicated but still the same error. If someone has an idea I'm a taker thank you in advance for your help. A: Try pip install jupyterlab. Refer for more info: https://jupyterlab.readthedocs.io/en/stable/getting_started/installation.html I also see that you are having an error: Microsoft Visual C++ 14.0 or greater is required You can also try installing/upgrading Microsoft Visual C++ A: I still have the same error with pip install jupyterlab. I had already checked, I have the last version of Microsoft Visual Redistribuate C++
Unable to install the jupyter module with pip
I would like to be able to install the python module jupyter with pip but I get an error in my terminal when I try 'pip install jupyter' which returns this: ` error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [9 lines of output] C:\Users\nunes\AppData\Local\Temp\pip-build-env-dofs9qdx\overlay\Lib\site-packages\setuptools\_distutils\dist.py:265: UserWarning: Unknown distribution option: 'cffi_modules' warnings.warn(msg) running egg_info writing pyzmq.egg-info\PKG-INFO writing dependency_links to pyzmq.egg-info\dependency_links.txt writing requirements to pyzmq.egg-info\requires.txt writing top-level names to pyzmq.egg-info\top_level.txt running configure error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. ` I have installed Microsoft Visual Studio Builds Tools as indicated but still the same error. If someone has an idea I'm a taker thank you in advance for your help.
[ "Try pip install jupyterlab.\nRefer for more info: https://jupyterlab.readthedocs.io/en/stable/getting_started/installation.html\nI also see that you are having an error: Microsoft Visual C++ 14.0 or greater is required\nYou can also try installing/upgrading Microsoft Visual C++\n", "I still have the same error with pip install jupyterlab. I had already checked, I have the last version of Microsoft Visual Redistribuate C++\n" ]
[ 0, 0 ]
[]
[]
[ "jupyter", "pip", "python" ]
stackoverflow_0074659543_jupyter_pip_python.txt
Q: Nest.js app becomes unresponsive following an Error thrown in an async function without an await The issue that if there is an exception thrown in an async function but that function was called without an await, the Nest application goes into a state where it no longer responds to requests but the process does not exist. There may be times where we want to call a function in a request but don't need to wait for it to finish before returning to response to the caller but most of the time that we encounter this it was just an accidental omission of an await. The fact that it renders the server useless has been very problematic. I suspect there may be a simple solution to this problem but I have been unsuccessful in finding it myself. app.controller.ts import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getHello(): string { return this.appService.getHello(); } @Get('/crash') public async crash(): Promise<void> { await this.appService.crash(); } } app.service.ts import { Injectable } from '@nestjs/common'; const sleep = async (ms: number): Promise<void> => { return new Promise((resolve) => { setTimeout(resolve, ms); }); }; const functionThatThrows = async (): Promise<void> => { await sleep(2000); throw new Error('this will crash the app'); }; @Injectable() export class AppService { getHello(): string { return 'Hello World!'; } public async crash(): Promise<void> { console.log('crashing the app in 3 seconds...'); await sleep(1000); functionThatThrows(); // async function called without await } } Calling the endpoint the first time succeeds: curl http://localhost:3000/crash Calling it afterward and the server does not respond: curl http://localhost:3000/crash curl: (7) Failed to connect to localhost port 3000 after 5 ms: Connection refused A: This is due to the fact that node crashes on unhandled promise rejections. Nest's exception filter will catch errors that happen during the request, but if an error happens outside of the request (like a promise/async function without an await), then only the standard Node error handler is active. You'd need a process.on('unhandledRejection', errorHandler) to keep the process from crashing
Nest.js app becomes unresponsive following an Error thrown in an async function without an await
The issue that if there is an exception thrown in an async function but that function was called without an await, the Nest application goes into a state where it no longer responds to requests but the process does not exist. There may be times where we want to call a function in a request but don't need to wait for it to finish before returning to response to the caller but most of the time that we encounter this it was just an accidental omission of an await. The fact that it renders the server useless has been very problematic. I suspect there may be a simple solution to this problem but I have been unsuccessful in finding it myself. app.controller.ts import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getHello(): string { return this.appService.getHello(); } @Get('/crash') public async crash(): Promise<void> { await this.appService.crash(); } } app.service.ts import { Injectable } from '@nestjs/common'; const sleep = async (ms: number): Promise<void> => { return new Promise((resolve) => { setTimeout(resolve, ms); }); }; const functionThatThrows = async (): Promise<void> => { await sleep(2000); throw new Error('this will crash the app'); }; @Injectable() export class AppService { getHello(): string { return 'Hello World!'; } public async crash(): Promise<void> { console.log('crashing the app in 3 seconds...'); await sleep(1000); functionThatThrows(); // async function called without await } } Calling the endpoint the first time succeeds: curl http://localhost:3000/crash Calling it afterward and the server does not respond: curl http://localhost:3000/crash curl: (7) Failed to connect to localhost port 3000 after 5 ms: Connection refused
[ "This is due to the fact that node crashes on unhandled promise rejections. Nest's exception filter will catch errors that happen during the request, but if an error happens outside of the request (like a promise/async function without an await), then only the standard Node error handler is active. You'd need a process.on('unhandledRejection', errorHandler) to keep the process from crashing\n" ]
[ 1 ]
[]
[]
[ "nestjs" ]
stackoverflow_0074660025_nestjs.txt
Q: Why drawablePadding is not working in Button? I am trying to increase gap between the drawable icon on the left and the text on the right. I am using drawablePadding. But this does not seem to have any effect. Here is the code - <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background_gradient" tools:context=".Authentication"> <Button android:id="@+id/google_sign_in_btn" android:drawableLeft="@drawable/g_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@color/white" android:fontFamily="@font/roboto_medium" android:textColor="#8A000000" android:text="@string/sign_in_with_google_txt" android:padding="8dp" android:drawablePadding="100dp" android:textAllCaps="false" android:textSize="16sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> And here is the result - A: drawablePadding won't work on materialButtons as the materialButton class reads the drawable padding from app:iconPadding attribute instead of drawablePadding. If you look at the source code of the material button you will see this : iconPadding = attributes.getDimensionPixelSize(R.styleable.MaterialButton_iconPadding, 0); here you can see that icon's padding is read from iconPadding attribute. comparing it to TextView (Button extends textView) we have : for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { //lots of cases case com.android.internal.R.styleable.TextView_drawablePadding: drawablePadding = a.getDimensionPixelSize(attr, drawablePadding); break; } } To get an idea of how these xml attributes work, see Creating a View Class A: I had the same issue and I changed my Button to https://developer.android.com/reference/com/google/android/material/button/MaterialButton Like this you can use the app:iconPadding attribute in the Material Button instead of android:drawablePadding, to increase or decrease the padding between the drawable and the text. This worked fine for me. You can even set negative values like app:iconPadding="-5" which results in an even smaller padding between the drawable and the text. Like for instance: <com.google.android.material.button.MaterialButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableTop="@drawable/your_drawable" android:text="Your Text" app:iconPadding="10dp"/> I hope this helps!
Why drawablePadding is not working in Button?
I am trying to increase gap between the drawable icon on the left and the text on the right. I am using drawablePadding. But this does not seem to have any effect. Here is the code - <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background_gradient" tools:context=".Authentication"> <Button android:id="@+id/google_sign_in_btn" android:drawableLeft="@drawable/g_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@color/white" android:fontFamily="@font/roboto_medium" android:textColor="#8A000000" android:text="@string/sign_in_with_google_txt" android:padding="8dp" android:drawablePadding="100dp" android:textAllCaps="false" android:textSize="16sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> And here is the result -
[ "drawablePadding won't work on materialButtons as the materialButton class reads the drawable padding from app:iconPadding attribute instead of drawablePadding.\nIf you look at the source code of the material button you will see this :\niconPadding = attributes.getDimensionPixelSize(R.styleable.MaterialButton_iconPadding, 0);\nhere you can see that icon's padding is read from iconPadding attribute.\ncomparing it to TextView (Button extends textView) we have :\n for (int i = 0; i < n; i++) {\n int attr = a.getIndex(i);\n\n switch (attr) {\n \n //lots of cases\n\n case com.android.internal.R.styleable.TextView_drawablePadding:\n drawablePadding = a.getDimensionPixelSize(attr, drawablePadding);\n break;\n\n }\n }\n\nTo get an idea of how these xml attributes work, see Creating a View Class\n", "I had the same issue and I changed my Button to https://developer.android.com/reference/com/google/android/material/button/MaterialButton\nLike this you can use the app:iconPadding attribute in the Material Button instead of android:drawablePadding, to increase or decrease the padding between the drawable and the text. This worked fine for me. You can even set negative values like app:iconPadding=\"-5\" which results in an even smaller padding between the drawable and the text.\nLike for instance:\n <com.google.android.material.button.MaterialButton\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:drawableTop=\"@drawable/your_drawable\"\n android:text=\"Your Text\"\n app:iconPadding=\"10dp\"/>\n\nI hope this helps!\n" ]
[ 2, 0 ]
[]
[]
[ "android", "android_layout" ]
stackoverflow_0065895952_android_android_layout.txt
Q: Receiving OSError: [Errno 8] Exec format error in app running in Docker Container I have a React/Flask app running within a Docker container. There is no issue with me building the project using docker-compose, and running the app itself in the container. Where I am running into issues is a particular API route that is supposed to fetch user profiles from the DB, encrypt the values in a text file, and return to the frontend for download. The encryption script is written in C, though the API route is written in Python. When I try and encrypt through the app running in Docker, I am given the following error message: OSError: [Errno 8] Exec format error: './app/Crypto/encrypt.exe' I know the following command works in the CLI if invoked outside of the Docker Container (still invoked at the same directory level as it would in app): ./app/Crypto/encrypt.exe -k ./app/Crypto/secretkey -i ./profile.txt -o ./profile.encr I am using the following Python code to invoke the command in the API route which is where it fails: proc = subprocess.Popen(f"./app/Crypto/encrypt.exe -k ./app/Crypto/secretkey -i ./{profile.profile_name}.txt -o ./{profile.profile_name}.encr", shell=True) The Dockerfile for my backend is pasted below: FROM python:3 WORKDIR /app ENV FLASK_APP=main.py COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . . CMD ["python", "main.py"] I have tried to tackle the issue a few different ways: By default my Docker Container was built with Architecture of ARM64. I read that the OS Error was caused by Architecture not being AMD64, so I rebuilt the container with AMD64 and it gave me the same error. In case this was a permissions error, I ran chmod +rwx on encrypt.exe through the Dockerfile when building the container. Pretty sure it has nothing to do with permissions especially as it still failed. I added a shebang (#!/bin/bash) to the script as well as to the Dockerfile. At the end of the day I know I am failing when using subprocess.Popen, so I am positive I must be missing something when invoking the script using Python, or there is a configuration in my Docker Container that is preventing this functionality. My machine is a Macbook Pro which the script runs fine on. The script has also successfully been utilized on a machine running Linux. Any chances folks have seen similar issues arise with this error? Thanks in advance! A: So thanks to David Maze's comment on this, I followed the lead that maybe the executable I wanted to run needed to be built within the Dockerfile. I destroyed my original container, added in a step to run the Makefile that generates the executable, and finally ran the program through the app running in the Docker container. This did the trick! Not sure as to why the executable needed to be compiled within the Docker container, but running 'make' on the Makefile within the Dockerfile did the trick.
Receiving OSError: [Errno 8] Exec format error in app running in Docker Container
I have a React/Flask app running within a Docker container. There is no issue with me building the project using docker-compose, and running the app itself in the container. Where I am running into issues is a particular API route that is supposed to fetch user profiles from the DB, encrypt the values in a text file, and return to the frontend for download. The encryption script is written in C, though the API route is written in Python. When I try and encrypt through the app running in Docker, I am given the following error message: OSError: [Errno 8] Exec format error: './app/Crypto/encrypt.exe' I know the following command works in the CLI if invoked outside of the Docker Container (still invoked at the same directory level as it would in app): ./app/Crypto/encrypt.exe -k ./app/Crypto/secretkey -i ./profile.txt -o ./profile.encr I am using the following Python code to invoke the command in the API route which is where it fails: proc = subprocess.Popen(f"./app/Crypto/encrypt.exe -k ./app/Crypto/secretkey -i ./{profile.profile_name}.txt -o ./{profile.profile_name}.encr", shell=True) The Dockerfile for my backend is pasted below: FROM python:3 WORKDIR /app ENV FLASK_APP=main.py COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . . CMD ["python", "main.py"] I have tried to tackle the issue a few different ways: By default my Docker Container was built with Architecture of ARM64. I read that the OS Error was caused by Architecture not being AMD64, so I rebuilt the container with AMD64 and it gave me the same error. In case this was a permissions error, I ran chmod +rwx on encrypt.exe through the Dockerfile when building the container. Pretty sure it has nothing to do with permissions especially as it still failed. I added a shebang (#!/bin/bash) to the script as well as to the Dockerfile. At the end of the day I know I am failing when using subprocess.Popen, so I am positive I must be missing something when invoking the script using Python, or there is a configuration in my Docker Container that is preventing this functionality. My machine is a Macbook Pro which the script runs fine on. The script has also successfully been utilized on a machine running Linux. Any chances folks have seen similar issues arise with this error? Thanks in advance!
[ "So thanks to David Maze's comment on this, I followed the lead that maybe the executable I wanted to run needed to be built within the Dockerfile. I destroyed my original container, added in a step to run the Makefile that generates the executable, and finally ran the program through the app running in the Docker container. This did the trick! Not sure as to why the executable needed to be compiled within the Docker container, but running 'make' on the Makefile within the Dockerfile did the trick.\n" ]
[ 0 ]
[]
[]
[ "docker", "python" ]
stackoverflow_0074605372_docker_python.txt
Q: Reading dynamic length comma separated values using fscanf I have a txt file which contains patient details separated by commas I want to read each value store that in a structure. But, the problem is that some of the entries contain 3 values and the others contain 4. ENTRIES IN TXT FILE are: 1032,Pugsley Yanson,CELL,3048005191 1048,Banjo Codi,TBD, 1056,Lettuce Peas,WORK,7934346809 My Code looks like : `struct Phone { char description[PHONE_DESC_LEN]; char number[PHONE_LEN]; }; // Data type: Patient struct Patient { int patientNumber; char name[NAME_LEN]; struct Phone phone; }; void importPatients(const char* datafile, struct Patient patients[], int max){ FILE *fp = fopen(datafile, "r"); int i = 0; int read = 0; while (!feof(fp) && i < max){ read = fscanf(fp,"%d,%14[^,],%4[^,],%10[^,]\n",&patients[i].patientNumber,patients[i].name,patients[i].phone.description,patients[i].phone.number); if(read == 0 && !feof(fp)){ fclose(fp); return; } i++; } fclose(fp); } This code works perfectly when reading entries with 4 values but fails as soon as it encounters an entry with 3 values like: 1048,Banjo Codi,TBD, How can this be fixed or is there a better approach to solve this problem? A: At least these issues Inconsistent , Sometimes a line of data ends with a final field, sometimes not. 1032,Pugsley Yanson,CELL,3048005191 1048,Banjo Codi,TBD, Avoid line ending problems: read the line with fgets() and then parse. Why is “while( !feof(file) )” always wrong? Be sure char buffers are big enough #define NAME_LEN (14 + 1) #define PHONE_DESC_LEN ( 4 + 1) #define PHONE_LEN (10 + 1) Weak test Do not test against 1 possible undesired return value. read could be other than 0 or 4. Test against desired return value. // if(read == 0 if(read != 4 [Needs re-work, re-work done below] Alternate: char buf[100]; while (i < max && fgets(buf, sizeof buf, fp)){ int read = sscanf(buf,"%d , %14[^,], %4[^,], %10[^,]", &patients[i].patientNumber, patients[i].name, patients[i].phone.description, patients[i].phone.number); if (read != 4) { report_error(); } else { i++; } } fclose(fp); [Update] Untested sample code to better handle empty fields. Likely deserves more testing - later. // Return patient count. -1 implies error int importPatients(const char *datafile, struct Patient patients[], int max) { FILE *fp = fopen(datafile, "r"); if (fp == NULL) { return -1; } char buf[100]; int i = 0; while (i < max && fgets(buf, sizeof buf, fp)) { const char *token = strtok(buf, ','); if (token == NULL) { return -1; } patients[i].patientNumber = aoti(token); // Better code would use strtol() token = strtok(buf, ','); if (token == NULL) { return -1; } snprintf(patients[i].name, sizeof patients[i].name, "%s", token); // TBD, check return value to buffer fit. token = strtok(buf, ','); if (token == NULL) { return -1; } snprintf(patients[i].phone.description, sizeof patients[i].phone.description, "%s", token); token = strtok(buf, '\n'); if (token == NULL) { return -1; } snprintf(patients[i].phone.number, sizeof patients[i].phone.number, "%s", token); i++; } fclose(fp); return i; }
Reading dynamic length comma separated values using fscanf
I have a txt file which contains patient details separated by commas I want to read each value store that in a structure. But, the problem is that some of the entries contain 3 values and the others contain 4. ENTRIES IN TXT FILE are: 1032,Pugsley Yanson,CELL,3048005191 1048,Banjo Codi,TBD, 1056,Lettuce Peas,WORK,7934346809 My Code looks like : `struct Phone { char description[PHONE_DESC_LEN]; char number[PHONE_LEN]; }; // Data type: Patient struct Patient { int patientNumber; char name[NAME_LEN]; struct Phone phone; }; void importPatients(const char* datafile, struct Patient patients[], int max){ FILE *fp = fopen(datafile, "r"); int i = 0; int read = 0; while (!feof(fp) && i < max){ read = fscanf(fp,"%d,%14[^,],%4[^,],%10[^,]\n",&patients[i].patientNumber,patients[i].name,patients[i].phone.description,patients[i].phone.number); if(read == 0 && !feof(fp)){ fclose(fp); return; } i++; } fclose(fp); } This code works perfectly when reading entries with 4 values but fails as soon as it encounters an entry with 3 values like: 1048,Banjo Codi,TBD, How can this be fixed or is there a better approach to solve this problem?
[ "At least these issues\nInconsistent ,\nSometimes a line of data ends with a final field, sometimes not.\n1032,Pugsley Yanson,CELL,3048005191\n1048,Banjo Codi,TBD,\n\nAvoid line ending problems: read the line with fgets() and then parse.\nWhy is “while( !feof(file) )” always wrong?\nBe sure char buffers are big enough\n#define NAME_LEN (14 + 1)\n#define PHONE_DESC_LEN ( 4 + 1)\n#define PHONE_LEN (10 + 1)\n\nWeak test\nDo not test against 1 possible undesired return value. read could be other than 0 or 4. Test against desired return value.\n// if(read == 0\nif(read != 4\n\n\n[Needs re-work, re-work done below]\nAlternate:\nchar buf[100];\nwhile (i < max && fgets(buf, sizeof buf, fp)){\n int read = sscanf(buf,\"%d , %14[^,], %4[^,], %10[^,]\",\n &patients[i].patientNumber, patients[i].name, \n patients[i].phone.description, patients[i].phone.number);\n if (read != 4) {\n report_error();\n } else {\n i++;\n }\n}\nfclose(fp);\n\n[Update]\nUntested sample code to better handle empty fields. Likely deserves more testing - later.\n// Return patient count. -1 implies error\nint importPatients(const char *datafile, struct Patient patients[], int max) {\n FILE *fp = fopen(datafile, \"r\");\n if (fp == NULL) {\n return -1;\n }\n\n char buf[100];\n int i = 0;\n while (i < max && fgets(buf, sizeof buf, fp)) {\n const char *token = strtok(buf, ',');\n if (token == NULL) {\n return -1;\n }\n patients[i].patientNumber = aoti(token); // Better code would use strtol()\n\n token = strtok(buf, ',');\n if (token == NULL) {\n return -1;\n }\n snprintf(patients[i].name, sizeof patients[i].name, \"%s\", token); // TBD, check return value to buffer fit.\n\n token = strtok(buf, ',');\n if (token == NULL) {\n return -1;\n }\n snprintf(patients[i].phone.description,\n sizeof patients[i].phone.description, \"%s\", token);\n\n token = strtok(buf, '\\n');\n if (token == NULL) {\n return -1;\n }\n snprintf(patients[i].phone.number, sizeof patients[i].phone.number, \"%s\",\n token);\n\n i++;\n }\n fclose(fp);\n return i;\n}\n\n" ]
[ 3 ]
[]
[]
[ "c", "scanf", "struct" ]
stackoverflow_0074660092_c_scanf_struct.txt
Q: Swift CLGeocoder() on return I get nothing I want to use CLGeocoder() as a function so I made two one for latitude and another one for longitude. but on my return I get nothing but when I print in my latitude function I'm getting my latitude. and in the log its more strange because the print appearing in the log is not the same order in my code. Here is my code: //getLongFromAddress is exactely the same func getLatFromAddress(`let` address:String) -> Double { let geocoder = CLGeocoder() var lat = 0.00 geocoder.geocodeAddressString(address) { placemarks, error in let placemark = placemarks?.first if placemark?.location?.coordinate.latitude != nil { lat = (placemark?.location?.coordinate.latitude)! }else { //print(error as Any) } //Here i get my lat print("Lat: \(lat)") } //here my late is still 0.00 return lat } Where I call my function: func checkAddress() -> Bool { var check = true var lat1 = 0.00 var long1 = 0.00 var lat2 = 0.00 var long2 = 0.00 address1 = "Paris" address2 = "London" lat1 = getLatFromAddress(let: address1) long1 = getLongFromAddress(let: address1) lat2 = getLatFromAddress(let: address2) long2 = getLongFromAddress(let: address2) print(lat1," - ",long1) print(lat2," - ",long2) let coordinate₀ = CLLocation(latitude: lat1, longitude: long1) let coordinate₁ = CLLocation(latitude: lat2, longitude: long2) //get the distance to meter and with meterToKiloleter convert meter into kilometer let distance = meterToKilometer(let:coordinate₀.distance(from: coordinate₁)) if distance > 50 { check = false } return check } Here is the log: 0.0 - 0.0 0.0 - 0.0 2022-12-02 18:46:06.936965+0100 Storyboard[10796:272148] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 67 46 6F 01 00 00 00'} 2022-12-02 18:46:06.938224+0100 Storyboard[10796:272266] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 27 4F 6F 01 00 00 00'} 2022-12-02 18:46:06.939091+0100 Storyboard[10796:272156] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 E7 7A 6F 01 00 00 00'} 2022-12-02 18:46:06.939753+0100 Storyboard[10796:272501] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 E7 57 6F 01 00 00 00'} Lat: 48.8567879 Long: -0.0793965 Lat: 51.5033466 Long: 2.3510768 What I understand: I know why my lat is returning nothing, it's probably because it's not in geocoder.geocodeAddressString(address) { placemarks, error in So I try to return in but I get another error: Unexpected non-void return value in void function And of most code I see on CLGeocoder() like in this post :Can I get the user longitude and latitude from their address in Swift? they get their lat and long on the (geocoder..etc). What I want to know is first, is possible to use CLGeocoder() as a function and return a double value and secondly if yes how to do that because I am lost... A: I believe you will not be able to return a Double because it contains an asynchronous call to the geocodeAddressString(_:completionHandler:) method of the CLGeocoder class. Asynchronous calls do not return a value directly. Instead, they use a completion handler to return the result of the operation at a later time. To fix this, you can use a completion handler to return the Double value from the getCoordsFromAddress(withAddress:) method. Here's an example of how this can be done: func getCoordsFromAddress(withAddress address: String, completion: @escaping (Double) -> Void) { let geocoder = CLGeocoder() // Use CLGeocoder to convert the address into coordinates geocoder.geocodeAddressString(address) { (placemarks, error) in // Return early if there was an error guard error == nil else { return } // Return early if no placemarks were found guard let placemarks = placemarks, !placemarks.isEmpty else { return } // Use the first placemark to obtain the coordinates let location = placemarks.first!.location completion(location.coordinate.latitude) } } You can then call the getCoordsFromAddress(withAddress:completion:) method like this: getCoordsFromAddress(withAddress: "1 Infinite Loop, Cupertino, CA 95014") { (latitude) in // Use the latitude value here }
Swift CLGeocoder() on return I get nothing
I want to use CLGeocoder() as a function so I made two one for latitude and another one for longitude. but on my return I get nothing but when I print in my latitude function I'm getting my latitude. and in the log its more strange because the print appearing in the log is not the same order in my code. Here is my code: //getLongFromAddress is exactely the same func getLatFromAddress(`let` address:String) -> Double { let geocoder = CLGeocoder() var lat = 0.00 geocoder.geocodeAddressString(address) { placemarks, error in let placemark = placemarks?.first if placemark?.location?.coordinate.latitude != nil { lat = (placemark?.location?.coordinate.latitude)! }else { //print(error as Any) } //Here i get my lat print("Lat: \(lat)") } //here my late is still 0.00 return lat } Where I call my function: func checkAddress() -> Bool { var check = true var lat1 = 0.00 var long1 = 0.00 var lat2 = 0.00 var long2 = 0.00 address1 = "Paris" address2 = "London" lat1 = getLatFromAddress(let: address1) long1 = getLongFromAddress(let: address1) lat2 = getLatFromAddress(let: address2) long2 = getLongFromAddress(let: address2) print(lat1," - ",long1) print(lat2," - ",long2) let coordinate₀ = CLLocation(latitude: lat1, longitude: long1) let coordinate₁ = CLLocation(latitude: lat2, longitude: long2) //get the distance to meter and with meterToKiloleter convert meter into kilometer let distance = meterToKilometer(let:coordinate₀.distance(from: coordinate₁)) if distance > 50 { check = false } return check } Here is the log: 0.0 - 0.0 0.0 - 0.0 2022-12-02 18:46:06.936965+0100 Storyboard[10796:272148] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 67 46 6F 01 00 00 00'} 2022-12-02 18:46:06.938224+0100 Storyboard[10796:272266] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 27 4F 6F 01 00 00 00'} 2022-12-02 18:46:06.939091+0100 Storyboard[10796:272156] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 E7 7A 6F 01 00 00 00'} 2022-12-02 18:46:06.939753+0100 Storyboard[10796:272501] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 E7 57 6F 01 00 00 00'} Lat: 48.8567879 Long: -0.0793965 Lat: 51.5033466 Long: 2.3510768 What I understand: I know why my lat is returning nothing, it's probably because it's not in geocoder.geocodeAddressString(address) { placemarks, error in So I try to return in but I get another error: Unexpected non-void return value in void function And of most code I see on CLGeocoder() like in this post :Can I get the user longitude and latitude from their address in Swift? they get their lat and long on the (geocoder..etc). What I want to know is first, is possible to use CLGeocoder() as a function and return a double value and secondly if yes how to do that because I am lost...
[ "I believe you will not be able to return a Double because it contains an asynchronous call to the geocodeAddressString(_:completionHandler:) method of the CLGeocoder class. Asynchronous calls do not return a value directly. Instead, they use a completion handler to return the result of the operation at a later time.\nTo fix this, you can use a completion handler to return the Double value from the getCoordsFromAddress(withAddress:) method. Here's an example of how this can be done:\nfunc getCoordsFromAddress(withAddress address: String, completion: @escaping (Double) -> Void) {\n let geocoder = CLGeocoder()\n\n // Use CLGeocoder to convert the address into coordinates\n geocoder.geocodeAddressString(address) { (placemarks, error) in\n // Return early if there was an error\n guard error == nil else {\n return\n }\n\n // Return early if no placemarks were found\n guard let placemarks = placemarks, !placemarks.isEmpty else {\n return\n }\n\n // Use the first placemark to obtain the coordinates\n let location = placemarks.first!.location\n completion(location.coordinate.latitude)\n }\n}\n\nYou can then call the getCoordsFromAddress(withAddress:completion:) method like this:\ngetCoordsFromAddress(withAddress: \"1 Infinite Loop, Cupertino, CA 95014\") { (latitude) in\n // Use the latitude value here\n}\n\n" ]
[ 0 ]
[]
[]
[ "swift" ]
stackoverflow_0074659766_swift.txt
Q: How we handle input validation on python I am new to python. I am wondering how we handle input validation using try catch. I have the code below, would you provide some suggestion? try: validate_input(date, value, region) raise IllegalArgumentError("Invalid input") except IllegalArgumentError as error: print("Invalid input occur:", error) class IllegalArgumentError(ValueError): pass def validate_input(date, value, region): if ((date is not None and date != "") and (value is not None and value != "") and (region is not None and region != "")): return True else: raise IllegalArgumentError("Invalid lambda event parameters") A: Suggestions First of all, you cannot call a function before it being actually created. Also, except is used to provide a set of code if the execution flow of code is interrupted with an error, so the raising of another error inside the except is illogical You need to use a base exception to create a custom exception Will provide two ways on how I would have done this class IllegalArgumentError(Exception): def __init__(self, err): self.err = err super().__init__(self.err) def validate_input(date, value, region): if ((date is not None and date != "") and (value is not None and value != "") and (region is not None and region != "")): return True else: raise IllegalArgumentError("Invalid lambda event parameters") date = input() value = input() region = input() validate_input(date,value,region) import sys def validate_input(date, value, region): if ((date is not None and date != "") and (value is not None and value != "") and (region is not None and region != "")): return True else: raise ValueError try: date = input() value = input() region = input() validate_input(date, value, region) except ValueError: sys.exit("Invalid lambda event parameters") Hope this helps!
How we handle input validation on python
I am new to python. I am wondering how we handle input validation using try catch. I have the code below, would you provide some suggestion? try: validate_input(date, value, region) raise IllegalArgumentError("Invalid input") except IllegalArgumentError as error: print("Invalid input occur:", error) class IllegalArgumentError(ValueError): pass def validate_input(date, value, region): if ((date is not None and date != "") and (value is not None and value != "") and (region is not None and region != "")): return True else: raise IllegalArgumentError("Invalid lambda event parameters")
[ "Suggestions\n\nFirst of all, you cannot call a function before it being actually created.\nAlso, except is used to provide a set of code if the execution flow of code is interrupted with an error, so the raising of another error inside the except is illogical\nYou need to use a base exception to create a custom exception\n\nWill provide two ways on how I would have done this\n\n\n\nclass IllegalArgumentError(Exception):\n def __init__(self, err):\n self.err = err\n super().__init__(self.err)\n \ndef validate_input(date, value, region):\n if ((date is not None and date != \"\") and (value is not None and value != \"\") and\n (region is not None and region != \"\")):\n return True\n else:\n raise IllegalArgumentError(\"Invalid lambda event parameters\")\ndate = input()\nvalue = input()\nregion = input()\nvalidate_input(date,value,region)\n\n\n\n\nimport sys\ndef validate_input(date, value, region):\n if ((date is not None and date != \"\") and (value is not None and value != \"\") and\n (region is not None and region != \"\")):\n return True\n else:\n raise ValueError\n \ntry:\n date = input()\n value = input()\n region = input()\n validate_input(date, value, region)\nexcept ValueError:\n sys.exit(\"Invalid lambda event parameters\")\n\nHope this helps!\n" ]
[ 0 ]
[]
[]
[ "python", "try_catch", "validation" ]
stackoverflow_0074659981_python_try_catch_validation.txt
Q: video_thumbnail package does not generate different thumbnails for different time frames I have a video file and want to generate 10 different thumbnails for the whole video. I use video_thumbnail package and VideoThumbnail.fromFile() constructor. This constructor has an argument called timeMs and is for, as the documentation states: generates the thumbnail from the frame around the specified millisecond. My code is as follows: List<String> recordingThumbnailsPaths = List<String>.generate(10, (int index) => ''); Future<void> getRecordingThumbnailsPaths() async { final int totalMilliSecs = (await FlutterVideoInfo().getVideoInfo(videoFile!.path))! .duration! .toInt(); // For debug purpose print('Total (ms): $totalMilliSecs'); for (int i = 0; i < 10; i++) { int ms = totalMilliSecs ~/ 10 * i; recordingThumbnailsPaths[i] = (await VideoThumbnail.thumbnailFile( video: videoFile!.path, timeMs: ms))!; // For debug purpose print('Iteration $i\nCurrent (ms): $ms'); } } And here is the log output for each iteration: Total (ms): 17480 Iteration 0 Current (ms): 0 Iteration 1 Current (ms): 1748 Iteration 2 Current (ms): 3496 Iteration 3 Current (ms): 5244 ... Iteration 9 Current (ms): 15732 But it generates the same first thumbnail for each time frame. So what is the solution? Thanks in advance for your help! A: I made some edits to the code, and it works fine: import 'dart:io'; import 'package:flutter/material.dart'; import 'package:path/path.dart'; import 'package:video_thumbnail/video_thumbnail.dart'; class TestPage extends StatefulWidget { const TestPage({ super.key, }); @override State<TestPage> createState() => _TestPageState(); } class _TestPageState extends State<TestPage> { List<String> recordingThumbnailsPaths = []; Future<void> getRecordingThumbnailsPaths() async { final videoFile = /* Your Video File*/; final int totalMilliSecs = 15000; for (int i = 0; i < 10; i++) { int ms = totalMilliSecs ~/ 100 * i; final current = (await VideoThumbnail.thumbnailFile( video: videoFile!.path!, timeMs: ms, thumbnailPath: dirname(videoFile!.path!) + "/$i.png", ))!; recordingThumbnailsPaths.add(current); } setState(() {}); print(recordingThumbnailsPaths); } @override Widget build(BuildContext context) { return GestureDetector( onTap: () {}, child: Scaffold( resizeToAvoidBottomInset: true, body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: () async { await getRecordingThumbnailsPaths(); }, child: Text("click"), ), Wrap( children: [ ...List.generate( recordingThumbnailsPaths.length, (index) => Image.file( File( recordingThumbnailsPaths[index], ), width: 100, ), ), ], ) ], ), ), ), ); } } I tried before, with you sample of code, and had the same issue, then I found that the video is the one having the same screenshots on those `int ms = totalMilliSecs ~/ 10 * I; duration values. so first make sure the video have different frames on those duration, or just make the ms differences bigger.
video_thumbnail package does not generate different thumbnails for different time frames
I have a video file and want to generate 10 different thumbnails for the whole video. I use video_thumbnail package and VideoThumbnail.fromFile() constructor. This constructor has an argument called timeMs and is for, as the documentation states: generates the thumbnail from the frame around the specified millisecond. My code is as follows: List<String> recordingThumbnailsPaths = List<String>.generate(10, (int index) => ''); Future<void> getRecordingThumbnailsPaths() async { final int totalMilliSecs = (await FlutterVideoInfo().getVideoInfo(videoFile!.path))! .duration! .toInt(); // For debug purpose print('Total (ms): $totalMilliSecs'); for (int i = 0; i < 10; i++) { int ms = totalMilliSecs ~/ 10 * i; recordingThumbnailsPaths[i] = (await VideoThumbnail.thumbnailFile( video: videoFile!.path, timeMs: ms))!; // For debug purpose print('Iteration $i\nCurrent (ms): $ms'); } } And here is the log output for each iteration: Total (ms): 17480 Iteration 0 Current (ms): 0 Iteration 1 Current (ms): 1748 Iteration 2 Current (ms): 3496 Iteration 3 Current (ms): 5244 ... Iteration 9 Current (ms): 15732 But it generates the same first thumbnail for each time frame. So what is the solution? Thanks in advance for your help!
[ "I made some edits to the code, and it works fine:\n\nimport 'dart:io';\nimport 'package:flutter/material.dart';\nimport 'package:path/path.dart';\nimport 'package:video_thumbnail/video_thumbnail.dart';\n\nclass TestPage extends StatefulWidget {\n const TestPage({\n super.key,\n });\n\n @override\n State<TestPage> createState() => _TestPageState();\n}\n\nclass _TestPageState extends State<TestPage> {\n List<String> recordingThumbnailsPaths = [];\n\n Future<void> getRecordingThumbnailsPaths() async {\n final videoFile = /* Your Video File*/;\n\n final int totalMilliSecs = 15000;\n for (int i = 0; i < 10; i++) {\n int ms = totalMilliSecs ~/ 100 * i;\n final current = (await VideoThumbnail.thumbnailFile(\n video: videoFile!.path!,\n timeMs: ms,\n thumbnailPath: dirname(videoFile!.path!) + \"/$i.png\",\n ))!;\n recordingThumbnailsPaths.add(current);\n }\n setState(() {});\n print(recordingThumbnailsPaths);\n }\n\n @override\n Widget build(BuildContext context) {\n return GestureDetector(\n onTap: () {},\n child: Scaffold(\n resizeToAvoidBottomInset: true,\n body: Center(\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n ElevatedButton(\n onPressed: () async {\n await getRecordingThumbnailsPaths();\n },\n child: Text(\"click\"),\n ),\n Wrap(\n children: [\n ...List.generate(\n recordingThumbnailsPaths.length,\n (index) => Image.file(\n File(\n recordingThumbnailsPaths[index],\n ),\n width: 100,\n ),\n ),\n ],\n )\n ],\n ),\n ),\n ),\n );\n }\n}\n\nI tried before, with you sample of code, and had the same issue, then I found that the video is the one having the same screenshots on those `int ms = totalMilliSecs ~/ 10 * I; duration values.\nso first make sure the video have different frames on those duration, or just make the ms differences bigger.\n" ]
[ 0 ]
[]
[]
[ "flutter", "flutter_packages", "flutter_video_player" ]
stackoverflow_0074646886_flutter_flutter_packages_flutter_video_player.txt
Q: Push a LazyColumn item to end of screen if the LazyColumn is empty I want to add a footer to LazyColumn that only appears when all the items are scrolled, but if there are no items in the LazyColumn or no enough items to cover the whole screen, I want the footer to show at the bottom of the screen. Since we cannot set weights in LazyColumn is there any other way to achieve this? A: You can use the LazyListState#layoutInfo to know if the list is empty or if there is available space at the bottom. val state = rememberLazyListState() val isIniatialLoading by remember { derivedStateOf { state.layoutInfo.viewportSize == IntSize.Zero } } //Empty list or empty space val hasEmptySpace by remember { derivedStateOf { val layoutInfo = state.layoutInfo val visibleItemsInfo = layoutInfo.visibleItemsInfo if (layoutInfo.totalItemsCount == 0) { true } else { val lastVisibleItem = visibleItemsInfo.last() val viewportHeight = layoutInfo.viewportEndOffset + layoutInfo.viewportStartOffset (lastVisibleItem.index + 1 == layoutInfo.totalItemsCount && lastVisibleItem.offset + lastVisibleItem.size < viewportHeight) } } } Then wrap the LazyColumn with a Column and apply the weight modifier to the list. Column(Modifier.fillMaxSize()) { LazyColumn( state = state, modifier = Modifier.weight(1f) ){ items(itemsList) { //.... } //Footer when the list covers the entire screen if (!hasEmptySpace){ item(){ //Footer() } } } // Display the Footer at the bottom of the screen if the list is empty or if there is an empty space if ( !isIniatialLoading && hasEmptySpace ){ //Footer() } }
Push a LazyColumn item to end of screen if the LazyColumn is empty
I want to add a footer to LazyColumn that only appears when all the items are scrolled, but if there are no items in the LazyColumn or no enough items to cover the whole screen, I want the footer to show at the bottom of the screen. Since we cannot set weights in LazyColumn is there any other way to achieve this?
[ "You can use the LazyListState#layoutInfo to know if the list is empty or if there is available space at the bottom.\nval state = rememberLazyListState()\n\nval isIniatialLoading by remember {\n derivedStateOf {\n state.layoutInfo.viewportSize == IntSize.Zero\n }\n}\n\n//Empty list or empty space\nval hasEmptySpace by remember {\n derivedStateOf {\n val layoutInfo = state.layoutInfo\n val visibleItemsInfo = layoutInfo.visibleItemsInfo\n if (layoutInfo.totalItemsCount == 0) {\n true\n } else {\n val lastVisibleItem = visibleItemsInfo.last()\n val viewportHeight = layoutInfo.viewportEndOffset + layoutInfo.viewportStartOffset\n \n (lastVisibleItem.index + 1 == layoutInfo.totalItemsCount &&\n lastVisibleItem.offset + lastVisibleItem.size < viewportHeight)\n }\n }\n}\n\nThen wrap the LazyColumn with a Column and apply the weight modifier to the list.\nColumn(Modifier.fillMaxSize()) {\n\n LazyColumn(\n state = state,\n modifier = Modifier.weight(1f)\n ){\n items(itemsList) {\n //....\n }\n\n //Footer when the list covers the entire screen\n if (!hasEmptySpace){\n item(){\n //Footer()\n }\n }\n }\n \n // Display the Footer at the bottom of the screen if the list is empty or if there is an empty space\n if ( !isIniatialLoading && hasEmptySpace ){\n //Footer()\n }\n\n}\n\n\n" ]
[ 1 ]
[]
[]
[ "android", "android_jetpack_compose", "android_jetpack_compose_lazy_column", "android_jetpack_compose_list" ]
stackoverflow_0074632034_android_android_jetpack_compose_android_jetpack_compose_lazy_column_android_jetpack_compose_list.txt
Q: Popup fails depending on what I BIND Here is the relevant portion of my Animal Picker in KIVY file shown below: AniPic@ANIMALPICKER id: aroot labelText: '' imageSource: '' animalCode: 'AB' animalName: 'GOGGA' BoxLayout: orientation: 'horizontal' width: root.width pos: 0,0 canvas.before: RoundedRectangle: pos: 5, 5 # the next two lines determine the position of the rectangle for the image size: root.width-10, root.height-10 source: root.imageSource radius:[10] PinButton: id: _pin on_release: root.pin_action(root.labelText) Label: id: _label text: root.labelText width: root.width color: (1, 1, 1, 1) MapButton: id: _map on_release: root.map_show(root.labelText) #========================================================================== AnimalWindow: : id: animalid name: 'animal' canvas.before: Color: rgba: 1, 1, 1, 1 Rectangle: pos: self.pos size: self.size BoxLayout: orientation: 'vertical' Label: id: choice text: "Sightings" color: 0, 0, 0, 1 size_hint_y: 0.05 canvas.before: Color: rgba: 0.5, 1, 0.5, 1 Rectangle: pos: self.pos size: self.size ScrollView: do_scroll_x: False do_scroll_y: True GridLayout: size: (root.width, root.height) cols: 1 rows: 9 padding: 10 spacing: 10 size_hint_x: None size_hint_y: 9 height: self.minimum_height row_default_height: 120 row_force_default: True AniPic: labelText: 'LION' imageSource: 'images/lion_pic.jpg' animalCode: 'LI' AniPic: labelText: 'CHEETAH' imageSource: 'images/cheetah_pic.png' animalCode: 'CH' Now when I click on a 'PinButton' of a particular animal (CHEETA) I get the app executing def pin_it(_animal): print('aaaa', _animal ) and shows. 'aaaa CHEETAH' BUT the POPUP code below, where I want 'confirmation' for pin action, does not show the popup but crashes: class ANIMALPICKER(RelativeLayout): def pin_action(self, _animal): # Prepare to confirm that you want to Pin the sighting title_text = _animal + ' ' + 'SIGHTING' content_text = 'Confirm Sighting?' content_box = BoxLayout(orientation='vertical') btn_box = BoxLayout(orientation='horizontal') btn_box.height = 24 content_label = Label() content_label.text = content_text yes_btn = Button(text='Yes') yes_btn.background_color = 0, 1, 0, 1 no_btn = Button(text='No') no_btn.background_color = 1, 0, 0, 1 btn_box.add_widget(yes_btn) btn_box.add_widget(no_btn) content_box.add_widget(content_label) content_box.add_widget(btn_box) # Now confirm that you want to Pin the sighting popup = Popup(title=title_text, separator_height=4, title_size='20sp', content=content_box, size_hint=(None, None), size=(200, 240), auto_dismiss=False) # dismiss popup and proceed to pin the sighting, on release of yes button yes_btn.bind(on_press=pin_it(_animal)) # dismiss popup on release of the NO button yes_btn.bind(on_release=popup.dismiss) popup.open() with the following message: File "/home/sib/PycharmProjects/SpotMap/animalWindow.py", line 66, in pin_action yes_btn.bind(on_press=pin_it(_animal)) File "kivy/_event.pyx", line 444, in kivy._event.EventDispatcher.bind AssertionError: None is not callable However when I bind a simple 'yes_btn.bind(on_press=dismiss)' instead of 'yes_btn.bind(on_press=pin_it(_animal))' the popup does display and the the popup dismisses when the button to which it is attached is pressed. Please at 82 years of age and a limited knowledge of Python, Kivy and OO I desperately need help in completing this app. A work around will also satisfy me Many Thanks A: I think the problem is that pin_it(_animal) completes the function instead of referencing the function object. from functools import partial myfun = partial(pin_it, animal=_animal) # this should be a function, not function() yes_btn.bind(on_press=myfun)
Popup fails depending on what I BIND
Here is the relevant portion of my Animal Picker in KIVY file shown below: AniPic@ANIMALPICKER id: aroot labelText: '' imageSource: '' animalCode: 'AB' animalName: 'GOGGA' BoxLayout: orientation: 'horizontal' width: root.width pos: 0,0 canvas.before: RoundedRectangle: pos: 5, 5 # the next two lines determine the position of the rectangle for the image size: root.width-10, root.height-10 source: root.imageSource radius:[10] PinButton: id: _pin on_release: root.pin_action(root.labelText) Label: id: _label text: root.labelText width: root.width color: (1, 1, 1, 1) MapButton: id: _map on_release: root.map_show(root.labelText) #========================================================================== AnimalWindow: : id: animalid name: 'animal' canvas.before: Color: rgba: 1, 1, 1, 1 Rectangle: pos: self.pos size: self.size BoxLayout: orientation: 'vertical' Label: id: choice text: "Sightings" color: 0, 0, 0, 1 size_hint_y: 0.05 canvas.before: Color: rgba: 0.5, 1, 0.5, 1 Rectangle: pos: self.pos size: self.size ScrollView: do_scroll_x: False do_scroll_y: True GridLayout: size: (root.width, root.height) cols: 1 rows: 9 padding: 10 spacing: 10 size_hint_x: None size_hint_y: 9 height: self.minimum_height row_default_height: 120 row_force_default: True AniPic: labelText: 'LION' imageSource: 'images/lion_pic.jpg' animalCode: 'LI' AniPic: labelText: 'CHEETAH' imageSource: 'images/cheetah_pic.png' animalCode: 'CH' Now when I click on a 'PinButton' of a particular animal (CHEETA) I get the app executing def pin_it(_animal): print('aaaa', _animal ) and shows. 'aaaa CHEETAH' BUT the POPUP code below, where I want 'confirmation' for pin action, does not show the popup but crashes: class ANIMALPICKER(RelativeLayout): def pin_action(self, _animal): # Prepare to confirm that you want to Pin the sighting title_text = _animal + ' ' + 'SIGHTING' content_text = 'Confirm Sighting?' content_box = BoxLayout(orientation='vertical') btn_box = BoxLayout(orientation='horizontal') btn_box.height = 24 content_label = Label() content_label.text = content_text yes_btn = Button(text='Yes') yes_btn.background_color = 0, 1, 0, 1 no_btn = Button(text='No') no_btn.background_color = 1, 0, 0, 1 btn_box.add_widget(yes_btn) btn_box.add_widget(no_btn) content_box.add_widget(content_label) content_box.add_widget(btn_box) # Now confirm that you want to Pin the sighting popup = Popup(title=title_text, separator_height=4, title_size='20sp', content=content_box, size_hint=(None, None), size=(200, 240), auto_dismiss=False) # dismiss popup and proceed to pin the sighting, on release of yes button yes_btn.bind(on_press=pin_it(_animal)) # dismiss popup on release of the NO button yes_btn.bind(on_release=popup.dismiss) popup.open() with the following message: File "/home/sib/PycharmProjects/SpotMap/animalWindow.py", line 66, in pin_action yes_btn.bind(on_press=pin_it(_animal)) File "kivy/_event.pyx", line 444, in kivy._event.EventDispatcher.bind AssertionError: None is not callable However when I bind a simple 'yes_btn.bind(on_press=dismiss)' instead of 'yes_btn.bind(on_press=pin_it(_animal))' the popup does display and the the popup dismisses when the button to which it is attached is pressed. Please at 82 years of age and a limited knowledge of Python, Kivy and OO I desperately need help in completing this app. A work around will also satisfy me Many Thanks
[ "I think the problem is that pin_it(_animal) completes the function instead of referencing the function object.\nfrom functools import partial\nmyfun = partial(pin_it, animal=_animal)\n# this should be a function, not function()\nyes_btn.bind(on_press=myfun)\n\n" ]
[ 0 ]
[]
[]
[ "kivy", "popup" ]
stackoverflow_0074655074_kivy_popup.txt
Q: Adding new chart types to react pivottable I'm wondering if it's possible to add new type of charts, like a radar chart, to the React library plotly/react-pivottable https://github.com/plotly/react-pivottable. I would like to add a spider chart, always from the chart library plotly, but I can't understand where to start as the documentation is a litle poor and the GitHub repo is quite silence... Maybe it's not even possible. Does anyone know if it's possible? A: Yes, it is possible to add new types of charts to the React Pivottable library, including a radar chart. The React Pivottable library is built on top of the Pivottable library, which is a powerful data-aggregation tool that can generate a variety of different charts and visualizations. It uses the Plotly library to render the charts, so you can use any of the chart types supported by Plotly in React Pivottable, including the radar chart. To add a new chart type, such as a radar chart, to React Pivottable, you can use the addRenderer method of the pivottable object. This method takes two arguments: the name of the new chart type, and a function that generates the chart using the Plotly library. Here's an example of how you could use the addRenderer method to add a radar chart to React Pivottable: import { pivottable } from 'react-pivottable'; import Plotly from 'plotly.js-basic-dist'; // Define a function that generates a radar chart using the // data and configuration provided by the Pivottable library const radarChartRenderer = (pivotData, opts) => { // Use the Plotly library to generate the chart const chartData = [{ type: 'scatterpolar', r: pivotData.map(d => d.value), theta: pivotData A: Yes, it's completely possible to add custom charts. You need to copy makeRenderer function from original repo and customised it according to the chart types. To add a new chart type (radar chart), to React Pivottable, you've to add directly on PlotlyRenderers. Here's an example of how you could add a radar chart to React Pivottable: const Plot = createPlotlyComponent(window.Plotly); const PlotlyRenderers = createPlotlyRenderers(Plot); const makeRenderer = ( PlotlyComponent, traceOptions = {}, layoutOptions = {}, transpose = false ) { class Renderer extends React.PureComponent { render() { const pivotData = new PivotData(this.props); const rowKeys = pivotData.getRowKeys(); const colKeys = pivotData.getColKeys(); const traceKeys = transpose ? colKeys : rowKeys; if (traceKeys.length === 0) { traceKeys.push([]); } const datumKeys = transpose ? rowKeys : colKeys; if (datumKeys.length === 0) { datumKeys.push([]); } let fullAggName = this.props.aggregatorName; const numInputs = this.props.aggregators[fullAggName]([])().numInputs || 0; if (numInputs !== 0) { fullAggName += ` of ${this.props.vals.slice(0, numInputs).join(", ")}`; } const data = traceKeys.map((traceKey) => { const r = []; const theta = []; for (const datumKey of datumKeys) { const val = parseFloat( pivotData .getAggregator( transpose ? datumKey : traceKey, transpose ? traceKey : datumKey ) .value() ); r.push(isFinite(val) ? val : null); theta.push(datumKey.join("-") || " "); } const trace = { name: traceKey.join("-") || fullAggName }; trace.fill = "toself"; trace.r = r; trace.theta = theta.length > 1 ? theta : [fullAggName]; return Object.assign(trace, traceOptions); }); const layout = { polar: { radialaxis: { visible: true, range: [0, 50] } }, /* eslint-disable no-magic-numbers */ // width: window.innerWidth / 1.5, // height: window.innerHeight / 1.4 - 50 // /* eslint-enable no-magic-numbers */ }; return ( <PlotlyComponent data={data} layout={Object.assign( layout, layoutOptions, this.props.plotlyOptions )} config={this.props.plotlyConfig} onUpdate={this.props.onRendererUpdate} /> ); } } return Renderer; } const radarChart = () => { return makeRenderer( Plot, { type: "scatterpolar" }, {}, true ); } PlotlyRenderers["Radar Chart"] = radarChart({}); const data = [ { country: "Spain", name: "Santiago", surname: "Ramón y Cajal", sex: "Male", age: 57, subject: "Medicine" }, { country: "United Kingdom", name: "Ada", surname: "Lovelace", sex: "Female", age: 47, subject: "Computing" }, { country: "United Kingdom", name: "Alan", surname: "Turing", sex: "Male", age: 55, subject: "Computing" }, { country: "France", name: "Antoine", surname: "Lavoisier", sex: "Male", age: 12, subject: "Chemistry" }, { country: "Poland", name: "Marie", surname: "Curie", sex: "Female", age: 33, subject: "Chemistry" }, { country: "Austria", name: "Hedy", surname: "Lamarr", sex: "Female", age: 34, subject: "Computing" }, { country: "Austria", name: "Erwin", surname: "Schrödinger", sex: "Male", age: 38, subject: "Physics" } ]; export default function App() { const [opts, setOpts] = useState({}); return ( <div className="App"> <PivotTableUI data={data} onChange={(e) => { setOpts(e); console.log(e); }} renderers={Object.assign({}, TableRenderers, PlotlyRenderers)} cols={["sex"]} rows={["subject", "country"]} rendererName="Table Heatmap" aggregatorName="Average" vals={["age"]} derivedAttributes={{ completeName: (el) => el.name + " " + el.surname }} {...opts} /> </div> ); } Here is the complete code: https://codesandbox.io/s/react-pivot-table-custom-charts-2utqbt?file=/src/App.js:3511-4468
Adding new chart types to react pivottable
I'm wondering if it's possible to add new type of charts, like a radar chart, to the React library plotly/react-pivottable https://github.com/plotly/react-pivottable. I would like to add a spider chart, always from the chart library plotly, but I can't understand where to start as the documentation is a litle poor and the GitHub repo is quite silence... Maybe it's not even possible. Does anyone know if it's possible?
[ "Yes, it is possible to add new types of charts to the React Pivottable library, including a radar chart. The React Pivottable library is built on top of the Pivottable library, which is a powerful data-aggregation tool that can generate a variety of different charts and visualizations. It uses the Plotly library to render the charts, so you can use any of the chart types supported by Plotly in React Pivottable, including the radar chart.\nTo add a new chart type, such as a radar chart, to React Pivottable, you can use the addRenderer method of the pivottable object. This method takes two arguments: the name of the new chart type, and a function that generates the chart using the Plotly library.\nHere's an example of how you could use the addRenderer method to add a radar chart to React Pivottable:\nimport { pivottable } from 'react-pivottable';\nimport Plotly from 'plotly.js-basic-dist';\n\n// Define a function that generates a radar chart using the\n// data and configuration provided by the Pivottable library\nconst radarChartRenderer = (pivotData, opts) => {\n // Use the Plotly library to generate the chart\n const chartData = [{\n type: 'scatterpolar',\n r: pivotData.map(d => d.value),\n theta: pivotData\n\n", "Yes, it's completely possible to add custom charts. You need to copy makeRenderer function from original repo and customised it according to the chart types.\nTo add a new chart type (radar chart), to React Pivottable, you've to add directly on PlotlyRenderers.\nHere's an example of how you could add a radar chart to React Pivottable:\nconst Plot = createPlotlyComponent(window.Plotly);\nconst PlotlyRenderers = createPlotlyRenderers(Plot);\n\nconst makeRenderer = (\n PlotlyComponent,\n traceOptions = {},\n layoutOptions = {},\n transpose = false\n) {\n class Renderer extends React.PureComponent {\n render() {\n const pivotData = new PivotData(this.props);\n const rowKeys = pivotData.getRowKeys();\n const colKeys = pivotData.getColKeys();\n const traceKeys = transpose ? colKeys : rowKeys;\n if (traceKeys.length === 0) {\n traceKeys.push([]);\n }\n const datumKeys = transpose ? rowKeys : colKeys;\n if (datumKeys.length === 0) {\n datumKeys.push([]);\n }\n\n let fullAggName = this.props.aggregatorName;\n const numInputs =\n this.props.aggregators[fullAggName]([])().numInputs || 0;\n if (numInputs !== 0) {\n fullAggName += ` of ${this.props.vals.slice(0, numInputs).join(\", \")}`;\n }\n\n const data = traceKeys.map((traceKey) => {\n const r = [];\n const theta = [];\n for (const datumKey of datumKeys) {\n const val = parseFloat(\n pivotData\n .getAggregator(\n transpose ? datumKey : traceKey,\n transpose ? traceKey : datumKey\n )\n .value()\n );\n r.push(isFinite(val) ? val : null);\n theta.push(datumKey.join(\"-\") || \" \");\n }\n const trace = { name: traceKey.join(\"-\") || fullAggName };\n\n trace.fill = \"toself\";\n trace.r = r;\n trace.theta = theta.length > 1 ? theta : [fullAggName];\n\n return Object.assign(trace, traceOptions);\n });\n\n const layout = {\n polar: {\n radialaxis: {\n visible: true,\n range: [0, 50]\n }\n },\n /* eslint-disable no-magic-numbers */\n // width: window.innerWidth / 1.5,\n // height: window.innerHeight / 1.4 - 50\n // /* eslint-enable no-magic-numbers */\n };\n\n return (\n <PlotlyComponent\n data={data}\n layout={Object.assign(\n layout,\n layoutOptions,\n this.props.plotlyOptions\n )}\n config={this.props.plotlyConfig}\n onUpdate={this.props.onRendererUpdate}\n />\n );\n }\n }\n\n return Renderer;\n}\n\nconst radarChart = () => {\n return makeRenderer(\n Plot,\n { type: \"scatterpolar\" },\n {},\n true\n );\n}\n\nPlotlyRenderers[\"Radar Chart\"] = radarChart({});\n\nconst data = [\n {\n country: \"Spain\",\n name: \"Santiago\",\n surname: \"Ramón y Cajal\",\n sex: \"Male\",\n age: 57,\n subject: \"Medicine\"\n },\n {\n country: \"United Kingdom\",\n name: \"Ada\",\n surname: \"Lovelace\",\n sex: \"Female\",\n age: 47,\n subject: \"Computing\"\n },\n {\n country: \"United Kingdom\",\n name: \"Alan\",\n surname: \"Turing\",\n sex: \"Male\",\n age: 55,\n subject: \"Computing\"\n },\n {\n country: \"France\",\n name: \"Antoine\",\n surname: \"Lavoisier\",\n sex: \"Male\",\n age: 12,\n subject: \"Chemistry\"\n },\n {\n country: \"Poland\",\n name: \"Marie\",\n surname: \"Curie\",\n sex: \"Female\",\n age: 33,\n subject: \"Chemistry\"\n },\n {\n country: \"Austria\",\n name: \"Hedy\",\n surname: \"Lamarr\",\n sex: \"Female\",\n age: 34,\n subject: \"Computing\"\n },\n {\n country: \"Austria\",\n name: \"Erwin\",\n surname: \"Schrödinger\",\n sex: \"Male\",\n age: 38,\n subject: \"Physics\"\n }\n];\n\n\nexport default function App() {\n const [opts, setOpts] = useState({});\n\n return (\n <div className=\"App\">\n <PivotTableUI\n data={data}\n onChange={(e) => {\n setOpts(e);\n console.log(e);\n }}\n renderers={Object.assign({}, TableRenderers, PlotlyRenderers)}\n cols={[\"sex\"]}\n rows={[\"subject\", \"country\"]}\n rendererName=\"Table Heatmap\"\n aggregatorName=\"Average\"\n vals={[\"age\"]}\n derivedAttributes={{ completeName: (el) => el.name + \" \" + el.surname }}\n {...opts}\n />\n </div>\n );\n}\n\nHere is the complete code:\nhttps://codesandbox.io/s/react-pivot-table-custom-charts-2utqbt?file=/src/App.js:3511-4468\n" ]
[ 1, 1 ]
[]
[]
[ "pivot_table", "plotly", "reactjs" ]
stackoverflow_0074647573_pivot_table_plotly_reactjs.txt
Q: Can this be done in Handbrake or FFMPEG Just wonder this could be done in Handbrake or FFMPEG. Any other transcoding software in Windows or MacOS would also be acceptable. I have many family videos, shooted with DSLR/action cam/phone. And the files are really huge without transcoding them. There are something I would like to have, Metadata should be all captured. Using Handbrake would not be able to capture the information of the used device. Also, the capture date will become the transcoding date which is definitely unacceptable. I would like to transcode them into HEVC (H.265) I need to batch transcode them since there're a lot of videos. If it's possible (not neccessary), I would also like to have the filename as "YYYYMMDD_HHMMSS". I think both 1 and 3 are quite frequently asked questions. This thread will be quite useful to all people who are looking for the same answer as well. Thanks a lot! A: I'd say no. Traditionally metadata handling in video is done fairly poorly - unlike still images. I have a similar issue and probably end up rolling my own. I assume you'd like to go to MP4 or MOV which has a number of different metadata styles: MP4, QuickTime, iTunes style, 3gpp, embedded ID3 (similar to MP3) etc. Since writing support of video metadata is done poorly - so is reading of video metadata. You could write more than one style into the file - hoping the tools that don't understand it will ignore the unknown metadata. As of now I would transcode to MOV/H.265 and use Apple style metadata so that it works correctly on my iPhone/iPad/AppleTV and Mac. Unfortunately - sometimes the answer is there is no answer but I'd love to be proven wrong. A: tl;dr - watch the video explainer: https://youtu.be/ZiGeVvNGn9c I came up with two different ways to batch transcode a folder full of video files using ffmpeg. As far as I know, ffmpeg will copy over all metadata without modification. Pure Python Way https://github.com/nuket/Shrinkr#shrinkr-batch-transcode-python-edition SCons Way https://github.com/nuket/Shrinkr#shrinkr-batch-transcode-scons-edition One uses pure Python, the other uses SCons build scripts. Transcoding video can be conceptually similar to compiling software, so, I gave this a shot. Both ways will let you run the batch repeatedly and will not repeat work, already-transcoded files won't be done again unless the source files change. Of the two ways, I prefer the SCons method, because it leverages the SCons build system to check for changes to the input / output files. The one downside to SCons is that for some reason it takes a while to start running, but once it figures out what it needs to do, it will execute all of the ffmpeg calls quickly. To get started, all you need to do is: pip3 install scons git checkout https://github.com/nuket/Shrinkr Copy ShrinkrArchive to the folder with all the videos. (Rename the file if you want.) Edit this line to set the ffmpeg parameters you want. Edit this line to gather up all the files you want (i.e. *.mp4 or *.mkv). Open up a command-line prompt in that folder. Run scons -f ShrinkrArchive. You'll need a copy of ffmpeg somewhere in your system PATH, and of course, a working copy of Python 3.x. Otherwise, it's pretty easy to use. I've been using it to transcode screencasts to more highly-compressed versions, before kicking them out to cold storage and getting file size savings between 66 - 75%. (Screencasts are usually low-entropy.) @Takin - to your request: If it's possible (not neccessary), I would also like to have the filename as "YYYYMMDD_HHMMSS". You can do this as well in an the ShrinkrArchive file (which is just an SCons build script), you'd have to add a file stat call to the file name emitter and change this line, which determines what to call the output file. This is an exercise left up to the reader, however. Anyways, hope this helps anyone who needs to transcode a bunch of files and doesn't want to use a GUI to do it. If anyone has questions, feel free to open up a new topic here or on GitHub. A: You need to put your videos inside "inputs" folder in the FFmpeg directory. Then run this .bat file from the same directory that FFmpeg exists: @echo off mkdir inputs mkdir outputs set "InputFolder=%~dp0inputs" :Begin echo. set /P fileformati=Insert the input format: echo. set /P fileformato=Insert the output format: echo. echo Press 1 to select CRF 16 echo Press 2 to select CRF 18 echo Press 3 to select CRF 20 echo Press 4 to select CRF 23 echo. choice /c 1234 /M "Select: " if %errorlevel% EQU 4 set crfnumber="23" if %errorlevel% EQU 3 set crfnumber="20" if %errorlevel% EQU 2 set crfnumber="18" if %errorlevel% EQU 1 set crfnumber="16" echo. echo Press 1 to select the "YUV 4:2:0 planar 8-bits color format" echo Press 2 to select the "YUV 4:2:0 planar 10-bits color format" echo Press 3 to select the "YUV 4:2:0 planar 12-bits color format" echo Press 4 to select the "YUV 4:2:2 planar 8-bits color format" echo Press 5 to select the "YUV 4:2:2 planar 10-bits color format" echo Press 6 to select the "YUV 4:2:2 planar 12-bits color format" echo Press 7 to select the "YUV 4:4:4 planar 8-bits color format" echo Press 8 to select the "YUV 4:4:4 planar 10-bits color format" echo Press 9 to select the "YUV 4:4:4 planar 12-bits color format" echo. choice /c 123456789 /M "Select: " if %errorlevel% EQU 9 set colorformat="yuv444p12le" if %errorlevel% EQU 8 set colorformat="yuv444p10le" if %errorlevel% EQU 7 set colorformat="yuv444p" if %errorlevel% EQU 6 set colorformat="yuv422p12le" if %errorlevel% EQU 5 set colorformat="yuv422p10le" if %errorlevel% EQU 4 set colorformat="yuv422p" if %errorlevel% EQU 3 set colorformat="yuv420p12le" if %errorlevel% EQU 2 set colorformat="yuv420p10le" if %errorlevel% EQU 1 set colorformat="yuv420p" for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a" set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%" set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" set "fullstamp=%YYYY%%MM%%DD%_%HH%%Min%%Sec%" echo fullstamp: "%fullstamp%" for /R "%InputFolder%" %%i in (*.%fileformati%) do (ffmpeg -n -i "%%~dpni.%fileformati%" -c:v libx265 -preset:v slow -crf %crfnumber% -vf format=%colorformat% -c:a copy -movflags use_metadata_tags -map_metadata 0 "outputs\%fullstamp% - %%~ni.%fileformato%") timeout /t 10
Can this be done in Handbrake or FFMPEG
Just wonder this could be done in Handbrake or FFMPEG. Any other transcoding software in Windows or MacOS would also be acceptable. I have many family videos, shooted with DSLR/action cam/phone. And the files are really huge without transcoding them. There are something I would like to have, Metadata should be all captured. Using Handbrake would not be able to capture the information of the used device. Also, the capture date will become the transcoding date which is definitely unacceptable. I would like to transcode them into HEVC (H.265) I need to batch transcode them since there're a lot of videos. If it's possible (not neccessary), I would also like to have the filename as "YYYYMMDD_HHMMSS". I think both 1 and 3 are quite frequently asked questions. This thread will be quite useful to all people who are looking for the same answer as well. Thanks a lot!
[ "I'd say no.\nTraditionally metadata handling in video is done fairly poorly - unlike still images. I have a similar issue and probably end up rolling my own. I assume you'd like to go to MP4 or MOV which has a number of different metadata styles: MP4, QuickTime, iTunes style, 3gpp, embedded ID3 (similar to MP3) etc.\nSince writing support of video metadata is done poorly - so is reading of video metadata. You could write more than one style into the file - hoping the tools that don't understand it will ignore the unknown metadata.\nAs of now I would transcode to MOV/H.265 and use Apple style metadata so that it works correctly on my iPhone/iPad/AppleTV and Mac.\nUnfortunately - sometimes the answer is there is no answer but I'd love to be proven wrong.\n", "tl;dr - watch the video explainer:\nhttps://youtu.be/ZiGeVvNGn9c\nI came up with two different ways to batch transcode a folder full of video files using ffmpeg. As far as I know, ffmpeg will copy over all metadata without modification.\nPure Python Way\nhttps://github.com/nuket/Shrinkr#shrinkr-batch-transcode-python-edition\nSCons Way\nhttps://github.com/nuket/Shrinkr#shrinkr-batch-transcode-scons-edition\nOne uses pure Python, the other uses SCons build scripts. Transcoding video can be conceptually similar to compiling software, so, I gave this a shot.\nBoth ways will let you run the batch repeatedly and will not repeat work, already-transcoded files won't be done again unless the source files change.\nOf the two ways, I prefer the SCons method, because it leverages the SCons build system to check for changes to the input / output files. The one downside to SCons is that for some reason it takes a while to start running, but once it figures out what it needs to do, it will execute all of the ffmpeg calls quickly.\nTo get started, all you need to do is:\n\npip3 install scons\ngit checkout https://github.com/nuket/Shrinkr\nCopy ShrinkrArchive to the folder with all the videos. (Rename the file if you want.)\nEdit this line to set the ffmpeg parameters you want.\nEdit this line to gather up all the files you want (i.e. *.mp4 or *.mkv).\nOpen up a command-line prompt in that folder.\nRun scons -f ShrinkrArchive.\n\nYou'll need a copy of ffmpeg somewhere in your system PATH, and of course, a working copy of Python 3.x.\nOtherwise, it's pretty easy to use. I've been using it to transcode screencasts to more highly-compressed versions, before kicking them out to cold storage and getting file size savings between 66 - 75%. (Screencasts are usually low-entropy.)\n@Takin - to your request:\n\nIf it's possible (not neccessary), I would also like to have the\nfilename as \"YYYYMMDD_HHMMSS\".\n\nYou can do this as well in an the ShrinkrArchive file (which is just an SCons build script), you'd have to add a file stat call to the file name emitter and change this line, which determines what to call the output file.\nThis is an exercise left up to the reader, however. \nAnyways, hope this helps anyone who needs to transcode a bunch of files and doesn't want to use a GUI to do it.\nIf anyone has questions, feel free to open up a new topic here or on GitHub.\n", "You need to put your videos inside \"inputs\" folder in the FFmpeg directory. Then run this .bat file from the same directory that FFmpeg exists:\n@echo off\nmkdir inputs\nmkdir outputs\nset \"InputFolder=%~dp0inputs\"\n\n:Begin\necho.\nset /P fileformati=Insert the input format: \n\necho.\nset /P fileformato=Insert the output format: \n\necho.\necho Press 1 to select CRF 16\necho Press 2 to select CRF 18\necho Press 3 to select CRF 20\necho Press 4 to select CRF 23\necho.\n\nchoice /c 1234 /M \"Select: \"\nif %errorlevel% EQU 4 set crfnumber=\"23\"\nif %errorlevel% EQU 3 set crfnumber=\"20\"\nif %errorlevel% EQU 2 set crfnumber=\"18\"\nif %errorlevel% EQU 1 set crfnumber=\"16\"\n\necho.\necho Press 1 to select the \"YUV 4:2:0 planar 8-bits color format\"\necho Press 2 to select the \"YUV 4:2:0 planar 10-bits color format\"\necho Press 3 to select the \"YUV 4:2:0 planar 12-bits color format\"\necho Press 4 to select the \"YUV 4:2:2 planar 8-bits color format\"\necho Press 5 to select the \"YUV 4:2:2 planar 10-bits color format\"\necho Press 6 to select the \"YUV 4:2:2 planar 12-bits color format\"\necho Press 7 to select the \"YUV 4:4:4 planar 8-bits color format\"\necho Press 8 to select the \"YUV 4:4:4 planar 10-bits color format\"\necho Press 9 to select the \"YUV 4:4:4 planar 12-bits color format\"\necho.\n\nchoice /c 123456789 /M \"Select: \"\nif %errorlevel% EQU 9 set colorformat=\"yuv444p12le\"\nif %errorlevel% EQU 8 set colorformat=\"yuv444p10le\"\nif %errorlevel% EQU 7 set colorformat=\"yuv444p\"\nif %errorlevel% EQU 6 set colorformat=\"yuv422p12le\"\nif %errorlevel% EQU 5 set colorformat=\"yuv422p10le\"\nif %errorlevel% EQU 4 set colorformat=\"yuv422p\"\nif %errorlevel% EQU 3 set colorformat=\"yuv420p12le\"\nif %errorlevel% EQU 2 set colorformat=\"yuv420p10le\"\nif %errorlevel% EQU 1 set colorformat=\"yuv420p\"\n\nfor /f \"tokens=2 delims==\" %%a in ('wmic OS Get localdatetime /value') do set \"dt=%%a\"\nset \"YY=%dt:~2,2%\" & set \"YYYY=%dt:~0,4%\" & set \"MM=%dt:~4,2%\" & set \"DD=%dt:~6,2%\"\nset \"HH=%dt:~8,2%\" & set \"Min=%dt:~10,2%\" & set \"Sec=%dt:~12,2%\"\n\nset \"datestamp=%YYYY%%MM%%DD%\" & set \"timestamp=%HH%%Min%%Sec%\"\nset \"fullstamp=%YYYY%%MM%%DD%_%HH%%Min%%Sec%\"\necho fullstamp: \"%fullstamp%\"\n\nfor /R \"%InputFolder%\" %%i in (*.%fileformati%) do (ffmpeg -n -i \"%%~dpni.%fileformati%\" -c:v libx265 -preset:v slow -crf %crfnumber% -vf format=%colorformat% -c:a copy -movflags use_metadata_tags -map_metadata 0 \"outputs\\%fullstamp% - %%~ni.%fileformato%\")\n\ntimeout /t 10\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "ffmpeg", "h.265", "handbrake", "hevc", "transcode" ]
stackoverflow_0046004235_ffmpeg_h.265_handbrake_hevc_transcode.txt
Q: Is there a matplotlib function in Python for forcing all subplots inside different figures to have the same x and y axis length? I'm testing out different way of displaying figures. I have one figure which is made up of 12 subplots split into two columns. Something like... fig, ax = plt.subplots(6, 2, figsize= (20,26)) I have another code which splits the 12 subplots into 3 different figures based on categorical data. Something like figA, ax = plt.subplots(5, 1, figsize= (10,23)) figB, ax = plt.subplots(3, 1, figsize= (10,17)) fig2, ax = plt.subplots(4, 1, figsize= (10,20)) Is there a way to ensure all the subplots in every figure have the same x and y axis length? A: Answer turns out to be simple. Use a variable that can be scaled by the number of plots in the figure. So, a figure with more plots will have a higher figsize yet equal plot sizes. Something like... ps = 5 #indicates plot size figA, ax = plt.subplots(5, 1, figsize= (10, 5*ps)) figB, ax = plt.subplots(3, 1, figsize= (10, 3*ps)) fig2, ax = plt.subplots(4, 1, figsize= (10, 4*ps)) A: I had a similar problem, try avg(len(x)) as the multiplier. It scales suitably for all lengths.
Is there a matplotlib function in Python for forcing all subplots inside different figures to have the same x and y axis length?
I'm testing out different way of displaying figures. I have one figure which is made up of 12 subplots split into two columns. Something like... fig, ax = plt.subplots(6, 2, figsize= (20,26)) I have another code which splits the 12 subplots into 3 different figures based on categorical data. Something like figA, ax = plt.subplots(5, 1, figsize= (10,23)) figB, ax = plt.subplots(3, 1, figsize= (10,17)) fig2, ax = plt.subplots(4, 1, figsize= (10,20)) Is there a way to ensure all the subplots in every figure have the same x and y axis length?
[ "Answer turns out to be simple. Use a variable that can be scaled by the number of plots in the figure. So, a figure with more plots will have a higher figsize yet equal plot sizes. Something like...\nps = 5 #indicates plot size\nfigA, ax = plt.subplots(5, 1, figsize= (10, 5*ps))\nfigB, ax = plt.subplots(3, 1, figsize= (10, 3*ps))\nfig2, ax = plt.subplots(4, 1, figsize= (10, 4*ps))\n\n", "I had a similar problem, try avg(len(x)) as the multiplier. It scales suitably for all lengths.\n" ]
[ 0, 0 ]
[]
[]
[ "figure", "matplotlib", "plot", "python", "subplot" ]
stackoverflow_0074382240_figure_matplotlib_plot_python_subplot.txt
Q: Flutter: How do I listen to permissions real time I am working on an app in which I want to continuously listen to location and battery permissions. Sample scenario: The user opens the app Grants permission access Goes to settings and revokes the permissions Opens the app again The app displays a snackbar that informs the user that permission has been revoked. I am a beginner and I am using the flutter-permissions-handler and the piece of code below shows my usage. _listenForLocationPermission() { Future<PermissionStatus> status = PermissionHandler() .checkPermissionStatus(PermissionGroup.locationWhenInUse); status.then((PermissionStatus status) { setState(() { _permissionStatus = status; if (_permissionStatus != PermissionStatus.granted) { _renderOfflineSnackbar('Offline'); } }); }); } Any advice on the above is appreciated. A: I'm in the same boat and have found that this works You need to extend your class with WidgetsBindingObserver class _AppState extends State<App> with WidgetsBindingObserver { PermissionStatus _status; ... ... then add these methods to your class @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } // check permissions when app is resumed // this is when permissions are changed in app settings outside of app void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.resumed) { PermissionHandler() .checkPermissionStatus(PermissionGroup.locationWhenInUse) .then(_updateStatus); } } My full code is below, but I've not included the build widget to keep it brief import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:permission_handler/permission_handler.dart'; void main() => runApp(App()); class App extends StatefulWidget { @override _AppState createState() => _AppState(); } class _AppState extends State<App> with WidgetsBindingObserver { PermissionStatus _status; // check permissions @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); PermissionHandler() // Check location permission has been granted .checkPermissionStatus(PermissionGroup .locationWhenInUse) //check permission returns a Future .then(_updateStatus); // handling in callback to prevent blocking UI } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } // check permissions when app is resumed // this is when permissions are changed in app settings outside of app void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.resumed) { PermissionHandler() .checkPermissionStatus(PermissionGroup.locationWhenInUse) .then(_updateStatus); } } override Widget build(BuildContext context) { return MaterialApp( ... ... } void _updateStatus(PermissionStatus status) { if (status != _status) { // check status has changed setState(() { _status = status; // update }); } else { if (status != PermissionStatus.granted) { PermissionHandler().requestPermissions( [PermissionGroup.locationWhenInUse]).then(_onStatusRequested); } } } } void _askPermission() { PermissionHandler().requestPermissions( [PermissionGroup.locationWhenInUse]).then(_onStatusRequested); } void _onStatusRequested(Map<PermissionGroup, PermissionStatus> statuses) { final status = statuses[PermissionGroup.locationWhenInUse]; if (status != PermissionStatus.granted) { // On iOS if "deny" is pressed, open App Settings PermissionHandler().openAppSettings(); } else { _updateStatus(status); } } I hope this helps A: Null safe code: permission_handler: ^8.0.0+2 The idea is to check for the permission in the app's lifecycle callback when the state is resumed. Here's the minimal code to get you going. class _FooPageState extends State<FooPage> with WidgetsBindingObserver { final Permission _permission = Permission.location; bool _checkingPermission = false; @override void initState() { super.initState(); WidgetsBinding.instance!.addObserver(this); } @override void dispose() { WidgetsBinding.instance!.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { super.didChangeAppLifecycleState(state); if (state == AppLifecycleState.resumed && !_checkingPermission) { _checkingPermission = true; _checkPermission(_permission).then((_) => _checkingPermission = false); } } Future<void> _checkPermission(Permission permission) async { final status = await permission.request(); if (status == PermissionStatus.granted) { print('Permission granted'); } else if (status == PermissionStatus.denied) { print('Permission denied. Show a dialog and again ask for the permission'); } else if (status == PermissionStatus.permanentlyDenied) { print('Take the user to the settings page.'); } } @override Widget build(BuildContext context) => Scaffold(); } A: If you use flutter_hooks, you can do: class ExampleWidget extends HookWidget { ... @override Widget build(BuildContext context) { final appLifecycleState = useAppLifecycleState(); useEffect(() { checkPermissions(); }, [appLifecycleState]); // Build your widget as normal return ... } } checkPermissions(); is a function I wrote to actually check permissions, depending on the library. For location, they have it documented in Usage. Thanks to Flutter hooks, the impact on the existing class is very small.
Flutter: How do I listen to permissions real time
I am working on an app in which I want to continuously listen to location and battery permissions. Sample scenario: The user opens the app Grants permission access Goes to settings and revokes the permissions Opens the app again The app displays a snackbar that informs the user that permission has been revoked. I am a beginner and I am using the flutter-permissions-handler and the piece of code below shows my usage. _listenForLocationPermission() { Future<PermissionStatus> status = PermissionHandler() .checkPermissionStatus(PermissionGroup.locationWhenInUse); status.then((PermissionStatus status) { setState(() { _permissionStatus = status; if (_permissionStatus != PermissionStatus.granted) { _renderOfflineSnackbar('Offline'); } }); }); } Any advice on the above is appreciated.
[ "I'm in the same boat and have found that this works\nYou need to extend your class with WidgetsBindingObserver\nclass _AppState extends State<App> with WidgetsBindingObserver {\n PermissionStatus _status;\n ...\n ...\n\nthen add these methods to your class\n@override\n void dispose() {\n WidgetsBinding.instance.removeObserver(this);\n super.dispose();\n }\n\n // check permissions when app is resumed\n // this is when permissions are changed in app settings outside of app\n void didChangeAppLifecycleState(AppLifecycleState state) {\n if (state == AppLifecycleState.resumed) {\n PermissionHandler()\n .checkPermissionStatus(PermissionGroup.locationWhenInUse)\n .then(_updateStatus);\n }\n }\n\nMy full code is below, but I've not included the build widget to keep it brief\nimport 'package:flutter/cupertino.dart';\nimport 'package:flutter/material.dart';\nimport 'package:permission_handler/permission_handler.dart';\n\nvoid main() => runApp(App());\n\nclass App extends StatefulWidget {\n @override\n _AppState createState() => _AppState();\n}\n\nclass _AppState extends State<App> with WidgetsBindingObserver {\n PermissionStatus _status;\n\n // check permissions\n @override\n void initState() {\n super.initState();\n WidgetsBinding.instance.addObserver(this);\n PermissionHandler() // Check location permission has been granted\n .checkPermissionStatus(PermissionGroup\n .locationWhenInUse) //check permission returns a Future\n .then(_updateStatus); // handling in callback to prevent blocking UI\n }\n\n @override\n void dispose() {\n WidgetsBinding.instance.removeObserver(this);\n super.dispose();\n }\n\n // check permissions when app is resumed\n // this is when permissions are changed in app settings outside of app\n void didChangeAppLifecycleState(AppLifecycleState state) {\n if (state == AppLifecycleState.resumed) {\n PermissionHandler()\n .checkPermissionStatus(PermissionGroup.locationWhenInUse)\n .then(_updateStatus);\n }\n }\n\noverride\n Widget build(BuildContext context) {\n return MaterialApp( \n ...\n ...\n}\n\nvoid _updateStatus(PermissionStatus status) {\n if (status != _status) {\n // check status has changed\n setState(() {\n _status = status; // update\n });\n } else {\n if (status != PermissionStatus.granted) {\n PermissionHandler().requestPermissions(\n [PermissionGroup.locationWhenInUse]).then(_onStatusRequested);\n }\n }\n }\n }\n\n void _askPermission() {\n PermissionHandler().requestPermissions(\n [PermissionGroup.locationWhenInUse]).then(_onStatusRequested);\n }\n\n void _onStatusRequested(Map<PermissionGroup, PermissionStatus> statuses) {\n final status = statuses[PermissionGroup.locationWhenInUse];\n if (status != PermissionStatus.granted) {\n // On iOS if \"deny\" is pressed, open App Settings\n PermissionHandler().openAppSettings();\n } else {\n _updateStatus(status);\n }\n }\n\n\nI hope this helps\n", "Null safe code:\npermission_handler: ^8.0.0+2\n\nThe idea is to check for the permission in the app's lifecycle callback when the state is resumed. Here's the minimal code to get you going.\nclass _FooPageState extends State<FooPage> with WidgetsBindingObserver {\n final Permission _permission = Permission.location;\n bool _checkingPermission = false;\n\n @override\n void initState() {\n super.initState();\n WidgetsBinding.instance!.addObserver(this);\n }\n\n @override\n void dispose() {\n WidgetsBinding.instance!.removeObserver(this);\n super.dispose();\n }\n\n @override\n void didChangeAppLifecycleState(AppLifecycleState state) {\n super.didChangeAppLifecycleState(state);\n if (state == AppLifecycleState.resumed && !_checkingPermission) {\n _checkingPermission = true;\n _checkPermission(_permission).then((_) => _checkingPermission = false);\n }\n }\n\n Future<void> _checkPermission(Permission permission) async {\n final status = await permission.request();\n if (status == PermissionStatus.granted) {\n print('Permission granted');\n } else if (status == PermissionStatus.denied) {\n print('Permission denied. Show a dialog and again ask for the permission');\n } else if (status == PermissionStatus.permanentlyDenied) {\n print('Take the user to the settings page.');\n }\n }\n\n @override\n Widget build(BuildContext context) => Scaffold();\n}\n\n", "If you use flutter_hooks, you can do:\nclass ExampleWidget extends HookWidget {\n ...\n @override\n Widget build(BuildContext context) {\n final appLifecycleState = useAppLifecycleState();\n useEffect(() {\n checkPermissions();\n }, [appLifecycleState]);\n\n // Build your widget as normal\n return ...\n }\n}\n\ncheckPermissions(); is a function I wrote to actually check permissions, depending on the library. For location, they have it documented in Usage.\nThanks to Flutter hooks, the impact on the existing class is very small.\n" ]
[ 26, 2, 0 ]
[]
[]
[ "android", "dart", "flutter", "ios", "permissions" ]
stackoverflow_0055442995_android_dart_flutter_ios_permissions.txt
Q: How to download files from SFTP that doesn't have actural files in Synapse? I have a little bit complicate situation here: I need to download files from a SFTP daily. I connect to the SFTP with username and SSH key, the keys have a passphrase. This SFTP has no actual files. All the files on the server is 0 bytes. The server will dynamicly generate the file if it get a "get" command. So when I connect the SFTP with Winscp, everything went perfectly. But I have to do it in Synapse. I managed to connect it in Pipeline with copy activity, and I managed to download all the files, but with no data content inside. Does anyone know how I can download the files with content? A: If you actually have files with content in SFTP location, then they should also be automatically copied using the pipeline in your Synapse. In case if you just want to copy the files that are having the content and ignore empty files, then you will have to use a get metadata activity to check the size of the file (i.e., > 0 bytes) and then filter those files only to copy to your desired destination. Using the childItems you can get the fileName, Type and Size and use these properties in the subsequent copy activity to only copy filter files to your destination.
How to download files from SFTP that doesn't have actural files in Synapse?
I have a little bit complicate situation here: I need to download files from a SFTP daily. I connect to the SFTP with username and SSH key, the keys have a passphrase. This SFTP has no actual files. All the files on the server is 0 bytes. The server will dynamicly generate the file if it get a "get" command. So when I connect the SFTP with Winscp, everything went perfectly. But I have to do it in Synapse. I managed to connect it in Pipeline with copy activity, and I managed to download all the files, but with no data content inside. Does anyone know how I can download the files with content?
[ "If you actually have files with content in SFTP location, then they should also be automatically copied using the pipeline in your Synapse. In case if you just want to copy the files that are having the content and ignore empty files, then you will have to use a get metadata activity to check the size of the file (i.e., > 0 bytes) and then filter those files only to copy to your desired destination. Using the childItems you can get the fileName, Type and Size and use these properties in the subsequent copy activity to only copy filter files to your destination.\n" ]
[ 0 ]
[]
[]
[ "azure_synapse", "sftp" ]
stackoverflow_0074594556_azure_synapse_sftp.txt
Q: Using heap memory for reading files To read data from a file, I create heap memory then pass the variable pointer to a function so fread() will put the file data into the pointer. But when the function returns, there is no data in the new created memory. int main(...) { MyFile File; File.Open(...); int filesize = File.Tell(); char* buffer = new buffer[filesize]; // Create some memory for the data File.Read((char**)&buffer); // Now do something with the buffer. BUT there is trash in it. File.Close(); delete [] buffer; } size_t File::Read(void* buf) { ... ::fseek(fStream, 0, SEEK_END); int fileSize = ::ftell(fStream); // Get file size. ::fseek(fStream, 0, SEEK_SET); ::fread(buf, 1, fileSize, fStream); return (fileSize); } Yes, I can put char * myBuffer = new char[fileSize]; inside of File::Read(...) before ::fread(myBuffer, 1, fileSize, fStream);, but I should not have to do this because I already have heap memory (buffer) in main(). A: You're reading your file contents into the pointer buffer, not the array it points to. You're overcomplicating things anyway. You don't need a pointer to a pointer, or a void*. You can simply pass a char* to Read. You should really also pass the size of the buffer pointed to into Read as well. Otherwise you risk overflowing your buffer. int main() { MyFile File; File.Open(/*.....*/); int filesize = File.Tell() char* buffer = new buffer[filesize]; // Create some memory for the data File.Read(buffer, filesize); // Now do something with the buffer. BUT there is trash in it. File.Close(); delete [] buffer; } size_t File::Read(char* buf, size_t count) { // ...... // No need to find the size of the file a second time // Return the actual number of bytes read return ::fread(buf, 1, count, fStream); }
Using heap memory for reading files
To read data from a file, I create heap memory then pass the variable pointer to a function so fread() will put the file data into the pointer. But when the function returns, there is no data in the new created memory. int main(...) { MyFile File; File.Open(...); int filesize = File.Tell(); char* buffer = new buffer[filesize]; // Create some memory for the data File.Read((char**)&buffer); // Now do something with the buffer. BUT there is trash in it. File.Close(); delete [] buffer; } size_t File::Read(void* buf) { ... ::fseek(fStream, 0, SEEK_END); int fileSize = ::ftell(fStream); // Get file size. ::fseek(fStream, 0, SEEK_SET); ::fread(buf, 1, fileSize, fStream); return (fileSize); } Yes, I can put char * myBuffer = new char[fileSize]; inside of File::Read(...) before ::fread(myBuffer, 1, fileSize, fStream);, but I should not have to do this because I already have heap memory (buffer) in main().
[ "You're reading your file contents into the pointer buffer, not the array it points to.\nYou're overcomplicating things anyway. You don't need a pointer to a pointer, or a void*. You can simply pass a char* to Read. You should really also pass the size of the buffer pointed to into Read as well. Otherwise you risk overflowing your buffer.\nint main() {\n MyFile File;\n File.Open(/*.....*/);\n int filesize = File.Tell()\n char* buffer = new buffer[filesize]; // Create some memory for the data \n File.Read(buffer, filesize);\n\n // Now do something with the buffer. BUT there is trash in it.\n\n File.Close();\n delete [] buffer;\n}\n\nsize_t File::Read(char* buf, size_t count) {\n // ......\n\n // No need to find the size of the file a second time\n\n // Return the actual number of bytes read\n return ::fread(buf, 1, count, fStream);\n}\n\n" ]
[ 2 ]
[]
[]
[ "c++", "file", "memory" ]
stackoverflow_0074659562_c++_file_memory.txt