content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
30
130
Q: function to count changes in a network (changes in node attributes) I would like to count the number of color changes in a network using a function. A change would be "red" to "green" (from a to b in the example) Overlaps (e.g., "green" to "green" and "orange", from c to c1 in the example) should not count as a change. Example data: library(tidyverse) network <- tibble( from=c("a","b","c","c"), to= c("b","c","c1","c2")) colors <- list( a=list("red"), b=list("red"), c=list("green"), c1=list("green","orange"), c2=list("blue","black") ) The correct output of the function would be 2 (from b to c and c to c2) in this example. A: Here's how you can create a function that counts the number of color changes in a network: count_color_changes <- function(network, colors) { # Initialize a counter to 0 counter <- 0 # Iterate over the rows in the network for (i in 1:nrow(network)) { # Get the 'from' and 'to' nodes for the current row from <- network[i, "from"] to <- network[i, "to"] # Get the list of colors for the 'from' and 'to' nodes from_colors <- colors[from] to_colors <- colors[to] # Check if there is at least one color that is present in the list # of colors for both the 'from' and 'to' nodes common_colors <- intersect(from_colors, to_colors) # If there are no common colors, then it means that there is a # color change from the 'from' node to the 'to' node if (length(common_colors) == 0) { # Increment the counter counter <- counter + 1 } } # Return the counter return(counter) } You can then use this function as follows: # Count the number of color changes in the network count_color_changes(network, colors) # Output: 1 This function first initializes a counter to 0. It then iterates over the rows in the `network A: This can be vectorized: # change inner lists in 'colors' to vectors colors <- lapply(colors, unlist) count_color_changes <- function(network, colors) { # list of lists of 'from' and to 'colors' col.ft <- lapply(network, \(x) colors[x]) # common colors col.com <- mapply(intersect, col.ft$from, col.ft$to) # number of transitions where no common color was found sum(sapply(col.com, length) == 0) } count_color_changes(network, colors) # 2
function to count changes in a network (changes in node attributes)
I would like to count the number of color changes in a network using a function. A change would be "red" to "green" (from a to b in the example) Overlaps (e.g., "green" to "green" and "orange", from c to c1 in the example) should not count as a change. Example data: library(tidyverse) network <- tibble( from=c("a","b","c","c"), to= c("b","c","c1","c2")) colors <- list( a=list("red"), b=list("red"), c=list("green"), c1=list("green","orange"), c2=list("blue","black") ) The correct output of the function would be 2 (from b to c and c to c2) in this example.
[ "Here's how you can create a function that counts the number of color changes in a network:\ncount_color_changes <- function(network, colors) {\n # Initialize a counter to 0\n counter <- 0\n\n # Iterate over the rows in the network\n for (i in 1:nrow(network)) {\n # Get the 'from' and 'to' nodes for the current row\n from <- network[i, \"from\"]\n to <- network[i, \"to\"]\n\n # Get the list of colors for the 'from' and 'to' nodes\n from_colors <- colors[from]\n to_colors <- colors[to]\n\n # Check if there is at least one color that is present in the list\n # of colors for both the 'from' and 'to' nodes\n common_colors <- intersect(from_colors, to_colors)\n\n # If there are no common colors, then it means that there is a\n # color change from the 'from' node to the 'to' node\n if (length(common_colors) == 0) {\n # Increment the counter\n counter <- counter + 1\n }\n }\n\n # Return the counter\n return(counter)\n}\n\nYou can then use this function as follows:\n# Count the number of color changes in the network\ncount_color_changes(network, colors)\n# Output: 1\n\nThis function first initializes a counter to 0. It then iterates over the rows in the `network\n", "This can be vectorized:\n# change inner lists in 'colors' to vectors\ncolors <- lapply(colors, unlist)\n\ncount_color_changes <- function(network, colors) {\n \n # list of lists of 'from' and to 'colors'\n col.ft <- lapply(network, \\(x) colors[x])\n # common colors\n col.com <- mapply(intersect, col.ft$from, col.ft$to)\n # number of transitions where no common color was found\n sum(sapply(col.com, length) == 0)\n}\n\ncount_color_changes(network, colors)\n# 2\n\n" ]
[ 1, 1 ]
[]
[]
[ "networking", "r" ]
stackoverflow_0074675417_networking_r.txt
Q: Why does my apps script function work on desktop but not mobile I have developed an application in Google Sheets that uses various app script functions. The functions work consistently on the desktop. When I use the spreadsheet on my phone however the functions don't work. The weird part is that when I have both the spreadsheet open on my phone and my desktop, side-by-side, and I enter data into my phone, nothing happens on the phone but the correct things happen on the desktop. Here is the application. https://docs.google.com/spreadsheets/d/1NWrc7Ey2uVRLFHNTT6r86A9ButgOM-3XpZLFR-PnF2c/edit?usp=sharing Simply enter "tofu" into cell A8. OnEdit code should retrieve data and place it in the other pick cells. When all the pink cells are filled click the submit checkbox and it will add the data to the "database". Everything was working in recent past but now there is this weird async phenomenon happening between the phone and the desktop. Thanks for the help! I tried to uninstall and reinstall google sheets/google drive on my phone. This did not work. The code had instances of .flush() which I removed but that didn't improve the problem. A: The execution log of you script project shows a few failed executions. The way you have shared the sample spreadsheet prevents others from seeing those logs, but you can examine them to find out why the script throws errors.
Why does my apps script function work on desktop but not mobile
I have developed an application in Google Sheets that uses various app script functions. The functions work consistently on the desktop. When I use the spreadsheet on my phone however the functions don't work. The weird part is that when I have both the spreadsheet open on my phone and my desktop, side-by-side, and I enter data into my phone, nothing happens on the phone but the correct things happen on the desktop. Here is the application. https://docs.google.com/spreadsheets/d/1NWrc7Ey2uVRLFHNTT6r86A9ButgOM-3XpZLFR-PnF2c/edit?usp=sharing Simply enter "tofu" into cell A8. OnEdit code should retrieve data and place it in the other pick cells. When all the pink cells are filled click the submit checkbox and it will add the data to the "database". Everything was working in recent past but now there is this weird async phenomenon happening between the phone and the desktop. Thanks for the help! I tried to uninstall and reinstall google sheets/google drive on my phone. This did not work. The code had instances of .flush() which I removed but that didn't improve the problem.
[ "The execution log of you script project shows a few failed executions. The way you have shared the sample spreadsheet prevents others from seeing those logs, but you can examine them to find out why the script throws errors.\n" ]
[ 0 ]
[]
[]
[ "google_apps_script" ]
stackoverflow_0074674988_google_apps_script.txt
Q: SessionNotCreatedException: Could not start a new session. Response code 500 error using Selenium Java and WebDriverManager through pom.xml I want to test my script on chrome beta version and for that reason I have installed chrome beta version but somehow I am not able to start it using Selenium Java. I have all the needed dependency added in pom.xml file regarding webdriver manager etc. I am sharing my console error and also script. ChromeOptions optionsBeta = new ChromeOptions(); optionsBeta.setBinary("C:\\Users\\WRP\\Downloads\\Programs\\ChromeSetup.exe"); System.setProperty("webdriver.chrome.driver", "C:\\Users\\WRP\\eclipse-workspace\\PracticeProject\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(optionsBeta); //System.setProperty("webdriver.chrome.driver", "./Driver/chromedriver.exe"); // WebDriver driver = new ChromeDriver(); WebDriverManager.chromedriver().setup(); //WebDriverManager.chromedriver().driverVersion("104.0.5112.29").setup(); //WebDriver driver = new ChromeDriver(); WebDriverWait waits=new WebDriverWait (driver, Duration.ofSeconds(10)); Error tracelogs: Starting ChromeDriver 104.0.5112.29 (eff877e18f767c77fef0481a1cba402c8cbad404-refs/branch-heads/5112@{#422}) on port 55215 Only local connections are allowed. Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe. ChromeDriver was started successfully. Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Response code 500. Message: unknown error: Chrome failed to start: crashed. (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location C:\Users\WRP\Downloads\Programs\ChromeSetup.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.) Build info: version: '4.3.0', revision: 'a4995e2c09*' System info: host: 'AWAIS-PC', ip: '192.168.1.62', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '18.0.1' Driver info: org.openqa.selenium.chrome.ChromeDriver Command: [null, newSession {capabilities=[Capabilities {browserName: chrome, goog:chromeOptions: {args: [], binary: C:\Users\WRP\Downloads\Prog..., extensions: []}}], desiredCapabilities=Capabilities {browserName: chrome, goog:chromeOptions: {args: [], binary: C:\Users\WRP\Downloads\Prog..., extensions: []}}}] at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:144) at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:102) at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:67) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:156) at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:167) at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:142) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:569) at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:264) at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:179) at org.openqa.selenium.chromium.ChromiumDriver.<init>(ChromiumDriver.java:101) at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:81) at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:70) at First_Test.Practice_First.main(Practice_First.java:29) A: This error message... Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Response code 500. Message: unknown error: Chrome failed to start: crashed. (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location C:\Users\WRP\Downloads\Programs\ChromeSetup.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.) ...implies that the ChromeDriver was unable to initiate/spawn a new Browsing Context i.e. google-chrome session. Your have to take care of a couple of things here as follows: setBinary() argument should be used to point to the binary executable i.e. chrome.exe post installation of the browser software (ChromeSetup.exe) optionsBeta.setBinary("C:\\location\\to\\chrome.exe"); You'd use either of the following (not both): The downloaded version of the chromedriver.exe using the System.setProperty() line as follows: System.setProperty("webdriver.chrome.driver", "C:\\Users\\WRP\\eclipse-workspace\\PracticeProject\\Driver\\chromedriver.exe"); The WebDriverManager dependency in pom.xml and setup the chromedriver as: WebDriverManager.chromedriver().setup(); Your effective code block will be: Using downloaded ChromeDriver: System.setProperty("webdriver.chrome.driver", "C:\\Users\\WRP\\eclipse-workspace\\PracticeProject\\Driver\\chromedriver.exe"); ChromeOptions optionsBeta = new ChromeOptions(); optionsBeta.setBinary("C:\\location\\to\\chrome.exe"); WebDriver driver = new ChromeDriver(optionsBeta); Using Maven Dependency in pom.xml: WebDriverManager.chromedriver().driverVersion("104.0.5112.29").setup(); ChromeOptions optionsBeta = new ChromeOptions(); optionsBeta.setBinary("C:\\location\\to\\chrome.exe"); WebDriver driver = new ChromeDriver(optionsBeta); A: Use the below chrome option options = webdriver.ChromeOptions() options.add_argument('--disable-dev-shm-usage') options.add_argument('--ignore-ssl-errors=yes') options.add_argument('--ignore-certificate-errors') This line very important on skip this error options.add_argument('--disable-dev-shm-usage')
SessionNotCreatedException: Could not start a new session. Response code 500 error using Selenium Java and WebDriverManager through pom.xml
I want to test my script on chrome beta version and for that reason I have installed chrome beta version but somehow I am not able to start it using Selenium Java. I have all the needed dependency added in pom.xml file regarding webdriver manager etc. I am sharing my console error and also script. ChromeOptions optionsBeta = new ChromeOptions(); optionsBeta.setBinary("C:\\Users\\WRP\\Downloads\\Programs\\ChromeSetup.exe"); System.setProperty("webdriver.chrome.driver", "C:\\Users\\WRP\\eclipse-workspace\\PracticeProject\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(optionsBeta); //System.setProperty("webdriver.chrome.driver", "./Driver/chromedriver.exe"); // WebDriver driver = new ChromeDriver(); WebDriverManager.chromedriver().setup(); //WebDriverManager.chromedriver().driverVersion("104.0.5112.29").setup(); //WebDriver driver = new ChromeDriver(); WebDriverWait waits=new WebDriverWait (driver, Duration.ofSeconds(10)); Error tracelogs: Starting ChromeDriver 104.0.5112.29 (eff877e18f767c77fef0481a1cba402c8cbad404-refs/branch-heads/5112@{#422}) on port 55215 Only local connections are allowed. Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe. ChromeDriver was started successfully. Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Response code 500. Message: unknown error: Chrome failed to start: crashed. (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location C:\Users\WRP\Downloads\Programs\ChromeSetup.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.) Build info: version: '4.3.0', revision: 'a4995e2c09*' System info: host: 'AWAIS-PC', ip: '192.168.1.62', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '18.0.1' Driver info: org.openqa.selenium.chrome.ChromeDriver Command: [null, newSession {capabilities=[Capabilities {browserName: chrome, goog:chromeOptions: {args: [], binary: C:\Users\WRP\Downloads\Prog..., extensions: []}}], desiredCapabilities=Capabilities {browserName: chrome, goog:chromeOptions: {args: [], binary: C:\Users\WRP\Downloads\Prog..., extensions: []}}}] at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:144) at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:102) at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:67) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:156) at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:167) at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:142) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:569) at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:264) at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:179) at org.openqa.selenium.chromium.ChromiumDriver.<init>(ChromiumDriver.java:101) at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:81) at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:70) at First_Test.Practice_First.main(Practice_First.java:29)
[ "This error message...\nException in thread \"main\" org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Response code 500. Message: unknown error: Chrome failed to start: crashed.\n (unknown error: DevToolsActivePort file doesn't exist)\n (The process started from chrome location C:\\Users\\WRP\\Downloads\\Programs\\ChromeSetup.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)\n\n...implies that the ChromeDriver was unable to initiate/spawn a new Browsing Context i.e. google-chrome session.\nYour have to take care of a couple of things here as follows:\n\nsetBinary() argument should be used to point to the binary executable i.e. chrome.exe post installation of the browser software (ChromeSetup.exe)\noptionsBeta.setBinary(\"C:\\\\location\\\\to\\\\chrome.exe\");\n\n\nYou'd use either of the following (not both):\n\nThe downloaded version of the chromedriver.exe using the System.setProperty() line as follows:\nSystem.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\WRP\\\\eclipse-workspace\\\\PracticeProject\\\\Driver\\\\chromedriver.exe\");\n\n\nThe WebDriverManager dependency in pom.xml and setup the chromedriver as:\nWebDriverManager.chromedriver().setup();\n\n\n\n\n\nYour effective code block will be:\n\nUsing downloaded ChromeDriver:\nSystem.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\WRP\\\\eclipse-workspace\\\\PracticeProject\\\\Driver\\\\chromedriver.exe\");\nChromeOptions optionsBeta = new ChromeOptions();\noptionsBeta.setBinary(\"C:\\\\location\\\\to\\\\chrome.exe\"); \nWebDriver driver = new ChromeDriver(optionsBeta);\n\n\nUsing Maven Dependency in pom.xml:\nWebDriverManager.chromedriver().driverVersion(\"104.0.5112.29\").setup();\nChromeOptions optionsBeta = new ChromeOptions();\noptionsBeta.setBinary(\"C:\\\\location\\\\to\\\\chrome.exe\"); \nWebDriver driver = new ChromeDriver(optionsBeta);\n\n\n\n", "Use the below chrome option\noptions = webdriver.ChromeOptions()\noptions.add_argument('--disable-dev-shm-usage')\noptions.add_argument('--ignore-ssl-errors=yes')\noptions.add_argument('--ignore-certificate-errors')\n\nThis line very important on skip this error\noptions.add_argument('--disable-dev-shm-usage')\n\n" ]
[ 0, 0 ]
[]
[]
[ "google_chrome", "java", "selenium", "selenium_chromedriver", "webdriver_manager" ]
stackoverflow_0073021320_google_chrome_java_selenium_selenium_chromedriver_webdriver_manager.txt
Q: When and why to use hash tables in CL instead of a-lists? I believe common lisp is the only language I have worked with that have a variety of extremely useful data structures. The a-list being the most important one to me. I use it all the time. When and why do you (or should you) use hash tables? My reluctance to using them is that, unlike the other data structures, hashtables in CL are not visible lists. Which honestly, I find weird considering almost everything is a list. Maybe I am missing something in my inexperience? A: The hash table is very useful when you have to access a large set of values through a key, since the complexity of this operation with a hash table is O(1), while the complexity of the operation using an a-list is O(n), where n is the length of the list. So, I use it when I need to access multiple times a set of values which has more then few elements. A: There are lot of assumptions to address in your question: I believe common lisp is the only language I have worked with that have a variety of extremely useful data structures. I don't think this is particularly true, the standard libraries of popular languages are filled with lot of data structures too (C++, Java, Rust, Python) When and why do you (or should you) use hash tables? Data-structures come with costs in terms of memory and processor usage: a list must be searched linearly to find an element, whereas an hash-table has a constant lookup cost: for small lists however the linear search might be faster than the constant lookup. Moreover, there are other criteria like: do I want to access the data concurrently? a List can be manipulated in a purely functional way, making data-sharing across threads easier than with a hash-table (but hash-table can be associated with a mutex, etc.) My reluctance to using them is that, unlike the other data structures, hashtables in CL are not visible lists. Which honestly, I find weird considering almost everything is a list. The source code of Lisp programs is made mostly of Lists and symbols, even if there is no such restriction. But at runtime, CL has a lot of different types that are not at all related to lists: bignums, floating points, rational numbers, complex numbers, vectors, arrays, packages, symbols, strings, classes and structures, hash-tables, readtables, functions, etc. You can model a lot of data at runtime by putting them in lists, which is something that works well for a lot of cases, but they are by far not the only types available. Just to emphasize a little bit, when you write: (vector 0 1 2) This might look like a list in your code, but at runtime the value really is a different kind of object, a vector. Do not be confused by how things are expressed in code and how they are represented during code execution. If you don't use it already, I suggest installing and using the Alexandria Lisp libray (see https://alexandria.common-lisp.dev/). There are useful functions to convert from and to hash-tables from alists or plists. More generally, I think it is important to architecture your libraries and programs in a way that hide implementation details: you define a function make-person and accessors person-age, person-name, etc. as well as other user-facing functions. And the actual implementation can use hash tables, lists, etc. but this is not really a concern that should be exposed, because exposing that is a risk: you won't be able to easily change your mind later if you find out that the performance is bad or if you want to add a cache, use a database, etc. I find however that CL is good at making nice interfaces that do not come with too much accidental complexity. A: My reluctance to using them is that, unlike the other data structures, hashtables in CL are not visible lists. They are definitely not lists, but indeed they are not visible either: #<HASH-TABLE :TEST EQL :COUNT 1 {100F4BA883}> this doesn't show what's inside the hash-table. During development it will require more steps to inspect what's inside (inspect, describe, alexandria:hash-table-alist, defining a non-portable print-object method…). serapeum:dict I like very much serapeum:dict, coupled with (serapeum:toggle-pretty-print-hash-table) (also the Cookbook). CL-USER> (serapeum:dict :a 1 :b 2 :c 3) ;; => #<HASH-TABLE :TEST EQUAL :COUNT 3 {100F6012D3}> CL-USER> (serapeum:toggle-pretty-print-hash-table) ;; print the above HT again: CL-USER> ** (SERAPEUM:DICT :A 1 :B 2 :C 3 ) Not only is it printed readably, but it allows to create the hash-table with initial elements at the same time (unlike make-hash-table) and you can read it back in. It's even easy to save such a structure on file. Serapeum is a solid library. Now, use hash-tables more easily. A: When to use a hash-table: You need to do fast (approximately "constant time") look-ups of data. When to use an a-list: You have a need to dynamically shadow data you pass on to functions. If neither of these obviously apply, you have to make a choice. And then, possibly, benchmark your choice. And then evaluate if rewriting it using the other choice would be better. In some experimentation that someone else did, well over a decade ago, the trade-off between an a-list and a hash-map in most Common Lisp implementation is somewhere in the region of 5 to 20 keys. However, if you have a need to "shadow" bindings, for functions you call, an a-list does provide that "for free", and a hash-map does not. So if that is something that your code does a lot of, an a-list MAY be the better choice. * (defun lookup (alist key) (assoc key alist)) LOOKUP * (lookup '((key1 . value1) (key2 . value2)) 'key1) (KEY1 . VALUE1) * (lookup '((key1 . value1) (key2 . value2)) 'key2) (KEY2 . VALUE2) * (lookup '((key2 . value3) (key1 . value1) (key2 . value2)) 'key2) (KEY2 . VALUE3)
When and why to use hash tables in CL instead of a-lists?
I believe common lisp is the only language I have worked with that have a variety of extremely useful data structures. The a-list being the most important one to me. I use it all the time. When and why do you (or should you) use hash tables? My reluctance to using them is that, unlike the other data structures, hashtables in CL are not visible lists. Which honestly, I find weird considering almost everything is a list. Maybe I am missing something in my inexperience?
[ "The hash table is very useful when you have to access a large set of values through a key, since the complexity of this operation with a hash table is O(1), while the complexity of the operation using an a-list is O(n), where n is the length of the list.\nSo, I use it when I need to access multiple times a set of values which has more then few elements.\n", "There are lot of assumptions to address in your question:\n\nI believe common lisp is the only language I have worked with that have a variety of extremely useful data structures.\n\nI don't think this is particularly true, the standard libraries of popular languages are filled with lot of data structures too (C++, Java, Rust, Python)\n\nWhen and why do you (or should you) use hash tables?\n\nData-structures come with costs in terms of memory and processor usage: a list must be searched linearly to find an element, whereas an hash-table has a constant lookup cost: for small lists however the linear search might be faster than the constant lookup. Moreover, there are other criteria like: do I want to access the data concurrently? a List can be manipulated in a purely functional way, making data-sharing across threads easier than with a hash-table (but hash-table can be associated with a mutex, etc.)\n\nMy reluctance to using them is that, unlike the other data structures, hashtables in CL are not visible lists. Which honestly, I find weird considering almost everything is a list.\n\nThe source code of Lisp programs is made mostly of Lists and symbols, even if there is no such restriction. But at runtime, CL has a lot of different types that are not at all related to lists: bignums, floating points, rational numbers, complex numbers, vectors, arrays, packages, symbols, strings, classes and structures, hash-tables, readtables, functions, etc. You can model a lot of data at runtime by putting them in lists, which is something that works well for a lot of cases, but they are by far not the only types available.\nJust to emphasize a little bit, when you write:\n(vector 0 1 2)\n\nThis might look like a list in your code, but at runtime the value really is a different kind of object, a vector. Do not be confused by how things are expressed in code and how they are represented during code execution.\nIf you don't use it already, I suggest installing and using the Alexandria Lisp libray (see https://alexandria.common-lisp.dev/). There are useful functions to convert from and to hash-tables from alists or plists.\nMore generally, I think it is important to architecture your libraries and programs in a way that hide implementation details: you define a function make-person and accessors person-age, person-name, etc. as well as other user-facing functions. And the actual implementation can use hash tables, lists, etc. but this is not really a concern that should be exposed, because exposing that is a risk: you won't be able to easily change your mind later if you find out that the performance is bad or if you want to add a cache, use a database, etc.\nI find however that CL is good at making nice interfaces that do not come with too much accidental complexity.\n", "\nMy reluctance to using them is that, unlike the other data structures, hashtables in CL are not visible lists.\n\nThey are definitely not lists, but indeed they are not visible either:\n#<HASH-TABLE :TEST EQL :COUNT 1 {100F4BA883}>\n\nthis doesn't show what's inside the hash-table. During development it will require more steps to inspect what's inside (inspect, describe, alexandria:hash-table-alist, defining a non-portable print-object method…).\nserapeum:dict\nI like very much serapeum:dict, coupled with (serapeum:toggle-pretty-print-hash-table) (also the Cookbook).\nCL-USER> (serapeum:dict :a 1 :b 2 :c 3)\n;; => #<HASH-TABLE :TEST EQUAL :COUNT 3 {100F6012D3}>\n\nCL-USER> (serapeum:toggle-pretty-print-hash-table)\n\n;; print the above HT again:\nCL-USER> **\n(SERAPEUM:DICT\n :A 1\n :B 2\n :C 3\n ) \n\nNot only is it printed readably, but it allows to create the hash-table with initial elements at the same time (unlike make-hash-table) and you can read it back in. It's even easy to save such a structure on file.\nSerapeum is a solid library.\nNow, use hash-tables more easily.\n", "When to use a hash-table: You need to do fast (approximately \"constant time\") look-ups of data.\nWhen to use an a-list: You have a need to dynamically shadow data you pass on to functions.\nIf neither of these obviously apply, you have to make a choice. And then, possibly, benchmark your choice. And then evaluate if rewriting it using the other choice would be better. In some experimentation that someone else did, well over a decade ago, the trade-off between an a-list and a hash-map in most Common Lisp implementation is somewhere in the region of 5 to 20 keys.\nHowever, if you have a need to \"shadow\" bindings, for functions you call, an a-list does provide that \"for free\", and a hash-map does not. So if that is something that your code does a lot of, an a-list MAY be the better choice.\n* (defun lookup (alist key) (assoc key alist))\nLOOKUP\n* (lookup '((key1 . value1) (key2 . value2)) 'key1)\n(KEY1 . VALUE1)\n* (lookup '((key1 . value1) (key2 . value2)) 'key2)\n(KEY2 . VALUE2)\n* (lookup '((key2 . value3) (key1 . value1) (key2 . value2)) 'key2)\n(KEY2 . VALUE3)\n\n" ]
[ 5, 3, 2, 1 ]
[]
[]
[ "common_lisp", "data_structures", "hashtable", "sbcl" ]
stackoverflow_0074653707_common_lisp_data_structures_hashtable_sbcl.txt
Q: Can a Gnu Make variable substitution expression match more than one pattern? Say I have a list of files with mixed suffixes, e.g. .cpp and .c, and I want to make a list where each .cpp and each .c extension is changed to .o. I realize I could sequentially process my list multiple times, one for each extension of interest. But is there a way to use a variable substitution to do it in one step? A: You can use the usual functional style concatenation by repeated application: FILES := a.c b.cpp c.cxx OBJECTS := $(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(patsubst %.cxx,%.o,$(FILES)))) A: You could always just remove any suffix, like this: OBJECTS := $(addsuffix .o,$(basename $(FILES)))
Can a Gnu Make variable substitution expression match more than one pattern?
Say I have a list of files with mixed suffixes, e.g. .cpp and .c, and I want to make a list where each .cpp and each .c extension is changed to .o. I realize I could sequentially process my list multiple times, one for each extension of interest. But is there a way to use a variable substitution to do it in one step?
[ "You can use the usual functional style concatenation by repeated application:\nFILES := a.c b.cpp c.cxx\nOBJECTS := $(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(patsubst %.cxx,%.o,$(FILES))))\n\n", "You could always just remove any suffix, like this:\nOBJECTS := $(addsuffix .o,$(basename $(FILES)))\n\n" ]
[ 0, 0 ]
[]
[]
[ "gnu", "makefile", "variable_substitution" ]
stackoverflow_0074671192_gnu_makefile_variable_substitution.txt
Q: Custom Authorization Attribute in .Net Core 5 I have the code below for a custom Authorize attribute public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { } } the issue is there is no such thing as HttpContextBase. I have all the httpcontext usings as well but still yells at me. what am i doing wrong? A: You can write the code like this:- Instead of HttpContextBase you can use AuthorizationFilterContext as mentioned in example. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class CustomAuthorizeAttribute : Attribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { //your code logic.......... } } A: If we want to write custom logic to authorize the user, I suggest you could consider using AuthorizeAttribute and the IAuthorizationFilter. The IAuthorizationFilter provide the OnAuthorization method which could write some custom logic to authorize the user. More details, you could refer to below codes: public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { //Custom code ... //Return based on logic context.Result = new UnauthorizedResult(); } } Besides, asp.net core recommend using the new policy design. The basic idea behind the new approach is to use the new [Authorize] attribute to designate a "policy" (e.g. [Authorize( Policy = "YouNeedToBe18ToDoThis")]. More details, you could refer to this answer. A: The below code worked for me in .Net Core 5 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class CustomAuthorization : Attribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { Microsoft.Extensions.Primitives.StringValues tokens; context.HttpContext.Request.Headers.TryGetValue("saToken", out tokens); var token = tokens.FirstOrDefault(); if (!string.IsNullOrEmpty(token)) { var jwtService = (IJwtService)context.HttpContext.RequestServices.GetService(typeof(IJwtService)); if (jwtService.IsValidToken(token)) return; else { context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; context.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Invalid Token"; context.Result = new JsonResult("Invalid Token") { Value = new { Status = "Unauthorized", Message = "Invalid Token" } }; } } else { context.HttpContext.Response.StatusCode = (int)HttpStatusCode.ExpectationFailed; context.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Please Provide Token"; context.Result = new JsonResult("Please Provide Token") { Value = new { Status = "ExpectationFailed", Message = "Please Provide Token" } }; } } }
Custom Authorization Attribute in .Net Core 5
I have the code below for a custom Authorize attribute public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { } } the issue is there is no such thing as HttpContextBase. I have all the httpcontext usings as well but still yells at me. what am i doing wrong?
[ "You can write the code like this:-\nInstead of HttpContextBase you can use AuthorizationFilterContext as mentioned in example.\n[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]\npublic class CustomAuthorizeAttribute : Attribute, IAuthorizationFilter\n{\n public void OnAuthorization(AuthorizationFilterContext context)\n {\n //your code logic..........\n }\n}\n\n", "If we want to write custom logic to authorize the user, I suggest you could consider using AuthorizeAttribute and the IAuthorizationFilter.\nThe IAuthorizationFilter provide the OnAuthorization method which could write some custom logic to authorize the user.\nMore details, you could refer to below codes:\npublic class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter\n{\n public void OnAuthorization(AuthorizationFilterContext context)\n {\n //Custom code ...\n\n \n\n //Return based on logic\n context.Result = new UnauthorizedResult();\n }\n\n\n}\n\nBesides, asp.net core recommend using the new policy design. The basic idea behind the new approach is to use the new [Authorize] attribute to designate a \"policy\" (e.g. [Authorize( Policy = \"YouNeedToBe18ToDoThis\")].\nMore details, you could refer to this answer.\n", "The below code worked for me in .Net Core 5\n[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]\npublic class CustomAuthorization : Attribute, IAuthorizationFilter\n{\n public void OnAuthorization(AuthorizationFilterContext context)\n {\n Microsoft.Extensions.Primitives.StringValues tokens;\n context.HttpContext.Request.Headers.TryGetValue(\"saToken\", out tokens);\n var token = tokens.FirstOrDefault();\n\n if (!string.IsNullOrEmpty(token))\n {\n var jwtService = (IJwtService)context.HttpContext.RequestServices.GetService(typeof(IJwtService));\n\n if (jwtService.IsValidToken(token))\n return;\n else\n {\n context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;\n context.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = \"Invalid Token\";\n context.Result = new JsonResult(\"Invalid Token\")\n {\n Value = new { Status = \"Unauthorized\", Message = \"Invalid Token\" }\n };\n }\n }\n else\n {\n context.HttpContext.Response.StatusCode = (int)HttpStatusCode.ExpectationFailed;\n context.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = \"Please Provide Token\";\n context.Result = new JsonResult(\"Please Provide Token\")\n {\n Value = new { Status = \"ExpectationFailed\", Message = \"Please Provide Token\" }\n };\n }\n }\n}\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ ".net_core", "asp.net_core", "asp.net_core_5.0" ]
stackoverflow_0067259624_.net_core_asp.net_core_asp.net_core_5.0.txt
Q: Subquery inside whereIn I need to create a little bit more complicated query. In first step I have to select Galleries which belongs to User model from array (I use whereIn to solve this problem) and I have to filter this results. I'm using where and orWhere to this. It looks like this: return Galleries::whereIn('user_id', $this->myMethod() ->get() ->pluck('id') ) ->where('something', 0) ->orWhere('somethingElse', 1) ->orwhere(function($query) { /* Other my code*/ ); }) ->limit($limit); } Problem is that my results is not correct. If I have only whereIn, it display correct profiles but without filters. If I add where and OrWhere it displays User's profile which are not visible in this array. Could you help me? How can I use where and orWhere to result of whereIn? A: You got a wrong data because your query more like SELECT * FROM Galleries WHERE user_id in (ids) and something = 0 or somethingElse = 1 or blabla... You can try to move your filtering code into a where with callback function Galleries::whereIn('user_id', $this->myMethod() ->get() ->pluck('id') ) ->where(function($query){ $query->where('something', 0) ->orWhere('somethingElse', 1) ->orwhere(function($query) { /* Other my code*/ }); }) ->limit($limit); The sql statement will be like SELECT * FROM Galleries WHERE user_id in (ids) and (something = 0 or somethingElse = 1 or blabla...)
Subquery inside whereIn
I need to create a little bit more complicated query. In first step I have to select Galleries which belongs to User model from array (I use whereIn to solve this problem) and I have to filter this results. I'm using where and orWhere to this. It looks like this: return Galleries::whereIn('user_id', $this->myMethod() ->get() ->pluck('id') ) ->where('something', 0) ->orWhere('somethingElse', 1) ->orwhere(function($query) { /* Other my code*/ ); }) ->limit($limit); } Problem is that my results is not correct. If I have only whereIn, it display correct profiles but without filters. If I add where and OrWhere it displays User's profile which are not visible in this array. Could you help me? How can I use where and orWhere to result of whereIn?
[ "You got a wrong data because your query more like\nSELECT * FROM Galleries WHERE user_id in (ids) and something = 0 or somethingElse = 1 or blabla...\n\nYou can try to move your filtering code into a where with callback function\nGalleries::whereIn('user_id',\n $this->myMethod()\n ->get()\n ->pluck('id')\n )\n ->where(function($query){\n $query->where('something', 0)\n ->orWhere('somethingElse', 1)\n ->orwhere(function($query) {\n /* Other my code*/\n \n });\n })\n ->limit($limit);\n\nThe sql statement will be like\nSELECT * FROM Galleries WHERE user_id in (ids) and (something = 0 or somethingElse = 1 or blabla...)\n\n" ]
[ 0 ]
[]
[]
[ "backend", "laravel", "php" ]
stackoverflow_0074675474_backend_laravel_php.txt
Q: Updating thresholds on the ROC curve Using python, I built six machine learning models. The aim is to predict death in patients hospitalised with heart conditions. (Target feature: 1=Died, 0=Alive at the time of discharge form the hospital) I created a ROC curve incorporating AUC for six algorithms. Considering that the data is imbalanced, I would like to change the threshold for all models. How do I update the thresholds for each model before I plot the ROC curve? I have looked at similar posts on this platform, but still struggling. PS: I am not an experienced programmer, but a medical doctor using machine learning as a tool to risk stratify patients with heart conditions. model1= RandomForestClassifier() model2 = LogisticRegression() model3 = modelsvc model4 = XGBClassifier() model5 = annmodel1 model6= DecisionTreeClassifier() # fit model model1.fit(data_train_test['train']['X'], data_train_test['train']['y']) model2.fit(data_train_test['train']['X'], data_train_test['train']['y']) model3.fit(data_train_test['train']['X'], data_train_test['train']['y']) model4.fit(data_train_test['train']['X'], data_train_test['train']['y']) model5.fit(data_train_test['train']['X'], data_train_test['train']['y']) model6.fit(data_train_test['train']['X'], data_train_test['train']['y']) pred_prob1 = model1.predict_proba(data_train_test['test']['X']) pred_prob2 = model2.predict_proba(data_train_test['test']['X']) pred_prob3 = model3.predict_proba(data_train_test['test']['X']) pred_prob4 = model4.predict_proba(data_train_test['test']['X']) pred_prob5 = model5.predict(data_train_test['test']['X']) pred_prob6 = model6.predict_proba(data_train_test['test']['X']) # get the best threshold J = tpr1 - fpr1 ix = argmax(J) best_thresh = thresh1[ix] print('Best Threshold=%f, sensitivity = %.3f, specificity = %.3f, J=%.3f' % (best_thresh, tpr1[ix], 1-fpr1[ix], J[ix])) pred_prob1 = (model1.predict_proba(data_train_test['test']['X'])[:,1] >= best_thresh).astype(bool) # roc curve for models fpr1, tpr1, thresh1 = roc_curve(data_train_test['test']['y'], pred_prob1[:,1], pos_label=1) fpr2, tpr2, thresh2 = roc_curve(data_train_test['test']['y'], pred_prob2[:,1], pos_label=1) fpr3, tpr3, thresh3 = roc_curve(data_train_test['test']['y'], pred_prob3[:,1], pos_label=1) fpr4, tpr4, thresh4 = roc_curve(data_train_test['test']['y'], pred_prob4[:,1], pos_label=1) fpr5, tpr5, thresh5 = roc_curve(data_train_test['test']['y'], pred_prob5[:,0], pos_label=1) fpr6, tpr6, thresh6 = roc_curve(data_train_test['test']['y'], pred_prob6[:,1], pos_label=1) # roc curve for tpr = fpr random_probs = [0 for i in range(len(data_train_test['test']['y']))] p_fpr, p_tpr, _ = roc_curve(data_train_test['test']['y'], random_probs, pos_label=1) # auc scores auc_score1 = roc_auc_score(data_train_test['test']['y'], pred_prob1[:,1]) auc_score2 = roc_auc_score(data_train_test['test']['y'], pred_prob2[:,1]) auc_score3 = roc_auc_score(data_train_test['test']['y'], pred_prob3[:,1]) auc_score4 = roc_auc_score(data_train_test['test']['y'], pred_prob4[:,1]) auc_score5 = roc_auc_score(data_train_test['test']['y'], pred_prob5[:,0]) auc_score6 = roc_auc_score(data_train_test['test']['y'], pred_prob6[:,1]) print(auc_score1, auc_score2, auc_score3, auc_score4, auc_score5, auc_score6) # plot roc curves plt.plot(fpr1, tpr1, linestyle='--',color='orange', label='Random forest AUC=0.82') plt.plot(fpr2, tpr2, linestyle='--',color='green', label='Logistic regression AUC=0.78') plt.plot(fpr3, tpr3, linestyle='--',color='red', label='Support vector machines AUC=0.77') plt.plot(fpr4, tpr4, linestyle='--',color='lime', label='Extreme gradient boosting AUC=0.76') plt.plot(fpr5, tpr5, linestyle='--',color='cyan', label='Multi-layer perceptron AUC=0.75') plt.plot(fpr6, tpr6, linestyle='--',color='blue', label='Decision trees AUC=0.62') plt.plot(p_fpr, p_tpr, linestyle='--', color='black') # x label plt.xlabel('False Positive Rate') # y label plt.ylabel('True Positive rate') plt.legend(loc='best') plt.savefig('ROC',dpi=300) plt.show(); A: In order to change the threshold for your models, you can use the predict_proba method to get the predicted probabilities for each model, then adjust the threshold value at which a predicted probability is considered positive. For example: # get predicted probabilities for each model pred_probs1 = model1.predict_proba(data_train_test['test']['X']) pred_probs2 = model2.predict_proba(data_train_test['test']['X']) pred_probs3 = model3.predict_proba(data_train_test['test']['X']) pred_probs4 = model4.predict_proba(data_train_test['test']['X']) pred_probs5 = model5.predict_proba(data_train_test['test']['X']) pred_probs6 = model6.predict_proba(data_train_test['test']['X']) # set the new threshold value threshold = 0.5 # convert predicted probabilities to binary predictions based on the new threshold value preds1 = (pred_probs1[:,1] >= threshold).astype(bool) preds2 = (pred_probs2[:,1] >= threshold).astype(bool) preds3 = (pred_probs3[:,1] >= threshold).astype(bool) preds4 = (pred_probs4[:,1] >= threshold).astype(bool) EDIT # get the best threshold J = tpr1 - fpr1 ix = argmax(J) best_thresh = thresh1[ix] print('Best Threshold=%f, sensitivity = %.3f, specificity = %.3f, J=%.3f' % (best_thresh, tpr1[ix], 1-fpr1[ix], J[ix])) # predict using the best threshold pred_prob1 = model1.predict(data_train_test['test']['X'], threshold=best_thresh) # roc curve for models fpr1, tpr1, thresh1 = roc_curve(data_train_test['test']['y'], pred_prob1, pos_label=1) fpr2, tpr2, thresh2 = roc_curve(data_train_test['test']['y'], model2.predict(data_train_test['test']['X'], threshold=best_thresh), pos_label=1) fpr3, tpr3, thresh3 = roc_curve(data_train_test['test']['y'], model3.predict(data_train_test['test']['X'], threshold=best_thresh), pos_label=1) fpr4, tpr4, thresh4 = roc_curve(data_train_test['test']['y'], model4.predict(data_train_test['test']['X'], threshold=best_thresh), pos_label=1) fpr5, tpr5, thresh5 = roc_curve(data_train_test['test']['y'], model5.predict(data_train_test['test']['X'], threshold=best_thresh), pos_label=1) fpr6, tpr6, thresh6 = roc_curve(data_train_test['test']['y'], model6.predict(data_train_test['test']['X'], threshold=best_thresh), pos_label=1) # auc for models roc_auc1 = auc(fpr1, tpr1) roc_auc2 = auc(fpr2, tpr2) roc_auc3 = auc(fpr3, tpr3) roc_auc4 = auc(fpr4, tpr4) roc_auc5 = auc(fpr5, tpr5) roc_auc6 = auc(fpr6, tpr6) # plot roc curve plt.plot(fpr1, tpr1, 'b', label = 'Model 1 (area = %0.2f)' % roc_auc1) plt.plot(fpr2, tpr2, 'r', label = 'Model 2 (area = %0.2f)' % roc_auc2) ...
Updating thresholds on the ROC curve
Using python, I built six machine learning models. The aim is to predict death in patients hospitalised with heart conditions. (Target feature: 1=Died, 0=Alive at the time of discharge form the hospital) I created a ROC curve incorporating AUC for six algorithms. Considering that the data is imbalanced, I would like to change the threshold for all models. How do I update the thresholds for each model before I plot the ROC curve? I have looked at similar posts on this platform, but still struggling. PS: I am not an experienced programmer, but a medical doctor using machine learning as a tool to risk stratify patients with heart conditions. model1= RandomForestClassifier() model2 = LogisticRegression() model3 = modelsvc model4 = XGBClassifier() model5 = annmodel1 model6= DecisionTreeClassifier() # fit model model1.fit(data_train_test['train']['X'], data_train_test['train']['y']) model2.fit(data_train_test['train']['X'], data_train_test['train']['y']) model3.fit(data_train_test['train']['X'], data_train_test['train']['y']) model4.fit(data_train_test['train']['X'], data_train_test['train']['y']) model5.fit(data_train_test['train']['X'], data_train_test['train']['y']) model6.fit(data_train_test['train']['X'], data_train_test['train']['y']) pred_prob1 = model1.predict_proba(data_train_test['test']['X']) pred_prob2 = model2.predict_proba(data_train_test['test']['X']) pred_prob3 = model3.predict_proba(data_train_test['test']['X']) pred_prob4 = model4.predict_proba(data_train_test['test']['X']) pred_prob5 = model5.predict(data_train_test['test']['X']) pred_prob6 = model6.predict_proba(data_train_test['test']['X']) # get the best threshold J = tpr1 - fpr1 ix = argmax(J) best_thresh = thresh1[ix] print('Best Threshold=%f, sensitivity = %.3f, specificity = %.3f, J=%.3f' % (best_thresh, tpr1[ix], 1-fpr1[ix], J[ix])) pred_prob1 = (model1.predict_proba(data_train_test['test']['X'])[:,1] >= best_thresh).astype(bool) # roc curve for models fpr1, tpr1, thresh1 = roc_curve(data_train_test['test']['y'], pred_prob1[:,1], pos_label=1) fpr2, tpr2, thresh2 = roc_curve(data_train_test['test']['y'], pred_prob2[:,1], pos_label=1) fpr3, tpr3, thresh3 = roc_curve(data_train_test['test']['y'], pred_prob3[:,1], pos_label=1) fpr4, tpr4, thresh4 = roc_curve(data_train_test['test']['y'], pred_prob4[:,1], pos_label=1) fpr5, tpr5, thresh5 = roc_curve(data_train_test['test']['y'], pred_prob5[:,0], pos_label=1) fpr6, tpr6, thresh6 = roc_curve(data_train_test['test']['y'], pred_prob6[:,1], pos_label=1) # roc curve for tpr = fpr random_probs = [0 for i in range(len(data_train_test['test']['y']))] p_fpr, p_tpr, _ = roc_curve(data_train_test['test']['y'], random_probs, pos_label=1) # auc scores auc_score1 = roc_auc_score(data_train_test['test']['y'], pred_prob1[:,1]) auc_score2 = roc_auc_score(data_train_test['test']['y'], pred_prob2[:,1]) auc_score3 = roc_auc_score(data_train_test['test']['y'], pred_prob3[:,1]) auc_score4 = roc_auc_score(data_train_test['test']['y'], pred_prob4[:,1]) auc_score5 = roc_auc_score(data_train_test['test']['y'], pred_prob5[:,0]) auc_score6 = roc_auc_score(data_train_test['test']['y'], pred_prob6[:,1]) print(auc_score1, auc_score2, auc_score3, auc_score4, auc_score5, auc_score6) # plot roc curves plt.plot(fpr1, tpr1, linestyle='--',color='orange', label='Random forest AUC=0.82') plt.plot(fpr2, tpr2, linestyle='--',color='green', label='Logistic regression AUC=0.78') plt.plot(fpr3, tpr3, linestyle='--',color='red', label='Support vector machines AUC=0.77') plt.plot(fpr4, tpr4, linestyle='--',color='lime', label='Extreme gradient boosting AUC=0.76') plt.plot(fpr5, tpr5, linestyle='--',color='cyan', label='Multi-layer perceptron AUC=0.75') plt.plot(fpr6, tpr6, linestyle='--',color='blue', label='Decision trees AUC=0.62') plt.plot(p_fpr, p_tpr, linestyle='--', color='black') # x label plt.xlabel('False Positive Rate') # y label plt.ylabel('True Positive rate') plt.legend(loc='best') plt.savefig('ROC',dpi=300) plt.show();
[ "In order to change the threshold for your models, you can use the predict_proba method to get the predicted probabilities for each model, then adjust the threshold value at which a predicted probability is considered positive. For example:\n# get predicted probabilities for each model\npred_probs1 = model1.predict_proba(data_train_test['test']['X'])\npred_probs2 = model2.predict_proba(data_train_test['test']['X'])\npred_probs3 = model3.predict_proba(data_train_test['test']['X'])\npred_probs4 = model4.predict_proba(data_train_test['test']['X'])\npred_probs5 = model5.predict_proba(data_train_test['test']['X'])\npred_probs6 = model6.predict_proba(data_train_test['test']['X'])\n\n# set the new threshold value\nthreshold = 0.5\n\n# convert predicted probabilities to binary predictions based on the new threshold value\npreds1 = (pred_probs1[:,1] >= threshold).astype(bool)\npreds2 = (pred_probs2[:,1] >= threshold).astype(bool)\npreds3 = (pred_probs3[:,1] >= threshold).astype(bool)\npreds4 = (pred_probs4[:,1] >= threshold).astype(bool)\n\nEDIT\n# get the best threshold\nJ = tpr1 - fpr1\nix = argmax(J)\nbest_thresh = thresh1[ix]\nprint('Best Threshold=%f, sensitivity = %.3f, specificity = %.3f, J=%.3f' % (best_thresh, tpr1[ix], 1-fpr1[ix], J[ix]))\n\n# predict using the best threshold\npred_prob1 = model1.predict(data_train_test['test']['X'], threshold=best_thresh)\n\n# roc curve for models\nfpr1, tpr1, thresh1 = roc_curve(data_train_test['test']['y'], pred_prob1, pos_label=1)\nfpr2, tpr2, thresh2 = roc_curve(data_train_test['test']['y'], model2.predict(data_train_test['test']['X'], threshold=best_thresh), pos_label=1)\nfpr3, tpr3, thresh3 = roc_curve(data_train_test['test']['y'], model3.predict(data_train_test['test']['X'], threshold=best_thresh), pos_label=1)\nfpr4, tpr4, thresh4 = roc_curve(data_train_test['test']['y'], model4.predict(data_train_test['test']['X'], threshold=best_thresh), pos_label=1)\nfpr5, tpr5, thresh5 = roc_curve(data_train_test['test']['y'], model5.predict(data_train_test['test']['X'], threshold=best_thresh), pos_label=1)\nfpr6, tpr6, thresh6 = roc_curve(data_train_test['test']['y'], model6.predict(data_train_test['test']['X'], threshold=best_thresh), pos_label=1)\n\n# auc for models\nroc_auc1 = auc(fpr1, tpr1)\nroc_auc2 = auc(fpr2, tpr2)\nroc_auc3 = auc(fpr3, tpr3)\nroc_auc4 = auc(fpr4, tpr4)\nroc_auc5 = auc(fpr5, tpr5)\nroc_auc6 = auc(fpr6, tpr6)\n\n# plot roc curve\nplt.plot(fpr1, tpr1, 'b', label = 'Model 1 (area = %0.2f)' % roc_auc1)\nplt.plot(fpr2, tpr2, 'r', label = 'Model 2 (area = %0.2f)' % roc_auc2)\n...\n\n\n" ]
[ 0 ]
[]
[]
[ "python", "roc", "threshold" ]
stackoverflow_0074675684_python_roc_threshold.txt
Q: How to fix bash: cd: insfollow: No such file or directory in termux I'm writing a script using termux and I received an error saying " bash: cd: unfollow: No such file or directory" I was writing a script for gaining Instagram followers on termux. So I write this command " cd insfollow and got an error displayed as " bash: cd: insfollow: No such file or directory" Please help me how to fix it A: it clearly says there is no such directory create a directory or check if the dir is inside another folder
How to fix bash: cd: insfollow: No such file or directory in termux
I'm writing a script using termux and I received an error saying " bash: cd: unfollow: No such file or directory" I was writing a script for gaining Instagram followers on termux. So I write this command " cd insfollow and got an error displayed as " bash: cd: insfollow: No such file or directory" Please help me how to fix it
[ "it clearly says there is no such directory\ncreate a directory or check if the dir is inside another folder\n" ]
[ 0 ]
[]
[]
[ "termux" ]
stackoverflow_0074616261_termux.txt
Q: Javascript clear object and append after I am creating a forech that calculates the percentage of discount of two values and then it replaces the new percentage with the old percentage. Everything is going well until the last line: when I use APPEND it adds the percentage value after the value of the old percentage. I need him to replace. I tried replace but returns badgetPerc is not a function. Javascript: var product = document.querySelectorAll(".product"); product.forEach((item) => { var price = item.querySelector(".price del span bdi"); var priceText = price.textContent; var priceSemReal = priceText.replace("R$", ""); var priceNumber = parseFloat(priceSemReal); var priceDisc = item.querySelector(".wc-simulador-parcelas-offer span bdi"); var priceDiscText = priceDisc.textContent; var priceDiscSemReal = priceDiscText.replace("R$", ""); var priceDiscNumber = parseFloat(priceDiscSemReal); var resultado = ((priceNumber - priceDiscNumber) / priceNumber) * 100; console.log(resultado); var badgetPerc = item.querySelector(".isb_percentage"); console.log(badgetPerc); badgetPerc.append(resultado); }); HTML: <div class="product"> <div class="isb_sale_percentage"> <span class="isb_percentage"> 10 </span> <span class="isb_percentage_text"> % </span> </div> <span class="price"> <del aria-hidden="true"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>1000,00</bdi> </span> </del> <span class="wc-simulador-parcelas-offer"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>500,00</bdi> </span> <span class="wc-simulador-parcelas-detalhes-valor">no PIX </span> </span> </span> </div> <div class="product"> <div class="isb_sale_percentage"> <span class="isb_percentage"> 10 </span> <span class="isb_percentage_text"> % </span> </div> <span class="price"> <del aria-hidden="true"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>500,00</bdi> </span> </del> <span class="wc-simulador-parcelas-offer"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>50,00</bdi> </span> <span class="wc-simulador-parcelas-detalhes-valor">no PIX </span> </span> </span> </div> <div class="product"> <div class="isb_sale_percentage"> <span class="isb_percentage"> 10 </span> <span class="isb_percentage_text"> % </span> </div> <span class="price"> <del aria-hidden="true"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>100,00</bdi> </span> </del> <span class="wc-simulador-parcelas-offer"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>90,00</bdi> </span> <span class="wc-simulador-parcelas-detalhes-valor">no PIX </span> </span> </span> </div> link: https://jsfiddle.net/castordida/bupmwe8x/1/ So the result: 10 50% 10 90% 10 10% what i expected: 50% 90% 10% A: To replace the text inside the badgetPerc element with the new percentage value, you can use the innerHTML property of the element instead of the append() method. The innerHTML property sets the contents of the element to the specified value, replacing any existing content. Here is an example of how you might use the innerHTML property to replace the text in the `badgetPerc element with the new percentage value: badgetPerc.innerHTML = resultado;
Javascript clear object and append after
I am creating a forech that calculates the percentage of discount of two values and then it replaces the new percentage with the old percentage. Everything is going well until the last line: when I use APPEND it adds the percentage value after the value of the old percentage. I need him to replace. I tried replace but returns badgetPerc is not a function. Javascript: var product = document.querySelectorAll(".product"); product.forEach((item) => { var price = item.querySelector(".price del span bdi"); var priceText = price.textContent; var priceSemReal = priceText.replace("R$", ""); var priceNumber = parseFloat(priceSemReal); var priceDisc = item.querySelector(".wc-simulador-parcelas-offer span bdi"); var priceDiscText = priceDisc.textContent; var priceDiscSemReal = priceDiscText.replace("R$", ""); var priceDiscNumber = parseFloat(priceDiscSemReal); var resultado = ((priceNumber - priceDiscNumber) / priceNumber) * 100; console.log(resultado); var badgetPerc = item.querySelector(".isb_percentage"); console.log(badgetPerc); badgetPerc.append(resultado); }); HTML: <div class="product"> <div class="isb_sale_percentage"> <span class="isb_percentage"> 10 </span> <span class="isb_percentage_text"> % </span> </div> <span class="price"> <del aria-hidden="true"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>1000,00</bdi> </span> </del> <span class="wc-simulador-parcelas-offer"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>500,00</bdi> </span> <span class="wc-simulador-parcelas-detalhes-valor">no PIX </span> </span> </span> </div> <div class="product"> <div class="isb_sale_percentage"> <span class="isb_percentage"> 10 </span> <span class="isb_percentage_text"> % </span> </div> <span class="price"> <del aria-hidden="true"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>500,00</bdi> </span> </del> <span class="wc-simulador-parcelas-offer"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>50,00</bdi> </span> <span class="wc-simulador-parcelas-detalhes-valor">no PIX </span> </span> </span> </div> <div class="product"> <div class="isb_sale_percentage"> <span class="isb_percentage"> 10 </span> <span class="isb_percentage_text"> % </span> </div> <span class="price"> <del aria-hidden="true"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>100,00</bdi> </span> </del> <span class="wc-simulador-parcelas-offer"> <span class="woocommerce-Price-amount amount"> <bdi><span class="woocommerce-Price-currencySymbol">R$</span>90,00</bdi> </span> <span class="wc-simulador-parcelas-detalhes-valor">no PIX </span> </span> </span> </div> link: https://jsfiddle.net/castordida/bupmwe8x/1/ So the result: 10 50% 10 90% 10 10% what i expected: 50% 90% 10%
[ "To replace the text inside the badgetPerc element with the new percentage value, you can use the innerHTML property of the element instead of the append() method. The innerHTML property sets the contents of the element to the specified value, replacing any existing content.\nHere is an example of how you might use the innerHTML property to replace the text in the `badgetPerc element with the new percentage value:\nbadgetPerc.innerHTML = resultado;\n\n" ]
[ 1 ]
[]
[]
[ "javascript" ]
stackoverflow_0074675534_javascript.txt
Q: Why isn't there just one star on a line? public class SA { public static void main(String[] args) { for(int i=1;i <=5;i++){ for(int j=1;j<=i;j++) System.out.print("*"); System.out.println(); } } } Why is one more star added to each line? Why isn't there just one star in a row? A: The outer loop iterates from 1 to 5, and the inner loop iterates from 1 to the current value of the outer loop. For each iteration of the inner loop, the program prints a "*" character to the console. After the inner loop completes, the program moves to the next line and starts the outer loop again. This continues until the outer loop completes, at which point the program ends.
Why isn't there just one star on a line?
public class SA { public static void main(String[] args) { for(int i=1;i <=5;i++){ for(int j=1;j<=i;j++) System.out.print("*"); System.out.println(); } } } Why is one more star added to each line? Why isn't there just one star in a row?
[ "The outer loop iterates from 1 to 5, and the inner loop iterates from 1 to the current value of the outer loop. For each iteration of the inner loop, the program prints a \"*\" character to the console. After the inner loop completes, the program moves to the next line and starts the outer loop again. This continues until the outer loop completes, at which point the program ends.\n" ]
[ 0 ]
[]
[]
[ "java", "loops", "nested", "nested_for_loop" ]
stackoverflow_0074675710_java_loops_nested_nested_for_loop.txt
Q: How to implement carousel (card slider) with Jetpack compose? I had been using this library to implement carousel in the View system. How do I implement carousel in Jetpack Compose? A: Well... It depends of the which feature you need from this library, but for "simple" pager you can use Pager Accompanist library. https://github.com/google/accompanist/tree/main/pager And you can check the docs here: https://google.github.io/accompanist/pager/ A: Try this way Using HorizontalPager @Composable fun BuildLoginSlider() { val pagerState = rememberPagerState(initialPage = 1) val sliderList = listOf() HorizontalPager( count = sliderList.size, state = pagerState, contentPadding = PaddingValues(horizontal = 150.dp), verticalAlignment = Alignment.CenterVertically, ) { page -> Card( colors = CardDefaults.cardColors(Color.Transparent), shape = RoundedCornerShape(10.dp), elevation = CardDefaults.cardElevation(0.dp), modifier = Modifier .graphicsLayer { val pageOffset = calculateCurrentOffsetForPage(page).absoluteValue lerp( start = 0.85f, stop = 1f, fraction = 1f - pageOffset.coerceIn(0f, 1f) ).also { scale -> scaleX = scale scaleY = scale } alpha = lerp( start = 0.5f, stop = 1f, fraction = 1f - pageOffset.coerceIn(0f, 1f) ) } // .aspectRatio(0.5f) ) { AsyncImage( model = Builder(LocalContext.current) .data(sliderList[page]) .crossfade(true) .scale(FILL) .build(), contentDescription = null, modifier = Modifier .offset { // Calculate the offset for the current page from the // scroll position val pageOffset = [email protected](page) // Then use it as a multiplier to apply an offset IntOffset( x = (70.dp * pageOffset).roundToPx(), y = 0, ) } ) } } } OUTPUT
How to implement carousel (card slider) with Jetpack compose?
I had been using this library to implement carousel in the View system. How do I implement carousel in Jetpack Compose?
[ "Well... It depends of the which feature you need from this library, but for \"simple\" pager you can use Pager Accompanist library.\nhttps://github.com/google/accompanist/tree/main/pager\nAnd you can check the docs here:\nhttps://google.github.io/accompanist/pager/\n", "Try this way Using HorizontalPager\n@Composable\nfun BuildLoginSlider() {\n val pagerState = rememberPagerState(initialPage = 1)\n val sliderList = listOf()\n\n HorizontalPager(\n count = sliderList.size, state = pagerState,\n contentPadding = PaddingValues(horizontal = 150.dp),\n verticalAlignment = Alignment.CenterVertically,\n ) { page ->\n Card(\n colors = CardDefaults.cardColors(Color.Transparent),\n shape = RoundedCornerShape(10.dp),\n elevation = CardDefaults.cardElevation(0.dp),\n modifier = Modifier\n .graphicsLayer {\n\n val pageOffset = calculateCurrentOffsetForPage(page).absoluteValue\n\n lerp(\n start = 0.85f,\n stop = 1f,\n fraction = 1f - pageOffset.coerceIn(0f, 1f)\n ).also { scale ->\n scaleX = scale\n scaleY = scale\n }\n alpha = lerp(\n start = 0.5f,\n stop = 1f,\n fraction = 1f - pageOffset.coerceIn(0f, 1f)\n )\n }\n // .aspectRatio(0.5f)\n ) {\n AsyncImage(\n model = Builder(LocalContext.current)\n .data(sliderList[page])\n .crossfade(true)\n .scale(FILL)\n .build(),\n contentDescription = null,\n modifier = Modifier\n .offset {\n // Calculate the offset for the current page from the\n // scroll position\n val pageOffset =\n [email protected](page)\n // Then use it as a multiplier to apply an offset\n IntOffset(\n x = (70.dp * pageOffset).roundToPx(),\n y = 0,\n )\n }\n )\n }\n\n }\n}\n\nOUTPUT\n\n" ]
[ 11, 0 ]
[]
[]
[ "android", "android_jetpack_compose", "carousel" ]
stackoverflow_0067431333_android_android_jetpack_compose_carousel.txt
Q: How can I get the values of cartItem and make a n order? How can I get the obj of the the cartItem and place an order? here's how my models.py look like. class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) cart = models.ForeignKey('Cart', on_delete=models.CASCADE) selected = models.BooleanField(default=False) A: At frontend - first get the list of Cart Select a cart Form an object with desired values. Send this object to django.
How can I get the values of cartItem and make a n order?
How can I get the obj of the the cartItem and place an order? here's how my models.py look like. class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) cart = models.ForeignKey('Cart', on_delete=models.CASCADE) selected = models.BooleanField(default=False)
[ "At frontend -\n\nfirst get the list of Cart\nSelect a cart\nForm an object with desired values.\nSend this object to django.\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "rest", "shopping_cart" ]
stackoverflow_0074672832_django_django_rest_framework_rest_shopping_cart.txt
Q: What could be a solution for repository management of code templates I'm trying to figure a solution to manage a structure for one-way sync of files across several repositories (in GitHub). The issue is as follows: I want to have one repository to store code templates (boilerplates). I want to have a second repository that contains alternate code created from those templates I want to have a one-way sync between the directories. I.e., when updating the templates, the changes should be reflected in the in the second repository as well. When further changes to the code in the second directory they should not appear in the first one. I want to be able to navigate large amounts of templates easily (without having to many branches or repositories to be used as submodules). For example given this structure: REPO1 template-1 index.html template-2 template-3 REPO2 alice index.html (from template-1) bob index.html (from template-2) eve Consider the following code as index.html: <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css"> </head> <body> <script src="index.js"></script> </body> </html> And say Alice has duplicated it and created her copy of index.html as: <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css"> </head> <body> <script src="index.js"></script> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi non nulla lectus.</p> </body> </html> When I add following code to the original index.hrml <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> The intended solution should allow Alice to get this increment without overwriting the paragraph which is unique to her file. I've tried using submodules, adding several remotes, and using github actions to sync the relevant files, but none of those were able to sync specific files (only the entire repositories) or do so without overwriting the changes. A: One potential solution to this problem would be to use a feature of Git called "subtrees". Subtrees allow you to merge the contents of one repository into another as a sub-directory. This allows you to keep the code templates in a separate repository and merge them into your second repository as needed, without overwriting any local changes you may have made. To use subtrees, you would first need to add the templates repository as a remote in your second repository: $ git remote add templates <url-of-templates-repo> Next, you would need to pull the templates repository into your second repository as a subtree. In this example, we will pull the templates into a directory called "boilerplates" in the second repository: git subtree add --prefix=boilerplates templates master This will pull the contents of the templates repository into the "boilerplates" directory in your second repository. You can then use the templates as needed, without overwriting any local changes you may have made. To update the templates in your second repository, you can use the following command: $ git subtree pull --prefix=boilerplates templates master This will pull any changes made to the templates repository into your second repository, without overwriting any local changes. You can also use subtrees to push changes you make to the templates in your second repository back to the templates repository. For example, if you make changes to the "template-1" directory in your second repository, you can push those changes back to the templates repository using the following command: $ git subtree push --prefix=boilerplates/template-1 templates master This will push the changes you made to the "template-1" directory in your second repository back to the templates repository, without affecting any other files in the templates repository. Overall, using subtrees can allow you to easily manage the relationship between your templates and second repositories, while still maintaining the ability to make local changes without overwriting updates from the templates repository.
What could be a solution for repository management of code templates
I'm trying to figure a solution to manage a structure for one-way sync of files across several repositories (in GitHub). The issue is as follows: I want to have one repository to store code templates (boilerplates). I want to have a second repository that contains alternate code created from those templates I want to have a one-way sync between the directories. I.e., when updating the templates, the changes should be reflected in the in the second repository as well. When further changes to the code in the second directory they should not appear in the first one. I want to be able to navigate large amounts of templates easily (without having to many branches or repositories to be used as submodules). For example given this structure: REPO1 template-1 index.html template-2 template-3 REPO2 alice index.html (from template-1) bob index.html (from template-2) eve Consider the following code as index.html: <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css"> </head> <body> <script src="index.js"></script> </body> </html> And say Alice has duplicated it and created her copy of index.html as: <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css"> </head> <body> <script src="index.js"></script> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi non nulla lectus.</p> </body> </html> When I add following code to the original index.hrml <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> The intended solution should allow Alice to get this increment without overwriting the paragraph which is unique to her file. I've tried using submodules, adding several remotes, and using github actions to sync the relevant files, but none of those were able to sync specific files (only the entire repositories) or do so without overwriting the changes.
[ "One potential solution to this problem would be to use a feature of Git called \"subtrees\". Subtrees allow you to merge the contents of one repository into another as a sub-directory. This allows you to keep the code templates in a separate repository and merge them into your second repository as needed, without overwriting any local changes you may have made.\nTo use subtrees, you would first need to add the templates repository as a remote in your second repository:\n$ git remote add templates <url-of-templates-repo>\n\nNext, you would need to pull the templates repository into your second repository as a subtree. In this example, we will pull the templates into a directory called \"boilerplates\" in the second repository:\ngit subtree add --prefix=boilerplates templates master\n\nThis will pull the contents of the templates repository into the \"boilerplates\" directory in your second repository. You can then use the templates as needed, without overwriting any local changes you may have made.\nTo update the templates in your second repository, you can use the following command:\n$ git subtree pull --prefix=boilerplates templates master\n\n\nThis will pull any changes made to the templates repository into your second repository, without overwriting any local changes.\nYou can also use subtrees to push changes you make to the templates in your second repository back to the templates repository. For example, if you make changes to the \"template-1\" directory in your second repository, you can push those changes back to the templates repository using the following command:\n$ git subtree push --prefix=boilerplates/template-1 templates master\n\n\nThis will push the changes you made to the \"template-1\" directory in your second repository back to the templates repository, without affecting any other files in the templates repository.\nOverall, using subtrees can allow you to easily manage the relationship between your templates and second repositories, while still maintaining the ability to make local changes without overwriting updates from the templates repository.\n" ]
[ 0 ]
[]
[]
[ "continuous_integration", "github", "github_actions" ]
stackoverflow_0074675683_continuous_integration_github_github_actions.txt
Q: ActiveX control '{XXX-XXX}' is not registered in this computer. Register the control and try again While migration of old application, which built on VC6.0 framework. I am getting below error message when I tried to open Dialog box from Resource View windows. The ActiveX control 6262D3A0-531B-11CF-91F6-C2863C338E30', is not registered on this computer. Register the control and try again. Please suggest step to open the dialog. (Dialog having ActiveX control, which is absolute in latest window OS i.e. Window 10/11) I tried to find ActiveX components on MS site, but no luck. A: Two possibilities come to mind after you have ruled out that this is a standard Microsoft component: It might be that this is a 3rd party component someone once bought. Look for an .ocx that might be present in the project files in a 3rd party folder. It could help, if you disclose the relevant lines in the resource file, so people have the chance to identify the component and with some luck tell you where you could get it. There is a chance that this is a custom-made component: Look for a subproject and build it. In any case register the component before use, for example regsvr32.exe path\to\your\component\the_comp.ocx. (On a 64-bit Windows, you might want to use C:\Windows\SysWOW64\regsvr32.exe, suppose this is a x86 project.)
ActiveX control '{XXX-XXX}' is not registered in this computer. Register the control and try again
While migration of old application, which built on VC6.0 framework. I am getting below error message when I tried to open Dialog box from Resource View windows. The ActiveX control 6262D3A0-531B-11CF-91F6-C2863C338E30', is not registered on this computer. Register the control and try again. Please suggest step to open the dialog. (Dialog having ActiveX control, which is absolute in latest window OS i.e. Window 10/11) I tried to find ActiveX components on MS site, but no luck.
[ "Two possibilities come to mind after you have ruled out that this is a standard Microsoft component:\n\nIt might be that this is a 3rd party component someone once bought. Look for an .ocx that might be present in the project files in a 3rd party folder. It could help, if you disclose the relevant lines in the resource file, so people have the chance to identify the component and with some luck tell you where you could get it.\nThere is a chance that this is a custom-made component: Look for a subproject and build it.\n\nIn any case register the component before use, for example regsvr32.exe path\\to\\your\\component\\the_comp.ocx. (On a 64-bit Windows, you might want to use C:\\Windows\\SysWOW64\\regsvr32.exe, suppose this is a x86 project.)\n" ]
[ 0 ]
[]
[]
[ "mfc", "visual_c++" ]
stackoverflow_0074664580_mfc_visual_c++.txt
Q: Error Message when trying to scrape FBref webpage Disclaimer: I am still a python beginner and trying to scrape for the first time. I am trying to scrape player stats from the current (22/23) Champions League season and convert it to a .csv file. If you see any other obvious errors then please point it out. Website: https://fbref.com/en/comps/8/stats/Champions-League-Stats I tried to change the following code to get it working for my needs but I am not successful: https://colab.research.google.com/drive/1PoHtZWcy8WaU1hnWmL7eCVUbxzci3-fr#scrollTo=2qYGN7pfk3gK There is the possibility to simply directly download a .csv file but I need to actually scrape the webpage. This is my (modified from above) code and I get the following error message and don't know how to resolve the problem: import requests from bs4 import BeautifulSoup import pandas as pd import re # Functions to get the data in a dataframe using BeautifulSoup def get_tables(url, text): res = requests.get(url) ## The next two lines get around the issue with comments breaking the parsing. comm = re.compile("<!--|-->") soup = BeautifulSoup(comm.sub("", res.text), 'lxml') all_tables = soup.findAll("table") player_table = all_tables[2] if text == 'for': return player_table if text != 'for': pass def get_frame(features, player_table): pre_df_player = dict() features_wanted_player = features rows_player = player_table.find_all('tr') for row in rows_player: if (row.find('th', {"scope": "row"}) is not None): for f in features_wanted_player: cell = row.find("td", {"data-stat": f}) a = cell.data.text().encode() text = a.decode("utf-8") if (text == ''): text = '0' if ((f != 'player') & (f != 'nationality') & (f != 'position') & (f != 'squad') & (f != 'age') & ( f != 'birth_year')): text = float(text.replace(',', '')) if f in pre_df_player: pre_df_player[f].append(text) else: pre_df_player[f] = [text] df_player = pd.DataFrame.from_dict(pre_df_player) return df_player def frame_for_category(category, top, end, features): url = (top + category + end) player_table = get_tables(url, 'for') df_player = get_frame(features, player_table) return df_player # Function to get the player data for outfield player, includes all categories - standard stats, shooting # passing, passing types, goal and shot creation, defensive actions, possession, and miscallaneous def get_outfield_data(top, end): df1 = frame_for_category('stats', top, end, stats) df2 = frame_for_category('shooting', top, end, shooting2) df3 = frame_for_category('passing', top, end, passing2) df4 = frame_for_category('passing_types', top, end, passing_types2) df5 = frame_for_category('gca', top, end, gca2) df6 = frame_for_category('defense', top, end, defense2) df7 = frame_for_category('possession', top, end, possession2) df8 = frame_for_category('misc', top, end, misc2) df = pd.concat([df1, df2, df3, df4, df5, df6, df7, df8], axis=1) df = df.loc[:, ~df.columns.duplicated()] return df # Function to get keeping and advance goalkeeping data def get_keeper_data(top, end): df1 = frame_for_category('keepers', top, end, keepers) df2 = frame_for_category('keepersadv', top, end, keepersadv2) df = pd.concat([df1, df2], axis=1) df = df.loc[:, ~df.columns.duplicated()] return df #This cell is to get the outfield player data for any competition #Go to the 'Standard stats' page of the league #For Champions League 2022/23, the link is this: https://fbref.com/en/comps/8/stats/Champions-League-Stats #Remove the 'stats', and pass the first and third part of the link as parameters like below df_outfield = get_outfield_data('https://fbref.com/en/comps/8/','/Champions-League-Stats') #Save csv file to Desktop df_outfield.to_csv('CL2022_23_Outfield.csv',index=False) df_outfield Error Message: Traceback (most recent call last): File "/home/student/Pycharm/Scraping FBREF.py", line 123, in <module> df_outfield = get_outfield_data('https://fbref.com/en/comps/8/','/Champions-League-Stats') File "/home/student/Pycharm/Scraping FBREF.py", line 97, in get_outfield_data df1 = frame_for_category('stats', top, end, stats) File "/home/student/Pycharm/Scraping FBREF.py", line 90, in frame_for_category df_player = get_frame(features, player_table) File "/home/student/Pycharm/Scraping FBREF.py", line 72, in get_frame a = cell.data.text().encode() AttributeError: 'NoneType' object has no attribute 'text' A: Found the solution myself. I had to add an if-statement to only encode when the cell is not None: for f in features_wanted_player: cell = row.find("td", {"data-stat": f}) if cell is not None: a = cell.text.strip().encode() Now it works perfectly fine.
Error Message when trying to scrape FBref webpage
Disclaimer: I am still a python beginner and trying to scrape for the first time. I am trying to scrape player stats from the current (22/23) Champions League season and convert it to a .csv file. If you see any other obvious errors then please point it out. Website: https://fbref.com/en/comps/8/stats/Champions-League-Stats I tried to change the following code to get it working for my needs but I am not successful: https://colab.research.google.com/drive/1PoHtZWcy8WaU1hnWmL7eCVUbxzci3-fr#scrollTo=2qYGN7pfk3gK There is the possibility to simply directly download a .csv file but I need to actually scrape the webpage. This is my (modified from above) code and I get the following error message and don't know how to resolve the problem: import requests from bs4 import BeautifulSoup import pandas as pd import re # Functions to get the data in a dataframe using BeautifulSoup def get_tables(url, text): res = requests.get(url) ## The next two lines get around the issue with comments breaking the parsing. comm = re.compile("<!--|-->") soup = BeautifulSoup(comm.sub("", res.text), 'lxml') all_tables = soup.findAll("table") player_table = all_tables[2] if text == 'for': return player_table if text != 'for': pass def get_frame(features, player_table): pre_df_player = dict() features_wanted_player = features rows_player = player_table.find_all('tr') for row in rows_player: if (row.find('th', {"scope": "row"}) is not None): for f in features_wanted_player: cell = row.find("td", {"data-stat": f}) a = cell.data.text().encode() text = a.decode("utf-8") if (text == ''): text = '0' if ((f != 'player') & (f != 'nationality') & (f != 'position') & (f != 'squad') & (f != 'age') & ( f != 'birth_year')): text = float(text.replace(',', '')) if f in pre_df_player: pre_df_player[f].append(text) else: pre_df_player[f] = [text] df_player = pd.DataFrame.from_dict(pre_df_player) return df_player def frame_for_category(category, top, end, features): url = (top + category + end) player_table = get_tables(url, 'for') df_player = get_frame(features, player_table) return df_player # Function to get the player data for outfield player, includes all categories - standard stats, shooting # passing, passing types, goal and shot creation, defensive actions, possession, and miscallaneous def get_outfield_data(top, end): df1 = frame_for_category('stats', top, end, stats) df2 = frame_for_category('shooting', top, end, shooting2) df3 = frame_for_category('passing', top, end, passing2) df4 = frame_for_category('passing_types', top, end, passing_types2) df5 = frame_for_category('gca', top, end, gca2) df6 = frame_for_category('defense', top, end, defense2) df7 = frame_for_category('possession', top, end, possession2) df8 = frame_for_category('misc', top, end, misc2) df = pd.concat([df1, df2, df3, df4, df5, df6, df7, df8], axis=1) df = df.loc[:, ~df.columns.duplicated()] return df # Function to get keeping and advance goalkeeping data def get_keeper_data(top, end): df1 = frame_for_category('keepers', top, end, keepers) df2 = frame_for_category('keepersadv', top, end, keepersadv2) df = pd.concat([df1, df2], axis=1) df = df.loc[:, ~df.columns.duplicated()] return df #This cell is to get the outfield player data for any competition #Go to the 'Standard stats' page of the league #For Champions League 2022/23, the link is this: https://fbref.com/en/comps/8/stats/Champions-League-Stats #Remove the 'stats', and pass the first and third part of the link as parameters like below df_outfield = get_outfield_data('https://fbref.com/en/comps/8/','/Champions-League-Stats') #Save csv file to Desktop df_outfield.to_csv('CL2022_23_Outfield.csv',index=False) df_outfield Error Message: Traceback (most recent call last): File "/home/student/Pycharm/Scraping FBREF.py", line 123, in <module> df_outfield = get_outfield_data('https://fbref.com/en/comps/8/','/Champions-League-Stats') File "/home/student/Pycharm/Scraping FBREF.py", line 97, in get_outfield_data df1 = frame_for_category('stats', top, end, stats) File "/home/student/Pycharm/Scraping FBREF.py", line 90, in frame_for_category df_player = get_frame(features, player_table) File "/home/student/Pycharm/Scraping FBREF.py", line 72, in get_frame a = cell.data.text().encode() AttributeError: 'NoneType' object has no attribute 'text'
[ "Found the solution myself. I had to add an if-statement to only encode when the cell is not None:\n for f in features_wanted_player:\n cell = row.find(\"td\", {\"data-stat\": f})\n if cell is not None:\n a = cell.text.strip().encode()\n\nNow it works perfectly fine.\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074337950_beautifulsoup_python_web_scraping.txt
Q: How to read keyboard input? I would like to read data from the keyboard in Python. I tried this code: nb = input('Choose a number') print('Number%s \n' % (nb)) But it doesn't work, either with eclipse nor in the terminal, it's always stop of the question. I can type a number but after nothing happen. Do you know why? A: Use input('Enter your input:') if you use Python 3. And if you want to have a numeric value, just convert it: try: mode = int(input('Input:')) except ValueError: print("Not a number") If you use Python 2, you need to use raw_input instead of input. A: It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)... This is basically correct: nb = input('Choose a number: ') The problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function raw_input: nb = raw_input('Choose a number: ') If you want to convert that to a number, then you should try: number = int(nb) ... though you need to take into account that this can raise an exception: try: number = int(nb) except ValueError: print("Invalid number") And if you want to print the number using formatting, in Python 3 str.format() is recommended: print("Number: {0}\n".format(number)) Instead of: print('Number %s \n' % (nb)) But both options (str.format() and %) do work in both Python 2.7 and Python 3. A: Non-blocking, multi-threaded example: As blocking on keyboard input (since the input() function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive. I use this technique in my eRCaGuy_PyTerm serial terminal program here (search the code for input()). This works by creating one thread to run in the background, continually calling input() and then passing any data it receives to a queue. In this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue. 1. Bare Python 3 code example (no comments): import threading import queue import time def read_kbd_input(inputQueue): print('Ready for keyboard input:') while (True): input_str = input() inputQueue.put(input_str) def main(): EXIT_COMMAND = "exit" inputQueue = queue.Queue() inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True) inputThread.start() while (True): if (inputQueue.qsize() > 0): input_str = inputQueue.get() print("input_str = {}".format(input_str)) if (input_str == EXIT_COMMAND): print("Exiting serial terminal.") break # Insert your code here to do whatever you want with the input_str. # The rest of your program goes here. time.sleep(0.01) print("End.") if (__name__ == '__main__'): main() 2. Same Python 3 code as above, but with extensive explanatory comments: """ read_keyboard_input.py Gabriel Staples www.ElectricRCAircraftGuy.com 14 Nov. 2018 References: - https://pyserial.readthedocs.io/en/latest/pyserial_api.html - *****https://www.tutorialspoint.com/python/python_multithreading.htm - *****https://en.wikibooks.org/wiki/Python_Programming/Threading - https://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass - https://docs.python.org/3/library/queue.html - https://docs.python.org/3.7/library/threading.html To install PySerial: `sudo python3 -m pip install pyserial` To run this program: `python3 this_filename.py` """ import threading import queue import time def read_kbd_input(inputQueue): print('Ready for keyboard input:') while (True): # Receive keyboard input from user. input_str = input() # Enqueue this input string. # Note: Lock not required here since we are only calling a single Queue method, not a sequence of them # which would otherwise need to be treated as one atomic operation. inputQueue.put(input_str) def main(): EXIT_COMMAND = "exit" # Command to exit this program # The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue # method calls in a row. Use this if you have such a need, as follows: # 1. Pass queueLock as an input parameter to whichever function requires it. # 2. Call queueLock.acquire() to obtain the lock. # 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling # inputQueue.qsize(), followed by inputQueue.put(), for example. # 4. Call queueLock.release() to release the lock. # queueLock = threading.Lock() #Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread. inputQueue = queue.Queue() # Create & start a thread to read keyboard inputs. # Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since # this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit. inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True) inputThread.start() # Main loop while (True): # Read keyboard inputs # Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure # multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this # example program, no locks are required. if (inputQueue.qsize() > 0): input_str = inputQueue.get() print("input_str = {}".format(input_str)) if (input_str == EXIT_COMMAND): print("Exiting serial terminal.") break # exit the while loop # Insert your code here to do whatever you want with the input_str. # The rest of your program goes here. # Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC. time.sleep(0.01) print("End.") # If you run this Python file directly (ex: via `python3 this_filename.py`), do the following: if (__name__ == '__main__'): main() Sample output: $ python3 read_keyboard_input.py Ready for keyboard input: hey input_str = hey hello input_str = hello 7000 input_str = 7000 exit input_str = exit Exiting serial terminal. End. The Python Queue library is thread-safe: Note that Queue.put() and Queue.get() and other Queue class methods are all thread-safe! (This is unlike queues and other containers in the standard template library in C++!) Since the Python Queue class and its methods are thread-safe, that means they implement all the internal locking semantics required for inter-thread operations, so each function call in the queue class can be considered as a single, atomic operation. See the notes at the top of the documentation: https://docs.python.org/3/library/queue.html (emphasis added): The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. References: https://pyserial.readthedocs.io/en/latest/pyserial_api.html *****https://www.tutorialspoint.com/python/python_multithreading.htm *****https://en.wikibooks.org/wiki/Python_Programming/Threading Python: How do I make a subclass from a superclass? https://docs.python.org/3/library/queue.html https://docs.python.org/3.7/library/threading.html [My repo where I use the techniques and code presented above] https://github.com/ElectricRCAircraftGuy/eRCaGuy_PyTerm Related/Cross-Linked: [my answer] PySerial non-blocking read loop A: you can simply use the input() function by using a variable. quick exemple! user = input("Enter any text: ") print(user) A: I came here looking for how to read a single character. I found the readchar library, based on the answers to this question.
How to read keyboard input?
I would like to read data from the keyboard in Python. I tried this code: nb = input('Choose a number') print('Number%s \n' % (nb)) But it doesn't work, either with eclipse nor in the terminal, it's always stop of the question. I can type a number but after nothing happen. Do you know why?
[ "Use\ninput('Enter your input:')\n\nif you use Python 3.\nAnd if you want to have a numeric value, just convert it:\ntry:\n mode = int(input('Input:'))\nexcept ValueError:\n print(\"Not a number\")\n\nIf you use Python 2, you need to use raw_input instead of input.\n", "It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)...\nThis is basically correct:\nnb = input('Choose a number: ')\n\nThe problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function raw_input:\nnb = raw_input('Choose a number: ')\n\nIf you want to convert that to a number, then you should try:\nnumber = int(nb)\n\n... though you need to take into account that this can raise an exception:\ntry:\n number = int(nb)\nexcept ValueError:\n print(\"Invalid number\")\n\nAnd if you want to print the number using formatting, in Python 3 str.format() is recommended:\nprint(\"Number: {0}\\n\".format(number))\n\nInstead of:\nprint('Number %s \\n' % (nb))\n\nBut both options (str.format() and %) do work in both Python 2.7 and Python 3.\n", "Non-blocking, multi-threaded example:\nAs blocking on keyboard input (since the input() function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive. I use this technique in my eRCaGuy_PyTerm serial terminal program here (search the code for input()).\nThis works by creating one thread to run in the background, continually calling input() and then passing any data it receives to a queue.\nIn this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue.\n1. Bare Python 3 code example (no comments):\nimport threading\nimport queue\nimport time\n\ndef read_kbd_input(inputQueue):\n print('Ready for keyboard input:')\n while (True):\n input_str = input()\n inputQueue.put(input_str)\n\ndef main():\n EXIT_COMMAND = \"exit\"\n inputQueue = queue.Queue()\n\n inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)\n inputThread.start()\n\n while (True):\n if (inputQueue.qsize() > 0):\n input_str = inputQueue.get()\n print(\"input_str = {}\".format(input_str))\n\n if (input_str == EXIT_COMMAND):\n print(\"Exiting serial terminal.\")\n break\n \n # Insert your code here to do whatever you want with the input_str.\n\n # The rest of your program goes here.\n\n time.sleep(0.01) \n print(\"End.\")\n\nif (__name__ == '__main__'): \n main()\n\n2. Same Python 3 code as above, but with extensive explanatory comments:\n\"\"\"\nread_keyboard_input.py\n\nGabriel Staples\nwww.ElectricRCAircraftGuy.com\n14 Nov. 2018\n\nReferences:\n- https://pyserial.readthedocs.io/en/latest/pyserial_api.html\n- *****https://www.tutorialspoint.com/python/python_multithreading.htm\n- *****https://en.wikibooks.org/wiki/Python_Programming/Threading\n- https://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass\n- https://docs.python.org/3/library/queue.html\n- https://docs.python.org/3.7/library/threading.html\n\nTo install PySerial: `sudo python3 -m pip install pyserial`\n\nTo run this program: `python3 this_filename.py`\n\n\"\"\"\n\nimport threading\nimport queue\nimport time\n\ndef read_kbd_input(inputQueue):\n print('Ready for keyboard input:')\n while (True):\n # Receive keyboard input from user.\n input_str = input()\n \n # Enqueue this input string.\n # Note: Lock not required here since we are only calling a single Queue method, not a sequence of them \n # which would otherwise need to be treated as one atomic operation.\n inputQueue.put(input_str)\n\ndef main():\n\n EXIT_COMMAND = \"exit\" # Command to exit this program\n\n # The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue\n # method calls in a row. Use this if you have such a need, as follows:\n # 1. Pass queueLock as an input parameter to whichever function requires it.\n # 2. Call queueLock.acquire() to obtain the lock.\n # 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling\n # inputQueue.qsize(), followed by inputQueue.put(), for example.\n # 4. Call queueLock.release() to release the lock.\n # queueLock = threading.Lock() \n\n #Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread.\n inputQueue = queue.Queue()\n\n # Create & start a thread to read keyboard inputs.\n # Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since\n # this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit.\n inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)\n inputThread.start()\n\n # Main loop\n while (True):\n\n # Read keyboard inputs\n # Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure\n # multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this\n # example program, no locks are required.\n if (inputQueue.qsize() > 0):\n input_str = inputQueue.get()\n print(\"input_str = {}\".format(input_str))\n\n if (input_str == EXIT_COMMAND):\n print(\"Exiting serial terminal.\")\n break # exit the while loop\n \n # Insert your code here to do whatever you want with the input_str.\n\n # The rest of your program goes here.\n\n # Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC.\n time.sleep(0.01) \n \n print(\"End.\")\n\n# If you run this Python file directly (ex: via `python3 this_filename.py`), do the following:\nif (__name__ == '__main__'): \n main()\n\nSample output:\n\n$ python3 read_keyboard_input.py\nReady for keyboard input:\nhey\ninput_str = hey\nhello\ninput_str = hello\n7000\ninput_str = 7000\nexit\ninput_str = exit\nExiting serial terminal.\nEnd.\n\nThe Python Queue library is thread-safe:\nNote that Queue.put() and Queue.get() and other Queue class methods are all thread-safe! (This is unlike queues and other containers in the standard template library in C++!) Since the Python Queue class and its methods are thread-safe, that means they implement all the internal locking semantics required for inter-thread operations, so each function call in the queue class can be considered as a single, atomic operation. See the notes at the top of the documentation: https://docs.python.org/3/library/queue.html (emphasis added):\n\nThe queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.\n\nReferences:\n\nhttps://pyserial.readthedocs.io/en/latest/pyserial_api.html\n*****https://www.tutorialspoint.com/python/python_multithreading.htm\n*****https://en.wikibooks.org/wiki/Python_Programming/Threading\nPython: How do I make a subclass from a superclass?\nhttps://docs.python.org/3/library/queue.html\nhttps://docs.python.org/3.7/library/threading.html\n[My repo where I use the techniques and code presented above] https://github.com/ElectricRCAircraftGuy/eRCaGuy_PyTerm\n\nRelated/Cross-Linked:\n\n[my answer] PySerial non-blocking read loop\n\n", "you can simply use the input() function by using a variable. quick exemple!\nuser = input(\"Enter any text: \")\nprint(user)\n\n", "I came here looking for how to read a single character.\nI found the readchar library, based on the answers to this question.\n" ]
[ 134, 87, 31, 0, 0 ]
[]
[]
[ "input", "keyboard", "python" ]
stackoverflow_0005404068_input_keyboard_python.txt
Q: Compare 2 dataframes, assign labels and split rows in Pandas/Pyspark I have 2 dataframes consisting expected_orders and actual_orders details. Input data: I want to create a label field in both dataframe and split the rows based on following criteria: Sort by country, product and date Group both data frames by country and product In both data frames, for each group if row's date and qty are matching then assign label same actual date/ same expected date If qty is matching but dates are different then assign labels (earlier expected date/ later expected date) and (earlier actual date/ later actual date) If qty is not an exact match but there are qty values remaining in other data frame of that group then split the row with greater qty value df to 2 rows: matching (less) qty value and remaining value Repeat steps unless all rows have labels If no quantity is remaining from other group then assign label no actual date or no expected date Expected output: I am trying to do this with nested loops but with millions of rows this is quite slow. for key, exp in expected_grouped: act = actual_grouped.get_group(key) ... for i, outerrow in enumerate(exp.itertuples()): for j, innerrow in enumerate(act.itertuples()): if: ... elif: ... Is there any better and faster way to do this? Any suggestions for improvement would be highly appreciated. A: To start, you can use the sort_values() method to sort the expected_orders and actual_orders dataframes by country, product, and date. This will ensure that the rows in both dataframes are in the same order and can be easily grouped and compared. Next, you can use the groupby() method to group the rows in both dataframes by country and product. This will allow you to compare the rows within each group and assign labels based on the criteria you provided. To compare the rows within each group, you can iterate through the rows in each dataframe and check if the quantity and date values match. If they do, you can assign the appropriate label to the row. If the quantity values match but the dates are different, you can split the row with the greater quantity value into two rows: one with the matching quantity and one with the remaining quantity. You can then assign the appropriate labels to each row. This approach should be faster and more efficient than using nested loops, as it leverages the powerful features of the Pandas library to handle the data manipulation and comparison tasks.
Compare 2 dataframes, assign labels and split rows in Pandas/Pyspark
I have 2 dataframes consisting expected_orders and actual_orders details. Input data: I want to create a label field in both dataframe and split the rows based on following criteria: Sort by country, product and date Group both data frames by country and product In both data frames, for each group if row's date and qty are matching then assign label same actual date/ same expected date If qty is matching but dates are different then assign labels (earlier expected date/ later expected date) and (earlier actual date/ later actual date) If qty is not an exact match but there are qty values remaining in other data frame of that group then split the row with greater qty value df to 2 rows: matching (less) qty value and remaining value Repeat steps unless all rows have labels If no quantity is remaining from other group then assign label no actual date or no expected date Expected output: I am trying to do this with nested loops but with millions of rows this is quite slow. for key, exp in expected_grouped: act = actual_grouped.get_group(key) ... for i, outerrow in enumerate(exp.itertuples()): for j, innerrow in enumerate(act.itertuples()): if: ... elif: ... Is there any better and faster way to do this? Any suggestions for improvement would be highly appreciated.
[ "To start, you can use the sort_values() method to sort the expected_orders and actual_orders dataframes by country, product, and date. This will ensure that the rows in both dataframes are in the same order and can be easily grouped and compared.\nNext, you can use the groupby() method to group the rows in both dataframes by country and product. This will allow you to compare the rows within each group and assign labels based on the criteria you provided.\nTo compare the rows within each group, you can iterate through the rows in each dataframe and check if the quantity and date values match. If they do, you can assign the appropriate label to the row. If the quantity values match but the dates are different, you can split the row with the greater quantity value into two rows: one with the matching quantity and one with the remaining quantity. You can then assign the appropriate labels to each row.\nThis approach should be faster and more efficient than using nested loops, as it leverages the powerful features of the Pandas library to handle the data manipulation and comparison tasks.\n" ]
[ 0 ]
[]
[]
[ "apache_spark_sql", "numpy", "pandas", "pyspark", "python" ]
stackoverflow_0074619139_apache_spark_sql_numpy_pandas_pyspark_python.txt
Q: Termux_Change_Repo using another way with command line I want to change reop mirror in Termux with cmd typing. Is there a way that I can do this without showing the blue screen and do it only by a command line?? A: yes you can by adding mirror link to source.list echo "YOUR URL" > $PREFIX/etc/apt/sources.list check this to know more link
Termux_Change_Repo using another way with command line
I want to change reop mirror in Termux with cmd typing. Is there a way that I can do this without showing the blue screen and do it only by a command line??
[ "yes you can by adding mirror link to source.list\necho \"YOUR URL\" > $PREFIX/etc/apt/sources.list\n\ncheck this to know more link\n" ]
[ 0 ]
[]
[]
[ "android", "termux" ]
stackoverflow_0074462176_android_termux.txt
Q: NetSuite Advance PDF/HTML template, sourcing the contact field from the PO transaction to the pdf I am trying to source the contact information on a purchase order transaction but it is retrieving the information from the attention field on the address, any idea how to do so I have tried using the field ID but still, no information is showing. below are the screenshots for your reference. PO transaction I tried using the attention code but it shows the field from the address. I also tried using the ${record.entityid_contact_name} code but nothing is showing. I am expecting the contact field to only populate the name Lori B on the pdf template. A: First of all contact record is linked to entity (vendor or customer) not transaction. So you will need to create a custom transaction body field to store this value before you can print on PDF. 1. Create Transaction Body Field to store the Vendor's primary contact Name Navigate to Customization > Lists, Records, & Fields > Transaction Body Fields > New Label: Enter Contact Name Id: vendor_pri_contact (*You can name this base on your own convention) Type: Select Free Form Text Store Value: Uncheck Checkmark (* Important) Click Applies To Purchase: Enter Checkmark Click Display Subtab: Select Main Click Validation & Defaulting -- Default Value: Enter {vendor.contact} -- Formula: Enter Checkmark Click [Save] 2. Make sure vendor has a primary contact set. At the vendor record, Relationships tab, click [Update primary] Assign "Primary Contact" role to the contact that you want to print on PDF 3. At the PDF html code, reference to the custom transaction body field id e.g. record.vendor_pri_contact Hope this help.
NetSuite Advance PDF/HTML template, sourcing the contact field from the PO transaction to the pdf
I am trying to source the contact information on a purchase order transaction but it is retrieving the information from the attention field on the address, any idea how to do so I have tried using the field ID but still, no information is showing. below are the screenshots for your reference. PO transaction I tried using the attention code but it shows the field from the address. I also tried using the ${record.entityid_contact_name} code but nothing is showing. I am expecting the contact field to only populate the name Lori B on the pdf template.
[ "First of all contact record is linked to entity (vendor or customer) not transaction. So you will need to create a custom transaction body field to store this value before you can print on PDF.\n1. Create Transaction Body Field to store the Vendor's primary contact Name\n\nNavigate to Customization > Lists, Records, & Fields > Transaction Body Fields > New\nLabel: Enter Contact Name\nId: vendor_pri_contact (*You can name this base on your own convention)\nType: Select Free Form Text\nStore Value: Uncheck Checkmark (* Important)\nClick Applies To\nPurchase: Enter Checkmark\nClick Display\nSubtab: Select Main\nClick Validation & Defaulting\n-- Default Value: Enter {vendor.contact}\n-- Formula: Enter Checkmark\nClick [Save]\n\n2. Make sure vendor has a primary contact set.\n\nAt the vendor record, Relationships tab, click [Update primary]\nAssign \"Primary Contact\" role to the contact that you want to print on PDF\n\n3. At the PDF html code, reference to the custom transaction body field id e.g. record.vendor_pri_contact\nHope this help.\n" ]
[ 0 ]
[]
[]
[ "css", "html", "netsuite", "netsuite2.com", "pdf" ]
stackoverflow_0074556980_css_html_netsuite_netsuite2.com_pdf.txt
Q: Got 50000 USDT on TRON address from faucet, but wallet has 0 USDT I'm new in crypto. I generate address TUQQ8pDFtVdzzJrrzQzgrC1WJeqy23zpVE on Tron "nile" network, then receive from another wallet 500 TRX and then got 50000 USDT from faucet by entering address mentioned above. When i checked balance, i saw that wallet has 0 USDT and 500 TRX, but i also saw a transfer of 50000 USDT. The question is - What should i do to see USDT into wallet or what i do wrong? I read tron developers guide, searched at stackoverflow, but unfortunately i can't find the right answer. Help me please :)
Got 50000 USDT on TRON address from faucet, but wallet has 0 USDT
I'm new in crypto. I generate address TUQQ8pDFtVdzzJrrzQzgrC1WJeqy23zpVE on Tron "nile" network, then receive from another wallet 500 TRX and then got 50000 USDT from faucet by entering address mentioned above. When i checked balance, i saw that wallet has 0 USDT and 500 TRX, but i also saw a transfer of 50000 USDT. The question is - What should i do to see USDT into wallet or what i do wrong? I read tron developers guide, searched at stackoverflow, but unfortunately i can't find the right answer. Help me please :)
[]
[]
[ "I've imported this Tron address into Tronlink extension for chrome and now i can see this usdt from faucet. So i can send it to another wallet programmatically.\n" ]
[ -1 ]
[ "tron" ]
stackoverflow_0074673682_tron.txt
Q: Error during insertion of a new row in a DataFrame I made a dataframe from a dictionary and set one of its columns as my index. While inserting new a row, I get this error: docdf=docdf.loc[sno_value]=[name_value,age_value,special_value,contact_value,fees_value,sal_value] AttributeError: 'list' object has no attribute 'loc' This is my code: import pandas as pd dict={"S.NO":[1,2,3,4,5], "NAME":["John Sharon","Steven Sufjans","Ram Charan","Krishna Kumar","James Chacko"], "AGE":[30,29,44,35,45], "SPECIALISATION":["Neuro","Psych","Cardio","General","Immunology"], "CONTACT":[9000401199,9947227405,9985258207,9982458204,8976517744], "FEES":[1200,2100,3450,4500,3425], "SAL":[20000,30000,40000,50000,45800]} docdf=pd.DataFrame(dict) docdf= docdf.set_index("S.NO") #INSERT A ROW sno_value=int(input('S.NO: ')) name_value = input('NAME: ') age_value = int(input('AGE: ')) special_value = input('SPECIALISATION: ') contact_value = int(input('CONTACT: ')) fees_value = int(input('FEES: ')) sal_value = int(input('SAL: ')) docdf=docdf.loc[sno_value]=[name_value,age_value,special_value,contact_value,fees_value,sal_value] print(docdf) I tried inserting each value separately and then tried to insert a new row using loc function. I was expecting the input S.NO to become the index of new row and then print the whole dictionary with the new row. A: To insert a new row into a data frame, you can use the pandas.DataFrame.loc method and provide the index of the new row as the first argument, followed by a list of values for the new row. However, the syntax of your code is incorrect. In your code, you are using the pandas.DataFrame.loc method to both retrieve a row from the data frame and to insert a new row into the data frame. This is not allowed, as the pandas.DataFrame.loc method is not designed to insert new rows into a data frame. To fix this error, you can use the pandas.DataFrame.loc method to retrieve the existing data frame, then use the pandas.DataFrame.loc method again to insert the new row into the data frame. Here is an example of how you might do this: # retrieve the existing data frame existing_df = docdf.loc[:] # insert the new row into the data frame new_df = existing_df.loc[sno_value] = [name_value, age_value, special_value, contact_value, fees_value, sal_value] Alternatively, you can use the pandas.DataFrame.append method to insert the new row into the data frame. The pandas.DataFrame.append method takes a dictionary or series as an argument and appends it to the data frame as a new row. Here is an example of how you might use the pandas.DataFrame.append method to insert the new row into the data frame: # create a dictionary or series containing the data for the new row new_row = { "S.NO": sno_value, "NAME": name_value, "AGE": age_value, "SPECIALISATION": special_value, "CONTACT": contact_value, "FEES": fees_value, "SAL": sal_value, } # insert the new row into the data frame new_df = docdf.append(new_row, ignore_index=True)
Error during insertion of a new row in a DataFrame
I made a dataframe from a dictionary and set one of its columns as my index. While inserting new a row, I get this error: docdf=docdf.loc[sno_value]=[name_value,age_value,special_value,contact_value,fees_value,sal_value] AttributeError: 'list' object has no attribute 'loc' This is my code: import pandas as pd dict={"S.NO":[1,2,3,4,5], "NAME":["John Sharon","Steven Sufjans","Ram Charan","Krishna Kumar","James Chacko"], "AGE":[30,29,44,35,45], "SPECIALISATION":["Neuro","Psych","Cardio","General","Immunology"], "CONTACT":[9000401199,9947227405,9985258207,9982458204,8976517744], "FEES":[1200,2100,3450,4500,3425], "SAL":[20000,30000,40000,50000,45800]} docdf=pd.DataFrame(dict) docdf= docdf.set_index("S.NO") #INSERT A ROW sno_value=int(input('S.NO: ')) name_value = input('NAME: ') age_value = int(input('AGE: ')) special_value = input('SPECIALISATION: ') contact_value = int(input('CONTACT: ')) fees_value = int(input('FEES: ')) sal_value = int(input('SAL: ')) docdf=docdf.loc[sno_value]=[name_value,age_value,special_value,contact_value,fees_value,sal_value] print(docdf) I tried inserting each value separately and then tried to insert a new row using loc function. I was expecting the input S.NO to become the index of new row and then print the whole dictionary with the new row.
[ "To insert a new row into a data frame, you can use the pandas.DataFrame.loc method and provide the index of the new row as the first argument, followed by a list of values for the new row. However, the syntax of your code is incorrect.\nIn your code, you are using the pandas.DataFrame.loc method to both retrieve a row from the data frame and to insert a new row into the data frame. This is not allowed, as the pandas.DataFrame.loc method is not designed to insert new rows into a data frame.\nTo fix this error, you can use the pandas.DataFrame.loc method to retrieve the existing data frame, then use the pandas.DataFrame.loc method again to insert the new row into the data frame. Here is an example of how you might do this:\n# retrieve the existing data frame\nexisting_df = docdf.loc[:]\n\n# insert the new row into the data frame\nnew_df = existing_df.loc[sno_value] = [name_value, age_value, special_value, contact_value, fees_value, sal_value]\n\nAlternatively, you can use the pandas.DataFrame.append method to insert the new row into the data frame. The pandas.DataFrame.append method takes a dictionary or series as an argument and appends it to the data frame as a new row. Here is an example of how you might use the pandas.DataFrame.append method to insert the new row into the data frame:\n# create a dictionary or series containing the data for the new row\nnew_row = {\n \"S.NO\": sno_value,\n \"NAME\": name_value,\n \"AGE\": age_value,\n \"SPECIALISATION\": special_value,\n \"CONTACT\": contact_value,\n \"FEES\": fees_value,\n \"SAL\": sal_value,\n}\n\n# insert the new row into the data frame\nnew_df = docdf.append(new_row, ignore_index=True)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "dictionary", "input", "pandas", "pandas_loc" ]
stackoverflow_0074675449_dataframe_dictionary_input_pandas_pandas_loc.txt
Q: Android AudioRecord with CHANNEL_IN_STEREO read raw Audio buffer resulted in mixed Left and Right audio I am trying to record an audio with CHANNEL_IN_STEREO configuration in which I am telling audio recorded to record audio in two channel. But after storing buffer array from recorder Audio left channel and right channel is resulting as mix. I cannot separate Audio Left channel and Right channel. Below is code written for same : import androidx.appcompat.app.AppCompatActivity; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity { AudioRecord record; Boolean status = true; private int sampleRate = 44100; private int channelConfig = AudioFormat.CHANNEL_IN_STEREO; private int audioFormat = AudioFormat.ENCODING_PCM_16BIT; int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat); byte buffer[] = new byte[8916]; ByteArrayOutputStream leftbaos; ByteArrayOutputStream rightbaos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button start = findViewById(R.id.start); Button stop = findViewById(R.id.stop); leftbaos = new ByteArrayOutputStream(); rightbaos = new ByteArrayOutputStream(); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startRecorder(); } }); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { stopRecorder(); } }); } private void startRecorder() { status = true; record = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, channelConfig, audioFormat, minBufSize); Thread streamThread = new Thread(new Runnable() { @Override public void run() { try { record.startRecording(); while (status == true) { int recorded_int = record.read(buffer, 0, minBufSize); byte leftChannelAudioData[] = new byte[buffer.length/2]; byte rightChannelAudioData[] = new byte[buffer.length/2]; for(int i = 0; i < buffer.length/2; i = i + 1) { leftChannelAudioData[i] = buffer[2*i]; rightChannelAudioData[i] = buffer[2*i+1]; } leftbaos.write(leftChannelAudioData,0,recorded_int/2); rightbaos.write(rightChannelAudioData,0,recorded_int/2); } } catch(Exception e) { } } }); streamThread.start(); } private void stopRecorder() { status = false; if(record!= null) { //storing left channel audio send(leftbaos,"/mydirectory/left.pcm"); //storing right channel audio send(rightbaos,"/mydirectory/right.pcm"); record.stop(); record.release(); } } private void send(ByteArrayOutputStream baos,String path) { File file = new File(path); try { FileOutputStream out = new FileOutputStream(file); baos.writeTo(out); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } I have Used below mentioned permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> In above code I am storing ByteArrayOutputStream in PCM file once recording gets stopped. How can I separate Audio Left channel and Right channel from Audio Record. A: I know this question belongs to long time ago, but I have an idea, I hope it works: You can use the AudioTrack or AudioRecord API's getChannelCount() method to determine the number of channels in a given audio track. Once you have this information, you can use the AudioTrack or AudioRecord API's read() method to read the audio data from the track and separate the left and right channels into separate buffers. For example, if you were using the AudioTrack API, the following code snippet would read the left and right channels of a stereo track into separate buffers: int channelCount = audioTrack.getChannelCount(); int bufferSize = audioTrack.getBufferSizeInBytes(); // Create two arrays for left and right channel. byte[] leftChannel = new byte[bufferSize]; byte[] rightChannel = new byte[bufferSize]; // Read audio data into the left and right channel arrays. audioTrack.read(leftChannel, 0, bufferSize); audioTrack.read(rightChannel, 0, bufferSize);
Android AudioRecord with CHANNEL_IN_STEREO read raw Audio buffer resulted in mixed Left and Right audio
I am trying to record an audio with CHANNEL_IN_STEREO configuration in which I am telling audio recorded to record audio in two channel. But after storing buffer array from recorder Audio left channel and right channel is resulting as mix. I cannot separate Audio Left channel and Right channel. Below is code written for same : import androidx.appcompat.app.AppCompatActivity; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity { AudioRecord record; Boolean status = true; private int sampleRate = 44100; private int channelConfig = AudioFormat.CHANNEL_IN_STEREO; private int audioFormat = AudioFormat.ENCODING_PCM_16BIT; int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat); byte buffer[] = new byte[8916]; ByteArrayOutputStream leftbaos; ByteArrayOutputStream rightbaos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button start = findViewById(R.id.start); Button stop = findViewById(R.id.stop); leftbaos = new ByteArrayOutputStream(); rightbaos = new ByteArrayOutputStream(); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startRecorder(); } }); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { stopRecorder(); } }); } private void startRecorder() { status = true; record = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, channelConfig, audioFormat, minBufSize); Thread streamThread = new Thread(new Runnable() { @Override public void run() { try { record.startRecording(); while (status == true) { int recorded_int = record.read(buffer, 0, minBufSize); byte leftChannelAudioData[] = new byte[buffer.length/2]; byte rightChannelAudioData[] = new byte[buffer.length/2]; for(int i = 0; i < buffer.length/2; i = i + 1) { leftChannelAudioData[i] = buffer[2*i]; rightChannelAudioData[i] = buffer[2*i+1]; } leftbaos.write(leftChannelAudioData,0,recorded_int/2); rightbaos.write(rightChannelAudioData,0,recorded_int/2); } } catch(Exception e) { } } }); streamThread.start(); } private void stopRecorder() { status = false; if(record!= null) { //storing left channel audio send(leftbaos,"/mydirectory/left.pcm"); //storing right channel audio send(rightbaos,"/mydirectory/right.pcm"); record.stop(); record.release(); } } private void send(ByteArrayOutputStream baos,String path) { File file = new File(path); try { FileOutputStream out = new FileOutputStream(file); baos.writeTo(out); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } I have Used below mentioned permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> In above code I am storing ByteArrayOutputStream in PCM file once recording gets stopped. How can I separate Audio Left channel and Right channel from Audio Record.
[ "I know this question belongs to long time ago, but I have an idea, I hope it works:\nYou can use the AudioTrack or AudioRecord API's getChannelCount() method to determine the number of channels in a given audio track. Once you have this information, you can use the AudioTrack or AudioRecord API's read() method to read the audio data from the track and separate the left and right channels into separate buffers.\nFor example, if you were using the AudioTrack API, the following code snippet would read the left and right channels of a stereo track into separate buffers:\nint channelCount = audioTrack.getChannelCount(); \nint bufferSize = audioTrack.getBufferSizeInBytes(); \n\n// Create two arrays for left and right channel. \nbyte[] leftChannel = new byte[bufferSize]; \nbyte[] rightChannel = new byte[bufferSize]; \n\n// Read audio data into the left and right channel arrays. \naudioTrack.read(leftChannel, 0, bufferSize); \naudioTrack.read(rightChannel, 0, bufferSize);\n\n" ]
[ 0 ]
[]
[]
[ "android", "android_audiorecord", "audio", "audio_streaming" ]
stackoverflow_0059339328_android_android_audiorecord_audio_audio_streaming.txt
Q: vim internal terminal run multiple commands at a time I create some useful vim command aliases like: command GccAndRun !gcc main.c && ./a.out However, it's better to run a.out and check source code in same window. I here about vim internel terminal, so I write the follwing sentence: command GccAndRun terminal gcc main.c && ./a.out But given error message: gcc: error: &&: No such file or directory in opened terminal. I don't know how to fix it. Please help me! A: Let's start by fixing your initial command, which can't work as-is: command GccAndRun !gcc main.c && ./a.out Now, :terminal unfortunately doesn't accept constructs like cmd1 && cmd2 or cmd1 | cmd2, so you will need a workaround: create a shell script, say run.sh, that does gcc main.c && ./a.out for you and do: command GccAndRun terminal run.sh Pros: you can put whatever you want in that script Cons: may need non-trivial scripting if you want to pass filenames, etc. pollutes the project is project-dependent doesn't leave you in terminal mode use the ++shell option, which tells Vim to run the given command in a non-interactive shell: command GccAndRun terminal ++shell gcc main.c && ./a.out Pros: you can input whatever command you want doesn't pollute the project is project-agnostic Cons: doesn't leave you in terminal mode See :help :terminal.
vim internal terminal run multiple commands at a time
I create some useful vim command aliases like: command GccAndRun !gcc main.c && ./a.out However, it's better to run a.out and check source code in same window. I here about vim internel terminal, so I write the follwing sentence: command GccAndRun terminal gcc main.c && ./a.out But given error message: gcc: error: &&: No such file or directory in opened terminal. I don't know how to fix it. Please help me!
[ "Let's start by fixing your initial command, which can't work as-is:\ncommand GccAndRun !gcc main.c && ./a.out\n\nNow, :terminal unfortunately doesn't accept constructs like cmd1 && cmd2 or cmd1 | cmd2, so you will need a workaround:\n\ncreate a shell script, say run.sh, that does gcc main.c && ./a.out for you and do:\ncommand GccAndRun terminal run.sh\n\nPros:\n\nyou can put whatever you want in that script\n\nCons:\n\nmay need non-trivial scripting if you want to pass filenames, etc.\npollutes the project\nis project-dependent\ndoesn't leave you in terminal mode\n\n\nuse the ++shell option, which tells Vim to run the given command in a non-interactive shell:\ncommand GccAndRun terminal ++shell gcc main.c && ./a.out\n\nPros:\n\nyou can input whatever command you want\ndoesn't pollute the project\nis project-agnostic\n\nCons:\n\ndoesn't leave you in terminal mode\n\n\n\nSee :help :terminal.\n" ]
[ 0 ]
[]
[]
[ "vim" ]
stackoverflow_0074675598_vim.txt
Q: Javascript - How using a variable for object property Im very beginner in javascript, i would like to use all variable created on each object property : let title = "Les Miserables"; let resume = "Blabla blaaabla..."; let autor = "Victor Hugo" let date = "1862" const books = { title: title, resume: desc, autor: autor, date: date, } I want a result like this => { title:'Les Miserables', resume:'Blabla blaaabla...', autor:'Victor Hugo', date: '1862'} Is this possible ? A: You can use object property shorthand notation: let title = "Les Miserables"; let resume = "Blabla blaaabla..."; let autor = "Victor Hugo"; let date = "1862"; const books = { title, resume, autor, date, }; console.log(books); /* Logs: { title: "Les Miserables", resume: "Blabla blaaabla...", autor: "Victor Hugo", date: "1862" } */ You can also assign the values directly to properties on the object instead of first declaring individual variables in the scope: const books = {}; books.title = "Les Miserables"; books.resume = "Blabla blaaabla..."; books.autor = "Victor Hugo"; books.date = "1862"; console.log(books); /* Logs: { title: "Les Miserables", resume: "Blabla blaaabla...", autor: "Victor Hugo", date: "1862" } */
Javascript - How using a variable for object property
Im very beginner in javascript, i would like to use all variable created on each object property : let title = "Les Miserables"; let resume = "Blabla blaaabla..."; let autor = "Victor Hugo" let date = "1862" const books = { title: title, resume: desc, autor: autor, date: date, } I want a result like this => { title:'Les Miserables', resume:'Blabla blaaabla...', autor:'Victor Hugo', date: '1862'} Is this possible ?
[ "You can use object property shorthand notation:\n\n\nlet title = \"Les Miserables\";\nlet resume = \"Blabla blaaabla...\";\nlet autor = \"Victor Hugo\";\nlet date = \"1862\";\n\nconst books = {\n title,\n resume,\n autor,\n date,\n};\n\nconsole.log(books); /* Logs:\n{\n title: \"Les Miserables\",\n resume: \"Blabla blaaabla...\",\n autor: \"Victor Hugo\",\n date: \"1862\"\n} */\n\n\n\nYou can also assign the values directly to properties on the object instead of first declaring individual variables in the scope:\n\n\nconst books = {};\n\nbooks.title = \"Les Miserables\";\nbooks.resume = \"Blabla blaaabla...\";\nbooks.autor = \"Victor Hugo\";\nbooks.date = \"1862\";\n\nconsole.log(books); /* Logs:\n{\n title: \"Les Miserables\",\n resume: \"Blabla blaaabla...\",\n autor: \"Victor Hugo\",\n date: \"1862\"\n} */\n\n\n\n" ]
[ 1 ]
[]
[]
[ "javascript", "object", "properties", "variables" ]
stackoverflow_0074675724_javascript_object_properties_variables.txt
Q: Two columns cannot be the same in multiple rows Is there a way to make sure two columns are unique combined but each of them by themselves can be duplicates? If we have cols a and b i want the system to allow this query. INSERT INTO test VALUES (1, 2); INSERT INTO test VALUES (1, 3); INSERT INTO test VALUES (2, 2); INSERT INTO test VALUES (2, 3); But not this INSERT INTO test VALUES (1, 2); INSERT INTO test VALUES (1, 2); A: Yes, you can create a unique index on the combination of columns a and b to ensure that the values in these columns are unique when considered together. Here is an example of how you can create a unique index on columns a and b in MySQL: CREATE TABLE test ( a INT, b INT, UNIQUE KEY (a, b) ); In this example, a unique index is created on the combination of columns a and b. This means that the values in these columns must be unique when considered together. However, each of these columns can have duplicate values when considered individually. For example, the following queries would be allowed: INSERT INTO test VALUES (1, 2); INSERT INTO test VALUES (1, 3); INSERT INTO test VALUES (2, 2); INSERT INTO test VALUES (2, 3); But the following query would not be allowed because it tries to insert a duplicate value for the combination of columns a and b: INSERT INTO test VALUES (1, 2); INSERT INTO test VALUES (1, 2); The unique index created in this example would prevent the second query from being executed, because it tries to insert a duplicate value for the combination of columns a and b.
Two columns cannot be the same in multiple rows
Is there a way to make sure two columns are unique combined but each of them by themselves can be duplicates? If we have cols a and b i want the system to allow this query. INSERT INTO test VALUES (1, 2); INSERT INTO test VALUES (1, 3); INSERT INTO test VALUES (2, 2); INSERT INTO test VALUES (2, 3); But not this INSERT INTO test VALUES (1, 2); INSERT INTO test VALUES (1, 2);
[ "Yes, you can create a unique index on the combination of columns a and b to ensure that the values in these columns are unique when considered together.\nHere is an example of how you can create a unique index on columns a and b in MySQL:\nCREATE TABLE test (\n a INT,\n b INT,\n UNIQUE KEY (a, b)\n);\n\nIn this example, a unique index is created on the combination of columns a and b. This means that the values in these columns must be unique when considered together. However, each of these columns can have duplicate values when considered individually.\nFor example, the following queries would be allowed:\nINSERT INTO test VALUES (1, 2);\nINSERT INTO test VALUES (1, 3);\nINSERT INTO test VALUES (2, 2);\nINSERT INTO test VALUES (2, 3);\n\nBut the following query would not be allowed because it tries to insert a duplicate value for the combination of columns a and b:\nINSERT INTO test VALUES (1, 2);\nINSERT INTO test VALUES (1, 2);\n\nThe unique index created in this example would prevent the second query from being executed, because it tries to insert a duplicate value for the combination of columns a and b.\n" ]
[ -1 ]
[]
[]
[ "sql" ]
stackoverflow_0074675742_sql.txt
Q: How can I build a function for Fibonacci numbers 1:42 I tried to build the function but I only am able to build a sequence not a function. Could someone give me some help with building a fib function. I expected a function but I wasn't able to build it and the sequence was not what I wanted. A: Here's a function that lets you determine how many Fibonacci numbers you want to get: # define number of numbers in Fibonacci sequence (with edits suggested by @Dirk) fib <- function(n) { x = numeric(n) x[1:3] = c(0,1,1) for(i in 4:n) x[i] = x[i-1] + x[i-2] x } Say, you want to see the first 10 Fibonacci numbers: fib(10) [1] 0 1 1 2 3 5 8 13 21 34
How can I build a function for Fibonacci numbers 1:42
I tried to build the function but I only am able to build a sequence not a function. Could someone give me some help with building a fib function. I expected a function but I wasn't able to build it and the sequence was not what I wanted.
[ "Here's a function that lets you determine how many Fibonacci numbers you want to get:\n# define number of numbers in Fibonacci sequence (with edits suggested by @Dirk)\n\nfib <- function(n) {\n x = numeric(n)\n x[1:3] = c(0,1,1)\n for(i in 4:n) x[i] = x[i-1] + x[i-2]\n x\n}\n\nSay, you want to see the first 10 Fibonacci numbers:\nfib(10)\n[1] 0 1 1 2 3 5 8 13 21 34 \n\n" ]
[ 2 ]
[]
[]
[ "r" ]
stackoverflow_0074675609_r.txt
Q: Yii2 API authentication Behaviors() Not working I am creating restful api in yii2. Here I am facing a issue. In my userController.php I have created a behaviour() for authentication. use yii\filters\auth\HttpBasicAuth; public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => HttpBasicAuth::className(), 'except' => ['signup'] ]; return $behaviors; } Here I have passed 'except' => ['signup'], So that authentication should be not applied to 'signup' action. But here it is not applied and asking for authentication for 'signup' action too. So, please guide where I have mistaken. A: Add this to your .htaccess files SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
Yii2 API authentication Behaviors() Not working
I am creating restful api in yii2. Here I am facing a issue. In my userController.php I have created a behaviour() for authentication. use yii\filters\auth\HttpBasicAuth; public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => HttpBasicAuth::className(), 'except' => ['signup'] ]; return $behaviors; } Here I have passed 'except' => ['signup'], So that authentication should be not applied to 'signup' action. But here it is not applied and asking for authentication for 'signup' action too. So, please guide where I have mistaken.
[ "Add this to your .htaccess files\nSetEnvIf Authorization \"(.*)\" HTTP_AUTHORIZATION=$1\n\n" ]
[ 0 ]
[ "public function behaviors()\n{\n $behaviors = parent::behaviors();\n $behaviors['authenticator'] = [\n [\n 'class' => HttpBasicAuth::className(),\n 'except' => ['signup']\n ]\n ];\n return $behaviors;\n}\n\n" ]
[ -1 ]
[ "api", "yii2", "yii2_advanced_app" ]
stackoverflow_0030638841_api_yii2_yii2_advanced_app.txt
Q: How to prevent users from inputing numbers outside of the range i have given? Write a program that allows user to input two integers in the range of (between) 1 to 100, inclusive and print the product as an output. The program must call a method/function, named computeProduct, which takes in the two numbers and returns the product. The method/function should also check that the two integers are within the 1 to 100 range, if not, it should print a message that says "Number is not in range, please try again." I was given this question for a homework, but i am not expecting any code answer for my question. I would like some advice and tips on the 'The method/function should also check that the two integers are within the 1 to 100 range, if not, it should print a message that says "Number is not in range, please try again."' I am pretty much brain dead on how to solve this. Any tips would be awesome! This is what i am trying but does not work as it does not stop the user from inputing wrong number does not alert the user right away after inputing a wrong value public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Please Key in integers only in the range between 1 to 100."); System.out.println("Please key in your first Integer: "); int a = scan.nextInt(); System.out.println("Please key in your second Integer: "); int b = scan.nextInt(); int totaloutput = computeProduct(a, b); System.out.println(totaloutput); } public static int computeProduct(int num1, int num2) { if (num1 < 1 || num1 > 100) { System.out.println("invalid range"); } else if (num2 < 1 || num2 > 100) { System.out.println("invalid range"); } int total = num1 * num2; return total; } } A: So you have to validate both the numbers in range. What you are doing now is first you are checking the num1 in range if not, then you are checking num2 is in range, which is wong the first validation should be false for the second validation to be in effect. So have all the validation in a single if condition. if(num1 < 1 || num1 > 100 || num2 < 1 || num2 > 100){ System.out.println("invalid range"); } then you have to terminate the method when you have invalid input. You can either throw an exception of return defaule value. Exception: if(num1 < 1 || num1 > 100 || num2 < 1 || num2 > 100){ System.out.println("invalid range"); throw new RuntimeException("Invalid Number") } Default value: if(num1 < 1 || num1 > 100 || num2 < 1 || num2 > 100){ System.out.println("invalid range"); return -1; } If you go with default value your method should be as below. public static int computeProduct(int num1, int num2) { if(num1 < 1 || num1 > 100 || num2 < 1 || num2 > 100){ System.out.println("invalid range"); return -1; } int total = num1 * num2; return total; }
How to prevent users from inputing numbers outside of the range i have given?
Write a program that allows user to input two integers in the range of (between) 1 to 100, inclusive and print the product as an output. The program must call a method/function, named computeProduct, which takes in the two numbers and returns the product. The method/function should also check that the two integers are within the 1 to 100 range, if not, it should print a message that says "Number is not in range, please try again." I was given this question for a homework, but i am not expecting any code answer for my question. I would like some advice and tips on the 'The method/function should also check that the two integers are within the 1 to 100 range, if not, it should print a message that says "Number is not in range, please try again."' I am pretty much brain dead on how to solve this. Any tips would be awesome! This is what i am trying but does not work as it does not stop the user from inputing wrong number does not alert the user right away after inputing a wrong value public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Please Key in integers only in the range between 1 to 100."); System.out.println("Please key in your first Integer: "); int a = scan.nextInt(); System.out.println("Please key in your second Integer: "); int b = scan.nextInt(); int totaloutput = computeProduct(a, b); System.out.println(totaloutput); } public static int computeProduct(int num1, int num2) { if (num1 < 1 || num1 > 100) { System.out.println("invalid range"); } else if (num2 < 1 || num2 > 100) { System.out.println("invalid range"); } int total = num1 * num2; return total; } }
[ "So you have to validate both the numbers in range.\nWhat you are doing now is first you are checking the num1 in range if not, then you are checking num2 is in range, which is wong the first validation should be false for the second validation to be in effect.\nSo have all the validation in a single if condition.\nif(num1 < 1 || num1 > 100 || num2 < 1 || num2 > 100){\n System.out.println(\"invalid range\");\n}\n\nthen you have to terminate the method when you have invalid input.\nYou can either throw an exception of return defaule value.\nException:\nif(num1 < 1 || num1 > 100 || num2 < 1 || num2 > 100){\n System.out.println(\"invalid range\");\n throw new RuntimeException(\"Invalid Number\")\n}\n\nDefault value:\nif(num1 < 1 || num1 > 100 || num2 < 1 || num2 > 100){\n System.out.println(\"invalid range\");\n return -1;\n}\n\nIf you go with default value your method should be as below.\npublic static int computeProduct(int num1, int num2) {\n if(num1 < 1 || num1 > 100 || num2 < 1 || num2 > 100){\n System.out.println(\"invalid range\");\n return -1;\n }\n int total = num1 * num2;\n return total;\n}\n\n" ]
[ 0 ]
[]
[]
[ "java", "methods" ]
stackoverflow_0074675676_java_methods.txt
Q: React - Route with same path, but different parameters change data on update I am creating a page where you can see peoples profiles and all their items, which has pathname="/users/{their id}" and a menu where it can take you to your profile. But my problem is that when you go to a persons profile page, and then to another one, the pathname changes but the data does not get rendered it only changes the pathname and the data remains the same. In order to render the data, you would have to refresh the page and then it shows the new users data. How would I get it so you wouldn't have to refresh the page, so like they click on the user they want to go to, the pathname changes and renders the new data without the page refresh? Also, something happens when you refresh the page when on a user profile, it is supposed to return the users' email address, which it does when you first visit the page, but when you refresh the page it returns an error saying it can't find the email. Here is the code for the menu part (link to my profile): import { Meteor } from "meteor/meteor" import React from "react"; import { withRouter, Link } from "react-router-dom"; import { SubjectRoutes } from "./subjectRoutes/subjectRoutes"; import AddNote from "./AddNote"; class Menu extends React.Component{ render(){ return( <div> <div className="scroll"></div> <div className="menu"> <h1>Menu</h1> <p><Link to="/">Home</Link></p> <Link to="/searchNotes">Notes</Link> <p><Link to="/addNote">Add a Note</Link></p> <p><Link to={`/users/${Meteor.userId()}`} >My Profile</Link></p> </div> </div> ) } } export default withRouter(Menu) userProfile.js: import { Meteor } from "meteor/meteor"; import React from "react"; import { withRouter } from "react-router-dom"; import { Tracker } from "meteor/tracker"; import Menu from "./Menu"; import RenderNotesByUserId from "./renderNotesByUserId" class userProfile extends React.Component{ constructor(props){ super(props); this.state = { email: "" }; } logoutUser(e){ e.preventDefault() Accounts.logout(() => { this.props.history.push("/login"); }); } componentWillMount() { Meteor.subscribe('user'); Meteor.subscribe('users'); this.tracker = Tracker.autorun(() => { const user = Meteor.users.findOne(this.props.match.params.userId) this.setState({email: user.emails[0].address}) }); } render(){ return( <div> <Menu /> <button onClick={this.logoutUser.bind(this)}>Logout</button> <h1>{this.state.email}</h1> <RenderNotesByUserId filter={this.props.match.params.userId}/> </div> ) } } export default withRouter(userProfile); Sorry to make this question so long it's just a really weird problem that I am having which I can't seem to find any answers to online. A: ComponentWillMount() only runs one time, before your component is rendered. You need to also use ComponentWillReceiveProps() in order to update your state when your props change. Check out React Component Lifecycle A: you can use useLocation in this situation. let location = useLocation(); useEffect(() => { dispatch(fetchDetail(id)) dispatch(fetchSuggestions(category)) // eslint-disable-next-line react-hooks/exhaustive-deps }, [location]);
React - Route with same path, but different parameters change data on update
I am creating a page where you can see peoples profiles and all their items, which has pathname="/users/{their id}" and a menu where it can take you to your profile. But my problem is that when you go to a persons profile page, and then to another one, the pathname changes but the data does not get rendered it only changes the pathname and the data remains the same. In order to render the data, you would have to refresh the page and then it shows the new users data. How would I get it so you wouldn't have to refresh the page, so like they click on the user they want to go to, the pathname changes and renders the new data without the page refresh? Also, something happens when you refresh the page when on a user profile, it is supposed to return the users' email address, which it does when you first visit the page, but when you refresh the page it returns an error saying it can't find the email. Here is the code for the menu part (link to my profile): import { Meteor } from "meteor/meteor" import React from "react"; import { withRouter, Link } from "react-router-dom"; import { SubjectRoutes } from "./subjectRoutes/subjectRoutes"; import AddNote from "./AddNote"; class Menu extends React.Component{ render(){ return( <div> <div className="scroll"></div> <div className="menu"> <h1>Menu</h1> <p><Link to="/">Home</Link></p> <Link to="/searchNotes">Notes</Link> <p><Link to="/addNote">Add a Note</Link></p> <p><Link to={`/users/${Meteor.userId()}`} >My Profile</Link></p> </div> </div> ) } } export default withRouter(Menu) userProfile.js: import { Meteor } from "meteor/meteor"; import React from "react"; import { withRouter } from "react-router-dom"; import { Tracker } from "meteor/tracker"; import Menu from "./Menu"; import RenderNotesByUserId from "./renderNotesByUserId" class userProfile extends React.Component{ constructor(props){ super(props); this.state = { email: "" }; } logoutUser(e){ e.preventDefault() Accounts.logout(() => { this.props.history.push("/login"); }); } componentWillMount() { Meteor.subscribe('user'); Meteor.subscribe('users'); this.tracker = Tracker.autorun(() => { const user = Meteor.users.findOne(this.props.match.params.userId) this.setState({email: user.emails[0].address}) }); } render(){ return( <div> <Menu /> <button onClick={this.logoutUser.bind(this)}>Logout</button> <h1>{this.state.email}</h1> <RenderNotesByUserId filter={this.props.match.params.userId}/> </div> ) } } export default withRouter(userProfile); Sorry to make this question so long it's just a really weird problem that I am having which I can't seem to find any answers to online.
[ "ComponentWillMount() only runs one time, before your component is rendered. You need to also use ComponentWillReceiveProps() in order to update your state when your props change. \nCheck out React Component Lifecycle\n", "you can use useLocation in this situation.\n\nlet location = useLocation();\n\nuseEffect(() => {\n dispatch(fetchDetail(id))\n dispatch(fetchSuggestions(category))\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n}, [location]);\n\n" ]
[ 2, 0 ]
[]
[]
[ "meteor", "parameters", "react_router", "react_router_dom", "reactjs" ]
stackoverflow_0045898530_meteor_parameters_react_router_react_router_dom_reactjs.txt
Q: CodeWars - javascript - Multiples of 3 or 5 recursively I'm currently training on codewars, and today was multiples of 3 and 5. I tried with a casual solution using reduce + ternary, and it worked. I then tried to solve it with recusrive function. Instructions are as follow : If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Additionally, if the number is negative, return 0 (for languages that do have them). Link is here https://www.codewars.com/kata/514b92a657cdc65150000006 Here is my solution : let res = 0 function solution(n){ if(n - 1 <= 0) { return 0 } if((n - 1) % 3 > 0) { if((n - 1) % 5 > 0) { return solution(n - 1, res) } else { res += n - 1 solution(n - 1, res) } } else { res += n - 1 solution(n - 1, res) } return res } It works on my computer but fails on codewars attemps, giving extravagant results, such as solution(6) = 9283 whereas on my computer 8 (correct answer) Also, I got the maximum call stack exceeded on codewars for 9513, but not on my computer. Ideas anyone ? A: function solution(number) { // Base case: return 0 if the number is negative if (number < 0) { return 0; } // Recursive case: if the number is a multiple of 3 or 5, add it to the sum of // the multiples of 3 or 5 below it, otherwise just return the sum of the // multiples of 3 or 5 below it return (number % 3 === 0 || number % 5 === 0) ? number + solution(number - 1) : solution(number - 1); } A: You can also use the sum of an arithmetic sequence to do this without iterating, so O(1). wiki const input = 10 function sum35(num){ num = num - 1 const lastThree = num - num%3 const threeQuantity = lastThree/3 const lastFive = num - num%5 const fiveQuantity = lastFive/5 return getSum(threeQuantity,3,lastThree) + getSum(fiveQuantity, 5, lastFive) function getSum(n, first, last) { return (n/2)*(first + last) } } console.log(sum35(10)) A: Defining res as a global is very likely the problem: its value will be reused for subsequent calls of the function. Change your function to take res as a parameter. If the signature must define only a single parameter, using an inner function would be an idea. Here's a solution using a nested function, simplifying some of the unnecessary complications and duplications: function solution(n) { let res = 0; function _solution(n) { if(n <= 0) { return 0; } if(n % 3 != 0 && n % 5 != 0) { return _solution(n - 1); } res += n; _solution(n - 1); return res; } return _solution(n - 1); } But note that this is not a "clean" recursive approach, because the function is actually a closure and has a side-effect: modifying the value of the outside variable res. For a proper recursive implementation, see yanai edri's answer.
CodeWars - javascript - Multiples of 3 or 5 recursively
I'm currently training on codewars, and today was multiples of 3 and 5. I tried with a casual solution using reduce + ternary, and it worked. I then tried to solve it with recusrive function. Instructions are as follow : If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Additionally, if the number is negative, return 0 (for languages that do have them). Link is here https://www.codewars.com/kata/514b92a657cdc65150000006 Here is my solution : let res = 0 function solution(n){ if(n - 1 <= 0) { return 0 } if((n - 1) % 3 > 0) { if((n - 1) % 5 > 0) { return solution(n - 1, res) } else { res += n - 1 solution(n - 1, res) } } else { res += n - 1 solution(n - 1, res) } return res } It works on my computer but fails on codewars attemps, giving extravagant results, such as solution(6) = 9283 whereas on my computer 8 (correct answer) Also, I got the maximum call stack exceeded on codewars for 9513, but not on my computer. Ideas anyone ?
[ "function solution(number) {\n // Base case: return 0 if the number is negative\n if (number < 0) {\n return 0;\n }\n\n // Recursive case: if the number is a multiple of 3 or 5, add it to the sum of\n // the multiples of 3 or 5 below it, otherwise just return the sum of the\n // multiples of 3 or 5 below it\n return (number % 3 === 0 || number % 5 === 0)\n ? number + solution(number - 1)\n : solution(number - 1);\n}\n\n", "You can also use the sum of an arithmetic sequence to do this without iterating, so O(1).\n\nwiki\n\n\nconst input = 10\n\nfunction sum35(num){\n num = num - 1\n const lastThree = num - num%3\n const threeQuantity = lastThree/3\n \n const lastFive = num - num%5\n const fiveQuantity = lastFive/5\n \n return getSum(threeQuantity,3,lastThree) + getSum(fiveQuantity, 5, lastFive)\n \n function getSum(n, first, last) {\n return (n/2)*(first + last)\n }\n}\n\nconsole.log(sum35(10))\n\n\n\n", "Defining res as a global is very likely the problem: its value will be reused for subsequent calls of the function.\nChange your function to take res as a parameter. If the signature must define only a single parameter, using an inner function would be an idea.\nHere's a solution using a nested function, simplifying some of the unnecessary complications and duplications:\nfunction solution(n) {\n let res = 0;\n\n function _solution(n) {\n if(n <= 0) {\n return 0;\n }\n\n if(n % 3 != 0 && n % 5 != 0) {\n return _solution(n - 1);\n }\n\n res += n;\n _solution(n - 1);\n return res;\n }\n\n return _solution(n - 1);\n}\n\nBut note that this is not a \"clean\" recursive approach, because the function is actually a closure and has a side-effect: modifying the value of the outside variable res. For a proper recursive implementation, see yanai edri's answer.\n" ]
[ 2, 2, 0 ]
[]
[]
[ "javascript", "recursion" ]
stackoverflow_0074675562_javascript_recursion.txt
Q: How can i convert mireds to RGB or display mireds in css? From an application i get a color temprature in mireds, i want to display it in a HTML box but i cant find a way to display it via mireds. I thought there was an answer anywhere on the internet for displaying it or converting it. But, unfortunately not. Does anyone know how i can convert or display it? Regards, Kuno A: The conversion you want to perform can be highly involved depending on the degree of precision required. Here is an outline of the algorithm and a Python implementation using Colour. M (Mired) is the MIcro REciprocal Degree (Colour) Temperature K (Kelvin) thus the first step is the conversion from Mired to Kelvin as follows: K = 10e6 / M. Then the Colour Temperature K can be converted to CIE xy Chromaticity Coordinates using a method such as Kang et al. (2002) for simplicity or if extreme precision is required Robertson (1968) or Ohno (2013) (but this is much more involved to convert to Javascript). Subsequently, the CIE xy Chromaticity Coordinates (equivalent to CIE xyY with Luminance set to 1) can be converted to CIE XYZ Tristimulus Values. The CIE XYZ tristimulus values can be converted to sRGB Colourspace Values, at its simplest, it is a matrix multiplication using the IEC 61966-2-1:1999 matrix. The sRGB Colourspace Values are non-linearly encoded with the sRGB Inverse Electro-Optical Transfer Function. Finally, the non-linear sRGB Colourspace Values are converted to hexadecimal. Note that the colours will overflow an 8-bit container thus you will need to normalise them. Python Implementation (Live Google Colab Notebook) import colour import colour.plotting import numpy as np def CCT_to_mired(K): return 10e6 / colour.utilities.as_float_array(K) def mired_to_CCT(M): return 10e6 / colour.utilities.as_float_array(M) M = CCT_to_mired( ['2000', '3000', '4000', '5000', '6000', '7000', '8000', '9000']) K = mired_to_CCT(M) xy = colour.CCT_to_xy(K, method='Kang 2002') XYZ = colour.xy_to_XYZ(xy) RGB = colour.XYZ_to_sRGB(XYZ) # Note that the colours are overflowing 8-bit, thus a normalisation # process must be used. RGB /= np.max(RGB, axis=1)[..., np.newaxis] colour.plotting.plot_multi_colour_swatches( [colour.plotting.ColourSwatch(RGB=np.clip(x, 0, 1)) for x in RGB]) print(colour.utilities.as_int_array(RGB * 255)) print(colour.notation.RGB_to_HEX(RGB)) # Conversion using the *Automatic Colour Conversion Graph*: print(colour.convert(K, 'CCT', 'Hexadecimal', CCT_to_xy={'method': 'Kang 2002'})) [[255 140 25] [255 184 111] [255 211 165] [255 230 207] [255 243 240] [244 242 255] [226 231 255] [214 223 255]] ['#ff8c19' '#ffb86f' '#ffd3a5' '#ffe6cf' '#fff3f0' '#f4f2ff' '#e2e7ff' '#d6dfff'] ['#7dd226' '#46ec8e' '#28f6c1' '#15fae2' '#08fcf9' '#fffd0a' '#f9fe17' '#f4fe22'] A: I made a quick-and-dirty solution in Python (+ numpy). It's very suitable to convert in cases when you don't really need too much accuracy, but the general idea should be preserved: import numpy as np def mired_to_rgb(mired): """ Quick and dirty, returns r, g, b tuple (all between 0 and 1) """ M2RGB = MIRED_RGB.T r = np.interp(mired, M2RGB[0], M2RGB[1]) g = np.interp(mired, M2RGB[0], M2RGB[2]) b = np.interp(mired, M2RGB[0], M2RGB[3]) return r, g, b MIRED_RGB = np.array([ [ 0, 0x86, 0xAE, 0xFF], [ 100, 0xBC, 0xD8, 0xFF], [ 200, 0xFE, 0xFC, 0xFF], [ 300, 0xFF, 0xED, 0xB6], [ 400, 0xFF, 0xD8, 0x77], [ 500, 0xFF, 0xC1, 0x40], [ 600, 0xFF, 0xA8, 0x00], [ 700, 0xFF, 0x90, 0x00], [ 800, 0xFF, 0x76, 0x00], [ 900, 0xFF, 0x59, 0x00], [1000, 0xFF, 0x39, 0x00], [1050, 0xFF, 0x00, 0x00], ]) / [1, 0xFF, 0xFF, 0xFF] I took the known colour values for some mireds (literally by using a colour picker on the colours in the image on the Mired wikipedia page). Then I interpolate, by interpolating separately the R, G and B values (as I said, only a rough approximation). If you want the thing to return values between 0 and 255, remove the / [1, 0xFF, 0xFF, 0xFF] at the end. Using numpy's interp to interpolate, but it shouldn't be hard to remove this dependency and make your own interp().
How can i convert mireds to RGB or display mireds in css?
From an application i get a color temprature in mireds, i want to display it in a HTML box but i cant find a way to display it via mireds. I thought there was an answer anywhere on the internet for displaying it or converting it. But, unfortunately not. Does anyone know how i can convert or display it? Regards, Kuno
[ "The conversion you want to perform can be highly involved depending on the degree of precision required. Here is an outline of the algorithm and a Python implementation using Colour.\n\nM (Mired) is the MIcro REciprocal Degree (Colour) Temperature K (Kelvin) thus the first step is the conversion from Mired to Kelvin as follows: K = 10e6 / M.\nThen the Colour Temperature K can be converted to CIE xy Chromaticity Coordinates using a method such as Kang et al. (2002) for simplicity or if extreme precision is required Robertson (1968) or Ohno (2013) (but this is much more involved to convert to Javascript).\nSubsequently, the CIE xy Chromaticity Coordinates (equivalent to CIE xyY with Luminance set to 1) can be converted to CIE XYZ Tristimulus Values.\nThe CIE XYZ tristimulus values can be converted to sRGB Colourspace Values, at its simplest, it is a matrix multiplication using the IEC 61966-2-1:1999 matrix.\nThe sRGB Colourspace Values are non-linearly encoded with the sRGB Inverse Electro-Optical Transfer Function.\nFinally, the non-linear sRGB Colourspace Values are converted to hexadecimal. Note that the colours will overflow an 8-bit container thus you will need to normalise them.\n\nPython Implementation (Live Google Colab Notebook)\nimport colour\nimport colour.plotting\nimport numpy as np\n\n\ndef CCT_to_mired(K):\n return 10e6 / colour.utilities.as_float_array(K)\n\n\ndef mired_to_CCT(M):\n return 10e6 / colour.utilities.as_float_array(M)\n\n\nM = CCT_to_mired(\n ['2000', '3000', '4000', '5000', '6000', '7000', '8000', '9000'])\n\nK = mired_to_CCT(M)\nxy = colour.CCT_to_xy(K, method='Kang 2002')\nXYZ = colour.xy_to_XYZ(xy)\nRGB = colour.XYZ_to_sRGB(XYZ)\n# Note that the colours are overflowing 8-bit, thus a normalisation\n# process must be used.\nRGB /= np.max(RGB, axis=1)[..., np.newaxis]\n\ncolour.plotting.plot_multi_colour_swatches(\n [colour.plotting.ColourSwatch(RGB=np.clip(x, 0, 1)) for x in RGB])\n\nprint(colour.utilities.as_int_array(RGB * 255))\nprint(colour.notation.RGB_to_HEX(RGB))\n\n# Conversion using the *Automatic Colour Conversion Graph*:\nprint(colour.convert(K, 'CCT', 'Hexadecimal', CCT_to_xy={'method': 'Kang 2002'}))\n\n\n[[255 140 25]\n [255 184 111]\n [255 211 165]\n [255 230 207]\n [255 243 240]\n [244 242 255]\n [226 231 255]\n [214 223 255]]\n['#ff8c19' '#ffb86f' '#ffd3a5' '#ffe6cf' '#fff3f0' '#f4f2ff' '#e2e7ff'\n'#d6dfff']\n['#7dd226' '#46ec8e' '#28f6c1' '#15fae2' '#08fcf9' '#fffd0a' '#f9fe17'\n'#f4fe22']\n\n", "I made a quick-and-dirty solution in Python (+ numpy). It's very suitable to convert in cases when you don't really need too much accuracy, but the general idea should be preserved:\nimport numpy as np\n\ndef mired_to_rgb(mired):\n \"\"\"\n Quick and dirty, returns r, g, b tuple (all between 0 and 1)\n \"\"\"\n M2RGB = MIRED_RGB.T\n r = np.interp(mired, M2RGB[0], M2RGB[1])\n g = np.interp(mired, M2RGB[0], M2RGB[2])\n b = np.interp(mired, M2RGB[0], M2RGB[3])\n return r, g, b\n\n\nMIRED_RGB = np.array([\n [ 0, 0x86, 0xAE, 0xFF],\n [ 100, 0xBC, 0xD8, 0xFF],\n [ 200, 0xFE, 0xFC, 0xFF],\n [ 300, 0xFF, 0xED, 0xB6],\n [ 400, 0xFF, 0xD8, 0x77],\n [ 500, 0xFF, 0xC1, 0x40],\n [ 600, 0xFF, 0xA8, 0x00],\n [ 700, 0xFF, 0x90, 0x00],\n [ 800, 0xFF, 0x76, 0x00],\n [ 900, 0xFF, 0x59, 0x00],\n [1000, 0xFF, 0x39, 0x00],\n [1050, 0xFF, 0x00, 0x00],\n ]) / [1, 0xFF, 0xFF, 0xFF]\n\nI took the known colour values for some mireds (literally by using a colour picker on the colours in the image on the Mired wikipedia page). Then I interpolate, by interpolating separately the R, G and B values (as I said, only a rough approximation).\nIf you want the thing to return values between 0 and 255, remove the / [1, 0xFF, 0xFF, 0xFF] at the end.\nUsing numpy's interp to interpolate, but it shouldn't be hard to remove this dependency and make your own interp().\n" ]
[ 3, 0 ]
[]
[]
[ "colors", "javascript" ]
stackoverflow_0060777515_colors_javascript.txt
Q: Unexpected behavior in Python's set.issubset I have the following code (Pdb) set(range(2, 2)).issubset(set(range(10, 95))) True and I don't understand why it's returning True. issubset is supposed to check if a set contains all the items of another set, but 2 can't be contained in a range from 10 to 95. Am I misunderstanding Python's doc? Or is that a bug? A: The code set(range(2, 2)).issubset(set(range(10, 95))) is returning True because the set range(2, 2) is an empty set, and an empty set is always a subset of any other set. The range function returns a range object that generates a sequence of numbers. When called with two arguments, start and stop, range(start, stop) generates a sequence of numbers from start to stop (exclusive), i.e. range(start, stop) generates the sequence start, start+1, start+2, ..., stop-1. In this code, range(2, 2) generates an empty sequence, because 2 is not less than 2 and therefore no numbers are generated. This means that set(range(2, 2)) creates a set containing no elements, which is an empty set. Since an empty set is a subset of any other set (including the set set(range(10, 95))), the issubset method returns True when called on set(range(2, 2)) and set(range(10, 95)). A: a = set(range(2,2)) is returning empty set Since, set "a" has nothing to compare in set "b" therefore it is returning True. A: It looks like you are misunderstanding the behavior of the issubset method in Python. This method checks whether a set is a subset of another set, not whether a range is a subset of another range. In your code, you are creating two sets: set(range(2, 2)) and set(range(10, 95)) The first set is an empty set, since the range from 2 to 2 is an empty range. The second set contains the numbers from 10 to 94, inclusive. When you use the issubset method, you are checking whether the empty set is a subset of the set containing the numbers from 10 to 94. Since empty set is a subset of any set, the issubset method returns True. To check whether a range is a subset of another range, you can use the in operator instead. For example: set(range(2, 2)) in set(range(10, 95)) This code will return False, since the range from 2 to 2 is not contained in the range from 10 to 94. In summary, your code is not a bug and it is returning the correct result based on the inputs you provided. The issue is that you are using the issubset method incorrectly, and you should use the in operator instead to check whether a range is a subset of another range.
Unexpected behavior in Python's set.issubset
I have the following code (Pdb) set(range(2, 2)).issubset(set(range(10, 95))) True and I don't understand why it's returning True. issubset is supposed to check if a set contains all the items of another set, but 2 can't be contained in a range from 10 to 95. Am I misunderstanding Python's doc? Or is that a bug?
[ "The code set(range(2, 2)).issubset(set(range(10, 95))) is returning True because the set range(2, 2) is an empty set, and an empty set is always a subset of any other set.\nThe range function returns a range object that generates a sequence of numbers. When called with two arguments, start and stop, range(start, stop) generates a sequence of numbers from start to stop (exclusive), i.e. range(start, stop) generates the sequence start, start+1, start+2, ..., stop-1.\nIn this code, range(2, 2) generates an empty sequence, because 2 is not less than 2 and therefore no numbers are generated. This means that set(range(2, 2)) creates a set containing no elements, which is an empty set.\nSince an empty set is a subset of any other set (including the set set(range(10, 95))), the issubset method returns True when called on set(range(2, 2)) and set(range(10, 95)).\n", "a = set(range(2,2)) is returning empty set\n\nSince, set \"a\" has nothing to compare in set \"b\" therefore it is returning True.\n", "It looks like you are misunderstanding the behavior of the issubset method in Python. This method checks whether a set is a subset of another set, not whether a range is a subset of another range.\nIn your code, you are creating two sets:\nset(range(2, 2))\n\nand\nset(range(10, 95))\n\nThe first set is an empty set, since the range from 2 to 2 is an empty range. The second set contains the numbers from 10 to 94, inclusive.\nWhen you use the issubset method, you are checking whether the empty set is a subset of the set containing the numbers from 10 to 94. Since empty set is a subset of any set, the issubset method returns True.\nTo check whether a range is a subset of another range, you can use the in operator instead. For example:\nset(range(2, 2)) in set(range(10, 95))\n\nThis code will return False, since the range from 2 to 2 is not contained in the range from 10 to 94.\nIn summary, your code is not a bug and it is returning the correct result based on the inputs you provided. The issue is that you are using the issubset method incorrectly, and you should use the in operator instead to check whether a range is a subset of another range.\n" ]
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074675632_python.txt
Q: Cyclic dependencies and interfaces I am a long time python developer. I was trying out Go, converting an existing python app to Go. It is modular and works really well for me. Upon creating the same structure in Go, I seem to land in cyclic import errors, a lot more than I want to. Never had any import problems in python. I never even had to use import aliases. So I may have had some cyclic imports which were not evident in python. I actually find that strange. Anyways, I am lost, trying to fix these in Go. I have read that interfaces can be used to avoid cyclic dependencies. But I don't understand how. I didn't find any examples on this either. Can somebody help me on this? The current python application structure is as follows: /main.py /settings/routes.py contains main routes depends on app1/routes.py, app2/routes.py etc /settings/database.py function like connect() which opens db session /settings/constants.py general constants /apps/app1/views.py url handler functions /apps/app1/models.py app specific database functions depends on settings/database.py /apps/app1/routes.py app specific routes /apps/app2/views.py url handler functions /apps/app2/models.py app specific database functions depends on settings/database.py /apps/app2/routes.py app specific routes settings/database.py has generic functions like connect() which opens a db session. So an app in the apps package calls database.connect() and a db session is opened. The same is the case with settings/routes.py it has functions that allow apps to add their sub-routes to the main route object. The settings package is more about functions than data/constants. This contains code that is used by apps in the apps package, that would otherwise have to be duplicated in all the apps. So if I need to change the router class, for instance, I just have to change settings/router.py and the apps will continue to work with no modifications. A: There're two high-level pieces to this: figuring out which code goes in which package, and tweaking your APIs to reduce the need for packages to take on as many dependencies. On designing APIs that avoid the need for some imports: Write config functions for hooking packages up to each other at run time rather than compile time. Instead of routes importing all the packages that define routes, it can export routes.Register, which main (or code in each app) can call. In general, configuration info probably flows through main or a dedicated package; scattering it around too much can make it hard to manage. Pass around basic types and interface values. If you're depending on a package for just a type name, maybe you can avoid that. Maybe some code handling a []Page can get instead use a []string of filenames or a []int of IDs or some more general interface (sql.Rows) instead. Consider having 'schema' packages with just pure data types and interfaces, so User is separate from code that might load users from the database. It doesn't have to depend on much (maybe on anything), so you can include it from anywhere. Ben Johnson gave a lightning talk at GopherCon 2016 suggesting that and organizing packages by dependencies. On organizing code into packages: As a rule, split a package up when each piece could be useful on its own. If two pieces of functionality are really intimately related, you don't have to split them into packages at all; you can organize with multiple files or types instead. Big packages can be OK; Go's net/http is one, for instance. Break up grab-bag packages (utils, tools) by topic or dependency. Otherwise you can end up importing a huge utils package (and taking on all its dependencies) for one or two pieces of functionality (that wouldn't have so many dependencies if separated out). Consider pushing reusable code 'down' into lower-level packages untangled from your particular use case. If you have a package page containing both logic for your content management system and all-purpose HTML-manipulation code, consider moving the HTML stuff "down" to a package html so you can use it without importing unrelated content management stuff. Here, I'd rearrange things so the router doesn't need to include the routes: instead, each app package calls a router.Register() method. This is what the Gorilla web toolkit's mux package does. Your routes, database, and constants packages sound like low-level pieces that should be imported by your app code and not import it. Generally, try to build your app in layers. Your higher-layer, use-case-specific app code should import lower-layer, more fundamental tools, and never the other way around. Here are some more thoughts: Packages are good for separating independently usable bits of functionality from the caller's perspective. For your internal code organization, you can easily shuffle code between source files in the package. The initial namespace for symbols you define in x/foo.go or x/bar.go is just package x, and it's not that hard to split/join files as needed, especially with the help of a utility like goimports. The standard library's net/http is about 7k lines (counting comments/blanks but not tests). Internally, it's split into many smaller files and types. But it's one package, I think 'cause there was no reason users would want, say, just cookie handling on its own. On the other hand, net and net/url are separate because they have uses outside HTTP. It's great if you can push "down" utilities into libraries that are independent and feel like their own polished products, or cleanly layer your application itself (e.g., UI sits atop an API sits atop some core libraries and data models). Likewise "horizontal" separation may help you hold the app in your head (e.g., the UI layer breaks up into user account management, the application core, and administrative tools, or something finer-grained than that). But, the core point is, you're free to split or not as works for you. Set up APIs to configure behavior at run-time so you don't have to import it at compile time. So, for example, your URL router can expose a Register method instead of importing appA, appB, etc. and reading a var Routes from each. You could make a myapp/routes package that imports router and all your views and calls router.Register. The fundamental idea is that the router is all-purpose code that needn't import your application's views. Some ways to put together config APIs: Pass app behavior via interfaces or funcs: http can be passed custom implementations of Handler (of course) but also CookieJar or File. text/template and html/template can accept functions to be accessible from templates (in a FuncMap). Export shortcut functions from your package if appropriate: In http, callers can either make and separately configure some http.Server objects, or call http.ListenAndServe(...) that uses a global Server. That gives you a nice design--everything's in an object and callers can create multiple Servers in a process and such--but it also offers a lazy way to configure in the simple single-server case. If you have to, just duct-tape it: You don't have to limit yourself to super-elegant config systems if you can't fit one to your app: maybe for some stuff a package "myapp/conf" with a global var Conf map[string]interface{} is useful. But be aware of downsides to global conf. If you want to write reusable libraries, they can't import myapp/conf; they need to accept all the info they need in constructors, etc. Globals also risk hard-wiring in an assumption something will always have a single value app-wide when it eventually won't; maybe today you have a single database config or HTTP server config or such, but someday you don't. Some more specific ways to move code or change definitions to reduce dependency issues: Separate fundamental tasks from app-dependent ones. One app I work on in another language has a "utils" module mixing general tasks (e.g., formatting datetimes or working with HTML) with app-specific stuff (that depends on the user schema, etc.). But the users package imports the utils, creating a cycle. If I were porting to Go, I'd move the user-dependent utils "up" out of the utils module, maybe to live with the user code or even above it. Consider breaking up grab-bag packages. Slightly enlarging on the last point: if two pieces of functionality are independent (that is, things still work if you move some code to another package) and unrelated from the user's perspective, they're candidates to be separated into two packages. Sometimes the bundling is harmless, but other times it leads to extra dependencies, or a less generic package name would just make clearer code. So my utils above might be broken up by topic or dependency (e.g., strutil, dbutil, etc.). If you wind up with lots of packages this way, we've got goimports to help manage them. Replace import-requiring object types in APIs with basic types and interfaces. Say two entities in your app have a many-to-many relationship like Users and Groups. If they live in different packages (a big 'if'), you can't have both u.Groups() returning a []group.Group and g.Users() returning []user.User because that requires the packages to import each other. However, you could change one or both of those return, say, a []uint of IDs or a sql.Rows or some other interface you can get to without importing a specific object type. Depending on your use case, types like User and Group might be so intimately related that it's better just to put them in one package, but if you decide they should be distinct, this is a way. Thanks for the detailed question and followup. A: Possible partial, but ugly answer: Have struggled with the import cyclic dependency problem for a year. For a while, was able to decouple enough so that there wasn't an import cycle. My application uses plugins heavily. At the same time, it uses encode/decode libraries (json and gob). For these, I have custom marshall and unmarshall methods, and equivalent for json. For these to work, the full type name including the package name must be identical on data structures that are passed to the codecs. The creation of the codecs must be in a package. This package is called from both other packages as well as from plugins. Everything works as long as the codec package doesn't need to call out to any package calling it, or use the methods or interfaces to the methods. In order to be able to use the types from the package in the plugins, the plugins have to be compiled with the package. Since I don't want to have to include the main program in the builds for the plugins, which would break the point of the plugins, only the codec package is included in both the plugins and the main program. Everything works up until I need to call from the codec package in to the main program, after the main program has called in to the codec package. This will cause an import cycle. To get rid of this, I can put the codec in the main program instead of its own package. But, because the specific datatypes being used in the marshalling/unmarshalling methods must be the same in the main program and the plugins, I would need to compile with the main program package for each of the plugins. Further, because I need to the main program to call out to the plugins I need the interface types for the plugins in the main program. Having never found a way to get this to work, I did think of a possible solution: First, separate the codec in to a plugin, instead of just a package Then, load it as the first plugin from the main program. Create a registration function to exchange interfaces with underlying methods. All encoders and decoders are created by calls in to this plugin. The plugin calls back to the main program through the registered interface. The main program and all the plugins use the same interface type package for this. However, the datatypes for the actual encoded data are referenced in the main program with a different name, but same underlying type than in the plugins, otherwise the same import cycle exists. to do this part requires doing an unsafe cast. Wrote a little function that does a forced cast so that the syntax is clean: (<cast pointer type*>Cast(<pointer to structure, or interface to pointer to structure>). The only other issue for the codecs is to make sure that when the data is sent to the encoder, it is cast so that the marshall/unmarshall methods recognize the datatype names. To make that easier, can import both the main program types from one package, and the plugin types from another package since they don't reference each other. Very complex workaround, but don't see how else to make this work. Have not tried this yet. May still end up with an import cycle when everything is done. [more on this] To avoid the import cycle problem, I use an unsafe type approach using pointers. First, here is a package with a little function Cast() to do the unsafe typecasting, to make the code easier to read: package ForcedCast import ( "unsafe" "reflect" ) // cast function to do casts with to hide the ugly syntax // used as the following: // <var> = (cast type)(cast(input var)) func Cast(i interface{})(unsafe.Pointer) { return (unsafe.Pointer(reflect.ValueOf(i).Pointer())) } Next I use the "interface{}" as the equivalent of a void pointer: package firstpackage type realstruct struct { ... } var Data realstruct // setup a function to call in to a loaded plugin var calledfuncptr func(interface) func callingfunc() { pluginpath := path.Join(<pathname>, "calledfuncplugin") plug, err := plugin.Open(pluginpath) rFunc, err := plug.Lookup("calledfunc") calledfuncptr = rFunc.(interface{}) calledfuncptr (&Data) } //in a plugin //plugins don't use packages for the main code, are build with -buildmode=plugin package main // identical definition of structure type realstruct struct { ... } var localdataptr *realstruct func calledfunc(needcast interface{}) { localdataptr = (*realstruct)(Cast(needcast)) } For cross type dependencies to any other packages, use the "interface{}" as a void pointer and cast appropriately as needed. This only works if the underlying type that is pointed to by the interface{} is identical wherever it is cast. To make this easier, I put the types in a separate file. In the calling package, they start with the package name. I then make a copy of the type file, change the package to "package main", and put it in the plugin directory so that the types are built, but not the package name. There is probably a way to do this for the actual data values, not just pointers, but I haven't gotten that to work right. One of the things I have done is to cast to an interface instead of a datatype pointer. This allows you to send interfaces to packages using the plugin approach, where there is an import cycle. The interface has a pointer to the datatype, and then you can use it for calling the methods on the datatype from the caller from the package that called in to the plugin. The reason why this works is that the datatypes are not visible outside of the plugin. That is, if I load to plugins, which are both package main, and the types are defined in the package main for both, but are different types with the same names, the types do not conflict. However, if I put a common package in to both plugins, that package must be identical and have the exact full pathname for where it was compiled from. To accommodate this, I use a docker container to do my builds so that I can force the pathnames to always be correct for any common containers across my plugins. I did say this was ugly, but it does work. If there is an import cycle because a type in one package uses a type in another package that then tries to use a type from the first package, the approach is to do a plugin that erases both types with interface{}. You can then make method and function calls back and forth doing the casting on the receiving side as needed. In summary: Use interface{} to make void pointers (that is, untyped). Use the Cast() to force them to a pointer type that matches the underlying pointer. Use the plugin type localization so that types in the package main in separate plugins, and in the main program do not conflict If you use a common package between plugins, the path must be identical for all built plugins and the main program. Use the plug package to load the plugins, and exchange function pointers For one of my issues I'm actually calling from a package in the main program out to a plugin, just to be able to call back to another package in the main program, avoiding the import cycle between the two packages. I ran in to this problem using the json and gob packages with custom marshaller methods. I use the types that are custom marshalled both in my main program, and in other plugins, while at the same time, I want the plugins to be built independent of the main program. I accomplish this by using a package for json and gob encode/decode custom methods that is included both in the main program and the plugins. However, I needed to be able to call back to the main program from the encoder methods, which gave me the import cycle type conflict. The above solution with another plugin specifically to solve the import cycle works. It does create an extra function call, but I have yet to see any other solution to this. Hope this helps with this issue. A: A shorter answer to your question (using interface), that does not take away the correctness and completeness of the other answers, is this example: UserService is causing cyclic import, where it should not really be called from AuthorizationService. It's just there to be able to extract the user details, so we can declare only the desired functionality in a separated receiver-side interface UserProvider: https://github.com/tzvatot/cyclic-import-solving-exaple/commit/bc60d7cfcbd4c3b6540bdb4117ab95c3f2987389 Basically, extracting an interface that contains only the required functionality on the receiver side, and use it instead of declaring a dependency on something external.
Cyclic dependencies and interfaces
I am a long time python developer. I was trying out Go, converting an existing python app to Go. It is modular and works really well for me. Upon creating the same structure in Go, I seem to land in cyclic import errors, a lot more than I want to. Never had any import problems in python. I never even had to use import aliases. So I may have had some cyclic imports which were not evident in python. I actually find that strange. Anyways, I am lost, trying to fix these in Go. I have read that interfaces can be used to avoid cyclic dependencies. But I don't understand how. I didn't find any examples on this either. Can somebody help me on this? The current python application structure is as follows: /main.py /settings/routes.py contains main routes depends on app1/routes.py, app2/routes.py etc /settings/database.py function like connect() which opens db session /settings/constants.py general constants /apps/app1/views.py url handler functions /apps/app1/models.py app specific database functions depends on settings/database.py /apps/app1/routes.py app specific routes /apps/app2/views.py url handler functions /apps/app2/models.py app specific database functions depends on settings/database.py /apps/app2/routes.py app specific routes settings/database.py has generic functions like connect() which opens a db session. So an app in the apps package calls database.connect() and a db session is opened. The same is the case with settings/routes.py it has functions that allow apps to add their sub-routes to the main route object. The settings package is more about functions than data/constants. This contains code that is used by apps in the apps package, that would otherwise have to be duplicated in all the apps. So if I need to change the router class, for instance, I just have to change settings/router.py and the apps will continue to work with no modifications.
[ "There're two high-level pieces to this: figuring out which code goes in which package, and tweaking your APIs to reduce the need for packages to take on as many dependencies. \nOn designing APIs that avoid the need for some imports:\n\nWrite config functions for hooking packages up to each other at run time rather than compile time. Instead of routes importing all the packages that define routes, it can export routes.Register, which main (or code in each app) can call. In general, configuration info probably flows through main or a dedicated package; scattering it around too much can make it hard to manage.\nPass around basic types and interface values. If you're depending on a package for just a type name, maybe you can avoid that. Maybe some code handling a []Page can get instead use a []string of filenames or a []int of IDs or some more general interface (sql.Rows) instead. \nConsider having 'schema' packages with just pure data types and interfaces, so User is separate from code that might load users from the database. It doesn't have to depend on much (maybe on anything), so you can include it from anywhere. Ben Johnson gave a lightning talk at GopherCon 2016 suggesting that and organizing packages by dependencies.\n\nOn organizing code into packages:\n\nAs a rule, split a package up when each piece could be useful on its own. If two pieces of functionality are really intimately related, you don't have to split them into packages at all; you can organize with multiple files or types instead. Big packages can be OK; Go's net/http is one, for instance.\nBreak up grab-bag packages (utils, tools) by topic or dependency. Otherwise you can end up importing a huge utils package (and taking on all its dependencies) for one or two pieces of functionality (that wouldn't have so many dependencies if separated out).\nConsider pushing reusable code 'down' into lower-level packages untangled from your particular use case. If you have a package page containing both logic for your content management system and all-purpose HTML-manipulation code, consider moving the HTML stuff \"down\" to a package html so you can use it without importing unrelated content management stuff. \n\n\nHere, I'd rearrange things so the router doesn't need to include the routes: instead, each app package calls a router.Register() method. This is what the Gorilla web toolkit's mux package does. Your routes, database, and constants packages sound like low-level pieces that should be imported by your app code and not import it.\nGenerally, try to build your app in layers. Your higher-layer, use-case-specific app code should import lower-layer, more fundamental tools, and never the other way around. Here are some more thoughts:\n\nPackages are good for separating independently usable bits of functionality from the caller's perspective. For your internal code organization, you can easily shuffle code between source files in the package. The initial namespace for symbols you define in x/foo.go or x/bar.go is just package x, and it's not that hard to split/join files as needed, especially with the help of a utility like goimports.\nThe standard library's net/http is about 7k lines (counting comments/blanks but not tests). Internally, it's split into many smaller files and types. But it's one package, I think 'cause there was no reason users would want, say, just cookie handling on its own. On the other hand, net and net/url are separate because they have uses outside HTTP.\nIt's great if you can push \"down\" utilities into libraries that are independent and feel like their own polished products, or cleanly layer your application itself (e.g., UI sits atop an API sits atop some core libraries and data models). Likewise \"horizontal\" separation may help you hold the app in your head (e.g., the UI layer breaks up into user account management, the application core, and administrative tools, or something finer-grained than that). But, the core point is, you're free to split or not as works for you.\nSet up APIs to configure behavior at run-time so you don't have to import it at compile time. So, for example, your URL router can expose a Register method instead of importing appA, appB, etc. and reading a var Routes from each. You could make a myapp/routes package that imports router and all your views and calls router.Register. The fundamental idea is that the router is all-purpose code that needn't import your application's views.\nSome ways to put together config APIs:\n\nPass app behavior via interfaces or funcs: http can be passed custom implementations of Handler (of course) but also CookieJar or File. text/template and html/template can accept functions to be accessible from templates (in a FuncMap).\nExport shortcut functions from your package if appropriate: In http, callers can either make and separately configure some http.Server objects, or call http.ListenAndServe(...) that uses a global Server. That gives you a nice design--everything's in an object and callers can create multiple Servers in a process and such--but it also offers a lazy way to configure in the simple single-server case. \nIf you have to, just duct-tape it: You don't have to limit yourself to super-elegant config systems if you can't fit one to your app: maybe for some stuff a package \"myapp/conf\" with a global var Conf map[string]interface{} is useful. \nBut be aware of downsides to global conf. If you want to write reusable libraries, they can't import myapp/conf; they need to accept all the info they need in constructors, etc. Globals also risk hard-wiring in an assumption something will always have a single value app-wide when it eventually won't; maybe today you have a single database config or HTTP server config or such, but someday you don't.\n\n\nSome more specific ways to move code or change definitions to reduce dependency issues:\n\nSeparate fundamental tasks from app-dependent ones. One app I work on in another language has a \"utils\" module mixing general tasks (e.g., formatting datetimes or working with HTML) with app-specific stuff (that depends on the user schema, etc.). But the users package imports the utils, creating a cycle. If I were porting to Go, I'd move the user-dependent utils \"up\" out of the utils module, maybe to live with the user code or even above it.\nConsider breaking up grab-bag packages. Slightly enlarging on the last point: if two pieces of functionality are independent (that is, things still work if you move some code to another package) and unrelated from the user's perspective, they're candidates to be separated into two packages. Sometimes the bundling is harmless, but other times it leads to extra dependencies, or a less generic package name would just make clearer code. So my utils above might be broken up by topic or dependency (e.g., strutil, dbutil, etc.). If you wind up with lots of packages this way, we've got goimports to help manage them.\nReplace import-requiring object types in APIs with basic types and interfaces. Say two entities in your app have a many-to-many relationship like Users and Groups. If they live in different packages (a big 'if'), you can't have both u.Groups() returning a []group.Group and g.Users() returning []user.User because that requires the packages to import each other. \nHowever, you could change one or both of those return, say, a []uint of IDs or a sql.Rows or some other interface you can get to without importing a specific object type. Depending on your use case, types like User and Group might be so intimately related that it's better just to put them in one package, but if you decide they should be distinct, this is a way. \n\nThanks for the detailed question and followup.\n", "Possible partial, but ugly answer:\nHave struggled with the import cyclic dependency problem for a year. For a while, was able to decouple enough so that there wasn't an import cycle. My application uses plugins heavily. At the same time, it uses encode/decode libraries (json and gob). For these, I have custom marshall and unmarshall methods, and equivalent for json.\nFor these to work, the full type name including the package name must be identical on data structures that are passed to the codecs. The creation of the codecs must be in a package. This package is called from both other packages as well as from plugins.\nEverything works as long as the codec package doesn't need to call out to any package calling it, or use the methods or interfaces to the methods. In order to be able to use the types from the package in the plugins, the plugins have to be compiled with the package. Since I don't want to have to include the main program in the builds for the plugins, which would break the point of the plugins, only the codec package is included in both the plugins and the main program. Everything works up until I need to call from the codec package in to the main program, after the main program has called in to the codec package. This will cause an import cycle. To get rid of this, I can put the codec in the main program instead of its own package. But, because the specific datatypes being used in the marshalling/unmarshalling methods must be the same in the main program and the plugins, I would need to compile with the main program package for each of the plugins. Further, because I need to the main program to call out to the plugins I need the interface types for the plugins in the main program. Having never found a way to get this to work, I did think of a possible solution:\nFirst, separate the codec in to a plugin, instead of just a package\nThen, load it as the first plugin from the main program.\nCreate a registration function to exchange interfaces with underlying methods.\nAll encoders and decoders are created by calls in to this plugin.\nThe plugin calls back to the main program through the registered interface.\nThe main program and all the plugins use the same interface type package for this.\nHowever, the datatypes for the actual encoded data are referenced in the main program\nwith a different name, but same underlying type than in the plugins, otherwise the same import cycle exists. to do this part requires doing an unsafe cast. Wrote\na little function that does a forced cast so that the syntax is clean:\n(<cast pointer type*>Cast(<pointer to structure, or interface to pointer to structure>).\nThe only other issue for the codecs is to make sure that when the data is sent to the encoder, it is cast so that the marshall/unmarshall methods recognize the datatype names. To make that easier, can import both the main program types from one package, and the plugin types from another package since they don't reference each other.\nVery complex workaround, but don't see how else to make this work.\nHave not tried this yet. May still end up with an import cycle when everything is done.\n[more on this]\nTo avoid the import cycle problem, I use an unsafe type approach using pointers. First, here is a package with a little function Cast() to do the unsafe typecasting, to make the code easier to read:\npackage ForcedCast\n\nimport (\n \"unsafe\"\n \"reflect\"\n)\n\n// cast function to do casts with to hide the ugly syntax\n// used as the following:\n// <var> = (cast type)(cast(input var))\nfunc Cast(i interface{})(unsafe.Pointer) {\n return (unsafe.Pointer(reflect.ValueOf(i).Pointer()))\n}\n\nNext I use the \"interface{}\" as the equivalent of a void pointer:\n\npackage firstpackage\ntype realstruct struct {\n ...\n} \n\nvar Data realstruct\n\n// setup a function to call in to a loaded plugin\nvar calledfuncptr func(interface)\n\nfunc callingfunc() {\n\n pluginpath := path.Join(<pathname>, \"calledfuncplugin\")\n plug, err := plugin.Open(pluginpath)\n\n rFunc, err := plug.Lookup(\"calledfunc\")\n calledfuncptr = rFunc.(interface{})\n\n calledfuncptr (&Data)\n}\n\n\n//in a plugin\n//plugins don't use packages for the main code, are build with -buildmode=plugin\npackage main\n\n// identical definition of structure\ntype realstruct struct {\n ...\n} \n\nvar localdataptr *realstruct\n\nfunc calledfunc(needcast interface{}) {\n\n localdataptr = (*realstruct)(Cast(needcast))\n\n}\n\nFor cross type dependencies to any other packages, use the \"interface{}\" as a void pointer and cast appropriately as needed.\nThis only works if the underlying type that is pointed to by the interface{} is identical wherever it is cast. To make this easier, I put the types in a separate file. In the calling package, they start with the package name. I then make a copy of the type file, change the package to \"package main\", and put it in the plugin directory so that the types are built, but not the package name.\nThere is probably a way to do this for the actual data values, not just pointers, but I haven't gotten that to work right.\nOne of the things I have done is to cast to an interface instead of a datatype pointer. This allows you to send interfaces to packages using the plugin approach, where there is an import cycle. The interface has a pointer to the datatype, and then you can use it for calling the methods on the datatype from the caller from the package that called in to the plugin.\nThe reason why this works is that the datatypes are not visible outside of the plugin. That is, if I load to plugins, which are both package main, and the types are defined in the package main for both, but are different types with the same names, the types do not conflict.\nHowever, if I put a common package in to both plugins, that package must be identical and have the exact full pathname for where it was compiled from. To accommodate this, I use a docker container to do my builds so that I can force the pathnames to always be correct for any common containers across my plugins.\nI did say this was ugly, but it does work. If there is an import cycle because a type in one package uses a type in another package that then tries to use a type from the first package, the approach is to do a plugin that erases both types with interface{}. You can then make method and function calls back and forth doing the casting on the receiving side as needed.\nIn summary:\nUse interface{} to make void pointers (that is, untyped).\nUse the Cast() to force them to a pointer type that matches the underlying pointer. Use the plugin type localization so that types in the package main in separate plugins, and in the main program do not conflict If you use a common package between plugins, the path must be identical for all built plugins and the main program. Use the plug package to load the plugins, and exchange function pointers\nFor one of my issues I'm actually calling from a package in the main program out to a plugin, just to be able to call back to another package in the main program, avoiding the import cycle between the two packages. I ran in to this problem using the json and gob packages with custom marshaller methods. I use the types that are custom marshalled both in my main program, and in other plugins, while at the same time, I want the plugins to be built independent of the main program. I accomplish this by using a package for json and gob encode/decode custom methods that is included both in the main program and the plugins. However, I needed to be able to call back to the main program from the encoder methods, which gave me the import cycle type conflict. The above solution with another plugin specifically to solve the import cycle works. It does create an extra function call, but I have yet to see any other solution to this.\nHope this helps with this issue.\n", "A shorter answer to your question (using interface), that does not take away the correctness and completeness of the other answers, is this example:\nUserService is causing cyclic import, where it should not really be called from AuthorizationService. It's just there to be able to extract the user details, so we can declare only the desired functionality in a separated receiver-side interface UserProvider:\nhttps://github.com/tzvatot/cyclic-import-solving-exaple/commit/bc60d7cfcbd4c3b6540bdb4117ab95c3f2987389\nBasically, extracting an interface that contains only the required functionality on the receiver side, and use it instead of declaring a dependency on something external.\n" ]
[ 87, 0, 0 ]
[]
[]
[ "go" ]
stackoverflow_0020380333_go.txt
Q: C - Type punning, Strict aliasing, and Endianness I've recently read about type punning and strict aliasing in C. I believe the following attempt at type-punning violates the strict aliasing rule: uint32_t x = 0; float f = *(float *)&x; In order to type-pun correctly, Wikipedia says "the strict alias rule is broken only by an explicit memcpy or by using a char pointer as a "middle man" (since those can be freely aliased)." So, my first question is: does the following code violate the strict aliasing rule (or invoke undefined/unspecified behavior)? Several sources say this is legal and fine, while others say it's not: uint32_t x = 0; float f = *(float *)(char *)&x; If so, (how) could this code be fixed? (still using the same "char pointer as a 'middle man' " idea) Or would I have to instead use memcpy or a union? If not, why? How would casting to char* and then to float* be any "safer" than simply casting to float* (or is safety not the issue)? My second question regards endianness, since that also seems to come up when discussing type-punning. If I malloc() some memory for two different data types (assuming aligned properly), could reading one or the other have different results on different platforms? As an example: float *p = malloc(sizeof(uint32_t) + sizeof(float)); // Allocating space for a uint32_t and a float uint32_t *a = (uint32_t *)(char *)p; float *b = (char *)p + sizeof(uint32_t); // Use a and b, etc. Could this change based on the endianness of the system? I'd assume not since I'm not using the value of a float read as an integer; the integer is being used as an integer and the float is being used as a float. I'd still consider myself a beginner in C, so I'm guessing there are better ways to do things like this, maybe type-punning isn't necessary at all, so feel free to include alternate solutions in your answer. Thanks. A: Wikipedia is wrong; using a “char pointer” is insufficient. You must use a character type. C 2018 6.5 7 says: An object shall have its stored value accessed only by an lvalue expression that has one of the following types: … — a character type. In *(float *)(char *)&x, you do not use a character type to access x. First the address of x is converted to a char *, then it is converted to a float *, and then * is applied. Since * is applied to a float *, this accesses the object as a float. The fact the address was converted through a char * at one point is irrelevant; the access is done as a float. And that does not conform to the rule in 6.5 7. To access the bytes of an object using a character type, you can use: unsigned char *px = (unsigned char *) &x; unsigned char *pf = (unsigned char *) &f; for (size_t i = 0; i < sizeof x; ++i) pf[i] = px[i]; Then, since px is an unsigned char *, the access px[i] is through an unsigned char type, which conforms to the rule in 6.5 7. Since there is a standard library routine to do this copy, you can also write memcpy(&f, &x, sizeof x);. Good compilers with optimization enabled will implement memcpy(&f, &x, sizeof x); as a single move operation rather than an actual byte-by-byte copy, circumstances permitting. How would casting to char* and then to float* be any "safer" than simply casting to float* (or is safety not the issue)? As explained above, it is not safer. However, if we ask “How is accessing through a character type safer than accessing an int through a float type?”, then the answer is that it conforms to the rule in 6.5 7 and puts the compiler on notice that aliasing may be occurring. Normally, if a function is passed a pointer to a float and a pointer to an int, the compiler is allowed to assume they point to different objects, and so any changes you make to things through the int pointer will not affect things used through the float pointer, and vice-versa. The compiler may optimize code based on this assumption that the two pointers do not point to the same thing. However, if you copy bytes through character lvalues, including by using memcpy, the compiler is required to allow for the possibility that those lvalues could be accessing any object (except that other rules may have additional restrictions, such as not modifying const objects). Could this change based on the endianness of the system? The C standard allows for float and int objects to have different endianness, but this is uncommon in C implementations. As long as they have the same endianness, copying the bytes of an int into a float or vice-versa will have the expected result (of revealing the encoding of a float object in a natural way in the bits of an int).
C - Type punning, Strict aliasing, and Endianness
I've recently read about type punning and strict aliasing in C. I believe the following attempt at type-punning violates the strict aliasing rule: uint32_t x = 0; float f = *(float *)&x; In order to type-pun correctly, Wikipedia says "the strict alias rule is broken only by an explicit memcpy or by using a char pointer as a "middle man" (since those can be freely aliased)." So, my first question is: does the following code violate the strict aliasing rule (or invoke undefined/unspecified behavior)? Several sources say this is legal and fine, while others say it's not: uint32_t x = 0; float f = *(float *)(char *)&x; If so, (how) could this code be fixed? (still using the same "char pointer as a 'middle man' " idea) Or would I have to instead use memcpy or a union? If not, why? How would casting to char* and then to float* be any "safer" than simply casting to float* (or is safety not the issue)? My second question regards endianness, since that also seems to come up when discussing type-punning. If I malloc() some memory for two different data types (assuming aligned properly), could reading one or the other have different results on different platforms? As an example: float *p = malloc(sizeof(uint32_t) + sizeof(float)); // Allocating space for a uint32_t and a float uint32_t *a = (uint32_t *)(char *)p; float *b = (char *)p + sizeof(uint32_t); // Use a and b, etc. Could this change based on the endianness of the system? I'd assume not since I'm not using the value of a float read as an integer; the integer is being used as an integer and the float is being used as a float. I'd still consider myself a beginner in C, so I'm guessing there are better ways to do things like this, maybe type-punning isn't necessary at all, so feel free to include alternate solutions in your answer. Thanks.
[ "Wikipedia is wrong; using a “char pointer” is insufficient. You must use a character type.\nC 2018 6.5 7 says:\n\nAn object shall have its stored value accessed only by an lvalue expression that has one of the following types:\n…\n— a character type.\n\nIn *(float *)(char *)&x, you do not use a character type to access x. First the address of x is converted to a char *, then it is converted to a float *, and then * is applied. Since * is applied to a float *, this accesses the object as a float. The fact the address was converted through a char * at one point is irrelevant; the access is done as a float. And that does not conform to the rule in 6.5 7.\nTo access the bytes of an object using a character type, you can use:\nunsigned char *px = (unsigned char *) &x;\nunsigned char *pf = (unsigned char *) &f;\nfor (size_t i = 0; i < sizeof x; ++i)\n pf[i] = px[i];\n\nThen, since px is an unsigned char *, the access px[i] is through an unsigned char type, which conforms to the rule in 6.5 7.\nSince there is a standard library routine to do this copy, you can also write memcpy(&f, &x, sizeof x);.\nGood compilers with optimization enabled will implement memcpy(&f, &x, sizeof x); as a single move operation rather than an actual byte-by-byte copy, circumstances permitting.\n\nHow would casting to char* and then to float* be any \"safer\" than simply casting to float* (or is safety not the issue)?\n\nAs explained above, it is not safer. However, if we ask “How is accessing through a character type safer than accessing an int through a float type?”, then the answer is that it conforms to the rule in 6.5 7 and puts the compiler on notice that aliasing may be occurring. Normally, if a function is passed a pointer to a float and a pointer to an int, the compiler is allowed to assume they point to different objects, and so any changes you make to things through the int pointer will not affect things used through the float pointer, and vice-versa. The compiler may optimize code based on this assumption that the two pointers do not point to the same thing. However, if you copy bytes through character lvalues, including by using memcpy, the compiler is required to allow for the possibility that those lvalues could be accessing any object (except that other rules may have additional restrictions, such as not modifying const objects).\n\nCould this change based on the endianness of the system?\n\nThe C standard allows for float and int objects to have different endianness, but this is uncommon in C implementations. As long as they have the same endianness, copying the bytes of an int into a float or vice-versa will have the expected result (of revealing the encoding of a float object in a natural way in the bits of an int).\n" ]
[ 1 ]
[]
[]
[ "c", "endianness", "memory", "type_punning", "undefined_behavior" ]
stackoverflow_0074673767_c_endianness_memory_type_punning_undefined_behavior.txt
Q: Transaction recovery in DynamoDB Does DynamoDB supporting in transaction recovery and how transaction recovery in dynamodb work? I had search in document of dynamodb and google and i not found it. A: No there is no such thing as a transaction recovery in DynamoDB. Transactions in DynamoDB are ACID compliant, but if you need to roll back a transaction then you would have to do so manually.
Transaction recovery in DynamoDB
Does DynamoDB supporting in transaction recovery and how transaction recovery in dynamodb work? I had search in document of dynamodb and google and i not found it.
[ "No there is no such thing as a transaction recovery in DynamoDB. Transactions in DynamoDB are ACID compliant, but if you need to roll back a transaction then you would have to do so manually.\n" ]
[ 1 ]
[]
[]
[ "amazon_dynamodb", "nosql" ]
stackoverflow_0074674039_amazon_dynamodb_nosql.txt
Q: How to center a text generated from an API in JS? I'm learning how to generate content with API's, but when I print in screen the generated text does not alignt with the rest of the container. <body class="container bg"> <div class="card row border-primary text-center" style="width: 40rem;"> <img src="../img/meme.jpg" class="card-img-top mx" alt="..."> <div class="card-body"> <h5 class="card-title">Best dad jokes!</h5> <div class="col-6 joke text-center"></div> <button class="col-6 btn btn-primary" onclick="pulsarBoton()">Pulsa para un nuevo chiste</button> </div> </div> <script src="api.js"></script> </body> Also I attach the API code too: const jokeText = document.querySelector(".joke"); async function buscarChiste() { const response = await fetch("https://icanhazdadjoke.com", { headers: { Accept: 'application/json', }, }); const joke = response.json(); return joke; } async function pulsarBoton() { const { joke } = await buscarChiste(); jokeText.innerText = joke; } The issue is that I need the card to be centered in the screen with all text centered but the generated text only is shown at the left of the card. Thanks in advance! Centering the API generated text A: The text is centered but you have col-6 on the div, so the container is taking 50% width of the available space making it look like it's left-aligned. Either remove col-6 or use a breakpoint: More. const jokeText = document.querySelector(".joke"); async function buscarChiste() { const response = await fetch("https://icanhazdadjoke.com", { headers: { Accept: 'application/json', }, }); const joke = response.json(); return joke; } async function pulsarBoton() { const { joke } = await buscarChiste(); jokeText.innerText = joke; } <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <body class="container bg"> <div class="card row border-primary text-center" style="width: 40rem;"> <img src="../img/meme.jpg" class="card-img-top mx" alt="..."> <div class="card-body"> <h5 class="card-title">Best dad jokes!</h5> <div class="joke text-center"></div> <button class="col-6 btn btn-primary" onclick="pulsarBoton()">Pulsa para un nuevo chiste</button> </div> </div> <script src="api.js"></script> </body>
How to center a text generated from an API in JS?
I'm learning how to generate content with API's, but when I print in screen the generated text does not alignt with the rest of the container. <body class="container bg"> <div class="card row border-primary text-center" style="width: 40rem;"> <img src="../img/meme.jpg" class="card-img-top mx" alt="..."> <div class="card-body"> <h5 class="card-title">Best dad jokes!</h5> <div class="col-6 joke text-center"></div> <button class="col-6 btn btn-primary" onclick="pulsarBoton()">Pulsa para un nuevo chiste</button> </div> </div> <script src="api.js"></script> </body> Also I attach the API code too: const jokeText = document.querySelector(".joke"); async function buscarChiste() { const response = await fetch("https://icanhazdadjoke.com", { headers: { Accept: 'application/json', }, }); const joke = response.json(); return joke; } async function pulsarBoton() { const { joke } = await buscarChiste(); jokeText.innerText = joke; } The issue is that I need the card to be centered in the screen with all text centered but the generated text only is shown at the left of the card. Thanks in advance! Centering the API generated text
[ "The text is centered but you have col-6 on the div, so the container is taking 50% width of the available space making it look like it's left-aligned. Either remove col-6 or use a breakpoint: More.\n\n\nconst jokeText = document.querySelector(\".joke\");\n\nasync function buscarChiste() {\n const response = await fetch(\"https://icanhazdadjoke.com\", {\n headers: {\n Accept: 'application/json',\n },\n });\n\n const joke = response.json();\n return joke;\n}\n\nasync function pulsarBoton() {\n const {\n joke\n } = await buscarChiste();\n jokeText.innerText = joke;\n}\n<link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC\" crossorigin=\"anonymous\">\n\n<body class=\"container bg\">\n <div class=\"card row border-primary text-center\" style=\"width: 40rem;\">\n <img src=\"../img/meme.jpg\" class=\"card-img-top mx\" alt=\"...\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">Best dad jokes!</h5>\n <div class=\"joke text-center\"></div>\n <button class=\"col-6 btn btn-primary\" onclick=\"pulsarBoton()\">Pulsa para un nuevo chiste</button>\n </div>\n </div>\n\n <script src=\"api.js\"></script>\n</body>\n\n\n\n" ]
[ 0 ]
[]
[]
[ "api_design", "bootstrap_5", "javascript", "text" ]
stackoverflow_0074674834_api_design_bootstrap_5_javascript_text.txt
Q: Netsuite REST API for cross-subsidiary item fulfillment I get the following error when I call the item fulfillment Netsuite rest api. Error while accessing a resource. You must have at least one valid line item for this transaction. The sales order needs to be fulfilled with an item that is available in another subsidiary. This can be done in UI but I have not been able to achieve that using the rest call as described from the following help site: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_161425629582.html The following is the JSON I am using: { "item": { "items": [ { "orderLine": 1, "quantity": 1, "itemReceive": true, "location": { "id": "239" }, "inventoryDetail": { "inventoryassignment": { "items": [ { "issueInventoryNumber": { "refName": "1D3B62A4000070" }, "quantity": 1.0 } ] }, "quantity": 1.0, "totalResults": 1 }, "shipGroup" : 1, "subsidiary": { "id": "1" } } ] }, "subsidiary": { "id": "1" }, "location": { "id": "239" } } The location 239 belongs in subsidiary 1 while the order is placed in subsidiary 3. Is it possible to use Netsuite rest api to fulfill orders with items from another subsidiary (cross-subsidiary fulfillment)? If yes, what am I missing? A: Is it due to role permission if the same action can be done thru UI ? Your API need to execute either using administrator role or a custom role that has access to multiple subsidiaries (at least the subsidiaries that you testing).
Netsuite REST API for cross-subsidiary item fulfillment
I get the following error when I call the item fulfillment Netsuite rest api. Error while accessing a resource. You must have at least one valid line item for this transaction. The sales order needs to be fulfilled with an item that is available in another subsidiary. This can be done in UI but I have not been able to achieve that using the rest call as described from the following help site: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_161425629582.html The following is the JSON I am using: { "item": { "items": [ { "orderLine": 1, "quantity": 1, "itemReceive": true, "location": { "id": "239" }, "inventoryDetail": { "inventoryassignment": { "items": [ { "issueInventoryNumber": { "refName": "1D3B62A4000070" }, "quantity": 1.0 } ] }, "quantity": 1.0, "totalResults": 1 }, "shipGroup" : 1, "subsidiary": { "id": "1" } } ] }, "subsidiary": { "id": "1" }, "location": { "id": "239" } } The location 239 belongs in subsidiary 1 while the order is placed in subsidiary 3. Is it possible to use Netsuite rest api to fulfill orders with items from another subsidiary (cross-subsidiary fulfillment)? If yes, what am I missing?
[ "Is it due to role permission if the same action can be done thru UI ? Your API need to execute either using administrator role or a custom role that has access to multiple subsidiaries (at least the subsidiaries that you testing).\n" ]
[ 0 ]
[]
[]
[ "netsuite", "rest" ]
stackoverflow_0074539749_netsuite_rest.txt
Q: Updating an embeded matplotlib image in PyQt5 I have a matplotlib image embedded in PyQt: But am now having trouble updating it. The UI and the initial embedding is set up as follows: class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): # Ui_MainWindow is a python class converted from .ui file def __init__(self, *args, obj=None, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setupUi(self) self.imageDisp = ImageDisplay() # Class definition below layoutImage = self.Image_Area.layout() # Image_Area is a Qt Group Box if layoutImage is None: layoutImage = QVBoxLayout(self.Image_Area) ax_img = self.imageDisp.displayImage() canvas_image = FigureCanvas(ax_img.figure) layoutImage.addWidget(canvas_image) self.NextImageButton.clicked.connect(self.inc) def inc(self): self.imageDisp.nextImage() layoutImage = self.Image_Area.layout() if layoutImage is None: layoutImage = QVBoxLayout(self.Image_Area) ax_img = self.imageDisp.UpdateImage() canvas_image = FigureCanvas(ax_img.figure) self.imageDisp.draw() layoutImage.addWidget(canvas_image) And the ImageDisplay class is defined as follows: class ImageDisplay(FigureCanvas): # FigureCanvas is matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg def __init__(self): # Other attributes fig = Figure() self.fig = fig self.axes = fig.add_subplot(111) def nextImage(self): # Do something here self.UpdateImage() def UpdateImage(self): self.axes.imshow(np.asarray(IMAGE)) return self.axes def displayImage(self): self.fig = Figure() self.axes = self.fig.add_subplot(111) self.axes.imshow(np.asarray(IMAGE)) return self.axes This does not update the image, but addWidget would create a new widget on top of it, resulting in a stacked plot: I tried to find ways to remove the widget but to no avail so far. Is there a way I can properly remove this widget and make a new one for the updated image? Or is there another way to display and update an image embedded in PyQt? A: try this instead from PyQt5 import QtWidgets from PyQt5.QtCore import * import sys import matplotlib matplotlib.use('Qt5Agg') from matplotlib.backends.backend_qt5agg import FigureCanvas from matplotlib.figure import Figure import numpy as np from matplotlib import image import matplotlib.pyplot as plt class MainWindow(QtWidgets.QMainWindow): def __init__(self, *args, obj=None, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.imageDisp = ImageDisplay(self, width=5, height=4, dpi=100) self.imageDisp.displayImage() self.NextImageButton=QtWidgets.QPushButton('next image',self) self.NextImageButton.clicked.connect(self.inc) layout = QtWidgets.QVBoxLayout() layout.addWidget(self.imageDisp) layout.addWidget(self.NextImageButton) widget = QtWidgets.QWidget() widget.setLayout(layout) self.setCentralWidget(widget) self.show() def inc(self): self.imageDisp.nextImage() class ImageDisplay(FigureCanvas): # FigureCanvas is matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg def __init__(self, parent=None, width=5, height=4, dpi=100): self.start=0 self.files=['ball.png','image.jpg'] self.fig = Figure(figsize=(width, height), dpi=dpi) self.fig.clear() self.axes = self.fig.add_subplot(111) self.axes.clear() self.axes.axis('off') plt.draw() super(ImageDisplay, self).__init__(self.fig) def nextImage(self): # Do something here self.IMAGE = image.imread(self.files[self.start%2]) self.UpdateImage() def UpdateImage(self): self.start+=1 self.axes.clear() self.axes.axis('off') self.axes.imshow(np.asarray(self.IMAGE)) self.draw() def displayImage(self): self.IMAGE = image.imread(self.files[self.start%2]) self.start+=1 self.axes.clear() self.axes.axis('off') self.axes.imshow(np.asarray(self.IMAGE)) self.draw() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) w = MainWindow() sys.exit(app.exec_())
Updating an embeded matplotlib image in PyQt5
I have a matplotlib image embedded in PyQt: But am now having trouble updating it. The UI and the initial embedding is set up as follows: class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): # Ui_MainWindow is a python class converted from .ui file def __init__(self, *args, obj=None, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setupUi(self) self.imageDisp = ImageDisplay() # Class definition below layoutImage = self.Image_Area.layout() # Image_Area is a Qt Group Box if layoutImage is None: layoutImage = QVBoxLayout(self.Image_Area) ax_img = self.imageDisp.displayImage() canvas_image = FigureCanvas(ax_img.figure) layoutImage.addWidget(canvas_image) self.NextImageButton.clicked.connect(self.inc) def inc(self): self.imageDisp.nextImage() layoutImage = self.Image_Area.layout() if layoutImage is None: layoutImage = QVBoxLayout(self.Image_Area) ax_img = self.imageDisp.UpdateImage() canvas_image = FigureCanvas(ax_img.figure) self.imageDisp.draw() layoutImage.addWidget(canvas_image) And the ImageDisplay class is defined as follows: class ImageDisplay(FigureCanvas): # FigureCanvas is matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg def __init__(self): # Other attributes fig = Figure() self.fig = fig self.axes = fig.add_subplot(111) def nextImage(self): # Do something here self.UpdateImage() def UpdateImage(self): self.axes.imshow(np.asarray(IMAGE)) return self.axes def displayImage(self): self.fig = Figure() self.axes = self.fig.add_subplot(111) self.axes.imshow(np.asarray(IMAGE)) return self.axes This does not update the image, but addWidget would create a new widget on top of it, resulting in a stacked plot: I tried to find ways to remove the widget but to no avail so far. Is there a way I can properly remove this widget and make a new one for the updated image? Or is there another way to display and update an image embedded in PyQt?
[ "try this instead\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtCore import * \nimport sys\nimport matplotlib\nmatplotlib.use('Qt5Agg')\nfrom matplotlib.backends.backend_qt5agg import FigureCanvas\nfrom matplotlib.figure import Figure\nimport numpy as np\nfrom matplotlib import image\nimport matplotlib.pyplot as plt\n\nclass MainWindow(QtWidgets.QMainWindow):\n def __init__(self, *args, obj=None, **kwargs):\n super(MainWindow, self).__init__(*args, **kwargs)\n self.imageDisp = ImageDisplay(self, width=5, height=4, dpi=100)\n self.imageDisp.displayImage()\n self.NextImageButton=QtWidgets.QPushButton('next image',self)\n self.NextImageButton.clicked.connect(self.inc)\n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(self.imageDisp)\n layout.addWidget(self.NextImageButton)\n widget = QtWidgets.QWidget()\n widget.setLayout(layout)\n self.setCentralWidget(widget)\n self.show()\n\n def inc(self):\n self.imageDisp.nextImage()\n\nclass ImageDisplay(FigureCanvas): # FigureCanvas is matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg\n def __init__(self, parent=None, width=5, height=4, dpi=100):\n self.start=0\n self.files=['ball.png','image.jpg']\n self.fig = Figure(figsize=(width, height), dpi=dpi)\n self.fig.clear()\n self.axes = self.fig.add_subplot(111)\n self.axes.clear()\n self.axes.axis('off')\n plt.draw()\n super(ImageDisplay, self).__init__(self.fig)\n def nextImage(self):\n # Do something here\n self.IMAGE = image.imread(self.files[self.start%2])\n self.UpdateImage()\n\n def UpdateImage(self):\n self.start+=1\n self.axes.clear()\n self.axes.axis('off')\n self.axes.imshow(np.asarray(self.IMAGE))\n self.draw()\n def displayImage(self):\n self.IMAGE = image.imread(self.files[self.start%2])\n self.start+=1\n self.axes.clear()\n self.axes.axis('off')\n self.axes.imshow(np.asarray(self.IMAGE))\n self.draw()\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n w = MainWindow()\n sys.exit(app.exec_())\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "pyqt", "python" ]
stackoverflow_0074672970_matplotlib_pyqt_python.txt
Q: how to minimaze a div and be able to resize the div next to it to get it its size I'm trying to be able to minimize a div that is already in my html page. when it gets minimized with a button, I need the div next to it to take its place, I also wanna be able to maximize the div back and when it gets maximized again I need the div next to it to get back to its original size, I'm only able to use javacript with no jquery I would appreciate any kind of help thank you, I didnt quite find what I want in google. A: Here is a possible solution using JavaScript: Add a button to your HTML page with an ID, for example: <button id="minimize-button">Minimize</button> Create a JavaScript function that will handle the click event on the button and toggle the visibility of the div you want to minimize: function toggleVisibility() { var div = document.getElementById('my-div'); if (div.style.display === 'none') { div.style.display = 'block'; } else { div.style.display = 'none'; } } Bind the function to the button's click event: document.getElementById('minimize-button').addEventListener('click', toggleVisibility); In order to make the div next to the minimized one take its place, you can use the CSS flexbox layout. Add the following styles to your CSS file: #container { display: flex; } #my-div { flex: 1; } #other-div { flex: 2; } This will make the div with the ID "my-div" take up 1/3 of the container's width, and the div with the ID "other-div" take up 2/3 of the container's width. To restore the original size of the divs when you maximize the div, you can add a class to the divs with the desired size and toggle that class when the div is minimized/maximized. For example: .small-div { flex: 1; } .large-div { flex: 2; } function toggleVisibility() { var div = document.getElementById('my-div'); var otherDiv = document.getElementById('other-div'); if (div.style.display === 'none') { div.style.display = 'block'; div.classList.remove('small-div'); div.classList.add('large-div'); otherDiv.classList.remove('large-div'); otherDiv.classList.add('small-div'); } else { div.style.display = 'none'; div.classList.remove('large-div'); div.classList.add('small-div'); otherDiv.classList.remove('small-div'); otherDiv.classList.add('large-div'); } } This will switch the sizes of the divs when the minimized div is shown/hidden. I hope this helps!
how to minimaze a div and be able to resize the div next to it to get it its size
I'm trying to be able to minimize a div that is already in my html page. when it gets minimized with a button, I need the div next to it to take its place, I also wanna be able to maximize the div back and when it gets maximized again I need the div next to it to get back to its original size, I'm only able to use javacript with no jquery I would appreciate any kind of help thank you, I didnt quite find what I want in google.
[ "Here is a possible solution using JavaScript:\nAdd a button to your HTML page with an ID, for example:\n<button id=\"minimize-button\">Minimize</button>\n\nCreate a JavaScript function that will handle the click event on the button and toggle the visibility of the div you want to minimize:\nfunction toggleVisibility() {\nvar div = document.getElementById('my-div');\nif (div.style.display === 'none') {\ndiv.style.display = 'block';\n} else {\ndiv.style.display = 'none';\n}\n}\n\nBind the function to the button's click event:\ndocument.getElementById('minimize-button').addEventListener('click', toggleVisibility);\n\nIn order to make the div next to the minimized one take its place, you can use the CSS flexbox layout. Add the following styles to your CSS file:\n#container {\ndisplay: flex;\n}\n\n#my-div {\nflex: 1;\n}\n\n#other-div {\nflex: 2;\n}\n\nThis will make the div with the ID \"my-div\" take up 1/3 of the container's width, and the div with the ID \"other-div\" take up 2/3 of the container's width.\n\nTo restore the original size of the divs when you maximize the div, you can add a class to the divs with the desired size and toggle that class when the div is minimized/maximized. For example:\n.small-div {\nflex: 1;\n}\n\n.large-div {\nflex: 2;\n}\n\nfunction toggleVisibility() {\nvar div = document.getElementById('my-div');\nvar otherDiv = document.getElementById('other-div');\nif (div.style.display === 'none') {\ndiv.style.display = 'block';\ndiv.classList.remove('small-div');\ndiv.classList.add('large-div');\notherDiv.classList.remove('large-div');\notherDiv.classList.add('small-div');\n} else {\ndiv.style.display = 'none';\ndiv.classList.remove('large-div');\ndiv.classList.add('small-div');\notherDiv.classList.remove('small-div');\notherDiv.classList.add('large-div');\n}\n}\n\nThis will switch the sizes of the divs when the minimized div is shown/hidden.\nI hope this helps!\n" ]
[ 0 ]
[]
[]
[ "html", "javascript" ]
stackoverflow_0074675748_html_javascript.txt
Q: How to arrange this 2D array diagonally with zeros around This is the code I came up with so far. The goal is to generate a table 10x10 just like in the image what i need The problem that I can't seem to understand is why it doesn't generate zeros and the last number 27 and just throws everything together. public class Main { public static void main(String[] args) { int values[][] = new int[10][10]; int n = 1; for (int i=0; i<=9; i++) { for (int j=9-i; j>=7-i; j--){ if (j >=0){ values[i][j] = n++; } System.out.printf(values[i][j] + " "); } System.out.println(); } } } I would appreciate any suggestions, thanks! What is see/get -- > what i see/ error A: The exception is thrown because you try to print the value at: values[i][-1]. Simply include the printing in the IF statement: if (j >=0){ values[i][j] = n++; System.out.printf(values[i][j] + " "); } A: You have to change your loop block and print block. You are getting error because you are trying to print values[i][-1] which is not exist. Please make changes to you code block in one of your loops. Instead of if (j >=0){ values[i][j] = n++; } System.out.println(values[i][j] + " "); // In this line after 26th loop you are getting error. Change to if (j >=0){ values[i][j] = n++; System.out.println(values[i][j] + " "); // Take this Print statement inside your if loop } I hope this will clear you doubt. A: Your code works. You just have to fill your arrays with 0s before running your algorithm. Take a look: // don't forget to import java.util import java.util.*; public class Main { public static void main(String[] args) { int values[][] = new int [10][10]; // here you fill the array with zeros for (int[] row : values) { for (int col : row) { row[col] = 0; } } // here is your algorithm int n = 1; for (int i=0; i<=9; i++) { for (int j=9-i; j>=7-i; j--){ if (j >=0){ values[i][j] = n++; } } } // here you print out the array for (int[] row : values) { System.out.println(Arrays.toString(row)); } } }
How to arrange this 2D array diagonally with zeros around
This is the code I came up with so far. The goal is to generate a table 10x10 just like in the image what i need The problem that I can't seem to understand is why it doesn't generate zeros and the last number 27 and just throws everything together. public class Main { public static void main(String[] args) { int values[][] = new int[10][10]; int n = 1; for (int i=0; i<=9; i++) { for (int j=9-i; j>=7-i; j--){ if (j >=0){ values[i][j] = n++; } System.out.printf(values[i][j] + " "); } System.out.println(); } } } I would appreciate any suggestions, thanks! What is see/get -- > what i see/ error
[ "The exception is thrown because you try to print the value at: values[i][-1].\nSimply include the printing in the IF statement:\nif (j >=0){\n values[i][j] = n++;\n\n System.out.printf(values[i][j] + \" \");\n \n\n}\n", "You have to change your loop block and print block. You are getting error because you are trying to print values[i][-1] which is not exist.\nPlease make changes to you code block in one of your loops.\nInstead of\nif (j >=0){\n values[i][j] = n++;\n}\nSystem.out.println(values[i][j] + \" \"); // In this line after 26th loop you are getting error.\n\nChange to\nif (j >=0){\n values[i][j] = n++;\n System.out.println(values[i][j] + \" \"); // Take this Print statement inside your if loop\n}\n\nI hope this will clear you doubt.\n", "Your code works. You just have to fill your arrays with 0s before running your algorithm.\nTake a look:\n// don't forget to import java.util\nimport java.util.*;\n\npublic class Main {\n public static void main(String[] args) {\n int values[][] = new int [10][10];\n // here you fill the array with zeros\n for (int[] row : values) {\n for (int col : row) {\n row[col] = 0;\n }\n }\n \n // here is your algorithm\n int n = 1;\n for (int i=0; i<=9; i++) {\n for (int j=9-i; j>=7-i; j--){\n if (j >=0){\n values[i][j] = n++;\n }\n }\n }\n \n // here you print out the array\n for (int[] row : values) {\n System.out.println(Arrays.toString(row));\n }\n }\n \n}\n\n" ]
[ 0, 0, -1 ]
[ "public class Main {\n\npublic static void main(String[] args) {\n int values[][] = new int [10][10];\n \n // Use a nested loop to iterate over all of the elements in the values array\n // and set each element to the corresponding value.\n int n = 1;\n for (int i=0; i<=9; i++) {\n for (int j=0; j<=9; j++){\n // Check if the current element is part of the triangle\n if (i + j >= 9 && i + j <= 11) {\n values[i][j] = n++;\n }\n }\n }\n \n // Print the values array\n for (int i=0; i<=9; i++) {\n for (int j=0; j<=9; j++) {\n System.out.printf(values[i][j] + \" \");\n }\n System.out.println();\n }\n}\n}\n\n" ]
[ -1 ]
[ "arrays", "java" ]
stackoverflow_0074675595_arrays_java.txt
Q: Exclude omitted lines in git-diff If we have this code below: 1: int a = 1; 2: int b = 2; 3: int c = 3; 4: int d = 4; And we removed line 2 and 3, and change line 1 into int a = 0; e.g. 1: int a = 0; 2: int d = 4; git diff will show output like this: 1: - int a = 1; 2: - int b = 2; 3: - int c = 3; 4: + int a = 0; 5: int d = 4; How can I make git-diff not display the line 2 and 3 above? It should only output like this: 1: - int a = 1; 2: + int a = 0; 3: int d = 4; I am creating a script and it will be easier for me to parse the diff result if it will only show the modified line (lines that has been really updated e.g. changed some value within the line) not the deleted lines Is this possible with git-diff? If not, are there any other option to solve this? A: No, it's not possible since you cannot know if a pair of deletion and addition was actually a modification. How do you know that int a = 1 was changed to int a = 0 and not that int b = 2 was changed to int a = 0? Let me change your patch slightly and ask you which lines you would keep: -int a = 1; -int b = 2; -int c = 3; +int b = 1; int d = 4; -int a = 1; -int b = 2; -int c = 3; +long c = 3; int d = 4; -int a = 1; -int b = 2; -int c = 3; +float e = 4.2; int d = 4; -int a = 1; -int b = 2; -int c = 3; +string name = "marc"; int d = 4;
Exclude omitted lines in git-diff
If we have this code below: 1: int a = 1; 2: int b = 2; 3: int c = 3; 4: int d = 4; And we removed line 2 and 3, and change line 1 into int a = 0; e.g. 1: int a = 0; 2: int d = 4; git diff will show output like this: 1: - int a = 1; 2: - int b = 2; 3: - int c = 3; 4: + int a = 0; 5: int d = 4; How can I make git-diff not display the line 2 and 3 above? It should only output like this: 1: - int a = 1; 2: + int a = 0; 3: int d = 4; I am creating a script and it will be easier for me to parse the diff result if it will only show the modified line (lines that has been really updated e.g. changed some value within the line) not the deleted lines Is this possible with git-diff? If not, are there any other option to solve this?
[ "No, it's not possible since you cannot know if a pair of deletion and addition was actually a modification.\nHow do you know that int a = 1 was changed to int a = 0 and not that int b = 2 was changed to int a = 0?\nLet me change your patch slightly and ask you which lines you would keep:\n-int a = 1;\n-int b = 2;\n-int c = 3;\n+int b = 1;\n int d = 4;\n\n-int a = 1;\n-int b = 2;\n-int c = 3;\n+long c = 3;\n int d = 4;\n\n-int a = 1;\n-int b = 2;\n-int c = 3;\n+float e = 4.2;\n int d = 4;\n\n-int a = 1;\n-int b = 2;\n-int c = 3;\n+string name = \"marc\";\n int d = 4;\n\n" ]
[ 1 ]
[]
[]
[ "git", "git_diff" ]
stackoverflow_0073785025_git_git_diff.txt
Q: Setting up continuous deployment using manual steps in Azure Web App Service / GitLab fails I want to set up a CD for my Azure Web App Service, I'm using a private GitLab Repository. Why is the "Sync" Button not clickable? Fetched SSH from Web App Service with https://website.scm.azurewebsites.net/api/sshkey?ensurePublicKey=1 Added SSH to GitLab (Settings > Repository > Deploy Keys) Added Deployment Settings in my Azure Web App Service (Deployment Center) as followed: Steps are from kudu Documentation. As said here the Sync Button should work now but it doesnt. Any ideas for this issue? A: The documentation says: Use your repo's URL when setting this up. This will allow the 'sync' button in the portal to work. Note: this may not work with private GitHub repos (see issue 2464). In that case, you may need to set it up as Local Git instead. Note that for a SSH URL ([email protected]), you do not use username/password usually. Try and use an HTTPS URL instead.
Setting up continuous deployment using manual steps in Azure Web App Service / GitLab fails
I want to set up a CD for my Azure Web App Service, I'm using a private GitLab Repository. Why is the "Sync" Button not clickable? Fetched SSH from Web App Service with https://website.scm.azurewebsites.net/api/sshkey?ensurePublicKey=1 Added SSH to GitLab (Settings > Repository > Deploy Keys) Added Deployment Settings in my Azure Web App Service (Deployment Center) as followed: Steps are from kudu Documentation. As said here the Sync Button should work now but it doesnt. Any ideas for this issue?
[ "The documentation says:\n\nUse your repo's URL when setting this up. This will allow the 'sync' button in the portal to work.\nNote: this may not work with private GitHub repos (see issue 2464). In that case, you may need to set it up as Local Git instead.\n\nNote that for a SSH URL ([email protected]), you do not use username/password usually. Try and use an HTTPS URL instead.\n" ]
[ 0 ]
[]
[]
[ "azure_appservice", "azure_deployment", "azure_web_app_service", "gitlab" ]
stackoverflow_0074675462_azure_appservice_azure_deployment_azure_web_app_service_gitlab.txt
Q: How to pass data to a webview that loads html locally i have a webview application which loads html locally and i want to update existing data <div id="sport"> <div class="case" id="jarak"> <a tabindex="-1"> Sport Channel </a> <div id="hide"> <div class="scroll-area"> <ul> <li class="scroll-nav"> <img onclick="location.href='http://xxx'; " tabindex="2" src="http://xxx" alt="xxx" class="squareBig"></img> </li> <li class="scroll-nav"> <img onclick="location.href='http://xxx'; " tabindex="2" src="http://xxx" alt="xxx" class="squareBig"></img> </li> </ul> </div> </div> </div> </div> there you see a flexbox, i will update it regularly img url and link in [li] tag, any ideas? thanks :) for now i keep use webview load html totally online but i want my webview just online for change some url on my html, I hope the answer related with json. A: One approach you can take is to use JSON to store the data for the img url and link in the [li] tag. Then, you can use JavaScript to update the HTML elements with the data from the JSON file. For example, you can create a JSON file with the following structure: { "imgUrl": "http://xxx", "link": "http://xxx" } Then, in your HTML, you can use JavaScript to retrieve the data from the JSON file and update the img and a elements with the corresponding data: <script> // Retrieve data from JSON file var data = getDataFromJSON(); // Update img and a elements with data from JSON var imgElement = document.getElementById("imgElementId"); imgElement.src = data.imgUrl; imgElement.alt = data.imgUrl; var linkElement = document.getElementById("linkElementId"); linkElement.href = data.link; </script> This way, you can update the img url and link in the [li] tag without having to load the entire HTML file from the web. You can simply update the JSON file with the new data, and the HTML elements will be updated automatically.
How to pass data to a webview that loads html locally
i have a webview application which loads html locally and i want to update existing data <div id="sport"> <div class="case" id="jarak"> <a tabindex="-1"> Sport Channel </a> <div id="hide"> <div class="scroll-area"> <ul> <li class="scroll-nav"> <img onclick="location.href='http://xxx'; " tabindex="2" src="http://xxx" alt="xxx" class="squareBig"></img> </li> <li class="scroll-nav"> <img onclick="location.href='http://xxx'; " tabindex="2" src="http://xxx" alt="xxx" class="squareBig"></img> </li> </ul> </div> </div> </div> </div> there you see a flexbox, i will update it regularly img url and link in [li] tag, any ideas? thanks :) for now i keep use webview load html totally online but i want my webview just online for change some url on my html, I hope the answer related with json.
[ "One approach you can take is to use JSON to store the data for the img url and link in the [li] tag. Then, you can use JavaScript to update the HTML elements with the data from the JSON file.\nFor example, you can create a JSON file with the following structure:\n{\n\"imgUrl\": \"http://xxx\",\n\"link\": \"http://xxx\"\n}\n\nThen, in your HTML, you can use JavaScript to retrieve the data from the JSON file and update the img and a elements with the corresponding data:\n\n<script>\n // Retrieve data from JSON file\n var data = getDataFromJSON();\n\n // Update img and a elements with data from JSON\n var imgElement = document.getElementById(\"imgElementId\");\n imgElement.src = data.imgUrl;\n imgElement.alt = data.imgUrl;\n\n var linkElement = document.getElementById(\"linkElementId\");\n linkElement.href = data.link;\n</script>\n\nThis way, you can update the img url and link in the [li] tag without having to load the entire HTML file from the web. You can simply update the JSON file with the new data, and the HTML elements will be updated automatically.\n" ]
[ 0 ]
[]
[]
[ "html", "javascript", "json", "webview" ]
stackoverflow_0074675746_html_javascript_json_webview.txt
Q: Github Pages Blank Screen When Deployed (Vite React.js) I followed a tutorial Instructions I followed for deploying a Vite React.js app to Gh pages. Deployment worked, etc. but the website is blank. Any solutions for my issue? Here is My Github Repo for refference. My config file : import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], base: '/vite-deploy-demo/' }) I was expecting to see my website live, but another thing that caught my attention is that, deploying to Netlify actually works. What could be wrong with Github Pages then? A: It looks like there may be an issue with the base property in your vite.config.js file. The base property should be the URL of the directory where your app is deployed on the web server. In your case, it looks like you have set the base property to '/vite-deploy-demo/'. This value seems incorrect, as it includes the URL path of the repository on GitHub. Instead of using the base property, you could try using the publicPath property to specify the URL path of the deployed app on the web server. For example, you could try setting publicPath: '/vite-deploy-demo/' in your config file. This will tell Vite to use '/vite-deploy-demo/' as the URL path for all assets in your app. Here is an example of what your vite.config.js file might look like with the publicPath property set: import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], publicPath: '/vite-deploy-demo/' })
Github Pages Blank Screen When Deployed (Vite React.js)
I followed a tutorial Instructions I followed for deploying a Vite React.js app to Gh pages. Deployment worked, etc. but the website is blank. Any solutions for my issue? Here is My Github Repo for refference. My config file : import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], base: '/vite-deploy-demo/' }) I was expecting to see my website live, but another thing that caught my attention is that, deploying to Netlify actually works. What could be wrong with Github Pages then?
[ "It looks like there may be an issue with the base property in your vite.config.js file. The base property should be the URL of the directory where your app is deployed on the web server. In your case, it looks like you have set the base property to '/vite-deploy-demo/'. This value seems incorrect, as it includes the URL path of the repository on GitHub.\nInstead of using the base property, you could try using the publicPath property to specify the URL path of the deployed app on the web server. For example, you could try setting publicPath: '/vite-deploy-demo/' in your config file. This will tell Vite to use '/vite-deploy-demo/' as the URL path for all assets in your app.\nHere is an example of what your vite.config.js file might look like with the publicPath property set:\n\n\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n publicPath: '/vite-deploy-demo/'\n})\n\n\n\n" ]
[ 0 ]
[]
[]
[ "github_actions", "github_pages", "reactjs" ]
stackoverflow_0074675383_github_actions_github_pages_reactjs.txt
Q: How to uninstall ASM bytecode viewer from my Mac? I installed 2 plugins, 1 is ASM bytecode viewer, the other is ASM bytecode viewer for kotlin, then my Android studio can't start... I checked the low of AS and realized that there is a duplicated installed, may I ask how should I get my AS back by removing unecessary ASM bytecode viewer? 2022-12-04 19:36:47,567 [ 0] INFO - #com.intellij.idea.Main - ------------------------------------------------------ IDE STARTED ------------------------------------------------------ 2022-12-04 19:36:47,595 [ 28] INFO - .intellij.util.EnvironmentUtil - loading shell env: /bin/bash -l -i -c '/Applications/Android Studio.app/Contents/bin/printenv.py' '/var/folders/23/fhstgrf11p523zqv5b4z1zqw0000gn/T/intellij-shell-env.11475173051245961351.tmp' 2022-12-04 19:36:47,612 [ 45] INFO - #com.intellij.idea.Main - IDE: Android Studio (build #AI-203.7717.56.2031.7935034, 21 Nov 2021 13:35) 2022-12-04 19:36:47,614 [ 47] INFO - #com.intellij.idea.Main - OS: Mac OS X (12.6, x86_64) 2022-12-04 19:36:47,626 [ 59] INFO - #com.intellij.idea.Main - JRE: 11.0.10+0-b96-7281165 (JetBrains s.r.o.) 2022-12-04 19:36:47,626 [ 59] INFO - #com.intellij.idea.Main - JVM: 11.0.10+0-b96-7281165 (OpenJDK 64-Bit Server VM) 2022-12-04 19:36:47,630 [ 63] INFO - #com.intellij.idea.Main - JVM Args: -Xms256m -Xmx1280m -XX:ReservedCodeCacheSize=512m -XX:+UseG1GC -XX:SoftRefLRUPolicyMSPerMB=50 -XX:CICompilerCount=2 -Dsun.io.useCanonCaches=false -Djdk.http.auth.tunneling.disabledSchemes="" -Djdk.attach.allowAttachSelf=true -Djdk.module.illegalAccess.silent=true -Dkotlinx.coroutines.debug=off -Djna.nosys=true -Djna.boot.library.path= -Didea.vendor.name=Google -XX:ErrorFile=/Users/savypan/java_error_in_studio_%p.log -XX:HeapDumpPath=/Users/savypan/java_error_in_studio.hprof -Djb.vmOptionsFile=/Applications/Android Studio.app/Contents/bin/studio.vmoptions -Didea.paths.selector=AndroidStudio2020.3 -Didea.executable=studio -Didea.platform.prefix=AndroidStudio -Didea.vendor.name=Google -Didea.home.path=/Applications/Android Studio.app/Contents 2022-12-04 19:36:47,631 [ 64] INFO - #com.intellij.idea.Main - library path: /Users/savypan/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:. 2022-12-04 19:36:47,631 [ 64] INFO - #com.intellij.idea.Main - boot library path: /Applications/Android Studio.app/Contents/jre/Contents/Home/lib 2022-12-04 19:36:47,671 [ 104] INFO - #com.intellij.idea.Main - locale=en_CN JNU=UTF-8 file.encoding=UTF-8 idea.config.path=/Users/savypan/Library/Application Support/Google/AndroidStudio2020.3 idea.system.path=/Users/savypan/Library/Caches/Google/AndroidStudio2020.3 idea.plugins.path=/Users/savypan/Library/Application Support/Google/AndroidStudio2020.3/plugins idea.log.path=/Users/savypan/Library/Logs/Google/AndroidStudio2020.3 2022-12-04 19:36:47,749 [ 182] WARN - .intellij.util.EnvironmentUtil - can't get shell environment java.lang.RuntimeException: command [/bin/bash, -l, -i, -c, '/Applications/Android Studio.app/Contents/bin/printenv.py' '/var/folders/23/fhstgrf11p523zqv5b4z1zqw0000gn/T/intellij-shell-env.11475173051245961351.tmp'] exit code:127 text:0 out:bash: no job control in this shell env: python: No such file or directory at com.intellij.util.EnvironmentUtil$ShellEnvReader.runProcessAndReadOutputAndEnvs(EnvironmentUtil.java:353) at com.intellij.util.EnvironmentUtil$ShellEnvReader.readShellEnv(EnvironmentUtil.java:254) at com.intellij.util.EnvironmentUtil$ShellEnvReader.readShellEnv(EnvironmentUtil.java:269) at com.intellij.util.EnvironmentUtil.getShellEnv(EnvironmentUtil.java:204) at com.intellij.util.EnvironmentUtil.lambda$loadEnvironment$0(EnvironmentUtil.java:106) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:668) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:665) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:665) at java.base/java.lang.Thread.run(Thread.java:834) 2022-12-04 19:36:48,001 [ 434] INFO - #com.intellij.idea.Main - JNA library (64-bit) loaded in 328 ms 2022-12-04 19:36:48,249 [ 682] INFO - ntellij.idea.ApplicationLoader - CPU cores: 8; ForkJoinPool.commonPool: java.util.concurrent.ForkJoinPool@2aabd8bc[Running, parallelism = 7, size = 0, active = 0, running = 0, steals = 0, tasks = 0, submissions = 0]; factory: com.intellij.concurrency.IdeaForkJoinWorkerThreadFactory@2f5b9028 2022-12-04 19:36:48,348 [ 781] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Users/savypan/Library/Application Support/Google/AndroidStudio2020.3/plugins/Kotlin, version=203-1.6.10-release-923-AS7717.8) misses optional descriptor kotlin-nodejs.xml 2022-12-04 19:36:48,350 [ 783] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Users/savypan/Library/Application Support/Google/AndroidStudio2020.3/plugins/Kotlin, version=203-1.6.10-release-923-AS7717.8) misses optional descriptor native-debug.xml 2022-12-04 19:36:48,351 [ 784] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Users/savypan/Library/Application Support/Google/AndroidStudio2020.3/plugins/Kotlin, version=203-1.6.10-release-923-AS7717.8) misses optional descriptor js-debug.xml 2022-12-04 19:36:48,494 [ 927] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Groovy, id=org.intellij.groovy, path=/Applications/Android Studio.app/Contents/plugins/Groovy, version=203.7717.56.2031.7935034) misses optional descriptor duplicates-groovy.xml 2022-12-04 19:36:48,495 [ 928] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Groovy, id=org.intellij.groovy, path=/Applications/Android Studio.app/Contents/plugins/Groovy, version=203.7717.56.2031.7935034) misses optional descriptor duplicates-detection-groovy.xml 2022-12-04 19:36:48,580 [ 1013] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Java, id=com.intellij.java, path=/Applications/Android Studio.app/Contents/plugins/java, version=203.7717.56.2031.7935034) misses optional descriptor profiler-java.xml 2022-12-04 19:36:48,582 [ 1015] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Java, id=com.intellij.java, path=/Applications/Android Studio.app/Contents/plugins/java, version=203.7717.56.2031.7935034) misses optional descriptor java-features-trainer.xml 2022-12-04 19:36:48,613 [ 1046] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Applications/Android Studio.app/Contents/plugins/Kotlin, version=203-1.5.20-release-289-AS7717.8) misses optional descriptor kotlin-nodejs.xml 2022-12-04 19:36:48,618 [ 1051] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Applications/Android Studio.app/Contents/plugins/Kotlin, version=203-1.5.20-release-289-AS7717.8) misses optional descriptor native-debug.xml 2022-12-04 19:36:48,619 [ 1052] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Applications/Android Studio.app/Contents/plugins/Kotlin, version=203-1.5.20-release-289-AS7717.8) misses optional descriptor js-debug.xml 2022-12-04 19:36:48,672 [ 1105] WARN - llij.ide.plugins.PluginManager - Problems found loading plugins: The ASM Bytecode Outline (id=ASM Bytecode Outline, path=~/Library/Application Support/Google/AndroidStudio2020.3/plugins/ASM-BO, version=0.3.5) plugin Plugin 'ASM Bytecode Outline' is compatible with IntelliJ IDEA only because it doesn't define any explicit module dependencies 2022-12-04 19:36:48,728 [ 1161] INFO - llij.ide.plugins.PluginManager - Loaded bundled plugins: IDEA CORE (203.7717.56), Layoutlib (203.7717.56.2031.7935034), Layoutlib Legacy (203.7717.56.2031.7935034), Google Login (203.7717.56.2031.7935034), CIDR Base (203.7717.56.2031.7935034), C/C++ Language Support (203.7717.56.2031.7935034), Clangd support (203.7717.56.2031.7935034), com.intellij.platform.images (203.7717.56.2031.7935034), JetBrains maven model api classes (203.7717.56.2031.7935034), JetBrains Repository Search (203.7717.56.2031.7935034), Subversion (203.7717.56.2031.7935034), Smali Support (203.7717.56.2031.7935034), Machine Learning Code Completion (203.7717.56.2031.7935034), Configuration Script (203.7717.56.2031.7935034), Copyright (203.7717.56.2031.7935034), Java (203.7717.56.2031.7935034), JUnit (203.7717.56.2031.7935034), Java IDE Customization (203.7717.56.2031.7935034), Java Stream Debugger (203.7717.56.2031.7935034), Java Bytecode Decompiler (203.7717.56.2031.7935034), Properties (203.7717.56.2031.7935034), Gradle (203.7717.56.2031.7935034), Java Internationalization (203.7717.56.2031.7935034), Resource Bundle Editor (203.7717.56.2031.7935034), Task Management (203.7717.56.2031.7935034), Mercurial (203.7717.56.2031.7935034), WebP Support (203.7717.56.2031.7935034), EditorConfig (203.7717.56.2031.7935034), Terminal (203.7717.56.2031.7935034), Git (203.7717.56.2031.7935034), ChangeReminder (203.7717.56.2031.7935034), GitHub (203.7717.56.2031.7935034), Next File Prediction (203.7717.56.2031.7935034), Shell Script (203.7717.56.2031.7935034), TextMate Bundles (203.7717.56.2031.7935034), YAML (203.7717.56.2031.7935034), Settings Repository (203.7717.56.2031.7935034), IntelliLang (203.7717.56.2031.7935034), TestNG (203.7717.56.2031.7935034), Code Coverage for Java (203.7717.56.2031.7935034), Groovy (203.7717.56.2031.7935034), Gradle-Java (203.7717.56.2031.7935034), Google Cloud Tools Core (203.7717.56.2031.7935034), Android (2020.3.1 Patch 4), Google Cloud Tools For Android Studio (203.7717.56.2031.7935034), Firebase Testing (203.7717.56.2031.7935034), Compose (203.7717.56.2031.7935034), Android NDK Support (203.7717.56.2031.7935034), Android APK Support (203.7717.56.2031.7935034), Google Developers Samples (203.7717.56.2031.7935034), Test Recorder (203.7717.56.2031.7935034), App Links Assistant (203.7717.56.2031.7935034), Firebase App Indexing (203.7717.56.2031.7935034) 2022-12-04 19:36:48,728 [ 1161] INFO - llij.ide.plugins.PluginManager - Loaded custom plugins: ASM Bytecode Viewer (7.2), ASM Bytecode Viewer Support Kotlin (1.1), Dart (203.8452), Kotlin (203-1.6.10-release-923-AS7717.8), Flutter (65.2.1), Markdown (203.6682.134) 2022-12-04 19:36:48,728 [ 1161] INFO - llij.ide.plugins.PluginManager - Disabled plugins: Firebase Services (203.7717.56.2031.7935034), Kotlin Multiplatform Mobile (0.3.0(203-1.6.0-release-795-IJ)-54) 2022-12-04 19:36:49,307 [ 1740] INFO - m.intellij.util.io.StorageLock - lower=100; upper=500; buffer=10; max=1260 2022-12-04 19:36:49,315 [ 1748] INFO - tellij.util.io.FileChannelUtil - uninterruptible FileChannels will be used for indexes 2022-12-04 19:36:49,361 [ 1794] INFO - m.intellij.ui.mac.touchbar.NST - touchbar-server isn't running, skip nst loading 2022-12-04 19:36:49,418 [ 1851] INFO - tellij.util.io.storage.Storage - Space waste in /Users/savypan/Library/Caches/Google/AndroidStudio2020.3/caches/attrib.dat is 26155394 bytes. Compacting now. 2022-12-04 19:36:49,420 [ 1853] INFO - tellij.util.io.storage.Storage - Compact failed: /Users/savypan/Library/Caches/Google/AndroidStudio2020.3/caches/attrib.dat.storageData.backup 2022-12-04 19:36:49,420 [ 1853] INFO - tellij.util.io.storage.Storage - Done compacting in 2msec. 2022-12-04 19:36:49,441 [ 1874] INFO - cation.options.RegistryManager - Registry values changed by user: external.system.auto.import.disabled = true 2022-12-04 19:36:49,464 [ 1897] INFO - com.intellij.ide.ui.UISettings - Loaded: fontSize=13, fontScale=1.0; restored: fontSize=13, fontScale=1.0 2022-12-04 19:36:49,492 [ 1925] INFO - intellij.diagnostic.JitWatcher - JIT compilation state checking enabled 2022-12-04 19:36:49,615 [ 2048] INFO - rains.ide.BuiltInServerManager - built-in server started, port 63342 2022-12-04 19:36:49,638 [ 2071] INFO - til.net.ssl.CertificateManager - Default SSL context initialized 2022-12-04 19:36:50,655 [ 3088] INFO - leBasedIndexDataInitialization - Initialization done: 1055 2022-12-04 19:36:50,748 [ 3181] INFO - exImpl$StubIndexInitialization - Initialization done: 92 2022-12-04 19:36:52,552 [ 4985] INFO - com.intellij.ide.ui.UISettings - Loaded: fontSize=13, fontScale=1.0; restored: fontSize=13, fontScale=1.0 2022-12-04 19:36:52,553 [ 4986] WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.AndroidInitialConfigurator) 2022-12-04 19:36:52,587 [ 5020] INFO - pi.util.registry.RegistryValue - Registry value 'external.system.auto.import.disabled' has changed to 'true' 2022-12-04 19:36:52,622 [ 5055] INFO - pl.local.NativeFileWatcherImpl - Starting file watcher: /Applications/Android Studio.app/Contents/bin/fsnotifier 2022-12-04 19:36:52,625 [ 5058] INFO - pl.local.NativeFileWatcherImpl - Native file watcher is operational. 2022-12-04 19:36:54,592 [ 7025] WARN - nSystem.impl.ActionManagerImpl - keymap "Xcode" not found [Plugin: com.intellij] 2022-12-04 19:36:54,602 [ 7035] WARN - nSystem.impl.ActionManagerImpl - keymap "Xcode" not found [Plugin: com.intellij.cidr.base] 2022-12-04 19:36:54,805 [ 7238] ERROR - nSystem.impl.ActionManagerImpl - action with the ID "showBytecodeViewer" was already registered. Action being registered is ASM Bytecode Viewer (Shows the bytecode viewer and ASMified code from the current class); Registered action is ASM Bytecode Viewer (Shows the bytecode viewer and ASMified code from the current class) Plugin: ASM Bytecode Viewer Support Kotlin [Plugin: ASM Bytecode Viewer Support Kotlin] com.intellij.diagnostic.PluginException: action with the ID "showBytecodeViewer" was already registered. Action being registered is ASM Bytecode Viewer (Shows the bytecode viewer and ASMified code from the current class); Registered action is ASM Bytecode Viewer (Shows the bytecode viewer and ASMified code from the current class) Plugin: ASM Bytecode Viewer Support Kotlin [Plugin: ASM Bytecode Viewer Support Kotlin] at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.reportActionError(ActionManagerImpl.java:392) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.reportActionError(ActionManagerImpl.java:387) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.registerChameleon(ActionManagerImpl.java:1325) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.addToMap(ActionManagerImpl.java:1298) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.registerAction(ActionManagerImpl.java:1268) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.registerOrReplaceActionInner(ActionManagerImpl.java:753) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.processActionElement(ActionManagerImpl.java:726) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.registerPluginActions(ActionManagerImpl.java:535) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.registerActions(ActionManagerImpl.java:200) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.<init>(ActionManagerImpl.java:177) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) at com.intellij.serviceContainer.ConstructorInjectionKt.instantiateUsingPicoContainer(constructorInjection.kt:47) at com.intellij.serviceContainer.ComponentManagerImpl.instantiateClassWithConstructorInjection(ComponentManagerImpl.kt:733) at com.intellij.serviceContainer.ServiceComponentAdapter.createAndInitialize(ServiceComponentAdapter.kt:49) at com.intellij.serviceContainer.ServiceComponentAdapter.access$createAndInitialize(ServiceComponentAdapter.kt:13) at com.intellij.serviceContainer.ServiceComponentAdapter$doCreateInstance$1.run(ServiceComponentAdapter.kt:43) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:658) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:610) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:65) at com.intellij.openapi.progress.impl.CoreProgressManager.executeNonCancelableSection(CoreProgressManager.java:218) at com.intellij.serviceContainer.ServiceComponentAdapter.doCreateInstance(ServiceComponentAdapter.kt:42) at com.intellij.serviceContainer.BaseComponentAdapter.getInstanceUncached(BaseComponentAdapter.kt:113) at com.intellij.serviceContainer.BaseComponentAdapter.getInstance(BaseComponentAdapter.kt:67) at com.intellij.serviceContainer.ComponentManagerImpl.doGetService(ComponentManagerImpl.kt:457) at com.intellij.serviceContainer.ComponentManagerImpl.getService(ComponentManagerImpl.kt:440) at com.intellij.openapi.actionSystem.ActionManager.getInstance(ActionManager.java:29) at com.intellij.openapi.actionSystem.impl.ActionPreloader.preload(ActionPreloader.java:15) at com.intellij.openapi.application.Preloader.lambda$preload$0(Preloader.java:84) at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:178) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:658) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:610) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:65) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:165) at com.intellij.openapi.application.Preloader.lambda$preload$1(Preloader.java:74) at com.intellij.util.concurrency.BoundedTaskExecutor.doRun(BoundedTaskExecutor.java:216) at com.intellij.util.concurrency.BoundedTaskExecutor.access$200(BoundedTaskExecutor.java:27) at com.intellij.util.concurrency.BoundedTaskExecutor$1.execute(BoundedTaskExecutor.java:195) at com.intellij.util.ConcurrencyUtil.runUnderThreadName(ConcurrencyUtil.java:208) at com.intellij.util.concurrency.BoundedTaskExecutor$1.run(BoundedTaskExecutor.java:184) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:668) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:665) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:665) at java.base/java.lang.Thread.run(Thread.java:834) 2022-12-04 19:36:54,807 [ 7240] ERROR - nSystem.impl.ActionManagerImpl - Android Studio Arctic Fox | 2020.3.1 Patch 4 Build #AI-203.7717.56.2031.7935034 2022-12-04 19:36:54,810 [ 7243] ERROR - nSystem.impl.ActionManagerImpl - JDK: 11.0.10; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o. 2022-12-04 19:36:54,810 [ 7243] ERROR - nSystem.impl.ActionManagerImpl - OS: Mac OS X 2022-12-04 19:36:54,811 [ 7244] ERROR - nSystem.impl.ActionManagerImpl - Plugin to blame: ASM Bytecode Viewer Support Kotlin version: 1.1 2022-12-04 19:36:54,812 [ 7245] ERROR - nSystem.impl.ActionManagerImpl - Last Action: 2022-12-04 19:36:54,998 [ 7431] INFO - verflags.ServerFlagInitializer - Enabled server flags: analytics/surveys/followup, exceptions/ClassCastException 2022-12-04 19:36:55,688 [ 8121] ERROR - ect.impl.ProjectFrameAllocator - Key org.objectweb.asm.idea.plugin.view.BytecodeOutline duplicated org.picocontainer.PicoRegistrationException: Key org.objectweb.asm.idea.plugin.view.BytecodeOutline duplicated at com.intellij.util.pico.DefaultPicoContainer.registerComponent(DefaultPicoContainer.java:119) at com.intellij.serviceContainer.ComponentManagerImpl.registerServices(ComponentManagerImpl.kt:364) at com.intellij.serviceContainer.ComponentManagerImpl.registerComponents(ComponentManagerImpl.kt:214) at com.intellij.openapi.project.impl.ProjectLoadHelper.registerComponents(projectLoader.kt:25) at com.intellij.openapi.project.impl.ProjectManagerImpl.initProject(ProjectManagerImpl.java:171) at com.intellij.openapi.project.impl.ProjectManagerExImpl.prepareProject(ProjectManagerExImpl.kt:242) at com.intellij.openapi.project.impl.ProjectManagerExImpl.access$prepareProject(ProjectManagerExImpl.kt:52) at com.intellij.openapi.project.impl.ProjectManagerExImpl$openProject$$inlined$runInAutoSaveDisabledMode$lambda$1.invoke(ProjectManagerExImpl.kt:104) at com.intellij.openapi.project.impl.ProjectManagerExImpl$openProject$$inlined$runInAutoSaveDisabledMode$lambda$1.invoke(ProjectManagerExImpl.kt:52) at com.intellij.openapi.project.impl.ProjectUiFrameAllocator$run$progressTask$1.run(ProjectFrameAllocator.kt:86) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$new$0(ProgressRunner.java:79) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$submit$3(ProgressRunner.java:235) at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:178) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:658) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:610) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:65) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:165) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$submit$4(ProgressRunner.java:235) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:668) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:665) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:665) at java.base/java.lang.Thread.run(Thread.java:834) 2022-12-04 19:36:55,689 [ 8122] ERROR - ect.impl.ProjectFrameAllocator - Android Studio Arctic Fox | 2020.3.1 Patch 4 Build #AI-203.7717.56.2031.7935034 2022-12-04 19:36:55,689 [ 8122] ERROR - ect.impl.ProjectFrameAllocator - JDK: 11.0.10; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o. 2022-12-04 19:36:55,689 [ 8122] ERROR - ect.impl.ProjectFrameAllocator - OS: Mac OS X 2022-12-04 19:36:55,689 [ 8122] ERROR - ect.impl.ProjectFrameAllocator - Last Action: 2022-12-04 19:36:56,476 [ 8909] ERROR - ect.impl.ProjectFrameAllocator - Key org.objectweb.asm.idea.plugin.view.BytecodeOutline duplicated org.picocontainer.PicoRegistrationException: Key org.objectweb.asm.idea.plugin.view.BytecodeOutline duplicated at com.intellij.util.pico.DefaultPicoContainer.registerComponent(DefaultPicoContainer.java:119) at com.intellij.serviceContainer.ComponentManagerImpl.registerServices(ComponentManagerImpl.kt:364) at com.intellij.serviceContainer.ComponentManagerImpl.registerComponents(ComponentManagerImpl.kt:214) at com.intellij.openapi.project.impl.ProjectLoadHelper.registerComponents(projectLoader.kt:25) at com.intellij.openapi.project.impl.ProjectManagerImpl.initProject(ProjectManagerImpl.java:171) at com.intellij.openapi.project.impl.ProjectManagerExImpl.prepareProject(ProjectManagerExImpl.kt:242) at com.intellij.openapi.project.impl.ProjectManagerExImpl.access$prepareProject(ProjectManagerExImpl.kt:52) at com.intellij.openapi.project.impl.ProjectManagerExImpl$openProject$$inlined$runInAutoSaveDisabledMode$lambda$1.invoke(ProjectManagerExImpl.kt:104) at com.intellij.openapi.project.impl.ProjectManagerExImpl$openProject$$inlined$runInAutoSaveDisabledMode$lambda$1.invoke(ProjectManagerExImpl.kt:52) at com.intellij.openapi.project.impl.ProjectUiFrameAllocator$run$progressTask$1.run(ProjectFrameAllocator.kt:86) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$new$0(ProgressRunner.java:79) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$submit$3(ProgressRunner.java:235) at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:178) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:658) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:610) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:65) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:165) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$submit$4(ProgressRunner.java:235) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:668) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:665) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:665) at java.base/java.lang.Thread.run(Thread.java:834) 2022-12-04 19:36:56,477 [ 8910] ERROR - ect.impl.ProjectFrameAllocator - Android Studio Arctic Fox | 2020.3.1 Patch 4 Build #AI-203.7717.56.2031.7935034 2022-12-04 19:36:56,477 [ 8910] ERROR - ect.impl.ProjectFrameAllocator - JDK: 11.0.10; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o. 2022-12-04 19:36:56,477 [ 8910] ERROR - ect.impl.ProjectFrameAllocator - OS: Mac OS X 2022-12-04 19:36:56,477 [ 8910] ERROR - ect.impl.ProjectFrameAllocator - Last Action: 2022-12-04 19:36:56,482 [ 8915] INFO - gs.impl.UpdateCheckerComponent - channel: release Anyone who experienced the similar issue can tell me, thanks! A: Thanks, I resolved by finding the real path of AS then deleted the libs.
How to uninstall ASM bytecode viewer from my Mac?
I installed 2 plugins, 1 is ASM bytecode viewer, the other is ASM bytecode viewer for kotlin, then my Android studio can't start... I checked the low of AS and realized that there is a duplicated installed, may I ask how should I get my AS back by removing unecessary ASM bytecode viewer? 2022-12-04 19:36:47,567 [ 0] INFO - #com.intellij.idea.Main - ------------------------------------------------------ IDE STARTED ------------------------------------------------------ 2022-12-04 19:36:47,595 [ 28] INFO - .intellij.util.EnvironmentUtil - loading shell env: /bin/bash -l -i -c '/Applications/Android Studio.app/Contents/bin/printenv.py' '/var/folders/23/fhstgrf11p523zqv5b4z1zqw0000gn/T/intellij-shell-env.11475173051245961351.tmp' 2022-12-04 19:36:47,612 [ 45] INFO - #com.intellij.idea.Main - IDE: Android Studio (build #AI-203.7717.56.2031.7935034, 21 Nov 2021 13:35) 2022-12-04 19:36:47,614 [ 47] INFO - #com.intellij.idea.Main - OS: Mac OS X (12.6, x86_64) 2022-12-04 19:36:47,626 [ 59] INFO - #com.intellij.idea.Main - JRE: 11.0.10+0-b96-7281165 (JetBrains s.r.o.) 2022-12-04 19:36:47,626 [ 59] INFO - #com.intellij.idea.Main - JVM: 11.0.10+0-b96-7281165 (OpenJDK 64-Bit Server VM) 2022-12-04 19:36:47,630 [ 63] INFO - #com.intellij.idea.Main - JVM Args: -Xms256m -Xmx1280m -XX:ReservedCodeCacheSize=512m -XX:+UseG1GC -XX:SoftRefLRUPolicyMSPerMB=50 -XX:CICompilerCount=2 -Dsun.io.useCanonCaches=false -Djdk.http.auth.tunneling.disabledSchemes="" -Djdk.attach.allowAttachSelf=true -Djdk.module.illegalAccess.silent=true -Dkotlinx.coroutines.debug=off -Djna.nosys=true -Djna.boot.library.path= -Didea.vendor.name=Google -XX:ErrorFile=/Users/savypan/java_error_in_studio_%p.log -XX:HeapDumpPath=/Users/savypan/java_error_in_studio.hprof -Djb.vmOptionsFile=/Applications/Android Studio.app/Contents/bin/studio.vmoptions -Didea.paths.selector=AndroidStudio2020.3 -Didea.executable=studio -Didea.platform.prefix=AndroidStudio -Didea.vendor.name=Google -Didea.home.path=/Applications/Android Studio.app/Contents 2022-12-04 19:36:47,631 [ 64] INFO - #com.intellij.idea.Main - library path: /Users/savypan/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:. 2022-12-04 19:36:47,631 [ 64] INFO - #com.intellij.idea.Main - boot library path: /Applications/Android Studio.app/Contents/jre/Contents/Home/lib 2022-12-04 19:36:47,671 [ 104] INFO - #com.intellij.idea.Main - locale=en_CN JNU=UTF-8 file.encoding=UTF-8 idea.config.path=/Users/savypan/Library/Application Support/Google/AndroidStudio2020.3 idea.system.path=/Users/savypan/Library/Caches/Google/AndroidStudio2020.3 idea.plugins.path=/Users/savypan/Library/Application Support/Google/AndroidStudio2020.3/plugins idea.log.path=/Users/savypan/Library/Logs/Google/AndroidStudio2020.3 2022-12-04 19:36:47,749 [ 182] WARN - .intellij.util.EnvironmentUtil - can't get shell environment java.lang.RuntimeException: command [/bin/bash, -l, -i, -c, '/Applications/Android Studio.app/Contents/bin/printenv.py' '/var/folders/23/fhstgrf11p523zqv5b4z1zqw0000gn/T/intellij-shell-env.11475173051245961351.tmp'] exit code:127 text:0 out:bash: no job control in this shell env: python: No such file or directory at com.intellij.util.EnvironmentUtil$ShellEnvReader.runProcessAndReadOutputAndEnvs(EnvironmentUtil.java:353) at com.intellij.util.EnvironmentUtil$ShellEnvReader.readShellEnv(EnvironmentUtil.java:254) at com.intellij.util.EnvironmentUtil$ShellEnvReader.readShellEnv(EnvironmentUtil.java:269) at com.intellij.util.EnvironmentUtil.getShellEnv(EnvironmentUtil.java:204) at com.intellij.util.EnvironmentUtil.lambda$loadEnvironment$0(EnvironmentUtil.java:106) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:668) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:665) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:665) at java.base/java.lang.Thread.run(Thread.java:834) 2022-12-04 19:36:48,001 [ 434] INFO - #com.intellij.idea.Main - JNA library (64-bit) loaded in 328 ms 2022-12-04 19:36:48,249 [ 682] INFO - ntellij.idea.ApplicationLoader - CPU cores: 8; ForkJoinPool.commonPool: java.util.concurrent.ForkJoinPool@2aabd8bc[Running, parallelism = 7, size = 0, active = 0, running = 0, steals = 0, tasks = 0, submissions = 0]; factory: com.intellij.concurrency.IdeaForkJoinWorkerThreadFactory@2f5b9028 2022-12-04 19:36:48,348 [ 781] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Users/savypan/Library/Application Support/Google/AndroidStudio2020.3/plugins/Kotlin, version=203-1.6.10-release-923-AS7717.8) misses optional descriptor kotlin-nodejs.xml 2022-12-04 19:36:48,350 [ 783] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Users/savypan/Library/Application Support/Google/AndroidStudio2020.3/plugins/Kotlin, version=203-1.6.10-release-923-AS7717.8) misses optional descriptor native-debug.xml 2022-12-04 19:36:48,351 [ 784] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Users/savypan/Library/Application Support/Google/AndroidStudio2020.3/plugins/Kotlin, version=203-1.6.10-release-923-AS7717.8) misses optional descriptor js-debug.xml 2022-12-04 19:36:48,494 [ 927] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Groovy, id=org.intellij.groovy, path=/Applications/Android Studio.app/Contents/plugins/Groovy, version=203.7717.56.2031.7935034) misses optional descriptor duplicates-groovy.xml 2022-12-04 19:36:48,495 [ 928] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Groovy, id=org.intellij.groovy, path=/Applications/Android Studio.app/Contents/plugins/Groovy, version=203.7717.56.2031.7935034) misses optional descriptor duplicates-detection-groovy.xml 2022-12-04 19:36:48,580 [ 1013] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Java, id=com.intellij.java, path=/Applications/Android Studio.app/Contents/plugins/java, version=203.7717.56.2031.7935034) misses optional descriptor profiler-java.xml 2022-12-04 19:36:48,582 [ 1015] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Java, id=com.intellij.java, path=/Applications/Android Studio.app/Contents/plugins/java, version=203.7717.56.2031.7935034) misses optional descriptor java-features-trainer.xml 2022-12-04 19:36:48,613 [ 1046] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Applications/Android Studio.app/Contents/plugins/Kotlin, version=203-1.5.20-release-289-AS7717.8) misses optional descriptor kotlin-nodejs.xml 2022-12-04 19:36:48,618 [ 1051] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Applications/Android Studio.app/Contents/plugins/Kotlin, version=203-1.5.20-release-289-AS7717.8) misses optional descriptor native-debug.xml 2022-12-04 19:36:48,619 [ 1052] INFO - llij.ide.plugins.PluginManager - Plugin PluginDescriptor(name=Kotlin, id=org.jetbrains.kotlin, path=/Applications/Android Studio.app/Contents/plugins/Kotlin, version=203-1.5.20-release-289-AS7717.8) misses optional descriptor js-debug.xml 2022-12-04 19:36:48,672 [ 1105] WARN - llij.ide.plugins.PluginManager - Problems found loading plugins: The ASM Bytecode Outline (id=ASM Bytecode Outline, path=~/Library/Application Support/Google/AndroidStudio2020.3/plugins/ASM-BO, version=0.3.5) plugin Plugin 'ASM Bytecode Outline' is compatible with IntelliJ IDEA only because it doesn't define any explicit module dependencies 2022-12-04 19:36:48,728 [ 1161] INFO - llij.ide.plugins.PluginManager - Loaded bundled plugins: IDEA CORE (203.7717.56), Layoutlib (203.7717.56.2031.7935034), Layoutlib Legacy (203.7717.56.2031.7935034), Google Login (203.7717.56.2031.7935034), CIDR Base (203.7717.56.2031.7935034), C/C++ Language Support (203.7717.56.2031.7935034), Clangd support (203.7717.56.2031.7935034), com.intellij.platform.images (203.7717.56.2031.7935034), JetBrains maven model api classes (203.7717.56.2031.7935034), JetBrains Repository Search (203.7717.56.2031.7935034), Subversion (203.7717.56.2031.7935034), Smali Support (203.7717.56.2031.7935034), Machine Learning Code Completion (203.7717.56.2031.7935034), Configuration Script (203.7717.56.2031.7935034), Copyright (203.7717.56.2031.7935034), Java (203.7717.56.2031.7935034), JUnit (203.7717.56.2031.7935034), Java IDE Customization (203.7717.56.2031.7935034), Java Stream Debugger (203.7717.56.2031.7935034), Java Bytecode Decompiler (203.7717.56.2031.7935034), Properties (203.7717.56.2031.7935034), Gradle (203.7717.56.2031.7935034), Java Internationalization (203.7717.56.2031.7935034), Resource Bundle Editor (203.7717.56.2031.7935034), Task Management (203.7717.56.2031.7935034), Mercurial (203.7717.56.2031.7935034), WebP Support (203.7717.56.2031.7935034), EditorConfig (203.7717.56.2031.7935034), Terminal (203.7717.56.2031.7935034), Git (203.7717.56.2031.7935034), ChangeReminder (203.7717.56.2031.7935034), GitHub (203.7717.56.2031.7935034), Next File Prediction (203.7717.56.2031.7935034), Shell Script (203.7717.56.2031.7935034), TextMate Bundles (203.7717.56.2031.7935034), YAML (203.7717.56.2031.7935034), Settings Repository (203.7717.56.2031.7935034), IntelliLang (203.7717.56.2031.7935034), TestNG (203.7717.56.2031.7935034), Code Coverage for Java (203.7717.56.2031.7935034), Groovy (203.7717.56.2031.7935034), Gradle-Java (203.7717.56.2031.7935034), Google Cloud Tools Core (203.7717.56.2031.7935034), Android (2020.3.1 Patch 4), Google Cloud Tools For Android Studio (203.7717.56.2031.7935034), Firebase Testing (203.7717.56.2031.7935034), Compose (203.7717.56.2031.7935034), Android NDK Support (203.7717.56.2031.7935034), Android APK Support (203.7717.56.2031.7935034), Google Developers Samples (203.7717.56.2031.7935034), Test Recorder (203.7717.56.2031.7935034), App Links Assistant (203.7717.56.2031.7935034), Firebase App Indexing (203.7717.56.2031.7935034) 2022-12-04 19:36:48,728 [ 1161] INFO - llij.ide.plugins.PluginManager - Loaded custom plugins: ASM Bytecode Viewer (7.2), ASM Bytecode Viewer Support Kotlin (1.1), Dart (203.8452), Kotlin (203-1.6.10-release-923-AS7717.8), Flutter (65.2.1), Markdown (203.6682.134) 2022-12-04 19:36:48,728 [ 1161] INFO - llij.ide.plugins.PluginManager - Disabled plugins: Firebase Services (203.7717.56.2031.7935034), Kotlin Multiplatform Mobile (0.3.0(203-1.6.0-release-795-IJ)-54) 2022-12-04 19:36:49,307 [ 1740] INFO - m.intellij.util.io.StorageLock - lower=100; upper=500; buffer=10; max=1260 2022-12-04 19:36:49,315 [ 1748] INFO - tellij.util.io.FileChannelUtil - uninterruptible FileChannels will be used for indexes 2022-12-04 19:36:49,361 [ 1794] INFO - m.intellij.ui.mac.touchbar.NST - touchbar-server isn't running, skip nst loading 2022-12-04 19:36:49,418 [ 1851] INFO - tellij.util.io.storage.Storage - Space waste in /Users/savypan/Library/Caches/Google/AndroidStudio2020.3/caches/attrib.dat is 26155394 bytes. Compacting now. 2022-12-04 19:36:49,420 [ 1853] INFO - tellij.util.io.storage.Storage - Compact failed: /Users/savypan/Library/Caches/Google/AndroidStudio2020.3/caches/attrib.dat.storageData.backup 2022-12-04 19:36:49,420 [ 1853] INFO - tellij.util.io.storage.Storage - Done compacting in 2msec. 2022-12-04 19:36:49,441 [ 1874] INFO - cation.options.RegistryManager - Registry values changed by user: external.system.auto.import.disabled = true 2022-12-04 19:36:49,464 [ 1897] INFO - com.intellij.ide.ui.UISettings - Loaded: fontSize=13, fontScale=1.0; restored: fontSize=13, fontScale=1.0 2022-12-04 19:36:49,492 [ 1925] INFO - intellij.diagnostic.JitWatcher - JIT compilation state checking enabled 2022-12-04 19:36:49,615 [ 2048] INFO - rains.ide.BuiltInServerManager - built-in server started, port 63342 2022-12-04 19:36:49,638 [ 2071] INFO - til.net.ssl.CertificateManager - Default SSL context initialized 2022-12-04 19:36:50,655 [ 3088] INFO - leBasedIndexDataInitialization - Initialization done: 1055 2022-12-04 19:36:50,748 [ 3181] INFO - exImpl$StubIndexInitialization - Initialization done: 92 2022-12-04 19:36:52,552 [ 4985] INFO - com.intellij.ide.ui.UISettings - Loaded: fontSize=13, fontScale=1.0; restored: fontSize=13, fontScale=1.0 2022-12-04 19:36:52,553 [ 4986] WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.AndroidInitialConfigurator) 2022-12-04 19:36:52,587 [ 5020] INFO - pi.util.registry.RegistryValue - Registry value 'external.system.auto.import.disabled' has changed to 'true' 2022-12-04 19:36:52,622 [ 5055] INFO - pl.local.NativeFileWatcherImpl - Starting file watcher: /Applications/Android Studio.app/Contents/bin/fsnotifier 2022-12-04 19:36:52,625 [ 5058] INFO - pl.local.NativeFileWatcherImpl - Native file watcher is operational. 2022-12-04 19:36:54,592 [ 7025] WARN - nSystem.impl.ActionManagerImpl - keymap "Xcode" not found [Plugin: com.intellij] 2022-12-04 19:36:54,602 [ 7035] WARN - nSystem.impl.ActionManagerImpl - keymap "Xcode" not found [Plugin: com.intellij.cidr.base] 2022-12-04 19:36:54,805 [ 7238] ERROR - nSystem.impl.ActionManagerImpl - action with the ID "showBytecodeViewer" was already registered. Action being registered is ASM Bytecode Viewer (Shows the bytecode viewer and ASMified code from the current class); Registered action is ASM Bytecode Viewer (Shows the bytecode viewer and ASMified code from the current class) Plugin: ASM Bytecode Viewer Support Kotlin [Plugin: ASM Bytecode Viewer Support Kotlin] com.intellij.diagnostic.PluginException: action with the ID "showBytecodeViewer" was already registered. Action being registered is ASM Bytecode Viewer (Shows the bytecode viewer and ASMified code from the current class); Registered action is ASM Bytecode Viewer (Shows the bytecode viewer and ASMified code from the current class) Plugin: ASM Bytecode Viewer Support Kotlin [Plugin: ASM Bytecode Viewer Support Kotlin] at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.reportActionError(ActionManagerImpl.java:392) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.reportActionError(ActionManagerImpl.java:387) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.registerChameleon(ActionManagerImpl.java:1325) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.addToMap(ActionManagerImpl.java:1298) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.registerAction(ActionManagerImpl.java:1268) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.registerOrReplaceActionInner(ActionManagerImpl.java:753) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.processActionElement(ActionManagerImpl.java:726) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.registerPluginActions(ActionManagerImpl.java:535) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.registerActions(ActionManagerImpl.java:200) at com.intellij.openapi.actionSystem.impl.ActionManagerImpl.<init>(ActionManagerImpl.java:177) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) at com.intellij.serviceContainer.ConstructorInjectionKt.instantiateUsingPicoContainer(constructorInjection.kt:47) at com.intellij.serviceContainer.ComponentManagerImpl.instantiateClassWithConstructorInjection(ComponentManagerImpl.kt:733) at com.intellij.serviceContainer.ServiceComponentAdapter.createAndInitialize(ServiceComponentAdapter.kt:49) at com.intellij.serviceContainer.ServiceComponentAdapter.access$createAndInitialize(ServiceComponentAdapter.kt:13) at com.intellij.serviceContainer.ServiceComponentAdapter$doCreateInstance$1.run(ServiceComponentAdapter.kt:43) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:658) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:610) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:65) at com.intellij.openapi.progress.impl.CoreProgressManager.executeNonCancelableSection(CoreProgressManager.java:218) at com.intellij.serviceContainer.ServiceComponentAdapter.doCreateInstance(ServiceComponentAdapter.kt:42) at com.intellij.serviceContainer.BaseComponentAdapter.getInstanceUncached(BaseComponentAdapter.kt:113) at com.intellij.serviceContainer.BaseComponentAdapter.getInstance(BaseComponentAdapter.kt:67) at com.intellij.serviceContainer.ComponentManagerImpl.doGetService(ComponentManagerImpl.kt:457) at com.intellij.serviceContainer.ComponentManagerImpl.getService(ComponentManagerImpl.kt:440) at com.intellij.openapi.actionSystem.ActionManager.getInstance(ActionManager.java:29) at com.intellij.openapi.actionSystem.impl.ActionPreloader.preload(ActionPreloader.java:15) at com.intellij.openapi.application.Preloader.lambda$preload$0(Preloader.java:84) at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:178) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:658) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:610) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:65) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:165) at com.intellij.openapi.application.Preloader.lambda$preload$1(Preloader.java:74) at com.intellij.util.concurrency.BoundedTaskExecutor.doRun(BoundedTaskExecutor.java:216) at com.intellij.util.concurrency.BoundedTaskExecutor.access$200(BoundedTaskExecutor.java:27) at com.intellij.util.concurrency.BoundedTaskExecutor$1.execute(BoundedTaskExecutor.java:195) at com.intellij.util.ConcurrencyUtil.runUnderThreadName(ConcurrencyUtil.java:208) at com.intellij.util.concurrency.BoundedTaskExecutor$1.run(BoundedTaskExecutor.java:184) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:668) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:665) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:665) at java.base/java.lang.Thread.run(Thread.java:834) 2022-12-04 19:36:54,807 [ 7240] ERROR - nSystem.impl.ActionManagerImpl - Android Studio Arctic Fox | 2020.3.1 Patch 4 Build #AI-203.7717.56.2031.7935034 2022-12-04 19:36:54,810 [ 7243] ERROR - nSystem.impl.ActionManagerImpl - JDK: 11.0.10; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o. 2022-12-04 19:36:54,810 [ 7243] ERROR - nSystem.impl.ActionManagerImpl - OS: Mac OS X 2022-12-04 19:36:54,811 [ 7244] ERROR - nSystem.impl.ActionManagerImpl - Plugin to blame: ASM Bytecode Viewer Support Kotlin version: 1.1 2022-12-04 19:36:54,812 [ 7245] ERROR - nSystem.impl.ActionManagerImpl - Last Action: 2022-12-04 19:36:54,998 [ 7431] INFO - verflags.ServerFlagInitializer - Enabled server flags: analytics/surveys/followup, exceptions/ClassCastException 2022-12-04 19:36:55,688 [ 8121] ERROR - ect.impl.ProjectFrameAllocator - Key org.objectweb.asm.idea.plugin.view.BytecodeOutline duplicated org.picocontainer.PicoRegistrationException: Key org.objectweb.asm.idea.plugin.view.BytecodeOutline duplicated at com.intellij.util.pico.DefaultPicoContainer.registerComponent(DefaultPicoContainer.java:119) at com.intellij.serviceContainer.ComponentManagerImpl.registerServices(ComponentManagerImpl.kt:364) at com.intellij.serviceContainer.ComponentManagerImpl.registerComponents(ComponentManagerImpl.kt:214) at com.intellij.openapi.project.impl.ProjectLoadHelper.registerComponents(projectLoader.kt:25) at com.intellij.openapi.project.impl.ProjectManagerImpl.initProject(ProjectManagerImpl.java:171) at com.intellij.openapi.project.impl.ProjectManagerExImpl.prepareProject(ProjectManagerExImpl.kt:242) at com.intellij.openapi.project.impl.ProjectManagerExImpl.access$prepareProject(ProjectManagerExImpl.kt:52) at com.intellij.openapi.project.impl.ProjectManagerExImpl$openProject$$inlined$runInAutoSaveDisabledMode$lambda$1.invoke(ProjectManagerExImpl.kt:104) at com.intellij.openapi.project.impl.ProjectManagerExImpl$openProject$$inlined$runInAutoSaveDisabledMode$lambda$1.invoke(ProjectManagerExImpl.kt:52) at com.intellij.openapi.project.impl.ProjectUiFrameAllocator$run$progressTask$1.run(ProjectFrameAllocator.kt:86) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$new$0(ProgressRunner.java:79) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$submit$3(ProgressRunner.java:235) at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:178) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:658) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:610) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:65) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:165) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$submit$4(ProgressRunner.java:235) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:668) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:665) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:665) at java.base/java.lang.Thread.run(Thread.java:834) 2022-12-04 19:36:55,689 [ 8122] ERROR - ect.impl.ProjectFrameAllocator - Android Studio Arctic Fox | 2020.3.1 Patch 4 Build #AI-203.7717.56.2031.7935034 2022-12-04 19:36:55,689 [ 8122] ERROR - ect.impl.ProjectFrameAllocator - JDK: 11.0.10; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o. 2022-12-04 19:36:55,689 [ 8122] ERROR - ect.impl.ProjectFrameAllocator - OS: Mac OS X 2022-12-04 19:36:55,689 [ 8122] ERROR - ect.impl.ProjectFrameAllocator - Last Action: 2022-12-04 19:36:56,476 [ 8909] ERROR - ect.impl.ProjectFrameAllocator - Key org.objectweb.asm.idea.plugin.view.BytecodeOutline duplicated org.picocontainer.PicoRegistrationException: Key org.objectweb.asm.idea.plugin.view.BytecodeOutline duplicated at com.intellij.util.pico.DefaultPicoContainer.registerComponent(DefaultPicoContainer.java:119) at com.intellij.serviceContainer.ComponentManagerImpl.registerServices(ComponentManagerImpl.kt:364) at com.intellij.serviceContainer.ComponentManagerImpl.registerComponents(ComponentManagerImpl.kt:214) at com.intellij.openapi.project.impl.ProjectLoadHelper.registerComponents(projectLoader.kt:25) at com.intellij.openapi.project.impl.ProjectManagerImpl.initProject(ProjectManagerImpl.java:171) at com.intellij.openapi.project.impl.ProjectManagerExImpl.prepareProject(ProjectManagerExImpl.kt:242) at com.intellij.openapi.project.impl.ProjectManagerExImpl.access$prepareProject(ProjectManagerExImpl.kt:52) at com.intellij.openapi.project.impl.ProjectManagerExImpl$openProject$$inlined$runInAutoSaveDisabledMode$lambda$1.invoke(ProjectManagerExImpl.kt:104) at com.intellij.openapi.project.impl.ProjectManagerExImpl$openProject$$inlined$runInAutoSaveDisabledMode$lambda$1.invoke(ProjectManagerExImpl.kt:52) at com.intellij.openapi.project.impl.ProjectUiFrameAllocator$run$progressTask$1.run(ProjectFrameAllocator.kt:86) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$new$0(ProgressRunner.java:79) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$submit$3(ProgressRunner.java:235) at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:178) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:658) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:610) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:65) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:165) at com.intellij.openapi.progress.impl.ProgressRunner.lambda$submit$4(ProgressRunner.java:235) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:668) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:665) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:665) at java.base/java.lang.Thread.run(Thread.java:834) 2022-12-04 19:36:56,477 [ 8910] ERROR - ect.impl.ProjectFrameAllocator - Android Studio Arctic Fox | 2020.3.1 Patch 4 Build #AI-203.7717.56.2031.7935034 2022-12-04 19:36:56,477 [ 8910] ERROR - ect.impl.ProjectFrameAllocator - JDK: 11.0.10; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o. 2022-12-04 19:36:56,477 [ 8910] ERROR - ect.impl.ProjectFrameAllocator - OS: Mac OS X 2022-12-04 19:36:56,477 [ 8910] ERROR - ect.impl.ProjectFrameAllocator - Last Action: 2022-12-04 19:36:56,482 [ 8915] INFO - gs.impl.UpdateCheckerComponent - channel: release Anyone who experienced the similar issue can tell me, thanks!
[ "Thanks, I resolved by finding the real path of AS then deleted the libs.\n" ]
[ 0 ]
[]
[]
[ "android", "bytecode", "kotlin" ]
stackoverflow_0074675396_android_bytecode_kotlin.txt
Q: Dot plot with column names on x-axis and shape of dots by index names I have this toy dataframe data = {'Column 1' : [1., 2., 3., 4.], 'Column 2' : [1.2, 2.2, 3.2, 4.2] } df = pd.DataFrame(data, index=["Apples", "Oranges", "Puppies", "Ducks"]) How can I make a dot/scatter plot of the dataframe with column names on the x-axis and the shape of the dots are different based on the index values, something similar to this? A: To create a dot/scatter plot of a dataframe with the column names on the x-axis and the shape of the dots being different based on the index values, you can use the matplotlib.pyplot.scatter function. Here is an example of how you could accomplish this using the toy dataframe you provided: import matplotlib.pyplot as plt # Create a scatter plot using the dataframe's column names as the x-axis values # and the index values as the y-axis values plt.scatter(df.columns, df.index) # Set the x-axis label to "Columns" plt.xlabel("Columns") # Set the y-axis label to "Index" plt.ylabel("Index") # Show the plot plt.show() This will create a scatter plot with the column names on the x-axis and the index values on the y-axis. The shape of the dots will be the default shape used by the scatter function, which is a circular dot. If you want to customize the shape of the dots based on the index values, you can create a dictionary mapping the index values to the desired marker shapes, and then use the marker parameter of the scatter function to specify the marker shapes for each index value. Here is an example of how you could do this: # Define a dictionary mapping the index values to the desired marker shapes marker_shapes = {"Apples": "^", "Oranges": "s", "Puppies": "*", "Ducks": "o"} # Create a scatter plot using the dataframe's column names as the x-axis values # and the index values as the y-axis values, using the marker shapes defined in # the marker_shapes dictionary plt.scatter(df.columns, df.index, marker=df.index.map(marker_shapes)) # Set the x-axis label to "Columns" plt.xlabel("Columns") # Set the y-axis label to "Index" plt.ylabel("Index") # Show the plot plt.show() This will create a scatter plot with the same x- and y-axis values as before, but the shape of the dots will be different based on the index values, as specified in the marker_shapes dictionary.
Dot plot with column names on x-axis and shape of dots by index names
I have this toy dataframe data = {'Column 1' : [1., 2., 3., 4.], 'Column 2' : [1.2, 2.2, 3.2, 4.2] } df = pd.DataFrame(data, index=["Apples", "Oranges", "Puppies", "Ducks"]) How can I make a dot/scatter plot of the dataframe with column names on the x-axis and the shape of the dots are different based on the index values, something similar to this?
[ "To create a dot/scatter plot of a dataframe with the column names on the x-axis and the shape of the dots being different based on the index values, you can use the matplotlib.pyplot.scatter function. Here is an example of how you could accomplish this using the toy dataframe you provided:\nimport matplotlib.pyplot as plt\n\n# Create a scatter plot using the dataframe's column names as the x-axis values\n# and the index values as the y-axis values\nplt.scatter(df.columns, df.index)\n\n# Set the x-axis label to \"Columns\"\nplt.xlabel(\"Columns\")\n\n# Set the y-axis label to \"Index\"\nplt.ylabel(\"Index\")\n\n# Show the plot\nplt.show()\n\nThis will create a scatter plot with the column names on the x-axis and the index values on the y-axis. The shape of the dots will be the default shape used by the scatter function, which is a circular dot.\nIf you want to customize the shape of the dots based on the index values, you can create a dictionary mapping the index values to the desired marker shapes, and then use the marker parameter of the scatter function to specify the marker shapes for each index value. Here is an example of how you could do this:\n# Define a dictionary mapping the index values to the desired marker shapes\nmarker_shapes = {\"Apples\": \"^\", \"Oranges\": \"s\", \"Puppies\": \"*\", \"Ducks\": \"o\"}\n\n# Create a scatter plot using the dataframe's column names as the x-axis values\n# and the index values as the y-axis values, using the marker shapes defined in\n# the marker_shapes dictionary\nplt.scatter(df.columns, df.index, marker=df.index.map(marker_shapes))\n\n# Set the x-axis label to \"Columns\"\nplt.xlabel(\"Columns\")\n\n# Set the y-axis label to \"Index\"\nplt.ylabel(\"Index\")\n\n# Show the plot\nplt.show()\n\nThis will create a scatter plot with the same x- and y-axis values as before, but the shape of the dots will be different based on the index values, as specified in the marker_shapes dictionary.\n" ]
[ 0 ]
[]
[]
[ "pandas", "plot", "python" ]
stackoverflow_0074675686_pandas_plot_python.txt
Q: Print Last Line of File Read In with Python How could I print the final line of a text file read in with python? fi=open(inputFile,"r") for line in fi: #go to last line and print it A: One option is to use file.readlines(): f1 = open(inputFile, "r") last_line = f1.readlines()[-1] f1.close() If you don't need the file after, though, it is recommended to use contexts using with, so that the file is automatically closed after: with open(inputFile, "r") as f1: last_line = f1.readlines()[-1] A: Do you need to be efficient by not reading all the lines into memory at once? Instead you can iterate over the file object. with open(inputfile, "r") as f: for line in f: pass print line #this is the last line of the file A: Three ways to read the last line of a file: For a small file, read the entire file into memory with open("file.txt") as file: lines = file.readlines() print(lines[-1]) For a big file, read line by line and print the last line with open("file.txt") as file: for line in file: pass print(line) For efficient approach, go directly to the last line import os with open("file.txt", "rb") as file: # Go to the end of the file before the last break-line file.seek(-2, os.SEEK_END) # Keep reading backward until you find the next break-line while file.read(1) != b'\n': file.seek(-2, os.SEEK_CUR) print(file.readline().decode()) A: If you can afford to read the entire file in memory(if the filesize is considerably less than the total memory), you can use the readlines() method as mentioned in one of the other answers, but if the filesize is large, the best way to do it is: fi=open(inputFile, 'r') lastline = "" for line in fi: lastline = line print lastline A: You could use csv.reader() to read your file as a list and print the last line. Cons: This method allocates a new variable (not an ideal memory-saver for very large files). Pros: List lookups take O(1) time, and you can easily manipulate a list if you happen to want to modify your inputFile, as well as read the final line. import csv lis = list(csv.reader(open(inputFile))) print lis[-1] # prints final line as a list of strings A: If you care about memory this should help you. last_line = '' with open(inputfile, "r") as f: f.seek(-2, os.SEEK_END) # -2 because last character is likely \n cur_char = f.read(1) while cur_char != '\n': last_line = cur_char + last_line f.seek(-2, os.SEEK_CUR) cur_char = f.read(1) print last_line A: This might help you. class FileRead(object): def __init__(self, file_to_read=None,file_open_mode=None,stream_size=100): super(FileRead, self).__init__() self.file_to_read = file_to_read self.file_to_write='test.txt' self.file_mode=file_open_mode self.stream_size=stream_size def file_read(self): try: with open(self.file_to_read,self.file_mode) as file_context: contents=file_context.read(self.stream_size) while len(contents)>0: yield contents contents=file_context.read(self.stream_size) except Exception as e: if type(e).__name__=='IOError': output="You have a file input/output error {}".format(e.args[1]) raise Exception (output) else: output="You have a file error {} {} ".format(file_context.name,e.args) raise Exception (output) b=FileRead("read.txt",'r') contents=b.file_read() lastline = "" for content in contents: # print '-------' lastline = content print lastline A: I use the pandas module for its convenience (often to extract the last value). Here is the example for the last row: import pandas as pd df = pd.read_csv('inputFile.csv') last_value = df.iloc[-1] The return is a pandas Series of the last row. The advantage of this is that you also get the entire contents as a pandas DataFrame.
Print Last Line of File Read In with Python
How could I print the final line of a text file read in with python? fi=open(inputFile,"r") for line in fi: #go to last line and print it
[ "One option is to use file.readlines():\nf1 = open(inputFile, \"r\")\nlast_line = f1.readlines()[-1]\nf1.close()\n\nIf you don't need the file after, though, it is recommended to use contexts using with, so that the file is automatically closed after:\nwith open(inputFile, \"r\") as f1:\n last_line = f1.readlines()[-1]\n\n", "Do you need to be efficient by not reading all the lines into memory at once? Instead you can iterate over the file object. \nwith open(inputfile, \"r\") as f:\n for line in f: pass\n print line #this is the last line of the file\n\n", "Three ways to read the last line of a file:\n\nFor a small file, read the entire file into memory\n\n\nwith open(\"file.txt\") as file: \n lines = file.readlines()\nprint(lines[-1])\n\n\nFor a big file, read line by line and print the last line\n\n\nwith open(\"file.txt\") as file:\n for line in file:\n pass\nprint(line)\n\n\nFor efficient approach, go directly to the last line\n\n\nimport os\n\nwith open(\"file.txt\", \"rb\") as file:\n # Go to the end of the file before the last break-line\n file.seek(-2, os.SEEK_END) \n # Keep reading backward until you find the next break-line\n while file.read(1) != b'\\n':\n file.seek(-2, os.SEEK_CUR) \n print(file.readline().decode())\n\n", "If you can afford to read the entire file in memory(if the filesize is considerably less than the total memory), you can use the readlines() method as mentioned in one of the other answers, but if the filesize is large, the best way to do it is:\nfi=open(inputFile, 'r')\nlastline = \"\"\nfor line in fi:\n lastline = line\nprint lastline\n\n", "You could use csv.reader() to read your file as a list and print the last line.\nCons: This method allocates a new variable (not an ideal memory-saver for very large files).\nPros: List lookups take O(1) time, and you can easily manipulate a list if you happen to want to modify your inputFile, as well as read the final line.\nimport csv\n\nlis = list(csv.reader(open(inputFile)))\nprint lis[-1] # prints final line as a list of strings\n\n", "If you care about memory this should help you.\nlast_line = ''\nwith open(inputfile, \"r\") as f:\n f.seek(-2, os.SEEK_END) # -2 because last character is likely \\n\n cur_char = f.read(1)\n\n while cur_char != '\\n':\n last_line = cur_char + last_line\n f.seek(-2, os.SEEK_CUR)\n cur_char = f.read(1)\n\n print last_line\n\n", "This might help you.\nclass FileRead(object):\n\n def __init__(self, file_to_read=None,file_open_mode=None,stream_size=100):\n\n super(FileRead, self).__init__()\n self.file_to_read = file_to_read\n self.file_to_write='test.txt'\n self.file_mode=file_open_mode\n self.stream_size=stream_size\n\n\n def file_read(self):\n try:\n with open(self.file_to_read,self.file_mode) as file_context:\n contents=file_context.read(self.stream_size)\n while len(contents)>0:\n yield contents\n contents=file_context.read(self.stream_size)\n\n except Exception as e:\n\n if type(e).__name__=='IOError':\n output=\"You have a file input/output error {}\".format(e.args[1])\n raise Exception (output)\n else:\n output=\"You have a file error {} {} \".format(file_context.name,e.args) \n raise Exception (output)\n\nb=FileRead(\"read.txt\",'r')\ncontents=b.file_read()\n\nlastline = \"\"\nfor content in contents:\n# print '-------'\n lastline = content\nprint lastline\n\n", "I use the pandas module for its convenience (often to extract the last value).\nHere is the example for the last row:\nimport pandas as pd\n\ndf = pd.read_csv('inputFile.csv')\nlast_value = df.iloc[-1]\n\n\nThe return is a pandas Series of the last row.\nThe advantage of this is that you also get the entire contents as a pandas DataFrame.\n" ]
[ 17, 10, 6, 4, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0037227909_python.txt
Q: Optaplaner - Working with double variable in ConstraintProvider Is there a way I can use groupBy(ConstraintCollectors.sum(x)) such as x is a variable of type Double ? I don't want to round it to n decimal pointes then multiply by 10^n. I would like to use the Double variable as is. A: As explained in an earlier answer, OptaPlanner does not provide means of working with double. That said, ConstraintCollectors.sum() is simple and if you look up its implementation, you should be able to implement a double-based one easily. Use with caution.
Optaplaner - Working with double variable in ConstraintProvider
Is there a way I can use groupBy(ConstraintCollectors.sum(x)) such as x is a variable of type Double ? I don't want to round it to n decimal pointes then multiply by 10^n. I would like to use the Double variable as is.
[ "As explained in an earlier answer, OptaPlanner does not provide means of working with double.\nThat said, ConstraintCollectors.sum() is simple and if you look up its implementation, you should be able to implement a double-based one easily. Use with caution.\n" ]
[ 0 ]
[]
[]
[ "optaplanner" ]
stackoverflow_0074675180_optaplanner.txt
Q: C# - Factory pattern using reflection or how? I'm developing a game in console c#, that you can read maps created in files. For doing so, i'm reading a file and storing that into a string. Then i'm reading each character individually and depending on the character, I need to create an object using the factory pattern. I don't know how to do it without coupling the code. I have the main entity Object. From object inherit different objects, like: Box, Wall, Grass, Tree. Each one is represented by a character in the file and translated to another character in the game, (B)ox = '■', (W)all = '▓', (G)rass = 'v', (T)ree = '↑'. The way I done that is by placing a property char "Model" in the Object with getter only, and in each object I override the getter with the corresponding model. Now, while I'm reading the file map mentioned before I need to tell the factory which object to build depending on the character read. I dont want to make a big switch(character) because it will be coupled, because for each object I want to add I will have to add a new case in the switch. Is any better way of doing so? Example of class Box: public class Box : Object { public override char Model { get { return '■'; } } public Box() { this.Name = "box"; this.MapCharacter = 'B'; this.Colors = new List<ConsoleColor>() { ConsoleColor.DarkYellow }; this.Destructible = true; this.Passable = false; this.SeeThrough = false; this.Health = 200; } public override void OnDestroy() { } } Example code of Factory: public class ObjectFactory : IObjectFactory { public Object GetObject(char mapCharacter) { switch (mapCharacter) { case 'B': return new Box(); case 'T': return new Tree(); case 'W': return new Wall(); case 'G': return new Grass(); default: return null; } } } My idea was using Reflection get the Model of each class inherted from Object and somehow return that class, but that seems poor code A: There are pros and cons of going with reflection (personally I would not go this way in general case) but with current code you can improve it a bit and reduce the boilerplate by "converting" switch to dictionary: public class ObjectFactory { private static readonly Dictionary<char, Func<MyObject>> _objectFactory = new Dictionary<char, Func<MyObject>>() { { 'B', () => new Box() }, // ... }; public Object GetObject(char mapCharacter) { if(_objectFactory.TryGetValue(mapCharacter, out var factory)) { return factory(); } return null; } } If you will decide that adding items to dictionary every time is to much - I would recommend to look into source generators, if this approach is to much - do not forget to "cache" the reflection. A: It is worth to take a look Activator.CreateInstance method. If a map has full name of class, then it is possible to create an instance like this: public class InstanceHelper { public static object Get(string fullyQualifiedName) { Type t = Type.GetType(fullyQualifiedName); return Activator.CreateInstance(t); } } So the above code can be called like this: Box box = InstanceHelper.Get("Box") as Box;
C# - Factory pattern using reflection or how?
I'm developing a game in console c#, that you can read maps created in files. For doing so, i'm reading a file and storing that into a string. Then i'm reading each character individually and depending on the character, I need to create an object using the factory pattern. I don't know how to do it without coupling the code. I have the main entity Object. From object inherit different objects, like: Box, Wall, Grass, Tree. Each one is represented by a character in the file and translated to another character in the game, (B)ox = '■', (W)all = '▓', (G)rass = 'v', (T)ree = '↑'. The way I done that is by placing a property char "Model" in the Object with getter only, and in each object I override the getter with the corresponding model. Now, while I'm reading the file map mentioned before I need to tell the factory which object to build depending on the character read. I dont want to make a big switch(character) because it will be coupled, because for each object I want to add I will have to add a new case in the switch. Is any better way of doing so? Example of class Box: public class Box : Object { public override char Model { get { return '■'; } } public Box() { this.Name = "box"; this.MapCharacter = 'B'; this.Colors = new List<ConsoleColor>() { ConsoleColor.DarkYellow }; this.Destructible = true; this.Passable = false; this.SeeThrough = false; this.Health = 200; } public override void OnDestroy() { } } Example code of Factory: public class ObjectFactory : IObjectFactory { public Object GetObject(char mapCharacter) { switch (mapCharacter) { case 'B': return new Box(); case 'T': return new Tree(); case 'W': return new Wall(); case 'G': return new Grass(); default: return null; } } } My idea was using Reflection get the Model of each class inherted from Object and somehow return that class, but that seems poor code
[ "There are pros and cons of going with reflection (personally I would not go this way in general case) but with current code you can improve it a bit and reduce the boilerplate by \"converting\" switch to dictionary:\npublic class ObjectFactory \n{\n private static readonly Dictionary<char, Func<MyObject>> _objectFactory = new Dictionary<char, Func<MyObject>>()\n {\n { 'B', () => new Box() },\n // ...\n };\n\n public Object GetObject(char mapCharacter)\n {\n if(_objectFactory.TryGetValue(mapCharacter, out var factory))\n {\n return factory();\n }\n\n return null;\n }\n}\n\nIf you will decide that adding items to dictionary every time is to much - I would recommend to look into source generators, if this approach is to much - do not forget to \"cache\" the reflection.\n", "It is worth to take a look Activator.CreateInstance method.\nIf a map has full name of class, then it is possible to create an instance like this:\npublic class InstanceHelper\n{\n public static object Get(string fullyQualifiedName)\n {\n Type t = Type.GetType(fullyQualifiedName);\n return Activator.CreateInstance(t);\n }\n}\n\nSo the above code can be called like this:\nBox box = InstanceHelper.Get(\"Box\") as Box;\n\n" ]
[ 2, 0 ]
[]
[]
[ "c#", "design_patterns" ]
stackoverflow_0074659733_c#_design_patterns.txt
Q: How to use onSuccess with useQueries in react-query? import { useQueries } from "react-query"; import axios from "axios"; const fetchFriend = id => { return axios.get(`http://localhost:4000/friends/${id}`); }; const useDynamicFriends = friendIds => { const queryResult = useQueries( friendIds.map(id => { return { queryKey: ["friends", id], queryFn: () => fetchFriend(parseInt(id)), } }) ); const isLoading = queryResult.some(result => result.isLoading) return {isLoading, queryResult}; } export default useDynamicFriends; I need to use an onSuccess method just like we can use in useQuery, that will run only after all api call is done. A: You can use queryCache.subscribe to achive that queryCache.subscribe(() => { const allQueriesResolved = queryResult.every(result => !result.isLoading); if (allQueriesResolved) { // Run your desired logic here } }); and import import { useQueries, queryCache } from "react-query";
How to use onSuccess with useQueries in react-query?
import { useQueries } from "react-query"; import axios from "axios"; const fetchFriend = id => { return axios.get(`http://localhost:4000/friends/${id}`); }; const useDynamicFriends = friendIds => { const queryResult = useQueries( friendIds.map(id => { return { queryKey: ["friends", id], queryFn: () => fetchFriend(parseInt(id)), } }) ); const isLoading = queryResult.some(result => result.isLoading) return {isLoading, queryResult}; } export default useDynamicFriends; I need to use an onSuccess method just like we can use in useQuery, that will run only after all api call is done.
[ "You can use queryCache.subscribe to achive that\n queryCache.subscribe(() => {\n \n const allQueriesResolved = queryResult.every(result => !result.isLoading);\n if (allQueriesResolved) {\n // Run your desired logic here\n }\n });\n\nand import\nimport { useQueries, queryCache } from \"react-query\";\n\n" ]
[ 0 ]
[]
[]
[ "react_hooks", "react_query", "reactjs" ]
stackoverflow_0074675779_react_hooks_react_query_reactjs.txt
Q: ImportError: cannot import name 'Option' from 'discord' I can't run my code, because of this Can someone help me ? ImportError: cannot import name 'Option' from 'discord' My imports are import discord import datetime from discord import Option from discord.ext import commands from discord.ext.commands import MissingPermissions from discord_components import Button, Select, SelectOption, ComponentsBot, interaction from discord_components.component import ButtonStyle from discord_slash import SlashCommand from discord_slash.utils.manage_commands import create_option A: This command solved the problem for me. pip install django-commands How do I come up with that? Quite simple, I changed from discord.py to py-cord and when I rebuild the server I have the same problem all the time. Not on my main system, so I analyzed my library and came across this library. It may be that it doesn't help for you.
ImportError: cannot import name 'Option' from 'discord'
I can't run my code, because of this Can someone help me ? ImportError: cannot import name 'Option' from 'discord' My imports are import discord import datetime from discord import Option from discord.ext import commands from discord.ext.commands import MissingPermissions from discord_components import Button, Select, SelectOption, ComponentsBot, interaction from discord_components.component import ButtonStyle from discord_slash import SlashCommand from discord_slash.utils.manage_commands import create_option
[ "This command solved the problem for me.\npip install django-commands\n\nHow do I come up with that?\nQuite simple, I changed from discord.py to py-cord and when I rebuild the server I have the same problem all the time.\nNot on my main system, so I analyzed my library and came across this library.\nIt may be that it doesn't help for you.\n" ]
[ 0 ]
[ "You need to install the developer version of pycord...\npip install git+https://github.com/Pycord-Development/pycord\n\nor\npy -3 -m pip install -U py-cord\n\n" ]
[ -1 ]
[ "discord.py", "python" ]
stackoverflow_0073464299_discord.py_python.txt
Q: Split vector by each NA in R I have the following vector called input: input <- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2) [1] 1 2 1 NA 3 2 NA 1 5 6 NA 2 2 I would like to split this vector into multiple vectors by each NA. So the desired output should look like this: > output [[1]] [1] 1 2 1 [[2]] [1] 3 2 [[3]] [1] 1 5 6 [[4]] [1] 2 2 As you can see every time a NA appears, it splits into a new vector. So I was wondering if anyone knows how to split a vector by each NA into multiple vectors? A: One way could go like follows: identify the NAs do cumsum split according to the cumulative sums remove the NAs input <- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2) tmp <- cumsum(is.na(input)) lapply(split(input, tmp), na.omit) A: Using a similar logic to @tpetzoldt, but removing the NAs before the split: split(na.omit(input), cumsum(is.na(input))[!is.na(input)]) $`0` [1] 1 2 1 $`1` [1] 3 2 $`2` [1] 1 5 6 $`3` [1] 2 2 A: This one is too verbose and overcomplicated, but for me it is easier to think of such problems, just wanted to share: library(tidyverse) tibble(input) %>% group_by(id = cumsum(is.na(input))) %>% na.omit %>% group_split() %>% map(.,~(.x %>%select(-id))) %>% map(.,~(.x %>%pull)) [[1]] [1] 1 2 1 [[2]] [1] 3 2 [[3]] [1] 1 5 6 [[4]] [1] 2 2 A: Here's a solution that is not verbose: strsplit(paste(input, collapse = " "), " NA ") [[1]] [1] "1 2 1" "3 2" "1 5 6" "2 2"
Split vector by each NA in R
I have the following vector called input: input <- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2) [1] 1 2 1 NA 3 2 NA 1 5 6 NA 2 2 I would like to split this vector into multiple vectors by each NA. So the desired output should look like this: > output [[1]] [1] 1 2 1 [[2]] [1] 3 2 [[3]] [1] 1 5 6 [[4]] [1] 2 2 As you can see every time a NA appears, it splits into a new vector. So I was wondering if anyone knows how to split a vector by each NA into multiple vectors?
[ "One way could go like follows:\n\nidentify the NAs\ndo cumsum\nsplit according to the cumulative sums\nremove the NAs\n\ninput <- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2)\ntmp <- cumsum(is.na(input))\nlapply(split(input, tmp), na.omit)\n\n", "Using a similar logic to @tpetzoldt, but removing the NAs before the split:\nsplit(na.omit(input), cumsum(is.na(input))[!is.na(input)])\n\n$`0`\n[1] 1 2 1\n\n$`1`\n[1] 3 2\n\n$`2`\n[1] 1 5 6\n\n$`3`\n[1] 2 2\n\n", "This one is too verbose and overcomplicated, but for me it is easier to think of such problems, just wanted to share:\nlibrary(tidyverse)\n\ntibble(input) %>% \n group_by(id = cumsum(is.na(input))) %>% \n na.omit %>% \n group_split() %>% \n map(.,~(.x %>%select(-id))) %>% \n map(.,~(.x %>%pull))\n\n\n[[1]]\n[1] 1 2 1\n\n[[2]]\n[1] 3 2\n\n[[3]]\n[1] 1 5 6\n\n[[4]]\n[1] 2 2\n\n", "Here's a solution that is not verbose:\nstrsplit(paste(input, collapse = \" \"), \" NA \")\n[[1]]\n[1] \"1 2 1\" \"3 2\" \"1 5 6\" \"2 2\" \n\n" ]
[ 5, 5, 2, 2 ]
[]
[]
[ "r", "split", "vector" ]
stackoverflow_0074674411_r_split_vector.txt
Q: Scipy curve fit doesn't perform a fit and raises "Covariance of the parameters could not be estimated" error I am trying to do a simple linear curve fit with scipy, normally this method works fine for me. This time however for a reason unknown to me it doesn't work. (I suspect that maybe the numbers are so big that it reaches the limit of what can be stored under a given data type.) Regardless of the reason, the idea is to make a plot that looks like this: As you see on the axis here the numbers are of a common order of magnitude. However this time I tried to make a fit to much bigger data points on the order of 1E10, for this I tried to use the following code (here I present only the code for making a scatter plot and then fitting only one data set). import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit ucrt_T = 2/np.sqrt(3) ucrt_U = 0.1/np.sqrt(3) T = [314.1, 325.1, 335.1, 345.1, 355.1, 365.1, 374.1, 384.1, 393.1] T_to_4th = [9733560790.61, 11170378213.80, 12609495509.84, 14183383217.88, 15900203737.92, 17768359469.96, 19586229219.65, 21765930026.49, 23878782252.31] ucrt_T_lst = [143130823.11, 158701221.00, 173801148.95, 189829733.26, 206814686.75, 224783722.22, 241820148.88, 261735288.93, 280568229.17] UBlack = [1.9,3.1, 4.4, 5.6, 7.0, 8.7, 10.2, 11.8, 13.4] def lin_function(x,a,b): return a*x + b def line_fit_2(): #Dodanie pozostałych punktów na wykresie plt.scatter(UBlack, T_to_4th, color='blue') plt.errorbar(UBlack, T_to_4th, yerr=ucrt_T, fmt='o') #Seria CZARNA VltBlack = np.array(UBlack) Tt4 = np.array(T_to_4th) popt, pcov = curve_fit(lin_function, VltBlack, Tt4, absolute_sigma=False) perr = np.sqrt(np.diag(pcov)) y = lin_function(VltBlack, *popt) #Stylistyka i wygląd wykresu #plt.plot(Pressure1, y, '--', color = 'g', label="fit with: $a={:.3f}\pm{:.3f}$, $b={:.3f}\pm{:.3f}$" .format(popt[0], perr[0], popt[1], perr[1])) plt.plot(VltBlack, y, '--', color='green') plt.ylabel(r'$T^4$ w $[K^4]$') plt.xlabel(r'Napięcie termometru U w [mV]') plt.legend(['Fit', 'Data points']) plt.grid() plt.show() line_fit_2() If you will run it you will find out that the scatter plot is created however the fit isn't executed properly, as only a horizontal line will be added. Additionally an error OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning) is raised. I would be very happy to know what I am doing wrong or how to resolve this problem. All help is appreciated! A: You've pretty much already answered your question, so I'll just confirm your suspicion: the reason the OptimizeWarning is raised is because the underlying optimization algorithm doesn't work properly/diverges due to large parameter numbers. The solution is very simple, just scale your input parameters before using the fitting tool. Just keep the scaling in mind when you add labels to your x/y axis: T_to_4th = np.array([9733560790.61, 11170378213.80, 12609495509.84, 14183383217.88, 15900203737.92, 17768359469.96, 19586229219.65, 21765930026.49, 23878782252.31])/10e6 ucrt_T_lst = np.array([143130823.11, 158701221.00, 173801148.95, 189829733.26, 206814686.75, 224783722.22, 241820148.88, 261735288.93, 280568229.17])/10e6 What I did is just divide the lists with big numbers by 10e6. This means that the values are no longer in kPa for example, but in mega kPa (which would be GPa now). To divide the entire list by the same value, first convert it to a numpy array. Hope this helps :)
Scipy curve fit doesn't perform a fit and raises "Covariance of the parameters could not be estimated" error
I am trying to do a simple linear curve fit with scipy, normally this method works fine for me. This time however for a reason unknown to me it doesn't work. (I suspect that maybe the numbers are so big that it reaches the limit of what can be stored under a given data type.) Regardless of the reason, the idea is to make a plot that looks like this: As you see on the axis here the numbers are of a common order of magnitude. However this time I tried to make a fit to much bigger data points on the order of 1E10, for this I tried to use the following code (here I present only the code for making a scatter plot and then fitting only one data set). import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit ucrt_T = 2/np.sqrt(3) ucrt_U = 0.1/np.sqrt(3) T = [314.1, 325.1, 335.1, 345.1, 355.1, 365.1, 374.1, 384.1, 393.1] T_to_4th = [9733560790.61, 11170378213.80, 12609495509.84, 14183383217.88, 15900203737.92, 17768359469.96, 19586229219.65, 21765930026.49, 23878782252.31] ucrt_T_lst = [143130823.11, 158701221.00, 173801148.95, 189829733.26, 206814686.75, 224783722.22, 241820148.88, 261735288.93, 280568229.17] UBlack = [1.9,3.1, 4.4, 5.6, 7.0, 8.7, 10.2, 11.8, 13.4] def lin_function(x,a,b): return a*x + b def line_fit_2(): #Dodanie pozostałych punktów na wykresie plt.scatter(UBlack, T_to_4th, color='blue') plt.errorbar(UBlack, T_to_4th, yerr=ucrt_T, fmt='o') #Seria CZARNA VltBlack = np.array(UBlack) Tt4 = np.array(T_to_4th) popt, pcov = curve_fit(lin_function, VltBlack, Tt4, absolute_sigma=False) perr = np.sqrt(np.diag(pcov)) y = lin_function(VltBlack, *popt) #Stylistyka i wygląd wykresu #plt.plot(Pressure1, y, '--', color = 'g', label="fit with: $a={:.3f}\pm{:.3f}$, $b={:.3f}\pm{:.3f}$" .format(popt[0], perr[0], popt[1], perr[1])) plt.plot(VltBlack, y, '--', color='green') plt.ylabel(r'$T^4$ w $[K^4]$') plt.xlabel(r'Napięcie termometru U w [mV]') plt.legend(['Fit', 'Data points']) plt.grid() plt.show() line_fit_2() If you will run it you will find out that the scatter plot is created however the fit isn't executed properly, as only a horizontal line will be added. Additionally an error OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning) is raised. I would be very happy to know what I am doing wrong or how to resolve this problem. All help is appreciated!
[ "You've pretty much already answered your question, so I'll just confirm your suspicion: the reason the OptimizeWarning is raised is because the underlying optimization algorithm doesn't work properly/diverges due to large parameter numbers.\nThe solution is very simple, just scale your input parameters before using the fitting tool. Just keep the scaling in mind when you add labels to your x/y axis:\nT_to_4th = np.array([9733560790.61, 11170378213.80, 12609495509.84, 14183383217.88, 15900203737.92, 17768359469.96, 19586229219.65, 21765930026.49, 23878782252.31])/10e6\nucrt_T_lst = np.array([143130823.11, 158701221.00, 173801148.95, 189829733.26, 206814686.75, 224783722.22, 241820148.88, 261735288.93, 280568229.17])/10e6\n\nWhat I did is just divide the lists with big numbers by 10e6. This means that the values are no longer in kPa for example, but in mega kPa (which would be GPa now).\nTo divide the entire list by the same value, first convert it to a numpy array.\nHope this helps :)\n" ]
[ 1 ]
[]
[]
[ "curve_fitting", "matplotlib", "python", "scipy" ]
stackoverflow_0074675326_curve_fitting_matplotlib_python_scipy.txt
Q: Creating a topic in Kafka only in one cluster I run Docker file in this location which creates 3 clusters with 3 brokers. When I run docker ps, I can see 3 zookeeper and 3 kafka instances. When I create a topic in one of the Kafka brokers (0.0.0.0:9092), and list broker topics, I see that topic listed in all brokers. My expectation was to see that topic only under the broker I picked. What am I missing? A: When you create a topic in Kafka, it is created on all the brokers in the cluster. This is because Kafka is a distributed system, and topics are distributed across the brokers in a cluster. When you list the topics on a particular broker, it will show all the topics that exist in the cluster, not just the ones that are hosted on that specific broker. If you want to see which topics are hosted on which broker, you can use the describe command to get more detailed information about a particular topic. For example, you can run the following command to get information about the my-topic topic: bin/kafka-topics.sh --zookeeper localhost:2181 --describe --topic my-topic This will return information about the topic, including the number of partitions, the replicas, and the leaders for each partition. The leader for a partition is the broker that is currently responsible for that partition. To limit a topic to only a single broker in Kafka, you need to specify the number of partitions and the number of replicas when you create the topic. The number of partitions determines how many partitions the topic will have, and the number of replicas determines how many copies of each partition will be created. For example, to create a topic with only one partition and one replica, which will be hosted on only a single broker, you can use the following command: bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic my-topic This will create a topic with one partition and one replica, and it will be hosted on only a single broker in the cluster. Keep in mind that when you limit a topic to only a single broker, you are sacrificing availability and durability for the topic. If the broker hosting the topic goes down, the topic will be unavailable, and if the broker fails, you may lose data for the topic. It is generally recommended to use multiple partitions and replicas for a topic to ensure availability and durability.
Creating a topic in Kafka only in one cluster
I run Docker file in this location which creates 3 clusters with 3 brokers. When I run docker ps, I can see 3 zookeeper and 3 kafka instances. When I create a topic in one of the Kafka brokers (0.0.0.0:9092), and list broker topics, I see that topic listed in all brokers. My expectation was to see that topic only under the broker I picked. What am I missing?
[ "When you create a topic in Kafka, it is created on all the brokers in the cluster. This is because Kafka is a distributed system, and topics are distributed across the brokers in a cluster. When you list the topics on a particular broker, it will show all the topics that exist in the cluster, not just the ones that are hosted on that specific broker.\nIf you want to see which topics are hosted on which broker, you can use the describe command to get more detailed information about a particular topic. For example, you can run the following command to get information about the my-topic topic:\nbin/kafka-topics.sh --zookeeper localhost:2181 --describe --topic my-topic\n\nThis will return information about the topic, including the number of partitions, the replicas, and the leaders for each partition. The leader for a partition is the broker that is currently responsible for that partition.\nTo limit a topic to only a single broker in Kafka, you need to specify the number of partitions and the number of replicas when you create the topic. The number of partitions determines how many partitions the topic will have, and the number of replicas determines how many copies of each partition will be created.\nFor example, to create a topic with only one partition and one replica, which will be hosted on only a single broker, you can use the following command:\nbin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic my-topic\n\nThis will create a topic with one partition and one replica, and it will be hosted on only a single broker in the cluster.\nKeep in mind that when you limit a topic to only a single broker, you are sacrificing availability and durability for the topic. If the broker hosting the topic goes down, the topic will be unavailable, and if the broker fails, you may lose data for the topic. It is generally recommended to use multiple partitions and replicas for a topic to ensure availability and durability.\n" ]
[ 2 ]
[]
[]
[ "apache_kafka" ]
stackoverflow_0074675797_apache_kafka.txt
Q: Why my return value is coming as NaN or default in kotlin? For a while, I want to convert the entered currencies to each other and show them on the other screen, but when I check the view model with println, the result I can see is NaN when I make viewmodel.result in the ui. What is the reason for this and how can I solve it? my ui If the user presses oncofirm on the button, the operations in the view model are performed. if (viewModel.isDialogShown) { AlertDialog( onDismiss = { viewModel.onDismissClick() }, onConfirm = { viewModel.getConversionRateByCurrency() viewModel.onDismissClick() //viewModel.calculate() println(viewModel.resultState) With println(viewModel.resultState) comes 0.0 but when I press the button for the second time and say confirm, then the correct result comes. my view model @HiltViewModel class ExchangeMainViewModel @Inject constructor( private val exchangeInsertUseCase: InsertExchangeUseCase, private val exchangeGetAllUseCase: GetAllExchangeUseCase, private val getConversionRateByCurrencyUseCase: GetConversionRateByCurrencyUseCase ) : ViewModel() { var isDialogShown by mutableStateOf(false) private set var dropDownMenuItem1 by mutableStateOf("") var dropDownMenuItem2 by mutableStateOf("") var outLineTxtFieldValue by mutableStateOf(TextFieldValue("")) var firstConversionRate by mutableStateOf(0.0) var secondConversionRate by mutableStateOf(0.0) var resultState by mutableStateOf(0.0) fun onConfirmClick() { isDialogShown = true } fun onDismissClick() { isDialogShown = false } fun check(context: Context): Boolean { if (outLineTxtFieldValue.text.isNullOrEmpty() || dropDownMenuItem1 == "" || dropDownMenuItem2 == "") { Toast.makeText(context, "please select a value and currency ", Toast.LENGTH_LONG).show() return false } return true } fun getConversionRateByCurrency() { viewModelScope.launch { val firstRate = async { getConversionRateByCurrencyUseCase.getConversionRateByCurrency(dropDownMenuItem1) } val secondRate = async { getConversionRateByCurrencyUseCase.getConversionRateByCurrency(dropDownMenuItem2) } firstConversionRate = firstRate.await() secondConversionRate = secondRate.await() delay(200L) val result = async { calculate() } resultState = result.await() } } private fun calculate(): Double { if (!firstConversionRate.equals(0.0) && !secondConversionRate.equals(0.0)) { val amount = outLineTxtFieldValue.text.toInt() val resultOfCalculate = (amount / firstConversionRate) * secondConversionRate return resultOfCalculate } return 1.1 } } I can see the value in the view model but not the ui. Also, I do a lot of checking with if and 0.0 because I couldn't get out of it, so I followed a method like this because I couldn't solve the problem. Anyone have a better idea? A: It looks like the issue is that you are not updating the resultState value until after the getConversionRateByCurrency function has completed. Because of this, when you try to display the resultState in your UI, it has not yet been updated and so it displays NaN. One way to fix this would be to update the resultState value immediately after calling the getConversionRateByCurrency function, like this: fun onConfirmClick() { isDialogShown = true getConversionRateByCurrency() resultState = calculate() } This will ensure that the resultState value is updated before it is displayed in the UI. You can then remove the delay and async calls in the getConversionRateByCurrency function, as they are no longer needed. Additionally, you may want to update your calculate function to handle the case where the conversion rates are not yet available (i.e., if they are still 0.0). You could do this by returning a default value (e.g., 0.0) if the conversion rates are not yet available, like this: private fun calculate(): Double { if (firstConversionRate != 0.0 && secondConversionRate != 0.0) { val amount = out
Why my return value is coming as NaN or default in kotlin?
For a while, I want to convert the entered currencies to each other and show them on the other screen, but when I check the view model with println, the result I can see is NaN when I make viewmodel.result in the ui. What is the reason for this and how can I solve it? my ui If the user presses oncofirm on the button, the operations in the view model are performed. if (viewModel.isDialogShown) { AlertDialog( onDismiss = { viewModel.onDismissClick() }, onConfirm = { viewModel.getConversionRateByCurrency() viewModel.onDismissClick() //viewModel.calculate() println(viewModel.resultState) With println(viewModel.resultState) comes 0.0 but when I press the button for the second time and say confirm, then the correct result comes. my view model @HiltViewModel class ExchangeMainViewModel @Inject constructor( private val exchangeInsertUseCase: InsertExchangeUseCase, private val exchangeGetAllUseCase: GetAllExchangeUseCase, private val getConversionRateByCurrencyUseCase: GetConversionRateByCurrencyUseCase ) : ViewModel() { var isDialogShown by mutableStateOf(false) private set var dropDownMenuItem1 by mutableStateOf("") var dropDownMenuItem2 by mutableStateOf("") var outLineTxtFieldValue by mutableStateOf(TextFieldValue("")) var firstConversionRate by mutableStateOf(0.0) var secondConversionRate by mutableStateOf(0.0) var resultState by mutableStateOf(0.0) fun onConfirmClick() { isDialogShown = true } fun onDismissClick() { isDialogShown = false } fun check(context: Context): Boolean { if (outLineTxtFieldValue.text.isNullOrEmpty() || dropDownMenuItem1 == "" || dropDownMenuItem2 == "") { Toast.makeText(context, "please select a value and currency ", Toast.LENGTH_LONG).show() return false } return true } fun getConversionRateByCurrency() { viewModelScope.launch { val firstRate = async { getConversionRateByCurrencyUseCase.getConversionRateByCurrency(dropDownMenuItem1) } val secondRate = async { getConversionRateByCurrencyUseCase.getConversionRateByCurrency(dropDownMenuItem2) } firstConversionRate = firstRate.await() secondConversionRate = secondRate.await() delay(200L) val result = async { calculate() } resultState = result.await() } } private fun calculate(): Double { if (!firstConversionRate.equals(0.0) && !secondConversionRate.equals(0.0)) { val amount = outLineTxtFieldValue.text.toInt() val resultOfCalculate = (amount / firstConversionRate) * secondConversionRate return resultOfCalculate } return 1.1 } } I can see the value in the view model but not the ui. Also, I do a lot of checking with if and 0.0 because I couldn't get out of it, so I followed a method like this because I couldn't solve the problem. Anyone have a better idea?
[ "It looks like the issue is that you are not updating the resultState value until after the getConversionRateByCurrency function has completed. Because of this, when you try to display the resultState in your UI, it has not yet been updated and so it displays NaN.\nOne way to fix this would be to update the resultState value immediately after calling the getConversionRateByCurrency function, like this:\nfun onConfirmClick() {\n isDialogShown = true\n getConversionRateByCurrency()\n resultState = calculate()\n}\n\nThis will ensure that the resultState value is updated before it is displayed in the UI. You can then remove the delay and async calls in the getConversionRateByCurrency function, as they are no longer needed.\nAdditionally, you may want to update your calculate function to handle the case where the conversion rates are not yet available (i.e., if they are still 0.0). You could do this by returning a default value (e.g., 0.0) if the conversion rates are not yet available, like this:\nprivate fun calculate(): Double {\n if (firstConversionRate != 0.0 && secondConversionRate != 0.0) {\n val amount = out\n\n" ]
[ 1 ]
[]
[]
[ "kotlin" ]
stackoverflow_0074675470_kotlin.txt
Q: Writing to the stream buffer of a string stream overrides the previous data What I want to do is to create string stream , and output stream, giving the buffer of string stream to output stream, so that it will output data to the string stream. Everything seems fine, but when I try to add data to buffer of the string stream it overrides the previous data. My question is why? and how can achieve a result, such that it does not override but simply adds to the string stream. Here is my code below: #include <iostream> #include <iomanip> #include <string> #include <sstream> using namespace std; int main () { stringstream s1("hello I am string stream"); streambuf *s1_bfr = s1.rdbuf(); ostream my_stream (s1_bfr); my_stream <<"hey"<<endl; cout <<s1.rdbuf()<<endl; //gives the result : " hey o I am string stream"( seems to me overriden) return 0; } A: The reason that the string in the stringstream object is being overwritten when you write to it using the ostream object is that, by default, the ostream object writes to the beginning of the stream buffer. This means that when you write the string "hey" to the ostream object, it replaces the initial string in the stringstream object. To fix this issue, you can use the ostream::seekp method to move the write position of the ostream object to the end of the stream buffer before writing to it. Here is an example of how you might do this: stringstream s1("hello I am string stream"); streambuf *s1_bfr = s1.rdbuf(); ostream my_stream (s1_bfr); my_stream.seekp(0, ios_base::end); // move the write position to the end of the stream my_stream <<"hey"<<endl; cout <<s1.rdbuf()<<endl; After making this change, the output of the program should be "hello I am string streamhey". Alternatively, you can use the stringstream::str method to retrieve the current contents of the stringstream object as a string, and then append the new string to the end of this string. Here is an example of how you might do this: stringstream s1("hello I am string stream"); string str = s1.str(); str += "hey\n"; s1.str(str); cout <<s1.rdbuf()<<endl; A: If you want to append the data in the beginning: #include <iostream> #include <iomanip> #include <string> #include <sstream> using namespace std; int main() { stringstream s1("hello I am string stream"); streambuf *s1_bfr = s1.rdbuf(); stringstream temp; //Create a temp stringsteam temp << "hey"; //add desired string into the stream temp << s1_bfr; //then add your orignal stream s1 = move(temp); // or ss.swap(temp); cout <<s1_bfr<<endl; return 0; }
Writing to the stream buffer of a string stream overrides the previous data
What I want to do is to create string stream , and output stream, giving the buffer of string stream to output stream, so that it will output data to the string stream. Everything seems fine, but when I try to add data to buffer of the string stream it overrides the previous data. My question is why? and how can achieve a result, such that it does not override but simply adds to the string stream. Here is my code below: #include <iostream> #include <iomanip> #include <string> #include <sstream> using namespace std; int main () { stringstream s1("hello I am string stream"); streambuf *s1_bfr = s1.rdbuf(); ostream my_stream (s1_bfr); my_stream <<"hey"<<endl; cout <<s1.rdbuf()<<endl; //gives the result : " hey o I am string stream"( seems to me overriden) return 0; }
[ "The reason that the string in the stringstream object is being overwritten when you write to it using the ostream object is that, by default, the ostream object writes to the beginning of the stream buffer. This means that when you write the string \"hey\" to the ostream object, it replaces the initial string in the stringstream object.\nTo fix this issue, you can use the ostream::seekp method to move the write position of the ostream object to the end of the stream buffer before writing to it. Here is an example of how you might do this:\nstringstream s1(\"hello I am string stream\");\nstreambuf *s1_bfr = s1.rdbuf();\nostream my_stream (s1_bfr);\nmy_stream.seekp(0, ios_base::end); // move the write position to the end of the stream\nmy_stream <<\"hey\"<<endl;\ncout <<s1.rdbuf()<<endl;\n\nAfter making this change, the output of the program should be \"hello I am string streamhey\".\nAlternatively, you can use the stringstream::str method to retrieve the current contents of the stringstream object as a string, and then append the new string to the end of this string. Here is an example of how you might do this:\nstringstream s1(\"hello I am string stream\");\nstring str = s1.str();\nstr += \"hey\\n\";\ns1.str(str);\ncout <<s1.rdbuf()<<endl;\n\n", "If you want to append the data in the beginning:\n #include <iostream>\n #include <iomanip>\n #include <string>\n #include <sstream>\n \n using namespace std;\n \n int main() {\n stringstream s1(\"hello I am string stream\");\n streambuf *s1_bfr = s1.rdbuf();\n stringstream temp; //Create a temp stringsteam\n temp << \"hey\"; //add desired string into the stream\n temp << s1_bfr; //then add your orignal stream\n s1 = move(temp); // or ss.swap(temp); \n cout <<s1_bfr<<endl;\n \n return 0;\n }\n\n" ]
[ 2, 1 ]
[]
[]
[ "c++", "ostream", "stream", "streambuf", "stringstream" ]
stackoverflow_0074675402_c++_ostream_stream_streambuf_stringstream.txt
Q: How to open a PopupMenuButton? How do I open a popup menu from a second widget? final button = new PopupMenuButton( itemBuilder: (_) => <PopupMenuItem<String>>[ new PopupMenuItem<String>( child: const Text('Doge'), value: 'Doge'), new PopupMenuItem<String>( child: const Text('Lion'), value: 'Lion'), ], onSelected: _doSomething); final tile = new ListTile(title: new Text('Doge or lion?'), trailing: button); I want to open the button's menu by tapping on tile. A: This works, but is inelegant (and has the same display problem as Rainer's solution above: class _MyHomePageState extends State<MyHomePage> { final GlobalKey _menuKey = GlobalKey(); @override Widget build(BuildContext context) { final button = PopupMenuButton( key: _menuKey, itemBuilder: (_) => const<PopupMenuItem<String>>[ PopupMenuItem<String>( child: Text('Doge'), value: 'Doge'), PopupMenuItem<String>( child: Text('Lion'), value: 'Lion'), ], onSelected: (_) {}); final tile = ListTile(title: Text('Doge or lion?'), trailing: button, onTap: () { // This is a hack because _PopupMenuButtonState is private. dynamic state = _menuKey.currentState; state.showButtonMenu(); }); return Scaffold( body: Center( child: tile, ), ); } } I suspect what you're actually asking for is something like what is tracked by https://github.com/flutter/flutter/issues/254 or https://github.com/flutter/flutter/issues/8277 -- the ability to associated a label with a control and have the label be clickable -- and is a missing feature from the Flutter framework. A: I think it would be better do it in this way, rather than showing a PopupMenuButton void _showPopupMenu() async { await showMenu( context: context, position: RelativeRect.fromLTRB(100, 100, 100, 100), items: [ PopupMenuItem<String>( child: const Text('Doge'), value: 'Doge'), PopupMenuItem<String>( child: const Text('Lion'), value: 'Lion'), ], elevation: 8.0, ); } There will be times when you would want to display _showPopupMenu at the location where you pressed on the button Use GestureDetector for that final tile = new ListTile( title: new Text('Doge or lion?'), trailing: GestureDetector( onTapDown: (TapDownDetails details) { _showPopupMenu(details.globalPosition); }, child: Container(child: Text("Press Me")), ), ); and then _showPopupMenu will be like _showPopupMenu(Offset offset) async { double left = offset.dx; double top = offset.dy; await showMenu( context: context, position: RelativeRect.fromLTRB(left, top, 0, 0), items: [ ..., elevation: 8.0, ); } A: Screenshot: Full code: class MyPage extends StatelessWidget { final GlobalKey<PopupMenuButtonState<int>> _key = GlobalKey(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( actions: [ PopupMenuButton<int>( key: _key, itemBuilder: (context) { return <PopupMenuEntry<int>>[ PopupMenuItem(child: Text('0'), value: 0), PopupMenuItem(child: Text('1'), value: 1), ]; }, ), ], ), body: RaisedButton( onPressed: () => _key.currentState.showButtonMenu(), child: Text('Open/Close menu'), ), ); } } A: I found a solution to your question. You can provide a child to PopupMenuButton which can be any Widget including a ListTile (see code below). Only problem is that the PopupMenu opens on the left side of the ListTile. final popupMenu = new PopupMenuButton( child: new ListTile( title: new Text('Doge or lion?'), trailing: const Icon(Icons.more_vert), ), itemBuilder: (_) => <PopupMenuItem<String>>[ new PopupMenuItem<String>( child: new Text('Doge'), value: 'Doge'), new PopupMenuItem<String>( child: new Text('Lion'), value: 'Lion'), ], onSelected: _doSomething, ) A: I don't think there is a way to achieve this behaviour. Although you can attach an onTap attribute to the tile, you can't access the MenuButton from the 'outside' An approach you could take is to use ExpansionPanels because they look like ListTiles and are intended to allow easy modification and editing. A: if you are using Material showMenu but you menu doesn't work properly or opens in wrong place follow my answer. this answer is based on answer of Vishal Singh. in GestureDetector use onLongPressStart or onTapUp for sending offset to function. onLongPressStart: (detail){ _showPopupMenu(detail.globalPosition); }, onLongPress is equivalent to (and is called immediately after) onLongPressStart. onTapUp, which is called at the same time (with onTap) but includes details regarding the pointer position. and for menu position do some thing like below position: RelativeRect.fromDirectional(textDirection: Directionality.of(context), start: left, top: top, end: left+2, bottom: top+2) full code _showPopupMenu(Offset offset) async { double left = offset.dx; double top = offset.dy; await showMenu( context: context, shape: RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(AppConst.borderRadiusSmall))), position: RelativeRect.fromDirectional(textDirection: Directionality.of(context), start: left, top: top, end: left+2, bottom: top+2), items: _getMenuItems(menu), elevation: 8.0, ).then((value) { value?.onTap.call(); }); }
How to open a PopupMenuButton?
How do I open a popup menu from a second widget? final button = new PopupMenuButton( itemBuilder: (_) => <PopupMenuItem<String>>[ new PopupMenuItem<String>( child: const Text('Doge'), value: 'Doge'), new PopupMenuItem<String>( child: const Text('Lion'), value: 'Lion'), ], onSelected: _doSomething); final tile = new ListTile(title: new Text('Doge or lion?'), trailing: button); I want to open the button's menu by tapping on tile.
[ "This works, but is inelegant (and has the same display problem as Rainer's solution above:\nclass _MyHomePageState extends State<MyHomePage> {\n final GlobalKey _menuKey = GlobalKey();\n\n @override\n Widget build(BuildContext context) {\n final button = PopupMenuButton(\n key: _menuKey,\n itemBuilder: (_) => const<PopupMenuItem<String>>[\n PopupMenuItem<String>(\n child: Text('Doge'), value: 'Doge'),\n PopupMenuItem<String>(\n child: Text('Lion'), value: 'Lion'),\n ],\n onSelected: (_) {});\n\n final tile =\n ListTile(title: Text('Doge or lion?'), trailing: button, onTap: () {\n // This is a hack because _PopupMenuButtonState is private.\n dynamic state = _menuKey.currentState;\n state.showButtonMenu();\n });\n return Scaffold(\n body: Center(\n child: tile,\n ),\n );\n }\n}\n\nI suspect what you're actually asking for is something like what is tracked by https://github.com/flutter/flutter/issues/254 or https://github.com/flutter/flutter/issues/8277 -- the ability to associated a label with a control and have the label be clickable -- and is a missing feature from the Flutter framework.\n", "I think it would be better do it in this way, rather than showing a PopupMenuButton\nvoid _showPopupMenu() async {\n await showMenu(\n context: context,\n position: RelativeRect.fromLTRB(100, 100, 100, 100),\n items: [\n PopupMenuItem<String>(\n child: const Text('Doge'), value: 'Doge'),\n PopupMenuItem<String>(\n child: const Text('Lion'), value: 'Lion'),\n ],\n elevation: 8.0,\n );\n}\n\n\nThere will be times when you would want to display _showPopupMenu at the location where you pressed on the button\nUse GestureDetector for that\nfinal tile = new ListTile(\n title: new Text('Doge or lion?'),\n trailing: GestureDetector(\n onTapDown: (TapDownDetails details) {\n _showPopupMenu(details.globalPosition);\n },\n child: Container(child: Text(\"Press Me\")),\n ),\n);\n\nand then _showPopupMenu will be like\n_showPopupMenu(Offset offset) async {\n double left = offset.dx;\n double top = offset.dy;\n await showMenu(\n context: context,\n position: RelativeRect.fromLTRB(left, top, 0, 0),\n items: [\n ...,\n elevation: 8.0,\n );\n}\n\n", "Screenshot:\n\n\nFull code:\nclass MyPage extends StatelessWidget {\n final GlobalKey<PopupMenuButtonState<int>> _key = GlobalKey();\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n actions: [\n PopupMenuButton<int>(\n key: _key,\n itemBuilder: (context) {\n return <PopupMenuEntry<int>>[\n PopupMenuItem(child: Text('0'), value: 0),\n PopupMenuItem(child: Text('1'), value: 1),\n ];\n },\n ),\n ],\n ),\n body: RaisedButton(\n onPressed: () => _key.currentState.showButtonMenu(),\n child: Text('Open/Close menu'),\n ),\n );\n }\n}\n\n", "I found a solution to your question. You can provide a child to PopupMenuButton which can be any Widget including a ListTile (see code below). Only problem is that the PopupMenu opens on the left side of the ListTile.\nfinal popupMenu = new PopupMenuButton(\n child: new ListTile(\n title: new Text('Doge or lion?'),\n trailing: const Icon(Icons.more_vert),\n ),\n itemBuilder: (_) => <PopupMenuItem<String>>[\n new PopupMenuItem<String>(\n child: new Text('Doge'), value: 'Doge'),\n new PopupMenuItem<String>(\n child: new Text('Lion'), value: 'Lion'),\n ],\n onSelected: _doSomething,\n)\n\n", "I don't think there is a way to achieve this behaviour. Although you can attach an onTap attribute to the tile, you can't access the MenuButton from the 'outside' \nAn approach you could take is to use ExpansionPanels because they look like ListTiles and are intended to allow easy modification and editing. \n", "if you are using Material showMenu but you menu doesn't work properly or opens in wrong place follow my answer.\nthis answer is based on answer of Vishal Singh.\nin GestureDetector\nuse onLongPressStart or onTapUp for sending offset to function.\nonLongPressStart: (detail){\n _showPopupMenu(detail.globalPosition);\n},\n\n\nonLongPress is equivalent to (and is called immediately after) onLongPressStart.\n\n\nonTapUp, which is called at the same time (with onTap) but includes details regarding the pointer position.\n\nand for menu position do some thing like below\n position: RelativeRect.fromDirectional(textDirection: Directionality.of(context), start: left, top: top, end: left+2, bottom: top+2)\n\nfull code\n\n _showPopupMenu(Offset offset) async {\n double left = offset.dx;\n double top = offset.dy;\n await showMenu(\n context: context,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.all(\n Radius.circular(AppConst.borderRadiusSmall))),\n position: RelativeRect.fromDirectional(textDirection: Directionality.of(context), start: left, top: top, end: left+2, bottom: top+2),\n items: _getMenuItems(menu),\n elevation: 8.0,\n ).then((value) {\n value?.onTap.call();\n });\n }\n\n" ]
[ 44, 44, 8, 7, 0, 0 ]
[ "class MyPage extends StatefulWidget {\n @override\n State<MyPage> createState() => _MyPageState();\n}\n\nclass _MyPageState extends State<MyPage> {\n final GlobalKey<PopupMenuButtonState<int>> _key = GlobalKey();\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n actions: [\n PopupMenuButton<int>(\n key: _key,\n itemBuilder: (context) {\n return <PopupMenuEntry<int>>[\n PopupMenuItem(child: Text('0'), value: 0),\n PopupMenuItem(child: Text('1'), value: 1),\n ];\n },\n ),\n ],\n ),\n body: RaisedButton(\n onPressed: () => _key.currentState.showButtonMenu(),\n child: Text('Open/Close menu'),\n ),\n );\n }\n}\n\n" ]
[ -1 ]
[ "dart", "flutter" ]
stackoverflow_0043349013_dart_flutter.txt
Q: Dictionary Py. Bid auction game. It should print the name and the bid of the person who bade higher but it keeps printing the last inserted key/value I have this code: def calc_winner(bidd): count = 0 winner = '' for name in bidd: higher = bidd[name] if higher > count: count = higher winner = str(name) print(f"The winner is {winner}, who bid ${count}.") calc_winner({"a": 1, "b": 2, "c": 0}) The code is supposed to find the highest bid and the name of the bidder, by remembering the value if it is higher than was previously seen. But instead, it seems that the last bid in the dictionary is used, no matter what, and the name is blank when that bid isn't the highest. That is: the output should be The winner is b, who bid $2 for this input, but instead I get The winner is , who bid $0.. What is wrong with the code, and how can I fix it? A: I checked your code and it seem to work. You just did not indent it properly :) Here is the working one: from replit import clear bidding = {} end = True def calc_winner(bidd): count = 0 winner = "" for name in bidd: higher = bidd[name] if higher > count: count = higher winner = str(name) print(f"The winner is {winner} with their bid of ${count}. Congratulations!") while end: name = input("What's your name?: ") bid = int(input("What's your bid?: $")) bidding[name] = bid print(bidding) result = input('Are there any other bidders? Type "yes" or "no": ') if result == "no": end = False calc_winner(bidding) elif result == "yes": clear()
Dictionary Py. Bid auction game. It should print the name and the bid of the person who bade higher but it keeps printing the last inserted key/value
I have this code: def calc_winner(bidd): count = 0 winner = '' for name in bidd: higher = bidd[name] if higher > count: count = higher winner = str(name) print(f"The winner is {winner}, who bid ${count}.") calc_winner({"a": 1, "b": 2, "c": 0}) The code is supposed to find the highest bid and the name of the bidder, by remembering the value if it is higher than was previously seen. But instead, it seems that the last bid in the dictionary is used, no matter what, and the name is blank when that bid isn't the highest. That is: the output should be The winner is b, who bid $2 for this input, but instead I get The winner is , who bid $0.. What is wrong with the code, and how can I fix it?
[ "I checked your code and it seem to work. You just did not indent it properly :)\nHere is the working one:\nfrom replit import clear\n\nbidding = {}\nend = True\n\ndef calc_winner(bidd):\n count = 0\n winner = \"\"\n for name in bidd:\n higher = bidd[name]\n if higher > count:\n count = higher\n winner = str(name)\n print(f\"The winner is {winner} with their bid of ${count}. Congratulations!\")\n\n\nwhile end:\n name = input(\"What's your name?: \")\n bid = int(input(\"What's your bid?: $\"))\n bidding[name] = bid\n print(bidding)\n result = input('Are there any other bidders? Type \"yes\" or \"no\": ')\n if result == \"no\":\n end = False\n calc_winner(bidding)\n elif result == \"yes\":\n clear()\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074675821_dictionary_python.txt
Q: MaterialUI - Changing the color Textfield on focus I'm trying to change the color of the label text in Textfield but I can't seem to figure it out. Here is what I'm trying: <TextField value={value} key={name} label={label} id={id} name={name} InputLabelProps={{ shrink: true, FormLabelClasses: { 'root': { '&:focused': { color: 'white' } }, focused: 'true' } }} /> Can someone give me a pointer on what I'm doing wrong here? I've also tried using the MuiThemeProvider but can't seem to figure that one out either: const theme = createMuiTheme({ overrides: { MuiFormLabel: { focused: true, root: { '&.focused': { color: 'white' } } } } }); How can I change the color of the Label? In this photo, I want the "Notes" to match the color of the underline Thanks for your help! A: Tim! Here is the snippet that should help you. const { TextField, createMuiTheme, MuiThemeProvider, CssBaseline, } = window['material-ui']; const theme = createMuiTheme({ overrides: { MuiFormLabel: { root: { "&$focused": { color: "tomato", fontWeight: "bold" } }, focused: {} } } }); class Index extends React.Component { render() { return ( <MuiThemeProvider theme={theme}> <div> <CssBaseline /> <TextField label="Text field" InputLabelProps={{shrink:true}} /> </div> </MuiThemeProvider> ); } } ReactDOM.render(<Index />, document.getElementById('root')); <script src="https://unpkg.com/react@latest/umd/react.development.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/react-dom@latest/umd/react-dom.development.js" crossorigin="anonymous"></script> <script src="https://unpkg.com/@material-ui/core/umd/material-ui.development.js" crossorigin="anonymous"></script> <div id="root"></div> A: Another way of doing it without the override is to have: const textStyles = makeStyles({ root: { "& .Mui-focused": { color: "tomato", fontWeight: "bold" }, }); class Index extends React.Component { const TextClass = textStyles() render() { return ( <MuiThemeProvider theme={theme}> <div> <CssBaseline /> <TextField className={textStyles.root} label="Text field" InputLabelProps={{shrink:true}} /> </div> </MuiThemeProvider> ); } } A: for v5 of @mui this code works const theme = createTheme({ components: { MuiInputLabel: { styleOverrides: { root: { fontWeight: 'bold', "&.Mui-focused": { color: 'rgba(0, 0, 0, 0.87)', }, }, } }, MuiTextField: { defaultProps: { variant: 'standard', }, }, }, A: const theme = createMuiTheme({ overrides: { MuiFormLabel: { root: { "&$focused": { .... } }, } } });
MaterialUI - Changing the color Textfield on focus
I'm trying to change the color of the label text in Textfield but I can't seem to figure it out. Here is what I'm trying: <TextField value={value} key={name} label={label} id={id} name={name} InputLabelProps={{ shrink: true, FormLabelClasses: { 'root': { '&:focused': { color: 'white' } }, focused: 'true' } }} /> Can someone give me a pointer on what I'm doing wrong here? I've also tried using the MuiThemeProvider but can't seem to figure that one out either: const theme = createMuiTheme({ overrides: { MuiFormLabel: { focused: true, root: { '&.focused': { color: 'white' } } } } }); How can I change the color of the Label? In this photo, I want the "Notes" to match the color of the underline Thanks for your help!
[ "Tim!\nHere is the snippet that should help you.\n\n\nconst {\r\n TextField,\r\n createMuiTheme,\r\n MuiThemeProvider,\r\n CssBaseline,\r\n} = window['material-ui'];\r\n\r\nconst theme = createMuiTheme({\r\n overrides: {\r\n MuiFormLabel: {\r\n root: {\r\n \"&$focused\": {\r\n color: \"tomato\",\r\n fontWeight: \"bold\"\r\n }\r\n }, \r\n \r\n focused: {}\r\n }\r\n }\r\n});\r\n\r\nclass Index extends React.Component { \r\n render() {\r\n return (\r\n <MuiThemeProvider theme={theme}>\r\n <div>\r\n <CssBaseline />\r\n <TextField label=\"Text field\" InputLabelProps={{shrink:true}} />\r\n </div>\r\n </MuiThemeProvider>\r\n );\r\n }\r\n}\r\n\r\nReactDOM.render(<Index />, document.getElementById('root'));\n <script src=\"https://unpkg.com/react@latest/umd/react.development.js\" crossorigin=\"anonymous\"></script>\r\n <script src=\"https://unpkg.com/react-dom@latest/umd/react-dom.development.js\" crossorigin=\"anonymous\"></script>\r\n <script src=\"https://unpkg.com/@material-ui/core/umd/material-ui.development.js\" crossorigin=\"anonymous\"></script>\r\n\r\n<div id=\"root\"></div>\n\n\n\n", "Another way of doing it without the override is to have:\nconst textStyles = makeStyles({\n root: {\n \"& .Mui-focused\": {\n color: \"tomato\", \n fontWeight: \"bold\"\n },\n});\n\nclass Index extends React.Component { \n const TextClass = textStyles()\n render() {\n return (\n <MuiThemeProvider theme={theme}>\n <div>\n <CssBaseline />\n <TextField className={textStyles.root} label=\"Text field\" InputLabelProps={{shrink:true}} />\n </div>\n </MuiThemeProvider>\n );\n }\n}\n\n\n", "for v5 of @mui this code works\nconst theme = createTheme({\n components: {\n MuiInputLabel: {\n styleOverrides: {\n root: {\n fontWeight: 'bold',\n \"&.Mui-focused\": {\n color: 'rgba(0, 0, 0, 0.87)',\n },\n },\n }\n },\n MuiTextField: {\n defaultProps: {\n variant: 'standard',\n },\n },\n },\n\n", "const theme = createMuiTheme({\n overrides: {\n MuiFormLabel: {\n root: {\n \"&$focused\": {\n ....\n }\n }, \n }\n }\n });\n\n" ]
[ 11, 4, 1, 0 ]
[]
[]
[ "material_ui", "reactjs" ]
stackoverflow_0052615530_material_ui_reactjs.txt
Q: Extract covariance from data frame in a loop sample_size <- 200 sample_meanvector <- c(3, 4) sample_covariance_matrix <- matrix(c(2, 1, 1, 2), ncol = 2) # create bivariate normal distribution sample_distribution <- mvrnorm(n = sample_size, mu = sample_meanvector, Sigma = sample_covariance_matrix) #Convert the datatype df_sample_distribution <- as.data.frame(sample_distribution) df_sample_distribution$Y <- (1 + df_sample_distribution$V1*2 + df_sample_distribution$V2 + rnorm(200,0,1)) colnames(df_sample_distribution)[1] <- "X1" colnames(df_sample_distribution)[2] <- "X2" Code above is the one I use to generate a bivariate normal distribution vectors and code below is the code to run regression over the generated data. Test2 <- lm( Y ~ X1, data = df_sample_distribution) #to extract only specific coefficients summary(Test)$coefficients[2,1] My question is whether there is a way such that I can regenerate data and run regression over it for 200 times and save all the outputs in a list. Here is the pseudo code in my head. for (){ #generate data for () { #extract coeffiients and insert them in a list } } In simple terms, step 1: create data step 2: run regression over it step 3: get the coefficient (hopefully save them in a list) I am looking for code that can loop through step 1 to 3 for 200 times and save everything results. Any ideas or inspirations are welcomed. Thank you guys in advance. A: Just wrap your code into a for-loop like your pseudo code: library(MASS) iterations <- 10 # In your example this should be 200 sample_size <- 200 sample_meanvector <- c(3, 4) sample_covariance_matrix <- matrix(c(2, 1, 1, 2), ncol = 2) # create output data.frame df_output <- data.frame(iteration = integer(0), coeff = double(0)) # loop over data generation and regression for (i in seq_len(iterations)) { sample_distribution <- mvrnorm(n = sample_size, mu = sample_meanvector, Sigma = sample_covariance_matrix) #Convert the datatype df_sample_distribution <- as.data.frame(sample_distribution) df_sample_distribution$Y <- (1 + df_sample_distribution$V1*2 + df_sample_distribution$V2 + rnorm(200,0,1)) colnames(df_sample_distribution)[1] <- "X1" colnames(df_sample_distribution)[2] <- "X2" df_output[i, 1] <- i df_output[i, 2] <- summary(lm( Y ~ X1, data = df_sample_distribution))$coefficients[2,1] } This returns df_output containing coefficients for each iteration: iteration coeff 1 1 2.647886 2 2 2.274654 3 3 2.447453 4 4 2.451471 5 5 2.568877 6 6 2.428295 7 7 2.440396 8 8 2.478357 9 9 2.477211 10 10 2.367012
Extract covariance from data frame in a loop
sample_size <- 200 sample_meanvector <- c(3, 4) sample_covariance_matrix <- matrix(c(2, 1, 1, 2), ncol = 2) # create bivariate normal distribution sample_distribution <- mvrnorm(n = sample_size, mu = sample_meanvector, Sigma = sample_covariance_matrix) #Convert the datatype df_sample_distribution <- as.data.frame(sample_distribution) df_sample_distribution$Y <- (1 + df_sample_distribution$V1*2 + df_sample_distribution$V2 + rnorm(200,0,1)) colnames(df_sample_distribution)[1] <- "X1" colnames(df_sample_distribution)[2] <- "X2" Code above is the one I use to generate a bivariate normal distribution vectors and code below is the code to run regression over the generated data. Test2 <- lm( Y ~ X1, data = df_sample_distribution) #to extract only specific coefficients summary(Test)$coefficients[2,1] My question is whether there is a way such that I can regenerate data and run regression over it for 200 times and save all the outputs in a list. Here is the pseudo code in my head. for (){ #generate data for () { #extract coeffiients and insert them in a list } } In simple terms, step 1: create data step 2: run regression over it step 3: get the coefficient (hopefully save them in a list) I am looking for code that can loop through step 1 to 3 for 200 times and save everything results. Any ideas or inspirations are welcomed. Thank you guys in advance.
[ "Just wrap your code into a for-loop like your pseudo code:\nlibrary(MASS)\n\niterations <- 10 # In your example this should be 200\n\nsample_size <- 200 \nsample_meanvector <- c(3, 4) \nsample_covariance_matrix <- matrix(c(2, 1, 1, 2),\n ncol = 2)\n\n# create output data.frame\ndf_output <- data.frame(iteration = integer(0), coeff = double(0))\n\n# loop over data generation and regression\nfor (i in seq_len(iterations)) {\n sample_distribution <- mvrnorm(n = sample_size,\n mu = sample_meanvector, \n Sigma = sample_covariance_matrix)\n \n #Convert the datatype\n df_sample_distribution <- as.data.frame(sample_distribution)\n \n df_sample_distribution$Y <- (1 + df_sample_distribution$V1*2 + df_sample_distribution$V2 + rnorm(200,0,1))\n colnames(df_sample_distribution)[1] <- \"X1\"\n colnames(df_sample_distribution)[2] <- \"X2\"\n \n df_output[i, 1] <- i\n df_output[i, 2] <- summary(lm( Y ~ X1, data = df_sample_distribution))$coefficients[2,1]\n}\n\nThis returns df_output containing coefficients for each iteration:\n iteration coeff\n1 1 2.647886\n2 2 2.274654\n3 3 2.447453\n4 4 2.451471\n5 5 2.568877\n6 6 2.428295\n7 7 2.440396\n8 8 2.478357\n9 9 2.477211\n10 10 2.367012\n\n" ]
[ 0 ]
[]
[]
[ "matrix", "r", "sampling" ]
stackoverflow_0074674660_matrix_r_sampling.txt
Q: How to integrate Developer Command Prompt for VS 2022 as Terminal in VS Code I would like to have the Microsoft VS C++ compiler cl available in VisualStudio code. I have Visual Studio Build Tools installed and can call cl from the Developer Command prompt. The default way recommended by Microsoft to get VS Code to use the cl compiler is to call VS Code from the Developer Command prompt. I would like to do it differently, with a terminal that I can call from VS Code and make it the default terminal if needed. In Windows Terminal, I get the automatically generated Developer Command prompt entry with the command line: cmd.exe /k "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\Tools\VsDevCmd.bat" -arch=x64 -host_arch=x64` or powershell.exe -NoExit -Command "&{Import-Module """C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"""; Enter-VsDevShell 0d0637f3 -SkipAutomaticLocation -DevCmdArguments """-arch=x64 -host_arch=x64"""}" If I paste this line into an existing vscode terminal, it works and I can use the cl compiler. But I can't manage to get it into an integrated terminal in settings.json. This is what I tried in the settings.json: "Developer Command Prompt for VS 2022": { "path": [ "${env:windir}\\Sysnative\\cmd.exe /k \"C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\Common7\\Tools\\VsDevCmd.bat\" -arch=x64 -host_arch=x64", "${env:windir}\\System32\\cmd.exe /k \"C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\Common7\\Tools\\VsDevCmd.bat\" -arch=x64 -host_arch=x64" ], "overrideName": true, "args": [], "icon": "terminal-cmd" }, Since VScode is pretty smart, it recognizes that this won't work and doesn't even list it as an entry within the available terminals. A: This works for me: "Dev Cmd - VS2022": { "path": "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\Tools\\VsDevCmd.bat", "args": [ "-arch=x64", "-host_arch=x64" ], "icon": "terminal-cmd" },
How to integrate Developer Command Prompt for VS 2022 as Terminal in VS Code
I would like to have the Microsoft VS C++ compiler cl available in VisualStudio code. I have Visual Studio Build Tools installed and can call cl from the Developer Command prompt. The default way recommended by Microsoft to get VS Code to use the cl compiler is to call VS Code from the Developer Command prompt. I would like to do it differently, with a terminal that I can call from VS Code and make it the default terminal if needed. In Windows Terminal, I get the automatically generated Developer Command prompt entry with the command line: cmd.exe /k "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\Tools\VsDevCmd.bat" -arch=x64 -host_arch=x64` or powershell.exe -NoExit -Command "&{Import-Module """C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"""; Enter-VsDevShell 0d0637f3 -SkipAutomaticLocation -DevCmdArguments """-arch=x64 -host_arch=x64"""}" If I paste this line into an existing vscode terminal, it works and I can use the cl compiler. But I can't manage to get it into an integrated terminal in settings.json. This is what I tried in the settings.json: "Developer Command Prompt for VS 2022": { "path": [ "${env:windir}\\Sysnative\\cmd.exe /k \"C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\Common7\\Tools\\VsDevCmd.bat\" -arch=x64 -host_arch=x64", "${env:windir}\\System32\\cmd.exe /k \"C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\Common7\\Tools\\VsDevCmd.bat\" -arch=x64 -host_arch=x64" ], "overrideName": true, "args": [], "icon": "terminal-cmd" }, Since VScode is pretty smart, it recognizes that this won't work and doesn't even list it as an entry within the available terminals.
[ "This works for me:\n\"Dev Cmd - VS2022\": {\n \"path\": \"C:\\\\Program Files\\\\Microsoft Visual Studio\\\\2022\\\\Community\\\\Common7\\\\Tools\\\\VsDevCmd.bat\",\n \"args\": [\n \"-arch=x64\",\n \"-host_arch=x64\"\n ],\n \"icon\": \"terminal-cmd\"\n},\n\n" ]
[ 0 ]
[]
[]
[ "cl", "visual_studio_code" ]
stackoverflow_0074674641_cl_visual_studio_code.txt
Q: Choose one from pair to get minimum value Given an array with n integers, we must choose at least one of two adjacent numbers and our goal is to get the lowest sum. For example, for (50,30,40,60,10,30,10) we will want to choose 30,40,10,10 for the lowest sum. What algorithm can I use to solve this problem? I don't think it's a greedy algorithm, but not sure. I tried the Greedy algorithm, but it didn't work. A: One approach to solve this problem would be to use dynamic programming. First, we need to define the subproblems we will be solving. In this case, we can define a subproblem as the minimum sum that can be obtained by choosing at least one of two adjacent numbers from a subarray of the input array. Next, we need to find the recursive relationship between the subproblems. In this case, we can consider two possibilities for the last number in the subarray: If the last number in the subarray is the first of the two adjacent numbers, the minimum sum is the sum of the minimum sum of the subarray without the last number and the second of the two adjacent numbers. If the last number in the subarray is the second of the two adjacent numbers, the minimum sum is the sum of the minimum sum of the subarray without the last number and the first of the two adjacent numbers. We can use this recursive relationship to define a recursive function to solve the problem. Here is an example implementation in Python: # Recursive function to find the minimum sum of a subarray of the input array def min_sum(arr, i): # If there are no more numbers in the array, return 0 if i < 0: return 0 # Consider the two possibilities for the last number in the subarray a = min_sum(arr, i - 2) + arr[i] b = min_sum(arr, i - 3) + arr[i - 1] # Return the minimum of the two possibilities return min(a, b) # Input array arr = [50, 30, 40, 60, 10, 30, 10] # Find the minimum sum by calling the recursive function with the length of the array as the starting index print(min_sum(arr, len(arr) - 1)) This approach will have a time complexity of O(3^n), where n is the length of the input array. This is because, for each number in the array, the recursive function is called three times (once for each possibility for the last number in the subarray). To improve the time complexity, we can use memoization to store the results of the recursive calls and avoid recalculating the same subproblems multiple times.
Choose one from pair to get minimum value
Given an array with n integers, we must choose at least one of two adjacent numbers and our goal is to get the lowest sum. For example, for (50,30,40,60,10,30,10) we will want to choose 30,40,10,10 for the lowest sum. What algorithm can I use to solve this problem? I don't think it's a greedy algorithm, but not sure. I tried the Greedy algorithm, but it didn't work.
[ "One approach to solve this problem would be to use dynamic programming.\nFirst, we need to define the subproblems we will be solving. In this case, we can define a subproblem as the minimum sum that can be obtained by choosing at least one of two adjacent numbers from a subarray of the input array.\nNext, we need to find the recursive relationship between the subproblems. In this case, we can consider two possibilities for the last number in the subarray:\nIf the last number in the subarray is the first of the two adjacent numbers, the minimum sum is the sum of the minimum sum of the subarray without the last number and the second of the two adjacent numbers.\nIf the last number in the subarray is the second of the two adjacent numbers, the minimum sum is the sum of the minimum sum of the subarray without the last number and the first of the two adjacent numbers.\nWe can use this recursive relationship to define a recursive function to solve the problem. Here is an example implementation in Python:\n# Recursive function to find the minimum sum of a subarray of the input array\ndef min_sum(arr, i):\n # If there are no more numbers in the array, return 0\n if i < 0:\n return 0\n\n # Consider the two possibilities for the last number in the subarray\n a = min_sum(arr, i - 2) + arr[i]\n b = min_sum(arr, i - 3) + arr[i - 1]\n\n # Return the minimum of the two possibilities\n return min(a, b)\n\n# Input array\narr = [50, 30, 40, 60, 10, 30, 10]\n\n# Find the minimum sum by calling the recursive function with the length of the array as the starting index\nprint(min_sum(arr, len(arr) - 1))\n\nThis approach will have a time complexity of O(3^n), where n is the length of the input array. This is because, for each number in the array, the recursive function is called three times (once for each possibility for the last number in the subarray).\nTo improve the time complexity, we can use memoization to store the results of the recursive calls and avoid recalculating the same subproblems multiple times.\n" ]
[ 0 ]
[]
[]
[ "algorithm", "greedy" ]
stackoverflow_0074675373_algorithm_greedy.txt
Q: Django cannot save a CharField with choices I have this CharField with some choices: M = 'Male' F = 'Female' O = 'Other' GENDER = [ (M, "Male"), (F, "Female"), (O, "Other") ] gender = models.CharField(max_length=10, choices=GENDER) When I try and save a model in the database I get the following error: django.db.utils.DataError: malformed array literal: "" LINE 1: ...ddleq', 'Cani', '1971-09-01'::date, '{Male}', '', ''::varcha... ^ DETAIL: Array value must start with "{" or dimension information. The {Male} value is so because I made the front end send the value like that but it's not that and the error makes no sense. Please can someone tell me why am I getting this error and how to fix it pls? I use the Python 3.8 Django 4.1 PostGreSQL Here is the TracebacK: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/mnt/500GB/calvin/projects/website/backend/api/views/profiles.py", line 51, in post new_profile = Profile.objects.create(first_name=first_name, middle_name=middle_name, last_name=last_name, bio=bio, birthdate=birthdate, gender=gender, languages=languages, user=user) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/query.py", line 671, in create obj.save(force_insert=True, using=self.db) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/base.py", line 812, in save self.save_base( File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/base.py", line 863, in save_base updated = self._save_table( File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/base.py", line 1006, in _save_table results = self._do_insert( File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/base.py", line 1047, in _do_insert return manager._insert( File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/query.py", line 1790, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1660, in execute_sql cursor.execute(sql, params) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/debug_toolbar/panels/sql/tracking.py", line 230, in execute return self._record(self.cursor.execute, sql, params) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/debug_toolbar/panels/sql/tracking.py", line 154, in _record return method(sql, params) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/backends/utils.py", line 103, in execute return super().execute(sql, params) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) django.db.utils.DataError: malformed array literal: "" LINE 1: ...ddleq', 'Cani', '1971-09-01'::date, '{Male}', '', ''::varcha... ^ DETAIL: Array value must start with "{" or dimension information. The model: # User profiles class Profile(models.Model): # Gender M = 'Male' F = 'Female' O = 'Other' GENDER = [ (M, "Male"), (F, "Female"), (O, "Other") ] # Basic information background = models.FileField(upload_to=background_to, null=True, blank=True) photo = models.FileField(upload_to=image_to, null=True, blank=True) slug = AutoSlugField(populate_from=['first_name', 'last_name', 'gender']) first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100) birthdate = models.DateField() gender = models.CharField(max_length=10, choices=GENDER) bio = models.TextField(max_length=5000, null=True, blank=True) languages = ArrayField(models.CharField(max_length=30, null=True, blank=True), null=True, blank=True) # Location information website = models.URLField(max_length=256, null=True, blank=True) # author information user = models.OneToOneField(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "profile" verbose_name_plural = "profiles" db_table = "user_profiles" def __str__(self): return self.first_name + ' ' + self.last_name def get_absolute_url(self): return self.slug A: This error is occurring because you are trying to save the value of the gender field in the database as a string, but the field is expecting an array of values. In order to fix this, you will need to change the value that is being sent from the front end to be an array instead of a string. For example, instead of sending the value as "{Male}", you would need to send it as ["Male"]. You can then use the Django built-in array field type to properly save the value in the database. Here is an example of how you could update your model to use the array field type: class MyModel(models.Model): M = 'Male' F = 'Female' O = 'Other' GENDER = [ (M, "Male"), (F, "Female"), (O, "Other") ] gender = models.ArrayField(models.CharField(max_length=10), choices=GENDER) Once you have updated your model, you can then save the array of values for the gender field in the database. You may also want to update your front end code to properly format the value as an array before sending it to the server. This will help ensure that the correct data is being saved in the database and prevent errors like this from occurring in the future.
Django cannot save a CharField with choices
I have this CharField with some choices: M = 'Male' F = 'Female' O = 'Other' GENDER = [ (M, "Male"), (F, "Female"), (O, "Other") ] gender = models.CharField(max_length=10, choices=GENDER) When I try and save a model in the database I get the following error: django.db.utils.DataError: malformed array literal: "" LINE 1: ...ddleq', 'Cani', '1971-09-01'::date, '{Male}', '', ''::varcha... ^ DETAIL: Array value must start with "{" or dimension information. The {Male} value is so because I made the front end send the value like that but it's not that and the error makes no sense. Please can someone tell me why am I getting this error and how to fix it pls? I use the Python 3.8 Django 4.1 PostGreSQL Here is the TracebacK: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/mnt/500GB/calvin/projects/website/backend/api/views/profiles.py", line 51, in post new_profile = Profile.objects.create(first_name=first_name, middle_name=middle_name, last_name=last_name, bio=bio, birthdate=birthdate, gender=gender, languages=languages, user=user) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/query.py", line 671, in create obj.save(force_insert=True, using=self.db) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/base.py", line 812, in save self.save_base( File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/base.py", line 863, in save_base updated = self._save_table( File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/base.py", line 1006, in _save_table results = self._do_insert( File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/base.py", line 1047, in _do_insert return manager._insert( File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/query.py", line 1790, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1660, in execute_sql cursor.execute(sql, params) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/debug_toolbar/panels/sql/tracking.py", line 230, in execute return self._record(self.cursor.execute, sql, params) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/debug_toolbar/panels/sql/tracking.py", line 154, in _record return method(sql, params) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/backends/utils.py", line 103, in execute return super().execute(sql, params) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/calvin/.local/share/virtualenvs/website-OCaWupbT/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) django.db.utils.DataError: malformed array literal: "" LINE 1: ...ddleq', 'Cani', '1971-09-01'::date, '{Male}', '', ''::varcha... ^ DETAIL: Array value must start with "{" or dimension information. The model: # User profiles class Profile(models.Model): # Gender M = 'Male' F = 'Female' O = 'Other' GENDER = [ (M, "Male"), (F, "Female"), (O, "Other") ] # Basic information background = models.FileField(upload_to=background_to, null=True, blank=True) photo = models.FileField(upload_to=image_to, null=True, blank=True) slug = AutoSlugField(populate_from=['first_name', 'last_name', 'gender']) first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100) birthdate = models.DateField() gender = models.CharField(max_length=10, choices=GENDER) bio = models.TextField(max_length=5000, null=True, blank=True) languages = ArrayField(models.CharField(max_length=30, null=True, blank=True), null=True, blank=True) # Location information website = models.URLField(max_length=256, null=True, blank=True) # author information user = models.OneToOneField(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "profile" verbose_name_plural = "profiles" db_table = "user_profiles" def __str__(self): return self.first_name + ' ' + self.last_name def get_absolute_url(self): return self.slug
[ "This error is occurring because you are trying to save the value of the gender field in the database as a string, but the field is expecting an array of values. In order to fix this, you will need to change the value that is being sent from the front end to be an array instead of a string.\nFor example, instead of sending the value as \"{Male}\", you would need to send it as [\"Male\"]. You can then use the Django built-in array field type to properly save the value in the database.\nHere is an example of how you could update your model to use the array field type:\nclass MyModel(models.Model):\nM = 'Male'\nF = 'Female'\nO = 'Other'\nGENDER = [\n(M, \"Male\"),\n(F, \"Female\"),\n(O, \"Other\")\n]\ngender = models.ArrayField(models.CharField(max_length=10), choices=GENDER)\n\nOnce you have updated your model, you can then save the array of values for the gender field in the database.\nYou may also want to update your front end code to properly format the value as an array before sending it to the server. This will help ensure that the correct data is being saved in the database and prevent errors like this from occurring in the future.\n" ]
[ 0 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0074675835_django_postgresql_python.txt
Q: mouseover event litsener is not fireing when i move over elements I'm trying to make a star rating system at an initial stage, the 5 star icon from font awesome deosn't seem to fire when an even litsener to add to it, i don't know what i'm doing wrong html ` <section class="mx-lg-3 pt-lg-5 pb-5" data-aos="fade-up"> <div class="container mt-5"> <div id="confirm-box">{% include "message.html" %}</div> <div class="row justify-content-center align-items-center"> <div class="col-lg-5 col-md-6 mb-3"> <img src="{{product.image.url}}" class="w-100" alt="product image"> </div> <div class="col-lg-3 col-md-5 product-details"> <p class="sale text-center">Sale</p> <h2>{{product.name|title}}</h2> <p>Product id: {{product.id}}</p> <div class="ratings"> <span class="fa fa-star checked" id="first"></span> <span class="fa fa-star checked" id="second"></span> <span class="fa fa-star checked" id="third"></span> <span class="fa fa-star-half-stroke checked" id="fourth"></span> <span class="fa fa-star" id="fifth"></span> </div> <p class="product-price">USD ${{product.price}}</p> <label for="">Quantity: </label> <input type="text" readonly id="product-quantity" value="{{current_item.quantity}}"> <button id="update-cart" data-product={{product.id}} data-action="add" class="btn add-btn update-cart">Add to cart</button> </div> </div> </div> </section> Javascript ` const one = document.getElementById('first') const two = document.getElementById('second') const three = document.getElementById('third') const four = document.getElementById('fourth') const five = document.getElementById('fifth') const arr = [one, two, three, four, five] one.addEventListener('mouseover', function(event){ console.log(event.targetS) console.log('event is working') }) arr.forEach(function(item) { item.addEventListener('mouseover', function(event) { console.log(event.target) }) }) i've tried it with just one of the element and it still doesn't fire A: You're trying to add the event listener to an element that doesn't exist in the DOM yet. To fix this issue, you can move the code that adds the event listener to the elements to a function that gets called when the page has finished loading. You can use the window.onload event to call this function, which will ensure that the elements have been added to the page before you try to add the event listener. Here's an example of how you can do this: window.onload = function() { const one = document.getElementById('first') const two = document.getElementById('second') const three = document.getElementById('third') const four = document.getElementById('fourth') const five = document.getElementById('fifth') const arr = [one, two, three, four, five] arr.forEach(function(item) { item.addEventListener('mouseover', function(event) { console.log(event.target) }) }) }
mouseover event litsener is not fireing when i move over elements
I'm trying to make a star rating system at an initial stage, the 5 star icon from font awesome deosn't seem to fire when an even litsener to add to it, i don't know what i'm doing wrong html ` <section class="mx-lg-3 pt-lg-5 pb-5" data-aos="fade-up"> <div class="container mt-5"> <div id="confirm-box">{% include "message.html" %}</div> <div class="row justify-content-center align-items-center"> <div class="col-lg-5 col-md-6 mb-3"> <img src="{{product.image.url}}" class="w-100" alt="product image"> </div> <div class="col-lg-3 col-md-5 product-details"> <p class="sale text-center">Sale</p> <h2>{{product.name|title}}</h2> <p>Product id: {{product.id}}</p> <div class="ratings"> <span class="fa fa-star checked" id="first"></span> <span class="fa fa-star checked" id="second"></span> <span class="fa fa-star checked" id="third"></span> <span class="fa fa-star-half-stroke checked" id="fourth"></span> <span class="fa fa-star" id="fifth"></span> </div> <p class="product-price">USD ${{product.price}}</p> <label for="">Quantity: </label> <input type="text" readonly id="product-quantity" value="{{current_item.quantity}}"> <button id="update-cart" data-product={{product.id}} data-action="add" class="btn add-btn update-cart">Add to cart</button> </div> </div> </div> </section> Javascript ` const one = document.getElementById('first') const two = document.getElementById('second') const three = document.getElementById('third') const four = document.getElementById('fourth') const five = document.getElementById('fifth') const arr = [one, two, three, four, five] one.addEventListener('mouseover', function(event){ console.log(event.targetS) console.log('event is working') }) arr.forEach(function(item) { item.addEventListener('mouseover', function(event) { console.log(event.target) }) }) i've tried it with just one of the element and it still doesn't fire
[ "You're trying to add the event listener to an element that doesn't exist in the DOM yet.\nTo fix this issue, you can move the code that adds the event listener to the elements to a function that gets called when the page has finished loading. You can use the window.onload event to call this function, which will ensure that the elements have been added to the page before you try to add the event listener.\nHere's an example of how you can do this:\nwindow.onload = function() {\n const one = document.getElementById('first')\n const two = document.getElementById('second')\n const three = document.getElementById('third')\n const four = document.getElementById('fourth')\n const five = document.getElementById('fifth')\n\n const arr = [one, two, three, four, five]\n\n arr.forEach(function(item) {\n item.addEventListener('mouseover', function(event) {\n console.log(event.target)\n })\n })\n}\n\n" ]
[ 1 ]
[]
[]
[ "addeventlistener", "arrays", "html", "javascript" ]
stackoverflow_0074675859_addeventlistener_arrays_html_javascript.txt
Q: Speed up multiplication of two dense tensors I want to perform element wise multiplication between two tensors, where most of the elements are zero. For two example tensors: test1 = np.zeros((2, 3, 5, 6)) test1[0, 0, :, 2] = 4 test1[0, 1, [2, 4], 1] = 7 test1[0, 2, 2, :] = 2 test1[1, 0, 4, 1:3] = 5 test1[1, :, 0, 1] = 3 and, test2 = np.zeros((5, 6, 4, 7)) test2[2, 2, 2, 4] = 4 test2[0, 1, :, 1] = 3 test2[4, 3, 2, :] = 6 test2[1, 0, 3, 1:3] = 1 test2[3, :, 0, 1] = 2 the calulation I need is: result = test1[..., None, None] * test2[None, None, ...] In the actual use case I am coding for, the tensors can have more dimensions and much longer lengths in some of the dimensions, so while the multiplication is reasonably quick, I would like to utilise the fact that most of the elements are zero. My first thought was to make a sparse representation of each tensor. coords1 = np.nonzero(test1) shape1 = test1.shape test1_squished = test1[coords1] coords1 = np.array(coords1) coords2 = np.nonzero(test2) shape2 = test2.shape test2_squished = test2[coords2] coords2 = np.array(coords2) Here there is enough information to perform the multiplication, by comparing the coordinates along the equal axes and multiplying if they are the same. I have a function for adding a new axis, def new_axis(coords, shape, axis): new_coords = np.zeros((len(coords)+1, len(coords[0]))) new_index = np.delete(np.arange(0, len(coords)+1), axis) new_coords[new_index] = coords coords = new_coords new_shape = np.zeros(len(new_coords), dtype=int) new_shape[new_index] = shape new_shape[axis] = 1 new_shape = np.array(new_shape) return coords, new_shape and for performing the multiplication, def multiply(coords1, shape1, array1, coords2, shape2, array2): #all inputs should be numpy arrays if np.array_equal( shape1, shape2 ): index1 = np.nonzero( ( coords1.T[:, None, :] == coords2.T ).all(-1).any(-1) )[0] index2 = np.nonzero( ( coords2.T[:, None, :] == coords1.T ).all(-1).any(-1) )[0] array = array1[index1] * array2[index2] coords = ( coords1.T[index] ).T shape = shape1 else: if len(shape1) == len(shape2): equal_index = np.nonzero( ( shape1 == shape2 ) )[0] not_equal_index = np.nonzero( ~( shape1 == shape2 ) )[0] if np.logical_or( ( shape1[not_equal_index] == 1 ), ( shape2[not_equal_index] == 1 ) ).all(): #if where not equal, one of them = 1 -> can broadcast # compare dimensions with same length, if equal then multiply corresponding elements multiply_index1 = np.nonzero( ( coords1[equal_index].T[:, None, :] == coords2[equal_index].T ).all(-1).any(-1) )[0] # would like vecotrised version of below array = [] coords = [] for index in multiply_index1: multiply_index2 = np.nonzero( ( (coords2[equal_index]).T == (coords1[equal_index]).T[index] ).all(-1) )[0] array.append( test_squished[index] * test2_squished[multiply_index2] ) temp = np.zeros((6, len(multiply_index2))) temp[not_equal_index] = ((coords1[not_equal_index].T[index]).T + (coords2[not_equal_index].T[multiply_index2])).T if len(multiply_index2)==1: temp[equal_index] = coords1[equal_index].T[index].T[:, None] else: temp[equal_index] = np.repeat( coords1[equal_index].T[index].T[:, None], len(multiply_index2), axis=-1) coords.append(temp) array = np.concatenate(array) coords = np.concatenate(coords, axis=-1) shape = shape1 shape[np.where(shape==1)] = shape2[np.where(shape==1)] else: print("error") else: print("error") return array, coords, shape However the multiply function is very inefficient and so I lose any gain of going to the sparse representation. Is there an elegant vectorised approach to the multiply function? Or is there a better solution than this sparse tensor idea? Thanks in advance. A: SIZE: 5000 DENSITY: 0.01 DEVICE: cpu torch: 0.0306358 seconds np: 0.000252247 seconds torch/np: 121.452 SIZE: 5000 DENSITY: 0.01 DEVICE: cuda torch: 0.0127137 seconds np: 0.000259161 seconds torch/np: 49.057 SIZE: 10000 DENSITY: 0.01 DEVICE: cpu torch: 0.155527 seconds np: 0.00106144 seconds torch/np: 146.524 SIZE: 10000 DENSITY: 0.01 DEVICE: cuda torch: 0.0476248 seconds np: 0.000991583 seconds torch/np: 48.0291 SIZE: 50000 DENSITY: 0.01 DEVICE: cpu torch: 5.94856 seconds np: 0.0456181 seconds torch/np: 130.399 SIZE: 50000 DENSITY: 0.01 DEVICE: cuda torch: 1.06403 seconds np: 0.0419693 seconds torch/np: 25.3527 SIZE: 50000 DENSITY: 0.0001 DEVICE: cpu torch: 0.0423768 seconds np: 0.000562191 seconds torch/np: 75.3779 SIZE: 50000 DENSITY: 0.0001 DEVICE: cuda torch: 0.0175352 seconds np: 0.000589371 seconds torch/np: 29.7524
Speed up multiplication of two dense tensors
I want to perform element wise multiplication between two tensors, where most of the elements are zero. For two example tensors: test1 = np.zeros((2, 3, 5, 6)) test1[0, 0, :, 2] = 4 test1[0, 1, [2, 4], 1] = 7 test1[0, 2, 2, :] = 2 test1[1, 0, 4, 1:3] = 5 test1[1, :, 0, 1] = 3 and, test2 = np.zeros((5, 6, 4, 7)) test2[2, 2, 2, 4] = 4 test2[0, 1, :, 1] = 3 test2[4, 3, 2, :] = 6 test2[1, 0, 3, 1:3] = 1 test2[3, :, 0, 1] = 2 the calulation I need is: result = test1[..., None, None] * test2[None, None, ...] In the actual use case I am coding for, the tensors can have more dimensions and much longer lengths in some of the dimensions, so while the multiplication is reasonably quick, I would like to utilise the fact that most of the elements are zero. My first thought was to make a sparse representation of each tensor. coords1 = np.nonzero(test1) shape1 = test1.shape test1_squished = test1[coords1] coords1 = np.array(coords1) coords2 = np.nonzero(test2) shape2 = test2.shape test2_squished = test2[coords2] coords2 = np.array(coords2) Here there is enough information to perform the multiplication, by comparing the coordinates along the equal axes and multiplying if they are the same. I have a function for adding a new axis, def new_axis(coords, shape, axis): new_coords = np.zeros((len(coords)+1, len(coords[0]))) new_index = np.delete(np.arange(0, len(coords)+1), axis) new_coords[new_index] = coords coords = new_coords new_shape = np.zeros(len(new_coords), dtype=int) new_shape[new_index] = shape new_shape[axis] = 1 new_shape = np.array(new_shape) return coords, new_shape and for performing the multiplication, def multiply(coords1, shape1, array1, coords2, shape2, array2): #all inputs should be numpy arrays if np.array_equal( shape1, shape2 ): index1 = np.nonzero( ( coords1.T[:, None, :] == coords2.T ).all(-1).any(-1) )[0] index2 = np.nonzero( ( coords2.T[:, None, :] == coords1.T ).all(-1).any(-1) )[0] array = array1[index1] * array2[index2] coords = ( coords1.T[index] ).T shape = shape1 else: if len(shape1) == len(shape2): equal_index = np.nonzero( ( shape1 == shape2 ) )[0] not_equal_index = np.nonzero( ~( shape1 == shape2 ) )[0] if np.logical_or( ( shape1[not_equal_index] == 1 ), ( shape2[not_equal_index] == 1 ) ).all(): #if where not equal, one of them = 1 -> can broadcast # compare dimensions with same length, if equal then multiply corresponding elements multiply_index1 = np.nonzero( ( coords1[equal_index].T[:, None, :] == coords2[equal_index].T ).all(-1).any(-1) )[0] # would like vecotrised version of below array = [] coords = [] for index in multiply_index1: multiply_index2 = np.nonzero( ( (coords2[equal_index]).T == (coords1[equal_index]).T[index] ).all(-1) )[0] array.append( test_squished[index] * test2_squished[multiply_index2] ) temp = np.zeros((6, len(multiply_index2))) temp[not_equal_index] = ((coords1[not_equal_index].T[index]).T + (coords2[not_equal_index].T[multiply_index2])).T if len(multiply_index2)==1: temp[equal_index] = coords1[equal_index].T[index].T[:, None] else: temp[equal_index] = np.repeat( coords1[equal_index].T[index].T[:, None], len(multiply_index2), axis=-1) coords.append(temp) array = np.concatenate(array) coords = np.concatenate(coords, axis=-1) shape = shape1 shape[np.where(shape==1)] = shape2[np.where(shape==1)] else: print("error") else: print("error") return array, coords, shape However the multiply function is very inefficient and so I lose any gain of going to the sparse representation. Is there an elegant vectorised approach to the multiply function? Or is there a better solution than this sparse tensor idea? Thanks in advance.
[ "SIZE: 5000 DENSITY: 0.01 DEVICE: cpu\ntorch: 0.0306358 seconds\nnp: 0.000252247 seconds\ntorch/np: 121.452\nSIZE: 5000 DENSITY: 0.01 DEVICE: cuda\ntorch: 0.0127137 seconds\nnp: 0.000259161 seconds\ntorch/np: 49.057\nSIZE: 10000 DENSITY: 0.01 DEVICE: cpu\ntorch: 0.155527 seconds\nnp: 0.00106144 seconds\ntorch/np: 146.524\nSIZE: 10000 DENSITY: 0.01 DEVICE: cuda\ntorch: 0.0476248 seconds\nnp: 0.000991583 seconds\ntorch/np: 48.0291\nSIZE: 50000 DENSITY: 0.01 DEVICE: cpu\ntorch: 5.94856 seconds\nnp: 0.0456181 seconds\ntorch/np: 130.399\nSIZE: 50000 DENSITY: 0.01 DEVICE: cuda\ntorch: 1.06403 seconds\nnp: 0.0419693 seconds\ntorch/np: 25.3527\nSIZE: 50000 DENSITY: 0.0001 DEVICE: cpu\ntorch: 0.0423768 seconds\nnp: 0.000562191 seconds\ntorch/np: 75.3779\nSIZE: 50000 DENSITY: 0.0001 DEVICE: cuda\ntorch: 0.0175352 seconds\nnp: 0.000589371 seconds\ntorch/np: 29.7524\n" ]
[ 0 ]
[]
[]
[ "numpy", "python", "tensor", "vectorization" ]
stackoverflow_0074675872_numpy_python_tensor_vectorization.txt
Q: create a new column that contains a list of values from subsequent rows of partition by ID I have a table like below, and want to create a new column that contains a list of values from another column subsequent rows like below, for copy paste: timestamp ID Value date_time ID s_val 2021-12-03 04:03:45 ID1 O 2021-12-03 04:03:46 ID1 P 2021-12-03 04:03:47 ID1 Q 2021-12-03 04:03:48 ID1 R 2021-12-03 04:03:49 ID1 NULL 2021-12-03 04:03:50 ID1 S 2021-12-03 04:03:51 ID1 T 2021-12-04 11:09:03 ID2 A 2021-12-04 11:09:04 ID2 B 2021-12-04 11:09:05 ID2 C A: Because Snowflake does not support cumulative window frames for LISTAGG, I wrote this one: SELECT m.date_time, m.ID, m.s_val, ( SELECT LISTAGG( s.s_val) FROM mydata s WHERE s.ID= m.ID and s.date_time <= m.date_time ) new_val FROM mydata m order by m.ID, m.date_Time; +---------------------+-----+-------+---------+ | DATE_TIME | ID | S_VAL | NEW_VAL | +---------------------+-----+-------+---------+ | 2021-12-03 40:03:45 | ID1 | O | O | | 2021-12-03 40:03:46 | ID1 | P | OP | | 2021-12-03 40:03:47 | ID1 | Q | OPQ | | 2021-12-03 40:03:48 | ID1 | R | OPQR | | 2021-12-03 40:03:49 | ID1 | NULL | OPQR | | 2021-12-03 40:03:50 | ID1 | S | OPQRS | | 2021-12-03 40:03:51 | ID1 | T | OPQRST | | 2021-12-04 11:09:03 | ID2 | A | A | | 2021-12-04 11:09:04 | ID2 | B | AB | | 2021-12-04 11:09:05 | ID2 | C | ABC | +---------------------+-----+-------+---------+
create a new column that contains a list of values from subsequent rows of partition by ID
I have a table like below, and want to create a new column that contains a list of values from another column subsequent rows like below, for copy paste: timestamp ID Value date_time ID s_val 2021-12-03 04:03:45 ID1 O 2021-12-03 04:03:46 ID1 P 2021-12-03 04:03:47 ID1 Q 2021-12-03 04:03:48 ID1 R 2021-12-03 04:03:49 ID1 NULL 2021-12-03 04:03:50 ID1 S 2021-12-03 04:03:51 ID1 T 2021-12-04 11:09:03 ID2 A 2021-12-04 11:09:04 ID2 B 2021-12-04 11:09:05 ID2 C
[ "Because Snowflake does not support cumulative window frames for LISTAGG, I wrote this one:\nSELECT m.date_time, m.ID, m.s_val, \n ( SELECT LISTAGG( s.s_val) FROM mydata s WHERE s.ID= m.ID and s.date_time <= m.date_time ) new_val\nFROM mydata m\norder by m.ID, m.date_Time;\n\n\n\n+---------------------+-----+-------+---------+\n| DATE_TIME | ID | S_VAL | NEW_VAL |\n+---------------------+-----+-------+---------+\n| 2021-12-03 40:03:45 | ID1 | O | O |\n| 2021-12-03 40:03:46 | ID1 | P | OP |\n| 2021-12-03 40:03:47 | ID1 | Q | OPQ |\n| 2021-12-03 40:03:48 | ID1 | R | OPQR |\n| 2021-12-03 40:03:49 | ID1 | NULL | OPQR |\n| 2021-12-03 40:03:50 | ID1 | S | OPQRS |\n| 2021-12-03 40:03:51 | ID1 | T | OPQRST |\n| 2021-12-04 11:09:03 | ID2 | A | A |\n| 2021-12-04 11:09:04 | ID2 | B | AB |\n| 2021-12-04 11:09:05 | ID2 | C | ABC |\n+---------------------+-----+-------+---------+\n\n" ]
[ 1 ]
[]
[]
[ "snowflake_cloud_data_platform" ]
stackoverflow_0074672694_snowflake_cloud_data_platform.txt
Q: glfwSwapBuffers slow (>3s) I have written a program that does some calculations on a compute shader and the returned data is then being displayed. This works perfectly, except that the program execution is blocked while the shader is running (see code below) and depending on the parameters, this can take a while: void CalculateSomething(GLfloat* Result) { // load some uniform variables glDispatchCompute(X, Y, 1); glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); GLfloat* mapped = (GLfloat*)(glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY)); memcpy(Result, mapped, sizeof(GLfloat) * X * Y); glUnmapBuffer(GL_SHADER_STORAGE_BUFFER); } void main { // Initialization stuff // ... while (glfwWindowShouldClose(Window) == 0) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glfwPollEvents(); glfwSwapInterval(2); // Doesn't matter what I put here CalculatateSomething(Result); Render(Result); glfwSwapBuffers(Window.WindowHandle); } } To keep the main loop running while the compute shader is calculating, I changed CalculateSomething to something like this: void CalculateSomething(GLfloat* Result) { // load some uniform variables glDispatchCompute(X, Y, 1); GPU_sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); } bool GPU_busy() { GLint GPU_status; if (GPU_sync == NULL) return false; else { glGetSynciv(GPU_sync, GL_SYNC_STATUS, 1, nullptr, &GPU_status); return GPU_status == GL_UNSIGNALED; } } These two functions are part of a class and it would get a little messy and complicated if I had to post all that here (if more code is needed, tell me). So every loop when the class is told to do the computation, it first checks, if the GPU is busy. If it's done, the result is copied to CPU-memory (or a calculation is started), else it returns to main without doing anything else. Anyway, this approach works in that it produces the right result. But my main loop is still blocked. Doing some timing revealed that CalculateSomething, Render (and everything else) runs fast (as I would expect them to do). But now glfwSwapBuffers takes >3000ms (depending on how long the calculations of the compute shader take). Shouldn't it be possible to switch buffers while a compute shader is running? Rendering the result seems to work fine and without delay (as long as the compute shader is not done yet, the old result should get rendered). Or am I missing something here (queued OpenGL calls get processed before glfwSwapBuffers does something?)? A: Instead of using a fence sync to check if the GPU is busy, you can use a double buffering technique where you have two sets of output buffer, one that is currently being rendered and another that is being written to by the compute shader. This way, the main loop can continuously swap the front and back buffers while the compute shader is running in the background. Here is some pseudo code to illustrate this approach: // Initialize the front and back buffer GLfloat* front_buffer = (GLfloat*)(glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY)); GLfloat* back_buffer = (GLfloat*)(glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY)); // Update function that is called in the main loop void Update() { // If the compute shader is currently running, do nothing if (compute_shader_running) return; // Swap the front and back buffer std::swap(front_buffer, back_buffer); // Dispatch the compute shader with the new back buffer glDispatchCompute(X, Y, 1); glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); // Set the compute_shader_running flag compute_shader_running = true; } // Render function that is called in the main loop void Render(GLfloat* Result) { // Use the current front buffer to render memcpy(Result, front_buffer, sizeof(GLfloat) * X * Y); // If the compute shader is done running, set the flag to false if (compute_shader_done) compute_shader_running = false; } void main { // Initialization stuff // ... while (glfwWindowShouldClose(Window) == 0) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glfwPollEvents(); glfwSwapInterval(2); Update(); Render(Result); glfwSwapBuffers(Window.WindowHandle); } } Note that this is just one possible solution and you may need to adjust the code depending on your specific requirements. Also, the code above is for illustration purposes only and may not compile as-is.
glfwSwapBuffers slow (>3s)
I have written a program that does some calculations on a compute shader and the returned data is then being displayed. This works perfectly, except that the program execution is blocked while the shader is running (see code below) and depending on the parameters, this can take a while: void CalculateSomething(GLfloat* Result) { // load some uniform variables glDispatchCompute(X, Y, 1); glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); GLfloat* mapped = (GLfloat*)(glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY)); memcpy(Result, mapped, sizeof(GLfloat) * X * Y); glUnmapBuffer(GL_SHADER_STORAGE_BUFFER); } void main { // Initialization stuff // ... while (glfwWindowShouldClose(Window) == 0) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glfwPollEvents(); glfwSwapInterval(2); // Doesn't matter what I put here CalculatateSomething(Result); Render(Result); glfwSwapBuffers(Window.WindowHandle); } } To keep the main loop running while the compute shader is calculating, I changed CalculateSomething to something like this: void CalculateSomething(GLfloat* Result) { // load some uniform variables glDispatchCompute(X, Y, 1); GPU_sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); } bool GPU_busy() { GLint GPU_status; if (GPU_sync == NULL) return false; else { glGetSynciv(GPU_sync, GL_SYNC_STATUS, 1, nullptr, &GPU_status); return GPU_status == GL_UNSIGNALED; } } These two functions are part of a class and it would get a little messy and complicated if I had to post all that here (if more code is needed, tell me). So every loop when the class is told to do the computation, it first checks, if the GPU is busy. If it's done, the result is copied to CPU-memory (or a calculation is started), else it returns to main without doing anything else. Anyway, this approach works in that it produces the right result. But my main loop is still blocked. Doing some timing revealed that CalculateSomething, Render (and everything else) runs fast (as I would expect them to do). But now glfwSwapBuffers takes >3000ms (depending on how long the calculations of the compute shader take). Shouldn't it be possible to switch buffers while a compute shader is running? Rendering the result seems to work fine and without delay (as long as the compute shader is not done yet, the old result should get rendered). Or am I missing something here (queued OpenGL calls get processed before glfwSwapBuffers does something?)?
[ "Instead of using a fence sync to check if the GPU is busy, you can use a double buffering technique where you have two sets of output buffer, one that is currently being rendered and another that is being written to by the compute shader. This way, the main loop can continuously swap the front and back buffers while the compute shader is running in the background.\nHere is some pseudo code to illustrate this approach:\n// Initialize the front and back buffer\nGLfloat* front_buffer = (GLfloat*)(glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY));\nGLfloat* back_buffer = (GLfloat*)(glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY));\n\n// Update function that is called in the main loop\nvoid Update()\n{\n // If the compute shader is currently running, do nothing\n if (compute_shader_running)\n return;\n\n\n // Swap the front and back buffer\n std::swap(front_buffer, back_buffer);\n\n // Dispatch the compute shader with the new back buffer\n glDispatchCompute(X, Y, 1);\n glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);\n\n // Set the compute_shader_running flag\n compute_shader_running = true;\n}\n\n// Render function that is called in the main loop\nvoid Render(GLfloat* Result)\n{\n // Use the current front buffer to render\n memcpy(Result, front_buffer, sizeof(GLfloat) * X * Y);\n\n\n // If the compute shader is done running, set the flag to false\n if (compute_shader_done)\n compute_shader_running = false;\n }\n\nvoid main\n{\n // Initialization stuff\n // ...\n\n\n while (glfwWindowShouldClose(Window) == 0)\n {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glfwPollEvents();\n glfwSwapInterval(2);\n\n Update();\n Render(Result);\n\n glfwSwapBuffers(Window.WindowHandle);\n }\n}\n\nNote that this is just one possible solution and you may need to adjust the code depending on your specific requirements. Also, the code above is for illustration purposes only and may not compile as-is.\n" ]
[ 0 ]
[]
[]
[ "c++", "glfw", "opengl" ]
stackoverflow_0074675744_c++_glfw_opengl.txt
Q: MongoDB : FindOne() return null but the document exist Discord.js V14 I am creating a giveaway system, I use mongo DB with the node module mongoose to store the giveaway data using this code : await DB.create({ GuildID: interaction.guild.id, MessageID: message.id, ChannelID: interaction.channel.id, EndTime: formattedDuration, Ended: false, HostedBy: interaction.user.id, Prize: prize, Winners: winners, Paused: false, Entered: [], }) it create the doc successfully in the database in a separated command I use this code to get the giveaway data also I am sure that the Message ID given is correct const data = await DB.findOne({ GuildID: interaction.guild.id, MessageID: messageId }); console.log(data); But it return null I tried findById() but the same it return null I am using discord.js v14.7.1 & mongoose v6.7.5 & node v18.12.1 A: You might have to wrap the messageId in ObjectId(messageId) if this is a ObjectId in the document const ObjectId = require('mongoose').Types.ObjectId; const data = await DB.findOne({ GuildID: interaction.guild.id, MessageID: ObjectId(messageId) }); console.log(data);
MongoDB : FindOne() return null but the document exist Discord.js V14
I am creating a giveaway system, I use mongo DB with the node module mongoose to store the giveaway data using this code : await DB.create({ GuildID: interaction.guild.id, MessageID: message.id, ChannelID: interaction.channel.id, EndTime: formattedDuration, Ended: false, HostedBy: interaction.user.id, Prize: prize, Winners: winners, Paused: false, Entered: [], }) it create the doc successfully in the database in a separated command I use this code to get the giveaway data also I am sure that the Message ID given is correct const data = await DB.findOne({ GuildID: interaction.guild.id, MessageID: messageId }); console.log(data); But it return null I tried findById() but the same it return null I am using discord.js v14.7.1 & mongoose v6.7.5 & node v18.12.1
[ "You might have to wrap the messageId in ObjectId(messageId) if this is a ObjectId in the document\nconst ObjectId = require('mongoose').Types.ObjectId;\nconst data = await DB.findOne({\n GuildID: interaction.guild.id,\n MessageID: ObjectId(messageId)\n });\n console.log(data);\n\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.js", "javascript", "mongodb", "mongoose" ]
stackoverflow_0074675793_discord_discord.js_javascript_mongodb_mongoose.txt
Q: Seaborn Striplot data visualization not applying colors to markers/bars/strips When creating a stripplot with seaborn, the code creates a striplot perfectly. Applies colors to the legend and all. Except the color is not applying to the various strips in within the stripplot. Appreciate the seaborn/matplotlib experts here, because I am at a loss. Code is below. Picture attached below with my results. import pandas as pd import matplotlib.pyplot as plt import seaborn as sns #set seaborn plotting aesthetics sns.set_style("whitegrid") data = [[2016.0, 0.4862, 0.4115, 0.3905, 0.3483, 0.1196], [2017.0, 0.4471, 0.4096, 0.3725, 0.2866, 0.1387], [2018.0, 0.4748, 0.4016, 0.3381, 0.2905, 0.2012], [2019.0, 0.4705, 0.4247, 0.3857, 0.3333, 0.2457], [2020.0, 0.4755, 0.4196, 0.3971, 0.3825, 0.2965]] # cols = ['attribute_time', '100-81%', '80-61%', '60-41%', '40-21%', '20-0%'] cols = ['attribute_time', '100-81 percentile', '80-61 percentile', '60-41 percentile', '40-21 percentile', '20-0 percentile'] df = pd.DataFrame(data, columns=cols) # Just to get rid of the decimals. df['attribute_time'] = df['attribute_time'].astype('int') print(df) df.columns = ['attribute_time', '100-81 percentile', '80-61 percentile', '60-41 percentile', '40-21 percentile', '20-0 percentile'] df = df.melt(id_vars = ['attribute_time'], value_name = 'pct_value', var_name = 'pct_range') print(df.head(20)) print(df['pct_range'].unique()) # # Create a dictionary mapping subgroup values to colors palette_colors = dict(zip(list(df['pct_range'].unique()), ['blue', 'orange', 'green', 'red', 'purple'])) print(palette_colors) fig, ax = plt.subplots() for year, value in zip(df['attribute_time'],df['pct_value']): ax.text(year - 2016, value, str(value), ha = 'center', va = 'bottom', fontsize = 'small',) sns.stripplot( data = df, x = 'attribute_time', y = 'pct_value', hue = 'pct_range', palette=palette_colors, jitter = False, marker = '_', size = 25, linewidth = 2, ax = ax ).legend(fontsize=7) plt.show() A: Matplotlib has two types of markers. Most are filled (e.g. as circle with a border). Some are unfilled (e.g. a horizontal line). Seaborn uses the hue color only for the interior, and uses a fixed color (default black) for the borders (edges). If I try to run your code, I get a warning from matplotlib complaining that a face color is given for unfilled markers. You can simply put edgecolor='face' to give the face color to the edges. (Matplotlib still gives the same warning, but does color the markers via the hue color.) import matplotlib.pyplot as plt import seaborn as sns import pandas as pd # set seaborn plotting aesthetics sns.set_style("whitegrid") data = [[2016.0, 0.4862, 0.4115, 0.3905, 0.3483, 0.1196], [2017.0, 0.4471, 0.4096, 0.3725, 0.2866, 0.1387], [2018.0, 0.4748, 0.4016, 0.3381, 0.2905, 0.2012], [2019.0, 0.4705, 0.4247, 0.3857, 0.3333, 0.2457], [2020.0, 0.4755, 0.4196, 0.3971, 0.3825, 0.2965]] cols = ['attribute_time', '100-81 percentile', '80-61 percentile', '60-41 percentile', '40-21 percentile', '20-0 percentile'] df = pd.DataFrame(data, columns=cols) # Just to get rid of the decimals. df['attribute_time'] = df['attribute_time'].astype('int') df_long = df.melt(id_vars=['attribute_time'], value_name='pct_value', var_name='pct_range') # Create a dictionary mapping subgroup values to colors palette_colors = dict(zip(list(df_long['pct_range'].unique()), plt.cm.get_cmap('Set1').colors)) fig, ax = plt.subplots() for year, value in zip(df_long['attribute_time'], df_long['pct_value']): ax.text(year - 2016, value, str(value), ha='center', va='bottom', fontsize='small', ) sns.stripplot(data=df_long, x='attribute_time', y='pct_value', hue='pct_range', palette=palette_colors, jitter=False, marker='_', size=25, linewidth=2, edgecolor='face', ax=ax) ax.legend(fontsize=7) plt.show()
Seaborn Striplot data visualization not applying colors to markers/bars/strips
When creating a stripplot with seaborn, the code creates a striplot perfectly. Applies colors to the legend and all. Except the color is not applying to the various strips in within the stripplot. Appreciate the seaborn/matplotlib experts here, because I am at a loss. Code is below. Picture attached below with my results. import pandas as pd import matplotlib.pyplot as plt import seaborn as sns #set seaborn plotting aesthetics sns.set_style("whitegrid") data = [[2016.0, 0.4862, 0.4115, 0.3905, 0.3483, 0.1196], [2017.0, 0.4471, 0.4096, 0.3725, 0.2866, 0.1387], [2018.0, 0.4748, 0.4016, 0.3381, 0.2905, 0.2012], [2019.0, 0.4705, 0.4247, 0.3857, 0.3333, 0.2457], [2020.0, 0.4755, 0.4196, 0.3971, 0.3825, 0.2965]] # cols = ['attribute_time', '100-81%', '80-61%', '60-41%', '40-21%', '20-0%'] cols = ['attribute_time', '100-81 percentile', '80-61 percentile', '60-41 percentile', '40-21 percentile', '20-0 percentile'] df = pd.DataFrame(data, columns=cols) # Just to get rid of the decimals. df['attribute_time'] = df['attribute_time'].astype('int') print(df) df.columns = ['attribute_time', '100-81 percentile', '80-61 percentile', '60-41 percentile', '40-21 percentile', '20-0 percentile'] df = df.melt(id_vars = ['attribute_time'], value_name = 'pct_value', var_name = 'pct_range') print(df.head(20)) print(df['pct_range'].unique()) # # Create a dictionary mapping subgroup values to colors palette_colors = dict(zip(list(df['pct_range'].unique()), ['blue', 'orange', 'green', 'red', 'purple'])) print(palette_colors) fig, ax = plt.subplots() for year, value in zip(df['attribute_time'],df['pct_value']): ax.text(year - 2016, value, str(value), ha = 'center', va = 'bottom', fontsize = 'small',) sns.stripplot( data = df, x = 'attribute_time', y = 'pct_value', hue = 'pct_range', palette=palette_colors, jitter = False, marker = '_', size = 25, linewidth = 2, ax = ax ).legend(fontsize=7) plt.show()
[ "Matplotlib has two types of markers. Most are filled (e.g. as circle with a border). Some are unfilled (e.g. a horizontal line).\nSeaborn uses the hue color only for the interior, and uses a fixed color (default black) for the borders (edges). If I try to run your code, I get a warning from matplotlib complaining that a face color is given for unfilled markers. You can simply put edgecolor='face' to give the face color to the edges. (Matplotlib still gives the same warning, but does color the markers via the hue color.)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\n# set seaborn plotting aesthetics\nsns.set_style(\"whitegrid\")\n\ndata = [[2016.0, 0.4862, 0.4115, 0.3905, 0.3483, 0.1196],\n [2017.0, 0.4471, 0.4096, 0.3725, 0.2866, 0.1387],\n [2018.0, 0.4748, 0.4016, 0.3381, 0.2905, 0.2012],\n [2019.0, 0.4705, 0.4247, 0.3857, 0.3333, 0.2457],\n [2020.0, 0.4755, 0.4196, 0.3971, 0.3825, 0.2965]]\ncols = ['attribute_time', '100-81 percentile', '80-61 percentile', '60-41 percentile', '40-21 percentile', '20-0 percentile']\n\ndf = pd.DataFrame(data, columns=cols)\n# Just to get rid of the decimals.\ndf['attribute_time'] = df['attribute_time'].astype('int')\ndf_long = df.melt(id_vars=['attribute_time'],\n value_name='pct_value',\n var_name='pct_range')\n# Create a dictionary mapping subgroup values to colors\npalette_colors = dict(zip(list(df_long['pct_range'].unique()), plt.cm.get_cmap('Set1').colors))\n\nfig, ax = plt.subplots()\n\nfor year, value in zip(df_long['attribute_time'], df_long['pct_value']):\n ax.text(year - 2016, value, str(value), ha='center', va='bottom', fontsize='small', )\n\nsns.stripplot(data=df_long,\n x='attribute_time',\n y='pct_value',\n hue='pct_range',\n palette=palette_colors,\n jitter=False,\n marker='_',\n size=25,\n linewidth=2,\n edgecolor='face',\n ax=ax)\nax.legend(fontsize=7)\n\nplt.show()\n\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python", "seaborn", "visualization" ]
stackoverflow_0074672393_matplotlib_python_seaborn_visualization.txt
Q: Class not getting called in WSO2 API in MicroIntegrator I am trying to call class from a WSO2 API. I have copied the JAR file of class mediator project to <MI_HOME>/lib. However, I am still getting this error: Error loading class : com.test.mediator.ChangeValue - Class not found java.lang.ClassNotFoundException: com.test.mediator.ChangeValue cannot be found by synapse-core_2.1.7.wso2v182 For a little better understanding calling class in sequence is as follows: <class name="com.test.mediator.ChangeValue"/> <log level="custom"> <property name="After CLASS" value="in Seq"/> <property expression="$ctx:NameN" name="NameClass"/> </log> For class, the class definition is as follows: package com.test.mediator; import org.apache.synapse.MessageContext; import org.apache.synapse.mediators.AbstractMediator; public class ChangeValue extends AbstractMediator { public boolean mediate(MessageContext context) { // TODO Implement your mediation logic here changeVal(context); return true; } public void changeVal(MessageContext context) { String Namem = (String) context.getProperty("NAMEE"); String Namen = "Hary"; context.setProperty("NameN", Namen); } } Why is this error showing up? A: This error indicated the MI is unable to load the custom class during the run time. Follow the below steps and try it out. Stop the server if already running. Remove the class mediator from MI/dropins and MI/lib folders. In the custom mediator project check the pom.xml file to check the packaging type. (There should be a tag <packaging>bundle/jar</packaging>). If pom contains <packaging>bundle</packaging>, copy the jar to MI/dropins directly. If pom does not contains tag or contains packaging with value jar as <packaging>jar</packaging> copy the mediator jar to MI/lib folder. Restart the server and try out.
Class not getting called in WSO2 API in MicroIntegrator
I am trying to call class from a WSO2 API. I have copied the JAR file of class mediator project to <MI_HOME>/lib. However, I am still getting this error: Error loading class : com.test.mediator.ChangeValue - Class not found java.lang.ClassNotFoundException: com.test.mediator.ChangeValue cannot be found by synapse-core_2.1.7.wso2v182 For a little better understanding calling class in sequence is as follows: <class name="com.test.mediator.ChangeValue"/> <log level="custom"> <property name="After CLASS" value="in Seq"/> <property expression="$ctx:NameN" name="NameClass"/> </log> For class, the class definition is as follows: package com.test.mediator; import org.apache.synapse.MessageContext; import org.apache.synapse.mediators.AbstractMediator; public class ChangeValue extends AbstractMediator { public boolean mediate(MessageContext context) { // TODO Implement your mediation logic here changeVal(context); return true; } public void changeVal(MessageContext context) { String Namem = (String) context.getProperty("NAMEE"); String Namen = "Hary"; context.setProperty("NameN", Namen); } } Why is this error showing up?
[ "This error indicated the MI is unable to load the custom class during the run time. Follow the below steps and try it out.\n\nStop the server if already running.\nRemove the class mediator from MI/dropins and MI/lib folders.\nIn the custom mediator project check the pom.xml file to check the packaging type. (There should be a tag <packaging>bundle/jar</packaging>).\nIf pom contains <packaging>bundle</packaging>, copy the jar to MI/dropins directly. If pom does not contains tag or contains packaging with value jar as <packaging>jar</packaging> copy the mediator jar to MI/lib folder.\nRestart the server and try out.\n\n" ]
[ 0 ]
[]
[]
[ "api", "class", "java", "wso2", "wso2_enterprise_integrator" ]
stackoverflow_0074662885_api_class_java_wso2_wso2_enterprise_integrator.txt
Q: How to see only uploaded users in laravel? I want to ask, how do I upload a file to the web on user 1 but only attach it to user 1, whereas currently it is also attached to user 2, my coding is wrong. like the example image below: Images Web If you look at the picture, if it has been uploaded, change it to Submitted status in the "Bahasa Indonesia" SUBJECT, but for user 2 it hasn't been uploaded, but it has also become Submitted, user 2's status must be Waiting because it hasn't been uploaded yet. And here is attached my mysql uploaded on user 1: Images MySqli AssignmentStudentController public function DataAssignment(){ $userAssignments = Assignment::join('subjects', 'assignments.id_subject', '=', 'subjects.id_sub') ->join('class_infos', 'subjects.id_class', '=', 'class_infos.id') ->join('class_details', 'class_infos.id', '=', 'class_details.id_class') ->where('class_details.id_user', '=', Auth::user()->id) ->get(); return view('student.assignment.data_assignment', compact('userAssignments')); } AssignmentStudentController.php <table class="w-full text-sm text-left text-gray-500 dark:text-gray-400"> <thead class="text-xs text-white uppercase bg-[#464867] dark:bg-[#464867]"> <tr> <th scope="col" class="py-3 px-6"> Subject </th> <th scope="col" class="py-3 px-6"> Title </th> <th scope="col" class="py-3 px-6"> Due Date </th> <th scope="col" class="py-3 px-6"> Submission Date </th> <th scope="col" class="py-3 px-6"> Status </th> <th scope="col" class="py-3 px-6"> Score </th> <th scope="col" class="py-3 px-6"> Action </th> </tr> </thead> <tbody> @forelse($userAssignments as $data) <tr class="bg-white border-b dark:bg-gray-900 dark:border-gray-700"> <th scope="row" class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{$data->subjects->name_subject}} </th> <td class="w-24 px-6 py-4 text-sm font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{$data->title}} </td> <td class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{ date('d M Y - H:m', strtotime($data->due_date)) }} WIB </td> <td class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{ (!empty($data->assignments->id_student)) ? date('d M Y - H:m' ,strtotime($data->assignments->updated_at)):'Not uploaded yet' }} </td> <td class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{ (!empty($data->assignments->id_student)) ? 'Submitted':'Waiting' }} </td> <td class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{ (!empty($data->assignments->id_student)) ? ($data->assignments->score) ? $data->assignments->score :'Process':'0' }} </td> <td class="py-4 px-6 flex font-medium text-gray-900 whitespace-nowrap dark:text-white"> @if(!empty( $data->assignments->id_student)) <a href="{{ (!empty($data->assignments->file_assignment))? url('upload/assignment/students/'.$data->assignments->file_assignment):''}}" download> <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clip-rule="evenodd"></path> </svg> </a> @else @endif <a type="button" data-modal-toggle="{{route('input.assignment', $data->id_id)}}"> <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M6 2a2 2 0 00-2 2v12a2 2 0 002 2h8a2 2 0 002-2V7.414A2 2 0 0015.414 6L12 2.586A2 2 0 0010.586 2H6zm5 6a1 1 0 10-2 0v2H7a1 1 0 100 2h2v2a1 1 0 102 0v-2h2a1 1 0 100-2h-2V8z" clip-rule="evenodd"></path> </svg> </a> <a href="{{ (!empty($data->file_asg))? url('upload/assignment/question/'.$data->file_asg):url('images/no_image.jpg') }}" download> <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M6 2a2 2 0 00-2 2v12a2 2 0 002 2h8a2 2 0 002-2V7.414A2 2 0 0015.414 6L12 2.586A2 2 0 0010.586 2H6zm5 6a1 1 0 10-2 0v3.586l-1.293-1.293a1 1 0 10-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 11.586V8z" clip-rule="evenodd"></path> </svg> </a> </td> </tr> @empty <tr colspan = "7" class="bg-white border-b dark:bg-gray-900 dark:border-gray-700"> <td class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> No Data </td> </tr> @endforelse </tbody> </table> A: You can check by defining a new method in addition to the assignments method in your model: class Assignment extends Model { public function assignments() { return $this->hasMany(<YOUR_ASSIGNMENTS_TABLE_NAME>::class, 'id_assignment', 'id_id'); } // new method public function checkStudentAssignmentIsNull() { return $this->hasMany(<YOUR_ASSIGNMENTS_TABLE_NAME>::class, 'id_assignment', 'id_id') ->where('<YOUR_ASSIGNMENTS_TABLE_NAME>.id_student', Auth::user()->id) ->first() === null; } } And when using, you can do !$data->checkStudentAssignmentIsNull() instead of !empty($data->assignments->id_student). I see your tables more clearly now: // new method public function checkStudentAssignmentIsNull() { return $this->hasMany(AssignmentDetail::class, 'id_assignment', 'id_id') ->where('assignment_details.id_student', Auth::user()->id) ->first() === null; }
How to see only uploaded users in laravel?
I want to ask, how do I upload a file to the web on user 1 but only attach it to user 1, whereas currently it is also attached to user 2, my coding is wrong. like the example image below: Images Web If you look at the picture, if it has been uploaded, change it to Submitted status in the "Bahasa Indonesia" SUBJECT, but for user 2 it hasn't been uploaded, but it has also become Submitted, user 2's status must be Waiting because it hasn't been uploaded yet. And here is attached my mysql uploaded on user 1: Images MySqli AssignmentStudentController public function DataAssignment(){ $userAssignments = Assignment::join('subjects', 'assignments.id_subject', '=', 'subjects.id_sub') ->join('class_infos', 'subjects.id_class', '=', 'class_infos.id') ->join('class_details', 'class_infos.id', '=', 'class_details.id_class') ->where('class_details.id_user', '=', Auth::user()->id) ->get(); return view('student.assignment.data_assignment', compact('userAssignments')); } AssignmentStudentController.php <table class="w-full text-sm text-left text-gray-500 dark:text-gray-400"> <thead class="text-xs text-white uppercase bg-[#464867] dark:bg-[#464867]"> <tr> <th scope="col" class="py-3 px-6"> Subject </th> <th scope="col" class="py-3 px-6"> Title </th> <th scope="col" class="py-3 px-6"> Due Date </th> <th scope="col" class="py-3 px-6"> Submission Date </th> <th scope="col" class="py-3 px-6"> Status </th> <th scope="col" class="py-3 px-6"> Score </th> <th scope="col" class="py-3 px-6"> Action </th> </tr> </thead> <tbody> @forelse($userAssignments as $data) <tr class="bg-white border-b dark:bg-gray-900 dark:border-gray-700"> <th scope="row" class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{$data->subjects->name_subject}} </th> <td class="w-24 px-6 py-4 text-sm font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{$data->title}} </td> <td class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{ date('d M Y - H:m', strtotime($data->due_date)) }} WIB </td> <td class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{ (!empty($data->assignments->id_student)) ? date('d M Y - H:m' ,strtotime($data->assignments->updated_at)):'Not uploaded yet' }} </td> <td class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{ (!empty($data->assignments->id_student)) ? 'Submitted':'Waiting' }} </td> <td class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> {{ (!empty($data->assignments->id_student)) ? ($data->assignments->score) ? $data->assignments->score :'Process':'0' }} </td> <td class="py-4 px-6 flex font-medium text-gray-900 whitespace-nowrap dark:text-white"> @if(!empty( $data->assignments->id_student)) <a href="{{ (!empty($data->assignments->file_assignment))? url('upload/assignment/students/'.$data->assignments->file_assignment):''}}" download> <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clip-rule="evenodd"></path> </svg> </a> @else @endif <a type="button" data-modal-toggle="{{route('input.assignment', $data->id_id)}}"> <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M6 2a2 2 0 00-2 2v12a2 2 0 002 2h8a2 2 0 002-2V7.414A2 2 0 0015.414 6L12 2.586A2 2 0 0010.586 2H6zm5 6a1 1 0 10-2 0v2H7a1 1 0 100 2h2v2a1 1 0 102 0v-2h2a1 1 0 100-2h-2V8z" clip-rule="evenodd"></path> </svg> </a> <a href="{{ (!empty($data->file_asg))? url('upload/assignment/question/'.$data->file_asg):url('images/no_image.jpg') }}" download> <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10" viewBox="0 0 20 20" fill="currentColor"> <path fill-rule="evenodd" d="M6 2a2 2 0 00-2 2v12a2 2 0 002 2h8a2 2 0 002-2V7.414A2 2 0 0015.414 6L12 2.586A2 2 0 0010.586 2H6zm5 6a1 1 0 10-2 0v3.586l-1.293-1.293a1 1 0 10-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 11.586V8z" clip-rule="evenodd"></path> </svg> </a> </td> </tr> @empty <tr colspan = "7" class="bg-white border-b dark:bg-gray-900 dark:border-gray-700"> <td class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"> No Data </td> </tr> @endforelse </tbody> </table>
[ "You can check by defining a new method in addition to the assignments method in your model:\nclass Assignment extends Model\n{\n public function assignments()\n {\n return $this->hasMany(<YOUR_ASSIGNMENTS_TABLE_NAME>::class, 'id_assignment', 'id_id');\n }\n\n // new method\n public function checkStudentAssignmentIsNull()\n {\n return $this->hasMany(<YOUR_ASSIGNMENTS_TABLE_NAME>::class, 'id_assignment', 'id_id')\n ->where('<YOUR_ASSIGNMENTS_TABLE_NAME>.id_student', Auth::user()->id)\n ->first() === null;\n }\n}\n\nAnd when using, you can do !$data->checkStudentAssignmentIsNull() instead of !empty($data->assignments->id_student).\n\nI see your tables more clearly now:\n// new method\npublic function checkStudentAssignmentIsNull()\n{\n return $this->hasMany(AssignmentDetail::class, 'id_assignment', 'id_id')\n ->where('assignment_details.id_student', Auth::user()->id)\n ->first() === null;\n}\n\n" ]
[ 0 ]
[]
[]
[ "is_empty", "laravel", "laravel_9", "mysql" ]
stackoverflow_0074675540_is_empty_laravel_laravel_9_mysql.txt
Q: Speed Up Keras Model Prediction Trying to detect emotion using Keras and grabbing the desktop with mss and them display back to the OpenCV Window. The keras model size is 360 mb. import time import cv2 import mss import numpy as np face_cascade = cv2.CascadeClassifier('face.xml') label = ["angry", "happy", "sad", "stress"] monitor = {"top": 0, "left": 0, "width": 1000, "height": 1000} with mss.mss() as sct: # Part of the screen to capture while "Screen capturing": # Get raw pixels from the screen, save it to a Numpy array img = np.array(sct.grab(monitor)) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 255), 2) roi_gray = gray[y:y+h,x:x+w] roi_gray = cv2.resize(roi_gray,(48,48),interpolation=cv2.INTER_AREA) roi = roi_gray.reshape(1, 48, 48, 1) prediction = model.predict(roi) t = label[prediction.argmax()] label_position = (x,y) cv2.putText(img,t,label_position,cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2) # Display the picture cv2.imshow("OpenCV/Numpy normal", img) #print("fps: {}".format(1 / (time.time() - last_time))) # Press "q" to quit if cv2.waitKey(25) & 0xFF == ord("q"): cv2.destroyAllWindows() break Is there any way to speed up this process or is it hardware bound? A: There are a few ways to potentially speed up this process: Use a smaller model: 360mb is quite large for a Keras model, so using a smaller model with fewer layers and parameters may improve performance. Use a faster hardware: The speed of this process is likely hardware-bound, so using a faster CPU or GPU may improve performance. Optimize the code: There may be ways to optimize the code, such as using optimized functions for image processing, using threading or multiprocessing, or using a more efficient data structure for storing and processing the data. Reduce the number of frames processed: Instead of processing every frame from the screen capture, you could skip some frames to reduce the workload. This may result in a lower frame rate, but may improve performance.
Speed Up Keras Model Prediction
Trying to detect emotion using Keras and grabbing the desktop with mss and them display back to the OpenCV Window. The keras model size is 360 mb. import time import cv2 import mss import numpy as np face_cascade = cv2.CascadeClassifier('face.xml') label = ["angry", "happy", "sad", "stress"] monitor = {"top": 0, "left": 0, "width": 1000, "height": 1000} with mss.mss() as sct: # Part of the screen to capture while "Screen capturing": # Get raw pixels from the screen, save it to a Numpy array img = np.array(sct.grab(monitor)) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 255), 2) roi_gray = gray[y:y+h,x:x+w] roi_gray = cv2.resize(roi_gray,(48,48),interpolation=cv2.INTER_AREA) roi = roi_gray.reshape(1, 48, 48, 1) prediction = model.predict(roi) t = label[prediction.argmax()] label_position = (x,y) cv2.putText(img,t,label_position,cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2) # Display the picture cv2.imshow("OpenCV/Numpy normal", img) #print("fps: {}".format(1 / (time.time() - last_time))) # Press "q" to quit if cv2.waitKey(25) & 0xFF == ord("q"): cv2.destroyAllWindows() break Is there any way to speed up this process or is it hardware bound?
[ "There are a few ways to potentially speed up this process:\nUse a smaller model: 360mb is quite large for a Keras model, so using a smaller model with fewer layers and parameters may improve performance.\nUse a faster hardware: The speed of this process is likely hardware-bound, so using a faster CPU or GPU may improve performance.\nOptimize the code: There may be ways to optimize the code, such as using optimized functions for image processing, using threading or multiprocessing, or using a more efficient data structure for storing and processing the data.\nReduce the number of frames processed: Instead of processing every frame from the screen capture, you could skip some frames to reduce the workload. This may result in a lower frame rate, but may improve performance.\n" ]
[ 1 ]
[]
[]
[ "keras", "opencv", "python" ]
stackoverflow_0074675873_keras_opencv_python.txt
Q: Operator and Pointer precedence Below is the problem I found on the internet. int main() { int a[4] = { 10, 21, 32, 43}; int *p = a + 3; ++*--p; ++*p--; p[2] += p[1]; for (int i = 0; i < 4; ++i) printf("%d - %d\t", a[i]); return 0; } //What will be the output? answer : 10 21 34 77 I understood a lot of things, but the only thing I'm stuck on: What is the difference between (++*--p) and (++*p--) ? Shouldn't these two give the same result? Because (*p--) and (*--p) give the same result in the compiler. The compiler I use is Code::Blocks A: Because (*p--) and (*--p) give the same result in the compiler. No, they do not. *p-- decrements p but applies * to the value of p before the decrement. *--p applies * to the value of p after the decrement. What is the difference between (++*--p) and (++*p--) ? ++*--p decrements p and increments the object it points to after the decrement. ++*p-- decrements p but increments the object it points to before the decrement. A: What is the difference between (++*--p) and (++*p--) ? The difference is that --p decrements p and resolves to the new value of p, whereas p-- decrements p and resolves to the old value of p. ++* works identically on both - performing indirection on p, incrementing the value p points to, and resolving to this new value. #include <stdio.h> int main(void) { int a = 10; int b = 10; /* This prints 9, and `a` is now 9 */ printf("%d\n", --a); /* This prints 10, and `b` is now 9 */ printf("%d\n", b--); /* This prints 9 and 9 */ printf("%d %d\n", a, b); } Shouldn't these two give the same result? Because (*p--) and (*--p) give the same result in the compiler. The order here matters, using (*--p) before (*p--) would resolve to the same element twice. Using (*p--) before (*--p) resolves to different elements. #include <stdio.h> int main(void) { int a[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int *p = a + 4; /* 4 then 4 */ printf("%d ", *--p); printf("%d\n", *p--); p = a + 4; /* 5 then 3 */ printf("%d ", *p--); printf("%d\n", *--p); }
Operator and Pointer precedence
Below is the problem I found on the internet. int main() { int a[4] = { 10, 21, 32, 43}; int *p = a + 3; ++*--p; ++*p--; p[2] += p[1]; for (int i = 0; i < 4; ++i) printf("%d - %d\t", a[i]); return 0; } //What will be the output? answer : 10 21 34 77 I understood a lot of things, but the only thing I'm stuck on: What is the difference between (++*--p) and (++*p--) ? Shouldn't these two give the same result? Because (*p--) and (*--p) give the same result in the compiler. The compiler I use is Code::Blocks
[ "\nBecause (*p--) and (*--p) give the same result in the compiler.\n\nNo, they do not. *p-- decrements p but applies * to the value of p before the decrement. *--p applies * to the value of p after the decrement.\n\nWhat is the difference between (++*--p) and (++*p--) ?\n\n++*--p decrements p and increments the object it points to after the decrement.\n++*p-- decrements p but increments the object it points to before the decrement.\n", "\nWhat is the difference between (++*--p) and (++*p--) ?\n\nThe difference is that --p decrements p and resolves to the new value of p, whereas p-- decrements p and resolves to the old value of p.\n++* works identically on both - performing indirection on p, incrementing the value p points to, and resolving to this new value.\n#include <stdio.h>\n\nint main(void)\n{ \n int a = 10; \n int b = 10; \n \n /* This prints 9, and `a` is now 9 */\n printf(\"%d\\n\", --a);\n /* This prints 10, and `b` is now 9 */\n printf(\"%d\\n\", b--);\n \n /* This prints 9 and 9 */\n printf(\"%d %d\\n\", a, b);\n}\n\n\nShouldn't these two give the same result? Because (*p--) and (*--p) give the same result in the compiler.\n\nThe order here matters, using (*--p) before (*p--) would resolve to the same element twice. Using (*p--) before (*--p) resolves to different elements.\n#include <stdio.h>\n\nint main(void)\n{\n int a[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };\n int *p = a + 4;\n \n /* 4 then 4 */\n printf(\"%d \", *--p);\n printf(\"%d\\n\", *p--);\n \n p = a + 4;\n /* 5 then 3 */\n printf(\"%d \", *p--);\n printf(\"%d\\n\", *--p);\n \n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "c", "pointers" ]
stackoverflow_0074675713_c_pointers.txt
Q: Where to find Status details for SSIS execution id in SSIS I have created an SSIS Package and deployed it on Server. While execution of Package i can see the report of Execution. i want to know that in which table SSIS execution id's information is stored? like if execution id= 2 that means packge is running when 4 that means failed when 7 that means success. i want to know all status ID's details. I thing there would be a table in ssis db where information would be saved against the status id. can some body help me> A: Status is saved in the View [SSISDB].[catalog].[executions] and the table underneath is [SSISDB].[internal].[operations] . The details of Status can be found here: https://learn.microsoft.com/en-us/sql/integration-services/system-views/catalog-executions-ssisdb-database status int The status of the operation. The possible values are created (1), running (2), canceled (3), failed (4), pending (5), ended unexpectedly (6), succeeded (7), stopping (8), and completed (9). If you need a dimension table for Status I think you have to create one yourself , it should be pretty easy from official documents. Here is full list of the official docs: https://learn.microsoft.com/en-us/sql/integration-services/system-views/views-integration-services-catalog This section describes the Transact-SQL views that are available for administering Integration Services projects that have been deployed to an instance of SQL Server. Query the Integration Services views to inspect objects, settings, and operational data that are stored in the SSISDB catalog. The default name of the catalog is SSISDB. The objects that are stored in the catalog include projects, packages, parameters, environments, and operational history. You can use the database views and stored procedures directly, or write custom code that calls the managed API. Management Studio and the managed API query the views and call the stored procedures that are described in this section to perform many of their tasks. In This Section catalog.catalog_properties (SSISDB Database) Displays the properties of the Integration Services catalog. catalog.effective_object_permissions (SSISDB Database) Displays the effective permissions for the current principal for all objects in the Integration Services catalog. catalog.environment_variables (SSISDB Database) Displays the environment variable details for all environments in the Integration Services catalog. catalog.environments (SSISDB Database) Displays the environment details for all environments in the Integration Services catalog. Environments contain variables that can be referenced by Integration Services projects. catalog.execution_parameter_values (SSISDB Database) Displays the actual parameter values that are used by Integration Services packages during an instance of execution. catalog.executions (SSISDB Database) Displays the instances of package execution in the Integration Services catalog. Packages that are executed with the Execute Package task run in the same instance of execution as the parent package. catalog.explicit_object_permissions (SSISDB Database) Displays only the permissions that have been explicitly assigned to the user. catalog.extended_operation_info (SSISDB Database) Displays extended information for all operations in the Integration Services catalog. catalog.folders (SSISDB Database) Displays the folders in the Integration Services catalog. catalog.object_parameters (SSISDB Database) Displays the parameters for all packages and projects in the Integration Services catalog. catalog.object_versions (SSISDB Database) Displays the versions of objects in the Integration Services catalog. In this release, only versions of projects are supported in this view. catalog.operation_messages (SSISDB Database) Displays messages that are logged during operations in the Integration Services catalog. catalog.operations (SSISDB Database) Displays the details of all operations in the Integration Services catalog. catalog.packages (SSISDB Database) Displays the details for all packages that appear in the Integration Services catalog. catalog.environment_references (SSISDB Database) Displays the environment references for all projects in the Integration Services [catalog][] catalog.projects (SSISDB Database) Displays the details for all projects that appear in the Integration Services catalog. catalog.validations (SSISDB Database) Displays the details of all project and package validations in the Integration Services catalog. catalog.master_properties (SSISDB Database) Displays the properties of the Integration Services Scale Out Master. catalog.worker_agents (SSISDB Database) Displays the information of Integration Services Scale Out Worker. A: Execution id, i.e. operation id is used to identify the operation. In my opinion this is very confusing, but you can see it from the structure of the catalog.executions view. from operations view you can get messages, from executions - packages.
Where to find Status details for SSIS execution id in SSIS
I have created an SSIS Package and deployed it on Server. While execution of Package i can see the report of Execution. i want to know that in which table SSIS execution id's information is stored? like if execution id= 2 that means packge is running when 4 that means failed when 7 that means success. i want to know all status ID's details. I thing there would be a table in ssis db where information would be saved against the status id. can some body help me>
[ "Status is saved in the View [SSISDB].[catalog].[executions] and the table underneath is [SSISDB].[internal].[operations] .\nThe details of Status can be found here:\nhttps://learn.microsoft.com/en-us/sql/integration-services/system-views/catalog-executions-ssisdb-database\n\nstatus int\nThe status of the operation. The possible values are\ncreated (1), running (2), canceled (3), failed (4), pending (5), ended\nunexpectedly (6), succeeded (7), stopping (8), and completed (9).\n\nIf you need a dimension table for Status I think you have to create one yourself , it should be pretty easy from official documents.\nHere is full list of the official docs:\nhttps://learn.microsoft.com/en-us/sql/integration-services/system-views/views-integration-services-catalog\n\nThis section describes the Transact-SQL views that are available for\nadministering Integration Services projects that have been deployed to\nan instance of SQL Server.\nQuery the Integration Services views to inspect objects, settings, and\noperational data that are stored in the SSISDB catalog.\nThe default name of the catalog is SSISDB. The objects that are stored\nin the catalog include projects, packages, parameters, environments,\nand operational history.\nYou can use the database views and stored procedures directly, or\nwrite custom code that calls the managed API. Management Studio and\nthe managed API query the views and call the stored procedures that\nare described in this section to perform many of their tasks.\nIn This Section\ncatalog.catalog_properties (SSISDB Database)\nDisplays the properties of the Integration Services catalog.\ncatalog.effective_object_permissions (SSISDB Database)\nDisplays the effective permissions for the current principal for all objects in the\nIntegration Services catalog.\ncatalog.environment_variables (SSISDB Database)\nDisplays the environment variable details for all environments in the Integration\nServices catalog.\ncatalog.environments (SSISDB Database)\nDisplays the environment details for all environments in the Integration Services catalog.\nEnvironments contain variables that can be referenced by Integration\nServices projects.\ncatalog.execution_parameter_values (SSISDB Database)\nDisplays the actual parameter values that are used by Integration Services packages\nduring an instance of execution.\ncatalog.executions (SSISDB Database)\nDisplays the instances of package execution in the Integration Services catalog. Packages that are\nexecuted with the Execute Package task run in the same instance of\nexecution as the parent package.\ncatalog.explicit_object_permissions (SSISDB Database)\nDisplays only the permissions that have been explicitly assigned to the user.\ncatalog.extended_operation_info (SSISDB Database)\nDisplays extended information for all operations in the Integration Services catalog.\ncatalog.folders (SSISDB Database)\nDisplays the folders in the Integration Services catalog.\ncatalog.object_parameters (SSISDB Database)\nDisplays the parameters for all packages and projects in the Integration Services catalog.\ncatalog.object_versions (SSISDB Database)\nDisplays the versions of objects in the Integration Services catalog. In this release, only\nversions of projects are supported in this view.\ncatalog.operation_messages (SSISDB Database)\nDisplays messages that are logged during operations in the Integration Services catalog.\ncatalog.operations (SSISDB Database)\nDisplays the details of all operations in the Integration Services catalog.\ncatalog.packages (SSISDB Database)\nDisplays the details for all packages that appear in the Integration Services catalog.\ncatalog.environment_references (SSISDB Database)\nDisplays the environment references for all projects in the Integration Services\n[catalog][]\ncatalog.projects (SSISDB Database)\nDisplays the details for all projects that appear in the Integration Services catalog.\ncatalog.validations (SSISDB Database)\nDisplays the details of all project and package validations in the Integration Services catalog.\ncatalog.master_properties (SSISDB Database)\nDisplays the properties of the Integration Services Scale Out Master.\ncatalog.worker_agents (SSISDB Database)\nDisplays the information of Integration Services Scale Out Worker.\n\n", "Execution id, i.e. operation id is used to identify the operation.\nIn my opinion this is very confusing, but you can see it from the structure of the catalog.executions view.\nfrom operations view you can get messages, from executions - packages.\n" ]
[ 8, 0 ]
[]
[]
[ "sql_server", "ssis", "ssis_2012" ]
stackoverflow_0057304583_sql_server_ssis_ssis_2012.txt
Q: NodeJS Express running on AWS Lambda returns error: 'listen EADDRINUSE: address already in use' I've set up AWS lambda with some NodeJS code to learn creating an API. API is set up using Express. The runtime is v18. I also set up API Gateway HTTP API with the lambda integration to invoke it. When I try to call GET method on the /collage route I get internal server error and the Lambda logs return the following: ERROR Uncaught Exception { "errorType": "Error", "errorMessage": "listen EADDRINUSE: address already in use /tmp/server-undefined.sock", "code": "EADDRINUSE", "errno": -98, "syscall": "listen", "address": "/tmp/server-undefined.sock", "port": -1, "stack": [ "Error: listen EADDRINUSE: address already in use /tmp/server-undefined.sock", " at Server.setupListenHandle [as _listen2] (node:net:1468:21)", " at listenInCluster (node:net:1533:12)", " at Server.listen (node:net:1632:5)", " at Function.listen (/var/task/node_modules/express/lib/application.js:635:24)", " at startServer (/var/task/node_modules/@vendia/serverless-express/src/index.js:138:17)", " at proxy (/var/task/node_modules/@vendia/serverless-express/src/index.js:191:14)", " at Server.<anonymous> (/var/task/node_modules/@vendia/serverless-express/src/index.js:192:32)", " at Server.emit (node:events:513:28)", " at emitListeningNT (node:net:1519:10)", " at process.processTicksAndRejections (node:internal/process/task_queues:81:21)" ] } Here is my code: const express = require('express'); const { proxy } = require('aws-serverless-express'); const app = express(); app.get('/collage', (req, res) => { const response = { statusCode: 200, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'Hello, World!' }) }; return response; }); exports.handler = (event, context) => { return proxy(app, event, context); }; The code is as basic as it gets and I put it ogether using some example tutorials and GPT3. Not really sure what could be the issue or how to debug it. There should be no port conflicts since it runs in Lambda.. I did accidentaly include app.listen(3000, () =>{}); before when I deployed the initial version. But it has since been fixed and lambda re-deployed. To make sure I even created a new lambda and deployed latest version to it and got same error. I tried searching this error on the web, but everyone recommends killing the process, but this is running in lambda so not really possible. What can I do to debug this? A: You are using a deprecated package aws-serverless-express. You should use serverless-express On 11/30, the AWS Serverless Express library is moving to Vendia and will be rebranded to serverless-express. Similarly, the aws-serverless-express NPM package will be deprecated in favor of a new serverless-express package.
NodeJS Express running on AWS Lambda returns error: 'listen EADDRINUSE: address already in use'
I've set up AWS lambda with some NodeJS code to learn creating an API. API is set up using Express. The runtime is v18. I also set up API Gateway HTTP API with the lambda integration to invoke it. When I try to call GET method on the /collage route I get internal server error and the Lambda logs return the following: ERROR Uncaught Exception { "errorType": "Error", "errorMessage": "listen EADDRINUSE: address already in use /tmp/server-undefined.sock", "code": "EADDRINUSE", "errno": -98, "syscall": "listen", "address": "/tmp/server-undefined.sock", "port": -1, "stack": [ "Error: listen EADDRINUSE: address already in use /tmp/server-undefined.sock", " at Server.setupListenHandle [as _listen2] (node:net:1468:21)", " at listenInCluster (node:net:1533:12)", " at Server.listen (node:net:1632:5)", " at Function.listen (/var/task/node_modules/express/lib/application.js:635:24)", " at startServer (/var/task/node_modules/@vendia/serverless-express/src/index.js:138:17)", " at proxy (/var/task/node_modules/@vendia/serverless-express/src/index.js:191:14)", " at Server.<anonymous> (/var/task/node_modules/@vendia/serverless-express/src/index.js:192:32)", " at Server.emit (node:events:513:28)", " at emitListeningNT (node:net:1519:10)", " at process.processTicksAndRejections (node:internal/process/task_queues:81:21)" ] } Here is my code: const express = require('express'); const { proxy } = require('aws-serverless-express'); const app = express(); app.get('/collage', (req, res) => { const response = { statusCode: 200, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'Hello, World!' }) }; return response; }); exports.handler = (event, context) => { return proxy(app, event, context); }; The code is as basic as it gets and I put it ogether using some example tutorials and GPT3. Not really sure what could be the issue or how to debug it. There should be no port conflicts since it runs in Lambda.. I did accidentaly include app.listen(3000, () =>{}); before when I deployed the initial version. But it has since been fixed and lambda re-deployed. To make sure I even created a new lambda and deployed latest version to it and got same error. I tried searching this error on the web, but everyone recommends killing the process, but this is running in lambda so not really possible. What can I do to debug this?
[ "You are using a deprecated package aws-serverless-express.\nYou should use serverless-express\n\nOn 11/30, the AWS Serverless Express library is moving to Vendia and will be rebranded to serverless-express. Similarly, the aws-serverless-express NPM package will be deprecated in favor of a new serverless-express package.\n\n" ]
[ 1 ]
[]
[]
[ "aws_api_gateway", "aws_lambda", "express", "node.js" ]
stackoverflow_0074672585_aws_api_gateway_aws_lambda_express_node.js.txt
Q: Issue with SourceTree while cloning a GitHub repository I know that similar question is already posted here, however I think that my scenario is a bit different. Here is what I have. I downloaded and installed the latest official version of the SourceTree software. Also, I have GitHub account with permissions to clone and push the repository. In order to manage a local copy I need to clone the on-line version. Here are the steps that I take: Start the SourceTree and navigate to File -> Clone / New ... In the opened window I paste the HTTPS clone URL. I copied it from the browser after I logged-in my GitHub account, so the link is correct. The nest step is to specify a local folder where the repository will be copied. But when I click to enter Destination Path, the window shows an error: This is not a valid source path / URL clicking the error may give the details: remote: Repository not found. fatal: repository 'https://github.com/org/repo.git/' not found remote: Repository not found. fatal: repository 'https://github.com/org/repo.git/' not found Or, the Details may be empty. The SourceTree does not tell me the reason for the error or anything else. I tried to re-install the SourceTree but the error still exists. I asked the Administration of the GitHub repository for any other permissions but my account has all of them. I am able to push changes to the online repository using the Terminal console, but I would like to use UI (that SourceTree provides) to manage and compare changes in the code. One think I did not try is to Clone the repository using another GtHub account. But I don't want to do that because I need to commit any changes to the repository on my behalf. Does anybody know how can this error be fixed or worked around? A: I was facing the same issue in Sourcetree for macOS: This is not a valid source path / URL The following solution worked for me: Sourcetree > Preferences > Advanced Remove the Host name Clone the project again in Sourcetree A prompt will pop up; enter your git credentials. That's it, it resolved my issue. A: Lastly on Mac I went to Sourcetree->Preferences->Git->Git version->Use System Git and it works... puf! A: The exact error message is (as illustrated here): This is not a valid source path / URL Possible cause: proxy settings (as in this thread) setup steps, with Git disabled (as in here) When SourceTree started for the first time, I skipped setting up Git & Mercurial in the wizard. Then I reran the wizard and chose to download and install the embedded packages. But it seems installing those didn't actually enable them - in the Tools -> Options dialogue they were both disabled! Enabling Mercurial (or Git in your case) allowed the clone dialogue to correctly identify the repo. credential issues (as in here, from my old answwer) A: So I'm here in 2021. Previous answers didn't work for me. There is an issue with a SourceTree (to be honest a lot of issues actually) and as a workaround you can use a token as a password to connect to GitHub. Use this url to create it: https://github.com/settings/tokens I hope it helps! A: I was facing the same issue with windows 10 and source tree. After bit research following solution worked for me. I needed to download or enable the git support in source tree. Steps 1) Go to Tools -> Options -> Git -> Enable git support That's it it resolved my issue. Happy coding :) A: I was facing the same issue in mac. The following solution worked for me : Generate personal access token in Github using the following steps : Login to Github account -> Settings -> Developer Settings -> Personal access tokens -> Generate new token -> Enter token name -> Generate token Sourcetree > Preferences > Advanced Remove the Host name Clone the project again in Sourcetree A prompt will pop up; enter your git credentials. (enter username and in password enter newly generated access token) After following this steps, Clone option will get enabled A: May I also just add that I resolved this issue by installing Git through SourceTree from [SourceTree]>Tools>Options>Git. As I'd been using mercurial exclusively on that system till then it had never been installed, and so was presenting the above described error when trying to clone. Hopefully this helps someone with the same issue! If not, good luck! A: I was facing the same issue with windows 10 and source tree. After bit research following solution worked for me. I needed to download or enable the git support in source tree. Steps 1) Go to Tools -> Options -> Git -> Enable git support That's it it resolved my issue. Happy coding :) A: Even tried all the options above, It quite dint work for me. I disable the option of ssl certificate steps : Go to Tools -> Options -> Git. check the box of "Disable SSL certificate validation" It worked for me. A: Open source tree Tools -> Options -> Git -> Update Embedded. While updating it will ask your gitlab account for linking. After that restart your system. A: Adding my scenario and solution: I have two factor authentication turned on. I couldn't see some private repositories, and couldn't clone from URL. The error I saw was: remote: Repository not found. fatal: repository 'https://github.com/bizzabo/web-common.git/' not found remote: Repository not found. fatal: repository 'https://github.com/bizzabo/web-common.git/' not found Supposedly newer versions of SourceTree don't need a personal access token because they can authenticate directly with github, but I couldn't get this to work. Apparently OAuth and 2FA don't mix well together -- so I changed the authentication method from oauth to basic and used the access token I generated. That did it. A: Just in case someone who has multiple git accounts connected and faces this issue, I solved it by going to Tools > Options > Authentication and marking the account which has access to the repo you are trying to clone as default. A: Install git to your system by browser and then go to the source tree, click on Tools -> Options -> Git then scroll down and click on system. It works for me, I hope for you too. A: I had to uninstall and reinstall SourceTree before it would work. I think my antivirus (Comodo ) was blocking/sandboxing some stuff on the initial install so I disabled it for the reinstall. A: I had also same issue This is not a valid source path / URL and it got resolved by updating the Embedded Git of Source Tree. This issue also manifested itself where I couldn't push or pull from previously cloned and working repositories in source tree. I complained about authentication username and password but clearly that was not the case. Steps to resolve: Open source tree, Tools -> Options -> Click on Git Tab -> Update Embedded Git. A: I had the same problem. My resolution was to commit an initial file into the repo. After that, I could clone the repo to my desktop. A: options -->Tools--->disable ssh worked for me in Mac A: The issue might be because of SourceTree didn't have all private access from Github I have answered here please check to avoid the duplicate answer posting reference link https://stackoverflow.com/a/62145210/4328589 A: If you are using Mac and there is Keychain access handling all your authentication, then delete the entry for stash/git url. Now try to checkout in sourcetree and it will ask to enter the password again. That will solve your problem. A: I face this issue on Windows 11 and following are the steps worked for me : Click on Open with GitHub Desktop option [Refer below image] Download & install Launch and click on Open in browser with Github.com Enter your credentials & validate Now, Open SourceTree Click on Tools > Options > Authentication You will see your Git credentials were successfully added in SourceTree & you can proceed with any option like clone repo etc A: I was trying to clone a project from gitlab. However, I have cloned gitlab projects earlier with an account/user credentials which is different from the new account I want to use. In this case, I had deleted the credentials for the old account and then I was able to clone the project by entering credentials for the new gitlab account. To delete the account on MAC go to Preferences > Advanced > Select the account to remove > Click remove. A: In my case i was doing new Mac book setup. Without installing Xcode i was trying to clone branch using SourceTree. After Xcode installation done, branch cloned successfully. SourceTree asked for system password for cloning. A: I'm posting another possible solution, as I just helped a colleague who couldn't clone a private repo belonging to a GitHub organization even though he had been given the correct level of access. Check the Windows Credential Manager, especially if you've been using the same machine for some time or have connected to different accounts. Git may be picking up the wrong credentials without you realizing it, and that's why it can't find the repo. To be on the safe side, delete all the credentials that have to do with git/github. You'll know you have done it properly and are starting from a fresh state when you will try cloning again and git will ask you to authorize it through your browser. A: probably you try the wrong account only add this account.name@ to link you can learn it from your GitLab account https://[email protected]/samrak-growth/samrak-app-backend.git A: In my specific case (setting up a new mac) the root cause was a "missing xcrun" meaning the local dev tools wasn't activated, and the local git client can't run properly. that was my fix xcode-select --install
Issue with SourceTree while cloning a GitHub repository
I know that similar question is already posted here, however I think that my scenario is a bit different. Here is what I have. I downloaded and installed the latest official version of the SourceTree software. Also, I have GitHub account with permissions to clone and push the repository. In order to manage a local copy I need to clone the on-line version. Here are the steps that I take: Start the SourceTree and navigate to File -> Clone / New ... In the opened window I paste the HTTPS clone URL. I copied it from the browser after I logged-in my GitHub account, so the link is correct. The nest step is to specify a local folder where the repository will be copied. But when I click to enter Destination Path, the window shows an error: This is not a valid source path / URL clicking the error may give the details: remote: Repository not found. fatal: repository 'https://github.com/org/repo.git/' not found remote: Repository not found. fatal: repository 'https://github.com/org/repo.git/' not found Or, the Details may be empty. The SourceTree does not tell me the reason for the error or anything else. I tried to re-install the SourceTree but the error still exists. I asked the Administration of the GitHub repository for any other permissions but my account has all of them. I am able to push changes to the online repository using the Terminal console, but I would like to use UI (that SourceTree provides) to manage and compare changes in the code. One think I did not try is to Clone the repository using another GtHub account. But I don't want to do that because I need to commit any changes to the repository on my behalf. Does anybody know how can this error be fixed or worked around?
[ "I was facing the same issue in Sourcetree for macOS:\n\nThis is not a valid source path / URL\n\n\nThe following solution worked for me:\n\nSourcetree > Preferences > Advanced\nRemove the Host name\nClone the project again in Sourcetree\nA prompt will pop up; enter your git credentials.\n\nThat's it, it resolved my issue.\n", "Lastly on Mac I went to\nSourcetree->Preferences->Git->Git version->Use System Git\nand it works... puf!\n", "The exact error message is (as illustrated here):\n This is not a valid source path / URL\n\n\nPossible cause:\n\nproxy settings (as in this thread)\nsetup steps, with Git disabled (as in here) \n\n\nWhen SourceTree started for the first time, I skipped setting up Git & Mercurial in the wizard. Then I reran the wizard and chose to download and install the embedded packages.\n But it seems installing those didn't actually enable them - in the Tools -> Options dialogue they were both disabled!\n Enabling Mercurial (or Git in your case) allowed the clone dialogue to correctly identify the repo.\n\ncredential issues (as in here, from my old answwer)\n\n", "So I'm here in 2021. Previous answers didn't work for me. There is an issue with a SourceTree (to be honest a lot of issues actually) and as a workaround you can use a token as a password to connect to GitHub.\nUse this url to create it: https://github.com/settings/tokens\nI hope it helps! \n", "I was facing the same issue with windows 10 and source tree. After bit research following solution worked for me.\nI needed to download or enable the git support in source tree.\nSteps\n1) Go to Tools -> Options -> Git -> Enable git support\nThat's it it resolved my issue. Happy coding :) \n", "I was facing the same issue in mac. The following solution worked for me :\n\nGenerate personal access token in Github using the following steps :\nLogin to Github account -> Settings -> Developer Settings -> Personal\naccess tokens -> Generate new token -> Enter token name -> Generate\ntoken\nSourcetree > Preferences > Advanced\nRemove the Host name\nClone the project again in Sourcetree\nA prompt will pop up; enter your git credentials. (enter username and in\npassword enter newly generated access token)\nAfter following this steps, Clone option will get enabled\n\n", "May I also just add that I resolved this issue by installing Git through SourceTree from [SourceTree]>Tools>Options>Git.\nAs I'd been using mercurial exclusively on that system till then it had never been installed, and so was presenting the above described error when trying to clone.\nHopefully this helps someone with the same issue! If not, good luck!\n", "I was facing the same issue with windows 10 and source tree. After bit research following solution worked for me. I needed to download or enable the git support in source tree.\nSteps 1) Go to Tools -> Options -> Git -> Enable git support\nThat's it it resolved my issue. Happy coding :)\n", "Even tried all the options above, It quite dint work for me.\n\nI disable the option of ssl certificate\n\nsteps : \nGo to Tools -> Options -> Git. check the box of \"Disable SSL certificate validation\"\nIt worked for me.\n", "Open source tree Tools -> Options -> Git -> Update Embedded. While updating it will ask your gitlab account for linking. After that restart your system. \n", "Adding my scenario and solution:\nI have two factor authentication turned on. I couldn't see some private repositories, and couldn't clone from URL. The error I saw was: \nremote: Repository not found.\nfatal: repository 'https://github.com/bizzabo/web-common.git/' not found\nremote: Repository not found.\nfatal: repository 'https://github.com/bizzabo/web-common.git/' not found\n\nSupposedly newer versions of SourceTree don't need a personal access token because they can authenticate directly with github, but I couldn't get this to work. \nApparently OAuth and 2FA don't mix well together -- so I changed the authentication method from oauth to basic and used the access token I generated. That did it.\n", "Just in case someone who has multiple git accounts connected and faces this issue, I solved it by going to Tools > Options > Authentication and marking the account which has access to the repo you are trying to clone as default.\n", "Install git to your system by browser and then go to the source tree, click on\nTools -> Options -> Git\nthen scroll down and click on system.\nIt works for me, I hope for you too.\n", "I had to uninstall and reinstall SourceTree before it would work. I think my antivirus (Comodo ) was blocking/sandboxing some stuff on the initial install so I disabled it for the reinstall.\n", "I had also same issue This is not a valid source path / URL and it got resolved by updating the Embedded Git of Source Tree.\nThis issue also manifested itself where I couldn't push or pull from previously cloned and working repositories in source tree. I complained about authentication username and password but clearly that was not the case.\nSteps to resolve:\nOpen source tree, Tools -> Options -> Click on Git Tab -> Update Embedded Git.\n", "I had the same problem. My resolution was to commit an initial file into the repo. After that, I could clone the repo to my desktop.\n", "options -->Tools--->disable ssh worked for me in Mac\n", "The issue might be because of SourceTree didn't have all private access from Github\nI have answered here please check to avoid the duplicate answer posting reference link\nhttps://stackoverflow.com/a/62145210/4328589\n", "If you are using Mac and there is Keychain access handling all your authentication, then delete the entry for stash/git url. Now try to checkout in sourcetree and it will ask to enter the password again.\nThat will solve your problem.\n", "I face this issue on Windows 11 and following are the steps worked for me :\n\nClick on Open with GitHub Desktop option [Refer below image] \nDownload & install\nLaunch and click on Open in browser with Github.com\nEnter your credentials & validate\nNow, Open SourceTree\nClick on Tools > Options > Authentication\nYou will see your Git credentials were successfully added in SourceTree & you can proceed with any option like clone repo etc\n\n", "I was trying to clone a project from gitlab. However, I have cloned gitlab projects earlier with an account/user credentials which is different from the new account I want to use. In this case, I had deleted the credentials for the old account and then I was able to clone the project by entering credentials for the new gitlab account. To delete the account on MAC go to Preferences > Advanced > Select the account to remove > Click remove.\n", "In my case i was doing new Mac book setup.\nWithout installing Xcode i was trying to clone branch using SourceTree.\n\nAfter Xcode installation done, branch cloned successfully.\n\nSourceTree asked for system password for cloning.\n", "I'm posting another possible solution, as I just helped a colleague who couldn't clone a private repo belonging to a GitHub organization even though he had been given the correct level of access.\nCheck the Windows Credential Manager, especially if you've been using the same machine for some time or have connected to different accounts.\nGit may be picking up the wrong credentials without you realizing it, and that's why it can't find the repo.\nTo be on the safe side, delete all the credentials that have to do with git/github. You'll know you have done it properly and are starting from a fresh state when you will try cloning again and git will ask you to authorize it through your browser.\n", "probably you try the wrong account only add this\naccount.name@ to link\nyou can learn it from your GitLab account\nhttps://[email protected]/samrak-growth/samrak-app-backend.git\n", "In my specific case (setting up a new mac) the root cause was a \"missing xcrun\" meaning the local dev tools wasn't activated, and the local git client can't run properly.\nthat was my fix\nxcode-select --install\n\n" ]
[ 40, 23, 21, 7, 5, 4, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "atlassian_sourcetree", "github" ]
stackoverflow_0020718193_atlassian_sourcetree_github.txt
Q: How to get all users in Firestore except those in block array list inside user document? I'm creating an app with Firebas Firestore as database. In my app users can block other users to exclude them from the next query. Which database structure should I use to do the Firestore query? When you block someone, the userID will be stored in an array inside your user document. The Firestore query only provides 'array-contains' operator to filter based on array values. So I need to query "array-NOT-contains" but Firestore doesn't provide it. DB structure users: { user1:{ name: "Lorem Ipsum" blockedUsersId: [ 0: user1, 1: user2] } } A: To implement this functionality, you can create a separate collection called "blocks" and store the blocked users in this collection. Each document in the "blocks" collection would contain two fields: "blocker" and "blocked", which represent the IDs of the blocking and blocked users respectively. When querying for users, you can use the Firestore "where" operator to filter out the blocked users by using the "array-contains" operator on the "blocker" field in the "blocks" collection. For example, the following query would return all users who are not blocked by the user with ID "user1": db.collection("users").where("id", "array-contains", "user1") Alternatively, you can create an index on the "blocker" field in the "blocks" collection, which would allow you to query for blocked users using the "where" operator. For example, the following query would return all users who are blocked by the user with ID "user1": db.collection("blocks") .where("blocker", "==", "user1") .get() .then(function(querySnapshot) { querySnapshot.forEach(function(doc) { // doc.data().blocked contains the ID of the blocked user }); }); You can then use the IDs of the blocked users to exclude them from the final query for users.
How to get all users in Firestore except those in block array list inside user document?
I'm creating an app with Firebas Firestore as database. In my app users can block other users to exclude them from the next query. Which database structure should I use to do the Firestore query? When you block someone, the userID will be stored in an array inside your user document. The Firestore query only provides 'array-contains' operator to filter based on array values. So I need to query "array-NOT-contains" but Firestore doesn't provide it. DB structure users: { user1:{ name: "Lorem Ipsum" blockedUsersId: [ 0: user1, 1: user2] } }
[ "To implement this functionality, you can create a separate collection called \"blocks\" and store the blocked users in this collection. Each document in the \"blocks\" collection would contain two fields: \"blocker\" and \"blocked\", which represent the IDs of the blocking and blocked users respectively.\nWhen querying for users, you can use the Firestore \"where\" operator to filter out the blocked users by using the \"array-contains\" operator on the \"blocker\" field in the \"blocks\" collection.\nFor example, the following query would return all users who are not blocked by the user with ID \"user1\":\ndb.collection(\"users\").where(\"id\", \"array-contains\", \"user1\")\n\nAlternatively, you can create an index on the \"blocker\" field in the \"blocks\" collection, which would allow you to query for blocked users using the \"where\" operator.\nFor example, the following query would return all users who are blocked by the user with ID \"user1\":\ndb.collection(\"blocks\")\n .where(\"blocker\", \"==\", \"user1\")\n .get()\n .then(function(querySnapshot) {\n querySnapshot.forEach(function(doc) {\n // doc.data().blocked contains the ID of the blocked user\n });\n });\n\nYou can then use the IDs of the blocked users to exclude them from the final query for users.\n" ]
[ 0 ]
[]
[]
[ "android", "firebase", "google_cloud_firestore", "kotlin" ]
stackoverflow_0074675875_android_firebase_google_cloud_firestore_kotlin.txt
Q: Sketchware: Error in/storage/emulated/0/.sketchware/mysc/602/app/src/main/java/com/DbEditor/VictorChannel/PageEditActivity.java(at line 83) I am creating an apk in Sketchware. I am trying to create a .db file editor, but this apk requires me to create a file manager within it so that I can browse the .db file. I was guided by this tutorial: https:/ /youtu .be/OkiBwSrT5WY But when compiling in my project it gives me an error enter image description here Error in /storage/emulated/0/.sketchware/mysc/602/app/src/main/java/com/DbEditor/VictorChannel/PageEditActivity.java (at line 83) ","design")); Syntax error in token "","", @expected Error in /storage/emulated/0/.sketchware/mysc/602/app/src/main/java/com/DbEditor/VictorChannel/PageEditActivity.java (at line 83) ","design")); String literal is not properly closed with a double quote I tried to look in the code what the problem was, I tried to remove the quotes, it didn't work, then I removed the parentheses in the code, that didn't work either. It doesn't work for me when trying to compile the apk directly from Sketchware it puts back quotes and parentheses it seems that it doesn't change anything. enter image description here I don't know what to do please Can someone please help me? A: ((View)_toolbar.getParent()).setBackgroundColor(Color.parseColor(_c)); getSupportActionBar().setBackgroundDrawable(new android.graphics.drawable.ColorDrawable(Color.parseColor(_c)));
Sketchware: Error in/storage/emulated/0/.sketchware/mysc/602/app/src/main/java/com/DbEditor/VictorChannel/PageEditActivity.java(at line 83)
I am creating an apk in Sketchware. I am trying to create a .db file editor, but this apk requires me to create a file manager within it so that I can browse the .db file. I was guided by this tutorial: https:/ /youtu .be/OkiBwSrT5WY But when compiling in my project it gives me an error enter image description here Error in /storage/emulated/0/.sketchware/mysc/602/app/src/main/java/com/DbEditor/VictorChannel/PageEditActivity.java (at line 83) ","design")); Syntax error in token "","", @expected Error in /storage/emulated/0/.sketchware/mysc/602/app/src/main/java/com/DbEditor/VictorChannel/PageEditActivity.java (at line 83) ","design")); String literal is not properly closed with a double quote I tried to look in the code what the problem was, I tried to remove the quotes, it didn't work, then I removed the parentheses in the code, that didn't work either. It doesn't work for me when trying to compile the apk directly from Sketchware it puts back quotes and parentheses it seems that it doesn't change anything. enter image description here I don't know what to do please Can someone please help me?
[ "((View)_toolbar.getParent()).setBackgroundColor(Color.parseColor(_c));\ngetSupportActionBar().setBackgroundDrawable(new android.graphics.drawable.ColorDrawable(Color.parseColor(_c)));\n" ]
[ 0 ]
[]
[]
[ "sketchware" ]
stackoverflow_0072309372_sketchware.txt
Q: How to change the highlight color of a textbox in vb.net 2010 Is it possible to change the highlight color of a textbox in vb.net. I want to replace lightblue to some other color with white color text. Any idea please? A: Work with a richtextbox instead, the layout looks the same.
How to change the highlight color of a textbox in vb.net 2010
Is it possible to change the highlight color of a textbox in vb.net. I want to replace lightblue to some other color with white color text. Any idea please?
[ "Work with a richtextbox instead, the layout looks the same.\n" ]
[ 0 ]
[]
[]
[ "vb.net_2010" ]
stackoverflow_0033876304_vb.net_2010.txt
Q: Request Mock in Python ''' api = API(url, timeout=2) response = api.get("") if response.success: c = response.body['content'] return c ''' for above function , I've mocked in following way ''' mock_response = MagicMock(success = True) mock_response.body.return_value = {'content':923,'a':1256} mock_api.get.return_value = mock_response''' above approach always return response.body['content'] as 1 , though I initialize mock_response.body.return_value equals to {'content':923,'a':1256}, byexpecting response.body['content'] equal to 923. How Can I make *response.body['content'] to access initialized values from mock ? A: To make the mock return the correct value for response.body['content'], you need to set the body attribute of the mock response object to a dictionary containing the content key. Here is an example: from unittest.mock import MagicMock # Set up the mock response object mock_response = MagicMock(success=True) # Set the body attribute to a dictionary containing the 'content' key mock_response.body = {'content': 923, 'a': 1256} # Set the return value of the mock API's get method to the mock response mock_api.get.return_value = mock_response Now, when you call the get method on the mock API and access the response.body['content'] attribute, it should return the correct value (i.e. 923). Note that in the original code, the body attribute is accessed using square bracket notation (response.body['content']), so it should be set to a dictionary rather than a mock object. If you set it to a mock object and try to access the content key using square bracket notation, it will always return 1 (or whatever the default return value of the mock object is).
Request Mock in Python
''' api = API(url, timeout=2) response = api.get("") if response.success: c = response.body['content'] return c ''' for above function , I've mocked in following way ''' mock_response = MagicMock(success = True) mock_response.body.return_value = {'content':923,'a':1256} mock_api.get.return_value = mock_response''' above approach always return response.body['content'] as 1 , though I initialize mock_response.body.return_value equals to {'content':923,'a':1256}, byexpecting response.body['content'] equal to 923. How Can I make *response.body['content'] to access initialized values from mock ?
[ "To make the mock return the correct value for response.body['content'], you need to set the body attribute of the mock response object to a dictionary containing the content key. Here is an example:\nfrom unittest.mock import MagicMock\n\n# Set up the mock response object\nmock_response = MagicMock(success=True)\n\n# Set the body attribute to a dictionary containing the 'content' key\nmock_response.body = {'content': 923, 'a': 1256}\n\n# Set the return value of the mock API's get method to the mock response\nmock_api.get.return_value = mock_response\n\nNow, when you call the get method on the mock API and access the response.body['content'] attribute, it should return the correct value (i.e. 923).\nNote that in the original code, the body attribute is accessed using square bracket notation (response.body['content']), so it should be set to a dictionary rather than a mock object. If you set it to a mock object and try to access the content key using square bracket notation, it will always return 1 (or whatever the default return value of the mock object is).\n" ]
[ 0 ]
[]
[]
[ "mocking", "python" ]
stackoverflow_0074675893_mocking_python.txt
Q: partial cumulative sum in python Suppose I have a numpy array (or pandas Series if it makes it any easier), which looks like this: foo = np.array([1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0]) I want to transform into an array bar = np.array([0, 1, 2, 3, 4,0, 1, 2, 0, 1, 2, 3]) where the entry is how many steps you need to walk to the left to find a 1 in foo. Now, obviously one can write a loop to compute bar from foo, but this will be bog slow. Is there anything more clever one can do? UPDATE The pd.Series solution is around 7 times slower than the pure numpy solution. The stupid loop solution is very slow (no surprise), but when jit compiled with numba is as fast as the numpy solution. A: You could do cumcount with pandas s = pd.Series(foo) bar = s.groupby(s.cumsum()).cumcount().to_numpy() Out[13]: array([0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2, 3], dtype=int64) A: One option, specifically for the shared example, with numpy: # get positions where value is 1 pos = foo.nonzero()[0] # need this when computing the cumsum values = np.diff(pos) - 1 arr = np.ones(foo.size, dtype=int) arr[0] = 0 arr[pos[1:]] = -values arr.cumsum() array([0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2, 3]) A: Yes, you can use the numpy.cumsum() function to compute bar from foo very efficiently. Here's how you can do it: import numpy as np # Define the input array foo = np.array([1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0]) # Compute the cumulative sum of foo, but shift the values # to the right by one position and insert a 0 at the beginning cs = np.insert(np.cumsum(foo), 0, 0) # Subtract the shifted cumulative sum from the original cumulative sum bar = np.cumsum(foo) - cs # Print the result print(bar) This should give you the desired output: array([0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2, 3]). Here's a brief explanation of how this works: The numpy.cumsum() function computes the cumulative sum of an array, which means that it sums up all the elements of the array up to and including each element. So, for example, if you apply numpy.cumsum() to the array [1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0], you get the array [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3]. Next, we use the numpy.insert() function to shift the values of the cumulative sum to the right by one position and insert a 0 at the beginning. This gives us the array [0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3]. Finally, we subtract the shifted cumulative sum from the original cumulative sum, which gives us the array [0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0]. This is exactly the same as the original array foo, except that the 1s have been replaced by the number of steps needed to walk to the left to find the next 1. This is exactly the result that we want. I hope this helps! Let me know if you have any other questions.
partial cumulative sum in python
Suppose I have a numpy array (or pandas Series if it makes it any easier), which looks like this: foo = np.array([1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0]) I want to transform into an array bar = np.array([0, 1, 2, 3, 4,0, 1, 2, 0, 1, 2, 3]) where the entry is how many steps you need to walk to the left to find a 1 in foo. Now, obviously one can write a loop to compute bar from foo, but this will be bog slow. Is there anything more clever one can do? UPDATE The pd.Series solution is around 7 times slower than the pure numpy solution. The stupid loop solution is very slow (no surprise), but when jit compiled with numba is as fast as the numpy solution.
[ "You could do cumcount with pandas\ns = pd.Series(foo)\nbar = s.groupby(s.cumsum()).cumcount().to_numpy()\nOut[13]: array([0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2, 3], dtype=int64)\n\n", "One option, specifically for the shared example, with numpy:\n# get positions where value is 1\npos = foo.nonzero()[0]\n# need this when computing the cumsum\nvalues = np.diff(pos) - 1\narr = np.ones(foo.size, dtype=int)\narr[0] = 0\narr[pos[1:]] = -values\narr.cumsum()\n\narray([0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2, 3])\n\n", "Yes, you can use the numpy.cumsum() function to compute bar from foo very efficiently. Here's how you can do it:\nimport numpy as np\n\n# Define the input array\nfoo = np.array([1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0])\n\n# Compute the cumulative sum of foo, but shift the values\n# to the right by one position and insert a 0 at the beginning\ncs = np.insert(np.cumsum(foo), 0, 0)\n\n# Subtract the shifted cumulative sum from the original cumulative sum\nbar = np.cumsum(foo) - cs\n\n# Print the result\nprint(bar)\n\nThis should give you the desired output: array([0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2, 3]).\nHere's a brief explanation of how this works: The numpy.cumsum() function computes the cumulative sum of an array, which means that it sums up all the elements of the array up to and including each element. So, for example, if you apply numpy.cumsum() to the array [1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0], you get the array [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3].\nNext, we use the numpy.insert() function to shift the values of the cumulative sum to the right by one position and insert a 0 at the beginning. This gives us the array [0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3].\nFinally, we subtract the shifted cumulative sum from the original cumulative sum, which gives us the array [0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0]. This is exactly the same as the original array foo, except that the 1s have been replaced by the number of steps needed to walk to the left to find the next 1. This is exactly the result that we want.\nI hope this helps! Let me know if you have any other questions.\n" ]
[ 9, 2, 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074620655_numpy_pandas_python.txt
Q: Angular - modify the data based on another service and return an observable I have one service that returns a list of vehicles. I need to get the driver for each vehicle and set it for the bus. So far, I have implemented it in such a way: return this.getVehicles().pipe( // Set the driver map((res) => { res.items = res.items.map((vehicle) => { if (vehicle.driver_id !== "") { this.driverSvc.get(vehicle.driver_id).subscribe((data) => { vehicle.driver = data; }) } return vehicle; }) return res; }), map((res) => { // This map needs to have the driver! console.log(vehicle.driver) // Undefined in all cases, where it should be set for one of the entries }) I know the console.log(vehicle.driver) logs undefined because of the subscribe. Is there any other way to modify my response based on the response from another service? A: As i already mentioned you need to use the switchMap operator to combine the two observables to a chain. The following example could maybe work for you: return this.getVehicles.pipe( // load the driver switchMap((response) => zip( ...response.map((vehicle) => this.driverSvc.get(vehicle.driver_id).pipe(map((driver) => { vehicle.driver = driver; return vehicle; })), ), ), ), map((responseWithDriver) => { // this map needs to have the driver! console.log(responseWithDriver); }), ); The switchMap let us use a new observable as return value and the zip operator let us combine multiple calls to one return value.
Angular - modify the data based on another service and return an observable
I have one service that returns a list of vehicles. I need to get the driver for each vehicle and set it for the bus. So far, I have implemented it in such a way: return this.getVehicles().pipe( // Set the driver map((res) => { res.items = res.items.map((vehicle) => { if (vehicle.driver_id !== "") { this.driverSvc.get(vehicle.driver_id).subscribe((data) => { vehicle.driver = data; }) } return vehicle; }) return res; }), map((res) => { // This map needs to have the driver! console.log(vehicle.driver) // Undefined in all cases, where it should be set for one of the entries }) I know the console.log(vehicle.driver) logs undefined because of the subscribe. Is there any other way to modify my response based on the response from another service?
[ "As i already mentioned you need to use the switchMap operator to combine the two observables to a chain. The following example could maybe work for you:\n return this.getVehicles.pipe(\n // load the driver\n switchMap((response) =>\n zip(\n ...response.map((vehicle) =>\n this.driverSvc.get(vehicle.driver_id).pipe(map((driver) => {\n vehicle.driver = driver;\n return vehicle;\n })),\n ),\n ),\n ),\n map((responseWithDriver) => {\n // this map needs to have the driver!\n console.log(responseWithDriver);\n }),\n );\n\nThe switchMap let us use a new observable as return value and the zip operator let us combine multiple calls to one return value.\n" ]
[ 1 ]
[]
[]
[ "angular", "rxjs", "typescript" ]
stackoverflow_0074675757_angular_rxjs_typescript.txt
Q: The sprite doesnt seems to be jumping i am following a brackeys tutorial, the sprite is moving left right but not jumping. "Jump" is working fine but the results are not present in the gameview.it references a script provided by brackeys but i dont whether thats the problem. Here is the code using System.Collections; using System.Collections.Generic; using UnityEngine; public class player_movemnt : MonoBehaviour { public CharacterController2D controller; float horizontal_movement =0f; public float run_speed = 60f; bool jump = false; void Update() { horizontal_movement = Input.GetAxisRaw("Horizontal")*run_speed; if(Input.GetButtonDown("Jump")) { jump = true; Debug.Log("l"); } } void FixedUpdate() { //move character controller.Move(horizontal_movement*Time.fixedDeltaTime,false, jump); jump= false; } } here is the CharacterControl2D scrip using UnityEngine; using UnityEngine.Events; public class CharacterController2D : MonoBehaviour { [SerializeField] private float m_JumpForce = 400f; // Amount of force added when the player jumps. [Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f; // Amount of maxSpeed applied to crouching movement. 1 = 100% [Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f; // How much to smooth out the movement [SerializeField] private bool m_AirControl = false; // Whether or not a player can steer while jumping; [SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character [SerializeField] private Transform m_GroundCheck; // A position marking where to check if the player is grounded. [SerializeField] private Transform m_CeilingCheck; // A position marking where to check for ceilings [SerializeField] private Collider2D m_CrouchDisableCollider; // A collider that will be disabled when crouching const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded private bool m_Grounded; // Whether or not the player is grounded. const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up private Rigidbody2D m_Rigidbody2D; private bool m_FacingRight = true; // For determining which way the player is currently facing. private Vector3 m_Velocity = Vector3.zero; [Header("Events")] [Space] public UnityEvent OnLandEvent; [System.Serializable] public class BoolEvent : UnityEvent<bool> { } public BoolEvent OnCrouchEvent; private bool m_wasCrouching = false; private void Awake() { m_Rigidbody2D = GetComponent<Rigidbody2D>(); if (OnLandEvent == null) OnLandEvent = new UnityEvent(); if (OnCrouchEvent == null) OnCrouchEvent = new BoolEvent(); } private void FixedUpdate() { bool wasGrounded = m_Grounded; m_Grounded = false; // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground // This can be done using layers instead but Sample Assets will not overwrite your project settings. Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround); for (int i = 0; i < colliders.Length; i++) { if (colliders[i].gameObject != gameObject) { m_Grounded = true; if (!wasGrounded) OnLandEvent.Invoke(); } } } public void Move(float move, bool crouch, bool jump) { // If crouching, check to see if the character can stand up if (!crouch) { // If the character has a ceiling preventing them from standing up, keep them crouching if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround)) { crouch = true; } } //only control the player if grounded or airControl is turned on if (m_Grounded || m_AirControl) { // If crouching if (crouch) { if (!m_wasCrouching) { m_wasCrouching = true; OnCrouchEvent.Invoke(true); } // Reduce the speed by the crouchSpeed multiplier move *= m_CrouchSpeed; // Disable one of the colliders when crouching if (m_CrouchDisableCollider != null) m_CrouchDisableCollider.enabled = false; } else { // Enable the collider when not crouching if (m_CrouchDisableCollider != null) m_CrouchDisableCollider.enabled = true; if (m_wasCrouching) { m_wasCrouching = false; OnCrouchEvent.Invoke(false); } } // Move the character by finding the target velocity Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y); // And then smoothing it out and applying it to the character m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing); // If the input is moving the player right and the player is facing left... if (move > 0 && !m_FacingRight) { // ... flip the player. Flip(); } // Otherwise if the input is moving the player left and the player is facing right... else if (move < 0 && m_FacingRight) { // ... flip the player. Flip(); } } // If the player should jump... if (m_Grounded && jump) { // Add a vertical force to the player. m_Grounded = false; m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce)); } } private void Flip() { // Switch the way the player is labelled as facing. m_FacingRight = !m_FacingRight; // Multiply the player's x local scale by -1. Vector3 theScale = transform.localScale; theScale.x *= -1; transform.localScale = theScale; } } i am completely dumbfounded with this problem. A: If you're using a separate class to handle your movement, it's always ideal to include it alongside your question. So others wont have to search for it. Your code appears okay, at least based on the tutorial you've mentioned. Double-check that them_GroundCheck GameObject of CharacterController2D is on the ground rather than on the bottom of the player, as that's responsible for ensuring you can jump in the first place. public CharacterController2D characterController; public float runSpeed = 60f; private float _horizontalMovement; private bool _jump; private void Update() { _horizontalMovement = Input.GetAxisRaw("Horizontal") * runSpeed; if (Input.GetButtonDown("Jump")) { _jump = true; } } private void FixedUpdate() { characterController.Move(_horizontalMovement * Time.fixedDeltaTime, false, _jump); _jump = false; } I'd recommend working backwards and ensuring your CharacterController2D is set up correctly to support the jump, including any attributes you need to add in the inspector window. Such as a reference to GroundCheck and its LayerMask.
The sprite doesnt seems to be jumping
i am following a brackeys tutorial, the sprite is moving left right but not jumping. "Jump" is working fine but the results are not present in the gameview.it references a script provided by brackeys but i dont whether thats the problem. Here is the code using System.Collections; using System.Collections.Generic; using UnityEngine; public class player_movemnt : MonoBehaviour { public CharacterController2D controller; float horizontal_movement =0f; public float run_speed = 60f; bool jump = false; void Update() { horizontal_movement = Input.GetAxisRaw("Horizontal")*run_speed; if(Input.GetButtonDown("Jump")) { jump = true; Debug.Log("l"); } } void FixedUpdate() { //move character controller.Move(horizontal_movement*Time.fixedDeltaTime,false, jump); jump= false; } } here is the CharacterControl2D scrip using UnityEngine; using UnityEngine.Events; public class CharacterController2D : MonoBehaviour { [SerializeField] private float m_JumpForce = 400f; // Amount of force added when the player jumps. [Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f; // Amount of maxSpeed applied to crouching movement. 1 = 100% [Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f; // How much to smooth out the movement [SerializeField] private bool m_AirControl = false; // Whether or not a player can steer while jumping; [SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character [SerializeField] private Transform m_GroundCheck; // A position marking where to check if the player is grounded. [SerializeField] private Transform m_CeilingCheck; // A position marking where to check for ceilings [SerializeField] private Collider2D m_CrouchDisableCollider; // A collider that will be disabled when crouching const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded private bool m_Grounded; // Whether or not the player is grounded. const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up private Rigidbody2D m_Rigidbody2D; private bool m_FacingRight = true; // For determining which way the player is currently facing. private Vector3 m_Velocity = Vector3.zero; [Header("Events")] [Space] public UnityEvent OnLandEvent; [System.Serializable] public class BoolEvent : UnityEvent<bool> { } public BoolEvent OnCrouchEvent; private bool m_wasCrouching = false; private void Awake() { m_Rigidbody2D = GetComponent<Rigidbody2D>(); if (OnLandEvent == null) OnLandEvent = new UnityEvent(); if (OnCrouchEvent == null) OnCrouchEvent = new BoolEvent(); } private void FixedUpdate() { bool wasGrounded = m_Grounded; m_Grounded = false; // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground // This can be done using layers instead but Sample Assets will not overwrite your project settings. Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround); for (int i = 0; i < colliders.Length; i++) { if (colliders[i].gameObject != gameObject) { m_Grounded = true; if (!wasGrounded) OnLandEvent.Invoke(); } } } public void Move(float move, bool crouch, bool jump) { // If crouching, check to see if the character can stand up if (!crouch) { // If the character has a ceiling preventing them from standing up, keep them crouching if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround)) { crouch = true; } } //only control the player if grounded or airControl is turned on if (m_Grounded || m_AirControl) { // If crouching if (crouch) { if (!m_wasCrouching) { m_wasCrouching = true; OnCrouchEvent.Invoke(true); } // Reduce the speed by the crouchSpeed multiplier move *= m_CrouchSpeed; // Disable one of the colliders when crouching if (m_CrouchDisableCollider != null) m_CrouchDisableCollider.enabled = false; } else { // Enable the collider when not crouching if (m_CrouchDisableCollider != null) m_CrouchDisableCollider.enabled = true; if (m_wasCrouching) { m_wasCrouching = false; OnCrouchEvent.Invoke(false); } } // Move the character by finding the target velocity Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y); // And then smoothing it out and applying it to the character m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing); // If the input is moving the player right and the player is facing left... if (move > 0 && !m_FacingRight) { // ... flip the player. Flip(); } // Otherwise if the input is moving the player left and the player is facing right... else if (move < 0 && m_FacingRight) { // ... flip the player. Flip(); } } // If the player should jump... if (m_Grounded && jump) { // Add a vertical force to the player. m_Grounded = false; m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce)); } } private void Flip() { // Switch the way the player is labelled as facing. m_FacingRight = !m_FacingRight; // Multiply the player's x local scale by -1. Vector3 theScale = transform.localScale; theScale.x *= -1; transform.localScale = theScale; } } i am completely dumbfounded with this problem.
[ "If you're using a separate class to handle your movement, it's always ideal to include it alongside your question. So others wont have to search for it.\nYour code appears okay, at least based on the tutorial you've mentioned. Double-check that them_GroundCheck GameObject of CharacterController2D is on the ground rather than on the bottom of the player, as that's responsible for ensuring you can jump in the first place.\npublic CharacterController2D characterController;\npublic float runSpeed = 60f;\n\nprivate float _horizontalMovement;\nprivate bool _jump;\n\nprivate void Update()\n{\n _horizontalMovement = Input.GetAxisRaw(\"Horizontal\") * runSpeed;\n if (Input.GetButtonDown(\"Jump\"))\n {\n _jump = true;\n }\n}\n\nprivate void FixedUpdate()\n{\n characterController.Move(_horizontalMovement * Time.fixedDeltaTime, false, _jump);\n _jump = false;\n}\n\nI'd recommend working backwards and ensuring your CharacterController2D is set up correctly to support the jump, including any attributes you need to add in the inspector window. Such as a reference to GroundCheck and its LayerMask.\n\n" ]
[ 0 ]
[]
[]
[ "2d", "c#", "unity3d" ]
stackoverflow_0074675716_2d_c#_unity3d.txt
Q: Pressing Ctrl + S automatically opens Output window Whenever i press Ctrl+S from keyboard or whenever i click on any file in Solution Explorer it automatically opens output window only in Visual Studio 2012. I tried Tools > Options > Projects and Solutions > Show output window when build starts I am using Visual Studio Professional 2012 But its just not working. Its irritates a lot. Please suggest how to get rid of it. A: if someone is facing this issue in visual studio community 2015, in my case the issue was caused because of the use of Backup and sync utility from google, I have synced my source directory to my google drive to maintain the latest copy of source backed up. The backup utility locks the file which you might be editing for syncing it to cloud storage. since the file is locked by another process, the visual studio cannot save the changes in the file. The fix was to pause the syncing for the time you are doing frequent changes. In your case, it might be some other process which might be locking the file. A: If you're using an extension, one of them could be the reason. I had the same problem while saving the CMakeLists.txt files. I checked one of the extension's setting, "CMake Tools", it has a "Cmake: Reveal Log" settings which causing this problem. I simply deactivated it I suggest you to check extensions' settings or try to find on settings with searching "output", "focus" etc.
Pressing Ctrl + S automatically opens Output window
Whenever i press Ctrl+S from keyboard or whenever i click on any file in Solution Explorer it automatically opens output window only in Visual Studio 2012. I tried Tools > Options > Projects and Solutions > Show output window when build starts I am using Visual Studio Professional 2012 But its just not working. Its irritates a lot. Please suggest how to get rid of it.
[ "if someone is facing this issue in visual studio community 2015, in my case the issue was caused because of the use of Backup and sync utility from google, I have synced my source directory to my google drive to maintain the latest copy of source backed up.\nThe backup utility locks the file which you might be editing for syncing it to cloud storage. since the file is locked by another process, the visual studio cannot save the changes in the file.\nThe fix was to pause the syncing for the time you are doing frequent changes.\nIn your case, it might be some other process which might be locking the file.\n", "If you're using an extension, one of them could be the reason.\nI had the same problem while saving the CMakeLists.txt files. I checked one of the extension's setting, \"CMake Tools\", it has a \"Cmake: Reveal Log\" settings which causing this problem. I simply deactivated it\n\nI suggest you to check extensions' settings or try to find on settings with searching \"output\", \"focus\" etc.\n" ]
[ 1, 1 ]
[]
[]
[ "output_window", "visual_studio_2012" ]
stackoverflow_0024256768_output_window_visual_studio_2012.txt
Q: GNU linker no success to make a relocatable module with calls to absolute addresses I work on a MC68360 platform using GNU development tools. What I need is a relocatable execution module that can make calls to absolute addresses, i.e to functions that are already in memory (ROM). I can't get the GNU linker to do so. The place of the function call in the application is a relocatable address and the provided function address is an absolute address. The end result is a relocatable address. How did I do it so far: I extract the Global Functions from the rom-image and make a file out of this, say rom_functions.S. This file looks like this: .text .globl sqrt .equ sqrt, 0x<abs addr> A check with readelf on rom_functions.o confirms all symbols are absolute addresses, there is no relocation table either. rom_functions.o is used to link with the application into a relocatable module with the following command line: ld -d -r -Rrom_functions.o -uappl_start -Tmyscript @$objs -o appl.rel appl.o The -R is used to include and preserve absolute addresses as is the purpose of this option I guess. Possibly I have mis-interpreted the -R option. I have tried -R<rom.img> but yields similar result , the called function address is made relocatable in the output and is thus - when loading - modified with the loadaddress; eventulally a the call will nog enter the desired function. Is there a solution to achieve what I want: a relocatable module with calls to absolute addresses? A: You can try using the -Ur linker option to specify that the symbol sqrt should be treated as a weak undefined reference. This will allow the linker to include the symbol in the output file, but without modifying its address. You can then use the -T linker option to specify a linker script that defines the address of the symbol sqrt as an absolute address. Here is an example of how you might use these options: ld -d -r -Ur -Tmyscript @$objs -o appl.rel appl.o The linker script myscript should be defined as follows: SECTIONS { .text : { *(.text) sqrt = 0x<abs addr>; } } This should create a relocatable module with calls to absolute addresses. You can then use a tool like objcopy to modify the addresses in the module to match the location where it will be loaded in memory.
GNU linker no success to make a relocatable module with calls to absolute addresses
I work on a MC68360 platform using GNU development tools. What I need is a relocatable execution module that can make calls to absolute addresses, i.e to functions that are already in memory (ROM). I can't get the GNU linker to do so. The place of the function call in the application is a relocatable address and the provided function address is an absolute address. The end result is a relocatable address. How did I do it so far: I extract the Global Functions from the rom-image and make a file out of this, say rom_functions.S. This file looks like this: .text .globl sqrt .equ sqrt, 0x<abs addr> A check with readelf on rom_functions.o confirms all symbols are absolute addresses, there is no relocation table either. rom_functions.o is used to link with the application into a relocatable module with the following command line: ld -d -r -Rrom_functions.o -uappl_start -Tmyscript @$objs -o appl.rel appl.o The -R is used to include and preserve absolute addresses as is the purpose of this option I guess. Possibly I have mis-interpreted the -R option. I have tried -R<rom.img> but yields similar result , the called function address is made relocatable in the output and is thus - when loading - modified with the loadaddress; eventulally a the call will nog enter the desired function. Is there a solution to achieve what I want: a relocatable module with calls to absolute addresses?
[ "You can try using the -Ur linker option to specify that the symbol sqrt should be treated as a weak undefined reference. This will allow the linker to include the symbol in the output file, but without modifying its address. You can then use the -T linker option to specify a linker script that defines the address of the symbol sqrt as an absolute address.\nHere is an example of how you might use these options:\nld -d -r -Ur -Tmyscript @$objs -o appl.rel appl.o\n\nThe linker script myscript should be defined as follows:\nSECTIONS\n{\n .text : {\n *(.text)\n sqrt = 0x<abs addr>;\n }\n}\n\nThis should create a relocatable module with calls to absolute addresses. You can then use a tool like objcopy to modify the addresses in the module to match the location where it will be loaded in memory.\n" ]
[ 0 ]
[]
[]
[ "absolute", "gnu", "linker", "relocation" ]
stackoverflow_0074675907_absolute_gnu_linker_relocation.txt
Q: Group by and get latest record of group I am trying to group my Swipes by user_id, then I only need the latest (by created_at) Swipe per user_id. So at the end I would like to have only latest Swipes (Collection) by user_id with no duplicates. How is this possible? Tried something like: Swipe::all()->sortBy('user_id')->unique('user_id') But latest record inside the group is not correct A: You can try using the groupBy and max methods to achieve your desired result: $latestSwipes = Swipe::all()->groupBy('user_id')->map(function($swipes) { return $swipes->max('created_at'); }); This will group all the swipes by user_id and then return only the swipe with the latest created_at timestamp for each group. This will return a collection of the latest swipes by user_id with no duplicates. Alternatively, you can use the sortByDesc and unique methods to achieve a similar result: $latestSwipes = Swipe::all()->sortByDesc('created_at')->unique('user_id'); This will first sort the swipes in descending order by created_at timestamp and then remove any duplicate user_id values, leaving only the latest swipe per user_id in the collection.
Group by and get latest record of group
I am trying to group my Swipes by user_id, then I only need the latest (by created_at) Swipe per user_id. So at the end I would like to have only latest Swipes (Collection) by user_id with no duplicates. How is this possible? Tried something like: Swipe::all()->sortBy('user_id')->unique('user_id') But latest record inside the group is not correct
[ "You can try using the groupBy and max methods to achieve your desired result:\n$latestSwipes = Swipe::all()->groupBy('user_id')->map(function($swipes) {\nreturn $swipes->max('created_at');\n});\n\nThis will group all the swipes by user_id and then return only the swipe with the latest created_at timestamp for each group. This will return a collection of the latest swipes by user_id with no duplicates.\nAlternatively, you can use the sortByDesc and unique methods to achieve a similar result:\n$latestSwipes = Swipe::all()->sortByDesc('created_at')->unique('user_id');\n\nThis will first sort the swipes in descending order by created_at timestamp and then remove any duplicate user_id values, leaving only the latest swipe per user_id in the collection.\n" ]
[ 1 ]
[]
[]
[ "laravel" ]
stackoverflow_0074675896_laravel.txt
Q: Showing button based on the scrolling status I'm pretty new in development and in SwiftUI. I learned a little with the Paul Hudson courses and by my self and I began to develop my first app but I'm facing a little problem that I can't solve alone... I have a view with some long text and I embed it in a scrollView. To show user there is a scrollable text I add this little arrow at the bottom on my Text but I want to show it only when the text is long enough to not show entirely without scrolling. And if it's showed i need it to disappear when the bottom of the scrollView is reached and reappear when the user scroll back on top... I let you my code here : VStack { Text("Lorem ipsum in my TestView") .font(.title) .padding(.bottom, 20) ScrollViewReader { proxy in ScrollView { Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed accumsan mi elementum metus eleifend fermentum. Vestibulum a ligula laoreet libero rhoncus pharetra. Vivamus ac erat non odio tempus iaculis. Phasellus tincidunt dapibus ultricies. Aliquam erat volutpat. Maecenas aliquam est felis. Etiam consectetur viverra velit. Phasellus ligula metus, congue quis est vel, fermentum euismod ligula. Nunc pulvinar luctus semper. Nunc non fringilla ligula. Morbi scelerisque, augue non tempus hendrerit, tellus lectus sagittis ex, nec volutpat mi lacus maximus elit.").padding() Text("").padding(.bottom, 10) .id("end") }.frame(maxWidth: 300, maxHeight: 100) .padding() .background(.quaternary) .clipShape(RoundedRectangle(cornerRadius: 10)) if showBottom { Button{ withAnimation { proxy.scrollTo("end") showBottom.toggle() } } label: { Image(systemName: "chevron.down.circle.fill") } } } And there is a screenshot and a video to show the problem : Screenshot Video : Screen record I tried to get the scroll status with scrollViewReader to show and hide the button but didn't work. A: You can achieve this by using a GeometryReader. Then you can create a custom coordinate space for your ScrollView and observe changes to the GeometryReader´s position in this coordinate space. But for this to work you need to know the height of the ScrollView itself. As you allredy put a frame on it I simply pulled this out to a local var. This is how this would look in an example: ScrollView { Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed accumsan mi elementum metus eleifend fermentum. Vestibulum a ligula laoreet libero rhoncus pharetra. Vivamus ac erat non odio tempus iaculis. Phasellus tincidunt dapibus ultricies. Aliquam erat volutpat. Maecenas aliquam est felis. Etiam consectetur viverra velit. Phasellus ligula metus, congue quis est vel, fermentum euismod ligula. Nunc pulvinar luctus semper. Nunc non fringilla ligula. Morbi scelerisque, augue non tempus hendrerit, tellus lectus sagittis ex, nec volutpat mi lacus maximus elit.").padding() Color.clear // use a 0 frame so it does not influence the layout .frame(height: 0) // id for scrolling .id("end") // add this to determine the position of the scrollview .background( // add the GeometryReader to the background GeometryReader{reader in // add another clear color to be able to observe // changes to geometry reader position Color.clear .onChange(of: reader.frame(in: .named("newSpace"))) { newValue in withAnimation { // if the first clear color y value is lower than the // height of the ScrollView plus a certain // threashold hide the button showBottom = !(newValue.minY < scrollViewHeight + 50) } } }) }.frame(width: 300, height: scrollViewHeight) .padding() .background(.quaternary) .clipShape(RoundedRectangle(cornerRadius: 10)) // add this to define a coordinate space for the scrollview .coordinateSpace(name: "newSpace")
Showing button based on the scrolling status
I'm pretty new in development and in SwiftUI. I learned a little with the Paul Hudson courses and by my self and I began to develop my first app but I'm facing a little problem that I can't solve alone... I have a view with some long text and I embed it in a scrollView. To show user there is a scrollable text I add this little arrow at the bottom on my Text but I want to show it only when the text is long enough to not show entirely without scrolling. And if it's showed i need it to disappear when the bottom of the scrollView is reached and reappear when the user scroll back on top... I let you my code here : VStack { Text("Lorem ipsum in my TestView") .font(.title) .padding(.bottom, 20) ScrollViewReader { proxy in ScrollView { Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed accumsan mi elementum metus eleifend fermentum. Vestibulum a ligula laoreet libero rhoncus pharetra. Vivamus ac erat non odio tempus iaculis. Phasellus tincidunt dapibus ultricies. Aliquam erat volutpat. Maecenas aliquam est felis. Etiam consectetur viverra velit. Phasellus ligula metus, congue quis est vel, fermentum euismod ligula. Nunc pulvinar luctus semper. Nunc non fringilla ligula. Morbi scelerisque, augue non tempus hendrerit, tellus lectus sagittis ex, nec volutpat mi lacus maximus elit.").padding() Text("").padding(.bottom, 10) .id("end") }.frame(maxWidth: 300, maxHeight: 100) .padding() .background(.quaternary) .clipShape(RoundedRectangle(cornerRadius: 10)) if showBottom { Button{ withAnimation { proxy.scrollTo("end") showBottom.toggle() } } label: { Image(systemName: "chevron.down.circle.fill") } } } And there is a screenshot and a video to show the problem : Screenshot Video : Screen record I tried to get the scroll status with scrollViewReader to show and hide the button but didn't work.
[ "You can achieve this by using a GeometryReader. Then you can create a custom coordinate space for your ScrollView and observe changes to the GeometryReader´s position in this coordinate space.\nBut for this to work you need to know the height of the ScrollView itself. As you allredy put a frame on it I simply pulled this out to a local var.\nThis is how this would look in an example:\nScrollView {\n Text(\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed accumsan mi elementum metus eleifend fermentum. Vestibulum a ligula laoreet libero rhoncus pharetra. Vivamus ac erat non odio tempus iaculis. Phasellus tincidunt dapibus ultricies. Aliquam erat volutpat. Maecenas aliquam est felis. Etiam consectetur viverra velit. Phasellus ligula metus, congue quis est vel, fermentum euismod ligula. Nunc pulvinar luctus semper. Nunc non fringilla ligula. Morbi scelerisque, augue non tempus hendrerit, tellus lectus sagittis ex, nec volutpat mi lacus maximus elit.\").padding()\n \n Color.clear\n // use a 0 frame so it does not influence the layout\n .frame(height: 0)\n // id for scrolling\n .id(\"end\")\n // add this to determine the position of the scrollview\n .background(\n // add the GeometryReader to the background\n GeometryReader{reader in\n // add another clear color to be able to observe\n // changes to geometry reader position\n Color.clear\n .onChange(of: reader.frame(in: .named(\"newSpace\"))) { newValue in\n withAnimation {\n // if the first clear color y value is lower than the\n // height of the ScrollView plus a certain\n // threashold hide the button\n showBottom = !(newValue.minY < scrollViewHeight + 50)\n }\n }\n })\n}.frame(width: 300, height: scrollViewHeight)\n .padding()\n .background(.quaternary)\n .clipShape(RoundedRectangle(cornerRadius: 10))\n// add this to define a coordinate space for the scrollview\n .coordinateSpace(name: \"newSpace\")\n\n" ]
[ 0 ]
[]
[]
[ "ios", "scrollview", "swiftui" ]
stackoverflow_0074674405_ios_scrollview_swiftui.txt
Q: Cannot get if statement to evaluate variable that is equivalent to the adding of the results of two functions I've found myself in a circle that I can't get out of where the compiler won't evaluate if totalSum % 10 == 0 #include <cs50.h> #include <stdio.h> int countingMachine(long n); int oddAdd(long cNum2) { int n = 0; long tempCred = cNum2; int add = 0; long double tempData = 0; while (tempCred != 0) { if (n % 2 != 0) { tempData = (tempCred % 10); if (tempData <= 0) { tempData = 0; add += (int) tempData; } add += tempData; } tempCred /= 10; n++; } return add; } int multAdd(long cNum) { int n = 0; long tempCred = cNum; int evenAdd = 0; int tempData = 0; while (tempCred != 0) { tempCred /= 10; if(n % 2 == 0) { tempData = (tempCred % 10)*2; if (tempData >= 10) { evenAdd += tempData % 10; evenAdd += tempData / 10; } else { evenAdd += tempData; } } n++; } return evenAdd; } long divNum(int count) { long long int divisor; int i; for(divisor = 10, i = 0; i <= count - 1; i++) { divisor = divisor * 10; } return divisor; } int mathCheck(long cardNum, long neoDiv) { int primeTwo = cardNum / neoDiv; return primeTwo; } int main(void) { int am1 = 34; int am2 = 37; int mc1 = 51; int mc2 = 52; int mc3 = 53; int mc4 = 54; int mc5 = 55; int vZA = 4; long n = 0; int tempCount = 0; int totalSum; long ccNum = 0; while (ccNum <= 0) { ccNum = get_long("Enter Credit Card Number\n"); } tempCount = ccNum; totalSum = oddAdd(ccNum); + multAdd(ccNum) % 10; tempCount = countingMachine(tempCount); printf("%i\n", tempCount); long long int divi = divNum(tempCount); printf("%lld\n", divi); long firstTwo = ccNum / divi; printf("%li\n", firstTwo); while (firstTwo >= 40 && firstTwo <= 50) { firstTwo /= 10; } if (firstTwo == am1 || firstTwo = am2 (&& totalSum % 10 == 0)) { printf("Number: %li\n", ccNum); printf("BANK OF AMERICA") } if (firstTwo == mc1 || mc2 || mc3 || mc4 || mc5 (&& totalSum % 10 == 0)) { printf("Number: %li\n", ccNum); printf("MASTERCARD"); } } int countingMachine(long n) { int count = 0; while(n != 0) { count++; n /= 10; } return count; } I have tried defining the functions with both void and int as return types, and neither seems to work, as it gives me the error && within '||' place parenthesis around the && statement to silence this warning for if (firstTwo == am1 || am2 && totalSum == 0) And when that's done, I get called object type 'int' is not a function or a function pointer or invalid operand to binary expression ('void *' and 'int') and if I attempt to call the functions with a return type of int instead of void, like in the code, I get much of the same errors, just without void *. A: Unfortunately you misunderstood the diagnostic message of the warning. Such messages are more for the experienced user, who remembers how to apply the suggestion properly. Starting with the conditional you wrote: if (firstTwo == am1 || am2 && totalSum == 0) The compiler told you to "place parenthesis around the && statement to silence this warning". And you tried, as the complete source currently shows: if (firstTwo == am1 || am2 (&& totalSum == 0)) Both of these tries syntactically tell the compiler to use am2 as a function object and call it. But since am2 is just an int object, it cannot do this. Therefore, it produced the next error message. What the warning message really means is to put the complete expression (statement) with the binary operator && in parentheses: if (firstTwo == am1 || (am2 && totalSum == 0)) This makes visible that && is evaluated before ||, which can be overseen easily. This will actually silent the warning, but it is not what you apparently want. This conditional will compare am2 with zero as the left operand of the && operator. C needs explicit expressions, when it comes to AND/OR-combined comparisons. Most probably this is what you want: if ((firstTwo == am1 || firstTwo == am2) && totalSum == 0) Note: There are more serious issues with your code, but for now this answers the asked and hardest problem. Reduce your code to a simple first working stage, and only if this works, add some small next feature. Do not try to write a "big bang" solution.
Cannot get if statement to evaluate variable that is equivalent to the adding of the results of two functions
I've found myself in a circle that I can't get out of where the compiler won't evaluate if totalSum % 10 == 0 #include <cs50.h> #include <stdio.h> int countingMachine(long n); int oddAdd(long cNum2) { int n = 0; long tempCred = cNum2; int add = 0; long double tempData = 0; while (tempCred != 0) { if (n % 2 != 0) { tempData = (tempCred % 10); if (tempData <= 0) { tempData = 0; add += (int) tempData; } add += tempData; } tempCred /= 10; n++; } return add; } int multAdd(long cNum) { int n = 0; long tempCred = cNum; int evenAdd = 0; int tempData = 0; while (tempCred != 0) { tempCred /= 10; if(n % 2 == 0) { tempData = (tempCred % 10)*2; if (tempData >= 10) { evenAdd += tempData % 10; evenAdd += tempData / 10; } else { evenAdd += tempData; } } n++; } return evenAdd; } long divNum(int count) { long long int divisor; int i; for(divisor = 10, i = 0; i <= count - 1; i++) { divisor = divisor * 10; } return divisor; } int mathCheck(long cardNum, long neoDiv) { int primeTwo = cardNum / neoDiv; return primeTwo; } int main(void) { int am1 = 34; int am2 = 37; int mc1 = 51; int mc2 = 52; int mc3 = 53; int mc4 = 54; int mc5 = 55; int vZA = 4; long n = 0; int tempCount = 0; int totalSum; long ccNum = 0; while (ccNum <= 0) { ccNum = get_long("Enter Credit Card Number\n"); } tempCount = ccNum; totalSum = oddAdd(ccNum); + multAdd(ccNum) % 10; tempCount = countingMachine(tempCount); printf("%i\n", tempCount); long long int divi = divNum(tempCount); printf("%lld\n", divi); long firstTwo = ccNum / divi; printf("%li\n", firstTwo); while (firstTwo >= 40 && firstTwo <= 50) { firstTwo /= 10; } if (firstTwo == am1 || firstTwo = am2 (&& totalSum % 10 == 0)) { printf("Number: %li\n", ccNum); printf("BANK OF AMERICA") } if (firstTwo == mc1 || mc2 || mc3 || mc4 || mc5 (&& totalSum % 10 == 0)) { printf("Number: %li\n", ccNum); printf("MASTERCARD"); } } int countingMachine(long n) { int count = 0; while(n != 0) { count++; n /= 10; } return count; } I have tried defining the functions with both void and int as return types, and neither seems to work, as it gives me the error && within '||' place parenthesis around the && statement to silence this warning for if (firstTwo == am1 || am2 && totalSum == 0) And when that's done, I get called object type 'int' is not a function or a function pointer or invalid operand to binary expression ('void *' and 'int') and if I attempt to call the functions with a return type of int instead of void, like in the code, I get much of the same errors, just without void *.
[ "Unfortunately you misunderstood the diagnostic message of the warning. Such messages are more for the experienced user, who remembers how to apply the suggestion properly.\nStarting with the conditional you wrote:\nif (firstTwo == am1 || am2 && totalSum == 0)\n\nThe compiler told you to \"place parenthesis around the && statement to silence this warning\".\nAnd you tried, as the complete source currently shows:\nif (firstTwo == am1 || am2 (&& totalSum == 0))\n\nBoth of these tries syntactically tell the compiler to use am2 as a function object and call it. But since am2 is just an int object, it cannot do this. Therefore, it produced the next error message.\nWhat the warning message really means is to put the complete expression (statement) with the binary operator && in parentheses:\nif (firstTwo == am1 || (am2 && totalSum == 0))\n\nThis makes visible that && is evaluated before ||, which can be overseen easily.\nThis will actually silent the warning, but it is not what you apparently want. This conditional will compare am2 with zero as the left operand of the && operator.\nC needs explicit expressions, when it comes to AND/OR-combined comparisons. Most probably this is what you want:\nif ((firstTwo == am1 || firstTwo == am2) && totalSum == 0)\n\n\nNote: There are more serious issues with your code, but for now this answers the asked and hardest problem. Reduce your code to a simple first working stage, and only if this works, add some small next feature. Do not try to write a \"big bang\" solution.\n" ]
[ 0 ]
[]
[]
[ "c", "conditional_statements", "function_call", "operands", "return_type" ]
stackoverflow_0074673010_c_conditional_statements_function_call_operands_return_type.txt
Q: Java: How to accept both string and integer in one variable I have to read a json input, in which one of the values can be either integer or string. Is the best or even only way to do that is to the define the variable in the model as an Object, or is there a better way? For example: The input can be: { "val" : 1 } but also: { "val" : "1" } is possible. I am working with Jackson. The first proposed answer is not relevant because there the member value is set to be integer, and if we get a string, jackson will convert it to integer. This is not what I ask for. I need the option for the member to be ready for multiple type options. The second proposed answer also does not fit my problem setup, since it uses 2 different classes as models. A: Yes, defining the "val" variable as an Object in the model is the best way to handle a value that can be either an integer or a string in a JSON input. This allows you to access the value as an Object and use type checking or type casting to handle the value as either an integer or a string in your code. For example, you could use the instanceof operator to check the type of the "val" variable and then handle it accordingly in your code: if (val instanceof Integer) { // handle val as an integer } else if (val instanceof String) { // handle val as a string } Alternatively, you could use type casting to explicitly convert the "val" variable to an integer or string, depending on its type: int intVal = (Integer) val; String strVal = (String) val; However, using type casting can lead to runtime errors if the "val" variable is not of the expected type, so it is generally safer to use type checking with the instanceof operator.
Java: How to accept both string and integer in one variable
I have to read a json input, in which one of the values can be either integer or string. Is the best or even only way to do that is to the define the variable in the model as an Object, or is there a better way? For example: The input can be: { "val" : 1 } but also: { "val" : "1" } is possible. I am working with Jackson. The first proposed answer is not relevant because there the member value is set to be integer, and if we get a string, jackson will convert it to integer. This is not what I ask for. I need the option for the member to be ready for multiple type options. The second proposed answer also does not fit my problem setup, since it uses 2 different classes as models.
[ "Yes, defining the \"val\" variable as an Object in the model is the best way to handle a value that can be either an integer or a string in a JSON input. This allows you to access the value as an Object and use type checking or type casting to handle the value as either an integer or a string in your code.\nFor example, you could use the instanceof operator to check the type of the \"val\" variable and then handle it accordingly in your code:\nif (val instanceof Integer) {\n// handle val as an integer\n} else if (val instanceof String) {\n// handle val as a string\n}\n\nAlternatively, you could use type casting to explicitly convert the \"val\" variable to an integer or string, depending on its type:\nint intVal = (Integer) val;\nString strVal = (String) val;\n\nHowever, using type casting can lead to runtime errors if the \"val\" variable is not of the expected type, so it is generally safer to use type checking with the instanceof operator.\n" ]
[ 0 ]
[]
[]
[ "java", "json" ]
stackoverflow_0074675906_java_json.txt
Q: creating a new empty data frame in each loop? I'm trying to create a new data frame for each one of my loops in a for loop; but i can't seem to get a new data frame each time. for(j in 1:10){ df_j = data.frame() } What I am trying to get is a bunch of new data frames in my environment. df_1 df_2 df_3 df_4 df_5 df_6 df_7 df_8 df_9 df_10 Im quite new to coding, so any help will be appreciated, thanks. When i tryied this it just made one data frame called 'df_j'. A: Creating new variables in a loop / automatically isn't a good idea. Consider using a list instead: Outside the for loop create my_list <- list(). Inside your loop assign the new data.frames using my_list[[j]] <- data.frame(). Access a data.frame for example via my_list[[5]] which is more or less your intended df_5. my_list <- list() for(j in 1:10){ my_list[[j]] <- data.frame() } my_list[[5]]
creating a new empty data frame in each loop?
I'm trying to create a new data frame for each one of my loops in a for loop; but i can't seem to get a new data frame each time. for(j in 1:10){ df_j = data.frame() } What I am trying to get is a bunch of new data frames in my environment. df_1 df_2 df_3 df_4 df_5 df_6 df_7 df_8 df_9 df_10 Im quite new to coding, so any help will be appreciated, thanks. When i tryied this it just made one data frame called 'df_j'.
[ "Creating new variables in a loop / automatically isn't a good idea. Consider using a list instead:\n\nOutside the for loop create my_list <- list().\nInside your loop assign the new data.frames using my_list[[j]] <- data.frame().\nAccess a data.frame for example via my_list[[5]] which is more or less your intended df_5.\n\nmy_list <- list()\n\nfor(j in 1:10){\n my_list[[j]] <- data.frame()\n}\n\nmy_list[[5]]\n\n" ]
[ 3 ]
[]
[]
[ "r" ]
stackoverflow_0074675791_r.txt
Q: Warning printed after migrating to Spring Boot 3.0 & Spring Integration 6.0 After migrating a project from Spring Boot v2.7 to v3.0 (and thus from Spring Integration v5.5 to v6.0), the following warnings are printed out: WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassA WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassB WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassC WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassD MyClassA extends IntegrationFlowAdapter, and is annotated with @Component: package com.foobar; @Component class MyClassA extends IntegrationFlowAdapter { // … } MyClassB is annotated with @ConfigurationProperties: package com.foobar; @ConfigurationProperties("my-config") class MyClassB { // … } MyClassC is annotated with @Configuration: package com.foobar; @Configuration class MyClassC { // … } And this particular one not even extending anything, nor annotated: package com.foobar; class MyClassD { // … } I didn’t see any relevant information in the Spring Boot and Spring Integration migration guides. There is a section about name resolution in the Spring Boot migration guide, but it is related to Gradle, and I’m using Maven. I’m not even sure what this name resolution is all about. I’m puzzled with the class LocalVariableTableParameterNameDiscoverer, and I’m not sure what migration task I’m supposed to do. A: As pointed by @m-deinum in the question’s comments, the problem is not related to Spring Boot or Spring Integration, but to Spring Framework itself. I needed to add the -parameters option to javac. If you are using Maven, adding the following in the pom.xml should solve the problem: <project> <!-- … --> <build> <pluginManagement> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.10.1</version> <configuration> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin> </plugins> </pluginManagement> </build> <!-- … --> </project> A: This is somewhat irrelevant to Spring Integration, neither Spring Boot. The change has happened in Spring Framework by itself: https://github.com/spring-projects/spring-framework/issues/29563. Yes, Spring Integration uses that LocalVariableTableParameterNameDiscoverer in the MessagePublishingInterceptor for @Publisher to have method arguments as an PublisherMetadataSource.ARGUMENT_MAP_VARIABLE_NAME variable in a SpEL EvaluationContext: https://docs.spring.io/spring-integration/docs/current/reference/html/message-publishing.html#message-publishing. Another one is a @MessagingGateway where we try to resolve header names from @Header method params if you don't provide a name attribute for that annotation: https://docs.spring.io/spring-integration/docs/current/reference/html/messaging-endpoints.html#mapping-method-arguments Similar logic is present in the MessagingMethodInvokerHelper to resolve header names for POJO service methods: https://docs.spring.io/spring-integration/docs/current/reference/html/configuration.html#annotations So, we need more info from your Spring Integration configuration to determine the place where you possible just would need to add a name attribute to the @Header annotation on your method param. I also see that this one LocalVariableTableParameterNameDiscoverer was deprecated in 6.0.1. Please, raise a GH issue against Spring Integration, so we will fix it in favor of the mentioned StandardReflectionParameterNameDiscoverer. A: These warnings are telling you that the LocalVariableTableParameterNameDiscoverer class is using a deprecated method for parameter name resolution. This class is used by Spring to discover the names of method parameters in your code. In order to fix these warnings, you need to compile your code with the -parameters flag instead of the -debug flag. To do this with Maven, you need to add the -parameters flag to the compilerArgs property of the maven-compiler-plugin in your pom.xml file. Here's an example of how you can do this: <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin> </plugins> </build> After you've made this change, recompile your code and the warnings should no longer appear. As for the name resolution itself, this is a process by which Spring determines the names of method parameters in your code. By default, the names of method parameters are not stored in compiled Java code, so if you want to use these names in your Spring configuration, you need to enable some sort of name resolution. The -parameters flag is one way to do this, and the -debug flag is another (deprecated) way. The -parameters flag is the recommended way to do this because it provides more accurate and efficient name resolution.
Warning printed after migrating to Spring Boot 3.0 & Spring Integration 6.0
After migrating a project from Spring Boot v2.7 to v3.0 (and thus from Spring Integration v5.5 to v6.0), the following warnings are printed out: WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassA WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassB WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassC WARN 22084 --- [ restartedMain] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: com.foobar.MyClassD MyClassA extends IntegrationFlowAdapter, and is annotated with @Component: package com.foobar; @Component class MyClassA extends IntegrationFlowAdapter { // … } MyClassB is annotated with @ConfigurationProperties: package com.foobar; @ConfigurationProperties("my-config") class MyClassB { // … } MyClassC is annotated with @Configuration: package com.foobar; @Configuration class MyClassC { // … } And this particular one not even extending anything, nor annotated: package com.foobar; class MyClassD { // … } I didn’t see any relevant information in the Spring Boot and Spring Integration migration guides. There is a section about name resolution in the Spring Boot migration guide, but it is related to Gradle, and I’m using Maven. I’m not even sure what this name resolution is all about. I’m puzzled with the class LocalVariableTableParameterNameDiscoverer, and I’m not sure what migration task I’m supposed to do.
[ "As pointed by @m-deinum in the question’s comments, the problem is not related to Spring Boot or Spring Integration, but to Spring Framework itself. I needed to add the -parameters option to javac.\nIf you are using Maven, adding the following in the pom.xml should solve the problem:\n<project>\n \n <!-- … -->\n\n <build>\n <pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.10.1</version>\n <configuration>\n <compilerArgs>\n <arg>-parameters</arg>\n </compilerArgs>\n </configuration>\n </plugin>\n </plugins>\n </pluginManagement>\n </build>\n\n <!-- … -->\n\n</project>\n\n", "This is somewhat irrelevant to Spring Integration, neither Spring Boot. The change has happened in Spring Framework by itself: https://github.com/spring-projects/spring-framework/issues/29563.\nYes, Spring Integration uses that LocalVariableTableParameterNameDiscoverer in the MessagePublishingInterceptor for @Publisher to have method arguments as an PublisherMetadataSource.ARGUMENT_MAP_VARIABLE_NAME variable in a SpEL EvaluationContext: https://docs.spring.io/spring-integration/docs/current/reference/html/message-publishing.html#message-publishing.\nAnother one is a @MessagingGateway where we try to resolve header names from @Header method params if you don't provide a name attribute for that annotation: https://docs.spring.io/spring-integration/docs/current/reference/html/messaging-endpoints.html#mapping-method-arguments\nSimilar logic is present in the MessagingMethodInvokerHelper to resolve header names for POJO service methods: https://docs.spring.io/spring-integration/docs/current/reference/html/configuration.html#annotations\nSo, we need more info from your Spring Integration configuration to determine the place where you possible just would need to add a name attribute to the @Header annotation on your method param.\nI also see that this one LocalVariableTableParameterNameDiscoverer was deprecated in 6.0.1. Please, raise a GH issue against Spring Integration, so we will fix it in favor of the mentioned StandardReflectionParameterNameDiscoverer.\n", "These warnings are telling you that the LocalVariableTableParameterNameDiscoverer class is using a deprecated method for parameter name resolution. This class is used by Spring to discover the names of method parameters in your code. In order to fix these warnings, you need to compile your code with the -parameters flag instead of the -debug flag.\nTo do this with Maven, you need to add the -parameters flag to the compilerArgs property of the maven-compiler-plugin in your pom.xml file. Here's an example of how you can do this:\n<build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.8.0</version>\n <configuration>\n <compilerArgs>\n <arg>-parameters</arg>\n </compilerArgs>\n </configuration>\n </plugin>\n </plugins>\n</build>\n\nAfter you've made this change, recompile your code and the warnings should no longer appear.\nAs for the name resolution itself, this is a process by which Spring determines the names of method parameters in your code. By default, the names of method parameters are not stored in compiled Java code, so if you want to use these names in your Spring configuration, you need to enable some sort of name resolution. The -parameters flag is one way to do this, and the -debug flag is another (deprecated) way. The -parameters flag is the recommended way to do this because it provides more accurate and efficient name resolution.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "spring", "spring_boot", "spring_integration" ]
stackoverflow_0074600681_spring_spring_boot_spring_integration.txt
Q: Flutter: FloatingActionButton shadow Are you able or is there a way to change the color of the shadow made by the FloatingActionButton.extended or any other floating button ? A: You can try this way: floatingActionButton: FloatingActionButton( onPressed: () {}, backgroundColor: Colors.red, elevation: 0, child: Container( decoration: BoxDecoration( color: Colors.transparent, borderRadius: BorderRadius.all( Radius.circular(100), ), boxShadow: [ BoxShadow( color: Colors.purple.withOpacity(0.3), spreadRadius: 7, blurRadius: 7, offset: Offset(3, 5), ), ], ), ), ), A: floatingActionButton: FloatingActionButton( onPressed: (){}, backgroundColor: Color(0xf0004451), elevation: 10, child: Container( padding: const EdgeInsets.all(14.0), decoration: BoxDecoration( color: Colors.transparent, borderRadius: BorderRadius.all( Radius.circular(60), ), boxShadow: [ BoxShadow( color: Color(0xffE1E8EB).withOpacity(0.35), spreadRadius: 8, blurRadius: 8, offset: const Offset(1, 1), ), ], ), child: const Icon(Icons.add, color: Color(0xffE1E8EB), size: 18, shadows: [Shadow( color: Color(0xffE1E8EB), offset: Offset(0.2, 0.5), blurRadius: 5.0, )], ), ), ), A: floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: Container( height: 70, width: 70, margin: const EdgeInsets.only(bottom: 10.0), decoration: BoxDecoration( color: Colors.transparent, borderRadius: const BorderRadius.all( Radius.circular(100), ), boxShadow: [ BoxShadow( color: MyColors.myWhite.withOpacity(0.3), spreadRadius: 6, blurRadius: 6, offset: const Offset(0.5, 0.5), ), ], ), child: FittedBox( child: FloatingActionButton( onPressed: (){}, backgroundColor: MyColors.myGreen, elevation: 10, child: const Icon(Icons.add, color: MyColors.myWhite, size: 18, shadows: [Shadow( color: MyColors.myWhite, offset: Offset(0.2, 0.5), blurRadius: 5.0, )], ), ), ), ),
Flutter: FloatingActionButton shadow
Are you able or is there a way to change the color of the shadow made by the FloatingActionButton.extended or any other floating button ?
[ "\nYou can try this way:\nfloatingActionButton: FloatingActionButton(\n onPressed: () {},\n backgroundColor: Colors.red,\n elevation: 0,\n child: Container(\n decoration: BoxDecoration(\n color: Colors.transparent,\n borderRadius: BorderRadius.all(\n Radius.circular(100),\n ),\n boxShadow: [\n BoxShadow(\n color: Colors.purple.withOpacity(0.3),\n spreadRadius: 7,\n blurRadius: 7,\n offset: Offset(3, 5),\n ),\n ],\n ),\n ),\n ),\n\n", "floatingActionButton: FloatingActionButton(\nonPressed: (){},\nbackgroundColor: Color(0xf0004451),\nelevation: 10,\n child: Container(\n padding: const EdgeInsets.all(14.0),\n decoration: BoxDecoration(\n color: Colors.transparent,\n borderRadius: BorderRadius.all(\n Radius.circular(60),\n ),\n boxShadow: [\n BoxShadow(\n color: Color(0xffE1E8EB).withOpacity(0.35),\n spreadRadius: 8,\n blurRadius: 8,\n offset: const Offset(1, 1),\n ),\n ],\n ),\n child: const Icon(Icons.add,\n color: Color(0xffE1E8EB),\n size: 18,\n shadows: [Shadow(\n color: Color(0xffE1E8EB),\n offset: Offset(0.2, 0.5),\n blurRadius: 5.0,\n )],\n ),\n ),\n),\n\n", "floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,\n floatingActionButton: Container(\n height: 70,\n width: 70,\n margin: const EdgeInsets.only(bottom: 10.0),\n decoration: BoxDecoration(\n color: Colors.transparent,\n borderRadius: const BorderRadius.all(\n Radius.circular(100),\n ),\n boxShadow: [\n BoxShadow(\n color: MyColors.myWhite.withOpacity(0.3),\n spreadRadius: 6,\n blurRadius: 6,\n offset: const Offset(0.5, 0.5),\n ),\n ],\n ),\n child: FittedBox(\n child: FloatingActionButton(\n onPressed: (){},\n backgroundColor: MyColors.myGreen,\n elevation: 10,\n child: const Icon(Icons.add,\n color: MyColors.myWhite,\n size: 18,\n shadows: [Shadow(\n color: MyColors.myWhite,\n offset: Offset(0.2, 0.5),\n blurRadius: 5.0,\n )],\n ),\n ),\n ),\n ),\n\n" ]
[ 9, 0, 0 ]
[]
[]
[ "dart", "floating_action_button", "flutter", "material_design" ]
stackoverflow_0051583184_dart_floating_action_button_flutter_material_design.txt
Q: Why "out T" for constructor input? I found the following code in the Kotlin forum and it works fine. sealed class JsonValue<out T>(val value: T) { class JsonString(value: String) : JsonValue<String>(value) class JsonBoolean(value: Boolean) : JsonValue<Boolean>(value) class JsonNumber(value: Number) : JsonValue<Number>(value) object JsonNull : JsonValue<Nothing?>(null) class JsonArray<V>(value: Array<V>) : JsonValue<Array<V>>(value) class JsonObject(value: Map<String, Any?>) : JsonValue<Map<String, Any?>>(value) override fun toString(): String = value.toString() } fun main() { var pi: JsonValue<Any?> pi = JsonValue.JsonString("pi"); println (pi) pi = JsonValue.JsonNumber(3.14); println (pi) pi = JsonValue.JsonNull; println (pi) } But I do not understand why it uses out T. An answer to a question about out in general states: out T [...] means functions can return T but they can't take T as arguments. in T [...] means functions can take T as arguments but they can't return T. If I take a look at the above code, I can see many constructors (functions), which take T (the value) as an argument. And I see no function which returns T. So my inital impression was: this must be a typo, it should be in T. But it does not even compile with in T. Why is it necessary to use out T, although the type goes into the constructor? A: The constructor doesn't really count :) Only instance members matter - things that you can do to instances of JsonValue. As explained in the linked answer, the whole idea of (declaration-site) covariance is that you are allowed to implicitly convert an instance of e.g. JsonValue<String> to JsonValue<Any?> if the type JsonValue<T> satisfies some requirements. One of the requirements is that JsonValue<T> should not have any functions that take in any Ts*, because if it did, weird things like this would happen: val x: JsonValue<Any?> = JsonString("foo") x.giveMeSomeT(123) x at runtime holds an instance of JsonString, but the giveMeSomeT method in JsonString would expect a String, not an Int, but as far as the compiler is concerned, x is a JsonValue<Any?>, so this should compile, and bad things would happen at runtime. So this is why having a function that takes in Ts stops you from marking JsonValue as out T. However, having a constructor that takes in a T is not problematic at all, since situations like the above cannot happen with just a constructor. And I see no function which returns T In fact, the getter of value returns T. Also note that you do not need something that returns T to in order to say out T. You just need to to have nothing that takes in Ts. This is vacuously valid for example: class Foo<out T> * More accurately and generally, whenever I say "take in any Ts", it should be "have T in an 'in' position", and whenever I say "return a T", it should be "have T in an 'out' position". This is to account for Ts being used as the type argument of other generic types.
Why "out T" for constructor input?
I found the following code in the Kotlin forum and it works fine. sealed class JsonValue<out T>(val value: T) { class JsonString(value: String) : JsonValue<String>(value) class JsonBoolean(value: Boolean) : JsonValue<Boolean>(value) class JsonNumber(value: Number) : JsonValue<Number>(value) object JsonNull : JsonValue<Nothing?>(null) class JsonArray<V>(value: Array<V>) : JsonValue<Array<V>>(value) class JsonObject(value: Map<String, Any?>) : JsonValue<Map<String, Any?>>(value) override fun toString(): String = value.toString() } fun main() { var pi: JsonValue<Any?> pi = JsonValue.JsonString("pi"); println (pi) pi = JsonValue.JsonNumber(3.14); println (pi) pi = JsonValue.JsonNull; println (pi) } But I do not understand why it uses out T. An answer to a question about out in general states: out T [...] means functions can return T but they can't take T as arguments. in T [...] means functions can take T as arguments but they can't return T. If I take a look at the above code, I can see many constructors (functions), which take T (the value) as an argument. And I see no function which returns T. So my inital impression was: this must be a typo, it should be in T. But it does not even compile with in T. Why is it necessary to use out T, although the type goes into the constructor?
[ "The constructor doesn't really count :) Only instance members matter - things that you can do to instances of JsonValue.\nAs explained in the linked answer, the whole idea of (declaration-site) covariance is that you are allowed to implicitly convert an instance of e.g. JsonValue<String> to JsonValue<Any?> if the type JsonValue<T> satisfies some requirements. One of the requirements is that JsonValue<T> should not have any functions that take in any Ts*, because if it did, weird things like this would happen:\nval x: JsonValue<Any?> = JsonString(\"foo\")\nx.giveMeSomeT(123)\n\nx at runtime holds an instance of JsonString, but the giveMeSomeT method in JsonString would expect a String, not an Int, but as far as the compiler is concerned, x is a JsonValue<Any?>, so this should compile, and bad things would happen at runtime.\nSo this is why having a function that takes in Ts stops you from marking JsonValue as out T. However, having a constructor that takes in a T is not problematic at all, since situations like the above cannot happen with just a constructor.\n\nAnd I see no function which returns T\n\nIn fact, the getter of value returns T. Also note that you do not need something that returns T to in order to say out T. You just need to to have nothing that takes in Ts. This is vacuously valid for example:\nclass Foo<out T>\n\n\n* More accurately and generally, whenever I say \"take in any Ts\", it should be \"have T in an 'in' position\", and whenever I say \"return a T\", it should be \"have T in an 'out' position\". This is to account for Ts being used as the type argument of other generic types.\n" ]
[ 3 ]
[]
[]
[ "generics", "kotlin" ]
stackoverflow_0074675773_generics_kotlin.txt
Q: Scrapy use private proxy I am using customly configured VM to act as a proxy server (via squid) and now I try to use it for my scraper. I am using scrapy-rotating-proxies to rotate trought my ip list definition but the problem is that my proxy is treated as DEAD right on the first attempt even thought I have verified that the proxy address is alive and is working just fine (I tested it by setting a proxy in firefox and tried to browse both http and https web pages. The proxy server is passwordless for testing purposes scrapy settings DOWNLOADER_MIDDLEWARES = { "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None, "scrapy.downloadermiddlewares.retry.RetryMiddleware": None, "scrapy_fake_useragent.middleware.RandomUserAgentMiddleware": 400, "scrapy_fake_useragent.middleware.RetryUserAgentMiddleware": 401, "rotating_proxies.middlewares.RotatingProxyMiddleware": 610, "rotating_proxies.middlewares.BanDetectionMiddleware": 620, } ROTATING_PROXY_LIST = ["X.X.X.X:3128"] scrapy logs 2022-12-02 13:31:22 [scrapy.core.engine] INFO: Spider opened 2022-12-02 13:31:22 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2022-12-02 13:31:22 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023 2022-12-02 13:31:22 [rotating_proxies.middlewares] INFO: Proxies(good: 0, dead: 0, unchecked: 1, reanimated: 0, mean backoff time: 0s) 2022-12-02 13:31:32 [rotating_proxies.expire] DEBUG: Proxy <http://X.X.X.X:3128> is DEAD 2022-12-02 13:31:32 [rotating_proxies.middlewares] DEBUG: Retrying <GET https://www.johnlewis.com/header/api/config> with another proxy (failed 1 times, max retries: 5) 2022-12-02 13:31:32 [rotating_proxies.middlewares] WARNING: No proxies available; marking all proxies as unchecked Settings I have changed for squid http_access allow all via off forwarded_for delete Please advice what can be the issue A: "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None, "scrapy.downloadermiddlewares.retry.RetryMiddleware": None, These middlewares was the issue, I cannot explain why scrapy was able to process my requests without proxies while having these middlewares enabled but after disabling them I was able to run scrapy using my proxies.
Scrapy use private proxy
I am using customly configured VM to act as a proxy server (via squid) and now I try to use it for my scraper. I am using scrapy-rotating-proxies to rotate trought my ip list definition but the problem is that my proxy is treated as DEAD right on the first attempt even thought I have verified that the proxy address is alive and is working just fine (I tested it by setting a proxy in firefox and tried to browse both http and https web pages. The proxy server is passwordless for testing purposes scrapy settings DOWNLOADER_MIDDLEWARES = { "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None, "scrapy.downloadermiddlewares.retry.RetryMiddleware": None, "scrapy_fake_useragent.middleware.RandomUserAgentMiddleware": 400, "scrapy_fake_useragent.middleware.RetryUserAgentMiddleware": 401, "rotating_proxies.middlewares.RotatingProxyMiddleware": 610, "rotating_proxies.middlewares.BanDetectionMiddleware": 620, } ROTATING_PROXY_LIST = ["X.X.X.X:3128"] scrapy logs 2022-12-02 13:31:22 [scrapy.core.engine] INFO: Spider opened 2022-12-02 13:31:22 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2022-12-02 13:31:22 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023 2022-12-02 13:31:22 [rotating_proxies.middlewares] INFO: Proxies(good: 0, dead: 0, unchecked: 1, reanimated: 0, mean backoff time: 0s) 2022-12-02 13:31:32 [rotating_proxies.expire] DEBUG: Proxy <http://X.X.X.X:3128> is DEAD 2022-12-02 13:31:32 [rotating_proxies.middlewares] DEBUG: Retrying <GET https://www.johnlewis.com/header/api/config> with another proxy (failed 1 times, max retries: 5) 2022-12-02 13:31:32 [rotating_proxies.middlewares] WARNING: No proxies available; marking all proxies as unchecked Settings I have changed for squid http_access allow all via off forwarded_for delete Please advice what can be the issue
[ " \"scrapy.downloadermiddlewares.useragent.UserAgentMiddleware\": None,\n \"scrapy.downloadermiddlewares.retry.RetryMiddleware\": None,\n\nThese middlewares was the issue, I cannot explain why scrapy was able to process my requests without proxies while having these middlewares enabled but after disabling them I was able to run scrapy using my proxies.\n" ]
[ 0 ]
[]
[]
[ "proxy", "python", "scrapy", "squid" ]
stackoverflow_0074656742_proxy_python_scrapy_squid.txt
Q: Unable to run a cucumber feature within IntelliJ I have a feature with a number of steps but the first one is the only working and the rest are working fine. Now when I add new steps to the same feature there not working either its very confusing. Its lis like half the feature is working but the other half is no working. Please see test runner below: import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions(features = "src/test/java/features", glue = {"stepDefinitions"}) public class TestRunner { } Folder structure: Error message: You can implement this step using the snippet(s) below: @Given("Add Place Payload with {string} {string} {string}") public void add_place_payload_with(String string, String string2, String string3) { // Write code here that turns the phrase above into concrete actions throw new io.cucumber.java.PendingException(); } I am also getting a red exclamation mark on the feature:
Unable to run a cucumber feature within IntelliJ
I have a feature with a number of steps but the first one is the only working and the rest are working fine. Now when I add new steps to the same feature there not working either its very confusing. Its lis like half the feature is working but the other half is no working. Please see test runner below: import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions(features = "src/test/java/features", glue = {"stepDefinitions"}) public class TestRunner { } Folder structure: Error message: You can implement this step using the snippet(s) below: @Given("Add Place Payload with {string} {string} {string}") public void add_place_payload_with(String string, String string2, String string3) { // Write code here that turns the phrase above into concrete actions throw new io.cucumber.java.PendingException(); } I am also getting a red exclamation mark on the feature:
[]
[]
[ "For example u can take one of this two sample test fraemworks with parallel execution and 'Allure' screenshots(when step fail):\nhttps://github.com/simileyskiy/cucumber7-selenium3.selenide5-junit5-Allure-parallelExecution\nhttps://github.com/simileyskiy/cucumber7-selenium4.selenide6-junit5-Allure-parallelExecution\n" ]
[ -6 ]
[ "bdd", "cucumber", "intellij_idea", "java", "rest_assured" ]
stackoverflow_0074658602_bdd_cucumber_intellij_idea_java_rest_assured.txt
Q: Split object propery values and create new array of object if they split I have object like this. I getting this object on backend with query and then transform with qs string library. { color: 'red,white', size: 'xl', manufacturer: 'adidas,nike' } I would like have array of object, what i need for prisma map filtering const filterList = [ {filter: "color", value: "red"}, {filter: "color", value: "white"}, {filter: "size", value: "xl"}, {filter: "manufacturer", value: "adidas"}, {filter: "manufacturer", value: "nike"}, ]; How can i this handle ? Thanks for a reply A: To create the desired array of objects from the original object, you can use the Object.entries() method to get an array of key-value pairs, then use Array.map() to iterate over the key-value pairs and create the array of objects. Here is an example: const obj = { color: 'red,white', size: 'xl', manufacturer: 'adidas,nike' }; const filterList = Object.entries(obj).map(([filter, value]) => { return value.split(",").map(v => ({ filter, value: v })); }).flat(); console.log(filterList); This will output the following array: [ {filter: "color", value: "red"}, {filter: "color", value: "white"}, {filter: "size", value: "xl"}, {filter: "manufacturer", value: "adidas"}, {filter: "manufacturer", value: "nike"}, ]
Split object propery values and create new array of object if they split
I have object like this. I getting this object on backend with query and then transform with qs string library. { color: 'red,white', size: 'xl', manufacturer: 'adidas,nike' } I would like have array of object, what i need for prisma map filtering const filterList = [ {filter: "color", value: "red"}, {filter: "color", value: "white"}, {filter: "size", value: "xl"}, {filter: "manufacturer", value: "adidas"}, {filter: "manufacturer", value: "nike"}, ]; How can i this handle ? Thanks for a reply
[ "To create the desired array of objects from the original object, you can use the Object.entries() method to get an array of key-value pairs, then use Array.map() to iterate over the key-value pairs and create the array of objects.\nHere is an example:\n\n\nconst obj = { \n color: 'red,white',\n size: 'xl', \n manufacturer: 'adidas,nike' \n};\n\nconst filterList = Object.entries(obj).map(([filter, value]) => {\n return value.split(\",\").map(v => ({ filter, value: v }));\n}).flat();\n\nconsole.log(filterList);\n\n\n\nThis will output the following array:\n[\n {filter: \"color\", value: \"red\"},\n {filter: \"color\", value: \"white\"}, \n {filter: \"size\", value: \"xl\"},\n {filter: \"manufacturer\", value: \"adidas\"},\n {filter: \"manufacturer\", value: \"nike\"},\n]\n\n" ]
[ 1 ]
[ "Like this?\n\n\nfunction transform(filters) {\n return Object.entries(filters).reduce((acc, [filter, commaSeparatedValues]) => {\n commaSeparatedValues.split(\",\").forEach(value => {\n acc.push({\n filter,\n value\n })\n });\n return acc;\n }, [])\n}\n\nconst sample = {\n color: \"red,white\",\n size: \"xl\",\n manufacturer: \"adidas,nike\",\n};\n\nconst transformed = transform(sample);\nconsole.log(transformed);\n\n\n\n" ]
[ -1 ]
[ "arrays", "javascript", "javascript_objects", "object", "qstring" ]
stackoverflow_0074675871_arrays_javascript_javascript_objects_object_qstring.txt
Q: Is there a way to extract all styles from an existing word document with python-docx and apply them to a newly generated one? I'm new to python-docx and I'm trying to bild a document generator. What I'd like to do is to use an existing word document to extract its styles and then apply these to a newly generated one. So then whenever I use something like document.add_heading('Test Heading', level=2) the level 2 heading is the same as in the document from which I extracted the styles. Many thanks in advance for any tips! A: You can extract the styles from an existing Word document by using the get_style_id method of the Document object. This method takes the name of the style you want to extract as an argument and returns the style ID. You can then use this style ID when adding a heading to the new document to ensure that it has the same style as the original heading. Here is an example: from docx import Document # Open the existing document existing_document = Document('existing_document.docx') # Extract the style ID of the level 2 heading heading2_style_id = existing_document.get_style_id('Heading 2') # Create a new document new_document = Document() # Add a level 2 heading with the extracted style ID new_document.add_heading('Test Heading', style=heading2_style_id) You can also use the styles property of the Document object to access the full list of styles in the existing document and iterate through them to extract the style IDs for each one. This can be useful if you want to extract multiple styles from the existing document and use them in the new document. from docx import Document # Open the existing document existing_document = Document('existing_document.docx') # Create a new document new_document = Document() # Iterate through the styles in the existing document for style in existing_document.styles: # Extract the style ID style_id = existing_document.get_style_id(style.name) # Use the style ID to add a paragraph with the style to the new document new_document.add_paragraph('Test paragraph', style=style_id)
Is there a way to extract all styles from an existing word document with python-docx and apply them to a newly generated one?
I'm new to python-docx and I'm trying to bild a document generator. What I'd like to do is to use an existing word document to extract its styles and then apply these to a newly generated one. So then whenever I use something like document.add_heading('Test Heading', level=2) the level 2 heading is the same as in the document from which I extracted the styles. Many thanks in advance for any tips!
[ "You can extract the styles from an existing Word document by using the get_style_id method of the Document object. This method takes the name of the style you want to extract as an argument and returns the style ID. You can then use this style ID when adding a heading to the new document to ensure that it has the same style as the original heading.\nHere is an example:\nfrom docx import Document\n\n# Open the existing document\nexisting_document = Document('existing_document.docx')\n\n# Extract the style ID of the level 2 heading\nheading2_style_id = existing_document.get_style_id('Heading 2')\n\n# Create a new document\nnew_document = Document()\n\n# Add a level 2 heading with the extracted style ID\nnew_document.add_heading('Test Heading', style=heading2_style_id)\n\nYou can also use the styles property of the Document object to access the full list of styles in the existing document and iterate through them to extract the style IDs for each one. This can be useful if you want to extract multiple styles from the existing document and use them in the new document.\nfrom docx import Document\n\n# Open the existing document\nexisting_document = Document('existing_document.docx')\n\n# Create a new document\nnew_document = Document()\n\n# Iterate through the styles in the existing document\nfor style in existing_document.styles:\n # Extract the style ID\n style_id = existing_document.get_style_id(style.name)\n\n # Use the style ID to add a paragraph with the style to the new document\n new_document.add_paragraph('Test paragraph', style=style_id)\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_docx" ]
stackoverflow_0074675909_python_python_docx.txt
Q: Convert Javascript object to a form data result like Jquery Ajax does I send POST data with XMLHttpRequest. I want to pass multiple parameters. As far as I know, this is the only way to do it: xhr.send('first=first&second=second&third=third'); Is there a way to use Javascript object instead? let formDataObject = { first: 'a', second: 'b', third: 'c' }; Jquery converts objects exactly how I need, but I no longer want to use Jquery. By passing Javascript object to xhr.send, I want final result to look like: The reason I need the request result to be Form data type and not Json, because on PHP side I want access POST data like so: <?php if($_POST['first'] == 'a') {... I know that I can decode Json on php side and do the required check, but I want to achieve exactly the same result as Jquery Ajax does. A: This function should help! function encodeURI(obj) { var result = ''; var splitter = ''; if (typeof obj === 'object') { Object.keys(obj).forEach(function (key) { result += splitter + key + '=' + encodeURIComponent(obj[key]); splitter = '&'; }); } return result; }
Convert Javascript object to a form data result like Jquery Ajax does
I send POST data with XMLHttpRequest. I want to pass multiple parameters. As far as I know, this is the only way to do it: xhr.send('first=first&second=second&third=third'); Is there a way to use Javascript object instead? let formDataObject = { first: 'a', second: 'b', third: 'c' }; Jquery converts objects exactly how I need, but I no longer want to use Jquery. By passing Javascript object to xhr.send, I want final result to look like: The reason I need the request result to be Form data type and not Json, because on PHP side I want access POST data like so: <?php if($_POST['first'] == 'a') {... I know that I can decode Json on php side and do the required check, but I want to achieve exactly the same result as Jquery Ajax does.
[ "This function should help!\n\n\nfunction encodeURI(obj) {\n var result = '';\n var splitter = '';\n if (typeof obj === 'object') {\n Object.keys(obj).forEach(function (key) {\n result += splitter + key + '=' + encodeURIComponent(obj[key]);\n splitter = '&';\n });\n }\n return result;\n}\n\n\n\n" ]
[ 1 ]
[]
[]
[ "javascript", "xmlhttprequest" ]
stackoverflow_0074675648_javascript_xmlhttprequest.txt
Q: react-select default value is not rendered when using useState hook I am trying to set the defaultValue for on the <Select /> component from react-select package. However, when I do set the default value, using a react hook (useState), it does not render the default values. If I was to hard code the array, it renders he default values fine. What I have so far https://codesandbox.io/s/codesandboxer-example-forked-2e3unk?file=/example.tsx:0-608 import React, { useEffect, useState } from "react"; import Select from "react-select"; export default function AnimatedMulti() { const [values, setValues] = useState([]); const [defaultValues, setDefaultValues] = useState([]); useEffect(() => { const data = [ { value: 1, label: "Label 1" }, { value: 2, label: "Label 2" }, { value: 3, label: "Label 3" } ]; setValues(data); setDefaultValues([data[0], data[1]]); }, []); return ( <Select closeMenuOnSelect={false} defaultValue={defaultValues} isMulti options={values} /> ); } Output Expectation I am expecting the select component to render two default values, however nothing has been rendered. Question How can I load the default values using react hook useState? A: You can use the value prop to set the selected options, and then keep updating the values from the state. Here is the sample code for the same. import React, { useEffect, useState } from "react"; import Select from "react-select"; export default function AnimatedMulti() { const [values, setValues] = useState([]); const [selectedValues, setSelectedValues] = useState([]); useEffect(() => { const data = [ { value: 1, label: "Label 1" }, { value: 2, label: "Label 2" }, { value: 3, label: "Label 3" } ]; setValues(data); setSelectedValues([data[0]]); }, []); const onOptionChange = (options) => { // Selected options... console.log("options...", options); setSelectedValues(options); }; return ( <Select closeMenuOnSelect={false} value={selectedValues} isMulti options={values} onChange={onOptionChange} /> ); } A: I don't think you can set default value after component have rendered. Uncontrolled components are components that manage their own state/value. They should not have a value prop (or in other words, value == undefined). If you need to set a value on those, you use the defaultValue prop. But this prop only works on mount / first render of the component. You usually access their state by using a ref, listening to the onChange handler or during form submission (using FormData). Ref: https://github.com/JedWatson/react-select/issues/4942#issuecomment-987649622 You can try using values attribute to set default values. import React, { useEffect, useState } from "react"; import Select from "react-select"; export default function AnimatedMulti() { const [values, setValues] = useState([]); const [defaultValues, setDefaultValues] = useState(null); useEffect(() => { const data = [ { value: 1, label: "Label 1" }, { value: 2, label: "Label 2" }, { value: 3, label: "Label 3" } ]; setValues(data); setDefaultValues([data[0], data[1]]); }, []); return ( <Select closeMenuOnSelect={false} value={defaultValues} isMulti options={values} /> ); }
react-select default value is not rendered when using useState hook
I am trying to set the defaultValue for on the <Select /> component from react-select package. However, when I do set the default value, using a react hook (useState), it does not render the default values. If I was to hard code the array, it renders he default values fine. What I have so far https://codesandbox.io/s/codesandboxer-example-forked-2e3unk?file=/example.tsx:0-608 import React, { useEffect, useState } from "react"; import Select from "react-select"; export default function AnimatedMulti() { const [values, setValues] = useState([]); const [defaultValues, setDefaultValues] = useState([]); useEffect(() => { const data = [ { value: 1, label: "Label 1" }, { value: 2, label: "Label 2" }, { value: 3, label: "Label 3" } ]; setValues(data); setDefaultValues([data[0], data[1]]); }, []); return ( <Select closeMenuOnSelect={false} defaultValue={defaultValues} isMulti options={values} /> ); } Output Expectation I am expecting the select component to render two default values, however nothing has been rendered. Question How can I load the default values using react hook useState?
[ "You can use the value prop to set the selected options, and then keep updating the values from the state.\nHere is the sample code for the same.\nimport React, { useEffect, useState } from \"react\";\nimport Select from \"react-select\";\n\nexport default function AnimatedMulti() {\n const [values, setValues] = useState([]);\n const [selectedValues, setSelectedValues] = useState([]);\n\n useEffect(() => {\n const data = [\n { value: 1, label: \"Label 1\" },\n { value: 2, label: \"Label 2\" },\n { value: 3, label: \"Label 3\" }\n ];\n\n setValues(data);\n setSelectedValues([data[0]]);\n }, []);\n\n const onOptionChange = (options) => {\n // Selected options...\n console.log(\"options...\", options);\n setSelectedValues(options);\n };\n\n return (\n <Select\n closeMenuOnSelect={false}\n value={selectedValues}\n isMulti\n options={values}\n onChange={onOptionChange}\n />\n );\n}\n\n", "I don't think you can set default value after component have rendered.\n\nUncontrolled components are components that manage their own state/value. They should not have a value prop (or in other words, value == undefined). If you need to set a value on those, you use the defaultValue prop. But this prop only works on mount / first render of the component. You usually access their state by using a ref, listening to the onChange handler or during form submission (using FormData).\n\nRef: https://github.com/JedWatson/react-select/issues/4942#issuecomment-987649622\nYou can try using values attribute to set default values.\nimport React, { useEffect, useState } from \"react\";\nimport Select from \"react-select\";\n\nexport default function AnimatedMulti() {\n const [values, setValues] = useState([]);\n const [defaultValues, setDefaultValues] = useState(null);\n\n useEffect(() => {\n const data = [\n { value: 1, label: \"Label 1\" },\n { value: 2, label: \"Label 2\" },\n { value: 3, label: \"Label 3\" }\n ];\n\n setValues(data);\n setDefaultValues([data[0], data[1]]);\n }, []);\n\n return (\n <Select\n closeMenuOnSelect={false}\n value={defaultValues}\n isMulti\n options={values}\n />\n );\n}\n\n" ]
[ 1, 0 ]
[]
[]
[ "react_select", "reactjs" ]
stackoverflow_0074675639_react_select_reactjs.txt